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