blob: 365da4f1351ba8d221bfa6d2942c50405bdbad65 [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,
132 AlignmentSource *alignSource) {
133 // 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();
139 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
140 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) {
1416 EnterDtorCleanups(Dtor, Dtor_Deleting);
1417 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001418 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001419 PopCleanupBlock();
1420 return;
1421 }
1422
John McCallb81884d2010-02-19 09:25:03 +00001423 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001424 // anything else.
1425 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001426 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001427 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001428 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001429
John McCallf99a6312010-07-21 05:30:47 +00001430 // Enter the epilogue cleanups.
1431 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001432
John McCallb81884d2010-02-19 09:25:03 +00001433 // If this is the complete variant, just invoke the base variant;
1434 // the epilogue will destruct the virtual bases. But we can't do
1435 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001436 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001437 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001438 switch (DtorType) {
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001439 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
John McCallf99a6312010-07-21 05:30:47 +00001440 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1441
1442 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001443 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1444 "can't emit a dtor without a body for non-Microsoft ABIs");
1445
John McCallf99a6312010-07-21 05:30:47 +00001446 // Enter the cleanup scopes for virtual bases.
1447 EnterDtorCleanups(Dtor, Dtor_Complete);
1448
Reid Klecknere7de47e2013-07-22 13:51:44 +00001449 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001450 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001451 /*Delegating=*/false, LoadCXXThisAddress());
John McCallf99a6312010-07-21 05:30:47 +00001452 break;
1453 }
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001454
John McCallf99a6312010-07-21 05:30:47 +00001455 // Fallthrough: act like we're in the base variant.
Saleem Abdulrasool8de4e872017-02-02 05:45:43 +00001456 LLVM_FALLTHROUGH;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001457
John McCallf99a6312010-07-21 05:30:47 +00001458 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001459 assert(Body);
1460
John McCallf99a6312010-07-21 05:30:47 +00001461 // Enter the cleanup scopes for fields and non-virtual bases.
1462 EnterDtorCleanups(Dtor, Dtor_Base);
1463
1464 // Initialize the vtable pointers before entering the body.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001465 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1466 // Insert the llvm.invariant.group.barrier intrinsic before initializing
1467 // the vptrs to cancel any previous assumptions we might have made.
1468 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1469 CGM.getCodeGenOpts().OptimizationLevel > 0)
1470 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1471 InitializeVTablePointers(Dtor->getParent());
1472 }
John McCallf99a6312010-07-21 05:30:47 +00001473
1474 if (isTryBody)
1475 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1476 else if (Body)
1477 EmitStmt(Body);
1478 else {
1479 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1480 // nothing to do besides what's in the epilogue
1481 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001482 // -fapple-kext must inline any call to this dtor into
1483 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001484 if (getLangOpts().AppleKext)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001485 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001486
John McCallf99a6312010-07-21 05:30:47 +00001487 break;
John McCallb81884d2010-02-19 09:25:03 +00001488 }
1489
John McCallf99a6312010-07-21 05:30:47 +00001490 // Jump out through the epilogue cleanups.
1491 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001492
1493 // Exit the try if applicable.
1494 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001495 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001496}
1497
Lang Hamesbf122742013-02-17 07:22:09 +00001498void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1499 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1500 const Stmt *RootS = AssignOp->getBody();
1501 assert(isa<CompoundStmt>(RootS) &&
1502 "Body of an implicit assignment operator should be compound stmt.");
1503 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1504
1505 LexicalScope Scope(*this, RootCS->getSourceRange());
1506
Xinliang David Lia951e8e2016-02-09 20:02:59 +00001507 incrementProfileCounter(RootCS);
Lang Hamesbf122742013-02-17 07:22:09 +00001508 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001509 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001510 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001511 AM.finish();
1512}
1513
John McCallf99a6312010-07-21 05:30:47 +00001514namespace {
1515 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001516 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001517 CallDtorDelete() {}
1518
Craig Topper4f12f102014-03-12 06:41:41 +00001519 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001520 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1521 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1522 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1523 CGF.getContext().getTagDeclType(ClassDecl));
1524 }
1525 };
1526
David Blaikie7e70d682015-08-18 22:40:54 +00001527 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001528 llvm::Value *ShouldDeleteCondition;
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001529
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001530 public:
1531 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001532 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001533 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001534 }
1535
Craig Topper4f12f102014-03-12 06:41:41 +00001536 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001537 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1538 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1539 llvm::Value *ShouldCallDelete
1540 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1541 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1542
1543 CGF.EmitBlock(callDeleteBB);
1544 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1545 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1546 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1547 CGF.getContext().getTagDeclType(ClassDecl));
1548 CGF.Builder.CreateBr(continueBB);
1549
1550 CGF.EmitBlock(continueBB);
1551 }
1552 };
1553
David Blaikie7e70d682015-08-18 22:40:54 +00001554 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001555 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001556 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001557 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001558
John McCall4bd0fb12011-07-12 16:41:08 +00001559 public:
1560 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1561 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001562 : field(field), destroyer(destroyer),
1563 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001564
Craig Topper4f12f102014-03-12 06:41:41 +00001565 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001566 // Find the address of the field.
John McCall7f416cc2015-09-08 08:05:57 +00001567 Address thisValue = CGF.LoadCXXThisAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001568 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1569 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1570 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001571 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001572
John McCall4bd0fb12011-07-12 16:41:08 +00001573 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001574 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001575 }
1576 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001577
Naomi Musgrave703835c2015-09-16 00:38:22 +00001578 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1579 CharUnits::QuantityType PoisonSize) {
1580 // Pass in void pointer and size of region as arguments to runtime
1581 // function
1582 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1583 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1584
1585 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1586
1587 llvm::FunctionType *FnType =
1588 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1589 llvm::Value *Fn =
1590 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1591 CGF.EmitNounwindRuntimeCall(Fn, Args);
1592 }
1593
1594 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001595 const CXXDestructorDecl *Dtor;
1596
1597 public:
Naomi Musgrave703835c2015-09-16 00:38:22 +00001598 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001599
1600 // Generate function call for handling object poisoning.
1601 // Disables tail call elimination, to prevent the current stack frame
1602 // from disappearing from the stack trace.
1603 void Emit(CodeGenFunction &CGF, Flags flags) override {
1604 const ASTRecordLayout &Layout =
1605 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1606
1607 // Nothing to poison.
1608 if (Layout.getFieldCount() == 0)
1609 return;
1610
1611 // Prevent the current stack frame from disappearing from the stack trace.
1612 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1613
1614 // Construct pointer to region to begin poisoning, and calculate poison
1615 // size, so that only members declared in this class are poisoned.
1616 ASTContext &Context = CGF.getContext();
1617 unsigned fieldIndex = 0;
1618 int startIndex = -1;
1619 // RecordDecl::field_iterator Field;
1620 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1621 // Poison field if it is trivial
1622 if (FieldHasTrivialDestructorBody(Context, Field)) {
1623 // Start sanitizing at this field
1624 if (startIndex < 0)
1625 startIndex = fieldIndex;
1626
1627 // Currently on the last field, and it must be poisoned with the
1628 // current block.
1629 if (fieldIndex == Layout.getFieldCount() - 1) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001630 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001631 }
1632 } else if (startIndex >= 0) {
1633 // No longer within a block of memory to poison, so poison the block
Naomi Musgrave703835c2015-09-16 00:38:22 +00001634 PoisonMembers(CGF, startIndex, fieldIndex);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001635 // Re-set the start index
1636 startIndex = -1;
1637 }
1638 fieldIndex += 1;
1639 }
1640 }
1641
1642 private:
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001643 /// \param layoutStartOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001644 /// start poisoning (inclusive)
NAKAMURA Takumif6cef72f2015-09-04 05:19:31 +00001645 /// \param layoutEndOffset index of the ASTRecordLayout field to
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001646 /// end poisoning (exclusive)
Naomi Musgrave703835c2015-09-16 00:38:22 +00001647 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001648 unsigned layoutEndOffset) {
1649 ASTContext &Context = CGF.getContext();
1650 const ASTRecordLayout &Layout =
1651 Context.getASTRecordLayout(Dtor->getParent());
1652
1653 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1654 CGF.SizeTy,
1655 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1656 .getQuantity());
1657
1658 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1659 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1660 OffsetSizePtr);
1661
1662 CharUnits::QuantityType PoisonSize;
1663 if (layoutEndOffset >= Layout.getFieldCount()) {
1664 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1665 Context.toCharUnitsFromBits(
1666 Layout.getFieldOffset(layoutStartOffset))
1667 .getQuantity();
1668 } else {
1669 PoisonSize = Context.toCharUnitsFromBits(
1670 Layout.getFieldOffset(layoutEndOffset) -
1671 Layout.getFieldOffset(layoutStartOffset))
1672 .getQuantity();
1673 }
1674
1675 if (PoisonSize == 0)
1676 return;
1677
Naomi Musgrave703835c2015-09-16 00:38:22 +00001678 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001679 }
1680 };
Naomi Musgrave703835c2015-09-16 00:38:22 +00001681
1682 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1683 const CXXDestructorDecl *Dtor;
1684
1685 public:
1686 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1687
1688 // Generate function call for handling vtable pointer poisoning.
1689 void Emit(CodeGenFunction &CGF, Flags flags) override {
1690 assert(Dtor->getParent()->isDynamicClass());
NAKAMURA Takumiee82b492015-09-16 06:26:56 +00001691 (void)Dtor;
Naomi Musgrave703835c2015-09-16 00:38:22 +00001692 ASTContext &Context = CGF.getContext();
1693 // Poison vtable and vtable ptr if they exist for this class.
1694 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1695
1696 CharUnits::QuantityType PoisonSize =
1697 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1698 // Pass in void pointer and size of region as arguments to runtime
1699 // function
1700 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1701 }
1702 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001703} // end anonymous namespace
John McCallf99a6312010-07-21 05:30:47 +00001704
Hans Wennborgdeff7032013-12-18 01:39:59 +00001705/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001706/// destructor. This is to call destructors on members and base classes
1707/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001708void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1709 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001710 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1711 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001712
John McCallf99a6312010-07-21 05:30:47 +00001713 // The deleting-destructor phase just needs to call the appropriate
1714 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001715 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001716 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001717 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001718 if (CXXStructorImplicitParamValue) {
1719 // If there is an implicit param to the deleting dtor, it's a boolean
1720 // telling whether we should call delete at the end of the dtor.
1721 EHStack.pushCleanup<CallDtorDeleteConditional>(
1722 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1723 } else {
1724 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1725 }
John McCall5c60a6f2010-02-18 19:59:28 +00001726 return;
1727 }
1728
John McCallf99a6312010-07-21 05:30:47 +00001729 const CXXRecordDecl *ClassDecl = DD->getParent();
1730
Richard Smith20104042011-09-18 12:11:43 +00001731 // Unions have no bases and do not call field destructors.
1732 if (ClassDecl->isUnion())
1733 return;
1734
John McCallf99a6312010-07-21 05:30:47 +00001735 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001736 if (DtorType == Dtor_Complete) {
Naomi Musgrave703835c2015-09-16 00:38:22 +00001737 // Poison the vtable pointer such that access after the base
1738 // and member destructors are invoked is invalid.
1739 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1740 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1741 ClassDecl->isPolymorphic())
1742 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
John McCallf99a6312010-07-21 05:30:47 +00001743
1744 // We push them in the forward order so that they'll be popped in
1745 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001746 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001747 CXXRecordDecl *BaseClassDecl
1748 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001749
John McCall5c60a6f2010-02-18 19:59:28 +00001750 // Ignore trivial destructors.
1751 if (BaseClassDecl->hasTrivialDestructor())
1752 continue;
John McCallf99a6312010-07-21 05:30:47 +00001753
John McCallcda666c2010-07-21 07:22:38 +00001754 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1755 BaseClassDecl,
1756 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001757 }
John McCallf99a6312010-07-21 05:30:47 +00001758
John McCall5c60a6f2010-02-18 19:59:28 +00001759 return;
1760 }
1761
1762 assert(DtorType == Dtor_Base);
Naomi Musgrave703835c2015-09-16 00:38:22 +00001763 // Poison the vtable pointer if it has no virtual bases, but inherits
1764 // virtual functions.
1765 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1766 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1767 ClassDecl->isPolymorphic())
1768 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001769
John McCallf99a6312010-07-21 05:30:47 +00001770 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001771 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001772 // Ignore virtual bases.
1773 if (Base.isVirtual())
1774 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001775
John McCallf99a6312010-07-21 05:30:47 +00001776 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001777
John McCallf99a6312010-07-21 05:30:47 +00001778 // Ignore trivial destructors.
1779 if (BaseClassDecl->hasTrivialDestructor())
1780 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001781
John McCallcda666c2010-07-21 07:22:38 +00001782 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1783 BaseClassDecl,
1784 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001785 }
1786
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001787 // Poison fields such that access after their destructors are
1788 // invoked, and before the base class destructor runs, is invalid.
1789 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1790 SanOpts.has(SanitizerKind::Memory))
Naomi Musgrave703835c2015-09-16 00:38:22 +00001791 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001792
John McCallf99a6312010-07-21 05:30:47 +00001793 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001794 for (const auto *Field : ClassDecl->fields()) {
1795 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001796 QualType::DestructionKind dtorKind = type.isDestructedType();
1797 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001798
Richard Smith921bd202012-02-26 09:11:52 +00001799 // Anonymous union members do not have their destructors called.
1800 const RecordType *RT = type->getAsUnionType();
1801 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1802
John McCall4bd0fb12011-07-12 16:41:08 +00001803 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001804 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001805 getDestroyer(dtorKind),
1806 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001807 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001808}
1809
John McCallf677a8e2011-07-13 06:10:41 +00001810/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1811/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001812///
John McCallf677a8e2011-07-13 06:10:41 +00001813/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001814/// \param arrayType the type of the array to initialize
1815/// \param arrayBegin an arrayType*
1816/// \param zeroInitialize true if each element should be
1817/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001818void CodeGenFunction::EmitCXXAggrConstructorCall(
Alexey Bataeve7545b32016-04-29 09:39:50 +00001819 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
John McCall7f416cc2015-09-08 08:05:57 +00001820 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001821 QualType elementType;
1822 llvm::Value *numElements =
1823 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001824
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001825 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001826}
1827
John McCallf677a8e2011-07-13 06:10:41 +00001828/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1829/// constructor for each of several members of an array.
1830///
1831/// \param ctor the constructor to call for each element
1832/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001833/// may be zero
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001834/// \param arrayBase a T*, where T is the type constructed by ctor
John McCallf677a8e2011-07-13 06:10:41 +00001835/// \param zeroInitialize true if each element should be
1836/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001837void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1838 llvm::Value *numElements,
John McCall7f416cc2015-09-08 08:05:57 +00001839 Address arrayBase,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001840 const CXXConstructExpr *E,
1841 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001842 // It's legal for numElements to be zero. This can happen both
1843 // dynamically, because x can be zero in 'new A[x]', and statically,
1844 // because of GCC extensions that permit zero-length arrays. There
1845 // are probably legitimate places where we could assume that this
1846 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001847 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001848
1849 // Optimize for a constant count.
1850 llvm::ConstantInt *constantCount
1851 = dyn_cast<llvm::ConstantInt>(numElements);
1852 if (constantCount) {
1853 // Just skip out if the constant count is zero.
1854 if (constantCount->isZero()) return;
1855
1856 // Otherwise, emit the check.
1857 } else {
1858 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1859 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1860 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1861 EmitBlock(loopBB);
1862 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001863
John McCallf677a8e2011-07-13 06:10:41 +00001864 // Find the end of the array.
John McCall7f416cc2015-09-08 08:05:57 +00001865 llvm::Value *arrayBegin = arrayBase.getPointer();
John McCallf677a8e2011-07-13 06:10:41 +00001866 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1867 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001868
John McCallf677a8e2011-07-13 06:10:41 +00001869 // Enter the loop, setting up a phi for the current location to initialize.
1870 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1871 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1872 EmitBlock(loopBB);
1873 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1874 "arrayctor.cur");
1875 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001876
Anders Carlsson27da15b2010-01-01 20:29:01 +00001877 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001878
John McCall7f416cc2015-09-08 08:05:57 +00001879 // The alignment of the base, adjusted by the size of a single element,
1880 // provides a conservative estimate of the alignment of every element.
1881 // (This assumes we never start tracking offsetted alignments.)
1882 //
1883 // Note that these are complete objects and so we don't need to
1884 // use the non-virtual size or alignment.
John McCallf677a8e2011-07-13 06:10:41 +00001885 QualType type = getContext().getTypeDeclType(ctor->getParent());
John McCall7f416cc2015-09-08 08:05:57 +00001886 CharUnits eltAlignment =
1887 arrayBase.getAlignment()
1888 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1889 Address curAddr = Address(cur, eltAlignment);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001890
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001891 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001892 if (zeroInitialize)
John McCall7f416cc2015-09-08 08:05:57 +00001893 EmitNullInitialization(curAddr, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001894
1895 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001896 // There are two contexts in which temporaries are destroyed at a different
1897 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001898 // default constructor is called to initialize an element of an array.
1899 // If the constructor has one or more default arguments, the destruction of
1900 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001901 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001902
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001903 {
John McCallbd309292010-07-06 01:34:17 +00001904 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001905
John McCallf677a8e2011-07-13 06:10:41 +00001906 // Evaluate the constructor and its arguments in a regular
1907 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001908 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001909 !ctor->getParent()->hasTrivialDestructor()) {
1910 Destroyer *destroyer = destroyCXXObject;
John McCall7f416cc2015-09-08 08:05:57 +00001911 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1912 *destroyer);
John McCallf677a8e2011-07-13 06:10:41 +00001913 }
1914
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001915 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
John McCall7f416cc2015-09-08 08:05:57 +00001916 /*Delegating=*/false, curAddr, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001917 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001918
John McCallf677a8e2011-07-13 06:10:41 +00001919 // Go to the next element.
1920 llvm::Value *next =
1921 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1922 "arrayctor.next");
1923 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001924
John McCallf677a8e2011-07-13 06:10:41 +00001925 // Check whether that's the end of the loop.
1926 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1927 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1928 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001929
John McCall6549b312011-07-13 07:37:11 +00001930 // Patch the earlier check to skip over the loop.
1931 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1932
John McCallf677a8e2011-07-13 06:10:41 +00001933 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001934}
1935
John McCall82fe67b2011-07-09 01:37:26 +00001936void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001937 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00001938 QualType type) {
1939 const RecordType *rtype = type->castAs<RecordType>();
1940 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1941 const CXXDestructorDecl *dtor = record->getDestructor();
1942 assert(!dtor->isTrivial());
1943 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001944 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001945}
1946
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001947void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1948 CXXCtorType Type,
1949 bool ForVirtualBase,
John McCall7f416cc2015-09-08 08:05:57 +00001950 bool Delegating, Address This,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001951 const CXXConstructExpr *E) {
Richard Smith5179eb72016-06-28 19:03:57 +00001952 CallArgList Args;
1953
1954 // Push the this ptr.
1955 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1956
1957 // If this is a trivial constructor, emit a memcpy now before we lose
1958 // the alignment information on the argument.
1959 // FIXME: It would be better to preserve alignment information into CallArg.
1960 if (isMemcpyEquivalentSpecialMember(D)) {
1961 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1962
1963 const Expr *Arg = E->getArg(0);
1964 QualType SrcTy = Arg->getType();
1965 Address Src = EmitLValue(Arg).getAddress();
1966 QualType DestTy = getContext().getTypeDeclType(D->getParent());
1967 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
1968 return;
1969 }
1970
1971 // Add the rest of the user-supplied arguments.
1972 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Hans Wennborg27dcc6c2017-02-01 02:21:07 +00001973 EvaluationOrder Order = E->isListInitialization()
1974 ? EvaluationOrder::ForceLeftToRight
1975 : EvaluationOrder::Default;
1976 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
1977 /*ParamsToSkip*/ 0, Order);
Richard Smith5179eb72016-06-28 19:03:57 +00001978
1979 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
1980}
1981
1982static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
1983 const CXXConstructorDecl *Ctor,
1984 CXXCtorType Type, CallArgList &Args) {
1985 // We can't forward a variadic call.
1986 if (Ctor->isVariadic())
1987 return false;
1988
1989 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1990 // If the parameters are callee-cleanup, it's not safe to forward.
1991 for (auto *P : Ctor->parameters())
1992 if (P->getType().isDestructedType())
1993 return false;
1994
1995 // Likewise if they're inalloca.
1996 const CGFunctionInfo &Info =
George Burgess IVd0a9e802017-02-23 22:07:35 +00001997 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
Richard Smith5179eb72016-06-28 19:03:57 +00001998 if (Info.usesInAlloca())
1999 return false;
2000 }
2001
2002 // Anything else should be OK.
2003 return true;
2004}
2005
2006void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2007 CXXCtorType Type,
2008 bool ForVirtualBase,
2009 bool Delegating,
2010 Address This,
2011 CallArgList &Args) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002012 const CXXRecordDecl *ClassDecl = D->getParent();
2013
Richard Smith419bd092015-04-29 19:26:57 +00002014 // C++11 [class.mfct.non-static]p2:
2015 // If a non-static member function of a class X is called for an object that
2016 // is not of type X, or of a type derived from X, the behavior is undefined.
2017 // FIXME: Provide a source location here.
John McCall7f416cc2015-09-08 08:05:57 +00002018 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002019 This.getPointer(), getContext().getRecordType(ClassDecl));
John McCallca972cd2010-02-06 00:25:16 +00002020
Richard Smith419bd092015-04-29 19:26:57 +00002021 if (D->isTrivial() && D->isDefaultConstructor()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002022 assert(Args.size() == 1 && "trivial default ctor with args");
Richard Smith419bd092015-04-29 19:26:57 +00002023 return;
2024 }
2025
2026 // If this is a trivial constructor, just emit what's needed. If this is a
2027 // union copy constructor, we must emit a memcpy, because the AST does not
2028 // model that copy.
2029 if (isMemcpyEquivalentSpecialMember(D)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002030 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00002031
Richard Smith5179eb72016-06-28 19:03:57 +00002032 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2033 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002034 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
David Majnemerfd1e7392015-02-03 23:04:06 +00002035 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002036 return;
2037 }
2038
George Burgess IVd0a9e802017-02-23 22:07:35 +00002039 bool PassPrototypeArgs = true;
Richard Smith5179eb72016-06-28 19:03:57 +00002040 // Check whether we can actually emit the constructor before trying to do so.
2041 if (auto Inherited = D->getInheritedConstructor()) {
George Burgess IVd0a9e802017-02-23 22:07:35 +00002042 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2043 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
Richard Smith5179eb72016-06-28 19:03:57 +00002044 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2045 Delegating, Args);
2046 return;
2047 }
2048 }
Reid Kleckner89077a12013-12-17 19:46:40 +00002049
2050 // Insert any ABI-specific implicit constructor arguments.
George Burgess IVf203dbf2017-02-22 20:28:02 +00002051 CGCXXABI::AddedStructorArgs ExtraArgs =
2052 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2053 Delegating, Args);
Reid Kleckner89077a12013-12-17 19:46:40 +00002054
2055 // Emit the call.
John McCallb92ab1a2016-10-26 23:46:34 +00002056 llvm::Constant *CalleePtr =
2057 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
George Burgess IVf203dbf2017-02-22 20:28:02 +00002058 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
George Burgess IVd0a9e802017-02-23 22:07:35 +00002059 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
John McCallb92ab1a2016-10-26 23:46:34 +00002060 CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2061 EmitCall(Info, Callee, ReturnValueSlot(), Args);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002062
2063 // Generate vtable assumptions if we're constructing a complete object
2064 // with a vtable. We don't do this for base subobjects for two reasons:
2065 // first, it's incorrect for classes with virtual bases, and second, we're
2066 // about to overwrite the vptrs anyway.
2067 // We also have to make sure if we can refer to vtable:
2068 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2069 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2070 // sure that definition of vtable is not hidden,
2071 // then we are always safe to refer to it.
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002072 // FIXME: It looks like InstCombine is very inefficient on dealing with
2073 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002074 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2075 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
Piotr Padlewski69dc9712015-09-28 20:30:22 +00002076 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2077 CGM.getCodeGenOpts().StrictVTablePointers)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002078 EmitVTableAssumptionLoads(ClassDecl, This);
2079}
2080
Richard Smith5179eb72016-06-28 19:03:57 +00002081void CodeGenFunction::EmitInheritedCXXConstructorCall(
2082 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2083 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2084 CallArgList Args;
2085 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2086 /*NeedsCopy=*/false);
2087
2088 // Forward the parameters.
2089 if (InheritedFromVBase &&
2090 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2091 // Nothing to do; this construction is not responsible for constructing
2092 // the base class containing the inherited constructor.
2093 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2094 // have constructor variants?
2095 Args.push_back(ThisArg);
2096 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2097 // The inheriting constructor was inlined; just inject its arguments.
2098 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2099 "wrong number of parameters for inherited constructor call");
2100 Args = CXXInheritedCtorInitExprArgs;
2101 Args[0] = ThisArg;
2102 } else {
2103 // The inheriting constructor was not inlined. Emit delegating arguments.
2104 Args.push_back(ThisArg);
2105 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2106 assert(OuterCtor->getNumParams() == D->getNumParams());
2107 assert(!OuterCtor->isVariadic() && "should have been inlined");
2108
2109 for (const auto *Param : OuterCtor->parameters()) {
2110 assert(getContext().hasSameUnqualifiedType(
2111 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2112 Param->getType()));
2113 EmitDelegateCallArg(Args, Param, E->getLocation());
2114
2115 // Forward __attribute__(pass_object_size).
2116 if (Param->hasAttr<PassObjectSizeAttr>()) {
2117 auto *POSParam = SizeArguments[Param];
2118 assert(POSParam && "missing pass_object_size value for forwarding");
2119 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2120 }
2121 }
2122 }
2123
2124 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2125 This, Args);
2126}
2127
2128void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2129 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2130 bool Delegating, CallArgList &Args) {
2131 InlinedInheritingConstructorScope Scope(*this, GlobalDecl(Ctor, CtorType));
2132
2133 // Save the arguments to be passed to the inherited constructor.
2134 CXXInheritedCtorInitExprArgs = Args;
2135
2136 FunctionArgList Params;
2137 QualType RetType = BuildFunctionArgList(CurGD, Params);
2138 FnRetTy = RetType;
2139
2140 // Insert any ABI-specific implicit constructor arguments.
2141 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2142 ForVirtualBase, Delegating, Args);
2143
2144 // Emit a simplified prolog. We only need to emit the implicit params.
2145 assert(Args.size() >= Params.size() && "too few arguments for call");
2146 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2147 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2148 const RValue &RV = Args[I].RV;
2149 assert(!RV.isComplex() && "complex indirect params not supported");
2150 ParamValue Val = RV.isScalar()
2151 ? ParamValue::forDirect(RV.getScalarVal())
2152 : ParamValue::forIndirect(RV.getAggregateAddress());
2153 EmitParmDecl(*Params[I], Val, I + 1);
2154 }
2155 }
2156
2157 // Create a return value slot if the ABI implementation wants one.
2158 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2159 // value instead.
2160 if (!RetType->isVoidType())
2161 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2162
2163 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2164 CXXThisValue = CXXABIThisValue;
2165
2166 // Directly emit the constructor initializers.
2167 EmitCtorPrologue(Ctor, CtorType, Params);
2168}
2169
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002170void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2171 llvm::Value *VTableGlobal =
2172 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2173 if (!VTableGlobal)
2174 return;
2175
2176 // We can just use the base offset in the complete class.
2177 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2178
2179 if (!NonVirtualOffset.isZero())
2180 This =
2181 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2182 Vptr.VTableClass, Vptr.NearestVBase);
2183
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002184 llvm::Value *VPtrValue =
2185 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002186 llvm::Value *Cmp =
2187 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2188 Builder.CreateAssumption(Cmp);
2189}
2190
2191void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2192 Address This) {
2193 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2194 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2195 EmitVTableAssumptionLoad(Vptr, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002196}
2197
John McCallf8ff7b92010-02-23 00:48:20 +00002198void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002199CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002200 Address This, Address Src,
2201 const CXXConstructExpr *E) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002202 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002203
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002204 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002205
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002206 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +00002207 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00002208
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002209 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00002210 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00002211 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002212 Src = Builder.CreateBitCast(Src, t);
John McCall7f416cc2015-09-08 08:05:57 +00002213 Args.add(RValue::get(Src.getPointer()), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00002214
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002215 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00002216 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002217 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002218
Richard Smith5179eb72016-06-28 19:03:57 +00002219 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00002220}
2221
2222void
John McCallf8ff7b92010-02-23 00:48:20 +00002223CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2224 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002225 const FunctionArgList &Args,
2226 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00002227 CallArgList DelegateArgs;
2228
2229 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2230 assert(I != E && "no parameters to constructor");
2231
2232 // this
Richard Smith5179eb72016-06-28 19:03:57 +00002233 Address This = LoadCXXThisAddress();
2234 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00002235 ++I;
2236
Richard Smith5179eb72016-06-28 19:03:57 +00002237 // FIXME: The location of the VTT parameter in the parameter list is
2238 // specific to the Itanium ABI and shouldn't be hardcoded here.
2239 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2240 assert(I != E && "cannot skip vtt parameter, already done with args");
2241 assert((*I)->getType()->isPointerType() &&
2242 "skipping parameter not of vtt type");
2243 ++I;
John McCallf8ff7b92010-02-23 00:48:20 +00002244 }
2245
2246 // Explicit arguments.
2247 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00002248 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002249 // FIXME: per-argument source location
2250 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00002251 }
2252
Richard Smith5179eb72016-06-28 19:03:57 +00002253 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2254 /*Delegating=*/true, This, DelegateArgs);
John McCallf8ff7b92010-02-23 00:48:20 +00002255}
2256
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002257namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002258 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002259 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002260 Address Addr;
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002261 CXXDtorType Type;
2262
John McCall7f416cc2015-09-08 08:05:57 +00002263 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002264 CXXDtorType Type)
2265 : Dtor(D), Addr(Addr), Type(Type) {}
2266
Craig Topper4f12f102014-03-12 06:41:41 +00002267 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002268 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002269 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002270 }
2271 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002272} // end anonymous namespace
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002273
Alexis Hunt61bc1732011-05-01 07:04:31 +00002274void
2275CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2276 const FunctionArgList &Args) {
2277 assert(Ctor->isDelegatingConstructor());
2278
John McCall7f416cc2015-09-08 08:05:57 +00002279 Address ThisPtr = LoadCXXThisAddress();
Alexis Hunt61bc1732011-05-01 07:04:31 +00002280
John McCall31168b02011-06-15 23:02:42 +00002281 AggValueSlot AggSlot =
John McCall7f416cc2015-09-08 08:05:57 +00002282 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002283 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002284 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002285 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002286
2287 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002288
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002289 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002290 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002291 CXXDtorType Type =
2292 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2293
2294 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2295 ClassDecl->getDestructor(),
2296 ThisPtr, Type);
2297 }
2298}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002299
Anders Carlsson27da15b2010-01-01 20:29:01 +00002300void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2301 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002302 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002303 bool Delegating,
John McCall7f416cc2015-09-08 08:05:57 +00002304 Address This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002305 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2306 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002307}
2308
John McCall53cad2e2010-07-21 01:41:18 +00002309namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002310 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002311 const CXXDestructorDecl *Dtor;
John McCall7f416cc2015-09-08 08:05:57 +00002312 Address Addr;
John McCall53cad2e2010-07-21 01:41:18 +00002313
John McCall7f416cc2015-09-08 08:05:57 +00002314 CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
John McCall53cad2e2010-07-21 01:41:18 +00002315 : Dtor(D), Addr(Addr) {}
2316
Craig Topper4f12f102014-03-12 06:41:41 +00002317 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002318 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002319 /*ForVirtualBase=*/false,
2320 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002321 }
2322 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002323} // end anonymous namespace
John McCall53cad2e2010-07-21 01:41:18 +00002324
John McCall8680f872010-07-21 06:29:51 +00002325void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
John McCall7f416cc2015-09-08 08:05:57 +00002326 Address Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002327 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002328}
2329
John McCall7f416cc2015-09-08 08:05:57 +00002330void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
John McCallbd309292010-07-06 01:34:17 +00002331 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2332 if (!ClassDecl) return;
2333 if (ClassDecl->hasTrivialDestructor()) return;
2334
2335 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002336 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002337 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002338}
2339
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002340void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
Anders Carlssone87fae92010-03-28 19:40:00 +00002341 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002342 llvm::Value *VTableAddressPoint =
2343 CGM.getCXXABI().getVTableAddressPointInStructor(
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002344 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2345
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002346 if (!VTableAddressPoint)
2347 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002348
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002349 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002350 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002351 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002352
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002353 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002354 // We need to use the virtual base offset offset because the virtual base
2355 // might have a different offset in the most derived class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002356
2357 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2358 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2359 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002360 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002361 // We can just use the base offset in the complete class.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002362 NonVirtualOffset = Vptr.Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002363 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002364
Anders Carlssonc58fb552010-05-03 00:29:58 +00002365 // Apply the offsets.
John McCall7f416cc2015-09-08 08:05:57 +00002366 Address VTableField = LoadCXXThisAddress();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002367
Ken Dyckcfc332c2011-03-23 00:45:26 +00002368 if (!NonVirtualOffset.isZero() || VirtualOffset)
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002369 VTableField = ApplyNonVirtualAndVirtualOffset(
2370 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2371 Vptr.NearestVBase);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002372
Reid Kleckner8d585132014-12-03 21:00:21 +00002373 // Finally, store the address point. Use the same LLVM types as the field to
2374 // support optimization.
2375 llvm::Type *VTablePtrTy =
2376 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2377 ->getPointerTo()
2378 ->getPointerTo();
2379 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2380 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002381
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002382 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002383 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr());
2384 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2385 CGM.getCodeGenOpts().StrictVTablePointers)
2386 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
Anders Carlssone87fae92010-03-28 19:40:00 +00002387}
2388
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002389CodeGenFunction::VPtrsVector
2390CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2391 CodeGenFunction::VPtrsVector VPtrsResult;
2392 VisitedVirtualBasesSetTy VBases;
2393 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2394 /*NearestVBase=*/nullptr,
2395 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2396 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2397 VPtrsResult);
2398 return VPtrsResult;
2399}
2400
2401void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2402 const CXXRecordDecl *NearestVBase,
2403 CharUnits OffsetFromNearestVBase,
2404 bool BaseIsNonVirtualPrimaryBase,
2405 const CXXRecordDecl *VTableClass,
2406 VisitedVirtualBasesSetTy &VBases,
2407 VPtrsVector &Vptrs) {
Anders Carlssond5895932010-03-28 21:07:49 +00002408 // If this base is a non-virtual primary base the address point has already
2409 // been set.
2410 if (!BaseIsNonVirtualPrimaryBase) {
2411 // Initialize the vtable pointer for this base.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002412 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2413 Vptrs.push_back(Vptr);
Anders Carlssond5895932010-03-28 21:07:49 +00002414 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002415
Anders Carlssond5895932010-03-28 21:07:49 +00002416 const CXXRecordDecl *RD = Base.getBase();
2417
2418 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002419 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002420 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002421 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002422
2423 // Ignore classes without a vtable.
2424 if (!BaseDecl->isDynamicClass())
2425 continue;
2426
Ken Dyck3fb4c892011-03-23 01:04:18 +00002427 CharUnits BaseOffset;
2428 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002429 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002430
Aaron Ballman574705e2014-03-13 15:41:46 +00002431 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002432 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002433 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002434 continue;
2435
Justin Bogner1cd11f12015-05-20 15:53:59 +00002436 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002437 getContext().getASTRecordLayout(VTableClass);
2438
Ken Dyck3fb4c892011-03-23 01:04:18 +00002439 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2440 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002441 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002442 } else {
2443 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2444
Ken Dyck16ffcac2011-03-24 01:21:01 +00002445 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002446 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002447 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002448 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002449 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002450
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002451 getVTablePointers(
2452 BaseSubobject(BaseDecl, BaseOffset),
2453 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2454 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
Anders Carlssond5895932010-03-28 21:07:49 +00002455 }
2456}
2457
2458void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2459 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002460 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002461 return;
2462
Anders Carlssond5895932010-03-28 21:07:49 +00002463 // Initialize the vtable pointers for this class and all of its bases.
Piotr Padlewskid679d7e2015-09-15 00:37:06 +00002464 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2465 for (const VPtr &Vptr : getVTablePointers(RD))
2466 InitializeVTablePointer(Vptr);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002467
2468 if (RD->getNumVBases())
2469 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002470}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002471
John McCall7f416cc2015-09-08 08:05:57 +00002472llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002473 llvm::Type *VTableTy,
2474 const CXXRecordDecl *RD) {
2475 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002476 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002477 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr());
2478
2479 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2480 CGM.getCodeGenOpts().StrictVTablePointers)
2481 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2482
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002483 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002484}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002485
Peter Collingbourned2926c92015-03-14 02:42:25 +00002486// If a class has a single non-virtual base and does not introduce or override
2487// virtual member functions or fields, it will have the same layout as its base.
2488// This function returns the least derived such class.
2489//
2490// Casting an instance of a base class to such a derived class is technically
2491// undefined behavior, but it is a relatively common hack for introducing member
2492// functions on class instances with specific properties (e.g. llvm::Operator)
2493// that works under most compilers and should not have security implications, so
2494// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2495static const CXXRecordDecl *
2496LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2497 if (!RD->field_empty())
2498 return RD;
2499
2500 if (RD->getNumVBases() != 0)
2501 return RD;
2502
2503 if (RD->getNumBases() != 1)
2504 return RD;
2505
2506 for (const CXXMethodDecl *MD : RD->methods()) {
2507 if (MD->isVirtual()) {
2508 // Virtual member functions are only ok if they are implicit destructors
2509 // because the implicit destructor will have the same semantics as the
2510 // base class's destructor if no fields are added.
2511 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2512 continue;
2513 return RD;
2514 }
2515 }
2516
2517 return LeastDerivedClassWithSameLayout(
2518 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2519}
2520
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002521void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2522 llvm::Value *VTable,
2523 SourceLocation Loc) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002524 if (CGM.getCodeGenOpts().WholeProgramVTables &&
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002525 CGM.HasHiddenLTOVisibility(RD)) {
Peter Collingbournefb532b92016-02-24 20:46:36 +00002526 llvm::Metadata *MD =
2527 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002528 llvm::Value *TypeId =
Peter Collingbournefb532b92016-02-24 20:46:36 +00002529 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2530
2531 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002532 llvm::Value *TypeTest =
2533 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2534 {CastedVTable, TypeId});
2535 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
Peter Collingbournefb532b92016-02-24 20:46:36 +00002536 }
2537
2538 if (SanOpts.has(SanitizerKind::CFIVCall))
2539 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2540}
2541
2542void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002543 llvm::Value *VTable,
2544 CFITypeCheckKind TCK,
2545 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002546 if (!SanOpts.has(SanitizerKind::CFICastStrict))
Peter Collingbournefb532b92016-02-24 20:46:36 +00002547 RD = LeastDerivedClassWithSameLayout(RD);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002548
Peter Collingbournefb532b92016-02-24 20:46:36 +00002549 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002550}
2551
Peter Collingbourned2926c92015-03-14 02:42:25 +00002552void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2553 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002554 bool MayBeNull,
2555 CFITypeCheckKind TCK,
2556 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002557 if (!getLangOpts().CPlusPlus)
2558 return;
2559
2560 auto *ClassTy = T->getAs<RecordType>();
2561 if (!ClassTy)
2562 return;
2563
2564 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2565
2566 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2567 return;
2568
Peter Collingbourned2926c92015-03-14 02:42:25 +00002569 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2570 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2571
Hans Wennborgdcfba332015-10-06 23:40:43 +00002572 llvm::BasicBlock *ContBlock = nullptr;
Peter Collingbourned2926c92015-03-14 02:42:25 +00002573
2574 if (MayBeNull) {
2575 llvm::Value *DerivedNotNull =
2576 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2577
2578 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2579 ContBlock = createBasicBlock("cast.cont");
2580
2581 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2582
2583 EmitBlock(CheckBlock);
2584 }
2585
John McCall7f416cc2015-09-08 08:05:57 +00002586 llvm::Value *VTable =
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00002587 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2588
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002589 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002590
2591 if (MayBeNull) {
2592 Builder.CreateBr(ContBlock);
2593 EmitBlock(ContBlock);
2594 }
2595}
2596
2597void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002598 llvm::Value *VTable,
2599 CFITypeCheckKind TCK,
2600 SourceLocation Loc) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +00002601 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2602 !CGM.HasHiddenLTOVisibility(RD))
2603 return;
2604
2605 std::string TypeName = RD->getQualifiedNameAsString();
2606 if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName))
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002607 return;
2608
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002609 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00002610 llvm::SanitizerStatKind SSK;
2611 switch (TCK) {
2612 case CFITCK_VCall:
2613 SSK = llvm::SanStat_CFI_VCall;
2614 break;
2615 case CFITCK_NVCall:
2616 SSK = llvm::SanStat_CFI_NVCall;
2617 break;
2618 case CFITCK_DerivedCast:
2619 SSK = llvm::SanStat_CFI_DerivedCast;
2620 break;
2621 case CFITCK_UnrelatedCast:
2622 SSK = llvm::SanStat_CFI_UnrelatedCast;
2623 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002624 case CFITCK_ICall:
2625 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbournedc134532016-01-16 00:31:22 +00002626 }
2627 EmitSanitizerStatReport(SSK);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002628
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002629 llvm::Metadata *MD =
2630 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002631 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002632
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002633 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002634 llvm::Value *TypeTest = Builder.CreateCall(
2635 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002636
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002637 SanitizerMask M;
2638 switch (TCK) {
2639 case CFITCK_VCall:
2640 M = SanitizerKind::CFIVCall;
2641 break;
2642 case CFITCK_NVCall:
2643 M = SanitizerKind::CFINVCall;
2644 break;
2645 case CFITCK_DerivedCast:
2646 M = SanitizerKind::CFIDerivedCast;
2647 break;
2648 case CFITCK_UnrelatedCast:
2649 M = SanitizerKind::CFIUnrelatedCast;
2650 break;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002651 case CFITCK_ICall:
2652 llvm_unreachable("not expecting CFITCK_ICall");
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002653 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002654
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002655 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002656 llvm::ConstantInt::get(Int8Ty, TCK),
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002657 EmitCheckSourceLocation(Loc),
2658 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002659 };
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002660
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002661 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2662 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2663 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002664 return;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002665 }
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002666
2667 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002668 EmitTrapCheck(TypeTest);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002669 return;
2670 }
2671
2672 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2673 CGM.getLLVMContext(),
2674 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002675 llvm::Value *ValidVtable = Builder.CreateCall(
2676 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002677 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2678 StaticData, {CastedVTable, ValidVtable});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002679}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002680
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002681bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2682 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2683 !SanOpts.has(SanitizerKind::CFIVCall) ||
2684 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2685 !CGM.HasHiddenLTOVisibility(RD))
2686 return false;
2687
2688 std::string TypeName = RD->getQualifiedNameAsString();
2689 return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName);
2690}
2691
2692llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2693 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2694 SanitizerScope SanScope(this);
2695
2696 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2697
2698 llvm::Metadata *MD =
2699 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2700 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2701
2702 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2703 llvm::Value *CheckedLoad = Builder.CreateCall(
2704 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2705 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2706 TypeId});
2707 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2708
2709 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002710 SanitizerHandler::CFICheckFail, nullptr, nullptr);
Peter Collingbourne0ca03632016-06-25 00:24:06 +00002711
2712 return Builder.CreateBitCast(
2713 Builder.CreateExtractValue(CheckedLoad, 0),
2714 cast<llvm::PointerType>(VTable->getType())->getElementType());
2715}
2716
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002717bool
2718CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2719 const CXXMethodDecl *MD) {
2720 // When building with -fapple-kext, all calls must go through the vtable since
2721 // the kernel linker can do runtime patching of vtables.
2722 if (getLangOpts().AppleKext)
2723 return false;
2724
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002725 // If the member function is marked 'final', we know that it can't be
Richard Smitha2716862016-11-11 01:01:31 +00002726 // overridden and can therefore devirtualize it unless it's pure virtual.
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002727 if (MD->hasAttr<FinalAttr>())
Richard Smitha2716862016-11-11 01:01:31 +00002728 return !MD->isPure();
Vedant Kumar2d38ae62016-10-20 18:44:14 +00002729
Richard Smith018ac392016-11-03 18:55:18 +00002730 // If the base expression (after skipping derived-to-base conversions) is a
2731 // class prvalue, then we can devirtualize.
2732 Base = Base->getBestDynamicClassTypeExpr();
2733 if (Base->isRValue() && Base->getType()->isRecordType())
2734 return true;
2735
Richard Smitha2716862016-11-11 01:01:31 +00002736 // If we don't even know what we would call, we can't devirtualize.
2737 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2738 if (!BestDynamicDecl)
2739 return false;
Anders Carlssonc36783e2011-05-08 20:32:23 +00002740
Richard Smitha2716862016-11-11 01:01:31 +00002741 // There may be a method corresponding to MD in a derived class.
2742 const CXXMethodDecl *DevirtualizedMethod =
2743 MD->getCorrespondingMethodInClass(BestDynamicDecl);
2744
2745 // If that method is pure virtual, we can't devirtualize. If this code is
2746 // reached, the result would be UB, not a direct call to the derived class
2747 // function, and we can't assume the derived class function is defined.
2748 if (DevirtualizedMethod->isPure())
2749 return false;
2750
2751 // If that method is marked final, we can devirtualize it.
2752 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2753 return true;
Anders Carlssonc36783e2011-05-08 20:32:23 +00002754
2755 // Similarly, if the class itself is marked 'final' it can't be overridden
2756 // and we can therefore devirtualize the member function call.
Richard Smitha2716862016-11-11 01:01:31 +00002757 if (BestDynamicDecl->hasAttr<FinalAttr>())
Anders Carlssonc36783e2011-05-08 20:32:23 +00002758 return true;
2759
Anders Carlssonc36783e2011-05-08 20:32:23 +00002760 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2761 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2762 // This is a record decl. We know the type and can devirtualize it.
2763 return VD->getType()->isRecordType();
2764 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002765
Anders Carlssonc36783e2011-05-08 20:32:23 +00002766 return false;
2767 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002768
2769 // We can devirtualize calls on an object accessed by a class member access
2770 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2771 // a derived class object constructed in the same location.
2772 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2773 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2774 return VD->getType()->isRecordType();
2775
Richard Smith018ac392016-11-03 18:55:18 +00002776 // Likewise for calls on an object accessed by a (non-reference) pointer to
2777 // member access.
2778 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2779 if (BO->isPtrMemOp()) {
2780 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2781 if (MPT->getPointeeType()->isRecordType())
2782 return true;
2783 }
2784 }
Anders Carlssonc36783e2011-05-08 20:32:23 +00002785
2786 // We can't devirtualize the call.
2787 return false;
2788}
2789
Faisal Vali571df122013-09-29 08:45:24 +00002790void CodeGenFunction::EmitForwardingCallToLambda(
2791 const CXXMethodDecl *callOperator,
2792 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002793 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002794 const CGFunctionInfo &calleeFnInfo =
2795 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
John McCallb92ab1a2016-10-26 23:46:34 +00002796 llvm::Constant *calleePtr =
John McCall8dda7b22012-07-07 06:41:13 +00002797 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2798 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002799
John McCall8dda7b22012-07-07 06:41:13 +00002800 // Prepare the return slot.
2801 const FunctionProtoType *FPT =
2802 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002803 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002804 ReturnValueSlot returnSlot;
2805 if (!resultType->isVoidType() &&
2806 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002807 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002808 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2809
2810 // We don't need to separately arrange the call arguments because
2811 // the call can't be variadic anyway --- it's impossible to forward
2812 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002813
Eli Friedman5b446882012-02-16 03:47:28 +00002814 // Now emit our call.
John McCallb92ab1a2016-10-26 23:46:34 +00002815 auto callee = CGCallee::forDirect(calleePtr, callOperator);
2816 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
Eli Friedman5b446882012-02-16 03:47:28 +00002817
John McCall8dda7b22012-07-07 06:41:13 +00002818 // If necessary, copy the returned value into the slot.
2819 if (!resultType->isVoidType() && returnSlot.isNull())
2820 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002821 else
2822 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002823}
2824
Eli Friedman2495ab02012-02-25 02:48:22 +00002825void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2826 const BlockDecl *BD = BlockInfo->getBlockDecl();
2827 const VarDecl *variable = BD->capture_begin()->getVariable();
2828 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2829
2830 // Start building arguments for forwarding call
2831 CallArgList CallArgs;
2832
2833 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
John McCall7f416cc2015-09-08 08:05:57 +00002834 Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2835 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
Eli Friedman2495ab02012-02-25 02:48:22 +00002836
2837 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002838 for (auto param : BD->parameters())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002839 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002840
Justin Bogner1cd11f12015-05-20 15:53:59 +00002841 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002842 "generic lambda interconversion to block not implemented");
2843 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002844}
2845
2846void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002847 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002848 // FIXME: Making this work correctly is nasty because it requires either
2849 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002850 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002851 return;
2852 }
2853
Richard Smithb47c36f2013-11-05 09:12:18 +00002854 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002855}
2856
2857void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2858 const CXXRecordDecl *Lambda = MD->getParent();
2859
2860 // Start building arguments for forwarding call
2861 CallArgList CallArgs;
2862
2863 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2864 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2865 CallArgs.add(RValue::get(ThisPtr), ThisType);
2866
2867 // Add the rest of the parameters.
David Majnemer59f77922016-06-24 04:05:48 +00002868 for (auto Param : MD->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002869 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2870
Faisal Vali571df122013-09-29 08:45:24 +00002871 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2872 // For a generic lambda, find the corresponding call operator specialization
2873 // to which the call to the static-invoker shall be forwarded.
2874 if (Lambda->isGenericLambda()) {
2875 assert(MD->isFunctionTemplateSpecialization());
2876 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2877 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002878 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002879 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002880 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002881 assert(CorrespondingCallOpSpecialization);
2882 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2883 }
2884 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002885}
2886
Douglas Gregor355efbb2012-02-17 03:02:34 +00002887void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2888 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002889 // FIXME: Making this work correctly is nasty because it requires either
2890 // cloning the body of the call operator or making the call operator forward.
2891 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002892 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002893 }
2894
Douglas Gregor355efbb2012-02-17 03:02:34 +00002895 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002896}