blob: 3b8209f06406488175b3959d9bf44aa297c35097 [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,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000132 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000133 // Ask the ABI to compute the actual address.
134 llvm::Value *ptr =
135 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
136 memberPtr, memberPtrType);
137
138 QualType memberType = memberPtrType->getPointeeType();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000139 CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000140 memberAlign =
141 CGM.getDynamicOffsetAlignment(base.getAlignment(),
142 memberPtrType->getClass()->getAsCXXRecordDecl(),
143 memberAlign);
144 return Address(ptr, memberAlign);
145}
146
David Majnemerc1709d32015-06-23 07:31:11 +0000147CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
148 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
149 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +0000150 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000151
David Majnemerc1709d32015-06-23 07:31:11 +0000152 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +0000153 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +0000154
John McCallcf142162010-08-07 06:22:56 +0000155 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +0000156 const CXXBaseSpecifier *Base = *I;
157 assert(!Base->isVirtual() && "Should not see virtual bases here!");
158
159 // Get the layout.
160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000161
162 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +0000163 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000164
Anders Carlssond829a022010-04-24 21:06:20 +0000165 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000166 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000167
Anders Carlssond829a022010-04-24 21:06:20 +0000168 RD = BaseDecl;
169 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000170
Ken Dycka1a4ae32011-03-22 00:53:26 +0000171 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +0000172}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000173
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000174llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000175CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +0000176 CastExpr::path_const_iterator PathBegin,
177 CastExpr::path_const_iterator PathEnd) {
178 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000179
Justin Bogner1cd11f12015-05-20 15:53:59 +0000180 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +0000181 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +0000182 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +0000183 return nullptr;
184
Justin Bogner1cd11f12015-05-20 15:53:59 +0000185 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000186 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000187
Ken Dycka1a4ae32011-03-22 00:53:26 +0000188 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +0000189}
190
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000191/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +0000192/// This should only be used for (1) non-virtual bases or (2) virtual bases
193/// when the type is known to be complete (e.g. in complete destructors).
194///
195/// The object pointed to by 'This' is assumed to be non-null.
John McCall7f416cc2015-09-08 08:05:57 +0000196Address
197CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000198 const CXXRecordDecl *Derived,
199 const CXXRecordDecl *Base,
200 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +0000201 // 'this' must be a pointer (in some address space) to Derived.
John McCall7f416cc2015-09-08 08:05:57 +0000202 assert(This.getElementType() == ConvertType(Derived));
John McCall6ce74722010-02-16 04:15:37 +0000203
204 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +0000205 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +0000206 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000207 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +0000208 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000209 else
Ken Dyck6aa767c2011-03-22 01:21:15 +0000210 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000211
212 // Shift and cast down to the base type.
213 // TODO: for complete types, this should be possible with a GEP.
John McCall7f416cc2015-09-08 08:05:57 +0000214 Address V = This;
215 if (!Offset.isZero()) {
216 V = Builder.CreateElementBitCast(V, Int8Ty);
217 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
John McCall6ce74722010-02-16 04:15:37 +0000218 }
John McCall7f416cc2015-09-08 08:05:57 +0000219 V = Builder.CreateElementBitCast(V, ConvertType(Base));
John McCall6ce74722010-02-16 04:15:37 +0000220
221 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000222}
John McCall6ce74722010-02-16 04:15:37 +0000223
John McCall7f416cc2015-09-08 08:05:57 +0000224static Address
225ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
John McCall13a39c62012-08-01 05:04:58 +0000226 CharUnits nonVirtualOffset,
John McCall7f416cc2015-09-08 08:05:57 +0000227 llvm::Value *virtualOffset,
228 const CXXRecordDecl *derivedClass,
229 const CXXRecordDecl *nearestVBase) {
John McCall13a39c62012-08-01 05:04:58 +0000230 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000231 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000232
233 // Compute the offset from the static and dynamic components.
234 llvm::Value *baseOffset;
235 if (!nonVirtualOffset.isZero()) {
236 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
237 nonVirtualOffset.getQuantity());
238 if (virtualOffset) {
239 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
240 }
241 } else {
242 baseOffset = virtualOffset;
243 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000244
Anders Carlsson53cebd12010-04-20 16:03:35 +0000245 // Apply the base offset.
John McCall7f416cc2015-09-08 08:05:57 +0000246 llvm::Value *ptr = addr.getPointer();
John McCall13a39c62012-08-01 05:04:58 +0000247 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
248 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
John McCall7f416cc2015-09-08 08:05:57 +0000249
250 // If we have a virtual component, the alignment of the result will
251 // be relative only to the known alignment of that vbase.
252 CharUnits alignment;
253 if (virtualOffset) {
254 assert(nearestVBase && "virtual offset without vbase?");
255 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
256 derivedClass, nearestVBase);
257 } else {
258 alignment = addr.getAlignment();
259 }
260 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
261
262 return Address(ptr, alignment);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000263}
264
John McCall7f416cc2015-09-08 08:05:57 +0000265Address CodeGenFunction::GetAddressOfBaseClass(
266 Address Value, const CXXRecordDecl *Derived,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000267 CastExpr::path_const_iterator PathBegin,
268 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
269 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000270 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000271
John McCallcf142162010-08-07 06:22:56 +0000272 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000273 const CXXRecordDecl *VBase = nullptr;
274
John McCall13a39c62012-08-01 05:04:58 +0000275 // Sema has done some convenient canonicalization here: if the
276 // access path involved any virtual steps, the conversion path will
277 // *start* with a step down to the correct virtual base subobject,
278 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000279 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000280 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000281 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
282 ++Start;
283 }
John McCall13a39c62012-08-01 05:04:58 +0000284
285 // Compute the static offset of the ultimate destination within its
286 // allocating subobject (the virtual base, if there is one, or else
287 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000288 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
289 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000290
John McCall13a39c62012-08-01 05:04:58 +0000291 // If there's a virtual step, we can sometimes "devirtualize" it.
292 // For now, that's limited to when the derived type is final.
293 // TODO: "devirtualize" this for accesses to known-complete objects.
294 if (VBase && Derived->hasAttr<FinalAttr>()) {
295 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
296 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
297 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000298 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000299 }
300
Anders Carlssond829a022010-04-24 21:06:20 +0000301 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000302 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000303 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000304
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000305 QualType DerivedTy = getContext().getRecordType(Derived);
John McCall7f416cc2015-09-08 08:05:57 +0000306 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000307
John McCall13a39c62012-08-01 05:04:58 +0000308 // If the static offset is zero and we don't have a virtual step,
309 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000310 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000311 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000312 SanitizerSet SkippedChecks;
313 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
John McCall7f416cc2015-09-08 08:05:57 +0000314 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
Vedant Kumar18348ea2017-02-17 23:22:55 +0000315 DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000316 }
Anders Carlssond829a022010-04-24 21:06:20 +0000317 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000318 }
John McCall13a39c62012-08-01 05:04:58 +0000319
Craig Topper8a13c412014-05-21 05:09:00 +0000320 llvm::BasicBlock *origBB = nullptr;
321 llvm::BasicBlock *endBB = nullptr;
322
John McCall13a39c62012-08-01 05:04:58 +0000323 // Skip over the offset (and the vtable load) if we're supposed to
324 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000325 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000326 origBB = Builder.GetInsertBlock();
327 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
328 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000329
John McCall7f416cc2015-09-08 08:05:57 +0000330 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
John McCall13a39c62012-08-01 05:04:58 +0000331 Builder.CreateCondBr(isNull, endBB, notNullBB);
332 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000333 }
334
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000335 if (sanitizePerformTypeCheck()) {
Vedant Kumar18348ea2017-02-17 23:22:55 +0000336 SanitizerSet SkippedChecks;
337 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000338 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000339 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000340 }
341
John McCall13a39c62012-08-01 05:04:58 +0000342 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000343 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000344 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000345 VirtualOffset =
346 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000347 }
Anders Carlssond829a022010-04-24 21:06:20 +0000348
John McCall13a39c62012-08-01 05:04:58 +0000349 // Apply both offsets.
John McCall7f416cc2015-09-08 08:05:57 +0000350 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
351 VirtualOffset, Derived, VBase);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000352
John McCall13a39c62012-08-01 05:04:58 +0000353 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000354 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000355
356 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000357 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000358 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
359 Builder.CreateBr(endBB);
360 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000361
John McCall13a39c62012-08-01 05:04:58 +0000362 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
John McCall7f416cc2015-09-08 08:05:57 +0000363 PHI->addIncoming(Value.getPointer(), notNullBB);
John McCall13a39c62012-08-01 05:04:58 +0000364 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
John McCall7f416cc2015-09-08 08:05:57 +0000365 Value = Address(PHI, Value.getAlignment());
Anders Carlssond829a022010-04-24 21:06:20 +0000366 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000367
Anders Carlssond829a022010-04-24 21:06:20 +0000368 return Value;
369}
370
John McCall7f416cc2015-09-08 08:05:57 +0000371Address
372CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000373 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000374 CastExpr::path_const_iterator PathBegin,
375 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000376 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000377 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000378
Anders Carlsson8c793172009-11-23 17:57:54 +0000379 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000380 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000381 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000382
Anders Carlsson600f7372010-01-31 01:43:37 +0000383 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000384 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000385
Anders Carlsson600f7372010-01-31 01:43:37 +0000386 if (!NonVirtualOffset) {
387 // No offset, we can just cast back.
John McCall7f416cc2015-09-08 08:05:57 +0000388 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
Anders Carlsson600f7372010-01-31 01:43:37 +0000389 }
Craig Topper8a13c412014-05-21 05:09:00 +0000390
391 llvm::BasicBlock *CastNull = nullptr;
392 llvm::BasicBlock *CastNotNull = nullptr;
393 llvm::BasicBlock *CastEnd = nullptr;
394
Anders Carlsson8c793172009-11-23 17:57:54 +0000395 if (NullCheckValue) {
396 CastNull = createBasicBlock("cast.null");
397 CastNotNull = createBasicBlock("cast.notnull");
398 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000399
John McCall7f416cc2015-09-08 08:05:57 +0000400 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
Anders Carlsson8c793172009-11-23 17:57:54 +0000401 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
402 EmitBlock(CastNotNull);
403 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000404
Anders Carlsson600f7372010-01-31 01:43:37 +0000405 // Apply the offset.
John McCall7f416cc2015-09-08 08:05:57 +0000406 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
Eli Friedman87549262012-02-28 22:07:56 +0000407 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
408 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000409
410 // Just cast.
411 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000412
John McCall7f416cc2015-09-08 08:05:57 +0000413 // Produce a PHI if we had a null-check.
Anders Carlsson8c793172009-11-23 17:57:54 +0000414 if (NullCheckValue) {
415 Builder.CreateBr(CastEnd);
416 EmitBlock(CastNull);
417 Builder.CreateBr(CastEnd);
418 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000419
Jay Foad20c0f022011-03-30 11:28:58 +0000420 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000421 PHI->addIncoming(Value, CastNotNull);
John McCall7f416cc2015-09-08 08:05:57 +0000422 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
Anders Carlsson8c793172009-11-23 17:57:54 +0000423 Value = PHI;
424 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000425
John McCall7f416cc2015-09-08 08:05:57 +0000426 return Address(Value, CGM.getClassPointerAlignment(Derived));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000427}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000428
429llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
430 bool ForVirtualBase,
431 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000432 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000433 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000434 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000435 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000436
John McCalldec348f72013-05-03 07:33:41 +0000437 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000438 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000439
Anders Carlssone36a6b32010-01-02 01:01:18 +0000440 llvm::Value *VTT;
441
John McCall5c60a6f2010-02-18 19:59:28 +0000442 uint64_t SubVTTIndex;
443
Douglas Gregor61535002013-01-31 05:50:40 +0000444 if (Delegating) {
445 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000446 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000447 } else if (RD == Base) {
448 // If the record matches the base, this is the complete ctor/dtor
449 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000450 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000451 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000452 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000453 SubVTTIndex = 0;
454 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000455 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000456 CharUnits BaseOffset = ForVirtualBase ?
457 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000458 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000459
Justin Bogner1cd11f12015-05-20 15:53:59 +0000460 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000461 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000462 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
463 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000464
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000465 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000466 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000467 VTT = LoadCXXVTT();
468 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000469 } else {
470 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000471 VTT = CGM.getVTables().GetAddrOfVTT(RD);
472 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000473 }
474
475 return VTT;
476}
477
John McCall1d987562010-07-21 01:23:41 +0000478namespace {
John McCallf99a6312010-07-21 05:30:47 +0000479 /// Call the destructor for a direct base class.
David Blaikie7e70d682015-08-18 22:40:54 +0000480 struct CallBaseDtor final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000481 const CXXRecordDecl *BaseClass;
482 bool BaseIsVirtual;
483 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
484 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000485
Craig Topper4f12f102014-03-12 06:41:41 +0000486 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000487 const CXXRecordDecl *DerivedClass =
488 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
489
490 const CXXDestructorDecl *D = BaseClass->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +0000491 Address Addr =
492 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
John McCallf99a6312010-07-21 05:30:47 +0000493 DerivedClass, BaseClass,
494 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000495 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
496 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000497 }
498 };
John McCall769250e2010-09-17 02:31:44 +0000499
500 /// A visitor which checks whether an initializer uses 'this' in a
501 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000502 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
503 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000504
505 bool UsesThis;
506
Scott Douglass503fc392015-06-10 13:53:15 +0000507 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000508
509 // Black-list all explicit and implicit references to 'this'.
510 //
511 // Do we need to worry about external references to 'this' derived
512 // from arbitrary code? If so, then anything which runs arbitrary
513 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000514 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000515 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000516} // end anonymous namespace
John McCall769250e2010-09-17 02:31:44 +0000517
518static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
519 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000520 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000521 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000522}
523
Justin Bogner1cd11f12015-05-20 15:53:59 +0000524static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000525 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000526 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000527 CXXCtorType CtorType) {
528 assert(BaseInit->isBaseInitializer() &&
529 "Must have base initializer!");
530
John McCall7f416cc2015-09-08 08:05:57 +0000531 Address ThisPtr = CGF.LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000532
Anders Carlssonfb404882009-12-24 22:46:43 +0000533 const Type *BaseType = BaseInit->getBaseClass();
534 CXXRecordDecl *BaseClassDecl =
535 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
536
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000537 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000538
539 // The base constructor doesn't construct virtual bases.
540 if (CtorType == Ctor_Base && isBaseVirtual)
541 return;
542
John McCall769250e2010-09-17 02:31:44 +0000543 // If the initializer for the base (other than the constructor
544 // itself) accesses 'this' in any way, we need to initialize the
545 // vtables.
546 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
547 CGF.InitializeVTablePointers(ClassDecl);
548
John McCall6ce74722010-02-16 04:15:37 +0000549 // We can pretend to be a complete class because it only matters for
550 // virtual bases, and we only do virtual bases for complete ctors.
John McCall7f416cc2015-09-08 08:05:57 +0000551 Address V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000552 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000553 BaseClassDecl,
554 isBaseVirtual);
John McCall8d6fc952011-08-25 20:40:09 +0000555 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000556 AggValueSlot::forAddr(V, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000557 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000558 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000559 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000560
561 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000562
563 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000564 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000565 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
566 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000567}
568
Richard Smith419bd092015-04-29 19:26:57 +0000569static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
570 auto *CD = dyn_cast<CXXConstructorDecl>(D);
571 if (!(CD && CD->isCopyOrMoveConstructor()) &&
572 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
573 return false;
574
575 // We can emit a memcpy for a trivial copy or move constructor/assignment.
576 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
577 return true;
578
579 // We *must* emit a memcpy for a defaulted union copy or move op.
580 if (D->getParent()->isUnion() && D->isDefaulted())
581 return true;
582
583 return false;
584}
585
Alexey Bataev152c71f2015-07-14 07:55:48 +0000586static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
587 CXXCtorInitializer *MemberInit,
588 LValue &LHS) {
589 FieldDecl *Field = MemberInit->getAnyMember();
590 if (MemberInit->isIndirectMemberInitializer()) {
591 // If we are initializing an anonymous union field, drill down to the field.
592 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
593 for (const auto *I : IndirectField->chain())
594 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
595 } else {
596 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
597 }
598}
599
Anders Carlssonfb404882009-12-24 22:46:43 +0000600static void EmitMemberInitializer(CodeGenFunction &CGF,
601 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000602 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000603 const CXXConstructorDecl *Constructor,
604 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000605 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000606 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000607 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000608 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000609
Anders Carlssonfb404882009-12-24 22:46:43 +0000610 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000611 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000612 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000613
614 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000615 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000616 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000617
Alexey Bataev152c71f2015-07-14 07:55:48 +0000618 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000619
Eli Friedman6ae63022012-02-14 02:15:49 +0000620 // Special case: if we are in a copy or move constructor, and we are copying
621 // an array of PODs or classes with trivial copy constructors, ignore the
622 // AST and perform the copy we know is equivalent.
623 // FIXME: This is hacky at best... if we had a bit more explicit information
624 // in the AST, we could generalize it more easily.
625 const ConstantArrayType *Array
626 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000627 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000628 Constructor->isCopyOrMoveConstructor()) {
629 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000630 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000631 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000632 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000633 unsigned SrcArgIndex =
634 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000635 llvm::Value *SrcPtr
636 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000637 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
638 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000639
Eli Friedman6ae63022012-02-14 02:15:49 +0000640 // Copy the aggregate.
641 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000642 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000643 // Ensure that we destroy the objects if an exception is thrown later in
644 // the constructor.
645 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
646 if (CGF.needsEHCleanup(dtorKind))
647 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000648 return;
649 }
650 }
651
Richard Smith30e304e2016-12-14 00:03:17 +0000652 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000653}
654
John McCall7f416cc2015-09-08 08:05:57 +0000655void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
Richard Smith30e304e2016-12-14 00:03:17 +0000656 Expr *Init) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000657 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000658 switch (getEvaluationKind(FieldType)) {
659 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000660 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000661 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000662 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000663 RValue RHS = RValue::get(EmitScalarExpr(Init));
664 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000665 }
John McCall47fb9502013-03-07 21:37:08 +0000666 break;
667 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000668 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000669 break;
670 case TEK_Aggregate: {
Richard Smith30e304e2016-12-14 00:03:17 +0000671 AggValueSlot Slot =
672 AggValueSlot::forLValue(LHS,
673 AggValueSlot::IsDestructed,
674 AggValueSlot::DoesNotNeedGCBarriers,
675 AggValueSlot::IsNotAliased);
676 EmitAggExpr(Init, Slot);
677 break;
Anders Carlssonfb404882009-12-24 22:46:43 +0000678 }
John McCall47fb9502013-03-07 21:37:08 +0000679 }
John McCall12cc42a2013-02-01 05:11:40 +0000680
681 // Ensure that we destroy this object if an exception is thrown
682 // later in the constructor.
683 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
684 if (needsEHCleanup(dtorKind))
685 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000686}
687
John McCallf8ff7b92010-02-23 00:48:20 +0000688/// Checks whether the given constructor is a valid subject for the
689/// complete-to-base constructor delegation optimization, i.e.
690/// emitting the complete constructor as a simple call to the base
691/// constructor.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000692bool CodeGenFunction::IsConstructorDelegationValid(
693 const CXXConstructorDecl *Ctor) {
John McCallf8ff7b92010-02-23 00:48:20 +0000694
695 // Currently we disable the optimization for classes with virtual
696 // bases because (1) the addresses of parameter variables need to be
697 // consistent across all initializers but (2) the delegate function
698 // call necessarily creates a second copy of the parameter variable.
699 //
700 // The limiting example (purely theoretical AFAIK):
701 // struct A { A(int &c) { c++; } };
702 // struct B : virtual A {
703 // B(int count) : A(count) { printf("%d\n", count); }
704 // };
705 // ...although even this example could in principle be emitted as a
706 // delegation since the address of the parameter doesn't escape.
707 if (Ctor->getParent()->getNumVBases()) {
708 // TODO: white-list trivial vbase initializers. This case wouldn't
709 // be subject to the restrictions below.
710
711 // TODO: white-list cases where:
712 // - there are no non-reference parameters to the constructor
713 // - the initializers don't access any non-reference parameters
714 // - the initializers don't take the address of non-reference
715 // parameters
716 // - etc.
717 // If we ever add any of the above cases, remember that:
718 // - function-try-blocks will always blacklist this optimization
719 // - we need to perform the constructor prologue and cleanup in
720 // EmitConstructorBody.
721
722 return false;
723 }
724
725 // We also disable the optimization for variadic functions because
726 // it's impossible to "re-pass" varargs.
727 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
728 return false;
729
Alexis Hunt61bc1732011-05-01 07:04:31 +0000730 // FIXME: Decide if we can do a delegation of a delegating constructor.
731 if (Ctor->isDelegatingConstructor())
732 return false;
733
John McCallf8ff7b92010-02-23 00:48:20 +0000734 return true;
735}
736
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000737// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
738// to poison the extra field paddings inserted under
739// -fsanitize-address-field-padding=1|2.
740void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
741 ASTContext &Context = getContext();
742 const CXXRecordDecl *ClassDecl =
743 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
744 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
745 if (!ClassDecl->mayInsertExtraPadding()) return;
746
747 struct SizeAndOffset {
748 uint64_t Size;
749 uint64_t Offset;
750 };
751
752 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
753 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
754
755 // Populate sizes and offsets of fields.
756 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
757 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
758 SSV[i].Offset =
759 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
760
761 size_t NumFields = 0;
762 for (const auto *Field : ClassDecl->fields()) {
763 const FieldDecl *D = Field;
764 std::pair<CharUnits, CharUnits> FieldInfo =
765 Context.getTypeInfoInChars(D->getType());
766 CharUnits FieldSize = FieldInfo.first;
767 assert(NumFields < SSV.size());
768 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
769 NumFields++;
770 }
771 assert(NumFields == SSV.size());
772 if (SSV.size() <= 1) return;
773
774 // We will insert calls to __asan_* run-time functions.
775 // LLVM AddressSanitizer pass may decide to inline them later.
776 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
777 llvm::FunctionType *FTy =
778 llvm::FunctionType::get(CGM.VoidTy, Args, false);
779 llvm::Constant *F = CGM.CreateRuntimeFunction(
780 FTy, Prologue ? "__asan_poison_intra_object_redzone"
781 : "__asan_unpoison_intra_object_redzone");
782
783 llvm::Value *ThisPtr = LoadCXXThis();
784 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000785 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000786 // For each field check if it has sufficient padding,
787 // if so (un)poison it with a call.
788 for (size_t i = 0; i < SSV.size(); i++) {
789 uint64_t AsanAlignment = 8;
790 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
791 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
792 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
793 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
794 (NextField % AsanAlignment) != 0)
795 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000796 Builder.CreateCall(
797 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
798 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000799 }
800}
801
John McCallb81884d2010-02-19 09:25:03 +0000802/// EmitConstructorBody - Emits the body of the current constructor.
803void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000804 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000805 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
806 CXXCtorType CtorType = CurGD.getCtorType();
807
Reid Kleckner340ad862014-01-13 22:57:31 +0000808 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
809 CtorType == Ctor_Complete) &&
810 "can only generate complete ctor for this ABI");
811
John McCallf8ff7b92010-02-23 00:48:20 +0000812 // Before we go any further, try the complete->base constructor
813 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000814 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000815 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000816 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000817 return;
818 }
819
Hans Wennborgdcfba332015-10-06 23:40:43 +0000820 const FunctionDecl *Definition = nullptr;
Richard Smith46bb5812014-08-01 01:56:39 +0000821 Stmt *Body = Ctor->getBody(Definition);
822 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000823
John McCallf8ff7b92010-02-23 00:48:20 +0000824 // Enter the function-try-block before the constructor prologue if
825 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000826 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000827 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000828 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000829
Justin Bogner66242d62015-04-23 23:06:47 +0000830 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000831
Richard Smithcc1b96d2013-06-12 22:31:48 +0000832 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000833
John McCall88313032012-03-30 04:25:03 +0000834 // TODO: in restricted cases, we can emit the vbase initializers of
835 // a complete ctor and then delegate to the base ctor.
836
John McCallf8ff7b92010-02-23 00:48:20 +0000837 // Emit the constructor prologue, i.e. the base and member
838 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000839 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000840
841 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000842 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000843 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
844 else if (Body)
845 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000846
847 // Emit any cleanup blocks associated with the member or base
848 // initializers, which includes (along the exceptional path) the
849 // destructors for those members and bases that were fully
850 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000851 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000852
John McCallf8ff7b92010-02-23 00:48:20 +0000853 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000854 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000855}
856
Lang Hamesbf122742013-02-17 07:22:09 +0000857namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000858 /// RAII object to indicate that codegen is copying the value representation
859 /// instead of the object representation. Useful when copying a struct or
860 /// class which has uninitialized members and we're only performing
861 /// lvalue-to-rvalue conversion on the object but not its members.
862 class CopyingValueRepresentation {
863 public:
864 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000865 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000866 CGF.SanOpts.set(SanitizerKind::Bool, false);
867 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000868 }
869 ~CopyingValueRepresentation() {
870 CGF.SanOpts = OldSanOpts;
871 }
872 private:
873 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000874 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000875 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000876} // end anonymous namespace
Hans Wennborgdcfba332015-10-06 23:40:43 +0000877
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000878namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000879 class FieldMemcpyizer {
880 public:
881 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
882 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000883 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000884 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000885 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
886 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000887
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000888 bool isMemcpyableField(FieldDecl *F) const {
889 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000890 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000891 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000892 Qualifiers Qual = F->getType().getQualifiers();
893 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
894 return false;
895 return true;
896 }
897
898 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000899 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000900 addInitialField(F);
901 else
902 addNextField(F);
903 }
904
David Majnemera586eb22014-10-10 18:57:10 +0000905 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000906 unsigned LastFieldSize =
907 LastField->isBitField() ?
908 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000909 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000910 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000911 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000912 CGF.getContext().getCharWidth() - 1;
913 CharUnits MemcpySize =
914 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
915 return MemcpySize;
916 }
917
918 void emitMemcpy() {
919 // Give the subclass a chance to bail out if it feels the memcpy isn't
920 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000921 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000922 return;
923 }
924
David Majnemera586eb22014-10-10 18:57:10 +0000925 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000926 if (FirstField->isBitField()) {
927 const CGRecordLayout &RL =
928 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
929 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000930 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000931 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000932 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000933 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000934 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000935 }
Lang Hamesbf122742013-02-17 07:22:09 +0000936
David Majnemera586eb22014-10-10 18:57:10 +0000937 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000938 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +0000939 Address ThisPtr = CGF.LoadCXXThisAddress();
940 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +0000941 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
942 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
943 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
944 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
945
John McCall7f416cc2015-09-08 08:05:57 +0000946 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
947 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
948 MemcpySize);
Lang Hamesbf122742013-02-17 07:22:09 +0000949 reset();
950 }
951
952 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000953 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000954 }
955
956 protected:
957 CodeGenFunction &CGF;
958 const CXXRecordDecl *ClassDecl;
959
960 private:
John McCall7f416cc2015-09-08 08:05:57 +0000961 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
962 llvm::PointerType *DPT = DestPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000963 llvm::Type *DBP =
964 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
965 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
966
John McCall7f416cc2015-09-08 08:05:57 +0000967 llvm::PointerType *SPT = SrcPtr.getType();
Lang Hamesbf122742013-02-17 07:22:09 +0000968 llvm::Type *SBP =
969 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
970 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
971
John McCall7f416cc2015-09-08 08:05:57 +0000972 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
Lang Hamesbf122742013-02-17 07:22:09 +0000973 }
974
975 void addInitialField(FieldDecl *F) {
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000976 FirstField = F;
977 LastField = F;
978 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
979 LastFieldOffset = FirstFieldOffset;
980 LastAddedFieldIndex = F->getFieldIndex();
981 }
Lang Hamesbf122742013-02-17 07:22:09 +0000982
983 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000984 // For the most part, the following invariant will hold:
985 // F->getFieldIndex() == LastAddedFieldIndex + 1
986 // The one exception is that Sema won't add a copy-initializer for an
987 // unnamed bitfield, which will show up here as a gap in the sequence.
988 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
989 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000990 LastAddedFieldIndex = F->getFieldIndex();
991
992 // The 'first' and 'last' fields are chosen by offset, rather than field
993 // index. This allows the code to support bitfields, as well as regular
994 // fields.
995 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
996 if (FOffset < FirstFieldOffset) {
997 FirstField = F;
998 FirstFieldOffset = FOffset;
999 } else if (FOffset > LastFieldOffset) {
1000 LastField = F;
1001 LastFieldOffset = FOffset;
1002 }
1003 }
1004
1005 const VarDecl *SrcRec;
1006 const ASTRecordLayout &RecLayout;
1007 FieldDecl *FirstField;
1008 FieldDecl *LastField;
1009 uint64_t FirstFieldOffset, LastFieldOffset;
1010 unsigned LastAddedFieldIndex;
1011 };
1012
1013 class ConstructorMemcpyizer : public FieldMemcpyizer {
1014 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001015 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001016 /// constructor.
1017 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1018 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001019 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001020 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001021 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001022 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001023 }
1024
1025 // Returns true if a CXXCtorInitializer represents a member initialization
1026 // that can be rolled into a memcpy.
1027 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1028 if (!MemcpyableCtor)
1029 return false;
1030 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001031 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001032 QualType FieldType = Field->getType();
1033 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1034
Richard Smith419bd092015-04-29 19:26:57 +00001035 // Bail out on non-memcpyable, not-trivially-copyable members.
1036 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001037 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1038 FieldType->isReferenceType()))
1039 return false;
1040
1041 // Bail out on volatile fields.
1042 if (!isMemcpyableField(Field))
1043 return false;
1044
1045 // Otherwise we're good.
1046 return true;
1047 }
1048
1049 public:
1050 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1051 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001052 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001053 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001054 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001055 CD->isCopyOrMoveConstructor() &&
1056 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1057 Args(Args) { }
1058
1059 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1060 if (isMemberInitMemcpyable(MemberInit)) {
1061 AggregatedInits.push_back(MemberInit);
1062 addMemcpyableField(MemberInit->getMember());
1063 } else {
1064 emitAggregatedInits();
1065 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1066 ConstructorDecl, Args);
1067 }
1068 }
1069
1070 void emitAggregatedInits() {
1071 if (AggregatedInits.size() <= 1) {
1072 // This memcpy is too small to be worthwhile. Fall back on default
1073 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001074 if (!AggregatedInits.empty()) {
1075 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001076 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001077 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001078 AggregatedInits.clear();
Lang Hamesbf122742013-02-17 07:22:09 +00001079 }
1080 reset();
1081 return;
1082 }
1083
1084 pushEHDestructors();
1085 emitMemcpy();
1086 AggregatedInits.clear();
1087 }
1088
1089 void pushEHDestructors() {
John McCall7f416cc2015-09-08 08:05:57 +00001090 Address ThisPtr = CGF.LoadCXXThisAddress();
Lang Hamesbf122742013-02-17 07:22:09 +00001091 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001092 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
Lang Hamesbf122742013-02-17 07:22:09 +00001093
1094 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001095 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1096 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001097 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001098 if (!CGF.needsEHCleanup(dtorKind))
1099 continue;
1100 LValue FieldLHS = LHS;
1101 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1102 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001103 }
1104 }
1105
1106 void finish() {
1107 emitAggregatedInits();
1108 }
1109
1110 private:
1111 const CXXConstructorDecl *ConstructorDecl;
1112 bool MemcpyableCtor;
1113 FunctionArgList &Args;
1114 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1115 };
1116
1117 class AssignmentMemcpyizer : public FieldMemcpyizer {
1118 private:
Lang Hamesbf122742013-02-17 07:22:09 +00001119 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001120 // exists. Otherwise returns null.
1121 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001122 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001123 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1125 // Recognise trivial assignments.
1126 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001127 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001128 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1129 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001130 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001131 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1132 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001133 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001134 Stmt *RHS = BO->getRHS();
1135 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1136 RHS = EC->getSubExpr();
1137 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return nullptr;
Warren Ristow8d17b402017-02-02 17:53:34 +00001139 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1140 if (ME2->getMemberDecl() == Field)
1141 return Field;
1142 }
1143 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001144 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1145 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001146 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001147 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001148 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1149 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001150 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001151 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1152 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001153 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001154 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1155 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001156 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001157 return Field;
1158 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1159 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1160 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001161 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001162 Expr *DstPtr = CE->getArg(0);
1163 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1164 DstPtr = DC->getSubExpr();
1165 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1166 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001167 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001168 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1169 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001170 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001171 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1172 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001173 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001174 Expr *SrcPtr = CE->getArg(1);
1175 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1176 SrcPtr = SC->getSubExpr();
1177 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1178 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001179 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001180 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1181 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001182 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001183 return Field;
1184 }
1185
Craig Topper8a13c412014-05-21 05:09:00 +00001186 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001187 }
1188
1189 bool AssignmentsMemcpyable;
1190 SmallVector<Stmt*, 16> AggregatedStmts;
1191
1192 public:
Lang Hamesbf122742013-02-17 07:22:09 +00001193 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1194 FunctionArgList &Args)
1195 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1196 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1197 assert(Args.size() == 2);
1198 }
1199
1200 void emitAssignment(Stmt *S) {
1201 FieldDecl *F = getMemcpyableField(S);
1202 if (F) {
1203 addMemcpyableField(F);
1204 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001205 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001206 emitAggregatedStmts();
1207 CGF.EmitStmt(S);
1208 }
1209 }
1210
1211 void emitAggregatedStmts() {
1212 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001213 if (!AggregatedStmts.empty()) {
1214 CopyingValueRepresentation CVR(CGF);
1215 CGF.EmitStmt(AggregatedStmts[0]);
1216 }
Lang Hamesbf122742013-02-17 07:22:09 +00001217 reset();
1218 }
1219
1220 emitMemcpy();
1221 AggregatedStmts.clear();
1222 }
1223
1224 void finish() {
1225 emitAggregatedStmts();
1226 }
1227 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001228} // end anonymous namespace
Lang Hamesbf122742013-02-17 07:22:09 +00001229
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001230static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1231 const Type *BaseType = BaseInit->getBaseClass();
1232 const auto *BaseClassDecl =
1233 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1234 return BaseClassDecl->isDynamicClass();
1235}
1236
Anders Carlssonfb404882009-12-24 22:46:43 +00001237/// EmitCtorPrologue - This routine generates necessary code to initialize
1238/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001239void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001240 CXXCtorType CtorType,
1241 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001242 if (CD->isDelegatingConstructor())
1243 return EmitDelegatingCXXConstructorCall(CD, Args);
1244
Anders Carlssonfb404882009-12-24 22:46:43 +00001245 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001246
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001247 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1248 E = CD->init_end();
1249
Craig Topper8a13c412014-05-21 05:09:00 +00001250 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001251 if (ClassDecl->getNumVBases() &&
1252 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1253 // The ABIs that don't have constructor variants need to put a branch
1254 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001255 BaseCtorContinueBB =
1256 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001257 assert(BaseCtorContinueBB);
1258 }
1259
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001260 llvm::Value *const OldThis = CXXThisValue;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001261 // Virtual base initializers first.
1262 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001263 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1264 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1265 isInitializerOfDynamicClass(*B))
1266 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001267 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1268 }
1269
1270 if (BaseCtorContinueBB) {
1271 // Complete object handler should continue to the remaining initializers.
1272 Builder.CreateBr(BaseCtorContinueBB);
1273 EmitBlock(BaseCtorContinueBB);
1274 }
1275
1276 // Then, non-virtual base initializers.
1277 for (; B != E && (*B)->isBaseInitializer(); B++) {
1278 assert(!(*B)->isBaseVirtual());
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001279
1280 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1281 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1282 isInitializerOfDynamicClass(*B))
1283 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001284 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001285 }
1286
Piotr Padlewski276a78d2015-10-02 22:12:40 +00001287 CXXThisValue = OldThis;
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001288
Anders Carlssond5895932010-03-28 21:07:49 +00001289 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001290
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001291 // And finally, initialize class members.
John McCall7f416cc2015-09-08 08:05:57 +00001292 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
Lang Hamesbf122742013-02-17 07:22:09 +00001293 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001294 for (; B != E; B++) {
1295 CXXCtorInitializer *Member = (*B);
1296 assert(!Member->isBaseInitializer());
1297 assert(Member->isAnyMemberInitializer() &&
1298 "Delegating initializer on non-delegating constructor");
1299 CM.addMemberInitializer(Member);
1300 }
Lang Hamesbf122742013-02-17 07:22:09 +00001301 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001302}
1303
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001304static bool
1305FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1306
1307static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001308HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001309 const CXXRecordDecl *BaseClassDecl,
1310 const CXXRecordDecl *MostDerivedClassDecl)
1311{
1312 // If the destructor is trivial we don't have to check anything else.
1313 if (BaseClassDecl->hasTrivialDestructor())
1314 return true;
1315
1316 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1317 return false;
1318
1319 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001320 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001321 if (!FieldHasTrivialDestructorBody(Context, Field))
1322 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001323
1324 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001325 for (const auto &I : BaseClassDecl->bases()) {
1326 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001327 continue;
1328
1329 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001330 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001331 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1332 MostDerivedClassDecl))
1333 return false;
1334 }
1335
1336 if (BaseClassDecl == MostDerivedClassDecl) {
1337 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001338 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001339 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001340 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001341 if (!HasTrivialDestructorBody(Context, VirtualBase,
1342 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001343 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001344 }
1345 }
1346
1347 return true;
1348}
1349
1350static bool
1351FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001352 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001353{
1354 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1355
1356 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1357 if (!RT)
1358 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001359
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001360 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001361
1362 // The destructor for an implicit anonymous union member is never invoked.
1363 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1364 return false;
1365
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001366 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1367}
1368
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001369/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1370/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001371static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001372 const CXXDestructorDecl *Dtor) {
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001373 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1374 if (!ClassDecl->isDynamicClass())
1375 return true;
1376
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001377 if (!Dtor->hasTrivialBody())
1378 return false;
1379
1380 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001381 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001382 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001383 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001384
1385 return true;
1386}
1387
John McCallb81884d2010-02-19 09:25:03 +00001388/// EmitDestructorBody - Emits the body of the current destructor.
1389void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1390 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1391 CXXDtorType DtorType = CurGD.getDtorType();
1392
Richard Smithdf054d32017-02-25 23:53:05 +00001393 // For an abstract class, non-base destructors are never used (and can't
1394 // be emitted in general, because vbase dtors may not have been validated
1395 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1396 // in fact emit references to them from other compilations, so emit them
1397 // as functions containing a trap instruction.
1398 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1399 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1400 TrapCall->setDoesNotReturn();
1401 TrapCall->setDoesNotThrow();
1402 Builder.CreateUnreachable();
1403 Builder.ClearInsertionPoint();
1404 return;
1405 }
1406
Justin Bognerfb298222015-05-20 16:16:23 +00001407 Stmt *Body = Dtor->getBody();
1408 if (Body)
1409 incrementProfileCounter(Body);
1410
John McCallf99a6312010-07-21 05:30:47 +00001411 // The call to operator delete in a deleting destructor happens
1412 // outside of the function-try-block, which means it's always
1413 // possible to delegate the destructor body to the complete
1414 // destructor. Do so.
1415 if (DtorType == Dtor_Deleting) {
Richard Smith5b349582017-10-13 01:55:36 +00001416 RunCleanupsScope DtorEpilogue(*this);
John McCallf99a6312010-07-21 05:30:47 +00001417 EnterDtorCleanups(Dtor, Dtor_Deleting);
Richard Smith5b349582017-10-13 01:55:36 +00001418 if (HaveInsertPoint())
1419 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1420 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001421 return;
1422 }
1423
John McCallb81884d2010-02-19 09:25:03 +00001424 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001425 // anything else.
1426 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001427 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001428 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001429 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001430
John McCallf99a6312010-07-21 05:30:47 +00001431 // Enter the epilogue cleanups.
1432 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001433
John McCallb81884d2010-02-19 09:25:03 +00001434 // If this is the complete variant, just invoke the base variant;
1435 // the epilogue will destruct the virtual bases. But we can't do
1436 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001437 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001438 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001439 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001440 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001441 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1442
1443 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001444 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1445 "can't emit a dtor without a body for non-Microsoft ABIs");
1446
John McCallf99a6312010-07-21 05:30:47 +00001447 // Enter the cleanup scopes for virtual bases.
1448 EnterDtorCleanups(Dtor, Dtor_Complete);
1449
Reid Klecknere7de47e2013-07-22 13:51:44 +00001450 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001451 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001452 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001453 break;
1454 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001455
John McCallf99a6312010-07-21 05:30:47 +00001456 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001457 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001458
John McCallf99a6312010-07-21 05:30:47 +00001459 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001460 assert(Body);
1461
John McCallf99a6312010-07-21 05:30:47 +00001462 // Enter the cleanup scopes for fields and non-virtual bases.
1463 EnterDtorCleanups(Dtor, Dtor_Base);
1464
1465 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001466 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1467 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1468 // the vptrs to cancel any previous assumptions we might have made.
1469 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1470 CGM.getCodeGenOpts().OptimizationLevel > 0)
1471 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1472 InitializeVTablePointers(Dtor->getParent());
1473 }
John McCallf99a6312010-07-21 05:30:47 +00001474
1475 if (isTryBody)
1476 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1477 else if (Body)
1478 EmitStmt(Body);
1479 else {
1480 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1481 // nothing to do besides what's in the epilogue
1482 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001483 // -fapple-kext must inline any call to this dtor into
1484 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001485 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001486 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001487
John McCallf99a6312010-07-21 05:30:47 +00001488 break;
John McCallb81884d2010-02-19 09:25:03 +00001489 }
1490
John McCallf99a6312010-07-21 05:30:47 +00001491 // Jump out through the epilogue cleanups.
1492 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001493
1494 // Exit the try if applicable.
1495 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001496 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001497}
1498
Lang Hamesbf122742013-02-17 07:22:09 +00001499void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1500 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1501 const Stmt *RootS = AssignOp->getBody();
1502 assert(isa<CompoundStmt>(RootS) &&
1503 "Body of an implicit assignment operator should be compound stmt.");
1504 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1505
1506 LexicalScope Scope(*this, RootCS->getSourceRange());
1507
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001508 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001509 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001510 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001511 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001512 AM.finish();
1513}
1514
John McCallf99a6312010-07-21 05:30:47 +00001515namespace {
Richard Smith5b349582017-10-13 01:55:36 +00001516 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1517 const CXXDestructorDecl *DD) {
1518 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
Haojian Wu5b5c81f2017-10-13 15:37:53 +00001519 return CGF.EmitScalarExpr(ThisArg);
Richard Smith5b349582017-10-13 01:55:36 +00001520 return CGF.LoadCXXThis();
1521 }
1522
John McCallf99a6312010-07-21 05:30:47 +00001523 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001524 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001525 CallDtorDelete() {}
1526
Craig Topper4f12f102014-03-12 06:41:41 +00001527 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001528 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1529 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Richard Smith5b349582017-10-13 01:55:36 +00001530 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1531 LoadThisForDtorDelete(CGF, Dtor),
John McCallf99a6312010-07-21 05:30:47 +00001532 CGF.getContext().getTagDeclType(ClassDecl));
1533 }
1534 };
1535
Richard Smith5b349582017-10-13 01:55:36 +00001536 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1537 llvm::Value *ShouldDeleteCondition,
1538 bool ReturnAfterDelete) {
1539 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1540 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1541 llvm::Value *ShouldCallDelete
1542 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1543 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1544
1545 CGF.EmitBlock(callDeleteBB);
1546 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1547 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1548 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1549 LoadThisForDtorDelete(CGF, Dtor),
1550 CGF.getContext().getTagDeclType(ClassDecl));
1551 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1552 ReturnAfterDelete &&
1553 "unexpected value for ReturnAfterDelete");
1554 if (ReturnAfterDelete)
1555 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1556 else
1557 CGF.Builder.CreateBr(continueBB);
1558
1559 CGF.EmitBlock(continueBB);
1560 }
1561
David Blaikie7e70d682015-08-18 22:40:54 +00001562 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001563 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001564
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001565 public:
1566 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001567 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001568 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001569 }
1570
Craig Topper4f12f102014-03-12 06:41:41 +00001571 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smith5b349582017-10-13 01:55:36 +00001572 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1573 /*ReturnAfterDelete*/false);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001574 }
1575 };
1576
David Blaikie7e70d682015-08-18 22:40:54 +00001577 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001578 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001579 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001580 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001581
John McCall4bd0fb12011-07-12 16:41:08 +00001582 public:
1583 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1584 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001585 : field(field), destroyer(destroyer),
1586 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001587
Craig Topper4f12f102014-03-12 06:41:41 +00001588 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001589 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001590 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001591 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1592 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1593 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001594 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001595
John McCall4bd0fb12011-07-12 16:41:08 +00001596 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001597 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001598 }
1599 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001600
Naomi Musgrave703835c2015-09-16 00:38:22 +00001601 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1602 CharUnits::QuantityType PoisonSize) {
Matt Morehouse4881a232017-09-20 22:53:08 +00001603 CodeGenFunction::SanitizerScope SanScope(&CGF);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001604 // Pass in void pointer and size of region as arguments to runtime
1605 // function
1606 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1607 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1608
1609 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1610
1611 llvm::FunctionType *FnType =
1612 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1613 llvm::Value *Fn =
1614 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1615 CGF.EmitNounwindRuntimeCall(Fn, Args);
1616 }
1617
1618 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001619 const CXXDestructorDecl *Dtor;
1620
1621 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001622 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001623
1624 // Generate function call for handling object poisoning.
1625 // Disables tail call elimination, to prevent the current stack frame
1626 // from disappearing from the stack trace.
1627 void Emit(CodeGenFunction &CGF, Flags flags) override {
1628 const ASTRecordLayout &Layout =
1629 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1630
1631 // Nothing to poison.
1632 if (Layout.getFieldCount() == 0)
1633 return;
1634
1635 // Prevent the current stack frame from disappearing from the stack trace.
1636 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1637
1638 // Construct pointer to region to begin poisoning, and calculate poison
1639 // size, so that only members declared in this class are poisoned.
1640 ASTContext &Context = CGF.getContext();
1641 unsigned fieldIndex = 0;
1642 int startIndex = -1;
1643 // RecordDecl::field_iterator Field;
1644 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1645 // Poison field if it is trivial
1646 if (FieldHasTrivialDestructorBody(Context, Field)) {
1647 // Start sanitizing at this field
1648 if (startIndex < 0)
1649 startIndex = fieldIndex;
1650
1651 // Currently on the last field, and it must be poisoned with the
1652 // current block.
1653 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001654 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001655 }
1656 } else if (startIndex >= 0) {
1657 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001658 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001659 // Re-set the start index
1660 startIndex = -1;
1661 }
1662 fieldIndex += 1;
1663 }
1664 }
1665
1666 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001667 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001668 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001669 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001670 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001671 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001672 unsigned layoutEndOffset) {
1673 ASTContext &Context = CGF.getContext();
1674 const ASTRecordLayout &Layout =
1675 Context.getASTRecordLayout(Dtor->getParent());
1676
1677 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1678 CGF.SizeTy,
1679 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1680 .getQuantity());
1681
1682 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1683 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1684 OffsetSizePtr);
1685
1686 CharUnits::QuantityType PoisonSize;
1687 if (layoutEndOffset >= Layout.getFieldCount()) {
1688 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1689 Context.toCharUnitsFromBits(
1690 Layout.getFieldOffset(layoutStartOffset))
1691 .getQuantity();
1692 } else {
1693 PoisonSize = Context.toCharUnitsFromBits(
1694 Layout.getFieldOffset(layoutEndOffset) -
1695 Layout.getFieldOffset(layoutStartOffset))
1696 .getQuantity();
1697 }
1698
1699 if (PoisonSize == 0)
1700 return;
1701
Naomi Musgrave703835c2015-09-16 00:38:22 +00001702 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001703 }
1704 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001705
1706 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1707 const CXXDestructorDecl *Dtor;
1708
1709 public:
1710 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1711
1712 // Generate function call for handling vtable pointer poisoning.
1713 void Emit(CodeGenFunction &CGF, Flags flags) override {
1714 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001715 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001716 ASTContext &Context = CGF.getContext();
1717 // Poison vtable and vtable ptr if they exist for this class.
1718 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1719
1720 CharUnits::QuantityType PoisonSize =
1721 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1722 // Pass in void pointer and size of region as arguments to runtime
1723 // function
1724 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1725 }
1726 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001727} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001728
Hans Wennborgdeff7032013-12-18 01:39:59 +00001729/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001730/// destructor. This is to call destructors on members and base classes
1731/// in reverse order of their construction.
Richard Smith5b349582017-10-13 01:55:36 +00001732///
1733/// For a deleting destructor, this also handles the case where a destroying
1734/// operator delete completely overrides the definition.
John McCallf99a6312010-07-21 05:30:47 +00001735void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1736 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001737 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1738 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001739
John McCallf99a6312010-07-21 05:30:47 +00001740 // The deleting-destructor phase just needs to call the appropriate
1741 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001742 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001743 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001744 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001745 if (CXXStructorImplicitParamValue) {
1746 // If there is an implicit param to the deleting dtor, it's a boolean
Richard Smith5b349582017-10-13 01:55:36 +00001747 // telling whether this is a deleting destructor.
1748 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1749 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1750 /*ReturnAfterDelete*/true);
1751 else
1752 EHStack.pushCleanup<CallDtorDeleteConditional>(
1753 NormalAndEHCleanup, CXXStructorImplicitParamValue);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001754 } else {
Richard Smith5b349582017-10-13 01:55:36 +00001755 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1756 const CXXRecordDecl *ClassDecl = DD->getParent();
1757 EmitDeleteCall(DD->getOperatorDelete(),
1758 LoadThisForDtorDelete(*this, DD),
1759 getContext().getTagDeclType(ClassDecl));
1760 EmitBranchThroughCleanup(ReturnBlock);
1761 } else {
1762 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1763 }
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001764 }
John McCall5c60a6f2010-02-18 19:59:28 +00001765 return;
1766 }
1767
John McCallf99a6312010-07-21 05:30:47 +00001768 const CXXRecordDecl *ClassDecl = DD->getParent();
1769
Richard Smith20104042011-09-18 12:11:43 +00001770 // Unions have no bases and do not call field destructors.
1771 if (ClassDecl->isUnion())
1772 return;
1773
John McCallf99a6312010-07-21 05:30:47 +00001774 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001775 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001776 // Poison the vtable pointer such that access after the base
1777 // and member destructors are invoked is invalid.
1778 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1779 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1780 ClassDecl->isPolymorphic())
1781 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001782
1783 // We push them in the forward order so that they'll be popped in
1784 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001785 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001786 CXXRecordDecl *BaseClassDecl
1787 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001788
John McCall5c60a6f2010-02-18 19:59:28 +00001789 // Ignore trivial destructors.
1790 if (BaseClassDecl->hasTrivialDestructor())
1791 continue;
John McCallf99a6312010-07-21 05:30:47 +00001792
John McCallcda666c2010-07-21 07:22:38 +00001793 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1794 BaseClassDecl,
1795 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001796 }
John McCallf99a6312010-07-21 05:30:47 +00001797
John McCall5c60a6f2010-02-18 19:59:28 +00001798 return;
1799 }
1800
1801 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001802 // Poison the vtable pointer if it has no virtual bases, but inherits
1803 // virtual functions.
1804 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1805 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1806 ClassDecl->isPolymorphic())
1807 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001808
John McCallf99a6312010-07-21 05:30:47 +00001809 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001810 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001811 // Ignore virtual bases.
1812 if (Base.isVirtual())
1813 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001814
John McCallf99a6312010-07-21 05:30:47 +00001815 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001816
John McCallf99a6312010-07-21 05:30:47 +00001817 // Ignore trivial destructors.
1818 if (BaseClassDecl->hasTrivialDestructor())
1819 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001820
John McCallcda666c2010-07-21 07:22:38 +00001821 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1822 BaseClassDecl,
1823 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001824 }
1825
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001826 // Poison fields such that access after their destructors are
1827 // invoked, and before the base class destructor runs, is invalid.
1828 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1829 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001830 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001831
John McCallf99a6312010-07-21 05:30:47 +00001832 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001833 for (const auto *Field : ClassDecl->fields()) {
1834 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001835 QualType::DestructionKind dtorKind = type.isDestructedType();
1836 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001837
Richard Smith921bd202012-02-26 09:11:52 +00001838 // Anonymous union members do not have their destructors called.
1839 const RecordType *RT = type->getAsUnionType();
1840 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1841
John McCall4bd0fb12011-07-12 16:41:08 +00001842 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001843 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001844 getDestroyer(dtorKind),
1845 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001846 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001847}
1848
John McCallf677a8e2011-07-13 06:10:41 +00001849/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1850/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001851///
John McCallf677a8e2011-07-13 06:10:41 +00001852/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001853/// \param arrayType the type of the array to initialize
1854/// \param arrayBegin an arrayType*
1855/// \param zeroInitialize true if each element should be
1856/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001857void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001858 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001859 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001860 QualType elementType;
1861 llvm::Value *numElements =
1862 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001863
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001864 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001865}
1866
John McCallf677a8e2011-07-13 06:10:41 +00001867/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1868/// constructor for each of several members of an array.
1869///
1870/// \param ctor the constructor to call for each element
1871/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001872/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001873/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001874/// \param zeroInitialize true if each element should be
1875/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001876void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1877 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001878 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001879 const CXXConstructExpr *E,
1880 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001881 // It's legal for numElements to be zero. This can happen both
1882 // dynamically, because x can be zero in 'new A[x]', and statically,
1883 // because of GCC extensions that permit zero-length arrays. There
1884 // are probably legitimate places where we could assume that this
1885 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001886 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001887
1888 // Optimize for a constant count.
1889 llvm::ConstantInt *constantCount
1890 = dyn_cast<llvm::ConstantInt>(numElements);
1891 if (constantCount) {
1892 // Just skip out if the constant count is zero.
1893 if (constantCount->isZero()) return;
1894
1895 // Otherwise, emit the check.
1896 } else {
1897 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1898 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1899 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1900 EmitBlock(loopBB);
1901 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001902
John McCallf677a8e2011-07-13 06:10:41 +00001903 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001904 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001905 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1906 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001907
John McCallf677a8e2011-07-13 06:10:41 +00001908 // Enter the loop, setting up a phi for the current location to initialize.
1909 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1910 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1911 EmitBlock(loopBB);
1912 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1913 "arrayctor.cur");
1914 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001915
Anders Carlsson27da15b2010-01-01 20:29:01 +00001916 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001917
John McCall7f416cc2015-09-08 08:05:57 +00001918 // The alignment of the base, adjusted by the size of a single element,
1919 // provides a conservative estimate of the alignment of every element.
1920 // (This assumes we never start tracking offsetted alignments.)
1921 //
1922 // Note that these are complete objects and so we don't need to
1923 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001924 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001925 CharUnits eltAlignment =
1926 arrayBase.getAlignment()
1927 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1928 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001929
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001930 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001931 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001932 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001933
1934 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001935 // There are two contexts in which temporaries are destroyed at a different
1936 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001937 // default constructor is called to initialize an element of an array.
1938 // If the constructor has one or more default arguments, the destruction of
1939 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001940 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001941
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001942 {
John McCallbd309292010-07-06 01:34:17 +00001943 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001944
John McCallf677a8e2011-07-13 06:10:41 +00001945 // Evaluate the constructor and its arguments in a regular
1946 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001947 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001948 !ctor->getParent()->hasTrivialDestructor()) {
1949 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001950 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1951 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001952 }
1953
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001954 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001955 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001956 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001957
John McCallf677a8e2011-07-13 06:10:41 +00001958 // Go to the next element.
1959 llvm::Value *next =
1960 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1961 "arrayctor.next");
1962 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001963
John McCallf677a8e2011-07-13 06:10:41 +00001964 // Check whether that's the end of the loop.
1965 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1966 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1967 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001968
John McCall6549b312011-07-13 07:37:11 +00001969 // Patch the earlier check to skip over the loop.
1970 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1971
John McCallf677a8e2011-07-13 06:10:41 +00001972 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001973}
1974
John McCall82fe67b2011-07-09 01:37:26 +00001975void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001976 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001977 QualType type) {
1978 const RecordType *rtype = type->castAs<RecordType>();
1979 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1980 const CXXDestructorDecl *dtor = record->getDestructor();
1981 assert(!dtor->isTrivial());
1982 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001983 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001984}
1985
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001986void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1987 CXXCtorType Type,
1988 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001989 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001990 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001991 CallArgList Args;
1992
1993 // Push the this ptr.
1994 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1995
1996 // If this is a trivial constructor, emit a memcpy now before we lose
1997 // the alignment information on the argument.
1998 // FIXME: It would be better to preserve alignment information into CallArg.
1999 if (isMemcpyEquivalentSpecialMember(D)) {
2000 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2001
2002 const Expr *Arg = E->getArg(0);
2003 QualType SrcTy = Arg->getType();
2004 Address Src = EmitLValue(Arg).getAddress();
2005 QualType DestTy = getContext().getTypeDeclType(D->getParent());
2006 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
2007 return;
2008 }
2009
2010 // Add the rest of the user-supplied arguments.
2011 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00002012 EvaluationOrder Order = E->isListInitialization()
2013 ? EvaluationOrder::ForceLeftToRight
2014 : EvaluationOrder::Default;
2015 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2016 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00002017
2018 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
2019}
2020
2021static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2022 const CXXConstructorDecl *Ctor,
2023 CXXCtorType Type, CallArgList &Args) {
2024 // We can't forward a variadic call.
2025 if (Ctor->isVariadic())
2026 return false;
2027
2028 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2029 // If the parameters are callee-cleanup, it's not safe to forward.
2030 for (auto *P : Ctor->parameters())
2031 if (P->getType().isDestructedType())
2032 return false;
2033
2034 // Likewise if they're inalloca.
2035 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00002036 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00002037 if (Info.usesInAlloca())
2038 return false;
2039 }
2040
2041 // Anything else should be OK.
2042 return true;
2043}
2044
2045void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2046 CXXCtorType Type,
2047 bool ForVirtualBase,
2048 bool Delegating,
2049 Address This,
2050 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002051 const CXXRecordDecl *ClassDecl = D->getParent();
2052
Richard Smith419bd092015-04-29 19:26:57 +00002053 // C++11 [class.mfct.non-static]p2:
2054 // If a non-static member function of a class X is called for an object that
2055 // is not of type X, or of a type derived from X, the behavior is undefined.
2056 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002057 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002058 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002059
Richard Smith419bd092015-04-29 19:26:57 +00002060 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002061 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002062 return;
2063 }
2064
2065 // If this is a trivial constructor, just emit what's needed. If this is a
2066 // union copy constructor, we must emit a memcpy, because the AST does not
2067 // model that copy.
2068 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002069 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002070
Richard Smith5179eb72016-06-28 19:03:57 +00002071 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2072 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002073 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002074 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002075 return;
2076 }
2077
George Burgess IVd0a9e802017-02-23 22:07:35 +00002078 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002079 // Check whether we can actually emit the constructor before trying to do so.
2080 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002081 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2082 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002083 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2084 Delegating, Args);
2085 return;
2086 }
2087 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002088
2089 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002090 CGCXXABI::AddedStructorArgs ExtraArgs =
2091 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2092 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002093
2094 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002095 llvm::Constant *CalleePtr =
2096 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002097 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002098 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002099 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2100 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002101
2102 // Generate vtable assumptions if we're constructing a complete object
2103 // with a vtable. We don't do this for base subobjects for two reasons:
2104 // first, it's incorrect for classes with virtual bases, and second, we're
2105 // about to overwrite the vptrs anyway.
2106 // We also have to make sure if we can refer to vtable:
2107 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2108 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2109 // sure that definition of vtable is not hidden,
2110 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002111 // FIXME: It looks like InstCombine is very inefficient on dealing with
2112 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002113 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2114 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002115 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2116 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002117 EmitVTableAssumptionLoads(ClassDecl, This);
2118}
2119
Richard Smith5179eb72016-06-28 19:03:57 +00002120void CodeGenFunction::EmitInheritedCXXConstructorCall(
2121 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2122 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2123 CallArgList Args;
2124 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2125 /*NeedsCopy=*/false);
2126
2127 // Forward the parameters.
2128 if (InheritedFromVBase &&
2129 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2130 // Nothing to do; this construction is not responsible for constructing
2131 // the base class containing the inherited constructor.
2132 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2133 // have constructor variants?
2134 Args.push_back(ThisArg);
2135 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2136 // The inheriting constructor was inlined; just inject its arguments.
2137 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2138 "wrong number of parameters for inherited constructor call");
2139 Args = CXXInheritedCtorInitExprArgs;
2140 Args[0] = ThisArg;
2141 } else {
2142 // The inheriting constructor was not inlined. Emit delegating arguments.
2143 Args.push_back(ThisArg);
2144 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2145 assert(OuterCtor->getNumParams() == D->getNumParams());
2146 assert(!OuterCtor->isVariadic() && "should have been inlined");
2147
2148 for (const auto *Param : OuterCtor->parameters()) {
2149 assert(getContext().hasSameUnqualifiedType(
2150 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2151 Param->getType()));
2152 EmitDelegateCallArg(Args, Param, E->getLocation());
2153
2154 // Forward __attribute__(pass_object_size).
2155 if (Param->hasAttr<PassObjectSizeAttr>()) {
2156 auto *POSParam = SizeArguments[Param];
2157 assert(POSParam && "missing pass_object_size value for forwarding");
2158 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2159 }
2160 }
2161 }
2162
2163 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2164 This, Args);
2165}
2166
2167void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2168 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2169 bool Delegating, CallArgList &Args) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00002170 GlobalDecl GD(Ctor, CtorType);
2171 InlinedInheritingConstructorScope Scope(*this, GD);
2172 ApplyInlineDebugLocation DebugScope(*this, GD);
Richard Smith5179eb72016-06-28 19:03:57 +00002173
2174 // Save the arguments to be passed to the inherited constructor.
2175 CXXInheritedCtorInitExprArgs = Args;
2176
2177 FunctionArgList Params;
2178 QualType RetType = BuildFunctionArgList(CurGD, Params);
2179 FnRetTy = RetType;
2180
2181 // Insert any ABI-specific implicit constructor arguments.
2182 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2183 ForVirtualBase, Delegating, Args);
2184
2185 // Emit a simplified prolog. We only need to emit the implicit params.
2186 assert(Args.size() >= Params.size() && "too few arguments for call");
2187 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2188 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2189 const RValue &RV = Args[I].RV;
2190 assert(!RV.isComplex() && "complex indirect params not supported");
2191 ParamValue Val = RV.isScalar()
2192 ? ParamValue::forDirect(RV.getScalarVal())
2193 : ParamValue::forIndirect(RV.getAggregateAddress());
2194 EmitParmDecl(*Params[I], Val, I + 1);
2195 }
2196 }
2197
2198 // Create a return value slot if the ABI implementation wants one.
2199 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2200 // value instead.
2201 if (!RetType->isVoidType())
2202 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2203
2204 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2205 CXXThisValue = CXXABIThisValue;
2206
2207 // Directly emit the constructor initializers.
2208 EmitCtorPrologue(Ctor, CtorType, Params);
2209}
2210
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002211void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2212 llvm::Value *VTableGlobal =
2213 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2214 if (!VTableGlobal)
2215 return;
2216
2217 // We can just use the base offset in the complete class.
2218 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2219
2220 if (!NonVirtualOffset.isZero())
2221 This =
2222 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2223 Vptr.VTableClass, Vptr.NearestVBase);
2224
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002225 llvm::Value *VPtrValue =
2226 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002227 llvm::Value *Cmp =
2228 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2229 Builder.CreateAssumption(Cmp);
2230}
2231
2232void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2233 Address This) {
2234 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2235 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2236 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002237}
2238
John McCallf8ff7b92010-02-23 00:48:20 +00002239void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002240CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002241 Address This, Address Src,
2242 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002243 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002244
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002245 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002246
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002247 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002248 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002249
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002250 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002251 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002252 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002253 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002254 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002255
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002256 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002257 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002258 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002259
Richard Smith5179eb72016-06-28 19:03:57 +00002260 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002261}
2262
2263void
John McCallf8ff7b92010-02-23 00:48:20 +00002264CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2265 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002266 const FunctionArgList &Args,
2267 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002268 CallArgList DelegateArgs;
2269
2270 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2271 assert(I != E && "no parameters to constructor");
2272
2273 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002274 Address This = LoadCXXThisAddress();
2275 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002276 ++I;
2277
Richard Smith5179eb72016-06-28 19:03:57 +00002278 // FIXME: The location of the VTT parameter in the parameter list is
2279 // specific to the Itanium ABI and shouldn't be hardcoded here.
2280 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2281 assert(I != E && "cannot skip vtt parameter, already done with args");
2282 assert((*I)->getType()->isPointerType() &&
2283 "skipping parameter not of vtt type");
2284 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002285 }
2286
2287 // Explicit arguments.
2288 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002289 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002290 // FIXME: per-argument source location
2291 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002292 }
2293
Richard Smith5179eb72016-06-28 19:03:57 +00002294 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2295 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002296}
2297
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002298namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002299 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002300 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002301 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002302 CXXDtorType Type;
2303
John McCall7f416cc2015-09-08 08:05:57 +00002304 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002305 CXXDtorType Type)
2306 : Dtor(D), Addr(Addr), Type(Type) {}
2307
Craig Topper4f12f102014-03-12 06:41:41 +00002308 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002309 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002310 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002311 }
2312 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002313} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002314
Alexis Hunt61bc1732011-05-01 07:04:31 +00002315void
2316CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2317 const FunctionArgList &Args) {
2318 assert(Ctor->isDelegatingConstructor());
2319
John McCall7f416cc2015-09-08 08:05:57 +00002320 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002321
John McCall31168b02011-06-15 23:02:42 +00002322 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002323 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002324 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002325 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002326 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002327
2328 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002329
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002330 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002331 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002332 CXXDtorType Type =
2333 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2334
2335 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2336 ClassDecl->getDestructor(),
2337 ThisPtr, Type);
2338 }
2339}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002340
Anders Carlsson27da15b2010-01-01 20:29:01 +00002341void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2342 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002343 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002344 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002345 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002346 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2347 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002348}
2349
John McCall53cad2e2010-07-21 01:41:18 +00002350namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002351 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002352 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002353 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002354
John McCall7f416cc2015-09-08 08:05:57 +00002355 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002356 : Dtor(D), Addr(Addr) {}
2357
Craig Topper4f12f102014-03-12 06:41:41 +00002358 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002359 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002360 /*ForVirtualBase=*/false,
2361 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002362 }
2363 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002364} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002365
John McCall8680f872010-07-21 06:29:51 +00002366void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002367 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002368 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002369}
2370
John McCall7f416cc2015-09-08 08:05:57 +00002371void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002372 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2373 if (!ClassDecl) return;
2374 if (ClassDecl->hasTrivialDestructor()) return;
2375
2376 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002377 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002378 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002379}
2380
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002381void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002382 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002383 llvm::Value *VTableAddressPoint =
2384 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002385 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2386
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002387 if (!VTableAddressPoint)
2388 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002389
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002390 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002391 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002392 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002393
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002394 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002395 // We need to use the virtual base offset offset because the virtual base
2396 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002397
2398 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2399 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2400 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002401 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002402 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002403 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002404 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002405
Anders Carlssonc58fb552010-05-03 00:29:58 +00002406 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002407 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002408
Ken Dyckcfc332c2011-03-23 00:45:26 +00002409 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002410 VTableField = ApplyNonVirtualAndVirtualOffset(
2411 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2412 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002413
Reid Kleckner8d585132014-12-03 21:00:21 +00002414 // Finally, store the address point. Use the same LLVM types as the field to
2415 // support optimization.
2416 llvm::Type *VTablePtrTy =
2417 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2418 ->getPointerTo()
2419 ->getPointerTo();
2420 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2421 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002422
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002423 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00002424 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAVTablePtrAccessInfo());
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002425 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2426 CGM.getCodeGenOpts().StrictVTablePointers)
2427 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002428}
2429
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002430CodeGenFunction::VPtrsVector
2431CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2432 CodeGenFunction::VPtrsVector VPtrsResult;
2433 VisitedVirtualBasesSetTy VBases;
2434 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2435 /*NearestVBase=*/nullptr,
2436 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2437 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2438 VPtrsResult);
2439 return VPtrsResult;
2440}
2441
2442void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2443 const CXXRecordDecl *NearestVBase,
2444 CharUnits OffsetFromNearestVBase,
2445 bool BaseIsNonVirtualPrimaryBase,
2446 const CXXRecordDecl *VTableClass,
2447 VisitedVirtualBasesSetTy &VBases,
2448 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002449 // If this base is a non-virtual primary base the address point has already
2450 // been set.
2451 if (!BaseIsNonVirtualPrimaryBase) {
2452 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002453 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2454 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002455 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002456
Anders Carlssond5895932010-03-28 21:07:49 +00002457 const CXXRecordDecl *RD = Base.getBase();
2458
2459 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002460 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002461 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002462 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002463
2464 // Ignore classes without a vtable.
2465 if (!BaseDecl->isDynamicClass())
2466 continue;
2467
Ken Dyck3fb4c892011-03-23 01:04:18 +00002468 CharUnits BaseOffset;
2469 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002470 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002471
Aaron Ballman574705e2014-03-13 15:41:46 +00002472 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002473 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002474 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002475 continue;
2476
Justin Bogner1cd11f12015-05-20 15:53:59 +00002477 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002478 getContext().getASTRecordLayout(VTableClass);
2479
Ken Dyck3fb4c892011-03-23 01:04:18 +00002480 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2481 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002482 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002483 } else {
2484 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2485
Ken Dyck16ffcac2011-03-24 01:21:01 +00002486 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002487 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002488 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002489 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002490 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002491
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002492 getVTablePointers(
2493 BaseSubobject(BaseDecl, BaseOffset),
2494 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2495 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002496 }
2497}
2498
2499void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2500 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002501 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002502 return;
2503
Anders Carlssond5895932010-03-28 21:07:49 +00002504 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002505 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2506 for (const VPtr &Vptr : getVTablePointers(RD))
2507 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002508
2509 if (RD->getNumVBases())
2510 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002511}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002512
John McCall7f416cc2015-09-08 08:05:57 +00002513llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002514 llvm::Type *VTableTy,
2515 const CXXRecordDecl *RD) {
2516 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002517 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00002518 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAVTablePtrAccessInfo());
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002519
2520 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2521 CGM.getCodeGenOpts().StrictVTablePointers)
2522 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2523
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002524 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002525}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002526
Peter Collingbourned2926c92015-03-14 02:42:25 +00002527// If a class has a single non-virtual base and does not introduce or override
2528// virtual member functions or fields, it will have the same layout as its base.
2529// This function returns the least derived such class.
2530//
2531// Casting an instance of a base class to such a derived class is technically
2532// undefined behavior, but it is a relatively common hack for introducing member
2533// functions on class instances with specific properties (e.g. llvm::Operator)
2534// that works under most compilers and should not have security implications, so
2535// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2536static const CXXRecordDecl *
2537LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2538 if (!RD->field_empty())
2539 return RD;
2540
2541 if (RD->getNumVBases() != 0)
2542 return RD;
2543
2544 if (RD->getNumBases() != 1)
2545 return RD;
2546
2547 for (const CXXMethodDecl *MD : RD->methods()) {
2548 if (MD->isVirtual()) {
2549 // Virtual member functions are only ok if they are implicit destructors
2550 // because the implicit destructor will have the same semantics as the
2551 // base class's destructor if no fields are added.
2552 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2553 continue;
2554 return RD;
2555 }
2556 }
2557
2558 return LeastDerivedClassWithSameLayout(
2559 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2560}
2561
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002562void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2563 llvm::Value *VTable,
2564 SourceLocation Loc) {
Peter Collingbourne396943a2017-07-31 22:35:33 +00002565 if (SanOpts.has(SanitizerKind::CFIVCall))
2566 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2567 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2568 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002569 llvm::Metadata *MD =
2570 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002571 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002572 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2573
2574 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002575 llvm::Value *TypeTest =
2576 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2577 {CastedVTable, TypeId});
2578 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002579 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00002580}
2581
2582void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002583 llvm::Value *VTable,
2584 CFITypeCheckKind TCK,
2585 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002586 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002587 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002588
Peter Collingbournefb532b92016-02-24 20:46:36 +00002589 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002590}
2591
Peter Collingbourned2926c92015-03-14 02:42:25 +00002592void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2593 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002594 bool MayBeNull,
2595 CFITypeCheckKind TCK,
2596 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002597 if (!getLangOpts().CPlusPlus)
2598 return;
2599
2600 auto *ClassTy = T->getAs<RecordType>();
2601 if (!ClassTy)
2602 return;
2603
2604 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2605
2606 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2607 return;
2608
Peter Collingbourned2926c92015-03-14 02:42:25 +00002609 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2610 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2611
Hans Wennborgdcfba332015-10-06 23:40:43 +00002612 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002613
2614 if (MayBeNull) {
2615 llvm::Value *DerivedNotNull =
2616 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2617
2618 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2619 ContBlock = createBasicBlock("cast.cont");
2620
2621 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2622
2623 EmitBlock(CheckBlock);
2624 }
2625
John McCall7f416cc2015-09-08 08:05:57 +00002626 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002627 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2628
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002629 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002630
2631 if (MayBeNull) {
2632 Builder.CreateBr(ContBlock);
2633 EmitBlock(ContBlock);
2634 }
2635}
2636
2637void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002638 llvm::Value *VTable,
2639 CFITypeCheckKind TCK,
2640 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002641 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2642 !CGM.HasHiddenLTOVisibility(RD))
2643 return;
2644
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002645 SanitizerMask M;
Peter Collingbournedc134532016-01-16 00:31:22 +00002646 llvm::SanitizerStatKind SSK;
2647 switch (TCK) {
2648 case CFITCK_VCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002649 M = SanitizerKind::CFIVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002650 SSK = llvm::SanStat_CFI_VCall;
2651 break;
2652 case CFITCK_NVCall:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002653 M = SanitizerKind::CFINVCall;
Peter Collingbournedc134532016-01-16 00:31:22 +00002654 SSK = llvm::SanStat_CFI_NVCall;
2655 break;
2656 case CFITCK_DerivedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002657 M = SanitizerKind::CFIDerivedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002658 SSK = llvm::SanStat_CFI_DerivedCast;
2659 break;
2660 case CFITCK_UnrelatedCast:
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002661 M = SanitizerKind::CFIUnrelatedCast;
Peter Collingbournedc134532016-01-16 00:31:22 +00002662 SSK = llvm::SanStat_CFI_UnrelatedCast;
2663 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002664 case CFITCK_ICall:
2665 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002666 }
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002667
2668 std::string TypeName = RD->getQualifiedNameAsString();
2669 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2670 return;
2671
2672 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002673 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002674
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002675 llvm::Metadata *MD =
2676 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002677 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002678
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002679 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002680 llvm::Value *TypeTest = Builder.CreateCall(
2681 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002682
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002683 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002684 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002685 EmitCheckSourceLocation(Loc),
2686 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002687 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002688
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002689 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2690 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2691 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002692 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002693 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002694
2695 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002696 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002697 return;
2698 }
2699
2700 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2701 CGM.getLLVMContext(),
2702 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002703 llvm::Value *ValidVtable = Builder.CreateCall(
2704 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002705 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2706 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002707}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002708
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002709bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2710 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2711 !SanOpts.has(SanitizerKind::CFIVCall) ||
2712 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2713 !CGM.HasHiddenLTOVisibility(RD))
2714 return false;
2715
2716 std::string TypeName = RD->getQualifiedNameAsString();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002717 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2718 SanitizerKind::CFIVCall, TypeName);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002719}
2720
2721llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2722 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2723 SanitizerScope SanScope(this);
2724
2725 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2726
2727 llvm::Metadata *MD =
2728 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2729 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2730
2731 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2732 llvm::Value *CheckedLoad = Builder.CreateCall(
2733 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2734 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2735 TypeId});
2736 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2737
2738 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002739 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002740
2741 return Builder.CreateBitCast(
2742 Builder.CreateExtractValue(CheckedLoad, 0),
2743 cast<llvm::PointerType>(VTable->getType())->getElementType());
2744}
2745
Faisal Vali571df122013-09-29 08:45:24 +00002746void CodeGenFunction::EmitForwardingCallToLambda(
2747 const CXXMethodDecl *callOperator,
2748 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002749 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002750 const CGFunctionInfo &calleeFnInfo =
2751 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002752 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002753 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2754 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002755
John McCall8dda7b22012-07-07 06:41:13 +00002756 // Prepare the return slot.
2757 const FunctionProtoType *FPT =
2758 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002759 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002760 ReturnValueSlot returnSlot;
2761 if (!resultType->isVoidType() &&
2762 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002763 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002764 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2765
2766 // We don't need to separately arrange the call arguments because
2767 // the call can't be variadic anyway --- it's impossible to forward
2768 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002769
Eli Friedman5b446882012-02-16 03:47:28 +00002770 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002771 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2772 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002773
John McCall8dda7b22012-07-07 06:41:13 +00002774 // If necessary, copy the returned value into the slot.
2775 if (!resultType->isVoidType() && returnSlot.isNull())
2776 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002777 else
2778 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002779}
2780
Eli Friedman2495ab02012-02-25 02:48:22 +00002781void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2782 const BlockDecl *BD = BlockInfo->getBlockDecl();
2783 const VarDecl *variable = BD->capture_begin()->getVariable();
2784 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002785 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2786
2787 if (CallOp->isVariadic()) {
2788 // FIXME: Making this work correctly is nasty because it requires either
2789 // cloning the body of the call operator or making the call operator
2790 // forward.
2791 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2792 return;
2793 }
Eli Friedman2495ab02012-02-25 02:48:22 +00002794
2795 // Start building arguments for forwarding call
2796 CallArgList CallArgs;
2797
2798 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002799 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2800 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002801
2802 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002803 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002804 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002805
Justin Bogner1cd11f12015-05-20 15:53:59 +00002806 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002807 "generic lambda interconversion to block not implemented");
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002808 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002809}
2810
2811void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2812 const CXXRecordDecl *Lambda = MD->getParent();
2813
2814 // Start building arguments for forwarding call
2815 CallArgList CallArgs;
2816
2817 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2818 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2819 CallArgs.add(RValue::get(ThisPtr), ThisType);
2820
2821 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002822 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002823 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2824
Faisal Vali571df122013-09-29 08:45:24 +00002825 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2826 // For a generic lambda, find the corresponding call operator specialization
2827 // to which the call to the static-invoker shall be forwarded.
2828 if (Lambda->isGenericLambda()) {
2829 assert(MD->isFunctionTemplateSpecialization());
2830 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2831 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002832 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002833 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002834 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002835 assert(CorrespondingCallOpSpecialization);
2836 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2837 }
2838 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002839}
2840
Reid Kleckner2d3c4212017-08-04 22:38:06 +00002841void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00002842 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002843 // FIXME: Making this work correctly is nasty because it requires either
2844 // cloning the body of the call operator or making the call operator forward.
2845 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002846 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002847 }
2848
Douglas Gregor355efbb2012-02-17 03:02:34 +00002849 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002850}