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