xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with code generation of C++ expressions
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCUDARuntime.h"
14 #include "CGCXXABI.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "ConstantEmitter.h"
19 #include "TargetInfo.h"
20 #include "clang/Basic/CodeGenOptions.h"
21 #include "clang/CodeGen/CGFunctionInfo.h"
22 #include "llvm/IR/Intrinsics.h"
23 
24 using namespace clang;
25 using namespace CodeGen;
26 
27 namespace {
28 struct MemberCallInfo {
29   RequiredArgs ReqArgs;
30   // Number of prefix arguments for the call. Ignores the `this` pointer.
31   unsigned PrefixSize;
32 };
33 }
34 
35 static MemberCallInfo
36 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37                                   llvm::Value *This, llvm::Value *ImplicitParam,
38                                   QualType ImplicitParamTy, const CallExpr *CE,
39                                   CallArgList &Args, CallArgList *RtlArgs) {
40   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
41          isa<CXXOperatorCallExpr>(CE));
42   assert(MD->isInstance() &&
43          "Trying to emit a member or operator call expr on a static method!");
44 
45   // Push the this ptr.
46   const CXXRecordDecl *RD =
47       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48   Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
49 
50   // If there is an implicit parameter (e.g. VTT), emit it.
51   if (ImplicitParam) {
52     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
53   }
54 
55   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
57   unsigned PrefixSize = Args.size() - 1;
58 
59   // And the rest of the call args.
60   if (RtlArgs) {
61     // Special case: if the caller emitted the arguments right-to-left already
62     // (prior to emitting the *this argument), we're done. This happens for
63     // assignment operators.
64     Args.addFrom(*RtlArgs);
65   } else if (CE) {
66     // Special case: skip first argument of CXXOperatorCall (it is "this").
67     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
68     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
69                      CE->getDirectCallee());
70   } else {
71     assert(
72         FPT->getNumParams() == 0 &&
73         "No CallExpr specified for function with non-zero number of arguments");
74   }
75   return {required, PrefixSize};
76 }
77 
78 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
79     const CXXMethodDecl *MD, const CGCallee &Callee,
80     ReturnValueSlot ReturnValue,
81     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
82     const CallExpr *CE, CallArgList *RtlArgs) {
83   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
84   CallArgList Args;
85   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
86       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
87   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
88       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
89   return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
90                   CE && CE == MustTailCall,
91                   CE ? CE->getExprLoc() : SourceLocation());
92 }
93 
94 RValue CodeGenFunction::EmitCXXDestructorCall(
95     GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
96     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
97   const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
98 
99   assert(!ThisTy.isNull());
100   assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
101          "Pointer/Object mixup");
102 
103   LangAS SrcAS = ThisTy.getAddressSpace();
104   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
105   if (SrcAS != DstAS) {
106     QualType DstTy = DtorDecl->getThisType();
107     llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
108     This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
109                                                  NewType);
110   }
111 
112   CallArgList Args;
113   commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
114                                     ImplicitParamTy, CE, Args, nullptr);
115   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
116                   ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
117                   CE ? CE->getExprLoc() : SourceLocation{});
118 }
119 
120 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
121                                             const CXXPseudoDestructorExpr *E) {
122   QualType DestroyedType = E->getDestroyedType();
123   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
124     // Automatic Reference Counting:
125     //   If the pseudo-expression names a retainable object with weak or
126     //   strong lifetime, the object shall be released.
127     Expr *BaseExpr = E->getBase();
128     Address BaseValue = Address::invalid();
129     Qualifiers BaseQuals;
130 
131     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
132     if (E->isArrow()) {
133       BaseValue = EmitPointerWithAlignment(BaseExpr);
134       const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
135       BaseQuals = PTy->getPointeeType().getQualifiers();
136     } else {
137       LValue BaseLV = EmitLValue(BaseExpr);
138       BaseValue = BaseLV.getAddress(*this);
139       QualType BaseTy = BaseExpr->getType();
140       BaseQuals = BaseTy.getQualifiers();
141     }
142 
143     switch (DestroyedType.getObjCLifetime()) {
144     case Qualifiers::OCL_None:
145     case Qualifiers::OCL_ExplicitNone:
146     case Qualifiers::OCL_Autoreleasing:
147       break;
148 
149     case Qualifiers::OCL_Strong:
150       EmitARCRelease(Builder.CreateLoad(BaseValue,
151                         DestroyedType.isVolatileQualified()),
152                      ARCPreciseLifetime);
153       break;
154 
155     case Qualifiers::OCL_Weak:
156       EmitARCDestroyWeak(BaseValue);
157       break;
158     }
159   } else {
160     // C++ [expr.pseudo]p1:
161     //   The result shall only be used as the operand for the function call
162     //   operator (), and the result of such a call has type void. The only
163     //   effect is the evaluation of the postfix-expression before the dot or
164     //   arrow.
165     EmitIgnoredExpr(E->getBase());
166   }
167 
168   return RValue::get(nullptr);
169 }
170 
171 static CXXRecordDecl *getCXXRecord(const Expr *E) {
172   QualType T = E->getType();
173   if (const PointerType *PTy = T->getAs<PointerType>())
174     T = PTy->getPointeeType();
175   const RecordType *Ty = T->castAs<RecordType>();
176   return cast<CXXRecordDecl>(Ty->getDecl());
177 }
178 
179 // Note: This function also emit constructor calls to support a MSVC
180 // extensions allowing explicit constructor function call.
181 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
182                                               ReturnValueSlot ReturnValue) {
183   const Expr *callee = CE->getCallee()->IgnoreParens();
184 
185   if (isa<BinaryOperator>(callee))
186     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
187 
188   const MemberExpr *ME = cast<MemberExpr>(callee);
189   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
190 
191   if (MD->isStatic()) {
192     // The method is static, emit it as we would a regular call.
193     CGCallee callee =
194         CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
195     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
196                     ReturnValue);
197   }
198 
199   bool HasQualifier = ME->hasQualifier();
200   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
201   bool IsArrow = ME->isArrow();
202   const Expr *Base = ME->getBase();
203 
204   return EmitCXXMemberOrOperatorMemberCallExpr(
205       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
206 }
207 
208 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
209     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
210     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
211     const Expr *Base) {
212   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
213 
214   // Compute the object pointer.
215   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
216 
217   const CXXMethodDecl *DevirtualizedMethod = nullptr;
218   if (CanUseVirtualCall &&
219       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
220     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
221     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
222     assert(DevirtualizedMethod);
223     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
224     const Expr *Inner = Base->IgnoreParenBaseCasts();
225     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
226         MD->getReturnType().getCanonicalType())
227       // If the return types are not the same, this might be a case where more
228       // code needs to run to compensate for it. For example, the derived
229       // method might return a type that inherits form from the return
230       // type of MD and has a prefix.
231       // For now we just avoid devirtualizing these covariant cases.
232       DevirtualizedMethod = nullptr;
233     else if (getCXXRecord(Inner) == DevirtualizedClass)
234       // If the class of the Inner expression is where the dynamic method
235       // is defined, build the this pointer from it.
236       Base = Inner;
237     else if (getCXXRecord(Base) != DevirtualizedClass) {
238       // If the method is defined in a class that is not the best dynamic
239       // one or the one of the full expression, we would have to build
240       // a derived-to-base cast to compute the correct this pointer, but
241       // we don't have support for that yet, so do a virtual call.
242       DevirtualizedMethod = nullptr;
243     }
244   }
245 
246   bool TrivialForCodegen =
247       MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
248   bool TrivialAssignment =
249       TrivialForCodegen &&
250       (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
251       !MD->getParent()->mayInsertExtraPadding();
252 
253   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
254   // operator before the LHS.
255   CallArgList RtlArgStorage;
256   CallArgList *RtlArgs = nullptr;
257   LValue TrivialAssignmentRHS;
258   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
259     if (OCE->isAssignmentOp()) {
260       if (TrivialAssignment) {
261         TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
262       } else {
263         RtlArgs = &RtlArgStorage;
264         EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
265                      drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
266                      /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
267       }
268     }
269   }
270 
271   LValue This;
272   if (IsArrow) {
273     LValueBaseInfo BaseInfo;
274     TBAAAccessInfo TBAAInfo;
275     Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
276     This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
277   } else {
278     This = EmitLValue(Base);
279   }
280 
281   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
282     // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
283     // constructing a new complete object of type Ctor.
284     assert(!RtlArgs);
285     assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
286     CallArgList Args;
287     commonEmitCXXMemberOrOperatorCall(
288         *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
289         /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
290 
291     EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
292                            /*Delegating=*/false, This.getAddress(*this), Args,
293                            AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
294                            /*NewPointerIsChecked=*/false);
295     return RValue::get(nullptr);
296   }
297 
298   if (TrivialForCodegen) {
299     if (isa<CXXDestructorDecl>(MD))
300       return RValue::get(nullptr);
301 
302     if (TrivialAssignment) {
303       // We don't like to generate the trivial copy/move assignment operator
304       // when it isn't necessary; just produce the proper effect here.
305       // It's important that we use the result of EmitLValue here rather than
306       // emitting call arguments, in order to preserve TBAA information from
307       // the RHS.
308       LValue RHS = isa<CXXOperatorCallExpr>(CE)
309                        ? TrivialAssignmentRHS
310                        : EmitLValue(*CE->arg_begin());
311       EmitAggregateAssign(This, RHS, CE->getType());
312       return RValue::get(This.getPointer(*this));
313     }
314 
315     assert(MD->getParent()->mayInsertExtraPadding() &&
316            "unknown trivial member function");
317   }
318 
319   // Compute the function type we're calling.
320   const CXXMethodDecl *CalleeDecl =
321       DevirtualizedMethod ? DevirtualizedMethod : MD;
322   const CGFunctionInfo *FInfo = nullptr;
323   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
324     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
325         GlobalDecl(Dtor, Dtor_Complete));
326   else
327     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
328 
329   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
330 
331   // C++11 [class.mfct.non-static]p2:
332   //   If a non-static member function of a class X is called for an object that
333   //   is not of type X, or of a type derived from X, the behavior is undefined.
334   SourceLocation CallLoc;
335   ASTContext &C = getContext();
336   if (CE)
337     CallLoc = CE->getExprLoc();
338 
339   SanitizerSet SkippedChecks;
340   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
341     auto *IOA = CMCE->getImplicitObjectArgument();
342     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
343     if (IsImplicitObjectCXXThis)
344       SkippedChecks.set(SanitizerKind::Alignment, true);
345     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
346       SkippedChecks.set(SanitizerKind::Null, true);
347   }
348   EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
349                 This.getPointer(*this),
350                 C.getRecordType(CalleeDecl->getParent()),
351                 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
352 
353   // C++ [class.virtual]p12:
354   //   Explicit qualification with the scope operator (5.1) suppresses the
355   //   virtual call mechanism.
356   //
357   // We also don't emit a virtual call if the base expression has a record type
358   // because then we know what the type is.
359   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
360 
361   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
362     assert(CE->arg_begin() == CE->arg_end() &&
363            "Destructor shouldn't have explicit parameters");
364     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
365     if (UseVirtualCall) {
366       CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
367                                                 This.getAddress(*this),
368                                                 cast<CXXMemberCallExpr>(CE));
369     } else {
370       GlobalDecl GD(Dtor, Dtor_Complete);
371       CGCallee Callee;
372       if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
373         Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
374       else if (!DevirtualizedMethod)
375         Callee =
376             CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
377       else {
378         Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
379       }
380 
381       QualType ThisTy =
382           IsArrow ? Base->getType()->getPointeeType() : Base->getType();
383       EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
384                             /*ImplicitParam=*/nullptr,
385                             /*ImplicitParamTy=*/QualType(), CE);
386     }
387     return RValue::get(nullptr);
388   }
389 
390   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
391   // 'CalleeDecl' instead.
392 
393   CGCallee Callee;
394   if (UseVirtualCall) {
395     Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
396   } else {
397     if (SanOpts.has(SanitizerKind::CFINVCall) &&
398         MD->getParent()->isDynamicClass()) {
399       llvm::Value *VTable;
400       const CXXRecordDecl *RD;
401       std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
402           *this, This.getAddress(*this), CalleeDecl->getParent());
403       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
404     }
405 
406     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
407       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
408     else if (!DevirtualizedMethod)
409       Callee =
410           CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
411     else {
412       Callee =
413           CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
414                               GlobalDecl(DevirtualizedMethod));
415     }
416   }
417 
418   if (MD->isVirtual()) {
419     Address NewThisAddr =
420         CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
421             *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
422     This.setAddress(NewThisAddr);
423   }
424 
425   return EmitCXXMemberOrOperatorCall(
426       CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
427       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
428 }
429 
430 RValue
431 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
432                                               ReturnValueSlot ReturnValue) {
433   const BinaryOperator *BO =
434       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
435   const Expr *BaseExpr = BO->getLHS();
436   const Expr *MemFnExpr = BO->getRHS();
437 
438   const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
439   const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
440   const auto *RD =
441       cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
442 
443   // Emit the 'this' pointer.
444   Address This = Address::invalid();
445   if (BO->getOpcode() == BO_PtrMemI)
446     This = EmitPointerWithAlignment(BaseExpr);
447   else
448     This = EmitLValue(BaseExpr).getAddress(*this);
449 
450   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
451                 QualType(MPT->getClass(), 0));
452 
453   // Get the member function pointer.
454   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
455 
456   // Ask the ABI to load the callee.  Note that This is modified.
457   llvm::Value *ThisPtrForCall = nullptr;
458   CGCallee Callee =
459     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
460                                              ThisPtrForCall, MemFnPtr, MPT);
461 
462   CallArgList Args;
463 
464   QualType ThisType =
465     getContext().getPointerType(getContext().getTagDeclType(RD));
466 
467   // Push the this ptr.
468   Args.add(RValue::get(ThisPtrForCall), ThisType);
469 
470   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
471 
472   // And the rest of the call args
473   EmitCallArgs(Args, FPT, E->arguments());
474   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
475                                                       /*PrefixSize=*/0),
476                   Callee, ReturnValue, Args, nullptr, E == MustTailCall,
477                   E->getExprLoc());
478 }
479 
480 RValue
481 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
482                                                const CXXMethodDecl *MD,
483                                                ReturnValueSlot ReturnValue) {
484   assert(MD->isInstance() &&
485          "Trying to emit a member call expr on a static method!");
486   return EmitCXXMemberOrOperatorMemberCallExpr(
487       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
488       /*IsArrow=*/false, E->getArg(0));
489 }
490 
491 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
492                                                ReturnValueSlot ReturnValue) {
493   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
494 }
495 
496 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
497                                             Address DestPtr,
498                                             const CXXRecordDecl *Base) {
499   if (Base->isEmpty())
500     return;
501 
502   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
503 
504   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
505   CharUnits NVSize = Layout.getNonVirtualSize();
506 
507   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
508   // present, they are initialized by the most derived class before calling the
509   // constructor.
510   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
511   Stores.emplace_back(CharUnits::Zero(), NVSize);
512 
513   // Each store is split by the existence of a vbptr.
514   CharUnits VBPtrWidth = CGF.getPointerSize();
515   std::vector<CharUnits> VBPtrOffsets =
516       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
517   for (CharUnits VBPtrOffset : VBPtrOffsets) {
518     // Stop before we hit any virtual base pointers located in virtual bases.
519     if (VBPtrOffset >= NVSize)
520       break;
521     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
522     CharUnits LastStoreOffset = LastStore.first;
523     CharUnits LastStoreSize = LastStore.second;
524 
525     CharUnits SplitBeforeOffset = LastStoreOffset;
526     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
527     assert(!SplitBeforeSize.isNegative() && "negative store size!");
528     if (!SplitBeforeSize.isZero())
529       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
530 
531     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
532     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
533     assert(!SplitAfterSize.isNegative() && "negative store size!");
534     if (!SplitAfterSize.isZero())
535       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
536   }
537 
538   // If the type contains a pointer to data member we can't memset it to zero.
539   // Instead, create a null constant and copy it to the destination.
540   // TODO: there are other patterns besides zero that we can usefully memset,
541   // like -1, which happens to be the pattern used by member-pointers.
542   // TODO: isZeroInitializable can be over-conservative in the case where a
543   // virtual base contains a member pointer.
544   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
545   if (!NullConstantForBase->isNullValue()) {
546     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
547         CGF.CGM.getModule(), NullConstantForBase->getType(),
548         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
549         NullConstantForBase, Twine());
550 
551     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
552                                DestPtr.getAlignment());
553     NullVariable->setAlignment(Align.getAsAlign());
554 
555     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
556 
557     // Get and call the appropriate llvm.memcpy overload.
558     for (std::pair<CharUnits, CharUnits> Store : Stores) {
559       CharUnits StoreOffset = Store.first;
560       CharUnits StoreSize = Store.second;
561       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
562       CGF.Builder.CreateMemCpy(
563           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
564           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
565           StoreSizeVal);
566     }
567 
568   // Otherwise, just memset the whole thing to zero.  This is legal
569   // because in LLVM, all default initializers (other than the ones we just
570   // handled above) are guaranteed to have a bit pattern of all zeros.
571   } else {
572     for (std::pair<CharUnits, CharUnits> Store : Stores) {
573       CharUnits StoreOffset = Store.first;
574       CharUnits StoreSize = Store.second;
575       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
576       CGF.Builder.CreateMemSet(
577           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
578           CGF.Builder.getInt8(0), StoreSizeVal);
579     }
580   }
581 }
582 
583 void
584 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
585                                       AggValueSlot Dest) {
586   assert(!Dest.isIgnored() && "Must have a destination!");
587   const CXXConstructorDecl *CD = E->getConstructor();
588 
589   // If we require zero initialization before (or instead of) calling the
590   // constructor, as can be the case with a non-user-provided default
591   // constructor, emit the zero initialization now, unless destination is
592   // already zeroed.
593   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
594     switch (E->getConstructionKind()) {
595     case CXXConstructExpr::CK_Delegating:
596     case CXXConstructExpr::CK_Complete:
597       EmitNullInitialization(Dest.getAddress(), E->getType());
598       break;
599     case CXXConstructExpr::CK_VirtualBase:
600     case CXXConstructExpr::CK_NonVirtualBase:
601       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
602                                       CD->getParent());
603       break;
604     }
605   }
606 
607   // If this is a call to a trivial default constructor, do nothing.
608   if (CD->isTrivial() && CD->isDefaultConstructor())
609     return;
610 
611   // Elide the constructor if we're constructing from a temporary.
612   if (getLangOpts().ElideConstructors && E->isElidable()) {
613     // FIXME: This only handles the simplest case, where the source object
614     //        is passed directly as the first argument to the constructor.
615     //        This should also handle stepping though implicit casts and
616     //        conversion sequences which involve two steps, with a
617     //        conversion operator followed by a converting constructor.
618     const Expr *SrcObj = E->getArg(0);
619     assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
620     assert(
621         getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
622     EmitAggExpr(SrcObj, Dest);
623     return;
624   }
625 
626   if (const ArrayType *arrayType
627         = getContext().getAsArrayType(E->getType())) {
628     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
629                                Dest.isSanitizerChecked());
630   } else {
631     CXXCtorType Type = Ctor_Complete;
632     bool ForVirtualBase = false;
633     bool Delegating = false;
634 
635     switch (E->getConstructionKind()) {
636      case CXXConstructExpr::CK_Delegating:
637       // We should be emitting a constructor; GlobalDecl will assert this
638       Type = CurGD.getCtorType();
639       Delegating = true;
640       break;
641 
642      case CXXConstructExpr::CK_Complete:
643       Type = Ctor_Complete;
644       break;
645 
646      case CXXConstructExpr::CK_VirtualBase:
647       ForVirtualBase = true;
648       LLVM_FALLTHROUGH;
649 
650      case CXXConstructExpr::CK_NonVirtualBase:
651       Type = Ctor_Base;
652      }
653 
654      // Call the constructor.
655      EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
656   }
657 }
658 
659 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
660                                                  const Expr *Exp) {
661   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
662     Exp = E->getSubExpr();
663   assert(isa<CXXConstructExpr>(Exp) &&
664          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
665   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
666   const CXXConstructorDecl *CD = E->getConstructor();
667   RunCleanupsScope Scope(*this);
668 
669   // If we require zero initialization before (or instead of) calling the
670   // constructor, as can be the case with a non-user-provided default
671   // constructor, emit the zero initialization now.
672   // FIXME. Do I still need this for a copy ctor synthesis?
673   if (E->requiresZeroInitialization())
674     EmitNullInitialization(Dest, E->getType());
675 
676   assert(!getContext().getAsConstantArrayType(E->getType())
677          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
678   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
679 }
680 
681 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
682                                         const CXXNewExpr *E) {
683   if (!E->isArray())
684     return CharUnits::Zero();
685 
686   // No cookie is required if the operator new[] being used is the
687   // reserved placement operator new[].
688   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
689     return CharUnits::Zero();
690 
691   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
692 }
693 
694 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
695                                         const CXXNewExpr *e,
696                                         unsigned minElements,
697                                         llvm::Value *&numElements,
698                                         llvm::Value *&sizeWithoutCookie) {
699   QualType type = e->getAllocatedType();
700 
701   if (!e->isArray()) {
702     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
703     sizeWithoutCookie
704       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
705     return sizeWithoutCookie;
706   }
707 
708   // The width of size_t.
709   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
710 
711   // Figure out the cookie size.
712   llvm::APInt cookieSize(sizeWidth,
713                          CalculateCookiePadding(CGF, e).getQuantity());
714 
715   // Emit the array size expression.
716   // We multiply the size of all dimensions for NumElements.
717   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
718   numElements =
719     ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
720   if (!numElements)
721     numElements = CGF.EmitScalarExpr(*e->getArraySize());
722   assert(isa<llvm::IntegerType>(numElements->getType()));
723 
724   // The number of elements can be have an arbitrary integer type;
725   // essentially, we need to multiply it by a constant factor, add a
726   // cookie size, and verify that the result is representable as a
727   // size_t.  That's just a gloss, though, and it's wrong in one
728   // important way: if the count is negative, it's an error even if
729   // the cookie size would bring the total size >= 0.
730   bool isSigned
731     = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
732   llvm::IntegerType *numElementsType
733     = cast<llvm::IntegerType>(numElements->getType());
734   unsigned numElementsWidth = numElementsType->getBitWidth();
735 
736   // Compute the constant factor.
737   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
738   while (const ConstantArrayType *CAT
739              = CGF.getContext().getAsConstantArrayType(type)) {
740     type = CAT->getElementType();
741     arraySizeMultiplier *= CAT->getSize();
742   }
743 
744   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
745   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
746   typeSizeMultiplier *= arraySizeMultiplier;
747 
748   // This will be a size_t.
749   llvm::Value *size;
750 
751   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
752   // Don't bloat the -O0 code.
753   if (llvm::ConstantInt *numElementsC =
754         dyn_cast<llvm::ConstantInt>(numElements)) {
755     const llvm::APInt &count = numElementsC->getValue();
756 
757     bool hasAnyOverflow = false;
758 
759     // If 'count' was a negative number, it's an overflow.
760     if (isSigned && count.isNegative())
761       hasAnyOverflow = true;
762 
763     // We want to do all this arithmetic in size_t.  If numElements is
764     // wider than that, check whether it's already too big, and if so,
765     // overflow.
766     else if (numElementsWidth > sizeWidth &&
767              numElementsWidth - sizeWidth > count.countLeadingZeros())
768       hasAnyOverflow = true;
769 
770     // Okay, compute a count at the right width.
771     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
772 
773     // If there is a brace-initializer, we cannot allocate fewer elements than
774     // there are initializers. If we do, that's treated like an overflow.
775     if (adjustedCount.ult(minElements))
776       hasAnyOverflow = true;
777 
778     // Scale numElements by that.  This might overflow, but we don't
779     // care because it only overflows if allocationSize does, too, and
780     // if that overflows then we shouldn't use this.
781     numElements = llvm::ConstantInt::get(CGF.SizeTy,
782                                          adjustedCount * arraySizeMultiplier);
783 
784     // Compute the size before cookie, and track whether it overflowed.
785     bool overflow;
786     llvm::APInt allocationSize
787       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
788     hasAnyOverflow |= overflow;
789 
790     // Add in the cookie, and check whether it's overflowed.
791     if (cookieSize != 0) {
792       // Save the current size without a cookie.  This shouldn't be
793       // used if there was overflow.
794       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
795 
796       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
797       hasAnyOverflow |= overflow;
798     }
799 
800     // On overflow, produce a -1 so operator new will fail.
801     if (hasAnyOverflow) {
802       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
803     } else {
804       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
805     }
806 
807   // Otherwise, we might need to use the overflow intrinsics.
808   } else {
809     // There are up to five conditions we need to test for:
810     // 1) if isSigned, we need to check whether numElements is negative;
811     // 2) if numElementsWidth > sizeWidth, we need to check whether
812     //   numElements is larger than something representable in size_t;
813     // 3) if minElements > 0, we need to check whether numElements is smaller
814     //    than that.
815     // 4) we need to compute
816     //      sizeWithoutCookie := numElements * typeSizeMultiplier
817     //    and check whether it overflows; and
818     // 5) if we need a cookie, we need to compute
819     //      size := sizeWithoutCookie + cookieSize
820     //    and check whether it overflows.
821 
822     llvm::Value *hasOverflow = nullptr;
823 
824     // If numElementsWidth > sizeWidth, then one way or another, we're
825     // going to have to do a comparison for (2), and this happens to
826     // take care of (1), too.
827     if (numElementsWidth > sizeWidth) {
828       llvm::APInt threshold(numElementsWidth, 1);
829       threshold <<= sizeWidth;
830 
831       llvm::Value *thresholdV
832         = llvm::ConstantInt::get(numElementsType, threshold);
833 
834       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
835       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
836 
837     // Otherwise, if we're signed, we want to sext up to size_t.
838     } else if (isSigned) {
839       if (numElementsWidth < sizeWidth)
840         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
841 
842       // If there's a non-1 type size multiplier, then we can do the
843       // signedness check at the same time as we do the multiply
844       // because a negative number times anything will cause an
845       // unsigned overflow.  Otherwise, we have to do it here. But at least
846       // in this case, we can subsume the >= minElements check.
847       if (typeSizeMultiplier == 1)
848         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
849                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
850 
851     // Otherwise, zext up to size_t if necessary.
852     } else if (numElementsWidth < sizeWidth) {
853       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
854     }
855 
856     assert(numElements->getType() == CGF.SizeTy);
857 
858     if (minElements) {
859       // Don't allow allocation of fewer elements than we have initializers.
860       if (!hasOverflow) {
861         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
862                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
863       } else if (numElementsWidth > sizeWidth) {
864         // The other existing overflow subsumes this check.
865         // We do an unsigned comparison, since any signed value < -1 is
866         // taken care of either above or below.
867         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
868                           CGF.Builder.CreateICmpULT(numElements,
869                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
870       }
871     }
872 
873     size = numElements;
874 
875     // Multiply by the type size if necessary.  This multiplier
876     // includes all the factors for nested arrays.
877     //
878     // This step also causes numElements to be scaled up by the
879     // nested-array factor if necessary.  Overflow on this computation
880     // can be ignored because the result shouldn't be used if
881     // allocation fails.
882     if (typeSizeMultiplier != 1) {
883       llvm::Function *umul_with_overflow
884         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
885 
886       llvm::Value *tsmV =
887         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
888       llvm::Value *result =
889           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
890 
891       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
892       if (hasOverflow)
893         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
894       else
895         hasOverflow = overflowed;
896 
897       size = CGF.Builder.CreateExtractValue(result, 0);
898 
899       // Also scale up numElements by the array size multiplier.
900       if (arraySizeMultiplier != 1) {
901         // If the base element type size is 1, then we can re-use the
902         // multiply we just did.
903         if (typeSize.isOne()) {
904           assert(arraySizeMultiplier == typeSizeMultiplier);
905           numElements = size;
906 
907         // Otherwise we need a separate multiply.
908         } else {
909           llvm::Value *asmV =
910             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
911           numElements = CGF.Builder.CreateMul(numElements, asmV);
912         }
913       }
914     } else {
915       // numElements doesn't need to be scaled.
916       assert(arraySizeMultiplier == 1);
917     }
918 
919     // Add in the cookie size if necessary.
920     if (cookieSize != 0) {
921       sizeWithoutCookie = size;
922 
923       llvm::Function *uadd_with_overflow
924         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
925 
926       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
927       llvm::Value *result =
928           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
929 
930       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
931       if (hasOverflow)
932         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
933       else
934         hasOverflow = overflowed;
935 
936       size = CGF.Builder.CreateExtractValue(result, 0);
937     }
938 
939     // If we had any possibility of dynamic overflow, make a select to
940     // overwrite 'size' with an all-ones value, which should cause
941     // operator new to throw.
942     if (hasOverflow)
943       size = CGF.Builder.CreateSelect(hasOverflow,
944                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
945                                       size);
946   }
947 
948   if (cookieSize == 0)
949     sizeWithoutCookie = size;
950   else
951     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
952 
953   return size;
954 }
955 
956 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
957                                     QualType AllocType, Address NewPtr,
958                                     AggValueSlot::Overlap_t MayOverlap) {
959   // FIXME: Refactor with EmitExprAsInit.
960   switch (CGF.getEvaluationKind(AllocType)) {
961   case TEK_Scalar:
962     CGF.EmitScalarInit(Init, nullptr,
963                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
964     return;
965   case TEK_Complex:
966     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
967                                   /*isInit*/ true);
968     return;
969   case TEK_Aggregate: {
970     AggValueSlot Slot
971       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
972                               AggValueSlot::IsDestructed,
973                               AggValueSlot::DoesNotNeedGCBarriers,
974                               AggValueSlot::IsNotAliased,
975                               MayOverlap, AggValueSlot::IsNotZeroed,
976                               AggValueSlot::IsSanitizerChecked);
977     CGF.EmitAggExpr(Init, Slot);
978     return;
979   }
980   }
981   llvm_unreachable("bad evaluation kind");
982 }
983 
984 void CodeGenFunction::EmitNewArrayInitializer(
985     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
986     Address BeginPtr, llvm::Value *NumElements,
987     llvm::Value *AllocSizeWithoutCookie) {
988   // If we have a type with trivial initialization and no initializer,
989   // there's nothing to do.
990   if (!E->hasInitializer())
991     return;
992 
993   Address CurPtr = BeginPtr;
994 
995   unsigned InitListElements = 0;
996 
997   const Expr *Init = E->getInitializer();
998   Address EndOfInit = Address::invalid();
999   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
1000   EHScopeStack::stable_iterator Cleanup;
1001   llvm::Instruction *CleanupDominator = nullptr;
1002 
1003   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
1004   CharUnits ElementAlign =
1005     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1006 
1007   // Attempt to perform zero-initialization using memset.
1008   auto TryMemsetInitialization = [&]() -> bool {
1009     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1010     // we can initialize with a memset to -1.
1011     if (!CGM.getTypes().isZeroInitializable(ElementType))
1012       return false;
1013 
1014     // Optimization: since zero initialization will just set the memory
1015     // to all zeroes, generate a single memset to do it in one shot.
1016 
1017     // Subtract out the size of any elements we've already initialized.
1018     auto *RemainingSize = AllocSizeWithoutCookie;
1019     if (InitListElements) {
1020       // We know this can't overflow; we check this when doing the allocation.
1021       auto *InitializedSize = llvm::ConstantInt::get(
1022           RemainingSize->getType(),
1023           getContext().getTypeSizeInChars(ElementType).getQuantity() *
1024               InitListElements);
1025       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1026     }
1027 
1028     // Create the memset.
1029     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1030     return true;
1031   };
1032 
1033   // If the initializer is an initializer list, first do the explicit elements.
1034   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1035     // Initializing from a (braced) string literal is a special case; the init
1036     // list element does not initialize a (single) array element.
1037     if (ILE->isStringLiteralInit()) {
1038       // Initialize the initial portion of length equal to that of the string
1039       // literal. The allocation must be for at least this much; we emitted a
1040       // check for that earlier.
1041       AggValueSlot Slot =
1042           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1043                                 AggValueSlot::IsDestructed,
1044                                 AggValueSlot::DoesNotNeedGCBarriers,
1045                                 AggValueSlot::IsNotAliased,
1046                                 AggValueSlot::DoesNotOverlap,
1047                                 AggValueSlot::IsNotZeroed,
1048                                 AggValueSlot::IsSanitizerChecked);
1049       EmitAggExpr(ILE->getInit(0), Slot);
1050 
1051       // Move past these elements.
1052       InitListElements =
1053           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1054               ->getSize().getZExtValue();
1055       CurPtr = Builder.CreateConstInBoundsGEP(
1056           CurPtr, InitListElements, "string.init.end");
1057 
1058       // Zero out the rest, if any remain.
1059       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1060       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1061         bool OK = TryMemsetInitialization();
1062         (void)OK;
1063         assert(OK && "couldn't memset character type?");
1064       }
1065       return;
1066     }
1067 
1068     InitListElements = ILE->getNumInits();
1069 
1070     // If this is a multi-dimensional array new, we will initialize multiple
1071     // elements with each init list element.
1072     QualType AllocType = E->getAllocatedType();
1073     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1074             AllocType->getAsArrayTypeUnsafe())) {
1075       ElementTy = ConvertTypeForMem(AllocType);
1076       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1077       InitListElements *= getContext().getConstantArrayElementCount(CAT);
1078     }
1079 
1080     // Enter a partial-destruction Cleanup if necessary.
1081     if (needsEHCleanup(DtorKind)) {
1082       // In principle we could tell the Cleanup where we are more
1083       // directly, but the control flow can get so varied here that it
1084       // would actually be quite complex.  Therefore we go through an
1085       // alloca.
1086       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1087                                    "array.init.end");
1088       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1089       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1090                                        ElementType, ElementAlign,
1091                                        getDestroyer(DtorKind));
1092       Cleanup = EHStack.stable_begin();
1093     }
1094 
1095     CharUnits StartAlign = CurPtr.getAlignment();
1096     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1097       // Tell the cleanup that it needs to destroy up to this
1098       // element.  TODO: some of these stores can be trivially
1099       // observed to be unnecessary.
1100       if (EndOfInit.isValid()) {
1101         auto FinishedPtr =
1102           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1103         Builder.CreateStore(FinishedPtr, EndOfInit);
1104       }
1105       // FIXME: If the last initializer is an incomplete initializer list for
1106       // an array, and we have an array filler, we can fold together the two
1107       // initialization loops.
1108       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1109                               ILE->getInit(i)->getType(), CurPtr,
1110                               AggValueSlot::DoesNotOverlap);
1111       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1112                                                  CurPtr.getPointer(),
1113                                                  Builder.getSize(1),
1114                                                  "array.exp.next"),
1115                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1116     }
1117 
1118     // The remaining elements are filled with the array filler expression.
1119     Init = ILE->getArrayFiller();
1120 
1121     // Extract the initializer for the individual array elements by pulling
1122     // out the array filler from all the nested initializer lists. This avoids
1123     // generating a nested loop for the initialization.
1124     while (Init && Init->getType()->isConstantArrayType()) {
1125       auto *SubILE = dyn_cast<InitListExpr>(Init);
1126       if (!SubILE)
1127         break;
1128       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1129       Init = SubILE->getArrayFiller();
1130     }
1131 
1132     // Switch back to initializing one base element at a time.
1133     CurPtr = Builder.CreateElementBitCast(CurPtr, BeginPtr.getElementType());
1134   }
1135 
1136   // If all elements have already been initialized, skip any further
1137   // initialization.
1138   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1139   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1140     // If there was a Cleanup, deactivate it.
1141     if (CleanupDominator)
1142       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1143     return;
1144   }
1145 
1146   assert(Init && "have trailing elements to initialize but no initializer");
1147 
1148   // If this is a constructor call, try to optimize it out, and failing that
1149   // emit a single loop to initialize all remaining elements.
1150   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1151     CXXConstructorDecl *Ctor = CCE->getConstructor();
1152     if (Ctor->isTrivial()) {
1153       // If new expression did not specify value-initialization, then there
1154       // is no initialization.
1155       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1156         return;
1157 
1158       if (TryMemsetInitialization())
1159         return;
1160     }
1161 
1162     // Store the new Cleanup position for irregular Cleanups.
1163     //
1164     // FIXME: Share this cleanup with the constructor call emission rather than
1165     // having it create a cleanup of its own.
1166     if (EndOfInit.isValid())
1167       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1168 
1169     // Emit a constructor call loop to initialize the remaining elements.
1170     if (InitListElements)
1171       NumElements = Builder.CreateSub(
1172           NumElements,
1173           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1174     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1175                                /*NewPointerIsChecked*/true,
1176                                CCE->requiresZeroInitialization());
1177     return;
1178   }
1179 
1180   // If this is value-initialization, we can usually use memset.
1181   ImplicitValueInitExpr IVIE(ElementType);
1182   if (isa<ImplicitValueInitExpr>(Init)) {
1183     if (TryMemsetInitialization())
1184       return;
1185 
1186     // Switch to an ImplicitValueInitExpr for the element type. This handles
1187     // only one case: multidimensional array new of pointers to members. In
1188     // all other cases, we already have an initializer for the array element.
1189     Init = &IVIE;
1190   }
1191 
1192   // At this point we should have found an initializer for the individual
1193   // elements of the array.
1194   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1195          "got wrong type of element to initialize");
1196 
1197   // If we have an empty initializer list, we can usually use memset.
1198   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1199     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1200       return;
1201 
1202   // If we have a struct whose every field is value-initialized, we can
1203   // usually use memset.
1204   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1205     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1206       if (RType->getDecl()->isStruct()) {
1207         unsigned NumElements = 0;
1208         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1209           NumElements = CXXRD->getNumBases();
1210         for (auto *Field : RType->getDecl()->fields())
1211           if (!Field->isUnnamedBitfield())
1212             ++NumElements;
1213         // FIXME: Recurse into nested InitListExprs.
1214         if (ILE->getNumInits() == NumElements)
1215           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1216             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1217               --NumElements;
1218         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1219           return;
1220       }
1221     }
1222   }
1223 
1224   // Create the loop blocks.
1225   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1226   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1227   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1228 
1229   // Find the end of the array, hoisted out of the loop.
1230   llvm::Value *EndPtr =
1231     Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(),
1232                               NumElements, "array.end");
1233 
1234   // If the number of elements isn't constant, we have to now check if there is
1235   // anything left to initialize.
1236   if (!ConstNum) {
1237     llvm::Value *IsEmpty =
1238       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1239     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1240   }
1241 
1242   // Enter the loop.
1243   EmitBlock(LoopBB);
1244 
1245   // Set up the current-element phi.
1246   llvm::PHINode *CurPtrPhi =
1247     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1248   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1249 
1250   CurPtr = Address(CurPtrPhi, ElementAlign);
1251 
1252   // Store the new Cleanup position for irregular Cleanups.
1253   if (EndOfInit.isValid())
1254     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1255 
1256   // Enter a partial-destruction Cleanup if necessary.
1257   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1258     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1259                                    ElementType, ElementAlign,
1260                                    getDestroyer(DtorKind));
1261     Cleanup = EHStack.stable_begin();
1262     CleanupDominator = Builder.CreateUnreachable();
1263   }
1264 
1265   // Emit the initializer into this element.
1266   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1267                           AggValueSlot::DoesNotOverlap);
1268 
1269   // Leave the Cleanup if we entered one.
1270   if (CleanupDominator) {
1271     DeactivateCleanupBlock(Cleanup, CleanupDominator);
1272     CleanupDominator->eraseFromParent();
1273   }
1274 
1275   // Advance to the next element by adjusting the pointer type as necessary.
1276   llvm::Value *NextPtr =
1277     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1278                                        "array.next");
1279 
1280   // Check whether we've gotten to the end of the array and, if so,
1281   // exit the loop.
1282   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1283   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1284   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1285 
1286   EmitBlock(ContBB);
1287 }
1288 
1289 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1290                                QualType ElementType, llvm::Type *ElementTy,
1291                                Address NewPtr, llvm::Value *NumElements,
1292                                llvm::Value *AllocSizeWithoutCookie) {
1293   ApplyDebugLocation DL(CGF, E);
1294   if (E->isArray())
1295     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1296                                 AllocSizeWithoutCookie);
1297   else if (const Expr *Init = E->getInitializer())
1298     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1299                             AggValueSlot::DoesNotOverlap);
1300 }
1301 
1302 /// Emit a call to an operator new or operator delete function, as implicitly
1303 /// created by new-expressions and delete-expressions.
1304 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1305                                 const FunctionDecl *CalleeDecl,
1306                                 const FunctionProtoType *CalleeType,
1307                                 const CallArgList &Args) {
1308   llvm::CallBase *CallOrInvoke;
1309   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1310   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1311   RValue RV =
1312       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1313                        Args, CalleeType, /*ChainCall=*/false),
1314                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1315 
1316   /// C++1y [expr.new]p10:
1317   ///   [In a new-expression,] an implementation is allowed to omit a call
1318   ///   to a replaceable global allocation function.
1319   ///
1320   /// We model such elidable calls with the 'builtin' attribute.
1321   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1322   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1323       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1324     CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
1325   }
1326 
1327   return RV;
1328 }
1329 
1330 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1331                                                  const CallExpr *TheCall,
1332                                                  bool IsDelete) {
1333   CallArgList Args;
1334   EmitCallArgs(Args, Type, TheCall->arguments());
1335   // Find the allocation or deallocation function that we're calling.
1336   ASTContext &Ctx = getContext();
1337   DeclarationName Name = Ctx.DeclarationNames
1338       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1339 
1340   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1341     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1342       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1343         return EmitNewDeleteCall(*this, FD, Type, Args);
1344   llvm_unreachable("predeclared global operator new/delete is missing");
1345 }
1346 
1347 namespace {
1348 /// The parameters to pass to a usual operator delete.
1349 struct UsualDeleteParams {
1350   bool DestroyingDelete = false;
1351   bool Size = false;
1352   bool Alignment = false;
1353 };
1354 }
1355 
1356 static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1357   UsualDeleteParams Params;
1358 
1359   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1360   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1361 
1362   // The first argument is always a void*.
1363   ++AI;
1364 
1365   // The next parameter may be a std::destroying_delete_t.
1366   if (FD->isDestroyingOperatorDelete()) {
1367     Params.DestroyingDelete = true;
1368     assert(AI != AE);
1369     ++AI;
1370   }
1371 
1372   // Figure out what other parameters we should be implicitly passing.
1373   if (AI != AE && (*AI)->isIntegerType()) {
1374     Params.Size = true;
1375     ++AI;
1376   }
1377 
1378   if (AI != AE && (*AI)->isAlignValT()) {
1379     Params.Alignment = true;
1380     ++AI;
1381   }
1382 
1383   assert(AI == AE && "unexpected usual deallocation function parameter");
1384   return Params;
1385 }
1386 
1387 namespace {
1388   /// A cleanup to call the given 'operator delete' function upon abnormal
1389   /// exit from a new expression. Templated on a traits type that deals with
1390   /// ensuring that the arguments dominate the cleanup if necessary.
1391   template<typename Traits>
1392   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1393     /// Type used to hold llvm::Value*s.
1394     typedef typename Traits::ValueTy ValueTy;
1395     /// Type used to hold RValues.
1396     typedef typename Traits::RValueTy RValueTy;
1397     struct PlacementArg {
1398       RValueTy ArgValue;
1399       QualType ArgType;
1400     };
1401 
1402     unsigned NumPlacementArgs : 31;
1403     unsigned PassAlignmentToPlacementDelete : 1;
1404     const FunctionDecl *OperatorDelete;
1405     ValueTy Ptr;
1406     ValueTy AllocSize;
1407     CharUnits AllocAlign;
1408 
1409     PlacementArg *getPlacementArgs() {
1410       return reinterpret_cast<PlacementArg *>(this + 1);
1411     }
1412 
1413   public:
1414     static size_t getExtraSize(size_t NumPlacementArgs) {
1415       return NumPlacementArgs * sizeof(PlacementArg);
1416     }
1417 
1418     CallDeleteDuringNew(size_t NumPlacementArgs,
1419                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1420                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1421                         CharUnits AllocAlign)
1422       : NumPlacementArgs(NumPlacementArgs),
1423         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1424         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1425         AllocAlign(AllocAlign) {}
1426 
1427     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1428       assert(I < NumPlacementArgs && "index out of range");
1429       getPlacementArgs()[I] = {Arg, Type};
1430     }
1431 
1432     void Emit(CodeGenFunction &CGF, Flags flags) override {
1433       const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1434       CallArgList DeleteArgs;
1435 
1436       // The first argument is always a void* (or C* for a destroying operator
1437       // delete for class type C).
1438       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1439 
1440       // Figure out what other parameters we should be implicitly passing.
1441       UsualDeleteParams Params;
1442       if (NumPlacementArgs) {
1443         // A placement deallocation function is implicitly passed an alignment
1444         // if the placement allocation function was, but is never passed a size.
1445         Params.Alignment = PassAlignmentToPlacementDelete;
1446       } else {
1447         // For a non-placement new-expression, 'operator delete' can take a
1448         // size and/or an alignment if it has the right parameters.
1449         Params = getUsualDeleteParams(OperatorDelete);
1450       }
1451 
1452       assert(!Params.DestroyingDelete &&
1453              "should not call destroying delete in a new-expression");
1454 
1455       // The second argument can be a std::size_t (for non-placement delete).
1456       if (Params.Size)
1457         DeleteArgs.add(Traits::get(CGF, AllocSize),
1458                        CGF.getContext().getSizeType());
1459 
1460       // The next (second or third) argument can be a std::align_val_t, which
1461       // is an enum whose underlying type is std::size_t.
1462       // FIXME: Use the right type as the parameter type. Note that in a call
1463       // to operator delete(size_t, ...), we may not have it available.
1464       if (Params.Alignment)
1465         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1466                            CGF.SizeTy, AllocAlign.getQuantity())),
1467                        CGF.getContext().getSizeType());
1468 
1469       // Pass the rest of the arguments, which must match exactly.
1470       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1471         auto Arg = getPlacementArgs()[I];
1472         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1473       }
1474 
1475       // Call 'operator delete'.
1476       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1477     }
1478   };
1479 }
1480 
1481 /// Enter a cleanup to call 'operator delete' if the initializer in a
1482 /// new-expression throws.
1483 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1484                                   const CXXNewExpr *E,
1485                                   Address NewPtr,
1486                                   llvm::Value *AllocSize,
1487                                   CharUnits AllocAlign,
1488                                   const CallArgList &NewArgs) {
1489   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1490 
1491   // If we're not inside a conditional branch, then the cleanup will
1492   // dominate and we can do the easier (and more efficient) thing.
1493   if (!CGF.isInConditionalBranch()) {
1494     struct DirectCleanupTraits {
1495       typedef llvm::Value *ValueTy;
1496       typedef RValue RValueTy;
1497       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1498       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1499     };
1500 
1501     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1502 
1503     DirectCleanup *Cleanup = CGF.EHStack
1504       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1505                                            E->getNumPlacementArgs(),
1506                                            E->getOperatorDelete(),
1507                                            NewPtr.getPointer(),
1508                                            AllocSize,
1509                                            E->passAlignment(),
1510                                            AllocAlign);
1511     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1512       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1513       Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1514     }
1515 
1516     return;
1517   }
1518 
1519   // Otherwise, we need to save all this stuff.
1520   DominatingValue<RValue>::saved_type SavedNewPtr =
1521     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1522   DominatingValue<RValue>::saved_type SavedAllocSize =
1523     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1524 
1525   struct ConditionalCleanupTraits {
1526     typedef DominatingValue<RValue>::saved_type ValueTy;
1527     typedef DominatingValue<RValue>::saved_type RValueTy;
1528     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1529       return V.restore(CGF);
1530     }
1531   };
1532   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1533 
1534   ConditionalCleanup *Cleanup = CGF.EHStack
1535     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1536                                               E->getNumPlacementArgs(),
1537                                               E->getOperatorDelete(),
1538                                               SavedNewPtr,
1539                                               SavedAllocSize,
1540                                               E->passAlignment(),
1541                                               AllocAlign);
1542   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1543     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1544     Cleanup->setPlacementArg(
1545         I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1546   }
1547 
1548   CGF.initFullExprCleanup();
1549 }
1550 
1551 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1552   // The element type being allocated.
1553   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1554 
1555   // 1. Build a call to the allocation function.
1556   FunctionDecl *allocator = E->getOperatorNew();
1557 
1558   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1559   unsigned minElements = 0;
1560   if (E->isArray() && E->hasInitializer()) {
1561     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1562     if (ILE && ILE->isStringLiteralInit())
1563       minElements =
1564           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1565               ->getSize().getZExtValue();
1566     else if (ILE)
1567       minElements = ILE->getNumInits();
1568   }
1569 
1570   llvm::Value *numElements = nullptr;
1571   llvm::Value *allocSizeWithoutCookie = nullptr;
1572   llvm::Value *allocSize =
1573     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1574                         allocSizeWithoutCookie);
1575   CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
1576 
1577   // Emit the allocation call.  If the allocator is a global placement
1578   // operator, just "inline" it directly.
1579   Address allocation = Address::invalid();
1580   CallArgList allocatorArgs;
1581   if (allocator->isReservedGlobalPlacementOperator()) {
1582     assert(E->getNumPlacementArgs() == 1);
1583     const Expr *arg = *E->placement_arguments().begin();
1584 
1585     LValueBaseInfo BaseInfo;
1586     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1587 
1588     // The pointer expression will, in many cases, be an opaque void*.
1589     // In these cases, discard the computed alignment and use the
1590     // formal alignment of the allocated type.
1591     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1592       allocation = allocation.withAlignment(allocAlign);
1593 
1594     // Set up allocatorArgs for the call to operator delete if it's not
1595     // the reserved global operator.
1596     if (E->getOperatorDelete() &&
1597         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1598       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1599       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1600     }
1601 
1602   } else {
1603     const FunctionProtoType *allocatorType =
1604       allocator->getType()->castAs<FunctionProtoType>();
1605     unsigned ParamsToSkip = 0;
1606 
1607     // The allocation size is the first argument.
1608     QualType sizeType = getContext().getSizeType();
1609     allocatorArgs.add(RValue::get(allocSize), sizeType);
1610     ++ParamsToSkip;
1611 
1612     if (allocSize != allocSizeWithoutCookie) {
1613       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1614       allocAlign = std::max(allocAlign, cookieAlign);
1615     }
1616 
1617     // The allocation alignment may be passed as the second argument.
1618     if (E->passAlignment()) {
1619       QualType AlignValT = sizeType;
1620       if (allocatorType->getNumParams() > 1) {
1621         AlignValT = allocatorType->getParamType(1);
1622         assert(getContext().hasSameUnqualifiedType(
1623                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1624                    sizeType) &&
1625                "wrong type for alignment parameter");
1626         ++ParamsToSkip;
1627       } else {
1628         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1629         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1630       }
1631       allocatorArgs.add(
1632           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1633           AlignValT);
1634     }
1635 
1636     // FIXME: Why do we not pass a CalleeDecl here?
1637     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1638                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1639 
1640     RValue RV =
1641       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1642 
1643     // Set !heapallocsite metadata on the call to operator new.
1644     if (getDebugInfo())
1645       if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
1646         getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
1647                                                  E->getExprLoc());
1648 
1649     // If this was a call to a global replaceable allocation function that does
1650     // not take an alignment argument, the allocator is known to produce
1651     // storage that's suitably aligned for any object that fits, up to a known
1652     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1653     CharUnits allocationAlign = allocAlign;
1654     if (!E->passAlignment() &&
1655         allocator->isReplaceableGlobalAllocationFunction()) {
1656       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1657           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1658       allocationAlign = std::max(
1659           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1660     }
1661 
1662     allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
1663   }
1664 
1665   // Emit a null check on the allocation result if the allocation
1666   // function is allowed to return null (because it has a non-throwing
1667   // exception spec or is the reserved placement new) and we have an
1668   // interesting initializer will be running sanitizers on the initialization.
1669   bool nullCheck = E->shouldNullCheckAllocation() &&
1670                    (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1671                     sanitizePerformTypeCheck());
1672 
1673   llvm::BasicBlock *nullCheckBB = nullptr;
1674   llvm::BasicBlock *contBB = nullptr;
1675 
1676   // The null-check means that the initializer is conditionally
1677   // evaluated.
1678   ConditionalEvaluation conditional(*this);
1679 
1680   if (nullCheck) {
1681     conditional.begin(*this);
1682 
1683     nullCheckBB = Builder.GetInsertBlock();
1684     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1685     contBB = createBasicBlock("new.cont");
1686 
1687     llvm::Value *isNull =
1688       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1689     Builder.CreateCondBr(isNull, contBB, notNullBB);
1690     EmitBlock(notNullBB);
1691   }
1692 
1693   // If there's an operator delete, enter a cleanup to call it if an
1694   // exception is thrown.
1695   EHScopeStack::stable_iterator operatorDeleteCleanup;
1696   llvm::Instruction *cleanupDominator = nullptr;
1697   if (E->getOperatorDelete() &&
1698       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1699     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1700                           allocatorArgs);
1701     operatorDeleteCleanup = EHStack.stable_begin();
1702     cleanupDominator = Builder.CreateUnreachable();
1703   }
1704 
1705   assert((allocSize == allocSizeWithoutCookie) ==
1706          CalculateCookiePadding(*this, E).isZero());
1707   if (allocSize != allocSizeWithoutCookie) {
1708     assert(E->isArray());
1709     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1710                                                        numElements,
1711                                                        E, allocType);
1712   }
1713 
1714   llvm::Type *elementTy = ConvertTypeForMem(allocType);
1715   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1716 
1717   // Passing pointer through launder.invariant.group to avoid propagation of
1718   // vptrs information which may be included in previous type.
1719   // To not break LTO with different optimizations levels, we do it regardless
1720   // of optimization level.
1721   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1722       allocator->isReservedGlobalPlacementOperator())
1723     result = Builder.CreateLaunderInvariantGroup(result);
1724 
1725   // Emit sanitizer checks for pointer value now, so that in the case of an
1726   // array it was checked only once and not at each constructor call. We may
1727   // have already checked that the pointer is non-null.
1728   // FIXME: If we have an array cookie and a potentially-throwing allocator,
1729   // we'll null check the wrong pointer here.
1730   SanitizerSet SkippedChecks;
1731   SkippedChecks.set(SanitizerKind::Null, nullCheck);
1732   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1733                 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1734                 result.getPointer(), allocType, result.getAlignment(),
1735                 SkippedChecks, numElements);
1736 
1737   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1738                      allocSizeWithoutCookie);
1739   if (E->isArray()) {
1740     // NewPtr is a pointer to the base element type.  If we're
1741     // allocating an array of arrays, we'll need to cast back to the
1742     // array pointer type.
1743     llvm::Type *resultType = ConvertTypeForMem(E->getType());
1744     if (result.getType() != resultType)
1745       result = Builder.CreateBitCast(result, resultType);
1746   }
1747 
1748   // Deactivate the 'operator delete' cleanup if we finished
1749   // initialization.
1750   if (operatorDeleteCleanup.isValid()) {
1751     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1752     cleanupDominator->eraseFromParent();
1753   }
1754 
1755   llvm::Value *resultPtr = result.getPointer();
1756   if (nullCheck) {
1757     conditional.end(*this);
1758 
1759     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1760     EmitBlock(contBB);
1761 
1762     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1763     PHI->addIncoming(resultPtr, notNullBB);
1764     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1765                      nullCheckBB);
1766 
1767     resultPtr = PHI;
1768   }
1769 
1770   return resultPtr;
1771 }
1772 
1773 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1774                                      llvm::Value *Ptr, QualType DeleteTy,
1775                                      llvm::Value *NumElements,
1776                                      CharUnits CookieSize) {
1777   assert((!NumElements && CookieSize.isZero()) ||
1778          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1779 
1780   const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1781   CallArgList DeleteArgs;
1782 
1783   auto Params = getUsualDeleteParams(DeleteFD);
1784   auto ParamTypeIt = DeleteFTy->param_type_begin();
1785 
1786   // Pass the pointer itself.
1787   QualType ArgTy = *ParamTypeIt++;
1788   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1789   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1790 
1791   // Pass the std::destroying_delete tag if present.
1792   llvm::AllocaInst *DestroyingDeleteTag = nullptr;
1793   if (Params.DestroyingDelete) {
1794     QualType DDTag = *ParamTypeIt++;
1795     llvm::Type *Ty = getTypes().ConvertType(DDTag);
1796     CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1797     DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1798     DestroyingDeleteTag->setAlignment(Align.getAsAlign());
1799     DeleteArgs.add(RValue::getAggregate(Address(DestroyingDeleteTag, Align)), DDTag);
1800   }
1801 
1802   // Pass the size if the delete function has a size_t parameter.
1803   if (Params.Size) {
1804     QualType SizeType = *ParamTypeIt++;
1805     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1806     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1807                                                DeleteTypeSize.getQuantity());
1808 
1809     // For array new, multiply by the number of elements.
1810     if (NumElements)
1811       Size = Builder.CreateMul(Size, NumElements);
1812 
1813     // If there is a cookie, add the cookie size.
1814     if (!CookieSize.isZero())
1815       Size = Builder.CreateAdd(
1816           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1817 
1818     DeleteArgs.add(RValue::get(Size), SizeType);
1819   }
1820 
1821   // Pass the alignment if the delete function has an align_val_t parameter.
1822   if (Params.Alignment) {
1823     QualType AlignValType = *ParamTypeIt++;
1824     CharUnits DeleteTypeAlign =
1825         getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1826             DeleteTy, true /* NeedsPreferredAlignment */));
1827     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1828                                                 DeleteTypeAlign.getQuantity());
1829     DeleteArgs.add(RValue::get(Align), AlignValType);
1830   }
1831 
1832   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1833          "unknown parameter to usual delete function");
1834 
1835   // Emit the call to delete.
1836   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1837 
1838   // If call argument lowering didn't use the destroying_delete_t alloca,
1839   // remove it again.
1840   if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1841     DestroyingDeleteTag->eraseFromParent();
1842 }
1843 
1844 namespace {
1845   /// Calls the given 'operator delete' on a single object.
1846   struct CallObjectDelete final : EHScopeStack::Cleanup {
1847     llvm::Value *Ptr;
1848     const FunctionDecl *OperatorDelete;
1849     QualType ElementType;
1850 
1851     CallObjectDelete(llvm::Value *Ptr,
1852                      const FunctionDecl *OperatorDelete,
1853                      QualType ElementType)
1854       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1855 
1856     void Emit(CodeGenFunction &CGF, Flags flags) override {
1857       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1858     }
1859   };
1860 }
1861 
1862 void
1863 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1864                                              llvm::Value *CompletePtr,
1865                                              QualType ElementType) {
1866   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1867                                         OperatorDelete, ElementType);
1868 }
1869 
1870 /// Emit the code for deleting a single object with a destroying operator
1871 /// delete. If the element type has a non-virtual destructor, Ptr has already
1872 /// been converted to the type of the parameter of 'operator delete'. Otherwise
1873 /// Ptr points to an object of the static type.
1874 static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1875                                        const CXXDeleteExpr *DE, Address Ptr,
1876                                        QualType ElementType) {
1877   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1878   if (Dtor && Dtor->isVirtual())
1879     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1880                                                 Dtor);
1881   else
1882     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1883 }
1884 
1885 /// Emit the code for deleting a single object.
1886 /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1887 /// if not.
1888 static bool EmitObjectDelete(CodeGenFunction &CGF,
1889                              const CXXDeleteExpr *DE,
1890                              Address Ptr,
1891                              QualType ElementType,
1892                              llvm::BasicBlock *UnconditionalDeleteBlock) {
1893   // C++11 [expr.delete]p3:
1894   //   If the static type of the object to be deleted is different from its
1895   //   dynamic type, the static type shall be a base class of the dynamic type
1896   //   of the object to be deleted and the static type shall have a virtual
1897   //   destructor or the behavior is undefined.
1898   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1899                     DE->getExprLoc(), Ptr.getPointer(),
1900                     ElementType);
1901 
1902   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1903   assert(!OperatorDelete->isDestroyingOperatorDelete());
1904 
1905   // Find the destructor for the type, if applicable.  If the
1906   // destructor is virtual, we'll just emit the vcall and return.
1907   const CXXDestructorDecl *Dtor = nullptr;
1908   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1909     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1910     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1911       Dtor = RD->getDestructor();
1912 
1913       if (Dtor->isVirtual()) {
1914         bool UseVirtualCall = true;
1915         const Expr *Base = DE->getArgument();
1916         if (auto *DevirtualizedDtor =
1917                 dyn_cast_or_null<const CXXDestructorDecl>(
1918                     Dtor->getDevirtualizedMethod(
1919                         Base, CGF.CGM.getLangOpts().AppleKext))) {
1920           UseVirtualCall = false;
1921           const CXXRecordDecl *DevirtualizedClass =
1922               DevirtualizedDtor->getParent();
1923           if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1924             // Devirtualized to the class of the base type (the type of the
1925             // whole expression).
1926             Dtor = DevirtualizedDtor;
1927           } else {
1928             // Devirtualized to some other type. Would need to cast the this
1929             // pointer to that type but we don't have support for that yet, so
1930             // do a virtual call. FIXME: handle the case where it is
1931             // devirtualized to the derived type (the type of the inner
1932             // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1933             UseVirtualCall = true;
1934           }
1935         }
1936         if (UseVirtualCall) {
1937           CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1938                                                       Dtor);
1939           return false;
1940         }
1941       }
1942     }
1943   }
1944 
1945   // Make sure that we call delete even if the dtor throws.
1946   // This doesn't have to a conditional cleanup because we're going
1947   // to pop it off in a second.
1948   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1949                                             Ptr.getPointer(),
1950                                             OperatorDelete, ElementType);
1951 
1952   if (Dtor)
1953     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1954                               /*ForVirtualBase=*/false,
1955                               /*Delegating=*/false,
1956                               Ptr, ElementType);
1957   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1958     switch (Lifetime) {
1959     case Qualifiers::OCL_None:
1960     case Qualifiers::OCL_ExplicitNone:
1961     case Qualifiers::OCL_Autoreleasing:
1962       break;
1963 
1964     case Qualifiers::OCL_Strong:
1965       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1966       break;
1967 
1968     case Qualifiers::OCL_Weak:
1969       CGF.EmitARCDestroyWeak(Ptr);
1970       break;
1971     }
1972   }
1973 
1974   // When optimizing for size, call 'operator delete' unconditionally.
1975   if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
1976     CGF.EmitBlock(UnconditionalDeleteBlock);
1977     CGF.PopCleanupBlock();
1978     return true;
1979   }
1980 
1981   CGF.PopCleanupBlock();
1982   return false;
1983 }
1984 
1985 namespace {
1986   /// Calls the given 'operator delete' on an array of objects.
1987   struct CallArrayDelete final : EHScopeStack::Cleanup {
1988     llvm::Value *Ptr;
1989     const FunctionDecl *OperatorDelete;
1990     llvm::Value *NumElements;
1991     QualType ElementType;
1992     CharUnits CookieSize;
1993 
1994     CallArrayDelete(llvm::Value *Ptr,
1995                     const FunctionDecl *OperatorDelete,
1996                     llvm::Value *NumElements,
1997                     QualType ElementType,
1998                     CharUnits CookieSize)
1999       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
2000         ElementType(ElementType), CookieSize(CookieSize) {}
2001 
2002     void Emit(CodeGenFunction &CGF, Flags flags) override {
2003       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
2004                          CookieSize);
2005     }
2006   };
2007 }
2008 
2009 /// Emit the code for deleting an array of objects.
2010 static void EmitArrayDelete(CodeGenFunction &CGF,
2011                             const CXXDeleteExpr *E,
2012                             Address deletedPtr,
2013                             QualType elementType) {
2014   llvm::Value *numElements = nullptr;
2015   llvm::Value *allocatedPtr = nullptr;
2016   CharUnits cookieSize;
2017   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
2018                                       numElements, allocatedPtr, cookieSize);
2019 
2020   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
2021 
2022   // Make sure that we call delete even if one of the dtors throws.
2023   const FunctionDecl *operatorDelete = E->getOperatorDelete();
2024   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
2025                                            allocatedPtr, operatorDelete,
2026                                            numElements, elementType,
2027                                            cookieSize);
2028 
2029   // Destroy the elements.
2030   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2031     assert(numElements && "no element count for a type with a destructor!");
2032 
2033     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2034     CharUnits elementAlign =
2035       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2036 
2037     llvm::Value *arrayBegin = deletedPtr.getPointer();
2038     llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2039       deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
2040 
2041     // Note that it is legal to allocate a zero-length array, and we
2042     // can never fold the check away because the length should always
2043     // come from a cookie.
2044     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
2045                          CGF.getDestroyer(dtorKind),
2046                          /*checkZeroLength*/ true,
2047                          CGF.needsEHCleanup(dtorKind));
2048   }
2049 
2050   // Pop the cleanup block.
2051   CGF.PopCleanupBlock();
2052 }
2053 
2054 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
2055   const Expr *Arg = E->getArgument();
2056   Address Ptr = EmitPointerWithAlignment(Arg);
2057 
2058   // Null check the pointer.
2059   //
2060   // We could avoid this null check if we can determine that the object
2061   // destruction is trivial and doesn't require an array cookie; we can
2062   // unconditionally perform the operator delete call in that case. For now, we
2063   // assume that deleted pointers are null rarely enough that it's better to
2064   // keep the branch. This might be worth revisiting for a -O0 code size win.
2065   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2066   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2067 
2068   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
2069 
2070   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2071   EmitBlock(DeleteNotNull);
2072 
2073   QualType DeleteTy = E->getDestroyedType();
2074 
2075   // A destroying operator delete overrides the entire operation of the
2076   // delete expression.
2077   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2078     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2079     EmitBlock(DeleteEnd);
2080     return;
2081   }
2082 
2083   // We might be deleting a pointer to array.  If so, GEP down to the
2084   // first non-array element.
2085   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2086   if (DeleteTy->isConstantArrayType()) {
2087     llvm::Value *Zero = Builder.getInt32(0);
2088     SmallVector<llvm::Value*,8> GEP;
2089 
2090     GEP.push_back(Zero); // point at the outermost array
2091 
2092     // For each layer of array type we're pointing at:
2093     while (const ConstantArrayType *Arr
2094              = getContext().getAsConstantArrayType(DeleteTy)) {
2095       // 1. Unpeel the array type.
2096       DeleteTy = Arr->getElementType();
2097 
2098       // 2. GEP to the first element of the array.
2099       GEP.push_back(Zero);
2100     }
2101 
2102     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(),
2103                                             Ptr.getPointer(), GEP, "del.first"),
2104                   Ptr.getAlignment());
2105   }
2106 
2107   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2108 
2109   if (E->isArrayForm()) {
2110     EmitArrayDelete(*this, E, Ptr, DeleteTy);
2111     EmitBlock(DeleteEnd);
2112   } else {
2113     if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
2114       EmitBlock(DeleteEnd);
2115   }
2116 }
2117 
2118 static bool isGLValueFromPointerDeref(const Expr *E) {
2119   E = E->IgnoreParens();
2120 
2121   if (const auto *CE = dyn_cast<CastExpr>(E)) {
2122     if (!CE->getSubExpr()->isGLValue())
2123       return false;
2124     return isGLValueFromPointerDeref(CE->getSubExpr());
2125   }
2126 
2127   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2128     return isGLValueFromPointerDeref(OVE->getSourceExpr());
2129 
2130   if (const auto *BO = dyn_cast<BinaryOperator>(E))
2131     if (BO->getOpcode() == BO_Comma)
2132       return isGLValueFromPointerDeref(BO->getRHS());
2133 
2134   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2135     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2136            isGLValueFromPointerDeref(ACO->getFalseExpr());
2137 
2138   // C++11 [expr.sub]p1:
2139   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2140   if (isa<ArraySubscriptExpr>(E))
2141     return true;
2142 
2143   if (const auto *UO = dyn_cast<UnaryOperator>(E))
2144     if (UO->getOpcode() == UO_Deref)
2145       return true;
2146 
2147   return false;
2148 }
2149 
2150 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2151                                          llvm::Type *StdTypeInfoPtrTy) {
2152   // Get the vtable pointer.
2153   Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
2154 
2155   QualType SrcRecordTy = E->getType();
2156 
2157   // C++ [class.cdtor]p4:
2158   //   If the operand of typeid refers to the object under construction or
2159   //   destruction and the static type of the operand is neither the constructor
2160   //   or destructor’s class nor one of its bases, the behavior is undefined.
2161   CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2162                     ThisPtr.getPointer(), SrcRecordTy);
2163 
2164   // C++ [expr.typeid]p2:
2165   //   If the glvalue expression is obtained by applying the unary * operator to
2166   //   a pointer and the pointer is a null pointer value, the typeid expression
2167   //   throws the std::bad_typeid exception.
2168   //
2169   // However, this paragraph's intent is not clear.  We choose a very generous
2170   // interpretation which implores us to consider comma operators, conditional
2171   // operators, parentheses and other such constructs.
2172   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2173           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2174     llvm::BasicBlock *BadTypeidBlock =
2175         CGF.createBasicBlock("typeid.bad_typeid");
2176     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2177 
2178     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2179     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2180 
2181     CGF.EmitBlock(BadTypeidBlock);
2182     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2183     CGF.EmitBlock(EndBlock);
2184   }
2185 
2186   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2187                                         StdTypeInfoPtrTy);
2188 }
2189 
2190 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2191   llvm::Type *StdTypeInfoPtrTy =
2192     ConvertType(E->getType())->getPointerTo();
2193 
2194   if (E->isTypeOperand()) {
2195     llvm::Constant *TypeInfo =
2196         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2197     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2198   }
2199 
2200   // C++ [expr.typeid]p2:
2201   //   When typeid is applied to a glvalue expression whose type is a
2202   //   polymorphic class type, the result refers to a std::type_info object
2203   //   representing the type of the most derived object (that is, the dynamic
2204   //   type) to which the glvalue refers.
2205   // If the operand is already most derived object, no need to look up vtable.
2206   if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
2207     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2208                                 StdTypeInfoPtrTy);
2209 
2210   QualType OperandTy = E->getExprOperand()->getType();
2211   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2212                                StdTypeInfoPtrTy);
2213 }
2214 
2215 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2216                                           QualType DestTy) {
2217   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2218   if (DestTy->isPointerType())
2219     return llvm::Constant::getNullValue(DestLTy);
2220 
2221   /// C++ [expr.dynamic.cast]p9:
2222   ///   A failed cast to reference type throws std::bad_cast
2223   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2224     return nullptr;
2225 
2226   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2227   return llvm::UndefValue::get(DestLTy);
2228 }
2229 
2230 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2231                                               const CXXDynamicCastExpr *DCE) {
2232   CGM.EmitExplicitCastExprType(DCE, this);
2233   QualType DestTy = DCE->getTypeAsWritten();
2234 
2235   QualType SrcTy = DCE->getSubExpr()->getType();
2236 
2237   // C++ [expr.dynamic.cast]p7:
2238   //   If T is "pointer to cv void," then the result is a pointer to the most
2239   //   derived object pointed to by v.
2240   const PointerType *DestPTy = DestTy->getAs<PointerType>();
2241 
2242   bool isDynamicCastToVoid;
2243   QualType SrcRecordTy;
2244   QualType DestRecordTy;
2245   if (DestPTy) {
2246     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2247     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2248     DestRecordTy = DestPTy->getPointeeType();
2249   } else {
2250     isDynamicCastToVoid = false;
2251     SrcRecordTy = SrcTy;
2252     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2253   }
2254 
2255   // C++ [class.cdtor]p5:
2256   //   If the operand of the dynamic_cast refers to the object under
2257   //   construction or destruction and the static type of the operand is not a
2258   //   pointer to or object of the constructor or destructor’s own class or one
2259   //   of its bases, the dynamic_cast results in undefined behavior.
2260   EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2261                 SrcRecordTy);
2262 
2263   if (DCE->isAlwaysNull())
2264     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2265       return T;
2266 
2267   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2268 
2269   // C++ [expr.dynamic.cast]p4:
2270   //   If the value of v is a null pointer value in the pointer case, the result
2271   //   is the null pointer value of type T.
2272   bool ShouldNullCheckSrcValue =
2273       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2274                                                          SrcRecordTy);
2275 
2276   llvm::BasicBlock *CastNull = nullptr;
2277   llvm::BasicBlock *CastNotNull = nullptr;
2278   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2279 
2280   if (ShouldNullCheckSrcValue) {
2281     CastNull = createBasicBlock("dynamic_cast.null");
2282     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2283 
2284     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2285     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2286     EmitBlock(CastNotNull);
2287   }
2288 
2289   llvm::Value *Value;
2290   if (isDynamicCastToVoid) {
2291     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2292                                                   DestTy);
2293   } else {
2294     assert(DestRecordTy->isRecordType() &&
2295            "destination type must be a record type!");
2296     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2297                                                 DestTy, DestRecordTy, CastEnd);
2298     CastNotNull = Builder.GetInsertBlock();
2299   }
2300 
2301   if (ShouldNullCheckSrcValue) {
2302     EmitBranch(CastEnd);
2303 
2304     EmitBlock(CastNull);
2305     EmitBranch(CastEnd);
2306   }
2307 
2308   EmitBlock(CastEnd);
2309 
2310   if (ShouldNullCheckSrcValue) {
2311     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2312     PHI->addIncoming(Value, CastNotNull);
2313     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2314 
2315     Value = PHI;
2316   }
2317 
2318   return Value;
2319 }
2320