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