blob: f91f6ede499e441d67cef934a325b59bcd244424 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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"
Mikael Nilsson9d2872d2018-12-13 10:15:27 +000019#include "TargetInfo.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000020#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000021#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000023#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000024#include "clang/AST/StmtCXX.h"
Richard Trieu63688182018-12-11 03:18:39 +000025#include "clang/Basic/CodeGenOptions.h"
Lang Hamesbf122742013-02-17 07:22:09 +000026#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000027#include "clang/CodeGen/CGFunctionInfo.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000028#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000029#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000030#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000031
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000032using namespace clang;
33using namespace CodeGen;
34
John McCall7f416cc2015-09-08 08:05:57 +000035/// Return the best known alignment for an unknown pointer to a
36/// particular class.
37CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
38 if (!RD->isCompleteDefinition())
39 return CharUnits::One(); // Hopefully won't be used anywhere.
40
41 auto &layout = getContext().getASTRecordLayout(RD);
42
43 // If the class is final, then we know that the pointer points to an
44 // object of that type and can use the full alignment.
45 if (RD->hasAttr<FinalAttr>()) {
46 return layout.getAlignment();
47
48 // Otherwise, we have to assume it could be a subclass.
49 } else {
50 return layout.getNonVirtualAlignment();
51 }
52}
53
54/// Return the best known alignment for a pointer to a virtual base,
55/// given the alignment of a pointer to the derived class.
56CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
57 const CXXRecordDecl *derivedClass,
58 const CXXRecordDecl *vbaseClass) {
59 // The basic idea here is that an underaligned derived pointer might
60 // indicate an underaligned base pointer.
61
62 assert(vbaseClass->isCompleteDefinition());
63 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
64 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
65
66 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
67 expectedVBaseAlign);
68}
69
70CharUnits
71CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
72 const CXXRecordDecl *baseDecl,
73 CharUnits expectedTargetAlign) {
74 // If the base is an incomplete type (which is, alas, possible with
75 // member pointers), be pessimistic.
76 if (!baseDecl->isCompleteDefinition())
77 return std::min(actualBaseAlign, expectedTargetAlign);
78
79 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
80 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
81
82 // If the class is properly aligned, assume the target offset is, too.
83 //
84 // This actually isn't necessarily the right thing to do --- if the
85 // class is a complete object, but it's only properly aligned for a
86 // base subobject, then the alignments of things relative to it are
87 // probably off as well. (Note that this requires the alignment of
88 // the target to be greater than the NV alignment of the derived
89 // class.)
90 //
91 // However, our approach to this kind of under-alignment can only
92 // ever be best effort; after all, we're never going to propagate
93 // alignments through variables or parameters. Note, in particular,
94 // that constructing a polymorphic type in an address that's less
95 // than pointer-aligned will generally trap in the constructor,
96 // unless we someday add some sort of attribute to change the
97 // assumed alignment of 'this'. So our goal here is pretty much
98 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000099 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +0000100 if (actualBaseAlign >= expectedBaseAlign) {
101 return expectedTargetAlign;
102 }
103
104 // Otherwise, we might be offset by an arbitrary multiple of the
105 // actual alignment. The correct adjustment is to take the min of
106 // the two alignments.
107 return std::min(actualBaseAlign, expectedTargetAlign);
108}
109
110Address CodeGenFunction::LoadCXXThisAddress() {
111 assert(CurFuncDecl && "loading 'this' without a func declaration?");
112 assert(isa<CXXMethodDecl>(CurFuncDecl));
113
114 // Lazily compute CXXThisAlignment.
115 if (CXXThisAlignment.isZero()) {
116 // Just use the best known alignment for the parent.
117 // TODO: if we're currently emitting a complete-object ctor/dtor,
118 // we can always use the complete-object alignment.
119 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
120 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
121 }
122
123 return Address(LoadCXXThis(), CXXThisAlignment);
124}
125
126/// Emit the address of a field using a member data pointer.
127///
128/// \param E Only used for emergency diagnostics
129Address
130CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
131 llvm::Value *memberPtr,
132 const MemberPointerType *memberPtrType,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000133 LValueBaseInfo *BaseInfo,
134 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000135 // Ask the ABI to compute the actual address.
136 llvm::Value *ptr =
137 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
138 memberPtr, memberPtrType);
139
140 QualType memberType = memberPtrType->getPointeeType();
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +0000141 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
142 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000143 memberAlign =
144 CGM.getDynamicOffsetAlignment(base.getAlignment(),
145 memberPtrType->getClass()->getAsCXXRecordDecl(),
146 memberAlign);
147 return Address(ptr, memberAlign);
148}
149
David Majnemerc1709d32015-06-23 07:31:11 +0000150CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
151 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
152 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000153 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000154
David Majnemerc1709d32015-06-23 07:31:11 +0000155 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000156 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000157
John McCallcf142162010-08-07 06:22:56 +0000158 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000159 const CXXBaseSpecifier *Base = *I;
160 assert(!Base->isVirtual() && "Should not see virtual bases here!");
161
162 // Get the layout.
163 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000164
165 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000166 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000167
Anders Carlssond829a022010-04-24 21:06:20 +0000168 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000169 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000170
Anders Carlssond829a022010-04-24 21:06:20 +0000171 RD = BaseDecl;
172 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000173
Ken Dycka1a4ae32011-03-22 00:53:26 +0000174 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000175}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000176
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000177llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000178CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000179 CastExpr::path_const_iterator PathBegin,
180 CastExpr::path_const_iterator PathEnd) {
181 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000182
Justin Bogner1cd11f12015-05-20 15:53:59 +0000183 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000184 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000185 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000186 return nullptr;
187
Justin Bogner1cd11f12015-05-20 15:53:59 +0000188 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000189 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000190
Ken Dycka1a4ae32011-03-22 00:53:26 +0000191 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000192}
193
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000194/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000195/// This should only be used for (1) non-virtual bases or (2) virtual bases
196/// when the type is known to be complete (e.g. in complete destructors).
197///
198/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000199Address
200CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000201 const CXXRecordDecl *Derived,
202 const CXXRecordDecl *Base,
203 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000204 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000205 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000206
207 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000208 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000209 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000210 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000211 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000212 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000213 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000214
215 // Shift and cast down to the base type.
216 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000217 Address V = This;
218 if (!Offset.isZero()) {
219 V = Builder.CreateElementBitCast(V, Int8Ty);
220 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000221 }
John McCall7f416cc2015-09-08 08:05:57 +0000222 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000223
224 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000225}
John McCall6ce74722010-02-16 04:15:37 +0000226
John McCall7f416cc2015-09-08 08:05:57 +0000227static Address
228ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000229 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000230 llvm::Value *virtualOffset,
231 const CXXRecordDecl *derivedClass,
232 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000233 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000234 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000235
236 // Compute the offset from the static and dynamic components.
237 llvm::Value *baseOffset;
238 if (!nonVirtualOffset.isZero()) {
239 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
240 nonVirtualOffset.getQuantity());
241 if (virtualOffset) {
242 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
243 }
244 } else {
245 baseOffset = virtualOffset;
246 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000247
Anders Carlsson53cebd12010-04-20 16:03:35 +0000248 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000249 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000250 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
251 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000252
253 // If we have a virtual component, the alignment of the result will
254 // be relative only to the known alignment of that vbase.
255 CharUnits alignment;
256 if (virtualOffset) {
257 assert(nearestVBase && "virtual offset without vbase?");
258 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
259 derivedClass, nearestVBase);
260 } else {
261 alignment = addr.getAlignment();
262 }
263 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
264
265 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000266}
267
John McCall7f416cc2015-09-08 08:05:57 +0000268Address CodeGenFunction::GetAddressOfBaseClass(
269 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000270 CastExpr::path_const_iterator PathBegin,
271 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
272 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000273 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000274
John McCallcf142162010-08-07 06:22:56 +0000275 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000276 const CXXRecordDecl *VBase = nullptr;
277
John McCall13a39c62012-08-01 05:04:58 +0000278 // Sema has done some convenient canonicalization here: if the
279 // access path involved any virtual steps, the conversion path will
280 // *start* with a step down to the correct virtual base subobject,
281 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000282 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000283 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000284 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
285 ++Start;
286 }
John McCall13a39c62012-08-01 05:04:58 +0000287
288 // Compute the static offset of the ultimate destination within its
289 // allocating subobject (the virtual base, if there is one, or else
290 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000291 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
292 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000293
John McCall13a39c62012-08-01 05:04:58 +0000294 // If there's a virtual step, we can sometimes "devirtualize" it.
295 // For now, that's limited to when the derived type is final.
296 // TODO: "devirtualize" this for accesses to known-complete objects.
297 if (VBase && Derived->hasAttr<FinalAttr>()) {
298 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
299 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
300 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000301 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000302 }
303
Anders Carlssond829a022010-04-24 21:06:20 +0000304 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000305 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000306 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000307
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000308 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000309 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000310
John McCall13a39c62012-08-01 05:04:58 +0000311 // If the static offset is zero and we don't have a virtual step,
312 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000313 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000314 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000315 SanitizerSet SkippedChecks;
316 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000317 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000318 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000319 }
Anders Carlssond829a022010-04-24 21:06:20 +0000320 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000321 }
John McCall13a39c62012-08-01 05:04:58 +0000322
Craig Topper8a13c412014-05-21 05:09:00 +0000323 llvm::BasicBlock *origBB = nullptr;
324 llvm::BasicBlock *endBB = nullptr;
325
John McCall13a39c62012-08-01 05:04:58 +0000326 // Skip over the offset (and the vtable load) if we're supposed to
327 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000328 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000329 origBB = Builder.GetInsertBlock();
330 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
331 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000332
John McCall7f416cc2015-09-08 08:05:57 +0000333 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000334 Builder.CreateCondBr(isNull, endBB, notNullBB);
335 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000336 }
337
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000338 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000339 SanitizerSet SkippedChecks;
340 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000341 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000342 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000343 }
344
John McCall13a39c62012-08-01 05:04:58 +0000345 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000346 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000347 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000348 VirtualOffset =
349 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000350 }
Anders Carlssond829a022010-04-24 21:06:20 +0000351
John McCall13a39c62012-08-01 05:04:58 +0000352 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000353 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
354 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000355
John McCall13a39c62012-08-01 05:04:58 +0000356 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000357 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000358
359 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000360 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000361 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
362 Builder.CreateBr(endBB);
363 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000364
John McCall13a39c62012-08-01 05:04:58 +0000365 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000366 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000367 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000368 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000369 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000370
Anders Carlssond829a022010-04-24 21:06:20 +0000371 return Value;
372}
373
John McCall7f416cc2015-09-08 08:05:57 +0000374Address
375CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000376 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000377 CastExpr::path_const_iterator PathBegin,
378 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000379 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000380 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000381
Anders Carlsson8c793172009-11-23 17:57:54 +0000382 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000383 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000384 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000385
Anders Carlsson600f7372010-01-31 01:43:37 +0000386 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000387 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000388
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 if (!NonVirtualOffset) {
390 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000391 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000392 }
Craig Topper8a13c412014-05-21 05:09:00 +0000393
394 llvm::BasicBlock *CastNull = nullptr;
395 llvm::BasicBlock *CastNotNull = nullptr;
396 llvm::BasicBlock *CastEnd = nullptr;
397
Anders Carlsson8c793172009-11-23 17:57:54 +0000398 if (NullCheckValue) {
399 CastNull = createBasicBlock("cast.null");
400 CastNotNull = createBasicBlock("cast.notnull");
401 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000402
John McCall7f416cc2015-09-08 08:05:57 +0000403 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000404 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
405 EmitBlock(CastNotNull);
406 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000407
Anders Carlsson600f7372010-01-31 01:43:37 +0000408 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000409 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000410 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
411 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000412
413 // Just cast.
414 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000415
John McCall7f416cc2015-09-08 08:05:57 +0000416 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000417 if (NullCheckValue) {
418 Builder.CreateBr(CastEnd);
419 EmitBlock(CastNull);
420 Builder.CreateBr(CastEnd);
421 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000422
Jay Foad20c0f022011-03-30 11:28:58 +0000423 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000424 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000425 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000426 Value = PHI;
427 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000428
John McCall7f416cc2015-09-08 08:05:57 +0000429 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000430}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000431
432llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
433 bool ForVirtualBase,
434 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000435 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000436 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000437 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000438 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000439
John McCalldec348f72013-05-03 07:33:41 +0000440 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000441 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000442
Anders Carlssone36a6b32010-01-02 01:01:18 +0000443 llvm::Value *VTT;
444
John McCall5c60a6f2010-02-18 19:59:28 +0000445 uint64_t SubVTTIndex;
446
Douglas Gregor61535002013-01-31 05:50:40 +0000447 if (Delegating) {
448 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000450 } else if (RD == Base) {
451 // If the record matches the base, this is the complete ctor/dtor
452 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000453 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000454 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000455 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000456 SubVTTIndex = 0;
457 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000458 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000459 CharUnits BaseOffset = ForVirtualBase ?
460 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000461 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000462
Justin Bogner1cd11f12015-05-20 15:53:59 +0000463 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000465 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
466 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000467
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000468 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000469 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470 VTT = LoadCXXVTT();
471 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000472 } else {
473 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000474 VTT = CGM.getVTables().GetAddrOfVTT(RD);
475 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000476 }
477
478 return VTT;
479}
480
John McCall1d987562010-07-21 01:23:41 +0000481namespace {
John McCallf99a6312010-07-21 05:30:47 +0000482 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000483 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000484 const CXXRecordDecl *BaseClass;
485 bool BaseIsVirtual;
486 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
487 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000488
Craig Topper4f12f102014-03-12 06:41:41 +0000489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000490 const CXXRecordDecl *DerivedClass =
491 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
492
493 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000494 Address Addr =
495 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000496 DerivedClass, BaseClass,
497 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000498 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
499 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000500 }
501 };
John McCall769250e2010-09-17 02:31:44 +0000502
503 /// A visitor which checks whether an initializer uses 'this' in a
504 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000505 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
506 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000507
508 bool UsesThis;
509
Scott Douglass503fc392015-06-10 13:53:15 +0000510 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000511
512 // Black-list all explicit and implicit references to 'this'.
513 //
514 // Do we need to worry about external references to 'this' derived
515 // from arbitrary code? If so, then anything which runs arbitrary
516 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000517 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000518 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000519} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000520
521static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
522 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000523 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000524 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000525}
526
Justin Bogner1cd11f12015-05-20 15:53:59 +0000527static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000528 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000529 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000530 CXXCtorType CtorType) {
531 assert(BaseInit->isBaseInitializer() &&
532 "Must have base initializer!");
533
John McCall7f416cc2015-09-08 08:05:57 +0000534 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000535
Anders Carlssonfb404882009-12-24 22:46:43 +0000536 const Type *BaseType = BaseInit->getBaseClass();
537 CXXRecordDecl *BaseClassDecl =
538 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
539
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000540 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000541
542 // The base constructor doesn't construct virtual bases.
543 if (CtorType == Ctor_Base && isBaseVirtual)
544 return;
545
John McCall769250e2010-09-17 02:31:44 +0000546 // If the initializer for the base (other than the constructor
547 // itself) accesses 'this' in any way, we need to initialize the
548 // vtables.
549 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
550 CGF.InitializeVTablePointers(ClassDecl);
551
John McCall6ce74722010-02-16 04:15:37 +0000552 // We can pretend to be a complete class because it only matters for
553 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000554 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000555 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000556 BaseClassDecl,
557 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000558 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000559 AggValueSlot::forAddr(
560 V, Qualifiers(),
561 AggValueSlot::IsDestructed,
562 AggValueSlot::DoesNotNeedGCBarriers,
563 AggValueSlot::IsNotAliased,
564 CGF.overlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000565
566 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000567
568 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000569 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000570 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
571 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000572}
573
Richard Smith419bd092015-04-29 19:26:57 +0000574static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
575 auto *CD = dyn_cast<CXXConstructorDecl>(D);
576 if (!(CD && CD->isCopyOrMoveConstructor()) &&
577 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
578 return false;
579
580 // We can emit a memcpy for a trivial copy or move constructor/assignment.
581 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
582 return true;
583
584 // We *must* emit a memcpy for a defaulted union copy or move op.
585 if (D->getParent()->isUnion() && D->isDefaulted())
586 return true;
587
588 return false;
589}
590
Alexey Bataev152c71f2015-07-14 07:55:48 +0000591static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
592 CXXCtorInitializer *MemberInit,
593 LValue &LHS) {
594 FieldDecl *Field = MemberInit->getAnyMember();
595 if (MemberInit->isIndirectMemberInitializer()) {
596 // If we are initializing an anonymous union field, drill down to the field.
597 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
598 for (const auto *I : IndirectField->chain())
599 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
600 } else {
601 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
602 }
603}
604
Anders Carlssonfb404882009-12-24 22:46:43 +0000605static void EmitMemberInitializer(CodeGenFunction &CGF,
606 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000607 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000608 const CXXConstructorDecl *Constructor,
609 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000610 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000611 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000612 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000613 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000614
Anders Carlssonfb404882009-12-24 22:46:43 +0000615 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000616 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000617 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000618
619 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000620 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000621 LValue LHS;
622
623 // If a base constructor is being emitted, create an LValue that has the
624 // non-virtual alignment.
625 if (CGF.CurGD.getCtorType() == Ctor_Base)
626 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
627 else
628 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000629
Alexey Bataev152c71f2015-07-14 07:55:48 +0000630 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000631
Eli Friedman6ae63022012-02-14 02:15:49 +0000632 // Special case: if we are in a copy or move constructor, and we are copying
633 // an array of PODs or classes with trivial copy constructors, ignore the
634 // AST and perform the copy we know is equivalent.
635 // FIXME: This is hacky at best... if we had a bit more explicit information
636 // in the AST, we could generalize it more easily.
637 const ConstantArrayType *Array
638 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000639 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000640 Constructor->isCopyOrMoveConstructor()) {
641 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000642 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000643 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000644 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000645 unsigned SrcArgIndex =
646 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000647 llvm::Value *SrcPtr
648 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000649 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
650 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000651
Eli Friedman6ae63022012-02-14 02:15:49 +0000652 // Copy the aggregate.
Richard Smithe78fac52018-04-05 20:52:58 +0000653 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.overlapForFieldInit(Field),
654 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000655 // Ensure that we destroy the objects if an exception is thrown later in
656 // the constructor.
657 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
658 if (CGF.needsEHCleanup(dtorKind))
Fangrui Song6907ce22018-07-30 19:24:48 +0000659 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000660 return;
661 }
662 }
663
Richard Smith30e304e2016-12-14 00:03:17 +0000664 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000665}
666
John McCall7f416cc2015-09-08 08:05:57 +0000667void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000668 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000669 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000670 switch (getEvaluationKind(FieldType)) {
671 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000672 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000673 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000674 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000675 RValue RHS = RValue::get(EmitScalarExpr(Init));
676 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000677 }
John McCall47fb9502013-03-07 21:37:08 +0000678 break;
679 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000680 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000681 break;
682 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000683 AggValueSlot Slot =
Richard Smithe78fac52018-04-05 20:52:58 +0000684 AggValueSlot::forLValue(
685 LHS,
686 AggValueSlot::IsDestructed,
687 AggValueSlot::DoesNotNeedGCBarriers,
688 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +0000689 overlapForFieldInit(Field),
690 AggValueSlot::IsNotZeroed,
691 // Checks are made by the code that calls constructor.
692 AggValueSlot::IsSanitizerChecked);
Richard Smith30e304e2016-12-14 00:03:17 +0000693 EmitAggExpr(Init, Slot);
694 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000695 }
John McCall47fb9502013-03-07 21:37:08 +0000696 }
John McCall12cc42a2013-02-01 05:11:40 +0000697
698 // Ensure that we destroy this object if an exception is thrown
699 // later in the constructor.
700 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
701 if (needsEHCleanup(dtorKind))
702 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000703}
704
John McCallf8ff7b92010-02-23 00:48:20 +0000705/// Checks whether the given constructor is a valid subject for the
706/// complete-to-base constructor delegation optimization, i.e.
707/// emitting the complete constructor as a simple call to the base
708/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000709bool CodeGenFunction::IsConstructorDelegationValid(
710 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000711
712 // Currently we disable the optimization for classes with virtual
713 // bases because (1) the addresses of parameter variables need to be
714 // consistent across all initializers but (2) the delegate function
715 // call necessarily creates a second copy of the parameter variable.
716 //
717 // The limiting example (purely theoretical AFAIK):
718 // struct A { A(int &c) { c++; } };
719 // struct B : virtual A {
720 // B(int count) : A(count) { printf("%d\n", count); }
721 // };
722 // ...although even this example could in principle be emitted as a
723 // delegation since the address of the parameter doesn't escape.
724 if (Ctor->getParent()->getNumVBases()) {
725 // TODO: white-list trivial vbase initializers. This case wouldn't
726 // be subject to the restrictions below.
727
728 // TODO: white-list cases where:
729 // - there are no non-reference parameters to the constructor
730 // - the initializers don't access any non-reference parameters
731 // - the initializers don't take the address of non-reference
732 // parameters
733 // - etc.
734 // If we ever add any of the above cases, remember that:
735 // - function-try-blocks will always blacklist this optimization
736 // - we need to perform the constructor prologue and cleanup in
737 // EmitConstructorBody.
738
739 return false;
740 }
741
742 // We also disable the optimization for variadic functions because
743 // it's impossible to "re-pass" varargs.
744 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
745 return false;
746
Alexis Hunt61bc1732011-05-01 07:04:31 +0000747 // FIXME: Decide if we can do a delegation of a delegating constructor.
748 if (Ctor->isDelegatingConstructor())
749 return false;
750
John McCallf8ff7b92010-02-23 00:48:20 +0000751 return true;
752}
753
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000754// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
755// to poison the extra field paddings inserted under
756// -fsanitize-address-field-padding=1|2.
757void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
758 ASTContext &Context = getContext();
759 const CXXRecordDecl *ClassDecl =
760 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
761 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
762 if (!ClassDecl->mayInsertExtraPadding()) return;
763
764 struct SizeAndOffset {
765 uint64_t Size;
766 uint64_t Offset;
767 };
768
769 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
770 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
771
772 // Populate sizes and offsets of fields.
773 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
774 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
775 SSV[i].Offset =
776 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
777
778 size_t NumFields = 0;
779 for (const auto *Field : ClassDecl->fields()) {
780 const FieldDecl *D = Field;
781 std::pair<CharUnits, CharUnits> FieldInfo =
782 Context.getTypeInfoInChars(D->getType());
783 CharUnits FieldSize = FieldInfo.first;
784 assert(NumFields < SSV.size());
785 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
786 NumFields++;
787 }
788 assert(NumFields == SSV.size());
789 if (SSV.size() <= 1) return;
790
791 // We will insert calls to __asan_* run-time functions.
792 // LLVM AddressSanitizer pass may decide to inline them later.
793 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
794 llvm::FunctionType *FTy =
795 llvm::FunctionType::get(CGM.VoidTy, Args, false);
796 llvm::Constant *F = CGM.CreateRuntimeFunction(
797 FTy, Prologue ? "__asan_poison_intra_object_redzone"
798 : "__asan_unpoison_intra_object_redzone");
799
800 llvm::Value *ThisPtr = LoadCXXThis();
801 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000802 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000803 // For each field check if it has sufficient padding,
804 // if so (un)poison it with a call.
805 for (size_t i = 0; i < SSV.size(); i++) {
806 uint64_t AsanAlignment = 8;
807 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
808 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
809 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
810 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
811 (NextField % AsanAlignment) != 0)
812 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000813 Builder.CreateCall(
814 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
815 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000816 }
817}
818
John McCallb81884d2010-02-19 09:25:03 +0000819/// EmitConstructorBody - Emits the body of the current constructor.
820void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000821 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000822 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
823 CXXCtorType CtorType = CurGD.getCtorType();
824
Reid Kleckner340ad862014-01-13 22:57:31 +0000825 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
826 CtorType == Ctor_Complete) &&
827 "can only generate complete ctor for this ABI");
828
John McCallf8ff7b92010-02-23 00:48:20 +0000829 // Before we go any further, try the complete->base constructor
830 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000831 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000832 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000833 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
John McCallf8ff7b92010-02-23 00:48:20 +0000834 return;
835 }
836
Hans Wennborgdcfba332015-10-06 23:40:43 +0000837 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000838 Stmt *Body = Ctor->getBody(Definition);
839 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000840
John McCallf8ff7b92010-02-23 00:48:20 +0000841 // Enter the function-try-block before the constructor prologue if
842 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000843 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000844 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000845 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000846
Justin Bogner66242d62015-04-23 23:06:47 +0000847 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000848
Richard Smithcc1b96d2013-06-12 22:31:48 +0000849 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000850
John McCall88313032012-03-30 04:25:03 +0000851 // TODO: in restricted cases, we can emit the vbase initializers of
852 // a complete ctor and then delegate to the base ctor.
853
John McCallf8ff7b92010-02-23 00:48:20 +0000854 // Emit the constructor prologue, i.e. the base and member
855 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000856 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000857
858 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000859 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000860 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
861 else if (Body)
862 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000863
864 // Emit any cleanup blocks associated with the member or base
865 // initializers, which includes (along the exceptional path) the
866 // destructors for those members and bases that were fully
867 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000868 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000869
John McCallf8ff7b92010-02-23 00:48:20 +0000870 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000871 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000872}
873
Lang Hamesbf122742013-02-17 07:22:09 +0000874namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000875 /// RAII object to indicate that codegen is copying the value representation
876 /// instead of the object representation. Useful when copying a struct or
877 /// class which has uninitialized members and we're only performing
878 /// lvalue-to-rvalue conversion on the object but not its members.
879 class CopyingValueRepresentation {
880 public:
881 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000882 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000883 CGF.SanOpts.set(SanitizerKind::Bool, false);
884 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000885 }
886 ~CopyingValueRepresentation() {
887 CGF.SanOpts = OldSanOpts;
888 }
889 private:
890 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000891 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000892 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000893} // end anonymous namespace
Fangrui Song6907ce22018-07-30 19:24:48 +0000894
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000895namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000896 class FieldMemcpyizer {
897 public:
898 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
899 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000900 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000901 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000902 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
903 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000904
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000905 bool isMemcpyableField(FieldDecl *F) const {
906 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000907 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000908 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000909 Qualifiers Qual = F->getType().getQualifiers();
910 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
911 return false;
912 return true;
913 }
914
915 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000916 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000917 addInitialField(F);
918 else
919 addNextField(F);
920 }
921
David Majnemera586eb22014-10-10 18:57:10 +0000922 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000923 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000924 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000925 LastField->isBitField()
926 ? LastField->getBitWidthValue(Ctx)
927 : Ctx.toBits(
928 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
929 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
930 FirstByteOffset + Ctx.getCharWidth() - 1;
931 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000932 return MemcpySize;
933 }
934
935 void emitMemcpy() {
936 // Give the subclass a chance to bail out if it feels the memcpy isn't
937 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000938 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000939 return;
940 }
941
David Majnemera586eb22014-10-10 18:57:10 +0000942 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000943 if (FirstField->isBitField()) {
944 const CGRecordLayout &RL =
945 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
946 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000947 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000948 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000949 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000950 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000951 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000952 }
Lang Hamesbf122742013-02-17 07:22:09 +0000953
David Majnemera586eb22014-10-10 18:57:10 +0000954 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000955 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000956 Address ThisPtr = CGF.LoadCXXThisAddress();
957 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000958 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
959 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
960 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
961 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
962
John McCall7f416cc2015-09-08 08:05:57 +0000963 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
964 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
965 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000966 reset();
967 }
968
969 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000970 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000971 }
972
973 protected:
974 CodeGenFunction &CGF;
975 const CXXRecordDecl *ClassDecl;
976
977 private:
John McCall7f416cc2015-09-08 08:05:57 +0000978 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
979 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000980 llvm::Type *DBP =
981 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
982 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
983
John McCall7f416cc2015-09-08 08:05:57 +0000984 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000985 llvm::Type *SBP =
986 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
987 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
988
John McCall7f416cc2015-09-08 08:05:57 +0000989 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000990 }
991
992 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000993 FirstField = F;
994 LastField = F;
995 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
996 LastFieldOffset = FirstFieldOffset;
997 LastAddedFieldIndex = F->getFieldIndex();
998 }
Lang Hamesbf122742013-02-17 07:22:09 +0000999
1000 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +00001001 // For the most part, the following invariant will hold:
1002 // F->getFieldIndex() == LastAddedFieldIndex + 1
1003 // The one exception is that Sema won't add a copy-initializer for an
1004 // unnamed bitfield, which will show up here as a gap in the sequence.
1005 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1006 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001007 LastAddedFieldIndex = F->getFieldIndex();
1008
1009 // The 'first' and 'last' fields are chosen by offset, rather than field
1010 // index. This allows the code to support bitfields, as well as regular
1011 // fields.
1012 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1013 if (FOffset < FirstFieldOffset) {
1014 FirstField = F;
1015 FirstFieldOffset = FOffset;
1016 } else if (FOffset > LastFieldOffset) {
1017 LastField = F;
1018 LastFieldOffset = FOffset;
1019 }
1020 }
1021
1022 const VarDecl *SrcRec;
1023 const ASTRecordLayout &RecLayout;
1024 FieldDecl *FirstField;
1025 FieldDecl *LastField;
1026 uint64_t FirstFieldOffset, LastFieldOffset;
1027 unsigned LastAddedFieldIndex;
1028 };
1029
1030 class ConstructorMemcpyizer : public FieldMemcpyizer {
1031 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001032 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001033 /// constructor.
1034 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1035 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001036 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001037 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001038 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001039 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001040 }
1041
1042 // Returns true if a CXXCtorInitializer represents a member initialization
1043 // that can be rolled into a memcpy.
1044 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1045 if (!MemcpyableCtor)
1046 return false;
1047 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001048 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001049 QualType FieldType = Field->getType();
1050 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1051
Richard Smith419bd092015-04-29 19:26:57 +00001052 // Bail out on non-memcpyable, not-trivially-copyable members.
1053 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001054 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1055 FieldType->isReferenceType()))
1056 return false;
1057
1058 // Bail out on volatile fields.
1059 if (!isMemcpyableField(Field))
1060 return false;
1061
1062 // Otherwise we're good.
1063 return true;
1064 }
1065
1066 public:
1067 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1068 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001069 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001070 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001071 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001072 CD->isCopyOrMoveConstructor() &&
1073 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1074 Args(Args) { }
1075
1076 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1077 if (isMemberInitMemcpyable(MemberInit)) {
1078 AggregatedInits.push_back(MemberInit);
1079 addMemcpyableField(MemberInit->getMember());
1080 } else {
1081 emitAggregatedInits();
1082 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1083 ConstructorDecl, Args);
1084 }
1085 }
1086
1087 void emitAggregatedInits() {
1088 if (AggregatedInits.size() <= 1) {
1089 // This memcpy is too small to be worthwhile. Fall back on default
1090 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001091 if (!AggregatedInits.empty()) {
1092 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001093 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001094 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001095 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001096 }
1097 reset();
1098 return;
1099 }
1100
1101 pushEHDestructors();
1102 emitMemcpy();
1103 AggregatedInits.clear();
1104 }
1105
1106 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001107 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001108 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001109 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001110
1111 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001112 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1113 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001114 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001115 if (!CGF.needsEHCleanup(dtorKind))
1116 continue;
1117 LValue FieldLHS = LHS;
1118 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1119 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001120 }
1121 }
1122
1123 void finish() {
1124 emitAggregatedInits();
1125 }
1126
1127 private:
1128 const CXXConstructorDecl *ConstructorDecl;
1129 bool MemcpyableCtor;
1130 FunctionArgList &Args;
1131 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1132 };
1133
1134 class AssignmentMemcpyizer : public FieldMemcpyizer {
1135 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001136 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001137 // exists. Otherwise returns null.
1138 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001139 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1142 // Recognise trivial assignments.
1143 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001144 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001145 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1146 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001147 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001148 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1149 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001150 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001151 Stmt *RHS = BO->getRHS();
1152 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1153 RHS = EC->getSubExpr();
1154 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001156 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1157 if (ME2->getMemberDecl() == Field)
1158 return Field;
1159 }
1160 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001161 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1162 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001163 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001164 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001165 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1166 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001167 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001168 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1169 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001170 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001171 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1172 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 return Field;
1175 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1176 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1177 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001178 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001179 Expr *DstPtr = CE->getArg(0);
1180 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1181 DstPtr = DC->getSubExpr();
1182 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1183 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001184 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001185 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1186 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001187 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001188 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1189 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001190 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001191 Expr *SrcPtr = CE->getArg(1);
1192 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1193 SrcPtr = SC->getSubExpr();
1194 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1195 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001196 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001197 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1198 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001199 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001200 return Field;
1201 }
1202
Craig Topper8a13c412014-05-21 05:09:00 +00001203 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001204 }
1205
1206 bool AssignmentsMemcpyable;
1207 SmallVector<Stmt*, 16> AggregatedStmts;
1208
1209 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001210 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1211 FunctionArgList &Args)
1212 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1213 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1214 assert(Args.size() == 2);
1215 }
1216
1217 void emitAssignment(Stmt *S) {
1218 FieldDecl *F = getMemcpyableField(S);
1219 if (F) {
1220 addMemcpyableField(F);
1221 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001222 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001223 emitAggregatedStmts();
1224 CGF.EmitStmt(S);
1225 }
1226 }
1227
1228 void emitAggregatedStmts() {
1229 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001230 if (!AggregatedStmts.empty()) {
1231 CopyingValueRepresentation CVR(CGF);
1232 CGF.EmitStmt(AggregatedStmts[0]);
1233 }
Lang Hamesbf122742013-02-17 07:22:09 +00001234 reset();
1235 }
1236
1237 emitMemcpy();
1238 AggregatedStmts.clear();
1239 }
1240
1241 void finish() {
1242 emitAggregatedStmts();
1243 }
1244 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001245} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001246
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001247static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1248 const Type *BaseType = BaseInit->getBaseClass();
1249 const auto *BaseClassDecl =
1250 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1251 return BaseClassDecl->isDynamicClass();
1252}
1253
Anders Carlssonfb404882009-12-24 22:46:43 +00001254/// EmitCtorPrologue - This routine generates necessary code to initialize
1255/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001256void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001257 CXXCtorType CtorType,
1258 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001259 if (CD->isDelegatingConstructor())
1260 return EmitDelegatingCXXConstructorCall(CD, Args);
1261
Anders Carlssonfb404882009-12-24 22:46:43 +00001262 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001263
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001264 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1265 E = CD->init_end();
1266
Craig Topper8a13c412014-05-21 05:09:00 +00001267 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001268 if (ClassDecl->getNumVBases() &&
1269 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1270 // The ABIs that don't have constructor variants need to put a branch
1271 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001272 BaseCtorContinueBB =
1273 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001274 assert(BaseCtorContinueBB);
1275 }
1276
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001277 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001278 // Virtual base initializers first.
1279 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001280 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1281 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1282 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001283 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001284 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1285 }
1286
1287 if (BaseCtorContinueBB) {
1288 // Complete object handler should continue to the remaining initializers.
1289 Builder.CreateBr(BaseCtorContinueBB);
1290 EmitBlock(BaseCtorContinueBB);
1291 }
1292
1293 // Then, non-virtual base initializers.
1294 for (; B != E && (*B)->isBaseInitializer(); B++) {
1295 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001296
1297 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1298 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1299 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001300 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001301 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001302 }
1303
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001304 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001305
Anders Carlssond5895932010-03-28 21:07:49 +00001306 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001307
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001308 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001309 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001310 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001311 for (; B != E; B++) {
1312 CXXCtorInitializer *Member = (*B);
1313 assert(!Member->isBaseInitializer());
1314 assert(Member->isAnyMemberInitializer() &&
1315 "Delegating initializer on non-delegating constructor");
1316 CM.addMemberInitializer(Member);
1317 }
Lang Hamesbf122742013-02-17 07:22:09 +00001318 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001319}
1320
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001321static bool
1322FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1323
1324static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001325HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001326 const CXXRecordDecl *BaseClassDecl,
1327 const CXXRecordDecl *MostDerivedClassDecl)
1328{
1329 // If the destructor is trivial we don't have to check anything else.
1330 if (BaseClassDecl->hasTrivialDestructor())
1331 return true;
1332
1333 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1334 return false;
1335
1336 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001337 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001338 if (!FieldHasTrivialDestructorBody(Context, Field))
1339 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001340
1341 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001342 for (const auto &I : BaseClassDecl->bases()) {
1343 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001344 continue;
1345
1346 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001347 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001348 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1349 MostDerivedClassDecl))
1350 return false;
1351 }
1352
1353 if (BaseClassDecl == MostDerivedClassDecl) {
1354 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001355 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001356 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001357 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001358 if (!HasTrivialDestructorBody(Context, VirtualBase,
1359 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001360 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001361 }
1362 }
1363
1364 return true;
1365}
1366
1367static bool
1368FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001369 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001370{
1371 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1372
1373 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1374 if (!RT)
1375 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001376
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001377 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001378
1379 // The destructor for an implicit anonymous union member is never invoked.
1380 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1381 return false;
1382
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001383 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1384}
1385
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001386/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1387/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001388static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001389 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001390 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1391 if (!ClassDecl->isDynamicClass())
1392 return true;
1393
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001394 if (!Dtor->hasTrivialBody())
1395 return false;
1396
1397 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001398 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001399 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001400 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001401
1402 return true;
1403}
1404
John McCallb81884d2010-02-19 09:25:03 +00001405/// EmitDestructorBody - Emits the body of the current destructor.
1406void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1407 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1408 CXXDtorType DtorType = CurGD.getDtorType();
1409
Richard Smithdf054d32017-02-25 23:53:05 +00001410 // For an abstract class, non-base destructors are never used (and can't
1411 // be emitted in general, because vbase dtors may not have been validated
1412 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1413 // in fact emit references to them from other compilations, so emit them
1414 // as functions containing a trap instruction.
1415 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1416 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1417 TrapCall->setDoesNotReturn();
1418 TrapCall->setDoesNotThrow();
1419 Builder.CreateUnreachable();
1420 Builder.ClearInsertionPoint();
1421 return;
1422 }
1423
Justin Bognerfb298222015-05-20 16:16:23 +00001424 Stmt *Body = Dtor->getBody();
1425 if (Body)
1426 incrementProfileCounter(Body);
1427
John McCallf99a6312010-07-21 05:30:47 +00001428 // The call to operator delete in a deleting destructor happens
1429 // outside of the function-try-block, which means it's always
1430 // possible to delegate the destructor body to the complete
1431 // destructor. Do so.
1432 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001433 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001434 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001435 if (HaveInsertPoint())
1436 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1437 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001438 return;
1439 }
1440
John McCallb81884d2010-02-19 09:25:03 +00001441 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001442 // anything else.
1443 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001444 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001445 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001446 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001447
John McCallf99a6312010-07-21 05:30:47 +00001448 // Enter the epilogue cleanups.
1449 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001450
John McCallb81884d2010-02-19 09:25:03 +00001451 // If this is the complete variant, just invoke the base variant;
1452 // the epilogue will destruct the virtual bases. But we can't do
1453 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001454 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001455 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001456 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001457 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001458 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1459
1460 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001461 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1462 "can't emit a dtor without a body for non-Microsoft ABIs");
1463
John McCallf99a6312010-07-21 05:30:47 +00001464 // Enter the cleanup scopes for virtual bases.
1465 EnterDtorCleanups(Dtor, Dtor_Complete);
1466
Reid Klecknere7de47e2013-07-22 13:51:44 +00001467 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001468 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001469 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001470 break;
1471 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001472
John McCallf99a6312010-07-21 05:30:47 +00001473 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001474 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001475
John McCallf99a6312010-07-21 05:30:47 +00001476 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001477 assert(Body);
1478
John McCallf99a6312010-07-21 05:30:47 +00001479 // Enter the cleanup scopes for fields and non-virtual bases.
1480 EnterDtorCleanups(Dtor, Dtor_Base);
1481
1482 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001483 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001484 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001485 // the vptrs to cancel any previous assumptions we might have made.
1486 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1487 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001488 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001489 InitializeVTablePointers(Dtor->getParent());
1490 }
John McCallf99a6312010-07-21 05:30:47 +00001491
1492 if (isTryBody)
1493 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1494 else if (Body)
1495 EmitStmt(Body);
1496 else {
1497 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1498 // nothing to do besides what's in the epilogue
1499 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001500 // -fapple-kext must inline any call to this dtor into
1501 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001502 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001503 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001504
John McCallf99a6312010-07-21 05:30:47 +00001505 break;
John McCallb81884d2010-02-19 09:25:03 +00001506 }
1507
John McCallf99a6312010-07-21 05:30:47 +00001508 // Jump out through the epilogue cleanups.
1509 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001510
1511 // Exit the try if applicable.
1512 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001513 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001514}
1515
Lang Hamesbf122742013-02-17 07:22:09 +00001516void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1517 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1518 const Stmt *RootS = AssignOp->getBody();
1519 assert(isa<CompoundStmt>(RootS) &&
1520 "Body of an implicit assignment operator should be compound stmt.");
1521 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1522
1523 LexicalScope Scope(*this, RootCS->getSourceRange());
1524
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001525 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001526 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001527 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001528 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001529 AM.finish();
1530}
1531
John McCallf99a6312010-07-21 05:30:47 +00001532namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001533 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1534 const CXXDestructorDecl *DD) {
1535 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001536 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001537 return CGF.LoadCXXThis();
1538 }
1539
John McCallf99a6312010-07-21 05:30:47 +00001540 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001541 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001542 CallDtorDelete() {}
1543
Craig Topper4f12f102014-03-12 06:41:41 +00001544 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001545 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1546 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001547 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1548 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001549 CGF.getContext().getTagDeclType(ClassDecl));
1550 }
1551 };
1552
Richard Smith5b349582017-10-13 01:55:36 +00001553 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1554 llvm::Value *ShouldDeleteCondition,
1555 bool ReturnAfterDelete) {
1556 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1557 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1558 llvm::Value *ShouldCallDelete
1559 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1560 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1561
1562 CGF.EmitBlock(callDeleteBB);
1563 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1564 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1565 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1566 LoadThisForDtorDelete(CGF, Dtor),
1567 CGF.getContext().getTagDeclType(ClassDecl));
1568 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1569 ReturnAfterDelete &&
1570 "unexpected value for ReturnAfterDelete");
1571 if (ReturnAfterDelete)
1572 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1573 else
1574 CGF.Builder.CreateBr(continueBB);
1575
1576 CGF.EmitBlock(continueBB);
1577 }
1578
David Blaikie7e70d682015-08-18 22:40:54 +00001579 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001580 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001581
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001582 public:
1583 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001584 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001585 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001586 }
1587
Craig Topper4f12f102014-03-12 06:41:41 +00001588 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001589 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1590 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001591 }
1592 };
1593
David Blaikie7e70d682015-08-18 22:40:54 +00001594 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001595 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001596 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001597 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001598
John McCall4bd0fb12011-07-12 16:41:08 +00001599 public:
1600 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1601 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001602 : field(field), destroyer(destroyer),
1603 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001604
Craig Topper4f12f102014-03-12 06:41:41 +00001605 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001606 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001607 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001608 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1609 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1610 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001611 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001612
John McCall4bd0fb12011-07-12 16:41:08 +00001613 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001614 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001615 }
1616 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001617
Naomi Musgrave703835c2015-09-16 00:38:22 +00001618 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1619 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001620 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001621 // Pass in void pointer and size of region as arguments to runtime
1622 // function
1623 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1624 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1625
1626 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1627
1628 llvm::FunctionType *FnType =
1629 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1630 llvm::Value *Fn =
1631 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1632 CGF.EmitNounwindRuntimeCall(Fn, Args);
1633 }
1634
1635 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001636 const CXXDestructorDecl *Dtor;
1637
1638 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001639 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001640
1641 // Generate function call for handling object poisoning.
1642 // Disables tail call elimination, to prevent the current stack frame
1643 // from disappearing from the stack trace.
1644 void Emit(CodeGenFunction &CGF, Flags flags) override {
1645 const ASTRecordLayout &Layout =
1646 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1647
1648 // Nothing to poison.
1649 if (Layout.getFieldCount() == 0)
1650 return;
1651
1652 // Prevent the current stack frame from disappearing from the stack trace.
1653 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1654
1655 // Construct pointer to region to begin poisoning, and calculate poison
1656 // size, so that only members declared in this class are poisoned.
1657 ASTContext &Context = CGF.getContext();
1658 unsigned fieldIndex = 0;
1659 int startIndex = -1;
1660 // RecordDecl::field_iterator Field;
1661 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1662 // Poison field if it is trivial
1663 if (FieldHasTrivialDestructorBody(Context, Field)) {
1664 // Start sanitizing at this field
1665 if (startIndex < 0)
1666 startIndex = fieldIndex;
1667
1668 // Currently on the last field, and it must be poisoned with the
1669 // current block.
1670 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001671 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001672 }
1673 } else if (startIndex >= 0) {
1674 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001675 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001676 // Re-set the start index
1677 startIndex = -1;
1678 }
1679 fieldIndex += 1;
1680 }
1681 }
1682
1683 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001684 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001685 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001686 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001687 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001688 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001689 unsigned layoutEndOffset) {
1690 ASTContext &Context = CGF.getContext();
1691 const ASTRecordLayout &Layout =
1692 Context.getASTRecordLayout(Dtor->getParent());
1693
1694 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1695 CGF.SizeTy,
1696 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1697 .getQuantity());
1698
1699 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1700 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1701 OffsetSizePtr);
1702
1703 CharUnits::QuantityType PoisonSize;
1704 if (layoutEndOffset >= Layout.getFieldCount()) {
1705 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1706 Context.toCharUnitsFromBits(
1707 Layout.getFieldOffset(layoutStartOffset))
1708 .getQuantity();
1709 } else {
1710 PoisonSize = Context.toCharUnitsFromBits(
1711 Layout.getFieldOffset(layoutEndOffset) -
1712 Layout.getFieldOffset(layoutStartOffset))
1713 .getQuantity();
1714 }
1715
1716 if (PoisonSize == 0)
1717 return;
1718
Naomi Musgrave703835c2015-09-16 00:38:22 +00001719 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001720 }
1721 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001722
1723 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1724 const CXXDestructorDecl *Dtor;
1725
1726 public:
1727 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1728
1729 // Generate function call for handling vtable pointer poisoning.
1730 void Emit(CodeGenFunction &CGF, Flags flags) override {
1731 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001732 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001733 ASTContext &Context = CGF.getContext();
1734 // Poison vtable and vtable ptr if they exist for this class.
1735 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1736
1737 CharUnits::QuantityType PoisonSize =
1738 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1739 // Pass in void pointer and size of region as arguments to runtime
1740 // function
1741 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1742 }
1743 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001744} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001746/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001747/// destructor. This is to call destructors on members and base classes
1748/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001749///
1750/// For a deleting destructor, this also handles the case where a destroying
1751/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001752void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1753 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001754 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1755 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001756
John McCallf99a6312010-07-21 05:30:47 +00001757 // The deleting-destructor phase just needs to call the appropriate
1758 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001759 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001760 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001761 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001762 if (CXXStructorImplicitParamValue) {
1763 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001764 // telling whether this is a deleting destructor.
1765 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1766 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1767 /*ReturnAfterDelete*/true);
1768 else
1769 EHStack.pushCleanup<CallDtorDeleteConditional>(
1770 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001771 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001772 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1773 const CXXRecordDecl *ClassDecl = DD->getParent();
1774 EmitDeleteCall(DD->getOperatorDelete(),
1775 LoadThisForDtorDelete(*this, DD),
1776 getContext().getTagDeclType(ClassDecl));
1777 EmitBranchThroughCleanup(ReturnBlock);
1778 } else {
1779 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1780 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001781 }
John McCall5c60a6f2010-02-18 19:59:28 +00001782 return;
1783 }
1784
John McCallf99a6312010-07-21 05:30:47 +00001785 const CXXRecordDecl *ClassDecl = DD->getParent();
1786
Richard Smith20104042011-09-18 12:11:43 +00001787 // Unions have no bases and do not call field destructors.
1788 if (ClassDecl->isUnion())
1789 return;
1790
John McCallf99a6312010-07-21 05:30:47 +00001791 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001792 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001793 // Poison the vtable pointer such that access after the base
1794 // and member destructors are invoked is invalid.
1795 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1796 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1797 ClassDecl->isPolymorphic())
1798 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001799
1800 // We push them in the forward order so that they'll be popped in
1801 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001802 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001803 CXXRecordDecl *BaseClassDecl
1804 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001805
John McCall5c60a6f2010-02-18 19:59:28 +00001806 // Ignore trivial destructors.
1807 if (BaseClassDecl->hasTrivialDestructor())
1808 continue;
John McCallf99a6312010-07-21 05:30:47 +00001809
John McCallcda666c2010-07-21 07:22:38 +00001810 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1811 BaseClassDecl,
1812 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001813 }
John McCallf99a6312010-07-21 05:30:47 +00001814
John McCall5c60a6f2010-02-18 19:59:28 +00001815 return;
1816 }
1817
1818 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001819 // Poison the vtable pointer if it has no virtual bases, but inherits
1820 // virtual functions.
1821 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1822 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1823 ClassDecl->isPolymorphic())
1824 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001825
John McCallf99a6312010-07-21 05:30:47 +00001826 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001828 // Ignore virtual bases.
1829 if (Base.isVirtual())
1830 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001831
John McCallf99a6312010-07-21 05:30:47 +00001832 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001833
John McCallf99a6312010-07-21 05:30:47 +00001834 // Ignore trivial destructors.
1835 if (BaseClassDecl->hasTrivialDestructor())
1836 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001837
John McCallcda666c2010-07-21 07:22:38 +00001838 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1839 BaseClassDecl,
1840 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001841 }
1842
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001843 // Poison fields such that access after their destructors are
1844 // invoked, and before the base class destructor runs, is invalid.
1845 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1846 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001847 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001848
John McCallf99a6312010-07-21 05:30:47 +00001849 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001850 for (const auto *Field : ClassDecl->fields()) {
1851 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001852 QualType::DestructionKind dtorKind = type.isDestructedType();
1853 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001854
Richard Smith921bd202012-02-26 09:11:52 +00001855 // Anonymous union members do not have their destructors called.
1856 const RecordType *RT = type->getAsUnionType();
1857 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1858
John McCall4bd0fb12011-07-12 16:41:08 +00001859 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001860 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001861 getDestroyer(dtorKind),
1862 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001863 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001864}
1865
John McCallf677a8e2011-07-13 06:10:41 +00001866/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1867/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001868///
John McCallf677a8e2011-07-13 06:10:41 +00001869/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001870/// \param arrayType the type of the array to initialize
1871/// \param arrayBegin an arrayType*
1872/// \param zeroInitialize true if each element should be
1873/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001874void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001875 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
Serge Pavlov37605182018-07-28 15:33:03 +00001876 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1877 bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001878 QualType elementType;
1879 llvm::Value *numElements =
1880 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001881
Serge Pavlov37605182018-07-28 15:33:03 +00001882 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1883 NewPointerIsChecked, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001884}
1885
John McCallf677a8e2011-07-13 06:10:41 +00001886/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1887/// constructor for each of several members of an array.
1888///
1889/// \param ctor the constructor to call for each element
1890/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001891/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001892/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001893/// \param zeroInitialize true if each element should be
1894/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001895void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1896 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001897 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001898 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00001899 bool NewPointerIsChecked,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001900 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001901 // It's legal for numElements to be zero. This can happen both
1902 // dynamically, because x can be zero in 'new A[x]', and statically,
1903 // because of GCC extensions that permit zero-length arrays. There
1904 // are probably legitimate places where we could assume that this
1905 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001906 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001907
1908 // Optimize for a constant count.
1909 llvm::ConstantInt *constantCount
1910 = dyn_cast<llvm::ConstantInt>(numElements);
1911 if (constantCount) {
1912 // Just skip out if the constant count is zero.
1913 if (constantCount->isZero()) return;
1914
1915 // Otherwise, emit the check.
1916 } else {
1917 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1918 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1919 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1920 EmitBlock(loopBB);
1921 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001922
John McCallf677a8e2011-07-13 06:10:41 +00001923 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001924 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001925 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1926 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001927
John McCallf677a8e2011-07-13 06:10:41 +00001928 // Enter the loop, setting up a phi for the current location to initialize.
1929 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1930 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1931 EmitBlock(loopBB);
1932 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1933 "arrayctor.cur");
1934 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001935
Anders Carlsson27da15b2010-01-01 20:29:01 +00001936 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001937
John McCall7f416cc2015-09-08 08:05:57 +00001938 // The alignment of the base, adjusted by the size of a single element,
1939 // provides a conservative estimate of the alignment of every element.
1940 // (This assumes we never start tracking offsetted alignments.)
Fangrui Song6907ce22018-07-30 19:24:48 +00001941 //
John McCall7f416cc2015-09-08 08:05:57 +00001942 // Note that these are complete objects and so we don't need to
1943 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001944 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001945 CharUnits eltAlignment =
1946 arrayBase.getAlignment()
1947 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1948 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001949
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001950 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001951 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001952 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001953
1954 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001955 // There are two contexts in which temporaries are destroyed at a different
1956 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001957 // default constructor is called to initialize an element of an array.
1958 // If the constructor has one or more default arguments, the destruction of
1959 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001960 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001961
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001962 {
John McCallbd309292010-07-06 01:34:17 +00001963 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001964
John McCallf677a8e2011-07-13 06:10:41 +00001965 // Evaluate the constructor and its arguments in a regular
1966 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001967 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001968 !ctor->getParent()->hasTrivialDestructor()) {
1969 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001970 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1971 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001972 }
1973
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001974 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00001975 /*Delegating=*/false, curAddr, E,
Serge Pavlov37605182018-07-28 15:33:03 +00001976 AggValueSlot::DoesNotOverlap, NewPointerIsChecked);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001977 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001978
John McCallf677a8e2011-07-13 06:10:41 +00001979 // Go to the next element.
1980 llvm::Value *next =
1981 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1982 "arrayctor.next");
1983 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001984
John McCallf677a8e2011-07-13 06:10:41 +00001985 // Check whether that's the end of the loop.
1986 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1987 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1988 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001989
John McCall6549b312011-07-13 07:37:11 +00001990 // Patch the earlier check to skip over the loop.
1991 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1992
John McCallf677a8e2011-07-13 06:10:41 +00001993 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001994}
1995
John McCall82fe67b2011-07-09 01:37:26 +00001996void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001997 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001998 QualType type) {
1999 const RecordType *rtype = type->castAs<RecordType>();
2000 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2001 const CXXDestructorDecl *dtor = record->getDestructor();
2002 assert(!dtor->isTrivial());
2003 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00002004 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00002005}
2006
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002007void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2008 CXXCtorType Type,
2009 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00002010 bool Delegating, Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002011 const CXXConstructExpr *E,
Serge Pavlov37605182018-07-28 15:33:03 +00002012 AggValueSlot::Overlap_t Overlap,
2013 bool NewPointerIsChecked) {
Richard Smith5179eb72016-06-28 19:03:57 +00002014 CallArgList Args;
2015
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002016 LangAS SlotAS = E->getType().getAddressSpace();
2017 QualType ThisType = D->getThisType(getContext());
2018 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2019 llvm::Value *ThisPtr = This.getPointer();
2020 if (SlotAS != ThisAS) {
2021 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2022 llvm::Type *NewType =
2023 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2024 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2025 ThisAS, SlotAS, NewType);
2026 }
Richard Smith5179eb72016-06-28 19:03:57 +00002027 // Push the this ptr.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002028 Args.add(RValue::get(ThisPtr), D->getThisType(getContext()));
Richard Smith5179eb72016-06-28 19:03:57 +00002029
2030 // If this is a trivial constructor, emit a memcpy now before we lose
2031 // the alignment information on the argument.
2032 // FIXME: It would be better to preserve alignment information into CallArg.
2033 if (isMemcpyEquivalentSpecialMember(D)) {
2034 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2035
2036 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002037 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002038 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002039 LValue Dest = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002040 EmitAggregateCopyCtor(Dest, Src, Overlap);
Richard Smith5179eb72016-06-28 19:03:57 +00002041 return;
2042 }
2043
2044 // Add the rest of the user-supplied arguments.
2045 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002046 EvaluationOrder Order = E->isListInitialization()
2047 ? EvaluationOrder::ForceLeftToRight
2048 : EvaluationOrder::Default;
2049 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2050 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002051
Richard Smithe78fac52018-04-05 20:52:58 +00002052 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
Serge Pavlov37605182018-07-28 15:33:03 +00002053 Overlap, E->getExprLoc(), NewPointerIsChecked);
Richard Smith5179eb72016-06-28 19:03:57 +00002054}
2055
2056static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2057 const CXXConstructorDecl *Ctor,
2058 CXXCtorType Type, CallArgList &Args) {
2059 // We can't forward a variadic call.
2060 if (Ctor->isVariadic())
2061 return false;
2062
2063 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2064 // If the parameters are callee-cleanup, it's not safe to forward.
2065 for (auto *P : Ctor->parameters())
2066 if (P->getType().isDestructedType())
2067 return false;
2068
2069 // Likewise if they're inalloca.
2070 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002071 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002072 if (Info.usesInAlloca())
2073 return false;
2074 }
2075
2076 // Anything else should be OK.
2077 return true;
2078}
2079
2080void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2081 CXXCtorType Type,
2082 bool ForVirtualBase,
2083 bool Delegating,
2084 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002085 CallArgList &Args,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002086 AggValueSlot::Overlap_t Overlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002087 SourceLocation Loc,
2088 bool NewPointerIsChecked) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002089 const CXXRecordDecl *ClassDecl = D->getParent();
2090
Serge Pavlov37605182018-07-28 15:33:03 +00002091 if (!NewPointerIsChecked)
2092 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2093 getContext().getRecordType(ClassDecl), CharUnits::Zero());
John McCallca972cd2010-02-06 00:25:16 +00002094
Richard Smith419bd092015-04-29 19:26:57 +00002095 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002096 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002097 return;
2098 }
2099
2100 // If this is a trivial constructor, just emit what's needed. If this is a
2101 // union copy constructor, we must emit a memcpy, because the AST does not
2102 // model that copy.
2103 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002104 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002105
Richard Smith5179eb72016-06-28 19:03:57 +00002106 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002107 Address Src(Args[1].getRValue(*this).getScalarVal(),
2108 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002109 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002110 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002111 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002112 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002113 return;
2114 }
2115
George Burgess IVd0a9e802017-02-23 22:07:35 +00002116 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002117 // Check whether we can actually emit the constructor before trying to do so.
2118 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002119 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2120 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002121 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2122 Delegating, Args);
2123 return;
2124 }
2125 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002126
2127 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002128 CGCXXABI::AddedStructorArgs ExtraArgs =
2129 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2130 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002131
2132 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002133 llvm::Constant *CalleePtr =
2134 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002135 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002136 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
Erich Keanede6480a32018-11-13 15:48:08 +00002137 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
John McCallb92ab1a2016-10-26 23:46:34 +00002138 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002139
2140 // Generate vtable assumptions if we're constructing a complete object
2141 // with a vtable. We don't do this for base subobjects for two reasons:
2142 // first, it's incorrect for classes with virtual bases, and second, we're
2143 // about to overwrite the vptrs anyway.
2144 // We also have to make sure if we can refer to vtable:
2145 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2146 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2147 // sure that definition of vtable is not hidden,
2148 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002149 // FIXME: It looks like InstCombine is very inefficient on dealing with
2150 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002151 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2152 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002153 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2154 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002155 EmitVTableAssumptionLoads(ClassDecl, This);
2156}
2157
Richard Smith5179eb72016-06-28 19:03:57 +00002158void CodeGenFunction::EmitInheritedCXXConstructorCall(
2159 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2160 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2161 CallArgList Args;
Yaxun Liu5b330e82018-03-15 15:25:19 +00002162 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()));
Richard Smith5179eb72016-06-28 19:03:57 +00002163
2164 // Forward the parameters.
2165 if (InheritedFromVBase &&
2166 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2167 // Nothing to do; this construction is not responsible for constructing
2168 // the base class containing the inherited constructor.
2169 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2170 // have constructor variants?
2171 Args.push_back(ThisArg);
2172 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2173 // The inheriting constructor was inlined; just inject its arguments.
2174 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2175 "wrong number of parameters for inherited constructor call");
2176 Args = CXXInheritedCtorInitExprArgs;
2177 Args[0] = ThisArg;
2178 } else {
2179 // The inheriting constructor was not inlined. Emit delegating arguments.
2180 Args.push_back(ThisArg);
2181 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2182 assert(OuterCtor->getNumParams() == D->getNumParams());
2183 assert(!OuterCtor->isVariadic() && "should have been inlined");
2184
2185 for (const auto *Param : OuterCtor->parameters()) {
2186 assert(getContext().hasSameUnqualifiedType(
2187 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2188 Param->getType()));
2189 EmitDelegateCallArg(Args, Param, E->getLocation());
2190
2191 // Forward __attribute__(pass_object_size).
2192 if (Param->hasAttr<PassObjectSizeAttr>()) {
2193 auto *POSParam = SizeArguments[Param];
2194 assert(POSParam && "missing pass_object_size value for forwarding");
2195 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2196 }
2197 }
2198 }
2199
2200 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Igor Kudrineff8f9d2018-06-25 05:48:04 +00002201 This, Args, AggValueSlot::MayOverlap,
Serge Pavlov37605182018-07-28 15:33:03 +00002202 E->getLocation(), /*NewPointerIsChecked*/true);
Richard Smith5179eb72016-06-28 19:03:57 +00002203}
2204
2205void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2206 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2207 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002208 GlobalDecl GD(Ctor, CtorType);
2209 InlinedInheritingConstructorScope Scope(*this, GD);
2210 ApplyInlineDebugLocation DebugScope(*this, GD);
Volodymyr Sapsai232d22f2018-12-20 22:43:26 +00002211 RunCleanupsScope RunCleanups(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002212
2213 // Save the arguments to be passed to the inherited constructor.
2214 CXXInheritedCtorInitExprArgs = Args;
2215
2216 FunctionArgList Params;
2217 QualType RetType = BuildFunctionArgList(CurGD, Params);
2218 FnRetTy = RetType;
2219
2220 // Insert any ABI-specific implicit constructor arguments.
2221 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2222 ForVirtualBase, Delegating, Args);
2223
2224 // Emit a simplified prolog. We only need to emit the implicit params.
2225 assert(Args.size() >= Params.size() && "too few arguments for call");
2226 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2227 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002228 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002229 assert(!RV.isComplex() && "complex indirect params not supported");
2230 ParamValue Val = RV.isScalar()
2231 ? ParamValue::forDirect(RV.getScalarVal())
2232 : ParamValue::forIndirect(RV.getAggregateAddress());
2233 EmitParmDecl(*Params[I], Val, I + 1);
2234 }
2235 }
2236
2237 // Create a return value slot if the ABI implementation wants one.
2238 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2239 // value instead.
2240 if (!RetType->isVoidType())
2241 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2242
2243 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2244 CXXThisValue = CXXABIThisValue;
2245
2246 // Directly emit the constructor initializers.
2247 EmitCtorPrologue(Ctor, CtorType, Params);
2248}
2249
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002250void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2251 llvm::Value *VTableGlobal =
2252 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2253 if (!VTableGlobal)
2254 return;
2255
2256 // We can just use the base offset in the complete class.
2257 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2258
2259 if (!NonVirtualOffset.isZero())
2260 This =
2261 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2262 Vptr.VTableClass, Vptr.NearestVBase);
2263
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002264 llvm::Value *VPtrValue =
2265 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002266 llvm::Value *Cmp =
2267 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2268 Builder.CreateAssumption(Cmp);
2269}
2270
2271void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2272 Address This) {
2273 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2274 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2275 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002276}
2277
John McCallf8ff7b92010-02-23 00:48:20 +00002278void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002279CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002280 Address This, Address Src,
2281 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002282 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002283
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002284 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002285
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002286 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002287 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002288
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002289 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002290 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002291 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002292 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002293 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002294
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002295 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002296 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002297 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002298
Serge Pavlov37605182018-07-28 15:33:03 +00002299 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2300 /*Delegating*/false, This, Args,
2301 AggValueSlot::MayOverlap, E->getExprLoc(),
2302 /*NewPointerIsChecked*/false);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002303}
2304
2305void
John McCallf8ff7b92010-02-23 00:48:20 +00002306CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2307 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002308 const FunctionArgList &Args,
2309 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002310 CallArgList DelegateArgs;
2311
2312 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2313 assert(I != E && "no parameters to constructor");
2314
2315 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002316 Address This = LoadCXXThisAddress();
2317 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002318 ++I;
2319
Richard Smith5179eb72016-06-28 19:03:57 +00002320 // FIXME: The location of the VTT parameter in the parameter list is
2321 // specific to the Itanium ABI and shouldn't be hardcoded here.
2322 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2323 assert(I != E && "cannot skip vtt parameter, already done with args");
2324 assert((*I)->getType()->isPointerType() &&
2325 "skipping parameter not of vtt type");
2326 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002327 }
2328
2329 // Explicit arguments.
2330 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002331 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002332 // FIXME: per-argument source location
2333 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002334 }
2335
Richard Smith5179eb72016-06-28 19:03:57 +00002336 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002337 /*Delegating=*/true, This, DelegateArgs,
Serge Pavlov37605182018-07-28 15:33:03 +00002338 AggValueSlot::MayOverlap, Loc,
2339 /*NewPointerIsChecked=*/true);
John McCallf8ff7b92010-02-23 00:48:20 +00002340}
2341
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002342namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002343 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002344 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002345 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002346 CXXDtorType Type;
2347
John McCall7f416cc2015-09-08 08:05:57 +00002348 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002349 CXXDtorType Type)
2350 : Dtor(D), Addr(Addr), Type(Type) {}
2351
Craig Topper4f12f102014-03-12 06:41:41 +00002352 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002353 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002354 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002355 }
2356 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002357} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002358
Alexis Hunt61bc1732011-05-01 07:04:31 +00002359void
2360CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2361 const FunctionArgList &Args) {
2362 assert(Ctor->isDelegatingConstructor());
2363
John McCall7f416cc2015-09-08 08:05:57 +00002364 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002365
John McCall31168b02011-06-15 23:02:42 +00002366 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002367 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002368 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002369 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002370 AggValueSlot::IsNotAliased,
Serge Pavlov37605182018-07-28 15:33:03 +00002371 AggValueSlot::MayOverlap,
2372 AggValueSlot::IsNotZeroed,
2373 // Checks are made by the code that calls constructor.
2374 AggValueSlot::IsSanitizerChecked);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002375
2376 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002377
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002378 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002379 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002380 CXXDtorType Type =
2381 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2382
2383 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2384 ClassDecl->getDestructor(),
2385 ThisPtr, Type);
2386 }
2387}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002388
Anders Carlsson27da15b2010-01-01 20:29:01 +00002389void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2390 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002391 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002392 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002393 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002394 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2395 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002396}
2397
John McCall53cad2e2010-07-21 01:41:18 +00002398namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002399 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002400 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002401 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002402
John McCall7f416cc2015-09-08 08:05:57 +00002403 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002404 : Dtor(D), Addr(Addr) {}
2405
Craig Topper4f12f102014-03-12 06:41:41 +00002406 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002407 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002408 /*ForVirtualBase=*/false,
2409 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002410 }
2411 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002412} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002413
John McCall8680f872010-07-21 06:29:51 +00002414void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002415 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002416 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002417}
2418
John McCall7f416cc2015-09-08 08:05:57 +00002419void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002420 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2421 if (!ClassDecl) return;
2422 if (ClassDecl->hasTrivialDestructor()) return;
2423
2424 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002425 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002426 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002427}
2428
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002429void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002430 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002431 llvm::Value *VTableAddressPoint =
2432 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002433 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2434
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002435 if (!VTableAddressPoint)
2436 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002437
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002438 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002439 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002440 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002441
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002442 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002443 // We need to use the virtual base offset offset because the virtual base
2444 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002445
2446 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2447 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2448 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002449 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002450 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002451 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002452 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002453
Anders Carlssonc58fb552010-05-03 00:29:58 +00002454 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002455 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002456
Ken Dyckcfc332c2011-03-23 00:45:26 +00002457 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002458 VTableField = ApplyNonVirtualAndVirtualOffset(
2459 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2460 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002461
Reid Kleckner8d585132014-12-03 21:00:21 +00002462 // Finally, store the address point. Use the same LLVM types as the field to
2463 // support optimization.
2464 llvm::Type *VTablePtrTy =
2465 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2466 ->getPointerTo()
2467 ->getPointerTo();
2468 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2469 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002470
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002471 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002472 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2473 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002474 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2475 CGM.getCodeGenOpts().StrictVTablePointers)
2476 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002477}
2478
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002479CodeGenFunction::VPtrsVector
2480CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2481 CodeGenFunction::VPtrsVector VPtrsResult;
2482 VisitedVirtualBasesSetTy VBases;
2483 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2484 /*NearestVBase=*/nullptr,
2485 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2486 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2487 VPtrsResult);
2488 return VPtrsResult;
2489}
2490
2491void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2492 const CXXRecordDecl *NearestVBase,
2493 CharUnits OffsetFromNearestVBase,
2494 bool BaseIsNonVirtualPrimaryBase,
2495 const CXXRecordDecl *VTableClass,
2496 VisitedVirtualBasesSetTy &VBases,
2497 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002498 // If this base is a non-virtual primary base the address point has already
2499 // been set.
2500 if (!BaseIsNonVirtualPrimaryBase) {
2501 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002502 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2503 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002504 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002505
Anders Carlssond5895932010-03-28 21:07:49 +00002506 const CXXRecordDecl *RD = Base.getBase();
2507
2508 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002509 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002510 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002511 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002512
2513 // Ignore classes without a vtable.
2514 if (!BaseDecl->isDynamicClass())
2515 continue;
2516
Ken Dyck3fb4c892011-03-23 01:04:18 +00002517 CharUnits BaseOffset;
2518 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002519 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002520
Aaron Ballman574705e2014-03-13 15:41:46 +00002521 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002522 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002523 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002524 continue;
2525
Justin Bogner1cd11f12015-05-20 15:53:59 +00002526 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002527 getContext().getASTRecordLayout(VTableClass);
2528
Ken Dyck3fb4c892011-03-23 01:04:18 +00002529 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2530 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002531 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002532 } else {
2533 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2534
Ken Dyck16ffcac2011-03-24 01:21:01 +00002535 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002536 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002537 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002538 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002539 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002540
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002541 getVTablePointers(
2542 BaseSubobject(BaseDecl, BaseOffset),
2543 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2544 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002545 }
2546}
2547
2548void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2549 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002550 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002551 return;
2552
Anders Carlssond5895932010-03-28 21:07:49 +00002553 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002554 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2555 for (const VPtr &Vptr : getVTablePointers(RD))
2556 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002557
2558 if (RD->getNumVBases())
2559 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002560}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002561
John McCall7f416cc2015-09-08 08:05:57 +00002562llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002563 llvm::Type *VTableTy,
2564 const CXXRecordDecl *RD) {
2565 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002566 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002567 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2568 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002569
2570 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2571 CGM.getCodeGenOpts().StrictVTablePointers)
2572 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2573
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002574 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002575}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002576
Peter Collingbourned2926c92015-03-14 02:42:25 +00002577// If a class has a single non-virtual base and does not introduce or override
2578// virtual member functions or fields, it will have the same layout as its base.
2579// This function returns the least derived such class.
2580//
2581// Casting an instance of a base class to such a derived class is technically
2582// undefined behavior, but it is a relatively common hack for introducing member
2583// functions on class instances with specific properties (e.g. llvm::Operator)
2584// that works under most compilers and should not have security implications, so
2585// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2586static const CXXRecordDecl *
2587LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2588 if (!RD->field_empty())
2589 return RD;
2590
2591 if (RD->getNumVBases() != 0)
2592 return RD;
2593
2594 if (RD->getNumBases() != 1)
2595 return RD;
2596
2597 for (const CXXMethodDecl *MD : RD->methods()) {
2598 if (MD->isVirtual()) {
2599 // Virtual member functions are only ok if they are implicit destructors
2600 // because the implicit destructor will have the same semantics as the
2601 // base class's destructor if no fields are added.
2602 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2603 continue;
2604 return RD;
2605 }
2606 }
2607
2608 return LeastDerivedClassWithSameLayout(
2609 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2610}
2611
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002612void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2613 llvm::Value *VTable,
2614 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002615 if (SanOpts.has(SanitizerKind::CFIVCall))
2616 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2617 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2618 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002619 llvm::Metadata *MD =
2620 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002621 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002622 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2623
2624 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002625 llvm::Value *TypeTest =
2626 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2627 {CastedVTable, TypeId});
2628 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002629 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002630}
2631
2632void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002633 llvm::Value *VTable,
2634 CFITypeCheckKind TCK,
2635 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002636 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002637 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002638
Peter Collingbournefb532b92016-02-24 20:46:36 +00002639 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002640}
2641
Peter Collingbourned2926c92015-03-14 02:42:25 +00002642void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2643 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002644 bool MayBeNull,
2645 CFITypeCheckKind TCK,
2646 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002647 if (!getLangOpts().CPlusPlus)
2648 return;
2649
2650 auto *ClassTy = T->getAs<RecordType>();
2651 if (!ClassTy)
2652 return;
2653
2654 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2655
2656 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2657 return;
2658
Peter Collingbourned2926c92015-03-14 02:42:25 +00002659 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2660 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2661
Hans Wennborgdcfba332015-10-06 23:40:43 +00002662 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002663
2664 if (MayBeNull) {
2665 llvm::Value *DerivedNotNull =
2666 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2667
2668 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2669 ContBlock = createBasicBlock("cast.cont");
2670
2671 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2672
2673 EmitBlock(CheckBlock);
2674 }
2675
Peter Collingbourne60108802017-12-13 21:53:04 +00002676 llvm::Value *VTable;
2677 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2678 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002679
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002680 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002681
2682 if (MayBeNull) {
2683 Builder.CreateBr(ContBlock);
2684 EmitBlock(ContBlock);
2685 }
2686}
2687
2688void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002689 llvm::Value *VTable,
2690 CFITypeCheckKind TCK,
2691 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002692 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2693 !CGM.HasHiddenLTOVisibility(RD))
2694 return;
2695
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002696 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002697 llvm::SanitizerStatKind SSK;
2698 switch (TCK) {
2699 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002700 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002701 SSK = llvm::SanStat_CFI_VCall;
2702 break;
2703 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002704 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002705 SSK = llvm::SanStat_CFI_NVCall;
2706 break;
2707 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002708 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002709 SSK = llvm::SanStat_CFI_DerivedCast;
2710 break;
2711 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002712 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002713 SSK = llvm::SanStat_CFI_UnrelatedCast;
2714 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002715 case CFITCK_ICall:
Peter Collingbournee44acad2018-06-26 02:15:47 +00002716 case CFITCK_NVMFCall:
2717 case CFITCK_VMFCall:
2718 llvm_unreachable("unexpected sanitizer kind");
Peter Collingbournedc134532016-01-16 00:31:22 +00002719 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002720
2721 std::string TypeName = RD->getQualifiedNameAsString();
2722 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2723 return;
2724
2725 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002726 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002727
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002728 llvm::Metadata *MD =
2729 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002730 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002731
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002732 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002733 llvm::Value *TypeTest = Builder.CreateCall(
2734 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002735
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002736 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002737 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002738 EmitCheckSourceLocation(Loc),
2739 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002740 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002741
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002742 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2743 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2744 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002745 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002746 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002747
2748 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002749 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002750 return;
2751 }
2752
2753 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2754 CGM.getLLVMContext(),
2755 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002756 llvm::Value *ValidVtable = Builder.CreateCall(
2757 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002758 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2759 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002760}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002761
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002762bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2763 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2764 !SanOpts.has(SanitizerKind::CFIVCall) ||
2765 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2766 !CGM.HasHiddenLTOVisibility(RD))
2767 return false;
2768
2769 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002770 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2771 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002772}
2773
2774llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2775 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2776 SanitizerScope SanScope(this);
2777
2778 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2779
2780 llvm::Metadata *MD =
2781 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2782 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2783
2784 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2785 llvm::Value *CheckedLoad = Builder.CreateCall(
2786 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2787 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2788 TypeId});
2789 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2790
2791 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002792 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002793
2794 return Builder.CreateBitCast(
2795 Builder.CreateExtractValue(CheckedLoad, 0),
2796 cast<llvm::PointerType>(VTable->getType())->getElementType());
2797}
2798
Faisal Vali571df122013-09-29 08:45:24 +00002799void CodeGenFunction::EmitForwardingCallToLambda(
2800 const CXXMethodDecl *callOperator,
2801 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002802 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002803 const CGFunctionInfo &calleeFnInfo =
2804 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002805 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002806 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2807 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002808
John McCall8dda7b22012-07-07 06:41:13 +00002809 // Prepare the return slot.
2810 const FunctionProtoType *FPT =
2811 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002812 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002813 ReturnValueSlot returnSlot;
2814 if (!resultType->isVoidType() &&
2815 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002816 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002817 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2818
2819 // We don't need to separately arrange the call arguments because
2820 // the call can't be variadic anyway --- it's impossible to forward
2821 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002822
Eli Friedman5b446882012-02-16 03:47:28 +00002823 // Now emit our call.
Erich Keanede6480a32018-11-13 15:48:08 +00002824 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
John McCallb92ab1a2016-10-26 23:46:34 +00002825 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002826
John McCall8dda7b22012-07-07 06:41:13 +00002827 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002828 if (!resultType->isVoidType() && returnSlot.isNull()) {
2829 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2830 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2831 }
John McCall8dda7b22012-07-07 06:41:13 +00002832 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002833 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002834 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002835}
2836
Eli Friedman2495ab02012-02-25 02:48:22 +00002837void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2838 const BlockDecl *BD = BlockInfo->getBlockDecl();
2839 const VarDecl *variable = BD->capture_begin()->getVariable();
2840 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002841 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2842
2843 if (CallOp->isVariadic()) {
2844 // FIXME: Making this work correctly is nasty because it requires either
2845 // cloning the body of the call operator or making the call operator
2846 // forward.
2847 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2848 return;
2849 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002850
2851 // Start building arguments for forwarding call
2852 CallArgList CallArgs;
2853
2854 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002855 Address ThisPtr = GetAddrOfBlockDecl(variable);
John McCall7f416cc2015-09-08 08:05:57 +00002856 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002857
2858 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002859 for (auto param : BD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002860 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002861
Justin Bogner1cd11f12015-05-20 15:53:59 +00002862 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002863 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002864 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002865}
2866
2867void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2868 const CXXRecordDecl *Lambda = MD->getParent();
2869
2870 // Start building arguments for forwarding call
2871 CallArgList CallArgs;
2872
2873 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2874 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2875 CallArgs.add(RValue::get(ThisPtr), ThisType);
2876
2877 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002878 for (auto Param : MD->parameters())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002879 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002880
Faisal Vali571df122013-09-29 08:45:24 +00002881 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2882 // For a generic lambda, find the corresponding call operator specialization
2883 // to which the call to the static-invoker shall be forwarded.
2884 if (Lambda->isGenericLambda()) {
2885 assert(MD->isFunctionTemplateSpecialization());
2886 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2887 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002888 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002889 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002890 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002891 assert(CorrespondingCallOpSpecialization);
2892 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2893 }
2894 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002895}
2896
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002897void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002898 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002899 // FIXME: Making this work correctly is nasty because it requires either
2900 // cloning the body of the call operator or making the call operator forward.
2901 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002902 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002903 }
2904
Douglas Gregor355efbb2012-02-17 03:02:34 +00002905 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002906}