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