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