1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with C++ code generation of classes
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
15 #include "CGDebugInfo.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenFunction.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Basic/CodeGenOptions.h"
26 #include "clang/Basic/TargetBuiltins.h"
27 #include "clang/CodeGen/CGFunctionInfo.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/Transforms/Utils/SanitizerStats.h"
31
32 using namespace clang;
33 using namespace CodeGen;
34
35 /// Return the best known alignment for an unknown pointer to a
36 /// particular class.
getClassPointerAlignment(const CXXRecordDecl * RD)37 CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
38 if (!RD->hasDefinition())
39 return CharUnits::One(); // Hopefully won't be used anywhere.
40
41 auto &layout = getContext().getASTRecordLayout(RD);
42
43 // If the class is final, then we know that the pointer points to an
44 // object of that type and can use the full alignment.
45 if (RD->isEffectivelyFinal())
46 return layout.getAlignment();
47
48 // Otherwise, we have to assume it could be a subclass.
49 return layout.getNonVirtualAlignment();
50 }
51
52 /// Return the smallest possible amount of storage that might be allocated
53 /// starting from the beginning of an object of a particular class.
54 ///
55 /// This may be smaller than sizeof(RD) if RD has virtual base classes.
getMinimumClassObjectSize(const CXXRecordDecl * RD)56 CharUnits CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl *RD) {
57 if (!RD->hasDefinition())
58 return CharUnits::One();
59
60 auto &layout = getContext().getASTRecordLayout(RD);
61
62 // If the class is final, then we know that the pointer points to an
63 // object of that type and can use the full alignment.
64 if (RD->isEffectivelyFinal())
65 return layout.getSize();
66
67 // Otherwise, we have to assume it could be a subclass.
68 return std::max(layout.getNonVirtualSize(), CharUnits::One());
69 }
70
71 /// Return the best known alignment for a pointer to a virtual base,
72 /// given the alignment of a pointer to the derived class.
getVBaseAlignment(CharUnits actualDerivedAlign,const CXXRecordDecl * derivedClass,const CXXRecordDecl * vbaseClass)73 CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
74 const CXXRecordDecl *derivedClass,
75 const CXXRecordDecl *vbaseClass) {
76 // The basic idea here is that an underaligned derived pointer might
77 // indicate an underaligned base pointer.
78
79 assert(vbaseClass->isCompleteDefinition());
80 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
81 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
82
83 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
84 expectedVBaseAlign);
85 }
86
87 CharUnits
getDynamicOffsetAlignment(CharUnits actualBaseAlign,const CXXRecordDecl * baseDecl,CharUnits expectedTargetAlign)88 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
89 const CXXRecordDecl *baseDecl,
90 CharUnits expectedTargetAlign) {
91 // If the base is an incomplete type (which is, alas, possible with
92 // member pointers), be pessimistic.
93 if (!baseDecl->isCompleteDefinition())
94 return std::min(actualBaseAlign, expectedTargetAlign);
95
96 auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
97 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
98
99 // If the class is properly aligned, assume the target offset is, too.
100 //
101 // This actually isn't necessarily the right thing to do --- if the
102 // class is a complete object, but it's only properly aligned for a
103 // base subobject, then the alignments of things relative to it are
104 // probably off as well. (Note that this requires the alignment of
105 // the target to be greater than the NV alignment of the derived
106 // class.)
107 //
108 // However, our approach to this kind of under-alignment can only
109 // ever be best effort; after all, we're never going to propagate
110 // alignments through variables or parameters. Note, in particular,
111 // that constructing a polymorphic type in an address that's less
112 // than pointer-aligned will generally trap in the constructor,
113 // unless we someday add some sort of attribute to change the
114 // assumed alignment of 'this'. So our goal here is pretty much
115 // just to allow the user to explicitly say that a pointer is
116 // under-aligned and then safely access its fields and vtables.
117 if (actualBaseAlign >= expectedBaseAlign) {
118 return expectedTargetAlign;
119 }
120
121 // Otherwise, we might be offset by an arbitrary multiple of the
122 // actual alignment. The correct adjustment is to take the min of
123 // the two alignments.
124 return std::min(actualBaseAlign, expectedTargetAlign);
125 }
126
LoadCXXThisAddress()127 Address CodeGenFunction::LoadCXXThisAddress() {
128 assert(CurFuncDecl && "loading 'this' without a func declaration?");
129 assert(isa<CXXMethodDecl>(CurFuncDecl));
130
131 // Lazily compute CXXThisAlignment.
132 if (CXXThisAlignment.isZero()) {
133 // Just use the best known alignment for the parent.
134 // TODO: if we're currently emitting a complete-object ctor/dtor,
135 // we can always use the complete-object alignment.
136 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
137 CXXThisAlignment = CGM.getClassPointerAlignment(RD);
138 }
139
140 return Address(LoadCXXThis(), CXXThisAlignment);
141 }
142
143 /// Emit the address of a field using a member data pointer.
144 ///
145 /// \param E Only used for emergency diagnostics
146 Address
EmitCXXMemberDataPointerAddress(const Expr * E,Address base,llvm::Value * memberPtr,const MemberPointerType * memberPtrType,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)147 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
148 llvm::Value *memberPtr,
149 const MemberPointerType *memberPtrType,
150 LValueBaseInfo *BaseInfo,
151 TBAAAccessInfo *TBAAInfo) {
152 // Ask the ABI to compute the actual address.
153 llvm::Value *ptr =
154 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
155 memberPtr, memberPtrType);
156
157 QualType memberType = memberPtrType->getPointeeType();
158 CharUnits memberAlign =
159 CGM.getNaturalTypeAlignment(memberType, BaseInfo, TBAAInfo);
160 memberAlign =
161 CGM.getDynamicOffsetAlignment(base.getAlignment(),
162 memberPtrType->getClass()->getAsCXXRecordDecl(),
163 memberAlign);
164 return Address(ptr, memberAlign);
165 }
166
computeNonVirtualBaseClassOffset(const CXXRecordDecl * DerivedClass,CastExpr::path_const_iterator Start,CastExpr::path_const_iterator End)167 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
168 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
169 CastExpr::path_const_iterator End) {
170 CharUnits Offset = CharUnits::Zero();
171
172 const ASTContext &Context = getContext();
173 const CXXRecordDecl *RD = DerivedClass;
174
175 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
176 const CXXBaseSpecifier *Base = *I;
177 assert(!Base->isVirtual() && "Should not see virtual bases here!");
178
179 // Get the layout.
180 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
181
182 const auto *BaseDecl =
183 cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
184
185 // Add the offset.
186 Offset += Layout.getBaseClassOffset(BaseDecl);
187
188 RD = BaseDecl;
189 }
190
191 return Offset;
192 }
193
194 llvm::Constant *
GetNonVirtualBaseClassOffset(const CXXRecordDecl * ClassDecl,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd)195 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
196 CastExpr::path_const_iterator PathBegin,
197 CastExpr::path_const_iterator PathEnd) {
198 assert(PathBegin != PathEnd && "Base path should not be empty!");
199
200 CharUnits Offset =
201 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
202 if (Offset.isZero())
203 return nullptr;
204
205 llvm::Type *PtrDiffTy =
206 Types.ConvertType(getContext().getPointerDiffType());
207
208 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
209 }
210
211 /// Gets the address of a direct base class within a complete object.
212 /// This should only be used for (1) non-virtual bases or (2) virtual bases
213 /// when the type is known to be complete (e.g. in complete destructors).
214 ///
215 /// The object pointed to by 'This' is assumed to be non-null.
216 Address
GetAddressOfDirectBaseInCompleteClass(Address This,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,bool BaseIsVirtual)217 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
218 const CXXRecordDecl *Derived,
219 const CXXRecordDecl *Base,
220 bool BaseIsVirtual) {
221 // 'this' must be a pointer (in some address space) to Derived.
222 assert(This.getElementType() == ConvertType(Derived));
223
224 // Compute the offset of the virtual base.
225 CharUnits Offset;
226 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
227 if (BaseIsVirtual)
228 Offset = Layout.getVBaseClassOffset(Base);
229 else
230 Offset = Layout.getBaseClassOffset(Base);
231
232 // Shift and cast down to the base type.
233 // TODO: for complete types, this should be possible with a GEP.
234 Address V = This;
235 if (!Offset.isZero()) {
236 V = Builder.CreateElementBitCast(V, Int8Ty);
237 V = Builder.CreateConstInBoundsByteGEP(V, Offset);
238 }
239 V = Builder.CreateElementBitCast(V, ConvertType(Base));
240
241 return V;
242 }
243
244 static Address
ApplyNonVirtualAndVirtualOffset(CodeGenFunction & CGF,Address addr,CharUnits nonVirtualOffset,llvm::Value * virtualOffset,const CXXRecordDecl * derivedClass,const CXXRecordDecl * nearestVBase)245 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
246 CharUnits nonVirtualOffset,
247 llvm::Value *virtualOffset,
248 const CXXRecordDecl *derivedClass,
249 const CXXRecordDecl *nearestVBase) {
250 // Assert that we have something to do.
251 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
252
253 // Compute the offset from the static and dynamic components.
254 llvm::Value *baseOffset;
255 if (!nonVirtualOffset.isZero()) {
256 llvm::Type *OffsetType =
257 (CGF.CGM.getTarget().getCXXABI().isItaniumFamily() &&
258 CGF.CGM.getItaniumVTableContext().isRelativeLayout())
259 ? CGF.Int32Ty
260 : CGF.PtrDiffTy;
261 baseOffset =
262 llvm::ConstantInt::get(OffsetType, nonVirtualOffset.getQuantity());
263 if (virtualOffset) {
264 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
265 }
266 } else {
267 baseOffset = virtualOffset;
268 }
269
270 // Apply the base offset.
271 llvm::Value *ptr = addr.getPointer();
272 unsigned AddrSpace = ptr->getType()->getPointerAddressSpace();
273 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace));
274 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
275
276 // If we have a virtual component, the alignment of the result will
277 // be relative only to the known alignment of that vbase.
278 CharUnits alignment;
279 if (virtualOffset) {
280 assert(nearestVBase && "virtual offset without vbase?");
281 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
282 derivedClass, nearestVBase);
283 } else {
284 alignment = addr.getAlignment();
285 }
286 alignment = alignment.alignmentAtOffset(nonVirtualOffset);
287
288 return Address(ptr, alignment);
289 }
290
GetAddressOfBaseClass(Address Value,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue,SourceLocation Loc)291 Address CodeGenFunction::GetAddressOfBaseClass(
292 Address Value, const CXXRecordDecl *Derived,
293 CastExpr::path_const_iterator PathBegin,
294 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
295 SourceLocation Loc) {
296 assert(PathBegin != PathEnd && "Base path should not be empty!");
297
298 CastExpr::path_const_iterator Start = PathBegin;
299 const CXXRecordDecl *VBase = nullptr;
300
301 // Sema has done some convenient canonicalization here: if the
302 // access path involved any virtual steps, the conversion path will
303 // *start* with a step down to the correct virtual base subobject,
304 // and hence will not require any further steps.
305 if ((*Start)->isVirtual()) {
306 VBase = cast<CXXRecordDecl>(
307 (*Start)->getType()->castAs<RecordType>()->getDecl());
308 ++Start;
309 }
310
311 // Compute the static offset of the ultimate destination within its
312 // allocating subobject (the virtual base, if there is one, or else
313 // the "complete" object that we see).
314 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
315 VBase ? VBase : Derived, Start, PathEnd);
316
317 // If there's a virtual step, we can sometimes "devirtualize" it.
318 // For now, that's limited to when the derived type is final.
319 // TODO: "devirtualize" this for accesses to known-complete objects.
320 if (VBase && Derived->hasAttr<FinalAttr>()) {
321 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
322 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
323 NonVirtualOffset += vBaseOffset;
324 VBase = nullptr; // we no longer have a virtual step
325 }
326
327 // Get the base pointer type.
328 llvm::Type *BasePtrTy =
329 ConvertType((PathEnd[-1])->getType())
330 ->getPointerTo(Value.getType()->getPointerAddressSpace());
331
332 QualType DerivedTy = getContext().getRecordType(Derived);
333 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
334
335 // If the static offset is zero and we don't have a virtual step,
336 // just do a bitcast; null checks are unnecessary.
337 if (NonVirtualOffset.isZero() && !VBase) {
338 if (sanitizePerformTypeCheck()) {
339 SanitizerSet SkippedChecks;
340 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
341 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
342 DerivedTy, DerivedAlign, SkippedChecks);
343 }
344 return Builder.CreateBitCast(Value, BasePtrTy);
345 }
346
347 llvm::BasicBlock *origBB = nullptr;
348 llvm::BasicBlock *endBB = nullptr;
349
350 // Skip over the offset (and the vtable load) if we're supposed to
351 // null-check the pointer.
352 if (NullCheckValue) {
353 origBB = Builder.GetInsertBlock();
354 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
355 endBB = createBasicBlock("cast.end");
356
357 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
358 Builder.CreateCondBr(isNull, endBB, notNullBB);
359 EmitBlock(notNullBB);
360 }
361
362 if (sanitizePerformTypeCheck()) {
363 SanitizerSet SkippedChecks;
364 SkippedChecks.set(SanitizerKind::Null, true);
365 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
366 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
367 }
368
369 // Compute the virtual offset.
370 llvm::Value *VirtualOffset = nullptr;
371 if (VBase) {
372 VirtualOffset =
373 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
374 }
375
376 // Apply both offsets.
377 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
378 VirtualOffset, Derived, VBase);
379
380 // Cast to the destination type.
381 Value = Builder.CreateBitCast(Value, BasePtrTy);
382
383 // Build a phi if we needed a null check.
384 if (NullCheckValue) {
385 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
386 Builder.CreateBr(endBB);
387 EmitBlock(endBB);
388
389 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
390 PHI->addIncoming(Value.getPointer(), notNullBB);
391 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
392 Value = Address(PHI, Value.getAlignment());
393 }
394
395 return Value;
396 }
397
398 Address
GetAddressOfDerivedClass(Address BaseAddr,const CXXRecordDecl * Derived,CastExpr::path_const_iterator PathBegin,CastExpr::path_const_iterator PathEnd,bool NullCheckValue)399 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
400 const CXXRecordDecl *Derived,
401 CastExpr::path_const_iterator PathBegin,
402 CastExpr::path_const_iterator PathEnd,
403 bool NullCheckValue) {
404 assert(PathBegin != PathEnd && "Base path should not be empty!");
405
406 QualType DerivedTy =
407 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
408 unsigned AddrSpace =
409 BaseAddr.getPointer()->getType()->getPointerAddressSpace();
410 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(AddrSpace);
411
412 llvm::Value *NonVirtualOffset =
413 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
414
415 if (!NonVirtualOffset) {
416 // No offset, we can just cast back.
417 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
418 }
419
420 llvm::BasicBlock *CastNull = nullptr;
421 llvm::BasicBlock *CastNotNull = nullptr;
422 llvm::BasicBlock *CastEnd = nullptr;
423
424 if (NullCheckValue) {
425 CastNull = createBasicBlock("cast.null");
426 CastNotNull = createBasicBlock("cast.notnull");
427 CastEnd = createBasicBlock("cast.end");
428
429 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
430 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
431 EmitBlock(CastNotNull);
432 }
433
434 // Apply the offset.
435 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
436 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
437 "sub.ptr");
438
439 // Just cast.
440 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
441
442 // Produce a PHI if we had a null-check.
443 if (NullCheckValue) {
444 Builder.CreateBr(CastEnd);
445 EmitBlock(CastNull);
446 Builder.CreateBr(CastEnd);
447 EmitBlock(CastEnd);
448
449 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
450 PHI->addIncoming(Value, CastNotNull);
451 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
452 Value = PHI;
453 }
454
455 return Address(Value, CGM.getClassPointerAlignment(Derived));
456 }
457
GetVTTParameter(GlobalDecl GD,bool ForVirtualBase,bool Delegating)458 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
459 bool ForVirtualBase,
460 bool Delegating) {
461 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
462 // This constructor/destructor does not need a VTT parameter.
463 return nullptr;
464 }
465
466 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
467 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
468
469 llvm::Value *VTT;
470
471 uint64_t SubVTTIndex;
472
473 if (Delegating) {
474 // If this is a delegating constructor call, just load the VTT.
475 return LoadCXXVTT();
476 } else if (RD == Base) {
477 // If the record matches the base, this is the complete ctor/dtor
478 // variant calling the base variant in a class with virtual bases.
479 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
480 "doing no-op VTT offset in base dtor/ctor?");
481 assert(!ForVirtualBase && "Can't have same class as virtual base!");
482 SubVTTIndex = 0;
483 } else {
484 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
485 CharUnits BaseOffset = ForVirtualBase ?
486 Layout.getVBaseClassOffset(Base) :
487 Layout.getBaseClassOffset(Base);
488
489 SubVTTIndex =
490 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
491 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
492 }
493
494 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
495 // A VTT parameter was passed to the constructor, use it.
496 VTT = LoadCXXVTT();
497 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
498 } else {
499 // We're the complete constructor, so get the VTT by name.
500 VTT = CGM.getVTables().GetAddrOfVTT(RD);
501 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
502 }
503
504 return VTT;
505 }
506
507 namespace {
508 /// Call the destructor for a direct base class.
509 struct CallBaseDtor final : EHScopeStack::Cleanup {
510 const CXXRecordDecl *BaseClass;
511 bool BaseIsVirtual;
CallBaseDtor__anon03c1798c0111::CallBaseDtor512 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
513 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
514
Emit__anon03c1798c0111::CallBaseDtor515 void Emit(CodeGenFunction &CGF, Flags flags) override {
516 const CXXRecordDecl *DerivedClass =
517 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
518
519 const CXXDestructorDecl *D = BaseClass->getDestructor();
520 // We are already inside a destructor, so presumably the object being
521 // destroyed should have the expected type.
522 QualType ThisTy = D->getThisObjectType();
523 Address Addr =
524 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
525 DerivedClass, BaseClass,
526 BaseIsVirtual);
527 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
528 /*Delegating=*/false, Addr, ThisTy);
529 }
530 };
531
532 /// A visitor which checks whether an initializer uses 'this' in a
533 /// way which requires the vtable to be properly set.
534 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
535 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
536
537 bool UsesThis;
538
DynamicThisUseChecker__anon03c1798c0111::DynamicThisUseChecker539 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
540
541 // Black-list all explicit and implicit references to 'this'.
542 //
543 // Do we need to worry about external references to 'this' derived
544 // from arbitrary code? If so, then anything which runs arbitrary
545 // external code might potentially access the vtable.
VisitCXXThisExpr__anon03c1798c0111::DynamicThisUseChecker546 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
547 };
548 } // end anonymous namespace
549
BaseInitializerUsesThis(ASTContext & C,const Expr * Init)550 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
551 DynamicThisUseChecker Checker(C);
552 Checker.Visit(Init);
553 return Checker.UsesThis;
554 }
555
EmitBaseInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * BaseInit)556 static void EmitBaseInitializer(CodeGenFunction &CGF,
557 const CXXRecordDecl *ClassDecl,
558 CXXCtorInitializer *BaseInit) {
559 assert(BaseInit->isBaseInitializer() &&
560 "Must have base initializer!");
561
562 Address ThisPtr = CGF.LoadCXXThisAddress();
563
564 const Type *BaseType = BaseInit->getBaseClass();
565 const auto *BaseClassDecl =
566 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
567
568 bool isBaseVirtual = BaseInit->isBaseVirtual();
569
570 // If the initializer for the base (other than the constructor
571 // itself) accesses 'this' in any way, we need to initialize the
572 // vtables.
573 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
574 CGF.InitializeVTablePointers(ClassDecl);
575
576 // We can pretend to be a complete class because it only matters for
577 // virtual bases, and we only do virtual bases for complete ctors.
578 Address V =
579 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
580 BaseClassDecl,
581 isBaseVirtual);
582 AggValueSlot AggSlot =
583 AggValueSlot::forAddr(
584 V, Qualifiers(),
585 AggValueSlot::IsDestructed,
586 AggValueSlot::DoesNotNeedGCBarriers,
587 AggValueSlot::IsNotAliased,
588 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
589
590 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
591
592 if (CGF.CGM.getLangOpts().Exceptions &&
593 !BaseClassDecl->hasTrivialDestructor())
594 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
595 isBaseVirtual);
596 }
597
isMemcpyEquivalentSpecialMember(const CXXMethodDecl * D)598 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
599 auto *CD = dyn_cast<CXXConstructorDecl>(D);
600 if (!(CD && CD->isCopyOrMoveConstructor()) &&
601 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
602 return false;
603
604 // We can emit a memcpy for a trivial copy or move constructor/assignment.
605 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
606 return true;
607
608 // We *must* emit a memcpy for a defaulted union copy or move op.
609 if (D->getParent()->isUnion() && D->isDefaulted())
610 return true;
611
612 return false;
613 }
614
EmitLValueForAnyFieldInitialization(CodeGenFunction & CGF,CXXCtorInitializer * MemberInit,LValue & LHS)615 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
616 CXXCtorInitializer *MemberInit,
617 LValue &LHS) {
618 FieldDecl *Field = MemberInit->getAnyMember();
619 if (MemberInit->isIndirectMemberInitializer()) {
620 // If we are initializing an anonymous union field, drill down to the field.
621 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
622 for (const auto *I : IndirectField->chain())
623 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
624 } else {
625 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
626 }
627 }
628
EmitMemberInitializer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,CXXCtorInitializer * MemberInit,const CXXConstructorDecl * Constructor,FunctionArgList & Args)629 static void EmitMemberInitializer(CodeGenFunction &CGF,
630 const CXXRecordDecl *ClassDecl,
631 CXXCtorInitializer *MemberInit,
632 const CXXConstructorDecl *Constructor,
633 FunctionArgList &Args) {
634 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
635 assert(MemberInit->isAnyMemberInitializer() &&
636 "Must have member initializer!");
637 assert(MemberInit->getInit() && "Must have initializer!");
638
639 // non-static data member initializers.
640 FieldDecl *Field = MemberInit->getAnyMember();
641 QualType FieldType = Field->getType();
642
643 llvm::Value *ThisPtr = CGF.LoadCXXThis();
644 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
645 LValue LHS;
646
647 // If a base constructor is being emitted, create an LValue that has the
648 // non-virtual alignment.
649 if (CGF.CurGD.getCtorType() == Ctor_Base)
650 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
651 else
652 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
653
654 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
655
656 // Special case: if we are in a copy or move constructor, and we are copying
657 // an array of PODs or classes with trivial copy constructors, ignore the
658 // AST and perform the copy we know is equivalent.
659 // FIXME: This is hacky at best... if we had a bit more explicit information
660 // in the AST, we could generalize it more easily.
661 const ConstantArrayType *Array
662 = CGF.getContext().getAsConstantArrayType(FieldType);
663 if (Array && Constructor->isDefaulted() &&
664 Constructor->isCopyOrMoveConstructor()) {
665 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
666 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
667 if (BaseElementTy.isPODType(CGF.getContext()) ||
668 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
669 unsigned SrcArgIndex =
670 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
671 llvm::Value *SrcPtr
672 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
673 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
674 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
675
676 // Copy the aggregate.
677 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
678 LHS.isVolatileQualified());
679 // Ensure that we destroy the objects if an exception is thrown later in
680 // the constructor.
681 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
682 if (CGF.needsEHCleanup(dtorKind))
683 CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType);
684 return;
685 }
686 }
687
688 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
689 }
690
EmitInitializerForField(FieldDecl * Field,LValue LHS,Expr * Init)691 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
692 Expr *Init) {
693 QualType FieldType = Field->getType();
694 switch (getEvaluationKind(FieldType)) {
695 case TEK_Scalar:
696 if (LHS.isSimple()) {
697 EmitExprAsInit(Init, Field, LHS, false);
698 } else {
699 RValue RHS = RValue::get(EmitScalarExpr(Init));
700 EmitStoreThroughLValue(RHS, LHS);
701 }
702 break;
703 case TEK_Complex:
704 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
705 break;
706 case TEK_Aggregate: {
707 AggValueSlot Slot = AggValueSlot::forLValue(
708 LHS, *this, AggValueSlot::IsDestructed,
709 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
710 getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed,
711 // Checks are made by the code that calls constructor.
712 AggValueSlot::IsSanitizerChecked);
713 EmitAggExpr(Init, Slot);
714 break;
715 }
716 }
717
718 // Ensure that we destroy this object if an exception is thrown
719 // later in the constructor.
720 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
721 if (needsEHCleanup(dtorKind))
722 pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType);
723 }
724
725 /// Checks whether the given constructor is a valid subject for the
726 /// complete-to-base constructor delegation optimization, i.e.
727 /// emitting the complete constructor as a simple call to the base
728 /// constructor.
IsConstructorDelegationValid(const CXXConstructorDecl * Ctor)729 bool CodeGenFunction::IsConstructorDelegationValid(
730 const CXXConstructorDecl *Ctor) {
731
732 // Currently we disable the optimization for classes with virtual
733 // bases because (1) the addresses of parameter variables need to be
734 // consistent across all initializers but (2) the delegate function
735 // call necessarily creates a second copy of the parameter variable.
736 //
737 // The limiting example (purely theoretical AFAIK):
738 // struct A { A(int &c) { c++; } };
739 // struct B : virtual A {
740 // B(int count) : A(count) { printf("%d\n", count); }
741 // };
742 // ...although even this example could in principle be emitted as a
743 // delegation since the address of the parameter doesn't escape.
744 if (Ctor->getParent()->getNumVBases()) {
745 // TODO: white-list trivial vbase initializers. This case wouldn't
746 // be subject to the restrictions below.
747
748 // TODO: white-list cases where:
749 // - there are no non-reference parameters to the constructor
750 // - the initializers don't access any non-reference parameters
751 // - the initializers don't take the address of non-reference
752 // parameters
753 // - etc.
754 // If we ever add any of the above cases, remember that:
755 // - function-try-blocks will always exclude this optimization
756 // - we need to perform the constructor prologue and cleanup in
757 // EmitConstructorBody.
758
759 return false;
760 }
761
762 // We also disable the optimization for variadic functions because
763 // it's impossible to "re-pass" varargs.
764 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
765 return false;
766
767 // FIXME: Decide if we can do a delegation of a delegating constructor.
768 if (Ctor->isDelegatingConstructor())
769 return false;
770
771 return true;
772 }
773
774 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
775 // to poison the extra field paddings inserted under
776 // -fsanitize-address-field-padding=1|2.
EmitAsanPrologueOrEpilogue(bool Prologue)777 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
778 ASTContext &Context = getContext();
779 const CXXRecordDecl *ClassDecl =
780 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
781 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
782 if (!ClassDecl->mayInsertExtraPadding()) return;
783
784 struct SizeAndOffset {
785 uint64_t Size;
786 uint64_t Offset;
787 };
788
789 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits(
790 CGM.getTargetCodeGenInfo().getDefaultAS());
791 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
792
793 // Populate sizes and offsets of fields.
794 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
795 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
796 SSV[i].Offset =
797 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
798
799 size_t NumFields = 0;
800 for (const auto *Field : ClassDecl->fields()) {
801 const FieldDecl *D = Field;
802 std::pair<CharUnits, CharUnits> FieldInfo =
803 Context.getTypeInfoInChars(D->getType());
804 CharUnits FieldSize = FieldInfo.first;
805 assert(NumFields < SSV.size());
806 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
807 NumFields++;
808 }
809 assert(NumFields == SSV.size());
810 if (SSV.size() <= 1) return;
811
812 // We will insert calls to __asan_* run-time functions.
813 // LLVM AddressSanitizer pass may decide to inline them later.
814 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
815 llvm::FunctionType *FTy =
816 llvm::FunctionType::get(CGM.VoidTy, Args, false);
817 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
818 FTy, Prologue ? "__asan_poison_intra_object_redzone"
819 : "__asan_unpoison_intra_object_redzone");
820
821 llvm::Value *ThisPtr = LoadCXXThis();
822 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
823 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
824 // For each field check if it has sufficient padding,
825 // if so (un)poison it with a call.
826 for (size_t i = 0; i < SSV.size(); i++) {
827 uint64_t AsanAlignment = 8;
828 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
829 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
830 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
831 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
832 (NextField % AsanAlignment) != 0)
833 continue;
834 Builder.CreateCall(
835 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
836 Builder.getIntN(PtrSize, PoisonSize)});
837 }
838 }
839
840 /// EmitConstructorBody - Emits the body of the current constructor.
EmitConstructorBody(FunctionArgList & Args)841 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
842 EmitAsanPrologueOrEpilogue(true);
843 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
844 CXXCtorType CtorType = CurGD.getCtorType();
845
846 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
847 CtorType == Ctor_Complete) &&
848 "can only generate complete ctor for this ABI");
849
850 // Before we go any further, try the complete->base constructor
851 // delegation optimization.
852 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
853 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
854 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
855 return;
856 }
857
858 const FunctionDecl *Definition = nullptr;
859 Stmt *Body = Ctor->getBody(Definition);
860 assert(Definition == Ctor && "emitting wrong constructor body");
861
862 // Enter the function-try-block before the constructor prologue if
863 // applicable.
864 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
865 if (IsTryBody)
866 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
867
868 incrementProfileCounter(Body);
869
870 RunCleanupsScope RunCleanups(*this);
871
872 // TODO: in restricted cases, we can emit the vbase initializers of
873 // a complete ctor and then delegate to the base ctor.
874
875 // Emit the constructor prologue, i.e. the base and member
876 // initializers.
877 EmitCtorPrologue(Ctor, CtorType, Args);
878
879 // Emit the body of the statement.
880 if (IsTryBody)
881 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
882 else if (Body)
883 EmitStmt(Body);
884
885 // Emit any cleanup blocks associated with the member or base
886 // initializers, which includes (along the exceptional path) the
887 // destructors for those members and bases that were fully
888 // constructed.
889 RunCleanups.ForceCleanup();
890
891 if (IsTryBody)
892 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
893 }
894
895 namespace {
896 /// RAII object to indicate that codegen is copying the value representation
897 /// instead of the object representation. Useful when copying a struct or
898 /// class which has uninitialized members and we're only performing
899 /// lvalue-to-rvalue conversion on the object but not its members.
900 class CopyingValueRepresentation {
901 public:
CopyingValueRepresentation(CodeGenFunction & CGF)902 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
903 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
904 CGF.SanOpts.set(SanitizerKind::Bool, false);
905 CGF.SanOpts.set(SanitizerKind::Enum, false);
906 }
~CopyingValueRepresentation()907 ~CopyingValueRepresentation() {
908 CGF.SanOpts = OldSanOpts;
909 }
910 private:
911 CodeGenFunction &CGF;
912 SanitizerSet OldSanOpts;
913 };
914 } // end anonymous namespace
915
916 namespace {
917 class FieldMemcpyizer {
918 public:
FieldMemcpyizer(CodeGenFunction & CGF,const CXXRecordDecl * ClassDecl,const VarDecl * SrcRec)919 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
920 const VarDecl *SrcRec)
921 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
922 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
923 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
924 LastFieldOffset(0), LastAddedFieldIndex(0) {}
925
isMemcpyableField(FieldDecl * F) const926 bool isMemcpyableField(FieldDecl *F) const {
927 // Never memcpy fields when we are adding poisoned paddings.
928 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
929 return false;
930 Qualifiers Qual = F->getType().getQualifiers();
931 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
932 return false;
933 return true;
934 }
935
addMemcpyableField(FieldDecl * F)936 void addMemcpyableField(FieldDecl *F) {
937 if (F->isZeroSize(CGF.getContext()))
938 return;
939 if (!FirstField)
940 addInitialField(F);
941 else
942 addNextField(F);
943 }
944
getMemcpySize(uint64_t FirstByteOffset) const945 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
946 ASTContext &Ctx = CGF.getContext();
947 unsigned LastFieldSize =
948 LastField->isBitField()
949 ? LastField->getBitWidthValue(Ctx)
950 : Ctx.toBits(
951 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
952 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
953 FirstByteOffset + Ctx.getCharWidth() - 1;
954 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
955 return MemcpySize;
956 }
957
emitMemcpy()958 void emitMemcpy() {
959 // Give the subclass a chance to bail out if it feels the memcpy isn't
960 // worth it (e.g. Hasn't aggregated enough data).
961 if (!FirstField) {
962 return;
963 }
964
965 uint64_t FirstByteOffset;
966 if (FirstField->isBitField()) {
967 const CGRecordLayout &RL =
968 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
969 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
970 // FirstFieldOffset is not appropriate for bitfields,
971 // we need to use the storage offset instead.
972 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
973 } else {
974 FirstByteOffset = FirstFieldOffset;
975 }
976
977 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
978 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
979 Address ThisPtr = CGF.LoadCXXThisAddress();
980 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
981 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
982 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
983 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
984 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
985
986 emitMemcpyIR(
987 Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF),
988 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF),
989 MemcpySize);
990 reset();
991 }
992
reset()993 void reset() {
994 FirstField = nullptr;
995 }
996
997 protected:
998 CodeGenFunction &CGF;
999 const CXXRecordDecl *ClassDecl;
1000
1001 private:
emitMemcpyIR(Address DestPtr,Address SrcPtr,CharUnits Size)1002 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
1003 llvm::PointerType *DPT = DestPtr.getType();
1004 llvm::Type *DBP =
1005 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
1006 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
1007
1008 llvm::PointerType *SPT = SrcPtr.getType();
1009 llvm::Type *SBP =
1010 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
1011 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
1012
1013 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
1014 }
1015
addInitialField(FieldDecl * F)1016 void addInitialField(FieldDecl *F) {
1017 FirstField = F;
1018 LastField = F;
1019 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1020 LastFieldOffset = FirstFieldOffset;
1021 LastAddedFieldIndex = F->getFieldIndex();
1022 }
1023
addNextField(FieldDecl * F)1024 void addNextField(FieldDecl *F) {
1025 // For the most part, the following invariant will hold:
1026 // F->getFieldIndex() == LastAddedFieldIndex + 1
1027 // The one exception is that Sema won't add a copy-initializer for an
1028 // unnamed bitfield, which will show up here as a gap in the sequence.
1029 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1030 "Cannot aggregate fields out of order.");
1031 LastAddedFieldIndex = F->getFieldIndex();
1032
1033 // The 'first' and 'last' fields are chosen by offset, rather than field
1034 // index. This allows the code to support bitfields, as well as regular
1035 // fields.
1036 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1037 if (FOffset < FirstFieldOffset) {
1038 FirstField = F;
1039 FirstFieldOffset = FOffset;
1040 } else if (FOffset >= LastFieldOffset) {
1041 LastField = F;
1042 LastFieldOffset = FOffset;
1043 }
1044 }
1045
1046 const VarDecl *SrcRec;
1047 const ASTRecordLayout &RecLayout;
1048 FieldDecl *FirstField;
1049 FieldDecl *LastField;
1050 uint64_t FirstFieldOffset, LastFieldOffset;
1051 unsigned LastAddedFieldIndex;
1052 };
1053
1054 class ConstructorMemcpyizer : public FieldMemcpyizer {
1055 private:
1056 /// Get source argument for copy constructor. Returns null if not a copy
1057 /// constructor.
getTrivialCopySource(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1058 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1059 const CXXConstructorDecl *CD,
1060 FunctionArgList &Args) {
1061 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1062 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1063 return nullptr;
1064 }
1065
1066 // Returns true if a CXXCtorInitializer represents a member initialization
1067 // that can be rolled into a memcpy.
isMemberInitMemcpyable(CXXCtorInitializer * MemberInit) const1068 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1069 if (!MemcpyableCtor)
1070 return false;
1071 FieldDecl *Field = MemberInit->getMember();
1072 assert(Field && "No field for member init.");
1073 QualType FieldType = Field->getType();
1074 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1075
1076 // Bail out on non-memcpyable, not-trivially-copyable members.
1077 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1078 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1079 FieldType->isReferenceType()))
1080 return false;
1081
1082 // Bail out on volatile fields.
1083 if (!isMemcpyableField(Field))
1084 return false;
1085
1086 // Otherwise we're good.
1087 return true;
1088 }
1089
1090 public:
ConstructorMemcpyizer(CodeGenFunction & CGF,const CXXConstructorDecl * CD,FunctionArgList & Args)1091 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1092 FunctionArgList &Args)
1093 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1094 ConstructorDecl(CD),
1095 MemcpyableCtor(CD->isDefaulted() &&
1096 CD->isCopyOrMoveConstructor() &&
1097 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1098 Args(Args) { }
1099
addMemberInitializer(CXXCtorInitializer * MemberInit)1100 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1101 if (isMemberInitMemcpyable(MemberInit)) {
1102 AggregatedInits.push_back(MemberInit);
1103 addMemcpyableField(MemberInit->getMember());
1104 } else {
1105 emitAggregatedInits();
1106 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1107 ConstructorDecl, Args);
1108 }
1109 }
1110
emitAggregatedInits()1111 void emitAggregatedInits() {
1112 if (AggregatedInits.size() <= 1) {
1113 // This memcpy is too small to be worthwhile. Fall back on default
1114 // codegen.
1115 if (!AggregatedInits.empty()) {
1116 CopyingValueRepresentation CVR(CGF);
1117 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1118 AggregatedInits[0], ConstructorDecl, Args);
1119 AggregatedInits.clear();
1120 }
1121 reset();
1122 return;
1123 }
1124
1125 pushEHDestructors();
1126 emitMemcpy();
1127 AggregatedInits.clear();
1128 }
1129
pushEHDestructors()1130 void pushEHDestructors() {
1131 Address ThisPtr = CGF.LoadCXXThisAddress();
1132 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1133 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1134
1135 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1136 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1137 QualType FieldType = MemberInit->getAnyMember()->getType();
1138 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1139 if (!CGF.needsEHCleanup(dtorKind))
1140 continue;
1141 LValue FieldLHS = LHS;
1142 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1143 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType);
1144 }
1145 }
1146
finish()1147 void finish() {
1148 emitAggregatedInits();
1149 }
1150
1151 private:
1152 const CXXConstructorDecl *ConstructorDecl;
1153 bool MemcpyableCtor;
1154 FunctionArgList &Args;
1155 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1156 };
1157
1158 class AssignmentMemcpyizer : public FieldMemcpyizer {
1159 private:
1160 // Returns the memcpyable field copied by the given statement, if one
1161 // exists. Otherwise returns null.
getMemcpyableField(Stmt * S)1162 FieldDecl *getMemcpyableField(Stmt *S) {
1163 if (!AssignmentsMemcpyable)
1164 return nullptr;
1165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1166 // Recognise trivial assignments.
1167 if (BO->getOpcode() != BO_Assign)
1168 return nullptr;
1169 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1170 if (!ME)
1171 return nullptr;
1172 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1173 if (!Field || !isMemcpyableField(Field))
1174 return nullptr;
1175 Stmt *RHS = BO->getRHS();
1176 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1177 RHS = EC->getSubExpr();
1178 if (!RHS)
1179 return nullptr;
1180 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1181 if (ME2->getMemberDecl() == Field)
1182 return Field;
1183 }
1184 return nullptr;
1185 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1186 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1187 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1188 return nullptr;
1189 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1190 if (!IOA)
1191 return nullptr;
1192 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1193 if (!Field || !isMemcpyableField(Field))
1194 return nullptr;
1195 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1196 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1197 return nullptr;
1198 return Field;
1199 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1200 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1201 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1202 return nullptr;
1203 Expr *DstPtr = CE->getArg(0);
1204 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1205 DstPtr = DC->getSubExpr();
1206 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1207 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1208 return nullptr;
1209 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1210 if (!ME)
1211 return nullptr;
1212 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1213 if (!Field || !isMemcpyableField(Field))
1214 return nullptr;
1215 Expr *SrcPtr = CE->getArg(1);
1216 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1217 SrcPtr = SC->getSubExpr();
1218 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1219 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1220 return nullptr;
1221 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1222 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1223 return nullptr;
1224 return Field;
1225 }
1226
1227 return nullptr;
1228 }
1229
1230 bool AssignmentsMemcpyable;
1231 SmallVector<Stmt*, 16> AggregatedStmts;
1232
1233 public:
AssignmentMemcpyizer(CodeGenFunction & CGF,const CXXMethodDecl * AD,FunctionArgList & Args)1234 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1235 FunctionArgList &Args)
1236 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1237 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1238 assert(Args.size() == 2);
1239 }
1240
emitAssignment(Stmt * S)1241 void emitAssignment(Stmt *S) {
1242 FieldDecl *F = getMemcpyableField(S);
1243 if (F) {
1244 addMemcpyableField(F);
1245 AggregatedStmts.push_back(S);
1246 } else {
1247 emitAggregatedStmts();
1248 CGF.EmitStmt(S);
1249 }
1250 }
1251
emitAggregatedStmts()1252 void emitAggregatedStmts() {
1253 if (AggregatedStmts.size() <= 1) {
1254 if (!AggregatedStmts.empty()) {
1255 CopyingValueRepresentation CVR(CGF);
1256 CGF.EmitStmt(AggregatedStmts[0]);
1257 }
1258 reset();
1259 }
1260
1261 emitMemcpy();
1262 AggregatedStmts.clear();
1263 }
1264
finish()1265 void finish() {
1266 emitAggregatedStmts();
1267 }
1268 };
1269 } // end anonymous namespace
1270
isInitializerOfDynamicClass(const CXXCtorInitializer * BaseInit)1271 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1272 const Type *BaseType = BaseInit->getBaseClass();
1273 const auto *BaseClassDecl =
1274 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
1275 return BaseClassDecl->isDynamicClass();
1276 }
1277
1278 /// EmitCtorPrologue - This routine generates necessary code to initialize
1279 /// base classes and non-static data members belonging to this constructor.
EmitCtorPrologue(const CXXConstructorDecl * CD,CXXCtorType CtorType,FunctionArgList & Args)1280 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1281 CXXCtorType CtorType,
1282 FunctionArgList &Args) {
1283 if (CD->isDelegatingConstructor())
1284 return EmitDelegatingCXXConstructorCall(CD, Args);
1285
1286 const CXXRecordDecl *ClassDecl = CD->getParent();
1287
1288 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1289 E = CD->init_end();
1290
1291 // Virtual base initializers first, if any. They aren't needed if:
1292 // - This is a base ctor variant
1293 // - There are no vbases
1294 // - The class is abstract, so a complete object of it cannot be constructed
1295 //
1296 // The check for an abstract class is necessary because sema may not have
1297 // marked virtual base destructors referenced.
1298 bool ConstructVBases = CtorType != Ctor_Base &&
1299 ClassDecl->getNumVBases() != 0 &&
1300 !ClassDecl->isAbstract();
1301
1302 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
1303 // constructor of a class with virtual bases takes an additional parameter to
1304 // conditionally construct the virtual bases. Emit that check here.
1305 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1306 if (ConstructVBases &&
1307 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1308 BaseCtorContinueBB =
1309 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1310 assert(BaseCtorContinueBB);
1311 }
1312
1313 llvm::Value *const OldThis = CXXThisValue;
1314 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1315 if (!ConstructVBases)
1316 continue;
1317 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1318 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1319 isInitializerOfDynamicClass(*B))
1320 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1321 EmitBaseInitializer(*this, ClassDecl, *B);
1322 }
1323
1324 if (BaseCtorContinueBB) {
1325 // Complete object handler should continue to the remaining initializers.
1326 Builder.CreateBr(BaseCtorContinueBB);
1327 EmitBlock(BaseCtorContinueBB);
1328 }
1329
1330 // Then, non-virtual base initializers.
1331 for (; B != E && (*B)->isBaseInitializer(); B++) {
1332 assert(!(*B)->isBaseVirtual());
1333
1334 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1335 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1336 isInitializerOfDynamicClass(*B))
1337 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1338 EmitBaseInitializer(*this, ClassDecl, *B);
1339 }
1340
1341 CXXThisValue = OldThis;
1342
1343 InitializeVTablePointers(ClassDecl);
1344
1345 // And finally, initialize class members.
1346 FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1347 ConstructorMemcpyizer CM(*this, CD, Args);
1348 for (; B != E; B++) {
1349 CXXCtorInitializer *Member = (*B);
1350 assert(!Member->isBaseInitializer());
1351 assert(Member->isAnyMemberInitializer() &&
1352 "Delegating initializer on non-delegating constructor");
1353 CM.addMemberInitializer(Member);
1354 }
1355 CM.finish();
1356 }
1357
1358 static bool
1359 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1360
1361 static bool
HasTrivialDestructorBody(ASTContext & Context,const CXXRecordDecl * BaseClassDecl,const CXXRecordDecl * MostDerivedClassDecl)1362 HasTrivialDestructorBody(ASTContext &Context,
1363 const CXXRecordDecl *BaseClassDecl,
1364 const CXXRecordDecl *MostDerivedClassDecl)
1365 {
1366 // If the destructor is trivial we don't have to check anything else.
1367 if (BaseClassDecl->hasTrivialDestructor())
1368 return true;
1369
1370 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1371 return false;
1372
1373 // Check fields.
1374 for (const auto *Field : BaseClassDecl->fields())
1375 if (!FieldHasTrivialDestructorBody(Context, Field))
1376 return false;
1377
1378 // Check non-virtual bases.
1379 for (const auto &I : BaseClassDecl->bases()) {
1380 if (I.isVirtual())
1381 continue;
1382
1383 const CXXRecordDecl *NonVirtualBase =
1384 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1385 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1386 MostDerivedClassDecl))
1387 return false;
1388 }
1389
1390 if (BaseClassDecl == MostDerivedClassDecl) {
1391 // Check virtual bases.
1392 for (const auto &I : BaseClassDecl->vbases()) {
1393 const CXXRecordDecl *VirtualBase =
1394 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1395 if (!HasTrivialDestructorBody(Context, VirtualBase,
1396 MostDerivedClassDecl))
1397 return false;
1398 }
1399 }
1400
1401 return true;
1402 }
1403
1404 static bool
FieldHasTrivialDestructorBody(ASTContext & Context,const FieldDecl * Field)1405 FieldHasTrivialDestructorBody(ASTContext &Context,
1406 const FieldDecl *Field)
1407 {
1408 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1409
1410 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1411 if (!RT)
1412 return true;
1413
1414 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1415
1416 // The destructor for an implicit anonymous union member is never invoked.
1417 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1418 return false;
1419
1420 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1421 }
1422
1423 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1424 /// any vtable pointers before calling this destructor.
CanSkipVTablePointerInitialization(CodeGenFunction & CGF,const CXXDestructorDecl * Dtor)1425 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
1426 const CXXDestructorDecl *Dtor) {
1427 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1428 if (!ClassDecl->isDynamicClass())
1429 return true;
1430
1431 if (!Dtor->hasTrivialBody())
1432 return false;
1433
1434 // Check the fields.
1435 for (const auto *Field : ClassDecl->fields())
1436 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1437 return false;
1438
1439 return true;
1440 }
1441
1442 /// EmitDestructorBody - Emits the body of the current destructor.
EmitDestructorBody(FunctionArgList & Args)1443 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1444 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1445 CXXDtorType DtorType = CurGD.getDtorType();
1446
1447 // For an abstract class, non-base destructors are never used (and can't
1448 // be emitted in general, because vbase dtors may not have been validated
1449 // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1450 // in fact emit references to them from other compilations, so emit them
1451 // as functions containing a trap instruction.
1452 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1453 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1454 TrapCall->setDoesNotReturn();
1455 TrapCall->setDoesNotThrow();
1456 Builder.CreateUnreachable();
1457 Builder.ClearInsertionPoint();
1458 return;
1459 }
1460
1461 Stmt *Body = Dtor->getBody();
1462 if (Body)
1463 incrementProfileCounter(Body);
1464
1465 // The call to operator delete in a deleting destructor happens
1466 // outside of the function-try-block, which means it's always
1467 // possible to delegate the destructor body to the complete
1468 // destructor. Do so.
1469 if (DtorType == Dtor_Deleting) {
1470 RunCleanupsScope DtorEpilogue(*this);
1471 EnterDtorCleanups(Dtor, Dtor_Deleting);
1472 if (HaveInsertPoint()) {
1473 QualType ThisTy = Dtor->getThisObjectType();
1474 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1475 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1476 }
1477 return;
1478 }
1479
1480 // If the body is a function-try-block, enter the try before
1481 // anything else.
1482 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1483 if (isTryBody)
1484 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1485 EmitAsanPrologueOrEpilogue(false);
1486
1487 // Enter the epilogue cleanups.
1488 RunCleanupsScope DtorEpilogue(*this);
1489
1490 // If this is the complete variant, just invoke the base variant;
1491 // the epilogue will destruct the virtual bases. But we can't do
1492 // this optimization if the body is a function-try-block, because
1493 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1494 // always delegate because we might not have a definition in this TU.
1495 switch (DtorType) {
1496 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
1497 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1498
1499 case Dtor_Complete:
1500 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1501 "can't emit a dtor without a body for non-Microsoft ABIs");
1502
1503 // Enter the cleanup scopes for virtual bases.
1504 EnterDtorCleanups(Dtor, Dtor_Complete);
1505
1506 if (!isTryBody) {
1507 QualType ThisTy = Dtor->getThisObjectType();
1508 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1509 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
1510 break;
1511 }
1512
1513 // Fallthrough: act like we're in the base variant.
1514 LLVM_FALLTHROUGH;
1515
1516 case Dtor_Base:
1517 assert(Body);
1518
1519 // Enter the cleanup scopes for fields and non-virtual bases.
1520 EnterDtorCleanups(Dtor, Dtor_Base);
1521
1522 // Initialize the vtable pointers before entering the body.
1523 if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1524 // Insert the llvm.launder.invariant.group intrinsic before initializing
1525 // the vptrs to cancel any previous assumptions we might have made.
1526 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1527 CGM.getCodeGenOpts().OptimizationLevel > 0)
1528 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1529 InitializeVTablePointers(Dtor->getParent());
1530 }
1531
1532 if (isTryBody)
1533 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1534 else if (Body)
1535 EmitStmt(Body);
1536 else {
1537 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1538 // nothing to do besides what's in the epilogue
1539 }
1540 // -fapple-kext must inline any call to this dtor into
1541 // the caller's body.
1542 if (getLangOpts().AppleKext)
1543 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1544
1545 break;
1546 }
1547
1548 // Jump out through the epilogue cleanups.
1549 DtorEpilogue.ForceCleanup();
1550
1551 // Exit the try if applicable.
1552 if (isTryBody)
1553 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1554 }
1555
emitImplicitAssignmentOperatorBody(FunctionArgList & Args)1556 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1557 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1558 const Stmt *RootS = AssignOp->getBody();
1559 assert(isa<CompoundStmt>(RootS) &&
1560 "Body of an implicit assignment operator should be compound stmt.");
1561 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1562
1563 LexicalScope Scope(*this, RootCS->getSourceRange());
1564
1565 incrementProfileCounter(RootCS);
1566 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1567 for (auto *I : RootCS->body())
1568 AM.emitAssignment(I);
1569 AM.finish();
1570 }
1571
1572 namespace {
LoadThisForDtorDelete(CodeGenFunction & CGF,const CXXDestructorDecl * DD)1573 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1574 const CXXDestructorDecl *DD) {
1575 if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1576 return CGF.EmitScalarExpr(ThisArg);
1577 return CGF.LoadCXXThis();
1578 }
1579
1580 /// Call the operator delete associated with the current destructor.
1581 struct CallDtorDelete final : EHScopeStack::Cleanup {
CallDtorDelete__anon03c1798c0411::CallDtorDelete1582 CallDtorDelete() {}
1583
Emit__anon03c1798c0411::CallDtorDelete1584 void Emit(CodeGenFunction &CGF, Flags flags) override {
1585 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1586 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1587 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1588 LoadThisForDtorDelete(CGF, Dtor),
1589 CGF.getContext().getTagDeclType(ClassDecl));
1590 }
1591 };
1592
EmitConditionalDtorDeleteCall(CodeGenFunction & CGF,llvm::Value * ShouldDeleteCondition,bool ReturnAfterDelete)1593 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1594 llvm::Value *ShouldDeleteCondition,
1595 bool ReturnAfterDelete) {
1596 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1597 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1598 llvm::Value *ShouldCallDelete
1599 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1600 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1601
1602 CGF.EmitBlock(callDeleteBB);
1603 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1604 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1605 CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1606 LoadThisForDtorDelete(CGF, Dtor),
1607 CGF.getContext().getTagDeclType(ClassDecl));
1608 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1609 ReturnAfterDelete &&
1610 "unexpected value for ReturnAfterDelete");
1611 if (ReturnAfterDelete)
1612 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1613 else
1614 CGF.Builder.CreateBr(continueBB);
1615
1616 CGF.EmitBlock(continueBB);
1617 }
1618
1619 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1620 llvm::Value *ShouldDeleteCondition;
1621
1622 public:
CallDtorDeleteConditional__anon03c1798c0411::CallDtorDeleteConditional1623 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1624 : ShouldDeleteCondition(ShouldDeleteCondition) {
1625 assert(ShouldDeleteCondition != nullptr);
1626 }
1627
Emit__anon03c1798c0411::CallDtorDeleteConditional1628 void Emit(CodeGenFunction &CGF, Flags flags) override {
1629 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1630 /*ReturnAfterDelete*/false);
1631 }
1632 };
1633
1634 class DestroyField final : public EHScopeStack::Cleanup {
1635 const FieldDecl *field;
1636 CodeGenFunction::Destroyer *destroyer;
1637 bool useEHCleanupForArray;
1638
1639 public:
DestroyField(const FieldDecl * field,CodeGenFunction::Destroyer * destroyer,bool useEHCleanupForArray)1640 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1641 bool useEHCleanupForArray)
1642 : field(field), destroyer(destroyer),
1643 useEHCleanupForArray(useEHCleanupForArray) {}
1644
Emit(CodeGenFunction & CGF,Flags flags)1645 void Emit(CodeGenFunction &CGF, Flags flags) override {
1646 // Find the address of the field.
1647 Address thisValue = CGF.LoadCXXThisAddress();
1648 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1649 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1650 LValue LV = CGF.EmitLValueForField(ThisLV, field);
1651 assert(LV.isSimple());
1652
1653 CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer,
1654 flags.isForNormalCleanup() && useEHCleanupForArray);
1655 }
1656 };
1657
EmitSanitizerDtorCallback(CodeGenFunction & CGF,llvm::Value * Ptr,CharUnits::QuantityType PoisonSize)1658 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1659 CharUnits::QuantityType PoisonSize) {
1660 CodeGenFunction::SanitizerScope SanScope(&CGF);
1661 // Pass in void pointer and size of region as arguments to runtime
1662 // function
1663 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1664 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1665
1666 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1667
1668 llvm::FunctionType *FnType =
1669 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1670 llvm::FunctionCallee Fn =
1671 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1672 CGF.EmitNounwindRuntimeCall(Fn, Args);
1673 }
1674
1675 class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
1676 const CXXDestructorDecl *Dtor;
1677
1678 public:
SanitizeDtorMembers(const CXXDestructorDecl * Dtor)1679 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1680
1681 // Generate function call for handling object poisoning.
1682 // Disables tail call elimination, to prevent the current stack frame
1683 // from disappearing from the stack trace.
Emit(CodeGenFunction & CGF,Flags flags)1684 void Emit(CodeGenFunction &CGF, Flags flags) override {
1685 const ASTRecordLayout &Layout =
1686 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1687
1688 // Nothing to poison.
1689 if (Layout.getFieldCount() == 0)
1690 return;
1691
1692 // Prevent the current stack frame from disappearing from the stack trace.
1693 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1694
1695 // Construct pointer to region to begin poisoning, and calculate poison
1696 // size, so that only members declared in this class are poisoned.
1697 ASTContext &Context = CGF.getContext();
1698 unsigned fieldIndex = 0;
1699 int startIndex = -1;
1700 // RecordDecl::field_iterator Field;
1701 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1702 // Poison field if it is trivial
1703 if (FieldHasTrivialDestructorBody(Context, Field)) {
1704 // Start sanitizing at this field
1705 if (startIndex < 0)
1706 startIndex = fieldIndex;
1707
1708 // Currently on the last field, and it must be poisoned with the
1709 // current block.
1710 if (fieldIndex == Layout.getFieldCount() - 1) {
1711 PoisonMembers(CGF, startIndex, Layout.getFieldCount());
1712 }
1713 } else if (startIndex >= 0) {
1714 // No longer within a block of memory to poison, so poison the block
1715 PoisonMembers(CGF, startIndex, fieldIndex);
1716 // Re-set the start index
1717 startIndex = -1;
1718 }
1719 fieldIndex += 1;
1720 }
1721 }
1722
1723 private:
1724 /// \param layoutStartOffset index of the ASTRecordLayout field to
1725 /// start poisoning (inclusive)
1726 /// \param layoutEndOffset index of the ASTRecordLayout field to
1727 /// end poisoning (exclusive)
PoisonMembers(CodeGenFunction & CGF,unsigned layoutStartOffset,unsigned layoutEndOffset)1728 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
1729 unsigned layoutEndOffset) {
1730 ASTContext &Context = CGF.getContext();
1731 const ASTRecordLayout &Layout =
1732 Context.getASTRecordLayout(Dtor->getParent());
1733
1734 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1735 CGF.SizeTy,
1736 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1737 .getQuantity());
1738
1739 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1740 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1741 OffsetSizePtr);
1742
1743 CharUnits::QuantityType PoisonSize;
1744 if (layoutEndOffset >= Layout.getFieldCount()) {
1745 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1746 Context.toCharUnitsFromBits(
1747 Layout.getFieldOffset(layoutStartOffset))
1748 .getQuantity();
1749 } else {
1750 PoisonSize = Context.toCharUnitsFromBits(
1751 Layout.getFieldOffset(layoutEndOffset) -
1752 Layout.getFieldOffset(layoutStartOffset))
1753 .getQuantity();
1754 }
1755
1756 if (PoisonSize == 0)
1757 return;
1758
1759 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
1760 }
1761 };
1762
1763 class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1764 const CXXDestructorDecl *Dtor;
1765
1766 public:
SanitizeDtorVTable(const CXXDestructorDecl * Dtor)1767 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1768
1769 // Generate function call for handling vtable pointer poisoning.
Emit(CodeGenFunction & CGF,Flags flags)1770 void Emit(CodeGenFunction &CGF, Flags flags) override {
1771 assert(Dtor->getParent()->isDynamicClass());
1772 (void)Dtor;
1773 ASTContext &Context = CGF.getContext();
1774 // Poison vtable and vtable ptr if they exist for this class.
1775 llvm::Value *VTablePtr = CGF.LoadCXXThis();
1776
1777 CharUnits::QuantityType PoisonSize =
1778 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1779 // Pass in void pointer and size of region as arguments to runtime
1780 // function
1781 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1782 }
1783 };
1784 } // end anonymous namespace
1785
1786 /// Emit all code that comes at the end of class's
1787 /// destructor. This is to call destructors on members and base classes
1788 /// in reverse order of their construction.
1789 ///
1790 /// For a deleting destructor, this also handles the case where a destroying
1791 /// operator delete completely overrides the definition.
EnterDtorCleanups(const CXXDestructorDecl * DD,CXXDtorType DtorType)1792 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1793 CXXDtorType DtorType) {
1794 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1795 "Should not emit dtor epilogue for non-exported trivial dtor!");
1796
1797 // The deleting-destructor phase just needs to call the appropriate
1798 // operator delete that Sema picked up.
1799 if (DtorType == Dtor_Deleting) {
1800 assert(DD->getOperatorDelete() &&
1801 "operator delete missing - EnterDtorCleanups");
1802 if (CXXStructorImplicitParamValue) {
1803 // If there is an implicit param to the deleting dtor, it's a boolean
1804 // telling whether this is a deleting destructor.
1805 if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1806 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1807 /*ReturnAfterDelete*/true);
1808 else
1809 EHStack.pushCleanup<CallDtorDeleteConditional>(
1810 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1811 } else {
1812 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1813 const CXXRecordDecl *ClassDecl = DD->getParent();
1814 EmitDeleteCall(DD->getOperatorDelete(),
1815 LoadThisForDtorDelete(*this, DD),
1816 getContext().getTagDeclType(ClassDecl));
1817 EmitBranchThroughCleanup(ReturnBlock);
1818 } else {
1819 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1820 }
1821 }
1822 return;
1823 }
1824
1825 const CXXRecordDecl *ClassDecl = DD->getParent();
1826
1827 // Unions have no bases and do not call field destructors.
1828 if (ClassDecl->isUnion())
1829 return;
1830
1831 // The complete-destructor phase just destructs all the virtual bases.
1832 if (DtorType == Dtor_Complete) {
1833 // Poison the vtable pointer such that access after the base
1834 // and member destructors are invoked is invalid.
1835 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1836 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1837 ClassDecl->isPolymorphic())
1838 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1839
1840 // We push them in the forward order so that they'll be popped in
1841 // the reverse order.
1842 for (const auto &Base : ClassDecl->vbases()) {
1843 auto *BaseClassDecl =
1844 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
1845
1846 // Ignore trivial destructors.
1847 if (BaseClassDecl->hasTrivialDestructor())
1848 continue;
1849
1850 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1851 BaseClassDecl,
1852 /*BaseIsVirtual*/ true);
1853 }
1854
1855 return;
1856 }
1857
1858 assert(DtorType == Dtor_Base);
1859 // Poison the vtable pointer if it has no virtual bases, but inherits
1860 // virtual functions.
1861 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1862 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1863 ClassDecl->isPolymorphic())
1864 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1865
1866 // Destroy non-virtual bases.
1867 for (const auto &Base : ClassDecl->bases()) {
1868 // Ignore virtual bases.
1869 if (Base.isVirtual())
1870 continue;
1871
1872 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1873
1874 // Ignore trivial destructors.
1875 if (BaseClassDecl->hasTrivialDestructor())
1876 continue;
1877
1878 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1879 BaseClassDecl,
1880 /*BaseIsVirtual*/ false);
1881 }
1882
1883 // Poison fields such that access after their destructors are
1884 // invoked, and before the base class destructor runs, is invalid.
1885 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1886 SanOpts.has(SanitizerKind::Memory))
1887 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
1888
1889 // Destroy direct fields.
1890 for (const auto *Field : ClassDecl->fields()) {
1891 QualType type = Field->getType();
1892 QualType::DestructionKind dtorKind = type.isDestructedType();
1893 if (!dtorKind) continue;
1894
1895 // Anonymous union members do not have their destructors called.
1896 const RecordType *RT = type->getAsUnionType();
1897 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1898
1899 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1900 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1901 getDestroyer(dtorKind),
1902 cleanupKind & EHCleanup);
1903 }
1904 }
1905
1906 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1907 /// constructor for each of several members of an array.
1908 ///
1909 /// \param ctor the constructor to call for each element
1910 /// \param arrayType the type of the array to initialize
1911 /// \param arrayBegin an arrayType*
1912 /// \param zeroInitialize true if each element should be
1913 /// zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,const ArrayType * arrayType,Address arrayBegin,const CXXConstructExpr * E,bool NewPointerIsChecked,bool zeroInitialize)1914 void CodeGenFunction::EmitCXXAggrConstructorCall(
1915 const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1916 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1917 bool zeroInitialize) {
1918 QualType elementType;
1919 llvm::Value *numElements =
1920 emitArrayLength(arrayType, elementType, arrayBegin);
1921
1922 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1923 NewPointerIsChecked, zeroInitialize);
1924 }
1925
1926 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1927 /// constructor for each of several members of an array.
1928 ///
1929 /// \param ctor the constructor to call for each element
1930 /// \param numElements the number of elements in the array;
1931 /// may be zero
1932 /// \param arrayBase a T*, where T is the type constructed by ctor
1933 /// \param zeroInitialize true if each element should be
1934 /// zero-initialized before it is constructed
EmitCXXAggrConstructorCall(const CXXConstructorDecl * ctor,llvm::Value * numElements,Address arrayBase,const CXXConstructExpr * E,bool NewPointerIsChecked,bool zeroInitialize)1935 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1936 llvm::Value *numElements,
1937 Address arrayBase,
1938 const CXXConstructExpr *E,
1939 bool NewPointerIsChecked,
1940 bool zeroInitialize) {
1941 // It's legal for numElements to be zero. This can happen both
1942 // dynamically, because x can be zero in 'new A[x]', and statically,
1943 // because of GCC extensions that permit zero-length arrays. There
1944 // are probably legitimate places where we could assume that this
1945 // doesn't happen, but it's not clear that it's worth it.
1946 llvm::BranchInst *zeroCheckBranch = nullptr;
1947
1948 // Optimize for a constant count.
1949 llvm::ConstantInt *constantCount
1950 = dyn_cast<llvm::ConstantInt>(numElements);
1951 if (constantCount) {
1952 // Just skip out if the constant count is zero.
1953 if (constantCount->isZero()) return;
1954
1955 // Otherwise, emit the check.
1956 } else {
1957 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1958 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1959 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1960 EmitBlock(loopBB);
1961 }
1962
1963 // Find the end of the array.
1964 llvm::Value *arrayBegin = arrayBase.getPointer();
1965 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1966 "arrayctor.end");
1967
1968 // Enter the loop, setting up a phi for the current location to initialize.
1969 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1970 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1971 EmitBlock(loopBB);
1972 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1973 "arrayctor.cur");
1974 cur->addIncoming(arrayBegin, entryBB);
1975
1976 // Inside the loop body, emit the constructor call on the array element.
1977
1978 // The alignment of the base, adjusted by the size of a single element,
1979 // provides a conservative estimate of the alignment of every element.
1980 // (This assumes we never start tracking offsetted alignments.)
1981 //
1982 // Note that these are complete objects and so we don't need to
1983 // use the non-virtual size or alignment.
1984 QualType type = getContext().getTypeDeclType(ctor->getParent());
1985 CharUnits eltAlignment =
1986 arrayBase.getAlignment()
1987 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1988 Address curAddr = Address(cur, eltAlignment);
1989
1990 // Zero initialize the storage, if requested.
1991 if (zeroInitialize)
1992 EmitNullInitialization(curAddr, type);
1993
1994 // C++ [class.temporary]p4:
1995 // There are two contexts in which temporaries are destroyed at a different
1996 // point than the end of the full-expression. The first context is when a
1997 // default constructor is called to initialize an element of an array.
1998 // If the constructor has one or more default arguments, the destruction of
1999 // every temporary created in a default argument expression is sequenced
2000 // before the construction of the next array element, if any.
2001
2002 {
2003 RunCleanupsScope Scope(*this);
2004
2005 // Evaluate the constructor and its arguments in a regular
2006 // partial-destroy cleanup.
2007 if (getLangOpts().Exceptions &&
2008 !ctor->getParent()->hasTrivialDestructor()) {
2009 Destroyer *destroyer = destroyCXXObject;
2010 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
2011 *destroyer);
2012 }
2013 auto currAVS = AggValueSlot::forAddr(
2014 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
2015 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
2016 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
2017 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
2018 : AggValueSlot::IsNotSanitizerChecked);
2019 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
2020 /*Delegating=*/false, currAVS, E);
2021 }
2022
2023 // Go to the next element.
2024 llvm::Value *next =
2025 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
2026 "arrayctor.next");
2027 cur->addIncoming(next, Builder.GetInsertBlock());
2028
2029 // Check whether that's the end of the loop.
2030 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
2031 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
2032 Builder.CreateCondBr(done, contBB, loopBB);
2033
2034 // Patch the earlier check to skip over the loop.
2035 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
2036
2037 EmitBlock(contBB);
2038 }
2039
destroyCXXObject(CodeGenFunction & CGF,Address addr,QualType type)2040 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
2041 Address addr,
2042 QualType type) {
2043 const RecordType *rtype = type->castAs<RecordType>();
2044 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2045 const CXXDestructorDecl *dtor = record->getDestructor();
2046 assert(!dtor->isTrivial());
2047 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
2048 /*Delegating=*/false, addr, type);
2049 }
2050
EmitCXXConstructorCall(const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,AggValueSlot ThisAVS,const CXXConstructExpr * E)2051 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2052 CXXCtorType Type,
2053 bool ForVirtualBase,
2054 bool Delegating,
2055 AggValueSlot ThisAVS,
2056 const CXXConstructExpr *E) {
2057 CallArgList Args;
2058 Address This = ThisAVS.getAddress();
2059 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
2060 QualType ThisType = D->getThisType();
2061 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2062 llvm::Value *ThisPtr = This.getPointer();
2063
2064 if (SlotAS != ThisAS) {
2065 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2066 llvm::Type *NewType =
2067 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2068 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2069 ThisAS, SlotAS, NewType);
2070 }
2071
2072 // Push the this ptr.
2073 Args.add(RValue::get(ThisPtr), D->getThisType());
2074
2075 // If this is a trivial constructor, emit a memcpy now before we lose
2076 // the alignment information on the argument.
2077 // FIXME: It would be better to preserve alignment information into CallArg.
2078 if (isMemcpyEquivalentSpecialMember(D)) {
2079 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2080
2081 const Expr *Arg = E->getArg(0);
2082 LValue Src = EmitLValue(Arg);
2083 QualType DestTy = getContext().getTypeDeclType(D->getParent());
2084 LValue Dest = MakeAddrLValue(This, DestTy);
2085 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
2086 return;
2087 }
2088
2089 // Add the rest of the user-supplied arguments.
2090 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2091 EvaluationOrder Order = E->isListInitialization()
2092 ? EvaluationOrder::ForceLeftToRight
2093 : EvaluationOrder::Default;
2094 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2095 /*ParamsToSkip*/ 0, Order);
2096
2097 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2098 ThisAVS.mayOverlap(), E->getExprLoc(),
2099 ThisAVS.isSanitizerChecked());
2100 }
2101
canEmitDelegateCallArgs(CodeGenFunction & CGF,const CXXConstructorDecl * Ctor,CXXCtorType Type,CallArgList & Args)2102 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2103 const CXXConstructorDecl *Ctor,
2104 CXXCtorType Type, CallArgList &Args) {
2105 // We can't forward a variadic call.
2106 if (Ctor->isVariadic())
2107 return false;
2108
2109 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2110 // If the parameters are callee-cleanup, it's not safe to forward.
2111 for (auto *P : Ctor->parameters())
2112 if (P->needsDestruction(CGF.getContext()))
2113 return false;
2114
2115 // Likewise if they're inalloca.
2116 const CGFunctionInfo &Info =
2117 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
2118 if (Info.usesInAlloca())
2119 return false;
2120 }
2121
2122 // Anything else should be OK.
2123 return true;
2124 }
2125
EmitCXXConstructorCall(const CXXConstructorDecl * D,CXXCtorType Type,bool ForVirtualBase,bool Delegating,Address This,CallArgList & Args,AggValueSlot::Overlap_t Overlap,SourceLocation Loc,bool NewPointerIsChecked)2126 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2127 CXXCtorType Type,
2128 bool ForVirtualBase,
2129 bool Delegating,
2130 Address This,
2131 CallArgList &Args,
2132 AggValueSlot::Overlap_t Overlap,
2133 SourceLocation Loc,
2134 bool NewPointerIsChecked) {
2135 const CXXRecordDecl *ClassDecl = D->getParent();
2136
2137 if (!NewPointerIsChecked)
2138 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2139 getContext().getRecordType(ClassDecl), CharUnits::Zero());
2140
2141 if (D->isTrivial() && D->isDefaultConstructor()) {
2142 assert(Args.size() == 1 && "trivial default ctor with args");
2143 return;
2144 }
2145
2146 // If this is a trivial constructor, just emit what's needed. If this is a
2147 // union copy constructor, we must emit a memcpy, because the AST does not
2148 // model that copy.
2149 if (isMemcpyEquivalentSpecialMember(D)) {
2150 assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2151
2152 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2153 Address Src(Args[1].getRValue(*this).getScalarVal(),
2154 CGM.getNaturalTypeAlignment(SrcTy));
2155 LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
2156 QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2157 LValue DestLVal = MakeAddrLValue(This, DestTy);
2158 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
2159 return;
2160 }
2161
2162 bool PassPrototypeArgs = true;
2163 // Check whether we can actually emit the constructor before trying to do so.
2164 if (auto Inherited = D->getInheritedConstructor()) {
2165 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2166 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2167 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2168 Delegating, Args);
2169 return;
2170 }
2171 }
2172
2173 // Insert any ABI-specific implicit constructor arguments.
2174 CGCXXABI::AddedStructorArgCounts ExtraArgs =
2175 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2176 Delegating, Args);
2177
2178 // Emit the call.
2179 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
2180 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2181 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
2182 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
2183 EmitCall(Info, Callee, ReturnValueSlot(), Args, nullptr, Loc);
2184
2185 // Generate vtable assumptions if we're constructing a complete object
2186 // with a vtable. We don't do this for base subobjects for two reasons:
2187 // first, it's incorrect for classes with virtual bases, and second, we're
2188 // about to overwrite the vptrs anyway.
2189 // We also have to make sure if we can refer to vtable:
2190 // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2191 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2192 // sure that definition of vtable is not hidden,
2193 // then we are always safe to refer to it.
2194 // FIXME: It looks like InstCombine is very inefficient on dealing with
2195 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2196 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2197 ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2198 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2199 CGM.getCodeGenOpts().StrictVTablePointers)
2200 EmitVTableAssumptionLoads(ClassDecl, This);
2201 }
2202
EmitInheritedCXXConstructorCall(const CXXConstructorDecl * D,bool ForVirtualBase,Address This,bool InheritedFromVBase,const CXXInheritedCtorInitExpr * E)2203 void CodeGenFunction::EmitInheritedCXXConstructorCall(
2204 const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2205 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2206 CallArgList Args;
2207 CallArg ThisArg(
2208 RValue::get(This.getPointer(), This.getAlignment().getQuantity()),
2209 D->getThisType());
2210
2211 // Forward the parameters.
2212 if (InheritedFromVBase &&
2213 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2214 // Nothing to do; this construction is not responsible for constructing
2215 // the base class containing the inherited constructor.
2216 // FIXME: Can we just pass undef's for the remaining arguments if we don't
2217 // have constructor variants?
2218 Args.push_back(ThisArg);
2219 } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2220 // The inheriting constructor was inlined; just inject its arguments.
2221 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2222 "wrong number of parameters for inherited constructor call");
2223 Args = CXXInheritedCtorInitExprArgs;
2224 Args[0] = ThisArg;
2225 } else {
2226 // The inheriting constructor was not inlined. Emit delegating arguments.
2227 Args.push_back(ThisArg);
2228 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2229 assert(OuterCtor->getNumParams() == D->getNumParams());
2230 assert(!OuterCtor->isVariadic() && "should have been inlined");
2231
2232 for (const auto *Param : OuterCtor->parameters()) {
2233 assert(getContext().hasSameUnqualifiedType(
2234 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2235 Param->getType()));
2236 EmitDelegateCallArg(Args, Param, E->getLocation());
2237
2238 // Forward __attribute__(pass_object_size).
2239 if (Param->hasAttr<PassObjectSizeAttr>()) {
2240 auto *POSParam = SizeArguments[Param];
2241 assert(POSParam && "missing pass_object_size value for forwarding");
2242 EmitDelegateCallArg(Args, POSParam, E->getLocation());
2243 }
2244 }
2245 }
2246
2247 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2248 This, Args, AggValueSlot::MayOverlap,
2249 E->getLocation(), /*NewPointerIsChecked*/true);
2250 }
2251
EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl * Ctor,CXXCtorType CtorType,bool ForVirtualBase,bool Delegating,CallArgList & Args)2252 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2253 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2254 bool Delegating, CallArgList &Args) {
2255 GlobalDecl GD(Ctor, CtorType);
2256 InlinedInheritingConstructorScope Scope(*this, GD);
2257 ApplyInlineDebugLocation DebugScope(*this, GD);
2258 RunCleanupsScope RunCleanups(*this);
2259
2260 // Save the arguments to be passed to the inherited constructor.
2261 CXXInheritedCtorInitExprArgs = Args;
2262
2263 FunctionArgList Params;
2264 QualType RetType = BuildFunctionArgList(CurGD, Params);
2265 FnRetTy = RetType;
2266
2267 // Insert any ABI-specific implicit constructor arguments.
2268 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2269 ForVirtualBase, Delegating, Args);
2270
2271 // Emit a simplified prolog. We only need to emit the implicit params.
2272 assert(Args.size() >= Params.size() && "too few arguments for call");
2273 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2274 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2275 const RValue &RV = Args[I].getRValue(*this);
2276 assert(!RV.isComplex() && "complex indirect params not supported");
2277 ParamValue Val = RV.isScalar()
2278 ? ParamValue::forDirect(RV.getScalarVal())
2279 : ParamValue::forIndirect(RV.getAggregateAddress());
2280 EmitParmDecl(*Params[I], Val, I + 1);
2281 }
2282 }
2283
2284 // Create a return value slot if the ABI implementation wants one.
2285 // FIXME: This is dumb, we should ask the ABI not to try to set the return
2286 // value instead.
2287 if (!RetType->isVoidType())
2288 ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2289
2290 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2291 CXXThisValue = CXXABIThisValue;
2292
2293 // Directly emit the constructor initializers.
2294 EmitCtorPrologue(Ctor, CtorType, Params);
2295 }
2296
EmitVTableAssumptionLoad(const VPtr & Vptr,Address This)2297 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2298 llvm::Value *VTableGlobal =
2299 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2300 if (!VTableGlobal)
2301 return;
2302
2303 // We can just use the base offset in the complete class.
2304 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2305
2306 if (!NonVirtualOffset.isZero())
2307 This =
2308 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2309 Vptr.VTableClass, Vptr.NearestVBase);
2310
2311 llvm::Value *VPtrValue =
2312 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2313 llvm::Value *Cmp =
2314 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2315 Builder.CreateAssumption(Cmp);
2316 }
2317
EmitVTableAssumptionLoads(const CXXRecordDecl * ClassDecl,Address This)2318 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2319 Address This) {
2320 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2321 for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2322 EmitVTableAssumptionLoad(Vptr, This);
2323 }
2324
2325 void
EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl * D,Address This,Address Src,const CXXConstructExpr * E)2326 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2327 Address This, Address Src,
2328 const CXXConstructExpr *E) {
2329 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2330
2331 CallArgList Args;
2332
2333 // Push the this ptr.
2334 Args.add(RValue::get(This.getPointer(), This.getAlignment().getQuantity()),
2335 D->getThisType());
2336
2337 // Push the src ptr.
2338 QualType QT = *(FPT->param_type_begin());
2339 llvm::Type *t = CGM.getTypes().ConvertType(QT);
2340 Src = Builder.CreateBitCast(Src, t);
2341 Args.add(RValue::get(Src.getPointer(), Src.getAlignment().getQuantity()), QT);
2342
2343 // Skip over first argument (Src).
2344 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2345 /*ParamsToSkip*/ 1);
2346
2347 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2348 /*Delegating*/false, This, Args,
2349 AggValueSlot::MayOverlap, E->getExprLoc(),
2350 /*NewPointerIsChecked*/false);
2351 }
2352
2353 void
EmitDelegateCXXConstructorCall(const CXXConstructorDecl * Ctor,CXXCtorType CtorType,const FunctionArgList & Args,SourceLocation Loc)2354 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2355 CXXCtorType CtorType,
2356 const FunctionArgList &Args,
2357 SourceLocation Loc) {
2358 CallArgList DelegateArgs;
2359
2360 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2361 assert(I != E && "no parameters to constructor");
2362
2363 // this
2364 Address This = LoadCXXThisAddress();
2365 DelegateArgs.add(
2366 RValue::get(This.getPointer(), This.getAlignment().getQuantity()),
2367 (*I)->getType());
2368 ++I;
2369
2370 // FIXME: The location of the VTT parameter in the parameter list is
2371 // specific to the Itanium ABI and shouldn't be hardcoded here.
2372 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2373 assert(I != E && "cannot skip vtt parameter, already done with args");
2374 assert((*I)->getType()->isPointerType() &&
2375 "skipping parameter not of vtt type");
2376 ++I;
2377 }
2378
2379 // Explicit arguments.
2380 for (; I != E; ++I) {
2381 const VarDecl *param = *I;
2382 // FIXME: per-argument source location
2383 EmitDelegateCallArg(DelegateArgs, param, Loc);
2384 }
2385
2386 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2387 /*Delegating=*/true, This, DelegateArgs,
2388 AggValueSlot::MayOverlap, Loc,
2389 /*NewPointerIsChecked=*/true);
2390 }
2391
2392 namespace {
2393 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2394 const CXXDestructorDecl *Dtor;
2395 Address Addr;
2396 CXXDtorType Type;
2397
CallDelegatingCtorDtor__anon03c1798c0511::CallDelegatingCtorDtor2398 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2399 CXXDtorType Type)
2400 : Dtor(D), Addr(Addr), Type(Type) {}
2401
Emit__anon03c1798c0511::CallDelegatingCtorDtor2402 void Emit(CodeGenFunction &CGF, Flags flags) override {
2403 // We are calling the destructor from within the constructor.
2404 // Therefore, "this" should have the expected type.
2405 QualType ThisTy = Dtor->getThisObjectType();
2406 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2407 /*Delegating=*/true, Addr, ThisTy);
2408 }
2409 };
2410 } // end anonymous namespace
2411
2412 void
EmitDelegatingCXXConstructorCall(const CXXConstructorDecl * Ctor,const FunctionArgList & Args)2413 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2414 const FunctionArgList &Args) {
2415 assert(Ctor->isDelegatingConstructor());
2416
2417 Address ThisPtr = LoadCXXThisAddress();
2418
2419 AggValueSlot AggSlot =
2420 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2421 AggValueSlot::IsDestructed,
2422 AggValueSlot::DoesNotNeedGCBarriers,
2423 AggValueSlot::IsNotAliased,
2424 AggValueSlot::MayOverlap,
2425 AggValueSlot::IsNotZeroed,
2426 // Checks are made by the code that calls constructor.
2427 AggValueSlot::IsSanitizerChecked);
2428
2429 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2430
2431 const CXXRecordDecl *ClassDecl = Ctor->getParent();
2432 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2433 CXXDtorType Type =
2434 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2435
2436 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2437 ClassDecl->getDestructor(),
2438 ThisPtr, Type);
2439 }
2440 }
2441
EmitCXXDestructorCall(const CXXDestructorDecl * DD,CXXDtorType Type,bool ForVirtualBase,bool Delegating,Address This,QualType ThisTy)2442 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2443 CXXDtorType Type,
2444 bool ForVirtualBase,
2445 bool Delegating, Address This,
2446 QualType ThisTy) {
2447 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2448 Delegating, This, ThisTy);
2449 }
2450
2451 namespace {
2452 struct CallLocalDtor final : EHScopeStack::Cleanup {
2453 const CXXDestructorDecl *Dtor;
2454 Address Addr;
2455 QualType Ty;
2456
CallLocalDtor__anon03c1798c0611::CallLocalDtor2457 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
2458 : Dtor(D), Addr(Addr), Ty(Ty) {}
2459
Emit__anon03c1798c0611::CallLocalDtor2460 void Emit(CodeGenFunction &CGF, Flags flags) override {
2461 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
2462 /*ForVirtualBase=*/false,
2463 /*Delegating=*/false, Addr, Ty);
2464 }
2465 };
2466 } // end anonymous namespace
2467
PushDestructorCleanup(const CXXDestructorDecl * D,QualType T,Address Addr)2468 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2469 QualType T, Address Addr) {
2470 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
2471 }
2472
PushDestructorCleanup(QualType T,Address Addr)2473 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2474 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2475 if (!ClassDecl) return;
2476 if (ClassDecl->hasTrivialDestructor()) return;
2477
2478 const CXXDestructorDecl *D = ClassDecl->getDestructor();
2479 assert(D && D->isUsed() && "destructor not marked as used!");
2480 PushDestructorCleanup(D, T, Addr);
2481 }
2482
InitializeVTablePointer(const VPtr & Vptr)2483 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2484 // Compute the address point.
2485 llvm::Value *VTableAddressPoint =
2486 CGM.getCXXABI().getVTableAddressPointInStructor(
2487 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2488
2489 if (!VTableAddressPoint)
2490 return;
2491
2492 // Compute where to store the address point.
2493 llvm::Value *VirtualOffset = nullptr;
2494 CharUnits NonVirtualOffset = CharUnits::Zero();
2495
2496 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2497 // We need to use the virtual base offset offset because the virtual base
2498 // might have a different offset in the most derived class.
2499
2500 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2501 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2502 NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2503 } else {
2504 // We can just use the base offset in the complete class.
2505 NonVirtualOffset = Vptr.Base.getBaseOffset();
2506 }
2507
2508 // Apply the offsets.
2509 Address VTableField = LoadCXXThisAddress();
2510
2511 if (!NonVirtualOffset.isZero() || VirtualOffset)
2512 VTableField = ApplyNonVirtualAndVirtualOffset(
2513 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2514 Vptr.NearestVBase);
2515
2516 // Finally, store the address point. Use the same LLVM types as the field to
2517 // support optimization.
2518 unsigned DefaultAS = CGM.getTargetCodeGenInfo().getDefaultAS();
2519 llvm::Type *VTablePtrTy =
2520 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2521 ->getPointerTo(DefaultAS)
2522 ->getPointerTo(DefaultAS);
2523 VTableField = Builder.CreateBitCast(VTableField,
2524 VTablePtrTy->getPointerTo(DefaultAS));
2525 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2526
2527 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2528 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2529 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2530 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2531 CGM.getCodeGenOpts().StrictVTablePointers)
2532 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2533 }
2534
2535 CodeGenFunction::VPtrsVector
getVTablePointers(const CXXRecordDecl * VTableClass)2536 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2537 CodeGenFunction::VPtrsVector VPtrsResult;
2538 VisitedVirtualBasesSetTy VBases;
2539 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2540 /*NearestVBase=*/nullptr,
2541 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2542 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2543 VPtrsResult);
2544 return VPtrsResult;
2545 }
2546
getVTablePointers(BaseSubobject Base,const CXXRecordDecl * NearestVBase,CharUnits OffsetFromNearestVBase,bool BaseIsNonVirtualPrimaryBase,const CXXRecordDecl * VTableClass,VisitedVirtualBasesSetTy & VBases,VPtrsVector & Vptrs)2547 void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2548 const CXXRecordDecl *NearestVBase,
2549 CharUnits OffsetFromNearestVBase,
2550 bool BaseIsNonVirtualPrimaryBase,
2551 const CXXRecordDecl *VTableClass,
2552 VisitedVirtualBasesSetTy &VBases,
2553 VPtrsVector &Vptrs) {
2554 // If this base is a non-virtual primary base the address point has already
2555 // been set.
2556 if (!BaseIsNonVirtualPrimaryBase) {
2557 // Initialize the vtable pointer for this base.
2558 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2559 Vptrs.push_back(Vptr);
2560 }
2561
2562 const CXXRecordDecl *RD = Base.getBase();
2563
2564 // Traverse bases.
2565 for (const auto &I : RD->bases()) {
2566 auto *BaseDecl =
2567 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2568
2569 // Ignore classes without a vtable.
2570 if (!BaseDecl->isDynamicClass())
2571 continue;
2572
2573 CharUnits BaseOffset;
2574 CharUnits BaseOffsetFromNearestVBase;
2575 bool BaseDeclIsNonVirtualPrimaryBase;
2576
2577 if (I.isVirtual()) {
2578 // Check if we've visited this virtual base before.
2579 if (!VBases.insert(BaseDecl).second)
2580 continue;
2581
2582 const ASTRecordLayout &Layout =
2583 getContext().getASTRecordLayout(VTableClass);
2584
2585 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2586 BaseOffsetFromNearestVBase = CharUnits::Zero();
2587 BaseDeclIsNonVirtualPrimaryBase = false;
2588 } else {
2589 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2590
2591 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2592 BaseOffsetFromNearestVBase =
2593 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2594 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2595 }
2596
2597 getVTablePointers(
2598 BaseSubobject(BaseDecl, BaseOffset),
2599 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2600 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2601 }
2602 }
2603
InitializeVTablePointers(const CXXRecordDecl * RD)2604 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2605 // Ignore classes without a vtable.
2606 if (!RD->isDynamicClass())
2607 return;
2608
2609 // Initialize the vtable pointers for this class and all of its bases.
2610 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2611 for (const VPtr &Vptr : getVTablePointers(RD))
2612 InitializeVTablePointer(Vptr);
2613
2614 if (RD->getNumVBases())
2615 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2616 }
2617
GetVTablePtr(Address This,llvm::Type * VTableTy,const CXXRecordDecl * RD)2618 llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
2619 llvm::Type *VTableTy,
2620 const CXXRecordDecl *RD) {
2621 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2622 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2623 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2624 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
2625
2626 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2627 CGM.getCodeGenOpts().StrictVTablePointers)
2628 CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2629
2630 return VTable;
2631 }
2632
2633 // If a class has a single non-virtual base and does not introduce or override
2634 // virtual member functions or fields, it will have the same layout as its base.
2635 // This function returns the least derived such class.
2636 //
2637 // Casting an instance of a base class to such a derived class is technically
2638 // undefined behavior, but it is a relatively common hack for introducing member
2639 // functions on class instances with specific properties (e.g. llvm::Operator)
2640 // that works under most compilers and should not have security implications, so
2641 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2642 static const CXXRecordDecl *
LeastDerivedClassWithSameLayout(const CXXRecordDecl * RD)2643 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2644 if (!RD->field_empty())
2645 return RD;
2646
2647 if (RD->getNumVBases() != 0)
2648 return RD;
2649
2650 if (RD->getNumBases() != 1)
2651 return RD;
2652
2653 for (const CXXMethodDecl *MD : RD->methods()) {
2654 if (MD->isVirtual()) {
2655 // Virtual member functions are only ok if they are implicit destructors
2656 // because the implicit destructor will have the same semantics as the
2657 // base class's destructor if no fields are added.
2658 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2659 continue;
2660 return RD;
2661 }
2662 }
2663
2664 return LeastDerivedClassWithSameLayout(
2665 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2666 }
2667
EmitTypeMetadataCodeForVCall(const CXXRecordDecl * RD,llvm::Value * VTable,SourceLocation Loc)2668 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2669 llvm::Value *VTable,
2670 SourceLocation Loc) {
2671 if (SanOpts.has(SanitizerKind::CFIVCall))
2672 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2673 else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2674 // Don't insert type test assumes if we are forcing public std
2675 // visibility.
2676 !CGM.HasLTOVisibilityPublicStd(RD)) {
2677 llvm::Metadata *MD =
2678 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2679 llvm::Value *TypeId =
2680 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2681
2682 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2683 llvm::Value *TypeTest =
2684 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2685 {CastedVTable, TypeId});
2686 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2687 }
2688 }
2689
EmitVTablePtrCheckForCall(const CXXRecordDecl * RD,llvm::Value * VTable,CFITypeCheckKind TCK,SourceLocation Loc)2690 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2691 llvm::Value *VTable,
2692 CFITypeCheckKind TCK,
2693 SourceLocation Loc) {
2694 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2695 RD = LeastDerivedClassWithSameLayout(RD);
2696
2697 EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2698 }
2699
EmitVTablePtrCheckForCast(QualType T,llvm::Value * Derived,bool MayBeNull,CFITypeCheckKind TCK,SourceLocation Loc)2700 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2701 llvm::Value *Derived,
2702 bool MayBeNull,
2703 CFITypeCheckKind TCK,
2704 SourceLocation Loc) {
2705 if (!getLangOpts().CPlusPlus)
2706 return;
2707
2708 auto *ClassTy = T->getAs<RecordType>();
2709 if (!ClassTy)
2710 return;
2711
2712 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2713
2714 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2715 return;
2716
2717 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2718 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2719
2720 llvm::BasicBlock *ContBlock = nullptr;
2721
2722 if (MayBeNull) {
2723 llvm::Value *DerivedNotNull =
2724 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2725
2726 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2727 ContBlock = createBasicBlock("cast.cont");
2728
2729 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2730
2731 EmitBlock(CheckBlock);
2732 }
2733
2734 llvm::Value *VTable;
2735 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2736 *this, Address(Derived, getPointerAlign()), ClassDecl);
2737
2738 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2739
2740 if (MayBeNull) {
2741 Builder.CreateBr(ContBlock);
2742 EmitBlock(ContBlock);
2743 }
2744 }
2745
EmitVTablePtrCheck(const CXXRecordDecl * RD,llvm::Value * VTable,CFITypeCheckKind TCK,SourceLocation Loc)2746 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2747 llvm::Value *VTable,
2748 CFITypeCheckKind TCK,
2749 SourceLocation Loc) {
2750 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2751 !CGM.HasHiddenLTOVisibility(RD))
2752 return;
2753
2754 SanitizerMask M;
2755 llvm::SanitizerStatKind SSK;
2756 switch (TCK) {
2757 case CFITCK_VCall:
2758 M = SanitizerKind::CFIVCall;
2759 SSK = llvm::SanStat_CFI_VCall;
2760 break;
2761 case CFITCK_NVCall:
2762 M = SanitizerKind::CFINVCall;
2763 SSK = llvm::SanStat_CFI_NVCall;
2764 break;
2765 case CFITCK_DerivedCast:
2766 M = SanitizerKind::CFIDerivedCast;
2767 SSK = llvm::SanStat_CFI_DerivedCast;
2768 break;
2769 case CFITCK_UnrelatedCast:
2770 M = SanitizerKind::CFIUnrelatedCast;
2771 SSK = llvm::SanStat_CFI_UnrelatedCast;
2772 break;
2773 case CFITCK_ICall:
2774 case CFITCK_NVMFCall:
2775 case CFITCK_VMFCall:
2776 llvm_unreachable("unexpected sanitizer kind");
2777 }
2778
2779 std::string TypeName = RD->getQualifiedNameAsString();
2780 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2781 return;
2782
2783 SanitizerScope SanScope(this);
2784 EmitSanitizerStatReport(SSK);
2785
2786 llvm::Metadata *MD =
2787 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2788 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2789
2790 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2791 llvm::Value *TypeTest = Builder.CreateCall(
2792 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2793
2794 llvm::Constant *StaticData[] = {
2795 llvm::ConstantInt::get(Int8Ty, TCK),
2796 EmitCheckSourceLocation(Loc),
2797 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2798 };
2799
2800 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2801 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2802 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2803 return;
2804 }
2805
2806 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2807 EmitTrapCheck(TypeTest);
2808 return;
2809 }
2810
2811 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2812 CGM.getLLVMContext(),
2813 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2814 llvm::Value *ValidVtable = Builder.CreateCall(
2815 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2816 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2817 StaticData, {CastedVTable, ValidVtable});
2818 }
2819
ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl * RD)2820 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2821 if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2822 !CGM.HasHiddenLTOVisibility(RD))
2823 return false;
2824
2825 if (CGM.getCodeGenOpts().VirtualFunctionElimination)
2826 return true;
2827
2828 if (!SanOpts.has(SanitizerKind::CFIVCall) ||
2829 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
2830 return false;
2831
2832 std::string TypeName = RD->getQualifiedNameAsString();
2833 return !getContext().getSanitizerBlacklist().isBlacklistedType(
2834 SanitizerKind::CFIVCall, TypeName);
2835 }
2836
EmitVTableTypeCheckedLoad(const CXXRecordDecl * RD,llvm::Value * VTable,uint64_t VTableByteOffset)2837 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2838 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2839 SanitizerScope SanScope(this);
2840
2841 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2842
2843 llvm::Metadata *MD =
2844 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2845 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2846
2847 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2848 llvm::Value *CheckedLoad = Builder.CreateCall(
2849 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2850 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2851 TypeId});
2852 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2853
2854 std::string TypeName = RD->getQualifiedNameAsString();
2855 if (SanOpts.has(SanitizerKind::CFIVCall) &&
2856 !getContext().getSanitizerBlacklist().isBlacklistedType(
2857 SanitizerKind::CFIVCall, TypeName)) {
2858 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2859 SanitizerHandler::CFICheckFail, {}, {});
2860 }
2861
2862 return Builder.CreateBitCast(
2863 Builder.CreateExtractValue(CheckedLoad, 0),
2864 cast<llvm::PointerType>(VTable->getType())->getElementType());
2865 }
2866
EmitForwardingCallToLambda(const CXXMethodDecl * callOperator,CallArgList & callArgs)2867 void CodeGenFunction::EmitForwardingCallToLambda(
2868 const CXXMethodDecl *callOperator,
2869 CallArgList &callArgs) {
2870 // Get the address of the call operator.
2871 const CGFunctionInfo &calleeFnInfo =
2872 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2873 llvm::Constant *calleePtr =
2874 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2875 CGM.getTypes().GetFunctionType(calleeFnInfo));
2876
2877 // Prepare the return slot.
2878 const FunctionProtoType *FPT =
2879 callOperator->getType()->castAs<FunctionProtoType>();
2880 QualType resultType = FPT->getReturnType();
2881 ReturnValueSlot returnSlot;
2882 if (!resultType->isVoidType() &&
2883 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2884 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2885 returnSlot =
2886 ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(),
2887 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
2888
2889 // We don't need to separately arrange the call arguments because
2890 // the call can't be variadic anyway --- it's impossible to forward
2891 // variadic arguments.
2892
2893 // Now emit our call.
2894 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
2895 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2896
2897 // If necessary, copy the returned value into the slot.
2898 if (!resultType->isVoidType() && returnSlot.isNull()) {
2899 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2900 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2901 }
2902 EmitReturnOfRValue(RV, resultType);
2903 } else
2904 EmitBranchThroughCleanup(ReturnBlock);
2905 }
2906
EmitLambdaBlockInvokeBody()2907 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2908 const BlockDecl *BD = BlockInfo->getBlockDecl();
2909 const VarDecl *variable = BD->capture_begin()->getVariable();
2910 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2911 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2912
2913 if (CallOp->isVariadic()) {
2914 // FIXME: Making this work correctly is nasty because it requires either
2915 // cloning the body of the call operator or making the call operator
2916 // forward.
2917 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2918 return;
2919 }
2920
2921 // Start building arguments for forwarding call
2922 CallArgList CallArgs;
2923
2924 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2925 Address ThisPtr = GetAddrOfBlockDecl(variable);
2926 CallArgs.add(
2927 RValue::get(ThisPtr.getPointer(), ThisPtr.getAlignment().getQuantity()),
2928 ThisType);
2929
2930 // Add the rest of the parameters.
2931 for (auto param : BD->parameters())
2932 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
2933
2934 assert(!Lambda->isGenericLambda() &&
2935 "generic lambda interconversion to block not implemented");
2936 EmitForwardingCallToLambda(CallOp, CallArgs);
2937 }
2938
EmitLambdaDelegatingInvokeBody(const CXXMethodDecl * MD)2939 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2940 const CXXRecordDecl *Lambda = MD->getParent();
2941
2942 // Start building arguments for forwarding call
2943 CallArgList CallArgs;
2944
2945 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2946 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2947 CallArgs.add(RValue::get(ThisPtr), ThisType);
2948
2949 // Add the rest of the parameters.
2950 for (auto Param : MD->parameters())
2951 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
2952
2953 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2954 // For a generic lambda, find the corresponding call operator specialization
2955 // to which the call to the static-invoker shall be forwarded.
2956 if (Lambda->isGenericLambda()) {
2957 assert(MD->isFunctionTemplateSpecialization());
2958 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2959 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2960 void *InsertPos = nullptr;
2961 FunctionDecl *CorrespondingCallOpSpecialization =
2962 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2963 assert(CorrespondingCallOpSpecialization);
2964 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2965 }
2966 EmitForwardingCallToLambda(CallOp, CallArgs);
2967 }
2968
EmitLambdaStaticInvokeBody(const CXXMethodDecl * MD)2969 void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
2970 if (MD->isVariadic()) {
2971 // FIXME: Making this work correctly is nasty because it requires either
2972 // cloning the body of the call operator or making the call operator forward.
2973 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2974 return;
2975 }
2976
2977 EmitLambdaDelegatingInvokeBody(MD);
2978 }
2979