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