1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
33     const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
34     CastExpr::path_const_iterator End) {
35   CharUnits Offset = CharUnits::Zero();
36 
37   const ASTContext &Context = getContext();
38   const CXXRecordDecl *RD = DerivedClass;
39 
40   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
41     const CXXBaseSpecifier *Base = *I;
42     assert(!Base->isVirtual() && "Should not see virtual bases here!");
43 
44     // Get the layout.
45     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46 
47     const CXXRecordDecl *BaseDecl =
48       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49 
50     // Add the offset.
51     Offset += Layout.getBaseClassOffset(BaseDecl);
52 
53     RD = BaseDecl;
54   }
55 
56   return Offset;
57 }
58 
59 llvm::Constant *
60 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
61                                    CastExpr::path_const_iterator PathBegin,
62                                    CastExpr::path_const_iterator PathEnd) {
63   assert(PathBegin != PathEnd && "Base path should not be empty!");
64 
65   CharUnits Offset =
66       computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
67   if (Offset.isZero())
68     return nullptr;
69 
70   llvm::Type *PtrDiffTy =
71   Types.ConvertType(getContext().getPointerDiffType());
72 
73   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
74 }
75 
76 /// Gets the address of a direct base class within a complete object.
77 /// This should only be used for (1) non-virtual bases or (2) virtual bases
78 /// when the type is known to be complete (e.g. in complete destructors).
79 ///
80 /// The object pointed to by 'This' is assumed to be non-null.
81 llvm::Value *
82 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
83                                                    const CXXRecordDecl *Derived,
84                                                    const CXXRecordDecl *Base,
85                                                    bool BaseIsVirtual) {
86   // 'this' must be a pointer (in some address space) to Derived.
87   assert(This->getType()->isPointerTy() &&
88          cast<llvm::PointerType>(This->getType())->getElementType()
89            == ConvertType(Derived));
90 
91   // Compute the offset of the virtual base.
92   CharUnits Offset;
93   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
94   if (BaseIsVirtual)
95     Offset = Layout.getVBaseClassOffset(Base);
96   else
97     Offset = Layout.getBaseClassOffset(Base);
98 
99   // Shift and cast down to the base type.
100   // TODO: for complete types, this should be possible with a GEP.
101   llvm::Value *V = This;
102   if (Offset.isPositive()) {
103     V = Builder.CreateBitCast(V, Int8PtrTy);
104     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
105   }
106   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
107 
108   return V;
109 }
110 
111 static llvm::Value *
112 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
113                                 CharUnits nonVirtualOffset,
114                                 llvm::Value *virtualOffset) {
115   // Assert that we have something to do.
116   assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
117 
118   // Compute the offset from the static and dynamic components.
119   llvm::Value *baseOffset;
120   if (!nonVirtualOffset.isZero()) {
121     baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
122                                         nonVirtualOffset.getQuantity());
123     if (virtualOffset) {
124       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
125     }
126   } else {
127     baseOffset = virtualOffset;
128   }
129 
130   // Apply the base offset.
131   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
132   ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
133   return ptr;
134 }
135 
136 llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
137     llvm::Value *Value, const CXXRecordDecl *Derived,
138     CastExpr::path_const_iterator PathBegin,
139     CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
140     SourceLocation Loc) {
141   assert(PathBegin != PathEnd && "Base path should not be empty!");
142 
143   CastExpr::path_const_iterator Start = PathBegin;
144   const CXXRecordDecl *VBase = nullptr;
145 
146   // Sema has done some convenient canonicalization here: if the
147   // access path involved any virtual steps, the conversion path will
148   // *start* with a step down to the correct virtual base subobject,
149   // and hence will not require any further steps.
150   if ((*Start)->isVirtual()) {
151     VBase =
152       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
153     ++Start;
154   }
155 
156   // Compute the static offset of the ultimate destination within its
157   // allocating subobject (the virtual base, if there is one, or else
158   // the "complete" object that we see).
159   CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
160       VBase ? VBase : Derived, Start, PathEnd);
161 
162   // If there's a virtual step, we can sometimes "devirtualize" it.
163   // For now, that's limited to when the derived type is final.
164   // TODO: "devirtualize" this for accesses to known-complete objects.
165   if (VBase && Derived->hasAttr<FinalAttr>()) {
166     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
167     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
168     NonVirtualOffset += vBaseOffset;
169     VBase = nullptr; // we no longer have a virtual step
170   }
171 
172   // Get the base pointer type.
173   llvm::Type *BasePtrTy =
174     ConvertType((PathEnd[-1])->getType())->getPointerTo();
175 
176   QualType DerivedTy = getContext().getRecordType(Derived);
177   CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
178 
179   // If the static offset is zero and we don't have a virtual step,
180   // just do a bitcast; null checks are unnecessary.
181   if (NonVirtualOffset.isZero() && !VBase) {
182     if (sanitizePerformTypeCheck()) {
183       EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
184                     !NullCheckValue);
185     }
186     return Builder.CreateBitCast(Value, BasePtrTy);
187   }
188 
189   llvm::BasicBlock *origBB = nullptr;
190   llvm::BasicBlock *endBB = nullptr;
191 
192   // Skip over the offset (and the vtable load) if we're supposed to
193   // null-check the pointer.
194   if (NullCheckValue) {
195     origBB = Builder.GetInsertBlock();
196     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
197     endBB = createBasicBlock("cast.end");
198 
199     llvm::Value *isNull = Builder.CreateIsNull(Value);
200     Builder.CreateCondBr(isNull, endBB, notNullBB);
201     EmitBlock(notNullBB);
202   }
203 
204   if (sanitizePerformTypeCheck()) {
205     EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
206                   DerivedTy, DerivedAlign, true);
207   }
208 
209   // Compute the virtual offset.
210   llvm::Value *VirtualOffset = nullptr;
211   if (VBase) {
212     VirtualOffset =
213       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
214   }
215 
216   // Apply both offsets.
217   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
218                                           NonVirtualOffset,
219                                           VirtualOffset);
220 
221   // Cast to the destination type.
222   Value = Builder.CreateBitCast(Value, BasePtrTy);
223 
224   // Build a phi if we needed a null check.
225   if (NullCheckValue) {
226     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
227     Builder.CreateBr(endBB);
228     EmitBlock(endBB);
229 
230     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
231     PHI->addIncoming(Value, notNullBB);
232     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
233     Value = PHI;
234   }
235 
236   return Value;
237 }
238 
239 llvm::Value *
240 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
241                                           const CXXRecordDecl *Derived,
242                                         CastExpr::path_const_iterator PathBegin,
243                                           CastExpr::path_const_iterator PathEnd,
244                                           bool NullCheckValue) {
245   assert(PathBegin != PathEnd && "Base path should not be empty!");
246 
247   QualType DerivedTy =
248     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
249   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
250 
251   llvm::Value *NonVirtualOffset =
252     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
253 
254   if (!NonVirtualOffset) {
255     // No offset, we can just cast back.
256     return Builder.CreateBitCast(Value, DerivedPtrTy);
257   }
258 
259   llvm::BasicBlock *CastNull = nullptr;
260   llvm::BasicBlock *CastNotNull = nullptr;
261   llvm::BasicBlock *CastEnd = nullptr;
262 
263   if (NullCheckValue) {
264     CastNull = createBasicBlock("cast.null");
265     CastNotNull = createBasicBlock("cast.notnull");
266     CastEnd = createBasicBlock("cast.end");
267 
268     llvm::Value *IsNull = Builder.CreateIsNull(Value);
269     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
270     EmitBlock(CastNotNull);
271   }
272 
273   // Apply the offset.
274   Value = Builder.CreateBitCast(Value, Int8PtrTy);
275   Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
276                             "sub.ptr");
277 
278   // Just cast.
279   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
280 
281   if (NullCheckValue) {
282     Builder.CreateBr(CastEnd);
283     EmitBlock(CastNull);
284     Builder.CreateBr(CastEnd);
285     EmitBlock(CastEnd);
286 
287     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
288     PHI->addIncoming(Value, CastNotNull);
289     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
290                      CastNull);
291     Value = PHI;
292   }
293 
294   return Value;
295 }
296 
297 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
298                                               bool ForVirtualBase,
299                                               bool Delegating) {
300   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
301     // This constructor/destructor does not need a VTT parameter.
302     return nullptr;
303   }
304 
305   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
306   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
307 
308   llvm::Value *VTT;
309 
310   uint64_t SubVTTIndex;
311 
312   if (Delegating) {
313     // If this is a delegating constructor call, just load the VTT.
314     return LoadCXXVTT();
315   } else if (RD == Base) {
316     // If the record matches the base, this is the complete ctor/dtor
317     // variant calling the base variant in a class with virtual bases.
318     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
319            "doing no-op VTT offset in base dtor/ctor?");
320     assert(!ForVirtualBase && "Can't have same class as virtual base!");
321     SubVTTIndex = 0;
322   } else {
323     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
324     CharUnits BaseOffset = ForVirtualBase ?
325       Layout.getVBaseClassOffset(Base) :
326       Layout.getBaseClassOffset(Base);
327 
328     SubVTTIndex =
329       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
330     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
331   }
332 
333   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
334     // A VTT parameter was passed to the constructor, use it.
335     VTT = LoadCXXVTT();
336     VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
337   } else {
338     // We're the complete constructor, so get the VTT by name.
339     VTT = CGM.getVTables().GetAddrOfVTT(RD);
340     VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
341   }
342 
343   return VTT;
344 }
345 
346 namespace {
347   /// Call the destructor for a direct base class.
348   struct CallBaseDtor : EHScopeStack::Cleanup {
349     const CXXRecordDecl *BaseClass;
350     bool BaseIsVirtual;
351     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
352       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
353 
354     void Emit(CodeGenFunction &CGF, Flags flags) override {
355       const CXXRecordDecl *DerivedClass =
356         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
357 
358       const CXXDestructorDecl *D = BaseClass->getDestructor();
359       llvm::Value *Addr =
360         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
361                                                   DerivedClass, BaseClass,
362                                                   BaseIsVirtual);
363       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
364                                 /*Delegating=*/false, Addr);
365     }
366   };
367 
368   /// A visitor which checks whether an initializer uses 'this' in a
369   /// way which requires the vtable to be properly set.
370   struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
371     typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
372 
373     bool UsesThis;
374 
375     DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
376 
377     // Black-list all explicit and implicit references to 'this'.
378     //
379     // Do we need to worry about external references to 'this' derived
380     // from arbitrary code?  If so, then anything which runs arbitrary
381     // external code might potentially access the vtable.
382     void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
383   };
384 }
385 
386 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
387   DynamicThisUseChecker Checker(C);
388   Checker.Visit(Init);
389   return Checker.UsesThis;
390 }
391 
392 static void EmitBaseInitializer(CodeGenFunction &CGF,
393                                 const CXXRecordDecl *ClassDecl,
394                                 CXXCtorInitializer *BaseInit,
395                                 CXXCtorType CtorType) {
396   assert(BaseInit->isBaseInitializer() &&
397          "Must have base initializer!");
398 
399   llvm::Value *ThisPtr = CGF.LoadCXXThis();
400 
401   const Type *BaseType = BaseInit->getBaseClass();
402   CXXRecordDecl *BaseClassDecl =
403     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
404 
405   bool isBaseVirtual = BaseInit->isBaseVirtual();
406 
407   // The base constructor doesn't construct virtual bases.
408   if (CtorType == Ctor_Base && isBaseVirtual)
409     return;
410 
411   // If the initializer for the base (other than the constructor
412   // itself) accesses 'this' in any way, we need to initialize the
413   // vtables.
414   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
415     CGF.InitializeVTablePointers(ClassDecl);
416 
417   // We can pretend to be a complete class because it only matters for
418   // virtual bases, and we only do virtual bases for complete ctors.
419   llvm::Value *V =
420     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
421                                               BaseClassDecl,
422                                               isBaseVirtual);
423   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
424   AggValueSlot AggSlot =
425     AggValueSlot::forAddr(V, Alignment, Qualifiers(),
426                           AggValueSlot::IsDestructed,
427                           AggValueSlot::DoesNotNeedGCBarriers,
428                           AggValueSlot::IsNotAliased);
429 
430   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
431 
432   if (CGF.CGM.getLangOpts().Exceptions &&
433       !BaseClassDecl->hasTrivialDestructor())
434     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
435                                           isBaseVirtual);
436 }
437 
438 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
439                                      LValue LHS,
440                                      Expr *Init,
441                                      llvm::Value *ArrayIndexVar,
442                                      QualType T,
443                                      ArrayRef<VarDecl *> ArrayIndexes,
444                                      unsigned Index) {
445   if (Index == ArrayIndexes.size()) {
446     LValue LV = LHS;
447 
448     if (ArrayIndexVar) {
449       // If we have an array index variable, load it and use it as an offset.
450       // Then, increment the value.
451       llvm::Value *Dest = LHS.getAddress();
452       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
453       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
454       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
455       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
456       CGF.Builder.CreateStore(Next, ArrayIndexVar);
457 
458       // Update the LValue.
459       LV.setAddress(Dest);
460       CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
461       LV.setAlignment(std::min(Align, LV.getAlignment()));
462     }
463 
464     switch (CGF.getEvaluationKind(T)) {
465     case TEK_Scalar:
466       CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
467       break;
468     case TEK_Complex:
469       CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
470       break;
471     case TEK_Aggregate: {
472       AggValueSlot Slot =
473         AggValueSlot::forLValue(LV,
474                                 AggValueSlot::IsDestructed,
475                                 AggValueSlot::DoesNotNeedGCBarriers,
476                                 AggValueSlot::IsNotAliased);
477 
478       CGF.EmitAggExpr(Init, Slot);
479       break;
480     }
481     }
482 
483     return;
484   }
485 
486   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
487   assert(Array && "Array initialization without the array type?");
488   llvm::Value *IndexVar
489     = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
490   assert(IndexVar && "Array index variable not loaded");
491 
492   // Initialize this index variable to zero.
493   llvm::Value* Zero
494     = llvm::Constant::getNullValue(
495                               CGF.ConvertType(CGF.getContext().getSizeType()));
496   CGF.Builder.CreateStore(Zero, IndexVar);
497 
498   // Start the loop with a block that tests the condition.
499   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
500   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
501 
502   CGF.EmitBlock(CondBlock);
503 
504   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
505   // Generate: if (loop-index < number-of-elements) fall to the loop body,
506   // otherwise, go to the block after the for-loop.
507   uint64_t NumElements = Array->getSize().getZExtValue();
508   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
509   llvm::Value *NumElementsPtr =
510     llvm::ConstantInt::get(Counter->getType(), NumElements);
511   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
512                                                   "isless");
513 
514   // If the condition is true, execute the body.
515   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
516 
517   CGF.EmitBlock(ForBody);
518   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
519 
520   // Inside the loop body recurse to emit the inner loop or, eventually, the
521   // constructor call.
522   EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
523                            Array->getElementType(), ArrayIndexes, Index + 1);
524 
525   CGF.EmitBlock(ContinueBlock);
526 
527   // Emit the increment of the loop counter.
528   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
529   Counter = CGF.Builder.CreateLoad(IndexVar);
530   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
531   CGF.Builder.CreateStore(NextVal, IndexVar);
532 
533   // Finally, branch back up to the condition for the next iteration.
534   CGF.EmitBranch(CondBlock);
535 
536   // Emit the fall-through block.
537   CGF.EmitBlock(AfterFor, true);
538 }
539 
540 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
541   auto *CD = dyn_cast<CXXConstructorDecl>(D);
542   if (!(CD && CD->isCopyOrMoveConstructor()) &&
543       !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
544     return false;
545 
546   // We can emit a memcpy for a trivial copy or move constructor/assignment.
547   if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
548     return true;
549 
550   // We *must* emit a memcpy for a defaulted union copy or move op.
551   if (D->getParent()->isUnion() && D->isDefaulted())
552     return true;
553 
554   return false;
555 }
556 
557 static void EmitMemberInitializer(CodeGenFunction &CGF,
558                                   const CXXRecordDecl *ClassDecl,
559                                   CXXCtorInitializer *MemberInit,
560                                   const CXXConstructorDecl *Constructor,
561                                   FunctionArgList &Args) {
562   ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
563   assert(MemberInit->isAnyMemberInitializer() &&
564          "Must have member initializer!");
565   assert(MemberInit->getInit() && "Must have initializer!");
566 
567   // non-static data member initializers.
568   FieldDecl *Field = MemberInit->getAnyMember();
569   QualType FieldType = Field->getType();
570 
571   llvm::Value *ThisPtr = CGF.LoadCXXThis();
572   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
573   LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
574 
575   if (MemberInit->isIndirectMemberInitializer()) {
576     // If we are initializing an anonymous union field, drill down to
577     // the field.
578     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
579     for (const auto *I : IndirectField->chain())
580       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
581     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
582   } else {
583     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
584   }
585 
586   // Special case: if we are in a copy or move constructor, and we are copying
587   // an array of PODs or classes with trivial copy constructors, ignore the
588   // AST and perform the copy we know is equivalent.
589   // FIXME: This is hacky at best... if we had a bit more explicit information
590   // in the AST, we could generalize it more easily.
591   const ConstantArrayType *Array
592     = CGF.getContext().getAsConstantArrayType(FieldType);
593   if (Array && Constructor->isDefaulted() &&
594       Constructor->isCopyOrMoveConstructor()) {
595     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
596     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
597     if (BaseElementTy.isPODType(CGF.getContext()) ||
598         (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
599       unsigned SrcArgIndex =
600           CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
601       llvm::Value *SrcPtr
602         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
603       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
604       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
605 
606       // Copy the aggregate.
607       CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
608                             LHS.isVolatileQualified());
609       // Ensure that we destroy the objects if an exception is thrown later in
610       // the constructor.
611       QualType::DestructionKind dtorKind = FieldType.isDestructedType();
612       if (CGF.needsEHCleanup(dtorKind))
613         CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
614       return;
615     }
616   }
617 
618   ArrayRef<VarDecl *> ArrayIndexes;
619   if (MemberInit->getNumArrayIndices())
620     ArrayIndexes = MemberInit->getArrayIndexes();
621   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
622 }
623 
624 void CodeGenFunction::EmitInitializerForField(
625     FieldDecl *Field, LValue LHS, Expr *Init,
626     ArrayRef<VarDecl *> ArrayIndexes) {
627   QualType FieldType = Field->getType();
628   switch (getEvaluationKind(FieldType)) {
629   case TEK_Scalar:
630     if (LHS.isSimple()) {
631       EmitExprAsInit(Init, Field, LHS, false);
632     } else {
633       RValue RHS = RValue::get(EmitScalarExpr(Init));
634       EmitStoreThroughLValue(RHS, LHS);
635     }
636     break;
637   case TEK_Complex:
638     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
639     break;
640   case TEK_Aggregate: {
641     llvm::Value *ArrayIndexVar = nullptr;
642     if (ArrayIndexes.size()) {
643       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
644 
645       // The LHS is a pointer to the first object we'll be constructing, as
646       // a flat array.
647       QualType BaseElementTy = getContext().getBaseElementType(FieldType);
648       llvm::Type *BasePtr = ConvertType(BaseElementTy);
649       BasePtr = llvm::PointerType::getUnqual(BasePtr);
650       llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
651                                                        BasePtr);
652       LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
653 
654       // Create an array index that will be used to walk over all of the
655       // objects we're constructing.
656       ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
657       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
658       Builder.CreateStore(Zero, ArrayIndexVar);
659 
660 
661       // Emit the block variables for the array indices, if any.
662       for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
663         EmitAutoVarDecl(*ArrayIndexes[I]);
664     }
665 
666     EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
667                              ArrayIndexes, 0);
668   }
669   }
670 
671   // Ensure that we destroy this object if an exception is thrown
672   // later in the constructor.
673   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
674   if (needsEHCleanup(dtorKind))
675     pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
676 }
677 
678 /// Checks whether the given constructor is a valid subject for the
679 /// complete-to-base constructor delegation optimization, i.e.
680 /// emitting the complete constructor as a simple call to the base
681 /// constructor.
682 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
683 
684   // Currently we disable the optimization for classes with virtual
685   // bases because (1) the addresses of parameter variables need to be
686   // consistent across all initializers but (2) the delegate function
687   // call necessarily creates a second copy of the parameter variable.
688   //
689   // The limiting example (purely theoretical AFAIK):
690   //   struct A { A(int &c) { c++; } };
691   //   struct B : virtual A {
692   //     B(int count) : A(count) { printf("%d\n", count); }
693   //   };
694   // ...although even this example could in principle be emitted as a
695   // delegation since the address of the parameter doesn't escape.
696   if (Ctor->getParent()->getNumVBases()) {
697     // TODO: white-list trivial vbase initializers.  This case wouldn't
698     // be subject to the restrictions below.
699 
700     // TODO: white-list cases where:
701     //  - there are no non-reference parameters to the constructor
702     //  - the initializers don't access any non-reference parameters
703     //  - the initializers don't take the address of non-reference
704     //    parameters
705     //  - etc.
706     // If we ever add any of the above cases, remember that:
707     //  - function-try-blocks will always blacklist this optimization
708     //  - we need to perform the constructor prologue and cleanup in
709     //    EmitConstructorBody.
710 
711     return false;
712   }
713 
714   // We also disable the optimization for variadic functions because
715   // it's impossible to "re-pass" varargs.
716   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
717     return false;
718 
719   // FIXME: Decide if we can do a delegation of a delegating constructor.
720   if (Ctor->isDelegatingConstructor())
721     return false;
722 
723   return true;
724 }
725 
726 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
727 // to poison the extra field paddings inserted under
728 // -fsanitize-address-field-padding=1|2.
729 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
730   ASTContext &Context = getContext();
731   const CXXRecordDecl *ClassDecl =
732       Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
733                : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
734   if (!ClassDecl->mayInsertExtraPadding()) return;
735 
736   struct SizeAndOffset {
737     uint64_t Size;
738     uint64_t Offset;
739   };
740 
741   unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
742   const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
743 
744   // Populate sizes and offsets of fields.
745   SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
746   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
747     SSV[i].Offset =
748         Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
749 
750   size_t NumFields = 0;
751   for (const auto *Field : ClassDecl->fields()) {
752     const FieldDecl *D = Field;
753     std::pair<CharUnits, CharUnits> FieldInfo =
754         Context.getTypeInfoInChars(D->getType());
755     CharUnits FieldSize = FieldInfo.first;
756     assert(NumFields < SSV.size());
757     SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
758     NumFields++;
759   }
760   assert(NumFields == SSV.size());
761   if (SSV.size() <= 1) return;
762 
763   // We will insert calls to __asan_* run-time functions.
764   // LLVM AddressSanitizer pass may decide to inline them later.
765   llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
766   llvm::FunctionType *FTy =
767       llvm::FunctionType::get(CGM.VoidTy, Args, false);
768   llvm::Constant *F = CGM.CreateRuntimeFunction(
769       FTy, Prologue ? "__asan_poison_intra_object_redzone"
770                     : "__asan_unpoison_intra_object_redzone");
771 
772   llvm::Value *ThisPtr = LoadCXXThis();
773   ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
774   uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
775   // For each field check if it has sufficient padding,
776   // if so (un)poison it with a call.
777   for (size_t i = 0; i < SSV.size(); i++) {
778     uint64_t AsanAlignment = 8;
779     uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
780     uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
781     uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
782     if (PoisonSize < AsanAlignment || !SSV[i].Size ||
783         (NextField % AsanAlignment) != 0)
784       continue;
785     Builder.CreateCall(
786         F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
787             Builder.getIntN(PtrSize, PoisonSize)});
788   }
789 }
790 
791 /// EmitConstructorBody - Emits the body of the current constructor.
792 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
793   EmitAsanPrologueOrEpilogue(true);
794   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
795   CXXCtorType CtorType = CurGD.getCtorType();
796 
797   assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
798           CtorType == Ctor_Complete) &&
799          "can only generate complete ctor for this ABI");
800 
801   // Before we go any further, try the complete->base constructor
802   // delegation optimization.
803   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
804       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
805     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
806     return;
807   }
808 
809   const FunctionDecl *Definition = 0;
810   Stmt *Body = Ctor->getBody(Definition);
811   assert(Definition == Ctor && "emitting wrong constructor body");
812 
813   // Enter the function-try-block before the constructor prologue if
814   // applicable.
815   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
816   if (IsTryBody)
817     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
818 
819   incrementProfileCounter(Body);
820 
821   RunCleanupsScope RunCleanups(*this);
822 
823   // TODO: in restricted cases, we can emit the vbase initializers of
824   // a complete ctor and then delegate to the base ctor.
825 
826   // Emit the constructor prologue, i.e. the base and member
827   // initializers.
828   EmitCtorPrologue(Ctor, CtorType, Args);
829 
830   // Emit the body of the statement.
831   if (IsTryBody)
832     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
833   else if (Body)
834     EmitStmt(Body);
835 
836   // Emit any cleanup blocks associated with the member or base
837   // initializers, which includes (along the exceptional path) the
838   // destructors for those members and bases that were fully
839   // constructed.
840   RunCleanups.ForceCleanup();
841 
842   if (IsTryBody)
843     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
844 }
845 
846 namespace {
847   /// RAII object to indicate that codegen is copying the value representation
848   /// instead of the object representation. Useful when copying a struct or
849   /// class which has uninitialized members and we're only performing
850   /// lvalue-to-rvalue conversion on the object but not its members.
851   class CopyingValueRepresentation {
852   public:
853     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
854         : CGF(CGF), OldSanOpts(CGF.SanOpts) {
855       CGF.SanOpts.set(SanitizerKind::Bool, false);
856       CGF.SanOpts.set(SanitizerKind::Enum, false);
857     }
858     ~CopyingValueRepresentation() {
859       CGF.SanOpts = OldSanOpts;
860     }
861   private:
862     CodeGenFunction &CGF;
863     SanitizerSet OldSanOpts;
864   };
865 }
866 
867 namespace {
868   class FieldMemcpyizer {
869   public:
870     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
871                     const VarDecl *SrcRec)
872       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
873         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
874         FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
875         LastFieldOffset(0), LastAddedFieldIndex(0) {}
876 
877     bool isMemcpyableField(FieldDecl *F) const {
878       // Never memcpy fields when we are adding poisoned paddings.
879       if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
880         return false;
881       Qualifiers Qual = F->getType().getQualifiers();
882       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
883         return false;
884       return true;
885     }
886 
887     void addMemcpyableField(FieldDecl *F) {
888       if (!FirstField)
889         addInitialField(F);
890       else
891         addNextField(F);
892     }
893 
894     CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
895       unsigned LastFieldSize =
896         LastField->isBitField() ?
897           LastField->getBitWidthValue(CGF.getContext()) :
898           CGF.getContext().getTypeSize(LastField->getType());
899       uint64_t MemcpySizeBits =
900         LastFieldOffset + LastFieldSize - FirstByteOffset +
901         CGF.getContext().getCharWidth() - 1;
902       CharUnits MemcpySize =
903         CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
904       return MemcpySize;
905     }
906 
907     void emitMemcpy() {
908       // Give the subclass a chance to bail out if it feels the memcpy isn't
909       // worth it (e.g. Hasn't aggregated enough data).
910       if (!FirstField) {
911         return;
912       }
913 
914       CharUnits Alignment;
915 
916       uint64_t FirstByteOffset;
917       if (FirstField->isBitField()) {
918         const CGRecordLayout &RL =
919           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
920         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
921         Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
922         // FirstFieldOffset is not appropriate for bitfields,
923         // it won't tell us what the storage offset should be and thus might not
924         // be properly aligned.
925         //
926         // Instead calculate the storage offset using the offset of the field in
927         // the struct type.
928         const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
929         FirstByteOffset =
930             DL.getStructLayout(RL.getLLVMType())
931                 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
932       } else {
933         Alignment = CGF.getContext().getDeclAlign(FirstField);
934         FirstByteOffset = FirstFieldOffset;
935       }
936 
937       assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
938               Alignment) == 0 && "Bad field alignment.");
939 
940       CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
941       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
942       llvm::Value *ThisPtr = CGF.LoadCXXThis();
943       LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
944       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
945       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
946       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
947       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
948 
949       emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
950                    Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
951                    MemcpySize, Alignment);
952       reset();
953     }
954 
955     void reset() {
956       FirstField = nullptr;
957     }
958 
959   protected:
960     CodeGenFunction &CGF;
961     const CXXRecordDecl *ClassDecl;
962 
963   private:
964 
965     void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
966                       CharUnits Size, CharUnits Alignment) {
967       llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
968       llvm::Type *DBP =
969         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
970       DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
971 
972       llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
973       llvm::Type *SBP =
974         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
975       SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
976 
977       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
978                                Alignment.getQuantity());
979     }
980 
981     void addInitialField(FieldDecl *F) {
982         FirstField = F;
983         LastField = F;
984         FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
985         LastFieldOffset = FirstFieldOffset;
986         LastAddedFieldIndex = F->getFieldIndex();
987         return;
988       }
989 
990     void addNextField(FieldDecl *F) {
991       // For the most part, the following invariant will hold:
992       //   F->getFieldIndex() == LastAddedFieldIndex + 1
993       // The one exception is that Sema won't add a copy-initializer for an
994       // unnamed bitfield, which will show up here as a gap in the sequence.
995       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
996              "Cannot aggregate fields out of order.");
997       LastAddedFieldIndex = F->getFieldIndex();
998 
999       // The 'first' and 'last' fields are chosen by offset, rather than field
1000       // index. This allows the code to support bitfields, as well as regular
1001       // fields.
1002       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1003       if (FOffset < FirstFieldOffset) {
1004         FirstField = F;
1005         FirstFieldOffset = FOffset;
1006       } else if (FOffset > LastFieldOffset) {
1007         LastField = F;
1008         LastFieldOffset = FOffset;
1009       }
1010     }
1011 
1012     const VarDecl *SrcRec;
1013     const ASTRecordLayout &RecLayout;
1014     FieldDecl *FirstField;
1015     FieldDecl *LastField;
1016     uint64_t FirstFieldOffset, LastFieldOffset;
1017     unsigned LastAddedFieldIndex;
1018   };
1019 
1020   class ConstructorMemcpyizer : public FieldMemcpyizer {
1021   private:
1022 
1023     /// Get source argument for copy constructor. Returns null if not a copy
1024     /// constructor.
1025     static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1026                                                const CXXConstructorDecl *CD,
1027                                                FunctionArgList &Args) {
1028       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1029         return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1030       return nullptr;
1031     }
1032 
1033     // Returns true if a CXXCtorInitializer represents a member initialization
1034     // that can be rolled into a memcpy.
1035     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1036       if (!MemcpyableCtor)
1037         return false;
1038       FieldDecl *Field = MemberInit->getMember();
1039       assert(Field && "No field for member init.");
1040       QualType FieldType = Field->getType();
1041       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1042 
1043       // Bail out on non-memcpyable, not-trivially-copyable members.
1044       if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1045           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1046             FieldType->isReferenceType()))
1047         return false;
1048 
1049       // Bail out on volatile fields.
1050       if (!isMemcpyableField(Field))
1051         return false;
1052 
1053       // Otherwise we're good.
1054       return true;
1055     }
1056 
1057   public:
1058     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1059                           FunctionArgList &Args)
1060       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1061         ConstructorDecl(CD),
1062         MemcpyableCtor(CD->isDefaulted() &&
1063                        CD->isCopyOrMoveConstructor() &&
1064                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
1065         Args(Args) { }
1066 
1067     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1068       if (isMemberInitMemcpyable(MemberInit)) {
1069         AggregatedInits.push_back(MemberInit);
1070         addMemcpyableField(MemberInit->getMember());
1071       } else {
1072         emitAggregatedInits();
1073         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1074                               ConstructorDecl, Args);
1075       }
1076     }
1077 
1078     void emitAggregatedInits() {
1079       if (AggregatedInits.size() <= 1) {
1080         // This memcpy is too small to be worthwhile. Fall back on default
1081         // codegen.
1082         if (!AggregatedInits.empty()) {
1083           CopyingValueRepresentation CVR(CGF);
1084           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1085                                 AggregatedInits[0], ConstructorDecl, Args);
1086         }
1087         reset();
1088         return;
1089       }
1090 
1091       pushEHDestructors();
1092       emitMemcpy();
1093       AggregatedInits.clear();
1094     }
1095 
1096     void pushEHDestructors() {
1097       llvm::Value *ThisPtr = CGF.LoadCXXThis();
1098       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1099       LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1100 
1101       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1102         QualType FieldType = AggregatedInits[i]->getMember()->getType();
1103         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1104         if (CGF.needsEHCleanup(dtorKind))
1105           CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1106       }
1107     }
1108 
1109     void finish() {
1110       emitAggregatedInits();
1111     }
1112 
1113   private:
1114     const CXXConstructorDecl *ConstructorDecl;
1115     bool MemcpyableCtor;
1116     FunctionArgList &Args;
1117     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1118   };
1119 
1120   class AssignmentMemcpyizer : public FieldMemcpyizer {
1121   private:
1122 
1123     // Returns the memcpyable field copied by the given statement, if one
1124     // exists. Otherwise returns null.
1125     FieldDecl *getMemcpyableField(Stmt *S) {
1126       if (!AssignmentsMemcpyable)
1127         return nullptr;
1128       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1129         // Recognise trivial assignments.
1130         if (BO->getOpcode() != BO_Assign)
1131           return nullptr;
1132         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1133         if (!ME)
1134           return nullptr;
1135         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1136         if (!Field || !isMemcpyableField(Field))
1137           return nullptr;
1138         Stmt *RHS = BO->getRHS();
1139         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1140           RHS = EC->getSubExpr();
1141         if (!RHS)
1142           return nullptr;
1143         MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1144         if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1145           return nullptr;
1146         return Field;
1147       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1148         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1149         if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1150           return nullptr;
1151         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1152         if (!IOA)
1153           return nullptr;
1154         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1155         if (!Field || !isMemcpyableField(Field))
1156           return nullptr;
1157         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1158         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1159           return nullptr;
1160         return Field;
1161       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1162         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1163         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1164           return nullptr;
1165         Expr *DstPtr = CE->getArg(0);
1166         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1167           DstPtr = DC->getSubExpr();
1168         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1169         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1170           return nullptr;
1171         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1172         if (!ME)
1173           return nullptr;
1174         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1175         if (!Field || !isMemcpyableField(Field))
1176           return nullptr;
1177         Expr *SrcPtr = CE->getArg(1);
1178         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1179           SrcPtr = SC->getSubExpr();
1180         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1181         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1182           return nullptr;
1183         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1184         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1185           return nullptr;
1186         return Field;
1187       }
1188 
1189       return nullptr;
1190     }
1191 
1192     bool AssignmentsMemcpyable;
1193     SmallVector<Stmt*, 16> AggregatedStmts;
1194 
1195   public:
1196 
1197     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1198                          FunctionArgList &Args)
1199       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1200         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1201       assert(Args.size() == 2);
1202     }
1203 
1204     void emitAssignment(Stmt *S) {
1205       FieldDecl *F = getMemcpyableField(S);
1206       if (F) {
1207         addMemcpyableField(F);
1208         AggregatedStmts.push_back(S);
1209       } else {
1210         emitAggregatedStmts();
1211         CGF.EmitStmt(S);
1212       }
1213     }
1214 
1215     void emitAggregatedStmts() {
1216       if (AggregatedStmts.size() <= 1) {
1217         if (!AggregatedStmts.empty()) {
1218           CopyingValueRepresentation CVR(CGF);
1219           CGF.EmitStmt(AggregatedStmts[0]);
1220         }
1221         reset();
1222       }
1223 
1224       emitMemcpy();
1225       AggregatedStmts.clear();
1226     }
1227 
1228     void finish() {
1229       emitAggregatedStmts();
1230     }
1231   };
1232 
1233 }
1234 
1235 /// EmitCtorPrologue - This routine generates necessary code to initialize
1236 /// base classes and non-static data members belonging to this constructor.
1237 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1238                                        CXXCtorType CtorType,
1239                                        FunctionArgList &Args) {
1240   if (CD->isDelegatingConstructor())
1241     return EmitDelegatingCXXConstructorCall(CD, Args);
1242 
1243   const CXXRecordDecl *ClassDecl = CD->getParent();
1244 
1245   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1246                                           E = CD->init_end();
1247 
1248   llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1249   if (ClassDecl->getNumVBases() &&
1250       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1251     // The ABIs that don't have constructor variants need to put a branch
1252     // before the virtual base initialization code.
1253     BaseCtorContinueBB =
1254       CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1255     assert(BaseCtorContinueBB);
1256   }
1257 
1258   // Virtual base initializers first.
1259   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1260     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1261   }
1262 
1263   if (BaseCtorContinueBB) {
1264     // Complete object handler should continue to the remaining initializers.
1265     Builder.CreateBr(BaseCtorContinueBB);
1266     EmitBlock(BaseCtorContinueBB);
1267   }
1268 
1269   // Then, non-virtual base initializers.
1270   for (; B != E && (*B)->isBaseInitializer(); B++) {
1271     assert(!(*B)->isBaseVirtual());
1272     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1273   }
1274 
1275   InitializeVTablePointers(ClassDecl);
1276 
1277   // And finally, initialize class members.
1278   FieldConstructionScope FCS(*this, CXXThisValue);
1279   ConstructorMemcpyizer CM(*this, CD, Args);
1280   for (; B != E; B++) {
1281     CXXCtorInitializer *Member = (*B);
1282     assert(!Member->isBaseInitializer());
1283     assert(Member->isAnyMemberInitializer() &&
1284            "Delegating initializer on non-delegating constructor");
1285     CM.addMemberInitializer(Member);
1286   }
1287   CM.finish();
1288 }
1289 
1290 static bool
1291 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1292 
1293 static bool
1294 HasTrivialDestructorBody(ASTContext &Context,
1295                          const CXXRecordDecl *BaseClassDecl,
1296                          const CXXRecordDecl *MostDerivedClassDecl)
1297 {
1298   // If the destructor is trivial we don't have to check anything else.
1299   if (BaseClassDecl->hasTrivialDestructor())
1300     return true;
1301 
1302   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1303     return false;
1304 
1305   // Check fields.
1306   for (const auto *Field : BaseClassDecl->fields())
1307     if (!FieldHasTrivialDestructorBody(Context, Field))
1308       return false;
1309 
1310   // Check non-virtual bases.
1311   for (const auto &I : BaseClassDecl->bases()) {
1312     if (I.isVirtual())
1313       continue;
1314 
1315     const CXXRecordDecl *NonVirtualBase =
1316       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1317     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1318                                   MostDerivedClassDecl))
1319       return false;
1320   }
1321 
1322   if (BaseClassDecl == MostDerivedClassDecl) {
1323     // Check virtual bases.
1324     for (const auto &I : BaseClassDecl->vbases()) {
1325       const CXXRecordDecl *VirtualBase =
1326         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1327       if (!HasTrivialDestructorBody(Context, VirtualBase,
1328                                     MostDerivedClassDecl))
1329         return false;
1330     }
1331   }
1332 
1333   return true;
1334 }
1335 
1336 static bool
1337 FieldHasTrivialDestructorBody(ASTContext &Context,
1338                               const FieldDecl *Field)
1339 {
1340   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1341 
1342   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1343   if (!RT)
1344     return true;
1345 
1346   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1347 
1348   // The destructor for an implicit anonymous union member is never invoked.
1349   if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1350     return false;
1351 
1352   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1353 }
1354 
1355 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1356 /// any vtable pointers before calling this destructor.
1357 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
1358                                                const CXXDestructorDecl *Dtor) {
1359   if (!Dtor->hasTrivialBody())
1360     return false;
1361 
1362   // Check the fields.
1363   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1364   for (const auto *Field : ClassDecl->fields())
1365     if (!FieldHasTrivialDestructorBody(Context, Field))
1366       return false;
1367 
1368   return true;
1369 }
1370 
1371 /// EmitDestructorBody - Emits the body of the current destructor.
1372 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1373   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1374   CXXDtorType DtorType = CurGD.getDtorType();
1375 
1376   Stmt *Body = Dtor->getBody();
1377   if (Body)
1378     incrementProfileCounter(Body);
1379 
1380   // The call to operator delete in a deleting destructor happens
1381   // outside of the function-try-block, which means it's always
1382   // possible to delegate the destructor body to the complete
1383   // destructor.  Do so.
1384   if (DtorType == Dtor_Deleting) {
1385     EnterDtorCleanups(Dtor, Dtor_Deleting);
1386     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1387                           /*Delegating=*/false, LoadCXXThis());
1388     PopCleanupBlock();
1389     return;
1390   }
1391 
1392   // If the body is a function-try-block, enter the try before
1393   // anything else.
1394   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1395   if (isTryBody)
1396     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1397   EmitAsanPrologueOrEpilogue(false);
1398 
1399   // Enter the epilogue cleanups.
1400   RunCleanupsScope DtorEpilogue(*this);
1401 
1402   // If this is the complete variant, just invoke the base variant;
1403   // the epilogue will destruct the virtual bases.  But we can't do
1404   // this optimization if the body is a function-try-block, because
1405   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1406   // always delegate because we might not have a definition in this TU.
1407   switch (DtorType) {
1408   case Dtor_Comdat:
1409     llvm_unreachable("not expecting a COMDAT");
1410 
1411   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1412 
1413   case Dtor_Complete:
1414     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1415            "can't emit a dtor without a body for non-Microsoft ABIs");
1416 
1417     // Enter the cleanup scopes for virtual bases.
1418     EnterDtorCleanups(Dtor, Dtor_Complete);
1419 
1420     if (!isTryBody) {
1421       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1422                             /*Delegating=*/false, LoadCXXThis());
1423       break;
1424     }
1425     // Fallthrough: act like we're in the base variant.
1426 
1427   case Dtor_Base:
1428     assert(Body);
1429 
1430     // Enter the cleanup scopes for fields and non-virtual bases.
1431     EnterDtorCleanups(Dtor, Dtor_Base);
1432 
1433     // Initialize the vtable pointers before entering the body.
1434     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1435         InitializeVTablePointers(Dtor->getParent());
1436 
1437     if (isTryBody)
1438       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1439     else if (Body)
1440       EmitStmt(Body);
1441     else {
1442       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1443       // nothing to do besides what's in the epilogue
1444     }
1445     // -fapple-kext must inline any call to this dtor into
1446     // the caller's body.
1447     if (getLangOpts().AppleKext)
1448       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1449     break;
1450   }
1451 
1452   // Jump out through the epilogue cleanups.
1453   DtorEpilogue.ForceCleanup();
1454 
1455   // Exit the try if applicable.
1456   if (isTryBody)
1457     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1458 }
1459 
1460 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1461   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1462   const Stmt *RootS = AssignOp->getBody();
1463   assert(isa<CompoundStmt>(RootS) &&
1464          "Body of an implicit assignment operator should be compound stmt.");
1465   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1466 
1467   LexicalScope Scope(*this, RootCS->getSourceRange());
1468 
1469   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1470   for (auto *I : RootCS->body())
1471     AM.emitAssignment(I);
1472   AM.finish();
1473 }
1474 
1475 namespace {
1476   /// Call the operator delete associated with the current destructor.
1477   struct CallDtorDelete : EHScopeStack::Cleanup {
1478     CallDtorDelete() {}
1479 
1480     void Emit(CodeGenFunction &CGF, Flags flags) override {
1481       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1482       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1483       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1484                          CGF.getContext().getTagDeclType(ClassDecl));
1485     }
1486   };
1487 
1488   struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1489     llvm::Value *ShouldDeleteCondition;
1490   public:
1491     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1492       : ShouldDeleteCondition(ShouldDeleteCondition) {
1493       assert(ShouldDeleteCondition != nullptr);
1494     }
1495 
1496     void Emit(CodeGenFunction &CGF, Flags flags) override {
1497       llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1498       llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1499       llvm::Value *ShouldCallDelete
1500         = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1501       CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1502 
1503       CGF.EmitBlock(callDeleteBB);
1504       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1505       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1506       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1507                          CGF.getContext().getTagDeclType(ClassDecl));
1508       CGF.Builder.CreateBr(continueBB);
1509 
1510       CGF.EmitBlock(continueBB);
1511     }
1512   };
1513 
1514   class DestroyField  : public EHScopeStack::Cleanup {
1515     const FieldDecl *field;
1516     CodeGenFunction::Destroyer *destroyer;
1517     bool useEHCleanupForArray;
1518 
1519   public:
1520     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1521                  bool useEHCleanupForArray)
1522       : field(field), destroyer(destroyer),
1523         useEHCleanupForArray(useEHCleanupForArray) {}
1524 
1525     void Emit(CodeGenFunction &CGF, Flags flags) override {
1526       // Find the address of the field.
1527       llvm::Value *thisValue = CGF.LoadCXXThis();
1528       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1529       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1530       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1531       assert(LV.isSimple());
1532 
1533       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1534                       flags.isForNormalCleanup() && useEHCleanupForArray);
1535     }
1536   };
1537 }
1538 
1539 /// \brief Emit all code that comes at the end of class's
1540 /// destructor. This is to call destructors on members and base classes
1541 /// in reverse order of their construction.
1542 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1543                                         CXXDtorType DtorType) {
1544   assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1545          "Should not emit dtor epilogue for non-exported trivial dtor!");
1546 
1547   // The deleting-destructor phase just needs to call the appropriate
1548   // operator delete that Sema picked up.
1549   if (DtorType == Dtor_Deleting) {
1550     assert(DD->getOperatorDelete() &&
1551            "operator delete missing - EnterDtorCleanups");
1552     if (CXXStructorImplicitParamValue) {
1553       // If there is an implicit param to the deleting dtor, it's a boolean
1554       // telling whether we should call delete at the end of the dtor.
1555       EHStack.pushCleanup<CallDtorDeleteConditional>(
1556           NormalAndEHCleanup, CXXStructorImplicitParamValue);
1557     } else {
1558       EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1559     }
1560     return;
1561   }
1562 
1563   const CXXRecordDecl *ClassDecl = DD->getParent();
1564 
1565   // Unions have no bases and do not call field destructors.
1566   if (ClassDecl->isUnion())
1567     return;
1568 
1569   // The complete-destructor phase just destructs all the virtual bases.
1570   if (DtorType == Dtor_Complete) {
1571 
1572     // We push them in the forward order so that they'll be popped in
1573     // the reverse order.
1574     for (const auto &Base : ClassDecl->vbases()) {
1575       CXXRecordDecl *BaseClassDecl
1576         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1577 
1578       // Ignore trivial destructors.
1579       if (BaseClassDecl->hasTrivialDestructor())
1580         continue;
1581 
1582       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1583                                         BaseClassDecl,
1584                                         /*BaseIsVirtual*/ true);
1585     }
1586 
1587     return;
1588   }
1589 
1590   assert(DtorType == Dtor_Base);
1591 
1592   // Destroy non-virtual bases.
1593   for (const auto &Base : ClassDecl->bases()) {
1594     // Ignore virtual bases.
1595     if (Base.isVirtual())
1596       continue;
1597 
1598     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1599 
1600     // Ignore trivial destructors.
1601     if (BaseClassDecl->hasTrivialDestructor())
1602       continue;
1603 
1604     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1605                                       BaseClassDecl,
1606                                       /*BaseIsVirtual*/ false);
1607   }
1608 
1609   // Destroy direct fields.
1610   for (const auto *Field : ClassDecl->fields()) {
1611     QualType type = Field->getType();
1612     QualType::DestructionKind dtorKind = type.isDestructedType();
1613     if (!dtorKind) continue;
1614 
1615     // Anonymous union members do not have their destructors called.
1616     const RecordType *RT = type->getAsUnionType();
1617     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1618 
1619     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1620     EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1621                                       getDestroyer(dtorKind),
1622                                       cleanupKind & EHCleanup);
1623   }
1624 }
1625 
1626 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1627 /// constructor for each of several members of an array.
1628 ///
1629 /// \param ctor the constructor to call for each element
1630 /// \param arrayType the type of the array to initialize
1631 /// \param arrayBegin an arrayType*
1632 /// \param zeroInitialize true if each element should be
1633 ///   zero-initialized before it is constructed
1634 void CodeGenFunction::EmitCXXAggrConstructorCall(
1635     const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1636     llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1637   QualType elementType;
1638   llvm::Value *numElements =
1639     emitArrayLength(arrayType, elementType, arrayBegin);
1640 
1641   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1642 }
1643 
1644 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1645 /// constructor for each of several members of an array.
1646 ///
1647 /// \param ctor the constructor to call for each element
1648 /// \param numElements the number of elements in the array;
1649 ///   may be zero
1650 /// \param arrayBegin a T*, where T is the type constructed by ctor
1651 /// \param zeroInitialize true if each element should be
1652 ///   zero-initialized before it is constructed
1653 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1654                                                  llvm::Value *numElements,
1655                                                  llvm::Value *arrayBegin,
1656                                                  const CXXConstructExpr *E,
1657                                                  bool zeroInitialize) {
1658 
1659   // It's legal for numElements to be zero.  This can happen both
1660   // dynamically, because x can be zero in 'new A[x]', and statically,
1661   // because of GCC extensions that permit zero-length arrays.  There
1662   // are probably legitimate places where we could assume that this
1663   // doesn't happen, but it's not clear that it's worth it.
1664   llvm::BranchInst *zeroCheckBranch = nullptr;
1665 
1666   // Optimize for a constant count.
1667   llvm::ConstantInt *constantCount
1668     = dyn_cast<llvm::ConstantInt>(numElements);
1669   if (constantCount) {
1670     // Just skip out if the constant count is zero.
1671     if (constantCount->isZero()) return;
1672 
1673   // Otherwise, emit the check.
1674   } else {
1675     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1676     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1677     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1678     EmitBlock(loopBB);
1679   }
1680 
1681   // Find the end of the array.
1682   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1683                                                     "arrayctor.end");
1684 
1685   // Enter the loop, setting up a phi for the current location to initialize.
1686   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1687   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1688   EmitBlock(loopBB);
1689   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1690                                          "arrayctor.cur");
1691   cur->addIncoming(arrayBegin, entryBB);
1692 
1693   // Inside the loop body, emit the constructor call on the array element.
1694 
1695   QualType type = getContext().getTypeDeclType(ctor->getParent());
1696 
1697   // Zero initialize the storage, if requested.
1698   if (zeroInitialize)
1699     EmitNullInitialization(cur, type);
1700 
1701   // C++ [class.temporary]p4:
1702   // There are two contexts in which temporaries are destroyed at a different
1703   // point than the end of the full-expression. The first context is when a
1704   // default constructor is called to initialize an element of an array.
1705   // If the constructor has one or more default arguments, the destruction of
1706   // every temporary created in a default argument expression is sequenced
1707   // before the construction of the next array element, if any.
1708 
1709   {
1710     RunCleanupsScope Scope(*this);
1711 
1712     // Evaluate the constructor and its arguments in a regular
1713     // partial-destroy cleanup.
1714     if (getLangOpts().Exceptions &&
1715         !ctor->getParent()->hasTrivialDestructor()) {
1716       Destroyer *destroyer = destroyCXXObject;
1717       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1718     }
1719 
1720     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1721                            /*Delegating=*/false, cur, E);
1722   }
1723 
1724   // Go to the next element.
1725   llvm::Value *next =
1726     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1727                               "arrayctor.next");
1728   cur->addIncoming(next, Builder.GetInsertBlock());
1729 
1730   // Check whether that's the end of the loop.
1731   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1732   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1733   Builder.CreateCondBr(done, contBB, loopBB);
1734 
1735   // Patch the earlier check to skip over the loop.
1736   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1737 
1738   EmitBlock(contBB);
1739 }
1740 
1741 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1742                                        llvm::Value *addr,
1743                                        QualType type) {
1744   const RecordType *rtype = type->castAs<RecordType>();
1745   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1746   const CXXDestructorDecl *dtor = record->getDestructor();
1747   assert(!dtor->isTrivial());
1748   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1749                             /*Delegating=*/false, addr);
1750 }
1751 
1752 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1753                                              CXXCtorType Type,
1754                                              bool ForVirtualBase,
1755                                              bool Delegating, llvm::Value *This,
1756                                              const CXXConstructExpr *E) {
1757   // C++11 [class.mfct.non-static]p2:
1758   //   If a non-static member function of a class X is called for an object that
1759   //   is not of type X, or of a type derived from X, the behavior is undefined.
1760   // FIXME: Provide a source location here.
1761   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1762                 getContext().getRecordType(D->getParent()));
1763 
1764   if (D->isTrivial() && D->isDefaultConstructor()) {
1765     assert(E->getNumArgs() == 0 && "trivial default ctor with args");
1766     return;
1767   }
1768 
1769   // If this is a trivial constructor, just emit what's needed. If this is a
1770   // union copy constructor, we must emit a memcpy, because the AST does not
1771   // model that copy.
1772   if (isMemcpyEquivalentSpecialMember(D)) {
1773     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1774 
1775     const Expr *Arg = E->getArg(0);
1776     QualType SrcTy = Arg->getType();
1777     llvm::Value *Src = EmitLValue(Arg).getAddress();
1778     QualType DestTy = getContext().getTypeDeclType(D->getParent());
1779     EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
1780     return;
1781   }
1782 
1783   CallArgList Args;
1784 
1785   // Push the this ptr.
1786   Args.add(RValue::get(This), D->getThisType(getContext()));
1787 
1788   // Add the rest of the user-supplied arguments.
1789   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1790   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
1791 
1792   // Insert any ABI-specific implicit constructor arguments.
1793   unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1794       *this, D, Type, ForVirtualBase, Delegating, Args);
1795 
1796   // Emit the call.
1797   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
1798   const CGFunctionInfo &Info =
1799       CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
1800   EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
1801 }
1802 
1803 void
1804 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1805                                         llvm::Value *This, llvm::Value *Src,
1806                                         const CXXConstructExpr *E) {
1807   if (isMemcpyEquivalentSpecialMember(D)) {
1808     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1809     assert(D->isCopyOrMoveConstructor() &&
1810            "trivial 1-arg ctor not a copy/move ctor");
1811     EmitAggregateCopyCtor(This, Src,
1812                           getContext().getTypeDeclType(D->getParent()),
1813                           E->arg_begin()->getType());
1814     return;
1815   }
1816   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
1817   assert(D->isInstance() &&
1818          "Trying to emit a member call expr on a static method!");
1819 
1820   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1821 
1822   CallArgList Args;
1823 
1824   // Push the this ptr.
1825   Args.add(RValue::get(This), D->getThisType(getContext()));
1826 
1827   // Push the src ptr.
1828   QualType QT = *(FPT->param_type_begin());
1829   llvm::Type *t = CGM.getTypes().ConvertType(QT);
1830   Src = Builder.CreateBitCast(Src, t);
1831   Args.add(RValue::get(Src), QT);
1832 
1833   // Skip over first argument (Src).
1834   EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1835                /*ParamsToSkip*/ 1);
1836 
1837   EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1838            Callee, ReturnValueSlot(), Args, D);
1839 }
1840 
1841 void
1842 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1843                                                 CXXCtorType CtorType,
1844                                                 const FunctionArgList &Args,
1845                                                 SourceLocation Loc) {
1846   CallArgList DelegateArgs;
1847 
1848   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1849   assert(I != E && "no parameters to constructor");
1850 
1851   // this
1852   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1853   ++I;
1854 
1855   // vtt
1856   if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
1857                                          /*ForVirtualBase=*/false,
1858                                          /*Delegating=*/true)) {
1859     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1860     DelegateArgs.add(RValue::get(VTT), VoidPP);
1861 
1862     if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
1863       assert(I != E && "cannot skip vtt parameter, already done with args");
1864       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1865       ++I;
1866     }
1867   }
1868 
1869   // Explicit arguments.
1870   for (; I != E; ++I) {
1871     const VarDecl *param = *I;
1872     // FIXME: per-argument source location
1873     EmitDelegateCallArg(DelegateArgs, param, Loc);
1874   }
1875 
1876   llvm::Value *Callee =
1877       CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
1878   EmitCall(CGM.getTypes()
1879                .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
1880            Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1881 }
1882 
1883 namespace {
1884   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1885     const CXXDestructorDecl *Dtor;
1886     llvm::Value *Addr;
1887     CXXDtorType Type;
1888 
1889     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1890                            CXXDtorType Type)
1891       : Dtor(D), Addr(Addr), Type(Type) {}
1892 
1893     void Emit(CodeGenFunction &CGF, Flags flags) override {
1894       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1895                                 /*Delegating=*/true, Addr);
1896     }
1897   };
1898 }
1899 
1900 void
1901 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1902                                                   const FunctionArgList &Args) {
1903   assert(Ctor->isDelegatingConstructor());
1904 
1905   llvm::Value *ThisPtr = LoadCXXThis();
1906 
1907   QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1908   CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1909   AggValueSlot AggSlot =
1910     AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1911                           AggValueSlot::IsDestructed,
1912                           AggValueSlot::DoesNotNeedGCBarriers,
1913                           AggValueSlot::IsNotAliased);
1914 
1915   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1916 
1917   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1918   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1919     CXXDtorType Type =
1920       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1921 
1922     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1923                                                 ClassDecl->getDestructor(),
1924                                                 ThisPtr, Type);
1925   }
1926 }
1927 
1928 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1929                                             CXXDtorType Type,
1930                                             bool ForVirtualBase,
1931                                             bool Delegating,
1932                                             llvm::Value *This) {
1933   CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1934                                      Delegating, This);
1935 }
1936 
1937 namespace {
1938   struct CallLocalDtor : EHScopeStack::Cleanup {
1939     const CXXDestructorDecl *Dtor;
1940     llvm::Value *Addr;
1941 
1942     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1943       : Dtor(D), Addr(Addr) {}
1944 
1945     void Emit(CodeGenFunction &CGF, Flags flags) override {
1946       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1947                                 /*ForVirtualBase=*/false,
1948                                 /*Delegating=*/false, Addr);
1949     }
1950   };
1951 }
1952 
1953 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1954                                             llvm::Value *Addr) {
1955   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1956 }
1957 
1958 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1959   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1960   if (!ClassDecl) return;
1961   if (ClassDecl->hasTrivialDestructor()) return;
1962 
1963   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1964   assert(D && D->isUsed() && "destructor not marked as used!");
1965   PushDestructorCleanup(D, Addr);
1966 }
1967 
1968 void
1969 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1970                                          const CXXRecordDecl *NearestVBase,
1971                                          CharUnits OffsetFromNearestVBase,
1972                                          const CXXRecordDecl *VTableClass) {
1973   const CXXRecordDecl *RD = Base.getBase();
1974 
1975   // Don't initialize the vtable pointer if the class is marked with the
1976   // 'novtable' attribute.
1977   if ((RD == VTableClass || RD == NearestVBase) &&
1978       VTableClass->hasAttr<MSNoVTableAttr>())
1979     return;
1980 
1981   // Compute the address point.
1982   bool NeedsVirtualOffset;
1983   llvm::Value *VTableAddressPoint =
1984       CGM.getCXXABI().getVTableAddressPointInStructor(
1985           *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1986   if (!VTableAddressPoint)
1987     return;
1988 
1989   // Compute where to store the address point.
1990   llvm::Value *VirtualOffset = nullptr;
1991   CharUnits NonVirtualOffset = CharUnits::Zero();
1992 
1993   if (NeedsVirtualOffset) {
1994     // We need to use the virtual base offset offset because the virtual base
1995     // might have a different offset in the most derived class.
1996     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1997                                                               LoadCXXThis(),
1998                                                               VTableClass,
1999                                                               NearestVBase);
2000     NonVirtualOffset = OffsetFromNearestVBase;
2001   } else {
2002     // We can just use the base offset in the complete class.
2003     NonVirtualOffset = Base.getBaseOffset();
2004   }
2005 
2006   // Apply the offsets.
2007   llvm::Value *VTableField = LoadCXXThis();
2008 
2009   if (!NonVirtualOffset.isZero() || VirtualOffset)
2010     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
2011                                                   NonVirtualOffset,
2012                                                   VirtualOffset);
2013 
2014   // Finally, store the address point. Use the same LLVM types as the field to
2015   // support optimization.
2016   llvm::Type *VTablePtrTy =
2017       llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2018           ->getPointerTo()
2019           ->getPointerTo();
2020   VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2021   VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2022   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2023   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
2024 }
2025 
2026 void
2027 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
2028                                           const CXXRecordDecl *NearestVBase,
2029                                           CharUnits OffsetFromNearestVBase,
2030                                           bool BaseIsNonVirtualPrimaryBase,
2031                                           const CXXRecordDecl *VTableClass,
2032                                           VisitedVirtualBasesSetTy& VBases) {
2033   // If this base is a non-virtual primary base the address point has already
2034   // been set.
2035   if (!BaseIsNonVirtualPrimaryBase) {
2036     // Initialize the vtable pointer for this base.
2037     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
2038                             VTableClass);
2039   }
2040 
2041   const CXXRecordDecl *RD = Base.getBase();
2042 
2043   // Traverse bases.
2044   for (const auto &I : RD->bases()) {
2045     CXXRecordDecl *BaseDecl
2046       = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2047 
2048     // Ignore classes without a vtable.
2049     if (!BaseDecl->isDynamicClass())
2050       continue;
2051 
2052     CharUnits BaseOffset;
2053     CharUnits BaseOffsetFromNearestVBase;
2054     bool BaseDeclIsNonVirtualPrimaryBase;
2055 
2056     if (I.isVirtual()) {
2057       // Check if we've visited this virtual base before.
2058       if (!VBases.insert(BaseDecl).second)
2059         continue;
2060 
2061       const ASTRecordLayout &Layout =
2062         getContext().getASTRecordLayout(VTableClass);
2063 
2064       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2065       BaseOffsetFromNearestVBase = CharUnits::Zero();
2066       BaseDeclIsNonVirtualPrimaryBase = false;
2067     } else {
2068       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2069 
2070       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2071       BaseOffsetFromNearestVBase =
2072         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2073       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2074     }
2075 
2076     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
2077                              I.isVirtual() ? BaseDecl : NearestVBase,
2078                              BaseOffsetFromNearestVBase,
2079                              BaseDeclIsNonVirtualPrimaryBase,
2080                              VTableClass, VBases);
2081   }
2082 }
2083 
2084 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2085   // Ignore classes without a vtable.
2086   if (!RD->isDynamicClass())
2087     return;
2088 
2089   // Initialize the vtable pointers for this class and all of its bases.
2090   VisitedVirtualBasesSetTy VBases;
2091   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2092                            /*NearestVBase=*/nullptr,
2093                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2094                            /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
2095 
2096   if (RD->getNumVBases())
2097     CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2098 }
2099 
2100 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
2101                                            llvm::Type *Ty) {
2102   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
2103   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2104   CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2105   return VTable;
2106 }
2107 
2108 // If a class has a single non-virtual base and does not introduce or override
2109 // virtual member functions or fields, it will have the same layout as its base.
2110 // This function returns the least derived such class.
2111 //
2112 // Casting an instance of a base class to such a derived class is technically
2113 // undefined behavior, but it is a relatively common hack for introducing member
2114 // functions on class instances with specific properties (e.g. llvm::Operator)
2115 // that works under most compilers and should not have security implications, so
2116 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2117 static const CXXRecordDecl *
2118 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2119   if (!RD->field_empty())
2120     return RD;
2121 
2122   if (RD->getNumVBases() != 0)
2123     return RD;
2124 
2125   if (RD->getNumBases() != 1)
2126     return RD;
2127 
2128   for (const CXXMethodDecl *MD : RD->methods()) {
2129     if (MD->isVirtual()) {
2130       // Virtual member functions are only ok if they are implicit destructors
2131       // because the implicit destructor will have the same semantics as the
2132       // base class's destructor if no fields are added.
2133       if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2134         continue;
2135       return RD;
2136     }
2137   }
2138 
2139   return LeastDerivedClassWithSameLayout(
2140       RD->bases_begin()->getType()->getAsCXXRecordDecl());
2141 }
2142 
2143 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
2144                                                 llvm::Value *VTable,
2145                                                 CFITypeCheckKind TCK,
2146                                                 SourceLocation Loc) {
2147   const CXXRecordDecl *ClassDecl = MD->getParent();
2148   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2149     ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2150 
2151   EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2152 }
2153 
2154 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2155                                                 llvm::Value *Derived,
2156                                                 bool MayBeNull,
2157                                                 CFITypeCheckKind TCK,
2158                                                 SourceLocation Loc) {
2159   if (!getLangOpts().CPlusPlus)
2160     return;
2161 
2162   auto *ClassTy = T->getAs<RecordType>();
2163   if (!ClassTy)
2164     return;
2165 
2166   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2167 
2168   if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2169     return;
2170 
2171   SmallString<64> MangledName;
2172   llvm::raw_svector_ostream Out(MangledName);
2173   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(T.getUnqualifiedType(),
2174                                                    Out);
2175 
2176   // Blacklist based on the mangled type.
2177   if (CGM.getContext().getSanitizerBlacklist().isBlacklistedType(Out.str()))
2178     return;
2179 
2180   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2181     ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2182 
2183   llvm::BasicBlock *ContBlock = 0;
2184 
2185   if (MayBeNull) {
2186     llvm::Value *DerivedNotNull =
2187         Builder.CreateIsNotNull(Derived, "cast.nonnull");
2188 
2189     llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2190     ContBlock = createBasicBlock("cast.cont");
2191 
2192     Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2193 
2194     EmitBlock(CheckBlock);
2195   }
2196 
2197   llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
2198   EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2199 
2200   if (MayBeNull) {
2201     Builder.CreateBr(ContBlock);
2202     EmitBlock(ContBlock);
2203   }
2204 }
2205 
2206 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2207                                          llvm::Value *VTable,
2208                                          CFITypeCheckKind TCK,
2209                                          SourceLocation Loc) {
2210   if (CGM.IsCFIBlacklistedRecord(RD))
2211     return;
2212 
2213   SanitizerScope SanScope(this);
2214 
2215   std::string OutName;
2216   llvm::raw_string_ostream Out(OutName);
2217   CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
2218 
2219   llvm::Value *BitSetName = llvm::MetadataAsValue::get(
2220       getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
2221 
2222   llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2223   llvm::Value *BitSetTest =
2224       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2225                          {CastedVTable, BitSetName});
2226 
2227   SanitizerMask M;
2228   switch (TCK) {
2229   case CFITCK_VCall:
2230     M = SanitizerKind::CFIVCall;
2231     break;
2232   case CFITCK_NVCall:
2233     M = SanitizerKind::CFINVCall;
2234     break;
2235   case CFITCK_DerivedCast:
2236     M = SanitizerKind::CFIDerivedCast;
2237     break;
2238   case CFITCK_UnrelatedCast:
2239     M = SanitizerKind::CFIUnrelatedCast;
2240     break;
2241   }
2242 
2243   llvm::Constant *StaticData[] = {
2244     EmitCheckSourceLocation(Loc),
2245     EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2246     llvm::ConstantInt::get(Int8Ty, TCK),
2247   };
2248   EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
2249             CastedVTable);
2250 }
2251 
2252 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2253 // quite what we want.
2254 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2255   while (true) {
2256     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2257       E = PE->getSubExpr();
2258       continue;
2259     }
2260 
2261     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2262       if (CE->getCastKind() == CK_NoOp) {
2263         E = CE->getSubExpr();
2264         continue;
2265       }
2266     }
2267     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2268       if (UO->getOpcode() == UO_Extension) {
2269         E = UO->getSubExpr();
2270         continue;
2271       }
2272     }
2273     return E;
2274   }
2275 }
2276 
2277 bool
2278 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2279                                                    const CXXMethodDecl *MD) {
2280   // When building with -fapple-kext, all calls must go through the vtable since
2281   // the kernel linker can do runtime patching of vtables.
2282   if (getLangOpts().AppleKext)
2283     return false;
2284 
2285   // If the most derived class is marked final, we know that no subclass can
2286   // override this member function and so we can devirtualize it. For example:
2287   //
2288   // struct A { virtual void f(); }
2289   // struct B final : A { };
2290   //
2291   // void f(B *b) {
2292   //   b->f();
2293   // }
2294   //
2295   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
2296   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2297     return true;
2298 
2299   // If the member function is marked 'final', we know that it can't be
2300   // overridden and can therefore devirtualize it.
2301   if (MD->hasAttr<FinalAttr>())
2302     return true;
2303 
2304   // Similarly, if the class itself is marked 'final' it can't be overridden
2305   // and we can therefore devirtualize the member function call.
2306   if (MD->getParent()->hasAttr<FinalAttr>())
2307     return true;
2308 
2309   Base = skipNoOpCastsAndParens(Base);
2310   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2311     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2312       // This is a record decl. We know the type and can devirtualize it.
2313       return VD->getType()->isRecordType();
2314     }
2315 
2316     return false;
2317   }
2318 
2319   // We can devirtualize calls on an object accessed by a class member access
2320   // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2321   // a derived class object constructed in the same location.
2322   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2323     if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2324       return VD->getType()->isRecordType();
2325 
2326   // We can always devirtualize calls on temporary object expressions.
2327   if (isa<CXXConstructExpr>(Base))
2328     return true;
2329 
2330   // And calls on bound temporaries.
2331   if (isa<CXXBindTemporaryExpr>(Base))
2332     return true;
2333 
2334   // Check if this is a call expr that returns a record type.
2335   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2336     return CE->getCallReturnType(getContext())->isRecordType();
2337 
2338   // We can't devirtualize the call.
2339   return false;
2340 }
2341 
2342 void CodeGenFunction::EmitForwardingCallToLambda(
2343                                       const CXXMethodDecl *callOperator,
2344                                       CallArgList &callArgs) {
2345   // Get the address of the call operator.
2346   const CGFunctionInfo &calleeFnInfo =
2347     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2348   llvm::Value *callee =
2349     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2350                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2351 
2352   // Prepare the return slot.
2353   const FunctionProtoType *FPT =
2354     callOperator->getType()->castAs<FunctionProtoType>();
2355   QualType resultType = FPT->getReturnType();
2356   ReturnValueSlot returnSlot;
2357   if (!resultType->isVoidType() &&
2358       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2359       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2360     returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2361 
2362   // We don't need to separately arrange the call arguments because
2363   // the call can't be variadic anyway --- it's impossible to forward
2364   // variadic arguments.
2365 
2366   // Now emit our call.
2367   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2368                        callArgs, callOperator);
2369 
2370   // If necessary, copy the returned value into the slot.
2371   if (!resultType->isVoidType() && returnSlot.isNull())
2372     EmitReturnOfRValue(RV, resultType);
2373   else
2374     EmitBranchThroughCleanup(ReturnBlock);
2375 }
2376 
2377 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2378   const BlockDecl *BD = BlockInfo->getBlockDecl();
2379   const VarDecl *variable = BD->capture_begin()->getVariable();
2380   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2381 
2382   // Start building arguments for forwarding call
2383   CallArgList CallArgs;
2384 
2385   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2386   llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2387   CallArgs.add(RValue::get(ThisPtr), ThisType);
2388 
2389   // Add the rest of the parameters.
2390   for (auto param : BD->params())
2391     EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2392 
2393   assert(!Lambda->isGenericLambda() &&
2394             "generic lambda interconversion to block not implemented");
2395   EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
2396 }
2397 
2398 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2399   if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2400     // FIXME: Making this work correctly is nasty because it requires either
2401     // cloning the body of the call operator or making the call operator forward.
2402     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2403     return;
2404   }
2405 
2406   EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2407 }
2408 
2409 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2410   const CXXRecordDecl *Lambda = MD->getParent();
2411 
2412   // Start building arguments for forwarding call
2413   CallArgList CallArgs;
2414 
2415   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2416   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2417   CallArgs.add(RValue::get(ThisPtr), ThisType);
2418 
2419   // Add the rest of the parameters.
2420   for (auto Param : MD->params())
2421     EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2422 
2423   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2424   // For a generic lambda, find the corresponding call operator specialization
2425   // to which the call to the static-invoker shall be forwarded.
2426   if (Lambda->isGenericLambda()) {
2427     assert(MD->isFunctionTemplateSpecialization());
2428     const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2429     FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2430     void *InsertPos = nullptr;
2431     FunctionDecl *CorrespondingCallOpSpecialization =
2432         CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2433     assert(CorrespondingCallOpSpecialization);
2434     CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2435   }
2436   EmitForwardingCallToLambda(CallOp, CallArgs);
2437 }
2438 
2439 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2440   if (MD->isVariadic()) {
2441     // FIXME: Making this work correctly is nasty because it requires either
2442     // cloning the body of the call operator or making the call operator forward.
2443     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2444     return;
2445   }
2446 
2447   EmitLambdaDelegatingInvokeBody(MD);
2448 }
2449