blob: db947d6514a4287133d1194b6541a998a0092095 [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"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hamesbf122742013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000026#include "clang/Frontend/CodeGenOptions.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Piotr Padlewski4b1ac722015-09-15 21:46:55 +000028#include "llvm/IR/Metadata.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000029#include "llvm/Transforms/Utils/SanitizerStats.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000030
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall7f416cc2015-09-08 08:05:57 +000034/// Return the best known alignment for an unknown pointer to a
35/// particular class.
36CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
37 if (!RD->isCompleteDefinition())
38 return CharUnits::One(); // Hopefully won't be used anywhere.
39
40 auto &layout = getContext().getASTRecordLayout(RD);
41
42 // If the class is final, then we know that the pointer points to an
43 // object of that type and can use the full alignment.
44 if (RD->hasAttr<FinalAttr>()) {
45 return layout.getAlignment();
46
47 // Otherwise, we have to assume it could be a subclass.
48 } else {
49 return layout.getNonVirtualAlignment();
50 }
51}
52
53/// Return the best known alignment for a pointer to a virtual base,
54/// given the alignment of a pointer to the derived class.
55CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
56 const CXXRecordDecl *derivedClass,
57 const CXXRecordDecl *vbaseClass) {
58 // The basic idea here is that an underaligned derived pointer might
59 // indicate an underaligned base pointer.
60
61 assert(vbaseClass->isCompleteDefinition());
62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
64
65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
66 expectedVBaseAlign);
67}
68
69CharUnits
70CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
71 const CXXRecordDecl *baseDecl,
72 CharUnits expectedTargetAlign) {
73 // If the base is an incomplete type (which is, alas, possible with
74 // member pointers), be pessimistic.
75 if (!baseDecl->isCompleteDefinition())
76 return std::min(actualBaseAlign, expectedTargetAlign);
77
78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
80
81 // If the class is properly aligned, assume the target offset is, too.
82 //
83 // This actually isn't necessarily the right thing to do --- if the
84 // class is a complete object, but it's only properly aligned for a
85 // base subobject, then the alignments of things relative to it are
86 // probably off as well. (Note that this requires the alignment of
87 // the target to be greater than the NV alignment of the derived
88 // class.)
89 //
90 // However, our approach to this kind of under-alignment can only
91 // ever be best effort; after all, we're never going to propagate
92 // alignments through variables or parameters. Note, in particular,
93 // that constructing a polymorphic type in an address that's less
94 // than pointer-aligned will generally trap in the constructor,
95 // unless we someday add some sort of attribute to change the
96 // assumed alignment of 'this'. So our goal here is pretty much
97 // just to allow the user to explicitly say that a pointer is
Eric Christopherd160c502016-01-29 01:35:53 +000098 // under-aligned and then safely access its fields and vtables.
John McCall7f416cc2015-09-08 08:05:57 +000099 if (actualBaseAlign >= expectedBaseAlign) {
100 return expectedTargetAlign;
101 }
102
103 // Otherwise, we might be offset by an arbitrary multiple of the
104 // actual alignment. The correct adjustment is to take the min of
105 // the two alignments.
106 return std::min(actualBaseAlign, expectedTargetAlign);
107}
108
109Address CodeGenFunction::LoadCXXThisAddress() {
110 assert(CurFuncDecl && "loading 'this' without a func declaration?");
111 assert(isa<CXXMethodDecl>(CurFuncDecl));
112
113 // Lazily compute CXXThisAlignment.
114 if (CXXThisAlignment.isZero()) {
115 // Just use the best known alignment for the parent.
116 // TODO: if we're currently emitting a complete-object ctor/dtor,
117 // we can always use the complete-object alignment.
118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
120 }
121
122 return Address(LoadCXXThis(), CXXThisAlignment);
123}
124
125/// Emit the address of a field using a member data pointer.
126///
127/// \param E Only used for emergency diagnostics
128Address
129CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
130 llvm::Value *memberPtr,
131 const MemberPointerType *memberPtrType,
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +0000132 LValueBaseInfo *BaseInfo,
133 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000134 // Ask the ABI to compute the actual address.
135 llvm::Value *ptr =
136 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
137 memberPtr, memberPtrType);
138
139 QualType memberType = memberPtrType->getPointeeType();
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +0000140 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
141 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000142 memberAlign =
143 CGM.getDynamicOffsetAlignment(base.getAlignment(),
144 memberPtrType->getClass()->getAsCXXRecordDecl(),
145 memberAlign);
146 return Address(ptr, memberAlign);
147}
148
David Majnemerc1709d32015-06-23 07:31:11 +0000149CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
150 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
151 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000152 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000153
David Majnemerc1709d32015-06-23 07:31:11 +0000154 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000155 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000156
John McCallcf142162010-08-07 06:22:56 +0000157 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000158 const CXXBaseSpecifier *Base = *I;
159 assert(!Base->isVirtual() && "Should not see virtual bases here!");
160
161 // Get the layout.
162 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000163
164 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000165 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000166
Anders Carlssond829a022010-04-24 21:06:20 +0000167 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000168 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000169
Anders Carlssond829a022010-04-24 21:06:20 +0000170 RD = BaseDecl;
171 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000172
Ken Dycka1a4ae32011-03-22 00:53:26 +0000173 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000174}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000175
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000176llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000177CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000178 CastExpr::path_const_iterator PathBegin,
179 CastExpr::path_const_iterator PathEnd) {
180 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000181
Justin Bogner1cd11f12015-05-20 15:53:59 +0000182 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000183 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000184 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000185 return nullptr;
186
Justin Bogner1cd11f12015-05-20 15:53:59 +0000187 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000188 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000189
Ken Dycka1a4ae32011-03-22 00:53:26 +0000190 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000191}
192
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000193/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000194/// This should only be used for (1) non-virtual bases or (2) virtual bases
195/// when the type is known to be complete (e.g. in complete destructors).
196///
197/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000198Address
199CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000200 const CXXRecordDecl *Derived,
201 const CXXRecordDecl *Base,
202 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000203 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000204 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000205
206 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000207 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000208 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000209 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000210 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000211 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000212 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000213
214 // Shift and cast down to the base type.
215 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000216 Address V = This;
217 if (!Offset.isZero()) {
218 V = Builder.CreateElementBitCast(V, Int8Ty);
219 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000220 }
John McCall7f416cc2015-09-08 08:05:57 +0000221 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000222
223 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000224}
John McCall6ce74722010-02-16 04:15:37 +0000225
John McCall7f416cc2015-09-08 08:05:57 +0000226static Address
227ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000228 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000229 llvm::Value *virtualOffset,
230 const CXXRecordDecl *derivedClass,
231 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000232 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000233 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000234
235 // Compute the offset from the static and dynamic components.
236 llvm::Value *baseOffset;
237 if (!nonVirtualOffset.isZero()) {
238 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
239 nonVirtualOffset.getQuantity());
240 if (virtualOffset) {
241 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
242 }
243 } else {
244 baseOffset = virtualOffset;
245 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000246
Anders Carlsson53cebd12010-04-20 16:03:35 +0000247 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000248 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000249 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
250 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000251
252 // If we have a virtual component, the alignment of the result will
253 // be relative only to the known alignment of that vbase.
254 CharUnits alignment;
255 if (virtualOffset) {
256 assert(nearestVBase && "virtual offset without vbase?");
257 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
258 derivedClass, nearestVBase);
259 } else {
260 alignment = addr.getAlignment();
261 }
262 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
263
264 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000265}
266
John McCall7f416cc2015-09-08 08:05:57 +0000267Address CodeGenFunction::GetAddressOfBaseClass(
268 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000269 CastExpr::path_const_iterator PathBegin,
270 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
271 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000272 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000273
John McCallcf142162010-08-07 06:22:56 +0000274 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000275 const CXXRecordDecl *VBase = nullptr;
276
John McCall13a39c62012-08-01 05:04:58 +0000277 // Sema has done some convenient canonicalization here: if the
278 // access path involved any virtual steps, the conversion path will
279 // *start* with a step down to the correct virtual base subobject,
280 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000281 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000282 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000283 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
284 ++Start;
285 }
John McCall13a39c62012-08-01 05:04:58 +0000286
287 // Compute the static offset of the ultimate destination within its
288 // allocating subobject (the virtual base, if there is one, or else
289 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000290 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
291 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000292
John McCall13a39c62012-08-01 05:04:58 +0000293 // If there's a virtual step, we can sometimes "devirtualize" it.
294 // For now, that's limited to when the derived type is final.
295 // TODO: "devirtualize" this for accesses to known-complete objects.
296 if (VBase && Derived->hasAttr<FinalAttr>()) {
297 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
298 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
299 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000300 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000301 }
302
Anders Carlssond829a022010-04-24 21:06:20 +0000303 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000304 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000305 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000306
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000307 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000308 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000309
John McCall13a39c62012-08-01 05:04:58 +0000310 // If the static offset is zero and we don't have a virtual step,
311 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000312 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000313 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000314 SanitizerSet SkippedChecks;
315 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000316 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000317 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000318 }
Anders Carlssond829a022010-04-24 21:06:20 +0000319 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000320 }
John McCall13a39c62012-08-01 05:04:58 +0000321
Craig Topper8a13c412014-05-21 05:09:00 +0000322 llvm::BasicBlock *origBB = nullptr;
323 llvm::BasicBlock *endBB = nullptr;
324
John McCall13a39c62012-08-01 05:04:58 +0000325 // Skip over the offset (and the vtable load) if we're supposed to
326 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000327 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000328 origBB = Builder.GetInsertBlock();
329 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
330 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000331
John McCall7f416cc2015-09-08 08:05:57 +0000332 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000333 Builder.CreateCondBr(isNull, endBB, notNullBB);
334 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000335 }
336
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000337 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000338 SanitizerSet SkippedChecks;
339 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000340 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000341 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000342 }
343
John McCall13a39c62012-08-01 05:04:58 +0000344 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000345 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000346 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000347 VirtualOffset =
348 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000349 }
Anders Carlssond829a022010-04-24 21:06:20 +0000350
John McCall13a39c62012-08-01 05:04:58 +0000351 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000352 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
353 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000354
John McCall13a39c62012-08-01 05:04:58 +0000355 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000356 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000357
358 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000359 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000360 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
361 Builder.CreateBr(endBB);
362 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000363
John McCall13a39c62012-08-01 05:04:58 +0000364 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000365 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000366 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000367 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000368 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000369
Anders Carlssond829a022010-04-24 21:06:20 +0000370 return Value;
371}
372
John McCall7f416cc2015-09-08 08:05:57 +0000373Address
374CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000375 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000376 CastExpr::path_const_iterator PathBegin,
377 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000378 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000379 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000380
Anders Carlsson8c793172009-11-23 17:57:54 +0000381 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000382 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000383 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000384
Anders Carlsson600f7372010-01-31 01:43:37 +0000385 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000386 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000387
Anders Carlsson600f7372010-01-31 01:43:37 +0000388 if (!NonVirtualOffset) {
389 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000390 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000391 }
Craig Topper8a13c412014-05-21 05:09:00 +0000392
393 llvm::BasicBlock *CastNull = nullptr;
394 llvm::BasicBlock *CastNotNull = nullptr;
395 llvm::BasicBlock *CastEnd = nullptr;
396
Anders Carlsson8c793172009-11-23 17:57:54 +0000397 if (NullCheckValue) {
398 CastNull = createBasicBlock("cast.null");
399 CastNotNull = createBasicBlock("cast.notnull");
400 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000401
John McCall7f416cc2015-09-08 08:05:57 +0000402 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000403 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
404 EmitBlock(CastNotNull);
405 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000406
Anders Carlsson600f7372010-01-31 01:43:37 +0000407 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000408 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Sanjay Patel372c3f12018-01-19 15:14:51 +0000409 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
410 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000411
412 // Just cast.
413 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000414
John McCall7f416cc2015-09-08 08:05:57 +0000415 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000416 if (NullCheckValue) {
417 Builder.CreateBr(CastEnd);
418 EmitBlock(CastNull);
419 Builder.CreateBr(CastEnd);
420 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000421
Jay Foad20c0f022011-03-30 11:28:58 +0000422 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000423 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000424 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000425 Value = PHI;
426 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000427
John McCall7f416cc2015-09-08 08:05:57 +0000428 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000429}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000430
431llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
432 bool ForVirtualBase,
433 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000434 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000435 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000436 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000437 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000438
John McCalldec348f72013-05-03 07:33:41 +0000439 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000440 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000441
Anders Carlssone36a6b32010-01-02 01:01:18 +0000442 llvm::Value *VTT;
443
John McCall5c60a6f2010-02-18 19:59:28 +0000444 uint64_t SubVTTIndex;
445
Douglas Gregor61535002013-01-31 05:50:40 +0000446 if (Delegating) {
447 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000448 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000449 } else if (RD == Base) {
450 // If the record matches the base, this is the complete ctor/dtor
451 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000452 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000453 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000454 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000455 SubVTTIndex = 0;
456 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000457 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000458 CharUnits BaseOffset = ForVirtualBase ?
459 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000460 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000461
Justin Bogner1cd11f12015-05-20 15:53:59 +0000462 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000463 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000464 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
465 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000466
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000467 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000468 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000469 VTT = LoadCXXVTT();
470 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000471 } else {
472 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000473 VTT = CGM.getVTables().GetAddrOfVTT(RD);
474 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000475 }
476
477 return VTT;
478}
479
John McCall1d987562010-07-21 01:23:41 +0000480namespace {
John McCallf99a6312010-07-21 05:30:47 +0000481 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000482 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000483 const CXXRecordDecl *BaseClass;
484 bool BaseIsVirtual;
485 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
486 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000487
Craig Topper4f12f102014-03-12 06:41:41 +0000488 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000489 const CXXRecordDecl *DerivedClass =
490 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
491
492 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000493 Address Addr =
494 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000495 DerivedClass, BaseClass,
496 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000497 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
498 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000499 }
500 };
John McCall769250e2010-09-17 02:31:44 +0000501
502 /// A visitor which checks whether an initializer uses 'this' in a
503 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000504 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
505 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000506
507 bool UsesThis;
508
Scott Douglass503fc392015-06-10 13:53:15 +0000509 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000510
511 // Black-list all explicit and implicit references to 'this'.
512 //
513 // Do we need to worry about external references to 'this' derived
514 // from arbitrary code? If so, then anything which runs arbitrary
515 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000516 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000517 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000518} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000519
520static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
521 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000522 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000523 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000524}
525
Justin Bogner1cd11f12015-05-20 15:53:59 +0000526static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000527 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000528 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000529 CXXCtorType CtorType) {
530 assert(BaseInit->isBaseInitializer() &&
531 "Must have base initializer!");
532
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000534
Anders Carlssonfb404882009-12-24 22:46:43 +0000535 const Type *BaseType = BaseInit->getBaseClass();
536 CXXRecordDecl *BaseClassDecl =
537 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
538
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000539 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000540
541 // The base constructor doesn't construct virtual bases.
542 if (CtorType == Ctor_Base && isBaseVirtual)
543 return;
544
John McCall769250e2010-09-17 02:31:44 +0000545 // If the initializer for the base (other than the constructor
546 // itself) accesses 'this' in any way, we need to initialize the
547 // vtables.
548 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
549 CGF.InitializeVTablePointers(ClassDecl);
550
John McCall6ce74722010-02-16 04:15:37 +0000551 // We can pretend to be a complete class because it only matters for
552 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000553 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000554 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000555 BaseClassDecl,
556 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000557 AggValueSlot AggSlot =
Richard Smithe78fac52018-04-05 20:52:58 +0000558 AggValueSlot::forAddr(
559 V, Qualifiers(),
560 AggValueSlot::IsDestructed,
561 AggValueSlot::DoesNotNeedGCBarriers,
562 AggValueSlot::IsNotAliased,
563 CGF.overlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
John McCall7a626f62010-09-15 10:14:12 +0000564
565 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000566
567 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000568 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000569 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
570 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000571}
572
Richard Smith419bd092015-04-29 19:26:57 +0000573static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
574 auto *CD = dyn_cast<CXXConstructorDecl>(D);
575 if (!(CD && CD->isCopyOrMoveConstructor()) &&
576 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
577 return false;
578
579 // We can emit a memcpy for a trivial copy or move constructor/assignment.
580 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
581 return true;
582
583 // We *must* emit a memcpy for a defaulted union copy or move op.
584 if (D->getParent()->isUnion() && D->isDefaulted())
585 return true;
586
587 return false;
588}
589
Alexey Bataev152c71f2015-07-14 07:55:48 +0000590static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
591 CXXCtorInitializer *MemberInit,
592 LValue &LHS) {
593 FieldDecl *Field = MemberInit->getAnyMember();
594 if (MemberInit->isIndirectMemberInitializer()) {
595 // If we are initializing an anonymous union field, drill down to the field.
596 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
597 for (const auto *I : IndirectField->chain())
598 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
599 } else {
600 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
601 }
602}
603
Anders Carlssonfb404882009-12-24 22:46:43 +0000604static void EmitMemberInitializer(CodeGenFunction &CGF,
605 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000606 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000607 const CXXConstructorDecl *Constructor,
608 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000609 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000610 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000611 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000612 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000613
Anders Carlssonfb404882009-12-24 22:46:43 +0000614 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000615 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000616 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000617
618 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000619 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Akira Hatanakae5dbb642018-01-27 00:34:09 +0000620 LValue LHS;
621
622 // If a base constructor is being emitted, create an LValue that has the
623 // non-virtual alignment.
624 if (CGF.CurGD.getCtorType() == Ctor_Base)
625 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
626 else
627 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000628
Alexey Bataev152c71f2015-07-14 07:55:48 +0000629 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000630
Eli Friedman6ae63022012-02-14 02:15:49 +0000631 // Special case: if we are in a copy or move constructor, and we are copying
632 // an array of PODs or classes with trivial copy constructors, ignore the
633 // AST and perform the copy we know is equivalent.
634 // FIXME: This is hacky at best... if we had a bit more explicit information
635 // in the AST, we could generalize it more easily.
636 const ConstantArrayType *Array
637 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000638 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000639 Constructor->isCopyOrMoveConstructor()) {
640 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000641 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000642 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000643 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000644 unsigned SrcArgIndex =
645 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000646 llvm::Value *SrcPtr
647 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000648 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
649 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000650
Eli Friedman6ae63022012-02-14 02:15:49 +0000651 // Copy the aggregate.
Richard Smithe78fac52018-04-05 20:52:58 +0000652 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.overlapForFieldInit(Field),
653 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000654 // Ensure that we destroy the objects if an exception is thrown later in
655 // the constructor.
656 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
657 if (CGF.needsEHCleanup(dtorKind))
658 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000659 return;
660 }
661 }
662
Richard Smith30e304e2016-12-14 00:03:17 +0000663 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000664}
665
John McCall7f416cc2015-09-08 08:05:57 +0000666void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000667 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000668 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000669 switch (getEvaluationKind(FieldType)) {
670 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000671 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000672 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000673 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000674 RValue RHS = RValue::get(EmitScalarExpr(Init));
675 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000676 }
John McCall47fb9502013-03-07 21:37:08 +0000677 break;
678 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000679 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000680 break;
681 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000682 AggValueSlot Slot =
Richard Smithe78fac52018-04-05 20:52:58 +0000683 AggValueSlot::forLValue(
684 LHS,
685 AggValueSlot::IsDestructed,
686 AggValueSlot::DoesNotNeedGCBarriers,
687 AggValueSlot::IsNotAliased,
688 overlapForFieldInit(Field));
Richard Smith30e304e2016-12-14 00:03:17 +0000689 EmitAggExpr(Init, Slot);
690 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000691 }
John McCall47fb9502013-03-07 21:37:08 +0000692 }
John McCall12cc42a2013-02-01 05:11:40 +0000693
694 // Ensure that we destroy this object if an exception is thrown
695 // later in the constructor.
696 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
697 if (needsEHCleanup(dtorKind))
698 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000699}
700
John McCallf8ff7b92010-02-23 00:48:20 +0000701/// Checks whether the given constructor is a valid subject for the
702/// complete-to-base constructor delegation optimization, i.e.
703/// emitting the complete constructor as a simple call to the base
704/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000705bool CodeGenFunction::IsConstructorDelegationValid(
706 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000707
708 // Currently we disable the optimization for classes with virtual
709 // bases because (1) the addresses of parameter variables need to be
710 // consistent across all initializers but (2) the delegate function
711 // call necessarily creates a second copy of the parameter variable.
712 //
713 // The limiting example (purely theoretical AFAIK):
714 // struct A { A(int &c) { c++; } };
715 // struct B : virtual A {
716 // B(int count) : A(count) { printf("%d\n", count); }
717 // };
718 // ...although even this example could in principle be emitted as a
719 // delegation since the address of the parameter doesn't escape.
720 if (Ctor->getParent()->getNumVBases()) {
721 // TODO: white-list trivial vbase initializers. This case wouldn't
722 // be subject to the restrictions below.
723
724 // TODO: white-list cases where:
725 // - there are no non-reference parameters to the constructor
726 // - the initializers don't access any non-reference parameters
727 // - the initializers don't take the address of non-reference
728 // parameters
729 // - etc.
730 // If we ever add any of the above cases, remember that:
731 // - function-try-blocks will always blacklist this optimization
732 // - we need to perform the constructor prologue and cleanup in
733 // EmitConstructorBody.
734
735 return false;
736 }
737
738 // We also disable the optimization for variadic functions because
739 // it's impossible to "re-pass" varargs.
740 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
741 return false;
742
Alexis Hunt61bc1732011-05-01 07:04:31 +0000743 // FIXME: Decide if we can do a delegation of a delegating constructor.
744 if (Ctor->isDelegatingConstructor())
745 return false;
746
John McCallf8ff7b92010-02-23 00:48:20 +0000747 return true;
748}
749
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000750// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
751// to poison the extra field paddings inserted under
752// -fsanitize-address-field-padding=1|2.
753void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
754 ASTContext &Context = getContext();
755 const CXXRecordDecl *ClassDecl =
756 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
757 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
758 if (!ClassDecl->mayInsertExtraPadding()) return;
759
760 struct SizeAndOffset {
761 uint64_t Size;
762 uint64_t Offset;
763 };
764
765 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
766 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
767
768 // Populate sizes and offsets of fields.
769 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
770 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
771 SSV[i].Offset =
772 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
773
774 size_t NumFields = 0;
775 for (const auto *Field : ClassDecl->fields()) {
776 const FieldDecl *D = Field;
777 std::pair<CharUnits, CharUnits> FieldInfo =
778 Context.getTypeInfoInChars(D->getType());
779 CharUnits FieldSize = FieldInfo.first;
780 assert(NumFields < SSV.size());
781 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
782 NumFields++;
783 }
784 assert(NumFields == SSV.size());
785 if (SSV.size() <= 1) return;
786
787 // We will insert calls to __asan_* run-time functions.
788 // LLVM AddressSanitizer pass may decide to inline them later.
789 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
790 llvm::FunctionType *FTy =
791 llvm::FunctionType::get(CGM.VoidTy, Args, false);
792 llvm::Constant *F = CGM.CreateRuntimeFunction(
793 FTy, Prologue ? "__asan_poison_intra_object_redzone"
794 : "__asan_unpoison_intra_object_redzone");
795
796 llvm::Value *ThisPtr = LoadCXXThis();
797 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000798 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000799 // For each field check if it has sufficient padding,
800 // if so (un)poison it with a call.
801 for (size_t i = 0; i < SSV.size(); i++) {
802 uint64_t AsanAlignment = 8;
803 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
804 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
805 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
806 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
807 (NextField % AsanAlignment) != 0)
808 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000809 Builder.CreateCall(
810 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
811 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000812 }
813}
814
John McCallb81884d2010-02-19 09:25:03 +0000815/// EmitConstructorBody - Emits the body of the current constructor.
816void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000817 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000818 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
819 CXXCtorType CtorType = CurGD.getCtorType();
820
Reid Kleckner340ad862014-01-13 22:57:31 +0000821 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
822 CtorType == Ctor_Complete) &&
823 "can only generate complete ctor for this ABI");
824
John McCallf8ff7b92010-02-23 00:48:20 +0000825 // Before we go any further, try the complete->base constructor
826 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000827 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000828 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000829 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000830 return;
831 }
832
Hans Wennborgdcfba332015-10-06 23:40:43 +0000833 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000834 Stmt *Body = Ctor->getBody(Definition);
835 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000836
John McCallf8ff7b92010-02-23 00:48:20 +0000837 // Enter the function-try-block before the constructor prologue if
838 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000839 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000840 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000841 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000842
Justin Bogner66242d62015-04-23 23:06:47 +0000843 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000844
Richard Smithcc1b96d2013-06-12 22:31:48 +0000845 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000846
John McCall88313032012-03-30 04:25:03 +0000847 // TODO: in restricted cases, we can emit the vbase initializers of
848 // a complete ctor and then delegate to the base ctor.
849
John McCallf8ff7b92010-02-23 00:48:20 +0000850 // Emit the constructor prologue, i.e. the base and member
851 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000852 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000853
854 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000855 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000856 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
857 else if (Body)
858 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000859
860 // Emit any cleanup blocks associated with the member or base
861 // initializers, which includes (along the exceptional path) the
862 // destructors for those members and bases that were fully
863 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000864 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000865
John McCallf8ff7b92010-02-23 00:48:20 +0000866 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000867 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000868}
869
Lang Hamesbf122742013-02-17 07:22:09 +0000870namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000871 /// RAII object to indicate that codegen is copying the value representation
872 /// instead of the object representation. Useful when copying a struct or
873 /// class which has uninitialized members and we're only performing
874 /// lvalue-to-rvalue conversion on the object but not its members.
875 class CopyingValueRepresentation {
876 public:
877 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000878 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000879 CGF.SanOpts.set(SanitizerKind::Bool, false);
880 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000881 }
882 ~CopyingValueRepresentation() {
883 CGF.SanOpts = OldSanOpts;
884 }
885 private:
886 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000887 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000888 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000889} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000890
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000891namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000892 class FieldMemcpyizer {
893 public:
894 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
895 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000896 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000897 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000898 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
899 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000900
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000901 bool isMemcpyableField(FieldDecl *F) const {
902 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000903 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000904 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000905 Qualifiers Qual = F->getType().getQualifiers();
906 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
907 return false;
908 return true;
909 }
910
911 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000912 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000913 addInitialField(F);
914 else
915 addNextField(F);
916 }
917
David Majnemera586eb22014-10-10 18:57:10 +0000918 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Richard Smithe78fac52018-04-05 20:52:58 +0000919 ASTContext &Ctx = CGF.getContext();
Lang Hamesbf122742013-02-17 07:22:09 +0000920 unsigned LastFieldSize =
Richard Smithe78fac52018-04-05 20:52:58 +0000921 LastField->isBitField()
922 ? LastField->getBitWidthValue(Ctx)
923 : Ctx.toBits(
924 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
925 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
926 FirstByteOffset + Ctx.getCharWidth() - 1;
927 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
Lang Hamesbf122742013-02-17 07:22:09 +0000928 return MemcpySize;
929 }
930
931 void emitMemcpy() {
932 // Give the subclass a chance to bail out if it feels the memcpy isn't
933 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000934 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000935 return;
936 }
937
David Majnemera586eb22014-10-10 18:57:10 +0000938 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000939 if (FirstField->isBitField()) {
940 const CGRecordLayout &RL =
941 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
942 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000943 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000944 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000945 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000946 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000947 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000948 }
Lang Hamesbf122742013-02-17 07:22:09 +0000949
David Majnemera586eb22014-10-10 18:57:10 +0000950 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000951 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000952 Address ThisPtr = CGF.LoadCXXThisAddress();
953 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000954 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
955 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
956 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
957 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
958
John McCall7f416cc2015-09-08 08:05:57 +0000959 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
960 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
961 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000962 reset();
963 }
964
965 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000966 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000967 }
968
969 protected:
970 CodeGenFunction &CGF;
971 const CXXRecordDecl *ClassDecl;
972
973 private:
John McCall7f416cc2015-09-08 08:05:57 +0000974 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
975 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000976 llvm::Type *DBP =
977 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
978 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
979
John McCall7f416cc2015-09-08 08:05:57 +0000980 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000981 llvm::Type *SBP =
982 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
983 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
984
John McCall7f416cc2015-09-08 08:05:57 +0000985 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000986 }
987
988 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000989 FirstField = F;
990 LastField = F;
991 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
992 LastFieldOffset = FirstFieldOffset;
993 LastAddedFieldIndex = F->getFieldIndex();
994 }
Lang Hamesbf122742013-02-17 07:22:09 +0000995
996 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000997 // For the most part, the following invariant will hold:
998 // F->getFieldIndex() == LastAddedFieldIndex + 1
999 // The one exception is that Sema won't add a copy-initializer for an
1000 // unnamed bitfield, which will show up here as a gap in the sequence.
1001 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1002 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +00001003 LastAddedFieldIndex = F->getFieldIndex();
1004
1005 // The 'first' and 'last' fields are chosen by offset, rather than field
1006 // index. This allows the code to support bitfields, as well as regular
1007 // fields.
1008 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1009 if (FOffset < FirstFieldOffset) {
1010 FirstField = F;
1011 FirstFieldOffset = FOffset;
1012 } else if (FOffset > LastFieldOffset) {
1013 LastField = F;
1014 LastFieldOffset = FOffset;
1015 }
1016 }
1017
1018 const VarDecl *SrcRec;
1019 const ASTRecordLayout &RecLayout;
1020 FieldDecl *FirstField;
1021 FieldDecl *LastField;
1022 uint64_t FirstFieldOffset, LastFieldOffset;
1023 unsigned LastAddedFieldIndex;
1024 };
1025
1026 class ConstructorMemcpyizer : public FieldMemcpyizer {
1027 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001028 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001029 /// constructor.
1030 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1031 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001032 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001033 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001034 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001035 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001036 }
1037
1038 // Returns true if a CXXCtorInitializer represents a member initialization
1039 // that can be rolled into a memcpy.
1040 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1041 if (!MemcpyableCtor)
1042 return false;
1043 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001044 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001045 QualType FieldType = Field->getType();
1046 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1047
Richard Smith419bd092015-04-29 19:26:57 +00001048 // Bail out on non-memcpyable, not-trivially-copyable members.
1049 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001050 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1051 FieldType->isReferenceType()))
1052 return false;
1053
1054 // Bail out on volatile fields.
1055 if (!isMemcpyableField(Field))
1056 return false;
1057
1058 // Otherwise we're good.
1059 return true;
1060 }
1061
1062 public:
1063 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1064 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001065 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001066 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001067 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001068 CD->isCopyOrMoveConstructor() &&
1069 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1070 Args(Args) { }
1071
1072 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1073 if (isMemberInitMemcpyable(MemberInit)) {
1074 AggregatedInits.push_back(MemberInit);
1075 addMemcpyableField(MemberInit->getMember());
1076 } else {
1077 emitAggregatedInits();
1078 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1079 ConstructorDecl, Args);
1080 }
1081 }
1082
1083 void emitAggregatedInits() {
1084 if (AggregatedInits.size() <= 1) {
1085 // This memcpy is too small to be worthwhile. Fall back on default
1086 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001087 if (!AggregatedInits.empty()) {
1088 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001089 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001090 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001091 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001092 }
1093 reset();
1094 return;
1095 }
1096
1097 pushEHDestructors();
1098 emitMemcpy();
1099 AggregatedInits.clear();
1100 }
1101
1102 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001103 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001104 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001105 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001106
1107 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001108 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1109 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001110 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001111 if (!CGF.needsEHCleanup(dtorKind))
1112 continue;
1113 LValue FieldLHS = LHS;
1114 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1115 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001116 }
1117 }
1118
1119 void finish() {
1120 emitAggregatedInits();
1121 }
1122
1123 private:
1124 const CXXConstructorDecl *ConstructorDecl;
1125 bool MemcpyableCtor;
1126 FunctionArgList &Args;
1127 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1128 };
1129
1130 class AssignmentMemcpyizer : public FieldMemcpyizer {
1131 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001132 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001133 // exists. Otherwise returns null.
1134 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001135 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001136 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001137 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1138 // Recognise trivial assignments.
1139 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001141 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1142 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001143 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001144 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1145 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001146 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001147 Stmt *RHS = BO->getRHS();
1148 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1149 RHS = EC->getSubExpr();
1150 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001151 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001152 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1153 if (ME2->getMemberDecl() == Field)
1154 return Field;
1155 }
1156 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001157 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1158 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001159 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001160 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001161 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1162 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001163 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001164 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1165 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001166 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001167 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1168 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001170 return Field;
1171 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1172 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1173 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001174 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001175 Expr *DstPtr = CE->getArg(0);
1176 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1177 DstPtr = DC->getSubExpr();
1178 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1179 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001180 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001181 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1182 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001183 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001184 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1185 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001186 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001187 Expr *SrcPtr = CE->getArg(1);
1188 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1189 SrcPtr = SC->getSubExpr();
1190 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1191 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001192 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001193 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1194 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001195 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001196 return Field;
1197 }
1198
Craig Topper8a13c412014-05-21 05:09:00 +00001199 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001200 }
1201
1202 bool AssignmentsMemcpyable;
1203 SmallVector<Stmt*, 16> AggregatedStmts;
1204
1205 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001206 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1207 FunctionArgList &Args)
1208 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1209 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1210 assert(Args.size() == 2);
1211 }
1212
1213 void emitAssignment(Stmt *S) {
1214 FieldDecl *F = getMemcpyableField(S);
1215 if (F) {
1216 addMemcpyableField(F);
1217 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001218 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001219 emitAggregatedStmts();
1220 CGF.EmitStmt(S);
1221 }
1222 }
1223
1224 void emitAggregatedStmts() {
1225 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001226 if (!AggregatedStmts.empty()) {
1227 CopyingValueRepresentation CVR(CGF);
1228 CGF.EmitStmt(AggregatedStmts[0]);
1229 }
Lang Hamesbf122742013-02-17 07:22:09 +00001230 reset();
1231 }
1232
1233 emitMemcpy();
1234 AggregatedStmts.clear();
1235 }
1236
1237 void finish() {
1238 emitAggregatedStmts();
1239 }
1240 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001241} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001242
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001243static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1244 const Type *BaseType = BaseInit->getBaseClass();
1245 const auto *BaseClassDecl =
1246 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1247 return BaseClassDecl->isDynamicClass();
1248}
1249
Anders Carlssonfb404882009-12-24 22:46:43 +00001250/// EmitCtorPrologue - This routine generates necessary code to initialize
1251/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001252void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001253 CXXCtorType CtorType,
1254 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001255 if (CD->isDelegatingConstructor())
1256 return EmitDelegatingCXXConstructorCall(CD, Args);
1257
Anders Carlssonfb404882009-12-24 22:46:43 +00001258 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001259
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001260 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1261 E = CD->init_end();
1262
Craig Topper8a13c412014-05-21 05:09:00 +00001263 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001264 if (ClassDecl->getNumVBases() &&
1265 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1266 // The ABIs that don't have constructor variants need to put a branch
1267 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001268 BaseCtorContinueBB =
1269 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001270 assert(BaseCtorContinueBB);
1271 }
1272
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001273 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001274 // Virtual base initializers first.
1275 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001276 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1277 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1278 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001279 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001280 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1281 }
1282
1283 if (BaseCtorContinueBB) {
1284 // Complete object handler should continue to the remaining initializers.
1285 Builder.CreateBr(BaseCtorContinueBB);
1286 EmitBlock(BaseCtorContinueBB);
1287 }
1288
1289 // Then, non-virtual base initializers.
1290 for (; B != E && (*B)->isBaseInitializer(); B++) {
1291 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001292
1293 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1294 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1295 isInitializerOfDynamicClass(*B))
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001296 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001297 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001298 }
1299
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001300 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001301
Anders Carlssond5895932010-03-28 21:07:49 +00001302 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001303
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001304 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001305 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001306 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001307 for (; B != E; B++) {
1308 CXXCtorInitializer *Member = (*B);
1309 assert(!Member->isBaseInitializer());
1310 assert(Member->isAnyMemberInitializer() &&
1311 "Delegating initializer on non-delegating constructor");
1312 CM.addMemberInitializer(Member);
1313 }
Lang Hamesbf122742013-02-17 07:22:09 +00001314 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001315}
1316
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001317static bool
1318FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1319
1320static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001321HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001322 const CXXRecordDecl *BaseClassDecl,
1323 const CXXRecordDecl *MostDerivedClassDecl)
1324{
1325 // If the destructor is trivial we don't have to check anything else.
1326 if (BaseClassDecl->hasTrivialDestructor())
1327 return true;
1328
1329 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1330 return false;
1331
1332 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001333 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001334 if (!FieldHasTrivialDestructorBody(Context, Field))
1335 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001336
1337 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001338 for (const auto &I : BaseClassDecl->bases()) {
1339 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001340 continue;
1341
1342 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001343 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001344 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1345 MostDerivedClassDecl))
1346 return false;
1347 }
1348
1349 if (BaseClassDecl == MostDerivedClassDecl) {
1350 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001351 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001352 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001353 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001354 if (!HasTrivialDestructorBody(Context, VirtualBase,
1355 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001356 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001357 }
1358 }
1359
1360 return true;
1361}
1362
1363static bool
1364FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001365 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001366{
1367 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1368
1369 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1370 if (!RT)
1371 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001372
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001373 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001374
1375 // The destructor for an implicit anonymous union member is never invoked.
1376 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1377 return false;
1378
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001379 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1380}
1381
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001382/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1383/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001384static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001385 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001386 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1387 if (!ClassDecl->isDynamicClass())
1388 return true;
1389
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001390 if (!Dtor->hasTrivialBody())
1391 return false;
1392
1393 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001394 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001395 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001396 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001397
1398 return true;
1399}
1400
John McCallb81884d2010-02-19 09:25:03 +00001401/// EmitDestructorBody - Emits the body of the current destructor.
1402void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1403 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1404 CXXDtorType DtorType = CurGD.getDtorType();
1405
Richard Smithdf054d32017-02-25 23:53:05 +00001406 // For an abstract class, non-base destructors are never used (and can't
1407 // be emitted in general, because vbase dtors may not have been validated
1408 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1409 // in fact emit references to them from other compilations, so emit them
1410 // as functions containing a trap instruction.
1411 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1412 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1413 TrapCall->setDoesNotReturn();
1414 TrapCall->setDoesNotThrow();
1415 Builder.CreateUnreachable();
1416 Builder.ClearInsertionPoint();
1417 return;
1418 }
1419
Justin Bognerfb298222015-05-20 16:16:23 +00001420 Stmt *Body = Dtor->getBody();
1421 if (Body)
1422 incrementProfileCounter(Body);
1423
John McCallf99a6312010-07-21 05:30:47 +00001424 // The call to operator delete in a deleting destructor happens
1425 // outside of the function-try-block, which means it's always
1426 // possible to delegate the destructor body to the complete
1427 // destructor. Do so.
1428 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001429 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001430 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001431 if (HaveInsertPoint())
1432 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1433 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001434 return;
1435 }
1436
John McCallb81884d2010-02-19 09:25:03 +00001437 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001438 // anything else.
1439 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001440 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001441 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001442 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001443
John McCallf99a6312010-07-21 05:30:47 +00001444 // Enter the epilogue cleanups.
1445 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001446
John McCallb81884d2010-02-19 09:25:03 +00001447 // If this is the complete variant, just invoke the base variant;
1448 // the epilogue will destruct the virtual bases. But we can't do
1449 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001450 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001451 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001452 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001453 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001454 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1455
1456 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001457 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1458 "can't emit a dtor without a body for non-Microsoft ABIs");
1459
John McCallf99a6312010-07-21 05:30:47 +00001460 // Enter the cleanup scopes for virtual bases.
1461 EnterDtorCleanups(Dtor, Dtor_Complete);
1462
Reid Klecknere7de47e2013-07-22 13:51:44 +00001463 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001464 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001465 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001466 break;
1467 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001468
John McCallf99a6312010-07-21 05:30:47 +00001469 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001470 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001471
John McCallf99a6312010-07-21 05:30:47 +00001472 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001473 assert(Body);
1474
John McCallf99a6312010-07-21 05:30:47 +00001475 // Enter the cleanup scopes for fields and non-virtual bases.
1476 EnterDtorCleanups(Dtor, Dtor_Base);
1477
1478 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001479 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001480 // Insert the llvm.launder.invariant.group intrinsic before initializing
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001481 // the vptrs to cancel any previous assumptions we might have made.
1482 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1483 CGM.getCodeGenOpts().OptimizationLevel > 0)
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001484 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001485 InitializeVTablePointers(Dtor->getParent());
1486 }
John McCallf99a6312010-07-21 05:30:47 +00001487
1488 if (isTryBody)
1489 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1490 else if (Body)
1491 EmitStmt(Body);
1492 else {
1493 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1494 // nothing to do besides what's in the epilogue
1495 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001496 // -fapple-kext must inline any call to this dtor into
1497 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001498 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001499 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001500
John McCallf99a6312010-07-21 05:30:47 +00001501 break;
John McCallb81884d2010-02-19 09:25:03 +00001502 }
1503
John McCallf99a6312010-07-21 05:30:47 +00001504 // Jump out through the epilogue cleanups.
1505 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001506
1507 // Exit the try if applicable.
1508 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001509 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001510}
1511
Lang Hamesbf122742013-02-17 07:22:09 +00001512void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1513 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1514 const Stmt *RootS = AssignOp->getBody();
1515 assert(isa<CompoundStmt>(RootS) &&
1516 "Body of an implicit assignment operator should be compound stmt.");
1517 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1518
1519 LexicalScope Scope(*this, RootCS->getSourceRange());
1520
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001521 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001522 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001523 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001524 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001525 AM.finish();
1526}
1527
John McCallf99a6312010-07-21 05:30:47 +00001528namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001529 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1530 const CXXDestructorDecl *DD) {
1531 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001532 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001533 return CGF.LoadCXXThis();
1534 }
1535
John McCallf99a6312010-07-21 05:30:47 +00001536 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001537 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001538 CallDtorDelete() {}
1539
Craig Topper4f12f102014-03-12 06:41:41 +00001540 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001541 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1542 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001543 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1544 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001545 CGF.getContext().getTagDeclType(ClassDecl));
1546 }
1547 };
1548
Richard Smith5b349582017-10-13 01:55:36 +00001549 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1550 llvm::Value *ShouldDeleteCondition,
1551 bool ReturnAfterDelete) {
1552 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1553 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1554 llvm::Value *ShouldCallDelete
1555 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1556 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1557
1558 CGF.EmitBlock(callDeleteBB);
1559 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1560 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1561 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1562 LoadThisForDtorDelete(CGF, Dtor),
1563 CGF.getContext().getTagDeclType(ClassDecl));
1564 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1565 ReturnAfterDelete &&
1566 "unexpected value for ReturnAfterDelete");
1567 if (ReturnAfterDelete)
1568 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1569 else
1570 CGF.Builder.CreateBr(continueBB);
1571
1572 CGF.EmitBlock(continueBB);
1573 }
1574
David Blaikie7e70d682015-08-18 22:40:54 +00001575 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001576 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001577
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001578 public:
1579 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001580 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001581 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001582 }
1583
Craig Topper4f12f102014-03-12 06:41:41 +00001584 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001585 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1586 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001587 }
1588 };
1589
David Blaikie7e70d682015-08-18 22:40:54 +00001590 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001591 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001592 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001593 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001594
John McCall4bd0fb12011-07-12 16:41:08 +00001595 public:
1596 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1597 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001598 : field(field), destroyer(destroyer),
1599 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001600
Craig Topper4f12f102014-03-12 06:41:41 +00001601 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001602 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001603 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001604 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1605 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1606 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001607 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001608
John McCall4bd0fb12011-07-12 16:41:08 +00001609 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001610 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001611 }
1612 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001613
Naomi Musgrave703835c2015-09-16 00:38:22 +00001614 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1615 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001616 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001617 // Pass in void pointer and size of region as arguments to runtime
1618 // function
1619 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1620 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1621
1622 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1623
1624 llvm::FunctionType *FnType =
1625 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1626 llvm::Value *Fn =
1627 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1628 CGF.EmitNounwindRuntimeCall(Fn, Args);
1629 }
1630
1631 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001632 const CXXDestructorDecl *Dtor;
1633
1634 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001635 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001636
1637 // Generate function call for handling object poisoning.
1638 // Disables tail call elimination, to prevent the current stack frame
1639 // from disappearing from the stack trace.
1640 void Emit(CodeGenFunction &CGF, Flags flags) override {
1641 const ASTRecordLayout &Layout =
1642 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1643
1644 // Nothing to poison.
1645 if (Layout.getFieldCount() == 0)
1646 return;
1647
1648 // Prevent the current stack frame from disappearing from the stack trace.
1649 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1650
1651 // Construct pointer to region to begin poisoning, and calculate poison
1652 // size, so that only members declared in this class are poisoned.
1653 ASTContext &Context = CGF.getContext();
1654 unsigned fieldIndex = 0;
1655 int startIndex = -1;
1656 // RecordDecl::field_iterator Field;
1657 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1658 // Poison field if it is trivial
1659 if (FieldHasTrivialDestructorBody(Context, Field)) {
1660 // Start sanitizing at this field
1661 if (startIndex < 0)
1662 startIndex = fieldIndex;
1663
1664 // Currently on the last field, and it must be poisoned with the
1665 // current block.
1666 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001667 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001668 }
1669 } else if (startIndex >= 0) {
1670 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001671 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001672 // Re-set the start index
1673 startIndex = -1;
1674 }
1675 fieldIndex += 1;
1676 }
1677 }
1678
1679 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001680 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001681 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001682 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001683 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001684 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001685 unsigned layoutEndOffset) {
1686 ASTContext &Context = CGF.getContext();
1687 const ASTRecordLayout &Layout =
1688 Context.getASTRecordLayout(Dtor->getParent());
1689
1690 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1691 CGF.SizeTy,
1692 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1693 .getQuantity());
1694
1695 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1696 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1697 OffsetSizePtr);
1698
1699 CharUnits::QuantityType PoisonSize;
1700 if (layoutEndOffset >= Layout.getFieldCount()) {
1701 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1702 Context.toCharUnitsFromBits(
1703 Layout.getFieldOffset(layoutStartOffset))
1704 .getQuantity();
1705 } else {
1706 PoisonSize = Context.toCharUnitsFromBits(
1707 Layout.getFieldOffset(layoutEndOffset) -
1708 Layout.getFieldOffset(layoutStartOffset))
1709 .getQuantity();
1710 }
1711
1712 if (PoisonSize == 0)
1713 return;
1714
Naomi Musgrave703835c2015-09-16 00:38:22 +00001715 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001716 }
1717 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001718
1719 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1720 const CXXDestructorDecl *Dtor;
1721
1722 public:
1723 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1724
1725 // Generate function call for handling vtable pointer poisoning.
1726 void Emit(CodeGenFunction &CGF, Flags flags) override {
1727 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001728 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001729 ASTContext &Context = CGF.getContext();
1730 // Poison vtable and vtable ptr if they exist for this class.
1731 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1732
1733 CharUnits::QuantityType PoisonSize =
1734 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1735 // Pass in void pointer and size of region as arguments to runtime
1736 // function
1737 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1738 }
1739 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001740} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001741
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001742/// Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001743/// destructor. This is to call destructors on members and base classes
1744/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001745///
1746/// For a deleting destructor, this also handles the case where a destroying
1747/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001748void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1749 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001750 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1751 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001752
John McCallf99a6312010-07-21 05:30:47 +00001753 // The deleting-destructor phase just needs to call the appropriate
1754 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001755 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001756 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001757 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001758 if (CXXStructorImplicitParamValue) {
1759 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001760 // telling whether this is a deleting destructor.
1761 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1762 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1763 /*ReturnAfterDelete*/true);
1764 else
1765 EHStack.pushCleanup<CallDtorDeleteConditional>(
1766 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001767 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001768 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1769 const CXXRecordDecl *ClassDecl = DD->getParent();
1770 EmitDeleteCall(DD->getOperatorDelete(),
1771 LoadThisForDtorDelete(*this, DD),
1772 getContext().getTagDeclType(ClassDecl));
1773 EmitBranchThroughCleanup(ReturnBlock);
1774 } else {
1775 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1776 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001777 }
John McCall5c60a6f2010-02-18 19:59:28 +00001778 return;
1779 }
1780
John McCallf99a6312010-07-21 05:30:47 +00001781 const CXXRecordDecl *ClassDecl = DD->getParent();
1782
Richard Smith20104042011-09-18 12:11:43 +00001783 // Unions have no bases and do not call field destructors.
1784 if (ClassDecl->isUnion())
1785 return;
1786
John McCallf99a6312010-07-21 05:30:47 +00001787 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001788 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001789 // Poison the vtable pointer such that access after the base
1790 // and member destructors are invoked is invalid.
1791 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1792 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1793 ClassDecl->isPolymorphic())
1794 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001795
1796 // We push them in the forward order so that they'll be popped in
1797 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001798 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001799 CXXRecordDecl *BaseClassDecl
1800 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001801
John McCall5c60a6f2010-02-18 19:59:28 +00001802 // Ignore trivial destructors.
1803 if (BaseClassDecl->hasTrivialDestructor())
1804 continue;
John McCallf99a6312010-07-21 05:30:47 +00001805
John McCallcda666c2010-07-21 07:22:38 +00001806 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1807 BaseClassDecl,
1808 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001809 }
John McCallf99a6312010-07-21 05:30:47 +00001810
John McCall5c60a6f2010-02-18 19:59:28 +00001811 return;
1812 }
1813
1814 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001815 // Poison the vtable pointer if it has no virtual bases, but inherits
1816 // virtual functions.
1817 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1818 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1819 ClassDecl->isPolymorphic())
1820 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001821
John McCallf99a6312010-07-21 05:30:47 +00001822 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001823 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001824 // Ignore virtual bases.
1825 if (Base.isVirtual())
1826 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001827
John McCallf99a6312010-07-21 05:30:47 +00001828 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001829
John McCallf99a6312010-07-21 05:30:47 +00001830 // Ignore trivial destructors.
1831 if (BaseClassDecl->hasTrivialDestructor())
1832 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001833
John McCallcda666c2010-07-21 07:22:38 +00001834 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1835 BaseClassDecl,
1836 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001837 }
1838
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001839 // Poison fields such that access after their destructors are
1840 // invoked, and before the base class destructor runs, is invalid.
1841 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1842 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001843 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001844
John McCallf99a6312010-07-21 05:30:47 +00001845 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001846 for (const auto *Field : ClassDecl->fields()) {
1847 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001848 QualType::DestructionKind dtorKind = type.isDestructedType();
1849 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001850
Richard Smith921bd202012-02-26 09:11:52 +00001851 // Anonymous union members do not have their destructors called.
1852 const RecordType *RT = type->getAsUnionType();
1853 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1854
John McCall4bd0fb12011-07-12 16:41:08 +00001855 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001856 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001857 getDestroyer(dtorKind),
1858 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001859 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001860}
1861
John McCallf677a8e2011-07-13 06:10:41 +00001862/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1863/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001864///
John McCallf677a8e2011-07-13 06:10:41 +00001865/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001866/// \param arrayType the type of the array to initialize
1867/// \param arrayBegin an arrayType*
1868/// \param zeroInitialize true if each element should be
1869/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001870void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001871 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001872 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001873 QualType elementType;
1874 llvm::Value *numElements =
1875 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001876
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001877 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001878}
1879
John McCallf677a8e2011-07-13 06:10:41 +00001880/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1881/// constructor for each of several members of an array.
1882///
1883/// \param ctor the constructor to call for each element
1884/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001885/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001886/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001887/// \param zeroInitialize true if each element should be
1888/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001889void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1890 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001892 const CXXConstructExpr *E,
1893 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001894 // It's legal for numElements to be zero. This can happen both
1895 // dynamically, because x can be zero in 'new A[x]', and statically,
1896 // because of GCC extensions that permit zero-length arrays. There
1897 // are probably legitimate places where we could assume that this
1898 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001899 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001900
1901 // Optimize for a constant count.
1902 llvm::ConstantInt *constantCount
1903 = dyn_cast<llvm::ConstantInt>(numElements);
1904 if (constantCount) {
1905 // Just skip out if the constant count is zero.
1906 if (constantCount->isZero()) return;
1907
1908 // Otherwise, emit the check.
1909 } else {
1910 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1911 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1912 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1913 EmitBlock(loopBB);
1914 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001915
John McCallf677a8e2011-07-13 06:10:41 +00001916 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001917 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001918 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1919 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001920
John McCallf677a8e2011-07-13 06:10:41 +00001921 // Enter the loop, setting up a phi for the current location to initialize.
1922 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1923 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1924 EmitBlock(loopBB);
1925 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1926 "arrayctor.cur");
1927 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001928
Anders Carlsson27da15b2010-01-01 20:29:01 +00001929 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001930
John McCall7f416cc2015-09-08 08:05:57 +00001931 // The alignment of the base, adjusted by the size of a single element,
1932 // provides a conservative estimate of the alignment of every element.
1933 // (This assumes we never start tracking offsetted alignments.)
1934 //
1935 // Note that these are complete objects and so we don't need to
1936 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001937 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001938 CharUnits eltAlignment =
1939 arrayBase.getAlignment()
1940 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1941 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001942
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001943 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001944 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001945 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001946
1947 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001948 // There are two contexts in which temporaries are destroyed at a different
1949 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001950 // default constructor is called to initialize an element of an array.
1951 // If the constructor has one or more default arguments, the destruction of
1952 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001953 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001954
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001955 {
John McCallbd309292010-07-06 01:34:17 +00001956 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001957
John McCallf677a8e2011-07-13 06:10:41 +00001958 // Evaluate the constructor and its arguments in a regular
1959 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001960 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001961 !ctor->getParent()->hasTrivialDestructor()) {
1962 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001963 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1964 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001965 }
1966
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001967 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00001968 /*Delegating=*/false, curAddr, E,
1969 AggValueSlot::DoesNotOverlap);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001970 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971
John McCallf677a8e2011-07-13 06:10:41 +00001972 // Go to the next element.
1973 llvm::Value *next =
1974 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1975 "arrayctor.next");
1976 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001977
John McCallf677a8e2011-07-13 06:10:41 +00001978 // Check whether that's the end of the loop.
1979 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1980 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1981 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001982
John McCall6549b312011-07-13 07:37:11 +00001983 // Patch the earlier check to skip over the loop.
1984 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1985
John McCallf677a8e2011-07-13 06:10:41 +00001986 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001987}
1988
John McCall82fe67b2011-07-09 01:37:26 +00001989void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001990 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001991 QualType type) {
1992 const RecordType *rtype = type->castAs<RecordType>();
1993 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1994 const CXXDestructorDecl *dtor = record->getDestructor();
1995 assert(!dtor->isTrivial());
1996 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001997 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001998}
1999
Alexey Samsonov70b9c012014-08-21 20:26:47 +00002000void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2001 CXXCtorType Type,
2002 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00002003 bool Delegating, Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002004 const CXXConstructExpr *E,
2005 AggValueSlot::Overlap_t Overlap) {
Richard Smith5179eb72016-06-28 19:03:57 +00002006 CallArgList Args;
2007
2008 // Push the this ptr.
2009 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
2010
2011 // If this is a trivial constructor, emit a memcpy now before we lose
2012 // the alignment information on the argument.
2013 // FIXME: It would be better to preserve alignment information into CallArg.
2014 if (isMemcpyEquivalentSpecialMember(D)) {
2015 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2016
2017 const Expr *Arg = E->getArg(0);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002018 LValue Src = EmitLValue(Arg);
Richard Smith5179eb72016-06-28 19:03:57 +00002019 QualType DestTy = getContext().getTypeDeclType(D->getParent());
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002020 LValue Dest = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002021 EmitAggregateCopyCtor(Dest, Src, Overlap);
Richard Smith5179eb72016-06-28 19:03:57 +00002022 return;
2023 }
2024
2025 // Add the rest of the user-supplied arguments.
2026 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002027 EvaluationOrder Order = E->isListInitialization()
2028 ? EvaluationOrder::ForceLeftToRight
2029 : EvaluationOrder::Default;
2030 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2031 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002032
Richard Smithe78fac52018-04-05 20:52:58 +00002033 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2034 Overlap);
Richard Smith5179eb72016-06-28 19:03:57 +00002035}
2036
2037static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2038 const CXXConstructorDecl *Ctor,
2039 CXXCtorType Type, CallArgList &Args) {
2040 // We can't forward a variadic call.
2041 if (Ctor->isVariadic())
2042 return false;
2043
2044 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2045 // If the parameters are callee-cleanup, it's not safe to forward.
2046 for (auto *P : Ctor->parameters())
2047 if (P->getType().isDestructedType())
2048 return false;
2049
2050 // Likewise if they're inalloca.
2051 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002052 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002053 if (Info.usesInAlloca())
2054 return false;
2055 }
2056
2057 // Anything else should be OK.
2058 return true;
2059}
2060
2061void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2062 CXXCtorType Type,
2063 bool ForVirtualBase,
2064 bool Delegating,
2065 Address This,
Richard Smithe78fac52018-04-05 20:52:58 +00002066 CallArgList &Args,
2067 AggValueSlot::Overlap_t Overlap) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002068 const CXXRecordDecl *ClassDecl = D->getParent();
2069
Richard Smith419bd092015-04-29 19:26:57 +00002070 // C++11 [class.mfct.non-static]p2:
2071 // If a non-static member function of a class X is called for an object that
2072 // is not of type X, or of a type derived from X, the behavior is undefined.
2073 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002074 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002075 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002076
Richard Smith419bd092015-04-29 19:26:57 +00002077 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002078 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002079 return;
2080 }
2081
2082 // If this is a trivial constructor, just emit what's needed. If this is a
2083 // union copy constructor, we must emit a memcpy, because the AST does not
2084 // model that copy.
2085 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002086 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002087
Richard Smith5179eb72016-06-28 19:03:57 +00002088 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
Yaxun Liu5b330e82018-03-15 15:25:19 +00002089 Address Src(Args[1].getRValue(*this).getScalarVal(),
2090 getNaturalTypeAlignment(SrcTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002091 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002092 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00002093 LValue DestLVal = MakeAddrLValue(This, DestTy);
Richard Smithe78fac52018-04-05 20:52:58 +00002094 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002095 return;
2096 }
2097
George Burgess IVd0a9e802017-02-23 22:07:35 +00002098 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002099 // Check whether we can actually emit the constructor before trying to do so.
2100 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002101 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2102 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002103 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2104 Delegating, Args);
2105 return;
2106 }
2107 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002108
2109 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002110 CGCXXABI::AddedStructorArgs ExtraArgs =
2111 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2112 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002113
2114 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002115 llvm::Constant *CalleePtr =
2116 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002117 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002118 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002119 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2120 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002121
2122 // Generate vtable assumptions if we're constructing a complete object
2123 // with a vtable. We don't do this for base subobjects for two reasons:
2124 // first, it's incorrect for classes with virtual bases, and second, we're
2125 // about to overwrite the vptrs anyway.
2126 // We also have to make sure if we can refer to vtable:
2127 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2128 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2129 // sure that definition of vtable is not hidden,
2130 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002131 // FIXME: It looks like InstCombine is very inefficient on dealing with
2132 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002133 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2134 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002135 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2136 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002137 EmitVTableAssumptionLoads(ClassDecl, This);
2138}
2139
Richard Smith5179eb72016-06-28 19:03:57 +00002140void CodeGenFunction::EmitInheritedCXXConstructorCall(
2141 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2142 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2143 CallArgList Args;
Yaxun Liu5b330e82018-03-15 15:25:19 +00002144 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()));
Richard Smith5179eb72016-06-28 19:03:57 +00002145
2146 // Forward the parameters.
2147 if (InheritedFromVBase &&
2148 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2149 // Nothing to do; this construction is not responsible for constructing
2150 // the base class containing the inherited constructor.
2151 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2152 // have constructor variants?
2153 Args.push_back(ThisArg);
2154 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2155 // The inheriting constructor was inlined; just inject its arguments.
2156 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2157 "wrong number of parameters for inherited constructor call");
2158 Args = CXXInheritedCtorInitExprArgs;
2159 Args[0] = ThisArg;
2160 } else {
2161 // The inheriting constructor was not inlined. Emit delegating arguments.
2162 Args.push_back(ThisArg);
2163 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2164 assert(OuterCtor->getNumParams() == D->getNumParams());
2165 assert(!OuterCtor->isVariadic() && "should have been inlined");
2166
2167 for (const auto *Param : OuterCtor->parameters()) {
2168 assert(getContext().hasSameUnqualifiedType(
2169 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2170 Param->getType()));
2171 EmitDelegateCallArg(Args, Param, E->getLocation());
2172
2173 // Forward __attribute__(pass_object_size).
2174 if (Param->hasAttr<PassObjectSizeAttr>()) {
2175 auto *POSParam = SizeArguments[Param];
2176 assert(POSParam && "missing pass_object_size value for forwarding");
2177 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2178 }
2179 }
2180 }
2181
2182 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002183 This, Args, AggValueSlot::MayOverlap);
Richard Smith5179eb72016-06-28 19:03:57 +00002184}
2185
2186void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2187 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2188 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002189 GlobalDecl GD(Ctor, CtorType);
2190 InlinedInheritingConstructorScope Scope(*this, GD);
2191 ApplyInlineDebugLocation DebugScope(*this, GD);
Richard Smith5179eb72016-06-28 19:03:57 +00002192
2193 // Save the arguments to be passed to the inherited constructor.
2194 CXXInheritedCtorInitExprArgs = Args;
2195
2196 FunctionArgList Params;
2197 QualType RetType = BuildFunctionArgList(CurGD, Params);
2198 FnRetTy = RetType;
2199
2200 // Insert any ABI-specific implicit constructor arguments.
2201 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2202 ForVirtualBase, Delegating, Args);
2203
2204 // Emit a simplified prolog. We only need to emit the implicit params.
2205 assert(Args.size() >= Params.size() && "too few arguments for call");
2206 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2207 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00002208 const RValue &RV = Args[I].getRValue(*this);
Richard Smith5179eb72016-06-28 19:03:57 +00002209 assert(!RV.isComplex() && "complex indirect params not supported");
2210 ParamValue Val = RV.isScalar()
2211 ? ParamValue::forDirect(RV.getScalarVal())
2212 : ParamValue::forIndirect(RV.getAggregateAddress());
2213 EmitParmDecl(*Params[I], Val, I + 1);
2214 }
2215 }
2216
2217 // Create a return value slot if the ABI implementation wants one.
2218 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2219 // value instead.
2220 if (!RetType->isVoidType())
2221 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2222
2223 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2224 CXXThisValue = CXXABIThisValue;
2225
2226 // Directly emit the constructor initializers.
2227 EmitCtorPrologue(Ctor, CtorType, Params);
2228}
2229
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002230void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2231 llvm::Value *VTableGlobal =
2232 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2233 if (!VTableGlobal)
2234 return;
2235
2236 // We can just use the base offset in the complete class.
2237 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2238
2239 if (!NonVirtualOffset.isZero())
2240 This =
2241 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2242 Vptr.VTableClass, Vptr.NearestVBase);
2243
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002244 llvm::Value *VPtrValue =
2245 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002246 llvm::Value *Cmp =
2247 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2248 Builder.CreateAssumption(Cmp);
2249}
2250
2251void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2252 Address This) {
2253 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2254 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2255 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002256}
2257
John McCallf8ff7b92010-02-23 00:48:20 +00002258void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002259CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002260 Address This, Address Src,
2261 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002262 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002263
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002264 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002265
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002266 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002267 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002268
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002269 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002270 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002271 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002272 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002273 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002274
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002275 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002276 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002277 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002278
Richard Smithe78fac52018-04-05 20:52:58 +00002279 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args,
2280 AggValueSlot::MayOverlap);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002281}
2282
2283void
John McCallf8ff7b92010-02-23 00:48:20 +00002284CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2285 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002286 const FunctionArgList &Args,
2287 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002288 CallArgList DelegateArgs;
2289
2290 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2291 assert(I != E && "no parameters to constructor");
2292
2293 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002294 Address This = LoadCXXThisAddress();
2295 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002296 ++I;
2297
Richard Smith5179eb72016-06-28 19:03:57 +00002298 // FIXME: The location of the VTT parameter in the parameter list is
2299 // specific to the Itanium ABI and shouldn't be hardcoded here.
2300 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2301 assert(I != E && "cannot skip vtt parameter, already done with args");
2302 assert((*I)->getType()->isPointerType() &&
2303 "skipping parameter not of vtt type");
2304 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002305 }
2306
2307 // Explicit arguments.
2308 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002309 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002310 // FIXME: per-argument source location
2311 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002312 }
2313
Richard Smith5179eb72016-06-28 19:03:57 +00002314 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
Richard Smithe78fac52018-04-05 20:52:58 +00002315 /*Delegating=*/true, This, DelegateArgs,
2316 AggValueSlot::MayOverlap);
John McCallf8ff7b92010-02-23 00:48:20 +00002317}
2318
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002319namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002320 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002321 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002322 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002323 CXXDtorType Type;
2324
John McCall7f416cc2015-09-08 08:05:57 +00002325 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002326 CXXDtorType Type)
2327 : Dtor(D), Addr(Addr), Type(Type) {}
2328
Craig Topper4f12f102014-03-12 06:41:41 +00002329 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002330 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002331 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002332 }
2333 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002334} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002335
Alexis Hunt61bc1732011-05-01 07:04:31 +00002336void
2337CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2338 const FunctionArgList &Args) {
2339 assert(Ctor->isDelegatingConstructor());
2340
John McCall7f416cc2015-09-08 08:05:57 +00002341 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002342
John McCall31168b02011-06-15 23:02:42 +00002343 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002344 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002345 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002346 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00002347 AggValueSlot::IsNotAliased,
2348 AggValueSlot::MayOverlap);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002349
2350 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002351
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002352 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002353 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002354 CXXDtorType Type =
2355 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2356
2357 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2358 ClassDecl->getDestructor(),
2359 ThisPtr, Type);
2360 }
2361}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002362
Anders Carlsson27da15b2010-01-01 20:29:01 +00002363void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2364 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002365 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002366 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002367 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002368 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2369 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002370}
2371
John McCall53cad2e2010-07-21 01:41:18 +00002372namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002373 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002374 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002375 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002376
John McCall7f416cc2015-09-08 08:05:57 +00002377 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002378 : Dtor(D), Addr(Addr) {}
2379
Craig Topper4f12f102014-03-12 06:41:41 +00002380 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002381 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002382 /*ForVirtualBase=*/false,
2383 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002384 }
2385 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002386} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002387
John McCall8680f872010-07-21 06:29:51 +00002388void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002389 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002390 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002391}
2392
John McCall7f416cc2015-09-08 08:05:57 +00002393void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002394 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2395 if (!ClassDecl) return;
2396 if (ClassDecl->hasTrivialDestructor()) return;
2397
2398 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002399 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002400 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002401}
2402
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002403void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002404 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002405 llvm::Value *VTableAddressPoint =
2406 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002407 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2408
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002409 if (!VTableAddressPoint)
2410 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002411
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002412 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002413 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002414 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002415
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002416 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002417 // We need to use the virtual base offset offset because the virtual base
2418 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002419
2420 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2421 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2422 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002423 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002424 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002425 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002426 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002427
Anders Carlssonc58fb552010-05-03 00:29:58 +00002428 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002429 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002430
Ken Dyckcfc332c2011-03-23 00:45:26 +00002431 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002432 VTableField = ApplyNonVirtualAndVirtualOffset(
2433 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2434 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002435
Reid Kleckner8d585132014-12-03 21:00:21 +00002436 // Finally, store the address point. Use the same LLVM types as the field to
2437 // support optimization.
2438 llvm::Type *VTablePtrTy =
2439 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2440 ->getPointerTo()
2441 ->getPointerTo();
2442 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2443 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002444
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002445 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002446 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2447 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002448 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2449 CGM.getCodeGenOpts().StrictVTablePointers)
2450 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002451}
2452
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002453CodeGenFunction::VPtrsVector
2454CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2455 CodeGenFunction::VPtrsVector VPtrsResult;
2456 VisitedVirtualBasesSetTy VBases;
2457 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2458 /*NearestVBase=*/nullptr,
2459 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2460 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2461 VPtrsResult);
2462 return VPtrsResult;
2463}
2464
2465void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2466 const CXXRecordDecl *NearestVBase,
2467 CharUnits OffsetFromNearestVBase,
2468 bool BaseIsNonVirtualPrimaryBase,
2469 const CXXRecordDecl *VTableClass,
2470 VisitedVirtualBasesSetTy &VBases,
2471 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002472 // If this base is a non-virtual primary base the address point has already
2473 // been set.
2474 if (!BaseIsNonVirtualPrimaryBase) {
2475 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002476 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2477 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002478 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002479
Anders Carlssond5895932010-03-28 21:07:49 +00002480 const CXXRecordDecl *RD = Base.getBase();
2481
2482 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002483 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002484 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002485 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002486
2487 // Ignore classes without a vtable.
2488 if (!BaseDecl->isDynamicClass())
2489 continue;
2490
Ken Dyck3fb4c892011-03-23 01:04:18 +00002491 CharUnits BaseOffset;
2492 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002493 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002494
Aaron Ballman574705e2014-03-13 15:41:46 +00002495 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002496 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002497 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002498 continue;
2499
Justin Bogner1cd11f12015-05-20 15:53:59 +00002500 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002501 getContext().getASTRecordLayout(VTableClass);
2502
Ken Dyck3fb4c892011-03-23 01:04:18 +00002503 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2504 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002505 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002506 } else {
2507 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2508
Ken Dyck16ffcac2011-03-24 01:21:01 +00002509 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002510 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002511 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002512 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002513 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002514
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002515 getVTablePointers(
2516 BaseSubobject(BaseDecl, BaseOffset),
2517 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2518 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002519 }
2520}
2521
2522void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2523 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002524 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002525 return;
2526
Anders Carlssond5895932010-03-28 21:07:49 +00002527 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002528 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2529 for (const VPtr &Vptr : getVTablePointers(RD))
2530 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002531
2532 if (RD->getNumVBases())
2533 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002534}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002535
John McCall7f416cc2015-09-08 08:05:57 +00002536llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002537 llvm::Type *VTableTy,
2538 const CXXRecordDecl *RD) {
2539 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002540 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +00002541 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2542 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002543
2544 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2545 CGM.getCodeGenOpts().StrictVTablePointers)
2546 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2547
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002548 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002549}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002550
Peter Collingbourned2926c92015-03-14 02:42:25 +00002551// If a class has a single non-virtual base and does not introduce or override
2552// virtual member functions or fields, it will have the same layout as its base.
2553// This function returns the least derived such class.
2554//
2555// Casting an instance of a base class to such a derived class is technically
2556// undefined behavior, but it is a relatively common hack for introducing member
2557// functions on class instances with specific properties (e.g. llvm::Operator)
2558// that works under most compilers and should not have security implications, so
2559// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2560static const CXXRecordDecl *
2561LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2562 if (!RD->field_empty())
2563 return RD;
2564
2565 if (RD->getNumVBases() != 0)
2566 return RD;
2567
2568 if (RD->getNumBases() != 1)
2569 return RD;
2570
2571 for (const CXXMethodDecl *MD : RD->methods()) {
2572 if (MD->isVirtual()) {
2573 // Virtual member functions are only ok if they are implicit destructors
2574 // because the implicit destructor will have the same semantics as the
2575 // base class's destructor if no fields are added.
2576 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2577 continue;
2578 return RD;
2579 }
2580 }
2581
2582 return LeastDerivedClassWithSameLayout(
2583 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2584}
2585
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002586void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2587 llvm::Value *VTable,
2588 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002589 if (SanOpts.has(SanitizerKind::CFIVCall))
2590 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2591 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2592 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002593 llvm::Metadata *MD =
2594 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002595 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002596 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2597
2598 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002599 llvm::Value *TypeTest =
2600 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2601 {CastedVTable, TypeId});
2602 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002603 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002604}
2605
2606void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002607 llvm::Value *VTable,
2608 CFITypeCheckKind TCK,
2609 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002610 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002611 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002612
Peter Collingbournefb532b92016-02-24 20:46:36 +00002613 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002614}
2615
Peter Collingbourned2926c92015-03-14 02:42:25 +00002616void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2617 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002618 bool MayBeNull,
2619 CFITypeCheckKind TCK,
2620 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002621 if (!getLangOpts().CPlusPlus)
2622 return;
2623
2624 auto *ClassTy = T->getAs<RecordType>();
2625 if (!ClassTy)
2626 return;
2627
2628 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2629
2630 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2631 return;
2632
Peter Collingbourned2926c92015-03-14 02:42:25 +00002633 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2634 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2635
Hans Wennborgdcfba332015-10-06 23:40:43 +00002636 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002637
2638 if (MayBeNull) {
2639 llvm::Value *DerivedNotNull =
2640 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2641
2642 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2643 ContBlock = createBasicBlock("cast.cont");
2644
2645 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2646
2647 EmitBlock(CheckBlock);
2648 }
2649
Peter Collingbourne60108802017-12-13 21:53:04 +00002650 llvm::Value *VTable;
2651 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2652 *this, Address(Derived, getPointerAlign()), ClassDecl);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002653
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002654 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002655
2656 if (MayBeNull) {
2657 Builder.CreateBr(ContBlock);
2658 EmitBlock(ContBlock);
2659 }
2660}
2661
2662void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002663 llvm::Value *VTable,
2664 CFITypeCheckKind TCK,
2665 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002666 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2667 !CGM.HasHiddenLTOVisibility(RD))
2668 return;
2669
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002670 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002671 llvm::SanitizerStatKind SSK;
2672 switch (TCK) {
2673 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002674 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002675 SSK = llvm::SanStat_CFI_VCall;
2676 break;
2677 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002678 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002679 SSK = llvm::SanStat_CFI_NVCall;
2680 break;
2681 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002682 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002683 SSK = llvm::SanStat_CFI_DerivedCast;
2684 break;
2685 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002686 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002687 SSK = llvm::SanStat_CFI_UnrelatedCast;
2688 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002689 case CFITCK_ICall:
2690 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002691 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002692
2693 std::string TypeName = RD->getQualifiedNameAsString();
2694 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2695 return;
2696
2697 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002698 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002699
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002700 llvm::Metadata *MD =
2701 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002702 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002703
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002704 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002705 llvm::Value *TypeTest = Builder.CreateCall(
2706 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002707
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002708 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002709 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002710 EmitCheckSourceLocation(Loc),
2711 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002712 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002713
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002714 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2715 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2716 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002717 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002718 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002719
2720 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002721 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002722 return;
2723 }
2724
2725 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2726 CGM.getLLVMContext(),
2727 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002728 llvm::Value *ValidVtable = Builder.CreateCall(
2729 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002730 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2731 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002732}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002733
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002734bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2735 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2736 !SanOpts.has(SanitizerKind::CFIVCall) ||
2737 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2738 !CGM.HasHiddenLTOVisibility(RD))
2739 return false;
2740
2741 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002742 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2743 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002744}
2745
2746llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2747 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2748 SanitizerScope SanScope(this);
2749
2750 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2751
2752 llvm::Metadata *MD =
2753 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2754 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2755
2756 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2757 llvm::Value *CheckedLoad = Builder.CreateCall(
2758 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2759 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2760 TypeId});
2761 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2762
2763 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002764 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002765
2766 return Builder.CreateBitCast(
2767 Builder.CreateExtractValue(CheckedLoad, 0),
2768 cast<llvm::PointerType>(VTable->getType())->getElementType());
2769}
2770
Faisal Vali571df122013-09-29 08:45:24 +00002771void CodeGenFunction::EmitForwardingCallToLambda(
2772 const CXXMethodDecl *callOperator,
2773 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002774 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002775 const CGFunctionInfo &calleeFnInfo =
2776 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002777 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002778 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2779 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002780
John McCall8dda7b22012-07-07 06:41:13 +00002781 // Prepare the return slot.
2782 const FunctionProtoType *FPT =
2783 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002784 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002785 ReturnValueSlot returnSlot;
2786 if (!resultType->isVoidType() &&
2787 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002788 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002789 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2790
2791 // We don't need to separately arrange the call arguments because
2792 // the call can't be variadic anyway --- it's impossible to forward
2793 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002794
Eli Friedman5b446882012-02-16 03:47:28 +00002795 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002796 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2797 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002798
John McCall8dda7b22012-07-07 06:41:13 +00002799 // If necessary, copy the returned value into the slot.
John McCall95088452017-12-14 18:21:14 +00002800 if (!resultType->isVoidType() && returnSlot.isNull()) {
2801 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2802 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2803 }
John McCall8dda7b22012-07-07 06:41:13 +00002804 EmitReturnOfRValue(RV, resultType);
John McCall95088452017-12-14 18:21:14 +00002805 } else
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002806 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002807}
2808
Eli Friedman2495ab02012-02-25 02:48:22 +00002809void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2810 const BlockDecl *BD = BlockInfo->getBlockDecl();
2811 const VarDecl *variable = BD->capture_begin()->getVariable();
2812 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002813 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2814
2815 if (CallOp->isVariadic()) {
2816 // FIXME: Making this work correctly is nasty because it requires either
2817 // cloning the body of the call operator or making the call operator
2818 // forward.
2819 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2820 return;
2821 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002822
2823 // Start building arguments for forwarding call
2824 CallArgList CallArgs;
2825
2826 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002827 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2828 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002829
2830 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002831 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002832 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002833
Justin Bogner1cd11f12015-05-20 15:53:59 +00002834 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002835 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002836 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002837}
2838
2839void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2840 const CXXRecordDecl *Lambda = MD->getParent();
2841
2842 // Start building arguments for forwarding call
2843 CallArgList CallArgs;
2844
2845 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2846 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2847 CallArgs.add(RValue::get(ThisPtr), ThisType);
2848
2849 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002850 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002851 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2852
Faisal Vali571df122013-09-29 08:45:24 +00002853 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2854 // For a generic lambda, find the corresponding call operator specialization
2855 // to which the call to the static-invoker shall be forwarded.
2856 if (Lambda->isGenericLambda()) {
2857 assert(MD->isFunctionTemplateSpecialization());
2858 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2859 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002860 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002861 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002862 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002863 assert(CorrespondingCallOpSpecialization);
2864 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2865 }
2866 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002867}
2868
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002869void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002870 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002871 // FIXME: Making this work correctly is nasty because it requires either
2872 // cloning the body of the call operator or making the call operator forward.
2873 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002874 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002875 }
2876
Douglas Gregor355efbb2012-02-17 03:02:34 +00002877 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002878}