15b955920c1d8f2cd35aae3c85b656578286a8bc1Anders Carlsson//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
216d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//
316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//                     The LLVM Compiler Infrastructure
416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//
516d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson// This file is distributed under the University of Illinois Open Source
616d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson// License. See LICENSE.TXT for details.
716d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//
816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//===----------------------------------------------------------------------===//
916d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//
1016d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson// This contains code dealing with code generation of C++ expressions
1116d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//
1216d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson//===----------------------------------------------------------------------===//
1316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson#include "CodeGenFunction.h"
156c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne#include "CGCUDARuntime.h"
164c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "CGCXXABI.h"
17c69e1cf04323f2e786d40e8a5ba84e77ee1c6827Devang Patel#include "CGDebugInfo.h"
1855fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CGObjCRuntime.h"
198b54999a831bb195c08541ca995ef0505c96193fMark Lacey#include "clang/CodeGen/CGFunctionInfo.h"
2055fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
21651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines#include "llvm/IR/CallSite.h"
223b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Intrinsics.h"
23ad3692bbe1874abafae1757a2b9d3bfa2249dc43Anders Carlsson
2416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlssonusing namespace clang;
2516d81b8db39593b5f1a38b077757272a09c12da8Anders Carlssonusing namespace CodeGen;
2616d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
273b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonRValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
284def70d3040e73707c738f7c366737a986135edfRichard Smith                                          SourceLocation CallLoc,
293b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                          llvm::Value *Callee,
303b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                          ReturnValueSlot ReturnValue,
313b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                          llvm::Value *This,
3259660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov                                          llvm::Value *ImplicitParam,
3359660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov                                          QualType ImplicitParamTy,
343b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                          CallExpr::const_arg_iterator ArgBeg,
353b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                          CallExpr::const_arg_iterator ArgEnd) {
363b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  assert(MD->isInstance() &&
373b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson         "Trying to emit a member call expr on a static method!");
383b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
392c9f87ca5cccbfdaad82762368af5b2323320653Richard Smith  // C++11 [class.mfct.non-static]p2:
402c9f87ca5cccbfdaad82762368af5b2323320653Richard Smith  //   If a non-static member function of a class X is called for an object that
412c9f87ca5cccbfdaad82762368af5b2323320653Richard Smith  //   is not of type X, or of a type derived from X, the behavior is undefined.
428e1cee6f23e2552b96b81e5ef419ab3f69c5b5c2Richard Smith  EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
438e1cee6f23e2552b96b81e5ef419ab3f69c5b5c2Richard Smith                                            : TCK_MemberCall,
448e1cee6f23e2552b96b81e5ef419ab3f69c5b5c2Richard Smith                CallLoc, This, getContext().getRecordType(MD->getParent()));
452c9f87ca5cccbfdaad82762368af5b2323320653Richard Smith
463b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  CallArgList Args;
473b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
483b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // Push the this ptr.
4904c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman  Args.add(RValue::get(This), MD->getThisType(getContext()));
503b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
5159660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov  // If there is an implicit parameter (e.g. VTT), emit it.
5259660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov  if (ImplicitParam) {
5359660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov    Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
54c997d4278d329e18891aac9698fb991b2d4622ebAnders Carlsson  }
55de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall
56de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
58c997d4278d329e18891aac9698fb991b2d4622ebAnders Carlsson
59de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  // And the rest of the call args.
603b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
613b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
620f3d0970dcdf6cf17550b86838dff12813968dbcJohn McCall  return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
63264ba48dc98f3f843935a485d5b086f7e0fdc4f1Rafael Espindola                  Callee, ReturnValue, Args, MD);
643b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson}
653b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
66ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindolastatic CXXRecordDecl *getCXXRecord(const Expr *E) {
67ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  QualType T = E->getType();
68ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  if (const PointerType *PTy = T->getAs<PointerType>())
69ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    T = PTy->getPointeeType();
70ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  const RecordType *Ty = T->castAs<RecordType>();
71ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  return cast<CXXRecordDecl>(Ty->getDecl());
72ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola}
73ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola
74dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet// Note: This function also emit constructor calls to support a MSVC
75dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet// extensions allowing explicit constructor function call.
763b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonRValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
773b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                              ReturnValueSlot ReturnValue) {
78379b5155b4566f63679e1da6b0ceb5fdfa2aec6dJohn McCall  const Expr *callee = CE->getCallee()->IgnoreParens();
79379b5155b4566f63679e1da6b0ceb5fdfa2aec6dJohn McCall
80379b5155b4566f63679e1da6b0ceb5fdfa2aec6dJohn McCall  if (isa<BinaryOperator>(callee))
813b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
82379b5155b4566f63679e1da6b0ceb5fdfa2aec6dJohn McCall
83379b5155b4566f63679e1da6b0ceb5fdfa2aec6dJohn McCall  const MemberExpr *ME = cast<MemberExpr>(callee);
843b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
853b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
863b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  if (MD->isStatic()) {
873b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    // The method is static, emit it as we would a regular call.
883b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
893b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    return EmitCall(getContext().getPointerType(MD->getType()), Callee,
90b914e87377fd4d7642f544000a79f8648c6f06c9Peter Collingbourne                    CE->getLocStart(), ReturnValue, CE->arg_begin(),
91b914e87377fd4d7642f544000a79f8648c6f06c9Peter Collingbourne                    CE->arg_end());
923b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  }
933b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
94fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall  // Compute the object pointer.
95632fbaa22fbed7c090eb83775731bfff786c2198Rafael Espindola  const Expr *Base = ME->getBase();
96632fbaa22fbed7c090eb83775731bfff786c2198Rafael Espindola  bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
97632fbaa22fbed7c090eb83775731bfff786c2198Rafael Espindola
986bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  const CXXMethodDecl *DevirtualizedMethod = nullptr;
999581ed07dee5376002620a0cfb363c6b9e5bdd3eBenjamin Kramer  if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
100ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
101ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
102ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    assert(DevirtualizedMethod);
103ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
104ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    const Expr *Inner = Base->ignoreParenBaseCasts();
105ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    if (getCXXRecord(Inner) == DevirtualizedClass)
106ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // If the class of the Inner expression is where the dynamic method
107ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // is defined, build the this pointer from it.
108ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      Base = Inner;
109ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    else if (getCXXRecord(Base) != DevirtualizedClass) {
110ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // If the method is defined in a class that is not the best dynamic
111ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // one or the one of the full expression, we would have to build
112ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // a derived-to-base cast to compute the correct this pointer, but
113ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      // we don't have support for that yet, so do a virtual call.
1146bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      DevirtualizedMethod = nullptr;
115ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    }
11680bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    // If the return types are not the same, this might be a case where more
11780bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    // code needs to run to compensate for it. For example, the derived
11880bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    // method might return a type that inherits form from the return
11980bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    // type of MD and has a prefix.
12080bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    // For now we just avoid devirtualizing these covariant cases.
12180bc96e6aa9bc8331473385150cff5e0db305da6Rafael Espindola    if (DevirtualizedMethod &&
122651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        DevirtualizedMethod->getReturnType().getCanonicalType() !=
123651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines            MD->getReturnType().getCanonicalType())
1246bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      DevirtualizedMethod = nullptr;
125ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  }
126632fbaa22fbed7c090eb83775731bfff786c2198Rafael Espindola
1273b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  llvm::Value *This;
1283b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  if (ME->isArrow())
129ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    This = EmitScalarExpr(Base);
1300e800c9c20d1a658a91096c756c4a4a9e90264fcJohn McCall  else
131ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    This = EmitLValue(Base).getAddress();
132632fbaa22fbed7c090eb83775731bfff786c2198Rafael Espindola
1333b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
134fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall  if (MD->isTrivial()) {
1356bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
136dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    if (isa<CXXConstructorDecl>(MD) &&
137dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet        cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
1386bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return RValue::get(nullptr);
139dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet
14085ea7aa961deac1d754f610af8062ae3f8b4e2a5Sebastian Redl    if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
14185ea7aa961deac1d754f610af8062ae3f8b4e2a5Sebastian Redl      // We don't like to generate the trivial copy/move assignment operator
14285ea7aa961deac1d754f610af8062ae3f8b4e2a5Sebastian Redl      // when it isn't necessary; just produce the proper effect here.
143dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet      llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
1446cacae8bf9597b8124cd40aedc189c04484e1990Benjamin Kramer      EmitAggregateAssign(This, RHS, CE->getType());
145dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet      return RValue::get(This);
146dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    }
147dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet
148dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    if (isa<CXXConstructorDecl>(MD) &&
14985ea7aa961deac1d754f610af8062ae3f8b4e2a5Sebastian Redl        cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
15085ea7aa961deac1d754f610af8062ae3f8b4e2a5Sebastian Redl      // Trivial move and copy ctor are the same.
151dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet      llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
152dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet      EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
153dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet                                     CE->arg_begin(), CE->arg_end());
154dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet      return RValue::get(This);
155dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    }
156dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    llvm_unreachable("unknown trivial member function");
1573b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  }
1583b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
159fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall  // Compute the function type we're calling.
160465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman  const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
1616bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  const CGFunctionInfo *FInfo = nullptr;
162465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
163465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman    FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
164de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall                                                 Dtor_Complete);
165465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman  else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
166465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman    FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
167465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman                                                             Ctor_Complete);
168dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet  else
169465e89e094004a2ff53ba930ca0c4b41e51299baEli Friedman    FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
170fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall
171a4130baad9d10b7feabb7e003da53424e986d269Reid Kleckner  llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
172fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall
1733b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // C++ [class.virtual]p12:
1743b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  //   Explicit qualification with the scope operator (5.1) suppresses the
1753b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  //   virtual call mechanism.
1763b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  //
1773b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // We also don't emit a virtual call if the base expression has a record type
1783b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // because then we know what the type is.
179ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola  bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
1803258abc2bad74e8bb1799d124bc4113c7234fa42Stephen Lin  llvm::Value *Callee;
1813b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin
182fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
1833b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin    assert(CE->arg_begin() == CE->arg_end() &&
1843b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin           "Destructor shouldn't have explicit parameters");
1853b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin    assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
186fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall    if (UseVirtualCall) {
1873b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin      CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
1883b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin                                                CE->getExprLoc(), This);
1893b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    } else {
1907edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith      if (getLangOpts().AppleKext &&
191ccd5259d33cbbdd6f5fbf7ccab4cb4a2702309eaFariborz Jahanian          MD->isVirtual() &&
192ccd5259d33cbbdd6f5fbf7ccab4cb4a2702309eaFariborz Jahanian          ME->hasQualifier())
193771c678c04f5f685b4f188ec6c2fd88ad0f7457fFariborz Jahanian        Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
194ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      else if (!DevirtualizedMethod)
195a4130baad9d10b7feabb7e003da53424e986d269Reid Kleckner        Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
1960b4fe503ef00d9f8ea330850d3e3b303e9c7c876Rafael Espindola      else {
197ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola        const CXXDestructorDecl *DDtor =
198ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola          cast<CXXDestructorDecl>(DevirtualizedMethod);
1990b4fe503ef00d9f8ea330850d3e3b303e9c7c876Rafael Espindola        Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
2000b4fe503ef00d9f8ea330850d3e3b303e9c7c876Rafael Espindola      }
2013b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin      EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
2026bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                        /*ImplicitParam=*/nullptr, QualType(), nullptr,nullptr);
2033b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    }
2046bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return RValue::get(nullptr);
2053b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin  }
2063b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin
2073b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
208dbee3411a22b0dbb03267f5445f7b796104991bbFrancois Pichet    Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
209fc4002872864e3c29c896000519ae989b6fdb7ddJohn McCall  } else if (UseVirtualCall) {
2108f189a9911a992a5c4118c3789485a85bd96e045Timur Iskhodzhanov    Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
2113b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  } else {
2127edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith    if (getLangOpts().AppleKext &&
213a50e33eb0ff7b73d44aebce88de3732583a7e960Fariborz Jahanian        MD->isVirtual() &&
2147ac0ff2a8791280102a557761dbb931deb21a1dcFariborz Jahanian        ME->hasQualifier())
215771c678c04f5f685b4f188ec6c2fd88ad0f7457fFariborz Jahanian      Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
216ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola    else if (!DevirtualizedMethod)
21712582bdc2e1fca260eb2437d87dab5302c37bab2Rafael Espindola      Callee = CGM.GetAddrOfFunction(MD, Ty);
2180b4fe503ef00d9f8ea330850d3e3b303e9c7c876Rafael Espindola    else {
219ea01d7661751e062bb670cc1a0bdfee5789cb96fRafael Espindola      Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
2200b4fe503ef00d9f8ea330850d3e3b303e9c7c876Rafael Espindola    }
2213b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  }
2223b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
223651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (MD->isVirtual()) {
224651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
225651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        *this, MD, This, UseVirtualCall);
226651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  }
2278f189a9911a992a5c4118c3789485a85bd96e045Timur Iskhodzhanov
2284def70d3040e73707c738f7c366737a986135edfRichard Smith  return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
2296bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                           /*ImplicitParam=*/nullptr, QualType(),
23059660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov                           CE->arg_begin(), CE->arg_end());
2313b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson}
2323b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2333b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonRValue
2343b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonCodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2353b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                              ReturnValueSlot ReturnValue) {
2363b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const BinaryOperator *BO =
2373b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson      cast<BinaryOperator>(E->getCallee()->IgnoreParens());
2383b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const Expr *BaseExpr = BO->getLHS();
2393b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const Expr *MemFnExpr = BO->getRHS();
2403b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2413b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const MemberPointerType *MPT =
242864c041e118155c2b1ce0ba36942a3da5a4a055eJohn McCall    MemFnExpr->getType()->castAs<MemberPointerType>();
24393d557bc1867b7d7b102f87290194b4be7932c92John McCall
2443b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const FunctionProtoType *FPT =
245864c041e118155c2b1ce0ba36942a3da5a4a055eJohn McCall    MPT->getPointeeType()->castAs<FunctionProtoType>();
2463b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const CXXRecordDecl *RD =
2473b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
2483b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2493b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // Get the member function pointer.
250d608cdb7c044365cf4e8764ade1e11e99c176078John McCall  llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
2513b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2523b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // Emit the 'this' pointer.
2533b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  llvm::Value *This;
2543b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2552de56d1d0c3a504ad1529de2677628bdfbb95cd4John McCall  if (BO->getOpcode() == BO_PtrMemI)
2563b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    This = EmitScalarExpr(BaseExpr);
2573b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  else
2583b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    This = EmitLValue(BaseExpr).getAddress();
2593b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2604def70d3040e73707c738f7c366737a986135edfRichard Smith  EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
2614def70d3040e73707c738f7c366737a986135edfRichard Smith                QualType(MPT->getClass(), 0));
2622c9f87ca5cccbfdaad82762368af5b2323320653Richard Smith
26393d557bc1867b7d7b102f87290194b4be7932c92John McCall  // Ask the ABI to load the callee.  Note that This is modified.
26493d557bc1867b7d7b102f87290194b4be7932c92John McCall  llvm::Value *Callee =
265651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
2663b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2673b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  CallArgList Args;
2683b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2693b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  QualType ThisType =
2703b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    getContext().getPointerType(getContext().getTagDeclType(RD));
2713b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2723b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // Push the this ptr.
27304c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman  Args.add(RValue::get(This), ThisType);
2740f3d0970dcdf6cf17550b86838dff12813968dbcJohn McCall
2750f3d0970dcdf6cf17550b86838dff12813968dbcJohn McCall  RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
2763b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2773b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  // And the rest of the call args
2783b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
2795d4a7559df106959dd721744c8971547f0f09097Nick Lewycky  return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
2805d4a7559df106959dd721744c8971547f0f09097Nick Lewycky                  Callee, ReturnValue, Args);
2813b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson}
2823b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
2833b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonRValue
2843b5ad2283c999f6edf7d42332a655447b7386b2eAnders CarlssonCodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2853b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                               const CXXMethodDecl *MD,
2863b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                                               ReturnValueSlot ReturnValue) {
2873b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  assert(MD->isInstance() &&
2883b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson         "Trying to emit a member call expr on a static method!");
2890e800c9c20d1a658a91096c756c4a4a9e90264fcJohn McCall  LValue LV = EmitLValue(E->getArg(0));
2900e800c9c20d1a658a91096c756c4a4a9e90264fcJohn McCall  llvm::Value *This = LV.getAddress();
2910e800c9c20d1a658a91096c756c4a4a9e90264fcJohn McCall
292b2b5658a8e4ad566303ec98caceaa3485e7635f7Douglas Gregor  if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
293b2b5658a8e4ad566303ec98caceaa3485e7635f7Douglas Gregor      MD->isTrivial()) {
294b2b5658a8e4ad566303ec98caceaa3485e7635f7Douglas Gregor    llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
295b2b5658a8e4ad566303ec98caceaa3485e7635f7Douglas Gregor    QualType Ty = E->getType();
2966cacae8bf9597b8124cd40aedc189c04484e1990Benjamin Kramer    EmitAggregateAssign(This, Src, Ty);
297b2b5658a8e4ad566303ec98caceaa3485e7635f7Douglas Gregor    return RValue::get(This);
2983b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  }
2993b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
300a2447e0d1e28669cd637204a871f15b1215277fdAnders Carlsson  llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
3014def70d3040e73707c738f7c366737a986135edfRichard Smith  return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
3026bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                           /*ImplicitParam=*/nullptr, QualType(),
30359660c21178b6af518bd4b564e032d5c9cc218cbTimur Iskhodzhanov                           E->arg_begin() + 1, E->arg_end());
3043b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson}
3053b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
3066c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter CollingbourneRValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3076c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne                                               ReturnValueSlot ReturnValue) {
3086c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
3096c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
3106c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
3112ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedmanstatic void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
3122ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                                            llvm::Value *DestPtr,
3132ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                                            const CXXRecordDecl *Base) {
3142ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  if (Base->isEmpty())
3152ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    return;
3162ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3172ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
3182ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3192ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
3202ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  CharUnits Size = Layout.getNonVirtualSize();
321651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  CharUnits Align = Layout.getNonVirtualAlignment();
3222ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3232ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  llvm::Value *SizeVal = CGF.CGM.getSize(Size);
3242ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3252ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // If the type contains a pointer to data member we can't memset it to zero.
3262ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // Instead, create a null constant and copy it to the destination.
3272ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // TODO: there are other patterns besides zero that we can usefully memset,
3282ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // like -1, which happens to be the pattern used by member-pointers.
3292ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // TODO: isZeroInitializable can be over-conservative in the case where a
3302ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // virtual base contains a member pointer.
3312ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
3322ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
3332ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3342ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    llvm::GlobalVariable *NullVariable =
3352ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman      new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
3362ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                               /*isConstant=*/true,
3372ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                               llvm::GlobalVariable::PrivateLinkage,
3382ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                               NullConstant, Twine());
3392ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    NullVariable->setAlignment(Align.getQuantity());
3402ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
3412ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3422ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    // Get and call the appropriate llvm.memcpy overload.
3432ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
3442ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    return;
3452ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  }
3462ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3472ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // Otherwise, just memset the whole thing to zero.  This is legal
3482ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // because in LLVM, all default initializers (other than the ones we just
3492ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  // handled above) are guaranteed to have a bit pattern of all zeros.
3502ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
3512ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman                           Align.getQuantity());
3522ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman}
3532ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman
3543b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlssonvoid
355558d2abc7f9fd6801cc7677200992313ae90b5d8John McCallCodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
356558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall                                      AggValueSlot Dest) {
357558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall  assert(!Dest.isIgnored() && "Must have a destination!");
3583b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  const CXXConstructorDecl *CD = E->getConstructor();
359759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor
360759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor  // If we require zero initialization before (or instead of) calling the
361759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor  // constructor, as can be the case with a non-user-provided default
362657baf19ca8a48a926bd3bc148b6ad1b17e53199Argyrios Kyrtzidis  // constructor, emit the zero initialization now, unless destination is
363657baf19ca8a48a926bd3bc148b6ad1b17e53199Argyrios Kyrtzidis  // already zeroed.
3642ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
3652ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    switch (E->getConstructionKind()) {
3662ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    case CXXConstructExpr::CK_Delegating:
3672ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    case CXXConstructExpr::CK_Complete:
3682ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman      EmitNullInitialization(Dest.getAddr(), E->getType());
3692ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman      break;
3702ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    case CXXConstructExpr::CK_VirtualBase:
3712ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    case CXXConstructExpr::CK_NonVirtualBase:
3722ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman      EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
3732ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman      break;
3742ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman    }
3752ed7cb649aa709b875c519f4a980a1e2b5712370Eli Friedman  }
376759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor
377759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor  // If this is a call to a trivial default constructor, do nothing.
378759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor  if (CD->isTrivial() && CD->isDefaultConstructor())
379759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor    return;
380759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor
381fc1e6c79bbfe0e9a58bb792996d51f42e36e3d6aJohn McCall  // Elide the constructor if we're constructing from a temporary.
382fc1e6c79bbfe0e9a58bb792996d51f42e36e3d6aJohn McCall  // The temporary check is required because Sema sets this on NRVO
383fc1e6c79bbfe0e9a58bb792996d51f42e36e3d6aJohn McCall  // returns.
3847edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith  if (getLangOpts().ElideConstructors && E->isElidable()) {
385fc1e6c79bbfe0e9a58bb792996d51f42e36e3d6aJohn McCall    assert(getContext().hasSameUnqualifiedType(E->getType(),
386fc1e6c79bbfe0e9a58bb792996d51f42e36e3d6aJohn McCall                                               E->getArg(0)->getType()));
387558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall    if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall      EmitAggExpr(E->getArg(0), Dest);
3893c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor      return;
3903c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor    }
3913b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson  }
392759e41baf6a95c3a265970b6bf1c97c233fd28b0Douglas Gregor
393c3c0766277cd64bf117450a1519c9cf762d994d4John McCall  if (const ConstantArrayType *arrayType
394c3c0766277cd64bf117450a1519c9cf762d994d4John McCall        = getContext().getAsConstantArrayType(E->getType())) {
395c3c0766277cd64bf117450a1519c9cf762d994d4John McCall    EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
3963b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                               E->arg_begin(), E->arg_end());
397c3c0766277cd64bf117450a1519c9cf762d994d4John McCall  } else {
3986bd2f6ad857949d4dfb6e75e0760c61950b917cfCameron Esfahani    CXXCtorType Type = Ctor_Complete;
399d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt    bool ForVirtualBase = false;
400378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor    bool Delegating = false;
401378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor
402d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt    switch (E->getConstructionKind()) {
403d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt     case CXXConstructExpr::CK_Delegating:
404059ce0d92eb5a7da900ae735dc0a2ea3d64f4b0bSean Hunt      // We should be emitting a constructor; GlobalDecl will assert this
405059ce0d92eb5a7da900ae735dc0a2ea3d64f4b0bSean Hunt      Type = CurGD.getCtorType();
406378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor      Delegating = true;
407d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      break;
408059ce0d92eb5a7da900ae735dc0a2ea3d64f4b0bSean Hunt
409d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt     case CXXConstructExpr::CK_Complete:
410d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      Type = Ctor_Complete;
411d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      break;
412d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt
413d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt     case CXXConstructExpr::CK_VirtualBase:
414d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      ForVirtualBase = true;
415d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      // fall-through
416d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt
417d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt     case CXXConstructExpr::CK_NonVirtualBase:
418d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt      Type = Ctor_Base;
419d49bd5515b89bedc57c3d1d3be457e4340dbdb1dSean Hunt    }
420155ed4a23366f4514befb1c9f5f89d16f8b8b6dbAnders Carlsson
4213b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson    // Call the constructor.
422378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor    EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
4233b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson                           E->arg_begin(), E->arg_end());
424155ed4a23366f4514befb1c9f5f89d16f8b8b6dbAnders Carlsson  }
4253b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson}
4263b5ad2283c999f6edf7d42332a655447b7386b2eAnders Carlsson
42734999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanianvoid
42834999876e215b22febc240b1a6dc054215d12f9cFariborz JahanianCodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
42934999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian                                            llvm::Value *Src,
430830937bc1100fba7682f7c32c40512085870f50cFariborz Jahanian                                            const Expr *Exp) {
4314765fa05b5652fcc4356371c2f481d0ea9a1b007John McCall  if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
43234999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian    Exp = E->getSubExpr();
43334999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  assert(isa<CXXConstructExpr>(Exp) &&
43434999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian         "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
43534999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
43634999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  const CXXConstructorDecl *CD = E->getConstructor();
43734999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  RunCleanupsScope Scope(*this);
43834999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian
43934999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  // If we require zero initialization before (or instead of) calling the
44034999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  // constructor, as can be the case with a non-user-provided default
44134999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  // constructor, emit the zero initialization now.
44234999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  // FIXME. Do I still need this for a copy ctor synthesis?
44334999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian  if (E->requiresZeroInitialization())
44434999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian    EmitNullInitialization(Dest, E->getType());
44534999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian
446858a546d8fe73b07f2296313bef2e30445ea164bChandler Carruth  assert(!getContext().getAsConstantArrayType(E->getType())
447858a546d8fe73b07f2296313bef2e30445ea164bChandler Carruth         && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
4485d4a7559df106959dd721744c8971547f0f09097Nick Lewycky  EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
44934999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian}
45034999876e215b22febc240b1a6dc054215d12f9cFariborz Jahanian
4511e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallstatic CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4521e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                                        const CXXNewExpr *E) {
453871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  if (!E->isArray())
454caf647c33ad74621c352c21d6c50d149ba49e89dKen Dyck    return CharUnits::Zero();
455871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson
456b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  // No cookie is required if the operator new[] being used is the
457b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  // reserved placement operator new[].
458b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
4595172ed92b42f0bc6a022542a08f7b18af821bcb3John McCall    return CharUnits::Zero();
4605172ed92b42f0bc6a022542a08f7b18af821bcb3John McCall
4616ec278d1a354517e20f13a877481453ee7940c78John McCall  return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
462a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson}
463a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson
4647d16627081caede9691a6f46b796da4073ac14adJohn McCallstatic llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
4657d16627081caede9691a6f46b796da4073ac14adJohn McCall                                        const CXXNewExpr *e,
4669203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                                        unsigned minElements,
4677d16627081caede9691a6f46b796da4073ac14adJohn McCall                                        llvm::Value *&numElements,
4687d16627081caede9691a6f46b796da4073ac14adJohn McCall                                        llvm::Value *&sizeWithoutCookie) {
4697d16627081caede9691a6f46b796da4073ac14adJohn McCall  QualType type = e->getAllocatedType();
4707d16627081caede9691a6f46b796da4073ac14adJohn McCall
4717d16627081caede9691a6f46b796da4073ac14adJohn McCall  if (!e->isArray()) {
4727d16627081caede9691a6f46b796da4073ac14adJohn McCall    CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
4737d16627081caede9691a6f46b796da4073ac14adJohn McCall    sizeWithoutCookie
4747d16627081caede9691a6f46b796da4073ac14adJohn McCall      = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
4757d16627081caede9691a6f46b796da4073ac14adJohn McCall    return sizeWithoutCookie;
47659174c0633fb5cde41735cfbff5744bdf837e8d9Douglas Gregor  }
477a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson
4787d16627081caede9691a6f46b796da4073ac14adJohn McCall  // The width of size_t.
4797d16627081caede9691a6f46b796da4073ac14adJohn McCall  unsigned sizeWidth = CGF.SizeTy->getBitWidth();
4807d16627081caede9691a6f46b796da4073ac14adJohn McCall
4811e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // Figure out the cookie size.
4827d16627081caede9691a6f46b796da4073ac14adJohn McCall  llvm::APInt cookieSize(sizeWidth,
4837d16627081caede9691a6f46b796da4073ac14adJohn McCall                         CalculateCookiePadding(CGF, e).getQuantity());
4841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
485a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson  // Emit the array size expression.
486e7ab92e1d62f9c243bbd1f42f72a7b3c2666d33eArgyrios Kyrtzidis  // We multiply the size of all dimensions for NumElements.
487e7ab92e1d62f9c243bbd1f42f72a7b3c2666d33eArgyrios Kyrtzidis  // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
4887d16627081caede9691a6f46b796da4073ac14adJohn McCall  numElements = CGF.EmitScalarExpr(e->getArraySize());
4897d16627081caede9691a6f46b796da4073ac14adJohn McCall  assert(isa<llvm::IntegerType>(numElements->getType()));
4907d16627081caede9691a6f46b796da4073ac14adJohn McCall
4917d16627081caede9691a6f46b796da4073ac14adJohn McCall  // The number of elements can be have an arbitrary integer type;
4927d16627081caede9691a6f46b796da4073ac14adJohn McCall  // essentially, we need to multiply it by a constant factor, add a
4937d16627081caede9691a6f46b796da4073ac14adJohn McCall  // cookie size, and verify that the result is representable as a
4947d16627081caede9691a6f46b796da4073ac14adJohn McCall  // size_t.  That's just a gloss, though, and it's wrong in one
4957d16627081caede9691a6f46b796da4073ac14adJohn McCall  // important way: if the count is negative, it's an error even if
4967d16627081caede9691a6f46b796da4073ac14adJohn McCall  // the cookie size would bring the total size >= 0.
497575a1c9dc8dc5b4977194993e289f9eda7295c39Douglas Gregor  bool isSigned
498575a1c9dc8dc5b4977194993e289f9eda7295c39Douglas Gregor    = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
4992acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::IntegerType *numElementsType
5007d16627081caede9691a6f46b796da4073ac14adJohn McCall    = cast<llvm::IntegerType>(numElements->getType());
5017d16627081caede9691a6f46b796da4073ac14adJohn McCall  unsigned numElementsWidth = numElementsType->getBitWidth();
5027d16627081caede9691a6f46b796da4073ac14adJohn McCall
5037d16627081caede9691a6f46b796da4073ac14adJohn McCall  // Compute the constant factor.
5047d16627081caede9691a6f46b796da4073ac14adJohn McCall  llvm::APInt arraySizeMultiplier(sizeWidth, 1);
505e7ab92e1d62f9c243bbd1f42f72a7b3c2666d33eArgyrios Kyrtzidis  while (const ConstantArrayType *CAT
5067d16627081caede9691a6f46b796da4073ac14adJohn McCall             = CGF.getContext().getAsConstantArrayType(type)) {
5077d16627081caede9691a6f46b796da4073ac14adJohn McCall    type = CAT->getElementType();
5087d16627081caede9691a6f46b796da4073ac14adJohn McCall    arraySizeMultiplier *= CAT->getSize();
509e7ab92e1d62f9c243bbd1f42f72a7b3c2666d33eArgyrios Kyrtzidis  }
510e7ab92e1d62f9c243bbd1f42f72a7b3c2666d33eArgyrios Kyrtzidis
5117d16627081caede9691a6f46b796da4073ac14adJohn McCall  CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
5127d16627081caede9691a6f46b796da4073ac14adJohn McCall  llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
5137d16627081caede9691a6f46b796da4073ac14adJohn McCall  typeSizeMultiplier *= arraySizeMultiplier;
5147d16627081caede9691a6f46b796da4073ac14adJohn McCall
5157d16627081caede9691a6f46b796da4073ac14adJohn McCall  // This will be a size_t.
5167d16627081caede9691a6f46b796da4073ac14adJohn McCall  llvm::Value *size;
5176c552c1d5f47fbba00e6268d96a26ad026f2da2aChris Lattner
518806941eab5e1d62d7676e5cdc0e1d9e397ea78b4Chris Lattner  // If someone is doing 'new int[42]' there is no need to do a dynamic check.
519806941eab5e1d62d7676e5cdc0e1d9e397ea78b4Chris Lattner  // Don't bloat the -O0 code.
5207d16627081caede9691a6f46b796da4073ac14adJohn McCall  if (llvm::ConstantInt *numElementsC =
5217d16627081caede9691a6f46b796da4073ac14adJohn McCall        dyn_cast<llvm::ConstantInt>(numElements)) {
5227d16627081caede9691a6f46b796da4073ac14adJohn McCall    const llvm::APInt &count = numElementsC->getValue();
5237d16627081caede9691a6f46b796da4073ac14adJohn McCall
5247d16627081caede9691a6f46b796da4073ac14adJohn McCall    bool hasAnyOverflow = false;
5257d16627081caede9691a6f46b796da4073ac14adJohn McCall
5267d16627081caede9691a6f46b796da4073ac14adJohn McCall    // If 'count' was a negative number, it's an overflow.
5277d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (isSigned && count.isNegative())
5287d16627081caede9691a6f46b796da4073ac14adJohn McCall      hasAnyOverflow = true;
5297d16627081caede9691a6f46b796da4073ac14adJohn McCall
5307d16627081caede9691a6f46b796da4073ac14adJohn McCall    // We want to do all this arithmetic in size_t.  If numElements is
5317d16627081caede9691a6f46b796da4073ac14adJohn McCall    // wider than that, check whether it's already too big, and if so,
5327d16627081caede9691a6f46b796da4073ac14adJohn McCall    // overflow.
5337d16627081caede9691a6f46b796da4073ac14adJohn McCall    else if (numElementsWidth > sizeWidth &&
5347d16627081caede9691a6f46b796da4073ac14adJohn McCall             numElementsWidth - sizeWidth > count.countLeadingZeros())
5357d16627081caede9691a6f46b796da4073ac14adJohn McCall      hasAnyOverflow = true;
5367d16627081caede9691a6f46b796da4073ac14adJohn McCall
5377d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Okay, compute a count at the right width.
5387d16627081caede9691a6f46b796da4073ac14adJohn McCall    llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
5397d16627081caede9691a6f46b796da4073ac14adJohn McCall
5409203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // If there is a brace-initializer, we cannot allocate fewer elements than
5419203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // there are initializers. If we do, that's treated like an overflow.
5429203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    if (adjustedCount.ult(minElements))
5439203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      hasAnyOverflow = true;
5449203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
5457d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Scale numElements by that.  This might overflow, but we don't
5467d16627081caede9691a6f46b796da4073ac14adJohn McCall    // care because it only overflows if allocationSize does, too, and
5477d16627081caede9691a6f46b796da4073ac14adJohn McCall    // if that overflows then we shouldn't use this.
5487d16627081caede9691a6f46b796da4073ac14adJohn McCall    numElements = llvm::ConstantInt::get(CGF.SizeTy,
5497d16627081caede9691a6f46b796da4073ac14adJohn McCall                                         adjustedCount * arraySizeMultiplier);
5507d16627081caede9691a6f46b796da4073ac14adJohn McCall
5517d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Compute the size before cookie, and track whether it overflowed.
5527d16627081caede9691a6f46b796da4073ac14adJohn McCall    bool overflow;
5537d16627081caede9691a6f46b796da4073ac14adJohn McCall    llvm::APInt allocationSize
5547d16627081caede9691a6f46b796da4073ac14adJohn McCall      = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
5557d16627081caede9691a6f46b796da4073ac14adJohn McCall    hasAnyOverflow |= overflow;
5567d16627081caede9691a6f46b796da4073ac14adJohn McCall
5577d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Add in the cookie, and check whether it's overflowed.
5587d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (cookieSize != 0) {
5597d16627081caede9691a6f46b796da4073ac14adJohn McCall      // Save the current size without a cookie.  This shouldn't be
5607d16627081caede9691a6f46b796da4073ac14adJohn McCall      // used if there was overflow.
5617d16627081caede9691a6f46b796da4073ac14adJohn McCall      sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
5627d16627081caede9691a6f46b796da4073ac14adJohn McCall
5637d16627081caede9691a6f46b796da4073ac14adJohn McCall      allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
5647d16627081caede9691a6f46b796da4073ac14adJohn McCall      hasAnyOverflow |= overflow;
5651e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
5667d16627081caede9691a6f46b796da4073ac14adJohn McCall
5677d16627081caede9691a6f46b796da4073ac14adJohn McCall    // On overflow, produce a -1 so operator new will fail.
5687d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (hasAnyOverflow) {
5697d16627081caede9691a6f46b796da4073ac14adJohn McCall      size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
570806941eab5e1d62d7676e5cdc0e1d9e397ea78b4Chris Lattner    } else {
5717d16627081caede9691a6f46b796da4073ac14adJohn McCall      size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
572806941eab5e1d62d7676e5cdc0e1d9e397ea78b4Chris Lattner    }
5731e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
5747d16627081caede9691a6f46b796da4073ac14adJohn McCall  // Otherwise, we might need to use the overflow intrinsics.
5757d16627081caede9691a6f46b796da4073ac14adJohn McCall  } else {
5769203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // There are up to five conditions we need to test for:
5777d16627081caede9691a6f46b796da4073ac14adJohn McCall    // 1) if isSigned, we need to check whether numElements is negative;
5787d16627081caede9691a6f46b796da4073ac14adJohn McCall    // 2) if numElementsWidth > sizeWidth, we need to check whether
5797d16627081caede9691a6f46b796da4073ac14adJohn McCall    //   numElements is larger than something representable in size_t;
5809203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // 3) if minElements > 0, we need to check whether numElements is smaller
5819203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    //    than that.
5829203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // 4) we need to compute
5837d16627081caede9691a6f46b796da4073ac14adJohn McCall    //      sizeWithoutCookie := numElements * typeSizeMultiplier
5847d16627081caede9691a6f46b796da4073ac14adJohn McCall    //    and check whether it overflows; and
5859203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // 5) if we need a cookie, we need to compute
5867d16627081caede9691a6f46b796da4073ac14adJohn McCall    //      size := sizeWithoutCookie + cookieSize
5877d16627081caede9691a6f46b796da4073ac14adJohn McCall    //    and check whether it overflows.
5887d16627081caede9691a6f46b796da4073ac14adJohn McCall
5896bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    llvm::Value *hasOverflow = nullptr;
5907d16627081caede9691a6f46b796da4073ac14adJohn McCall
5917d16627081caede9691a6f46b796da4073ac14adJohn McCall    // If numElementsWidth > sizeWidth, then one way or another, we're
5927d16627081caede9691a6f46b796da4073ac14adJohn McCall    // going to have to do a comparison for (2), and this happens to
5937d16627081caede9691a6f46b796da4073ac14adJohn McCall    // take care of (1), too.
5947d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (numElementsWidth > sizeWidth) {
5957d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::APInt threshold(numElementsWidth, 1);
5967d16627081caede9691a6f46b796da4073ac14adJohn McCall      threshold <<= sizeWidth;
5977d16627081caede9691a6f46b796da4073ac14adJohn McCall
5987d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *thresholdV
5997d16627081caede9691a6f46b796da4073ac14adJohn McCall        = llvm::ConstantInt::get(numElementsType, threshold);
6007d16627081caede9691a6f46b796da4073ac14adJohn McCall
6017d16627081caede9691a6f46b796da4073ac14adJohn McCall      hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
6027d16627081caede9691a6f46b796da4073ac14adJohn McCall      numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
6037d16627081caede9691a6f46b796da4073ac14adJohn McCall
6047d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Otherwise, if we're signed, we want to sext up to size_t.
6057d16627081caede9691a6f46b796da4073ac14adJohn McCall    } else if (isSigned) {
6067d16627081caede9691a6f46b796da4073ac14adJohn McCall      if (numElementsWidth < sizeWidth)
6077d16627081caede9691a6f46b796da4073ac14adJohn McCall        numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
6087d16627081caede9691a6f46b796da4073ac14adJohn McCall
6097d16627081caede9691a6f46b796da4073ac14adJohn McCall      // If there's a non-1 type size multiplier, then we can do the
6107d16627081caede9691a6f46b796da4073ac14adJohn McCall      // signedness check at the same time as we do the multiply
6117d16627081caede9691a6f46b796da4073ac14adJohn McCall      // because a negative number times anything will cause an
6129203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      // unsigned overflow.  Otherwise, we have to do it here. But at least
6139203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      // in this case, we can subsume the >= minElements check.
6147d16627081caede9691a6f46b796da4073ac14adJohn McCall      if (typeSizeMultiplier == 1)
6157d16627081caede9691a6f46b796da4073ac14adJohn McCall        hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
6169203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                              llvm::ConstantInt::get(CGF.SizeTy, minElements));
6177d16627081caede9691a6f46b796da4073ac14adJohn McCall
6187d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Otherwise, zext up to size_t if necessary.
6197d16627081caede9691a6f46b796da4073ac14adJohn McCall    } else if (numElementsWidth < sizeWidth) {
6207d16627081caede9691a6f46b796da4073ac14adJohn McCall      numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
6217d16627081caede9691a6f46b796da4073ac14adJohn McCall    }
6221e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
6237d16627081caede9691a6f46b796da4073ac14adJohn McCall    assert(numElements->getType() == CGF.SizeTy);
6241e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
6259203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    if (minElements) {
6269203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      // Don't allow allocation of fewer elements than we have initializers.
6279203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      if (!hasOverflow) {
6289203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl        hasOverflow = CGF.Builder.CreateICmpULT(numElements,
6299203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                              llvm::ConstantInt::get(CGF.SizeTy, minElements));
6309203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      } else if (numElementsWidth > sizeWidth) {
6319203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl        // The other existing overflow subsumes this check.
6329203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl        // We do an unsigned comparison, since any signed value < -1 is
6339203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl        // taken care of either above or below.
6349203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl        hasOverflow = CGF.Builder.CreateOr(hasOverflow,
6359203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                          CGF.Builder.CreateICmpULT(numElements,
6369203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                              llvm::ConstantInt::get(CGF.SizeTy, minElements)));
6379203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      }
6389203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    }
6399203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
6407d16627081caede9691a6f46b796da4073ac14adJohn McCall    size = numElements;
6411e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
6427d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Multiply by the type size if necessary.  This multiplier
6437d16627081caede9691a6f46b796da4073ac14adJohn McCall    // includes all the factors for nested arrays.
6447d16627081caede9691a6f46b796da4073ac14adJohn McCall    //
6457d16627081caede9691a6f46b796da4073ac14adJohn McCall    // This step also causes numElements to be scaled up by the
6467d16627081caede9691a6f46b796da4073ac14adJohn McCall    // nested-array factor if necessary.  Overflow on this computation
6477d16627081caede9691a6f46b796da4073ac14adJohn McCall    // can be ignored because the result shouldn't be used if
6487d16627081caede9691a6f46b796da4073ac14adJohn McCall    // allocation fails.
6497d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (typeSizeMultiplier != 1) {
6507d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *umul_with_overflow
6518dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer        = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
6527d16627081caede9691a6f46b796da4073ac14adJohn McCall
6537d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *tsmV =
6547d16627081caede9691a6f46b796da4073ac14adJohn McCall        llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
6557d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *result =
6567d16627081caede9691a6f46b796da4073ac14adJohn McCall        CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
6577d16627081caede9691a6f46b796da4073ac14adJohn McCall
6587d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
6597d16627081caede9691a6f46b796da4073ac14adJohn McCall      if (hasOverflow)
6607d16627081caede9691a6f46b796da4073ac14adJohn McCall        hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
6617d16627081caede9691a6f46b796da4073ac14adJohn McCall      else
6627d16627081caede9691a6f46b796da4073ac14adJohn McCall        hasOverflow = overflowed;
6637d16627081caede9691a6f46b796da4073ac14adJohn McCall
6647d16627081caede9691a6f46b796da4073ac14adJohn McCall      size = CGF.Builder.CreateExtractValue(result, 0);
6657d16627081caede9691a6f46b796da4073ac14adJohn McCall
6667d16627081caede9691a6f46b796da4073ac14adJohn McCall      // Also scale up numElements by the array size multiplier.
6677d16627081caede9691a6f46b796da4073ac14adJohn McCall      if (arraySizeMultiplier != 1) {
6687d16627081caede9691a6f46b796da4073ac14adJohn McCall        // If the base element type size is 1, then we can re-use the
6697d16627081caede9691a6f46b796da4073ac14adJohn McCall        // multiply we just did.
6707d16627081caede9691a6f46b796da4073ac14adJohn McCall        if (typeSize.isOne()) {
6717d16627081caede9691a6f46b796da4073ac14adJohn McCall          assert(arraySizeMultiplier == typeSizeMultiplier);
6727d16627081caede9691a6f46b796da4073ac14adJohn McCall          numElements = size;
6737d16627081caede9691a6f46b796da4073ac14adJohn McCall
6747d16627081caede9691a6f46b796da4073ac14adJohn McCall        // Otherwise we need a separate multiply.
6757d16627081caede9691a6f46b796da4073ac14adJohn McCall        } else {
6767d16627081caede9691a6f46b796da4073ac14adJohn McCall          llvm::Value *asmV =
6777d16627081caede9691a6f46b796da4073ac14adJohn McCall            llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
6787d16627081caede9691a6f46b796da4073ac14adJohn McCall          numElements = CGF.Builder.CreateMul(numElements, asmV);
6797d16627081caede9691a6f46b796da4073ac14adJohn McCall        }
6807d16627081caede9691a6f46b796da4073ac14adJohn McCall      }
6817d16627081caede9691a6f46b796da4073ac14adJohn McCall    } else {
6827d16627081caede9691a6f46b796da4073ac14adJohn McCall      // numElements doesn't need to be scaled.
6837d16627081caede9691a6f46b796da4073ac14adJohn McCall      assert(arraySizeMultiplier == 1);
6841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
6857d16627081caede9691a6f46b796da4073ac14adJohn McCall
6867d16627081caede9691a6f46b796da4073ac14adJohn McCall    // Add in the cookie size if necessary.
6877d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (cookieSize != 0) {
6887d16627081caede9691a6f46b796da4073ac14adJohn McCall      sizeWithoutCookie = size;
6897d16627081caede9691a6f46b796da4073ac14adJohn McCall
6907d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *uadd_with_overflow
6918dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer        = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
6927d16627081caede9691a6f46b796da4073ac14adJohn McCall
6937d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
6947d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *result =
6957d16627081caede9691a6f46b796da4073ac14adJohn McCall        CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
6967d16627081caede9691a6f46b796da4073ac14adJohn McCall
6977d16627081caede9691a6f46b796da4073ac14adJohn McCall      llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
6987d16627081caede9691a6f46b796da4073ac14adJohn McCall      if (hasOverflow)
6997d16627081caede9691a6f46b796da4073ac14adJohn McCall        hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
7007d16627081caede9691a6f46b796da4073ac14adJohn McCall      else
7017d16627081caede9691a6f46b796da4073ac14adJohn McCall        hasOverflow = overflowed;
7021e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
7037d16627081caede9691a6f46b796da4073ac14adJohn McCall      size = CGF.Builder.CreateExtractValue(result, 0);
7041e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
7051e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
7067d16627081caede9691a6f46b796da4073ac14adJohn McCall    // If we had any possibility of dynamic overflow, make a select to
7077d16627081caede9691a6f46b796da4073ac14adJohn McCall    // overwrite 'size' with an all-ones value, which should cause
7087d16627081caede9691a6f46b796da4073ac14adJohn McCall    // operator new to throw.
7097d16627081caede9691a6f46b796da4073ac14adJohn McCall    if (hasOverflow)
7107d16627081caede9691a6f46b796da4073ac14adJohn McCall      size = CGF.Builder.CreateSelect(hasOverflow,
7117d16627081caede9691a6f46b796da4073ac14adJohn McCall                                 llvm::Constant::getAllOnesValue(CGF.SizeTy),
7127d16627081caede9691a6f46b796da4073ac14adJohn McCall                                      size);
713806941eab5e1d62d7676e5cdc0e1d9e397ea78b4Chris Lattner  }
7141e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
7157d16627081caede9691a6f46b796da4073ac14adJohn McCall  if (cookieSize == 0)
7167d16627081caede9691a6f46b796da4073ac14adJohn McCall    sizeWithoutCookie = size;
7171e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  else
7187d16627081caede9691a6f46b796da4073ac14adJohn McCall    assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
7191e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
7207d16627081caede9691a6f46b796da4073ac14adJohn McCall  return size;
721a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson}
722a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson
7239203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redlstatic void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
7249203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                                    QualType AllocType, llvm::Value *NewPtr) {
725b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling  // FIXME: Refactor with EmitExprAsInit.
726d7722d9d76a851e7897f4127626616d3b1b8e530Eli Friedman  CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
7279d232c884ea9872d6555df0fd7359699819bc1f1John McCall  switch (CGF.getEvaluationKind(AllocType)) {
7289d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Scalar:
7296bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
7306bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                                         Alignment),
731a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                       false);
7329d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
7339d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Complex:
7349d232c884ea9872d6555df0fd7359699819bc1f1John McCall    CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
7359d232c884ea9872d6555df0fd7359699819bc1f1John McCall                                                           Alignment),
7369d232c884ea9872d6555df0fd7359699819bc1f1John McCall                                  /*isInit*/ true);
7379d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
7389d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Aggregate: {
739558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall    AggValueSlot Slot
740f394078fde147dcf27e9b6a7965517388d64dcb6Eli Friedman      = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
7417c2349be2d11143a2e59a167fd43362a3bf4585eJohn McCall                              AggValueSlot::IsDestructed,
7424418439220a8f8e0b1deffdccce2354854c702f5John McCall                              AggValueSlot::DoesNotNeedGCBarriers,
743649b4a1a9b5e6f768ca0cb84bd97b00f51083e15Chad Rosier                              AggValueSlot::IsNotAliased);
744558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall    CGF.EmitAggExpr(Init, Slot);
7459d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
7469d232c884ea9872d6555df0fd7359699819bc1f1John McCall  }
747558d2abc7f9fd6801cc7677200992313ae90b5d8John McCall  }
7489d232c884ea9872d6555df0fd7359699819bc1f1John McCall  llvm_unreachable("bad evaluation kind");
749ef66872797e46ced3ffdb428e582bc7f00474f99Fariborz Jahanian}
750ef66872797e46ced3ffdb428e582bc7f00474f99Fariborz Jahanian
751ef66872797e46ced3ffdb428e582bc7f00474f99Fariborz Jahanianvoid
752ef8225444452a1486bd721f3285301fe84643b00Stephen HinesCodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
753ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                         QualType ElementType,
754ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                         llvm::Value *BeginPtr,
755ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                         llvm::Value *NumElements,
756ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                         llvm::Value *AllocSizeWithoutCookie) {
757ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // If we have a type with trivial initialization and no initializer,
758ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // there's nothing to do.
7592aed8b88613863f3c439cdfb205bdf8b608fb205Sebastian Redl  if (!E->hasInitializer())
760ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    return;
761197056726ed6412501130c2ef2ff69009772aa65John McCall
762ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::Value *CurPtr = BeginPtr;
763197056726ed6412501130c2ef2ff69009772aa65John McCall
764ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  unsigned InitListElements = 0;
7659203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
7669203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  const Expr *Init = E->getInitializer();
767ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::AllocaInst *EndOfInit = nullptr;
768ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  QualType::DestructionKind DtorKind = ElementType.isDestructedType();
769ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  EHScopeStack::stable_iterator Cleanup;
770ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::Instruction *CleanupDominator = nullptr;
771b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling
7729203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  // If the initializer is an initializer list, first do the explicit elements.
7739203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
774ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    InitListElements = ILE->getNumInits();
775577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier
776b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling    // If this is a multi-dimensional array new, we will initialize multiple
777b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling    // elements with each init list element.
778b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling    QualType AllocType = E->getAllocatedType();
779b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling    if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
780b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling            AllocType->getAsArrayTypeUnsafe())) {
781ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      unsigned AS = CurPtr->getType()->getPointerAddressSpace();
782b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling      llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
783ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
784ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      InitListElements *= getContext().getConstantArrayElementCount(CAT);
785b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling    }
786b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling
787ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Enter a partial-destruction Cleanup if necessary.
788ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (needsEHCleanup(DtorKind)) {
789ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // In principle we could tell the Cleanup where we are more
790577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // directly, but the control flow can get so varied here that it
791577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // would actually be quite complex.  Therefore we go through an
792577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // alloca.
793ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
794ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
795ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
796ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                       getDestroyer(DtorKind));
797ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      Cleanup = EHStack.stable_begin();
798577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier    }
799577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier
8009203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
801577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // Tell the cleanup that it needs to destroy up to this
802577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // element.  TODO: some of these stores can be trivially
803577fb5b2c15f7c187983a53e53f4f53b5d7aabb1Chad Rosier      // observed to be unnecessary.
804ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      if (EndOfInit)
805ef8225444452a1486bd721f3285301fe84643b00Stephen Hines        Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
806ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                            EndOfInit);
807ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // FIXME: If the last initializer is an incomplete initializer list for
808ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // an array, and we have an array filler, we can fold together the two
809ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // initialization loops.
810b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling      StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
811ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                              ILE->getInit(i)->getType(), CurPtr);
812ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
8139203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    }
8149203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
8159203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    // The remaining elements are filled with the array filler expression.
8169203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    Init = ILE->getArrayFiller();
817b66a0f46ebf715835fb643d06510cd822f946c17Bill Wendling
818ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Extract the initializer for the individual array elements by pulling
819ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // out the array filler from all the nested initializer lists. This avoids
820ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // generating a nested loop for the initialization.
821ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    while (Init && Init->getType()->isConstantArrayType()) {
822ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      auto *SubILE = dyn_cast<InitListExpr>(Init);
823ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      if (!SubILE)
824ef8225444452a1486bd721f3285301fe84643b00Stephen Hines        break;
825ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
826ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      Init = SubILE->getArrayFiller();
827ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    }
828ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
829ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Switch back to initializing one base element at a time.
830ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
8319203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  }
8329203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
833ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Attempt to perform zero-initialization using memset.
834ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  auto TryMemsetInitialization = [&]() -> bool {
835ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
836ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // we can initialize with a memset to -1.
837ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (!CGM.getTypes().isZeroInitializable(ElementType))
838ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      return false;
839ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
840ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Optimization: since zero initialization will just set the memory
841ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // to all zeroes, generate a single memset to do it in one shot.
842ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
843ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Subtract out the size of any elements we've already initialized.
844ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    auto *RemainingSize = AllocSizeWithoutCookie;
845ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (InitListElements) {
846ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // We know this can't overflow; we check this when doing the allocation.
847ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      auto *InitializedSize = llvm::ConstantInt::get(
848ef8225444452a1486bd721f3285301fe84643b00Stephen Hines          RemainingSize->getType(),
849ef8225444452a1486bd721f3285301fe84643b00Stephen Hines          getContext().getTypeSizeInChars(ElementType).getQuantity() *
850ef8225444452a1486bd721f3285301fe84643b00Stephen Hines              InitListElements);
851ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
852ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    }
853ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
854ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Create the memset.
855ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
856ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
857ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                         Alignment.getQuantity(), false);
858ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    return true;
859ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  };
8606bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
861ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // If all elements have already been initialized, skip any further
862ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // initialization.
863ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
864ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
865ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // If there was a Cleanup, deactivate it.
866ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (CleanupDominator)
867ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      DeactivateCleanupBlock(Cleanup, CleanupDominator);
8686bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return;
8696bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  }
8706bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
871ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  assert(Init && "have trailing elements to initialize but no initializer");
872ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
873ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // If this is a constructor call, try to optimize it out, and failing that
874ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // emit a single loop to initialize all remaining elements.
875ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
876ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CXXConstructorDecl *Ctor = CCE->getConstructor();
877ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (Ctor->isTrivial()) {
878ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // If new expression did not specify value-initialization, then there
879ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      // is no initialization.
880ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
881ef8225444452a1486bd721f3285301fe84643b00Stephen Hines        return;
882ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
883ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      if (TryMemsetInitialization())
884ef8225444452a1486bd721f3285301fe84643b00Stephen Hines        return;
885ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    }
886ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
887ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Store the new Cleanup position for irregular Cleanups.
888ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    //
889ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // FIXME: Share this cleanup with the constructor call emission rather than
890ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // having it create a cleanup of its own.
891ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
892ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
893ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Emit a constructor call loop to initialize the remaining elements.
894ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (InitListElements)
895ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      NumElements = Builder.CreateSub(
896ef8225444452a1486bd721f3285301fe84643b00Stephen Hines          NumElements,
897ef8225444452a1486bd721f3285301fe84643b00Stephen Hines          llvm::ConstantInt::get(NumElements->getType(), InitListElements));
898ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr,
899ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                               CCE->arg_begin(), CCE->arg_end(),
900ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                               CCE->requiresZeroInitialization());
901ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    return;
902ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  }
903ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
904ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // If this is value-initialization, we can usually use memset.
905ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  ImplicitValueInitExpr IVIE(ElementType);
906ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (isa<ImplicitValueInitExpr>(Init)) {
907ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (TryMemsetInitialization())
908ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      return;
909ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
910ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // Switch to an ImplicitValueInitExpr for the element type. This handles
911ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // only one case: multidimensional array new of pointers to members. In
912ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    // all other cases, we already have an initializer for the array element.
913ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Init = &IVIE;
914ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  }
915ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
916ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // At this point we should have found an initializer for the individual
917ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // elements of the array.
918ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
919ef8225444452a1486bd721f3285301fe84643b00Stephen Hines         "got wrong type of element to initialize");
920ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
921ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // If we have an empty initializer list, we can usually use memset.
922ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (auto *ILE = dyn_cast<InitListExpr>(Init))
923ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (ILE->getNumInits() == 0 && TryMemsetInitialization())
924ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      return;
925ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
926ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Create the loop blocks.
927ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
928ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
929ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
930ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
931ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Find the end of the array, hoisted out of the loop.
932ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::Value *EndPtr =
933ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
934197056726ed6412501130c2ef2ff69009772aa65John McCall
9359203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  // If the number of elements isn't constant, we have to now check if there is
9369203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  // anything left to initialize.
937ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (!ConstNum) {
938ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
939197056726ed6412501130c2ef2ff69009772aa65John McCall                                                "array.isempty");
940ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
941197056726ed6412501130c2ef2ff69009772aa65John McCall  }
942197056726ed6412501130c2ef2ff69009772aa65John McCall
943197056726ed6412501130c2ef2ff69009772aa65John McCall  // Enter the loop.
944ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  EmitBlock(LoopBB);
945197056726ed6412501130c2ef2ff69009772aa65John McCall
946197056726ed6412501130c2ef2ff69009772aa65John McCall  // Set up the current-element phi.
947ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::PHINode *CurPtrPhi =
948ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
949ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  CurPtrPhi->addIncoming(CurPtr, EntryBB);
950ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  CurPtr = CurPtrPhi;
951ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
952ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Store the new Cleanup position for irregular Cleanups.
953ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
954ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
955ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Enter a partial-destruction Cleanup if necessary.
956ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (!CleanupDominator && needsEHCleanup(DtorKind)) {
957ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
958ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                   getDestroyer(DtorKind));
959ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Cleanup = EHStack.stable_begin();
960ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CleanupDominator = Builder.CreateUnreachable();
961197056726ed6412501130c2ef2ff69009772aa65John McCall  }
962197056726ed6412501130c2ef2ff69009772aa65John McCall
963197056726ed6412501130c2ef2ff69009772aa65John McCall  // Emit the initializer into this element.
964ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
965197056726ed6412501130c2ef2ff69009772aa65John McCall
966ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Leave the Cleanup if we entered one.
967ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (CleanupDominator) {
968ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    DeactivateCleanupBlock(Cleanup, CleanupDominator);
969ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CleanupDominator->eraseFromParent();
9706f103ba42cb69d50005a977c5ea583984ab63fc4John McCall  }
971197056726ed6412501130c2ef2ff69009772aa65John McCall
972651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // Advance to the next element by adjusting the pointer type as necessary.
973ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::Value *NextPtr =
974ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
975ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
976197056726ed6412501130c2ef2ff69009772aa65John McCall  // Check whether we've gotten to the end of the array and, if so,
977197056726ed6412501130c2ef2ff69009772aa65John McCall  // exit the loop.
978ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
979ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
980ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
981197056726ed6412501130c2ef2ff69009772aa65John McCall
982ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  EmitBlock(ContBB);
983ef66872797e46ced3ffdb428e582bc7f00474f99Fariborz Jahanian}
984ef66872797e46ced3ffdb428e582bc7f00474f99Fariborz Jahanian
985a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlssonstatic void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
986197056726ed6412501130c2ef2ff69009772aa65John McCall                               QualType ElementType,
987a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson                               llvm::Value *NewPtr,
98859174c0633fb5cde41735cfbff5744bdf837e8d9Douglas Gregor                               llvm::Value *NumElements,
98959174c0633fb5cde41735cfbff5744bdf837e8d9Douglas Gregor                               llvm::Value *AllocSizeWithoutCookie) {
990ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (E->isArray())
991ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
992ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                AllocSizeWithoutCookie);
993ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  else if (const Expr *Init = E->getInitializer())
994ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
995a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson}
996a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson
997ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith/// Emit a call to an operator new or operator delete function, as implicitly
998ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith/// created by new-expressions and delete-expressions.
999ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smithstatic RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1000ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                                const FunctionDecl *Callee,
1001ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                                const FunctionProtoType *CalleeType,
1002ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                                const CallArgList &Args) {
1003ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  llvm::Instruction *CallOrInvoke;
1004060cb4a28c9d0cb15c7a9bd5de2164685629ad9cRichard Smith  llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
1005ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  RValue RV =
1006ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
1007060cb4a28c9d0cb15c7a9bd5de2164685629ad9cRichard Smith                   CalleeAddr, ReturnValueSlot(), Args,
1008ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                   Callee, &CallOrInvoke);
1009ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith
1010ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  /// C++1y [expr.new]p10:
1011ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  ///   [In a new-expression,] an implementation is allowed to omit a call
1012ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  ///   to a replaceable global allocation function.
1013ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  ///
1014ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  /// We model such elidable calls with the 'builtin' attribute.
101587017a781f9e2d70a0478abaae26ba486f6e717eRafael Espindola  llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
1016060cb4a28c9d0cb15c7a9bd5de2164685629ad9cRichard Smith  if (Callee->isReplaceableGlobalAllocationFunction() &&
101787017a781f9e2d70a0478abaae26ba486f6e717eRafael Espindola      Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1018ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith    // FIXME: Add addAttribute to CallSite.
1019ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith    if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1020ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1021ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                       llvm::Attribute::Builtin);
1022ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith    else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1023ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      II->addAttribute(llvm::AttributeSet::FunctionIndex,
1024ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith                       llvm::Attribute::Builtin);
1025ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith    else
1026ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      llvm_unreachable("unexpected kind of call instruction");
1027ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  }
1028ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith
1029ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  return RV;
1030ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith}
1031ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith
1032ef8225444452a1486bd721f3285301fe84643b00Stephen HinesRValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1033ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                                 const Expr *Arg,
1034ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                                 bool IsDelete) {
1035ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  CallArgList Args;
1036ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  const Stmt *ArgS = Arg;
1037ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  EmitCallArgs(Args, *Type->param_type_begin(),
1038ef8225444452a1486bd721f3285301fe84643b00Stephen Hines               ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1039ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // Find the allocation or deallocation function that we're calling.
1040ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  ASTContext &Ctx = getContext();
1041ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  DeclarationName Name = Ctx.DeclarationNames
1042ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1043ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1044ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1045ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1046ef8225444452a1486bd721f3285301fe84643b00Stephen Hines        return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1047ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  llvm_unreachable("predeclared global operator new/delete is missing");
1048ef8225444452a1486bd721f3285301fe84643b00Stephen Hines}
1049ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
10507d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCallnamespace {
10517d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  /// A cleanup to call the given 'operator delete' function upon
10527d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  /// abnormal exit from a new expression.
10537d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  class CallDeleteDuringNew : public EHScopeStack::Cleanup {
10547d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    size_t NumPlacementArgs;
10557d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    const FunctionDecl *OperatorDelete;
10567d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    llvm::Value *Ptr;
10577d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    llvm::Value *AllocSize;
10587d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10597d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
10607d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10617d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  public:
10627d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    static size_t getExtraSize(size_t NumPlacementArgs) {
10637d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      return NumPlacementArgs * sizeof(RValue);
10647d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    }
10657d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10667d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    CallDeleteDuringNew(size_t NumPlacementArgs,
10677d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall                        const FunctionDecl *OperatorDelete,
10687d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall                        llvm::Value *Ptr,
10697d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall                        llvm::Value *AllocSize)
10707d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
10717d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall        Ptr(Ptr), AllocSize(AllocSize) {}
10727d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10737d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    void setPlacementArg(unsigned I, RValue Arg) {
10747d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      assert(I < NumPlacementArgs && "index out of range");
10757d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      getPlacementArgs()[I] = Arg;
10767d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    }
10777d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
1078651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    void Emit(CodeGenFunction &CGF, Flags flags) override {
10797d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      const FunctionProtoType *FPT
10807d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall        = OperatorDelete->getType()->getAs<FunctionProtoType>();
1081651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1082651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines             (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
10837d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10847d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      CallArgList DeleteArgs;
10857d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10867d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      // The first argument is always a void*.
1087651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
108804c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman      DeleteArgs.add(RValue::get(Ptr), *AI++);
10897d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10907d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      // A member 'operator delete' can take an extra 'size_t' argument.
1091651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      if (FPT->getNumParams() == NumPlacementArgs + 2)
109204c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman        DeleteArgs.add(RValue::get(AllocSize), *AI++);
10937d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10947d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      // Pass the rest of the arguments, which must match exactly.
10957d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      for (unsigned I = 0; I != NumPlacementArgs; ++I)
109604c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman        DeleteArgs.add(getPlacementArgs()[I], *AI++);
10977d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
10987d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall      // Call 'operator delete'.
1099ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
11007d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall    }
11017d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  };
11023019c444c672938c57f5573840071ecd73425ee7John McCall
11033019c444c672938c57f5573840071ecd73425ee7John McCall  /// A cleanup to call the given 'operator delete' function upon
11043019c444c672938c57f5573840071ecd73425ee7John McCall  /// abnormal exit from a new expression when the new expression is
11053019c444c672938c57f5573840071ecd73425ee7John McCall  /// conditional.
11063019c444c672938c57f5573840071ecd73425ee7John McCall  class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
11073019c444c672938c57f5573840071ecd73425ee7John McCall    size_t NumPlacementArgs;
11083019c444c672938c57f5573840071ecd73425ee7John McCall    const FunctionDecl *OperatorDelete;
1109804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    DominatingValue<RValue>::saved_type Ptr;
1110804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    DominatingValue<RValue>::saved_type AllocSize;
11113019c444c672938c57f5573840071ecd73425ee7John McCall
1112804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    DominatingValue<RValue>::saved_type *getPlacementArgs() {
1113804b807ea918184d6de63bd745e1ff75a9bfc679John McCall      return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
11143019c444c672938c57f5573840071ecd73425ee7John McCall    }
11153019c444c672938c57f5573840071ecd73425ee7John McCall
11163019c444c672938c57f5573840071ecd73425ee7John McCall  public:
11173019c444c672938c57f5573840071ecd73425ee7John McCall    static size_t getExtraSize(size_t NumPlacementArgs) {
1118804b807ea918184d6de63bd745e1ff75a9bfc679John McCall      return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
11193019c444c672938c57f5573840071ecd73425ee7John McCall    }
11203019c444c672938c57f5573840071ecd73425ee7John McCall
11213019c444c672938c57f5573840071ecd73425ee7John McCall    CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
11223019c444c672938c57f5573840071ecd73425ee7John McCall                                   const FunctionDecl *OperatorDelete,
1123804b807ea918184d6de63bd745e1ff75a9bfc679John McCall                                   DominatingValue<RValue>::saved_type Ptr,
1124804b807ea918184d6de63bd745e1ff75a9bfc679John McCall                              DominatingValue<RValue>::saved_type AllocSize)
11253019c444c672938c57f5573840071ecd73425ee7John McCall      : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
11263019c444c672938c57f5573840071ecd73425ee7John McCall        Ptr(Ptr), AllocSize(AllocSize) {}
11273019c444c672938c57f5573840071ecd73425ee7John McCall
1128804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
11293019c444c672938c57f5573840071ecd73425ee7John McCall      assert(I < NumPlacementArgs && "index out of range");
11303019c444c672938c57f5573840071ecd73425ee7John McCall      getPlacementArgs()[I] = Arg;
11313019c444c672938c57f5573840071ecd73425ee7John McCall    }
11323019c444c672938c57f5573840071ecd73425ee7John McCall
1133651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    void Emit(CodeGenFunction &CGF, Flags flags) override {
11343019c444c672938c57f5573840071ecd73425ee7John McCall      const FunctionProtoType *FPT
11353019c444c672938c57f5573840071ecd73425ee7John McCall        = OperatorDelete->getType()->getAs<FunctionProtoType>();
1136651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1137651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines             (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
11383019c444c672938c57f5573840071ecd73425ee7John McCall
11393019c444c672938c57f5573840071ecd73425ee7John McCall      CallArgList DeleteArgs;
11403019c444c672938c57f5573840071ecd73425ee7John McCall
11413019c444c672938c57f5573840071ecd73425ee7John McCall      // The first argument is always a void*.
1142651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
114304c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman      DeleteArgs.add(Ptr.restore(CGF), *AI++);
11443019c444c672938c57f5573840071ecd73425ee7John McCall
11453019c444c672938c57f5573840071ecd73425ee7John McCall      // A member 'operator delete' can take an extra 'size_t' argument.
1146651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      if (FPT->getNumParams() == NumPlacementArgs + 2) {
1147804b807ea918184d6de63bd745e1ff75a9bfc679John McCall        RValue RV = AllocSize.restore(CGF);
114804c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman        DeleteArgs.add(RV, *AI++);
11493019c444c672938c57f5573840071ecd73425ee7John McCall      }
11503019c444c672938c57f5573840071ecd73425ee7John McCall
11513019c444c672938c57f5573840071ecd73425ee7John McCall      // Pass the rest of the arguments, which must match exactly.
11523019c444c672938c57f5573840071ecd73425ee7John McCall      for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1153804b807ea918184d6de63bd745e1ff75a9bfc679John McCall        RValue RV = getPlacementArgs()[I].restore(CGF);
115404c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman        DeleteArgs.add(RV, *AI++);
11553019c444c672938c57f5573840071ecd73425ee7John McCall      }
11563019c444c672938c57f5573840071ecd73425ee7John McCall
11573019c444c672938c57f5573840071ecd73425ee7John McCall      // Call 'operator delete'.
1158ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
11593019c444c672938c57f5573840071ecd73425ee7John McCall    }
11603019c444c672938c57f5573840071ecd73425ee7John McCall  };
11613019c444c672938c57f5573840071ecd73425ee7John McCall}
11623019c444c672938c57f5573840071ecd73425ee7John McCall
11633019c444c672938c57f5573840071ecd73425ee7John McCall/// Enter a cleanup to call 'operator delete' if the initializer in a
11643019c444c672938c57f5573840071ecd73425ee7John McCall/// new-expression throws.
11653019c444c672938c57f5573840071ecd73425ee7John McCallstatic void EnterNewDeleteCleanup(CodeGenFunction &CGF,
11663019c444c672938c57f5573840071ecd73425ee7John McCall                                  const CXXNewExpr *E,
11673019c444c672938c57f5573840071ecd73425ee7John McCall                                  llvm::Value *NewPtr,
11683019c444c672938c57f5573840071ecd73425ee7John McCall                                  llvm::Value *AllocSize,
11693019c444c672938c57f5573840071ecd73425ee7John McCall                                  const CallArgList &NewArgs) {
11703019c444c672938c57f5573840071ecd73425ee7John McCall  // If we're not inside a conditional branch, then the cleanup will
11713019c444c672938c57f5573840071ecd73425ee7John McCall  // dominate and we can do the easier (and more efficient) thing.
11723019c444c672938c57f5573840071ecd73425ee7John McCall  if (!CGF.isInConditionalBranch()) {
11733019c444c672938c57f5573840071ecd73425ee7John McCall    CallDeleteDuringNew *Cleanup = CGF.EHStack
11743019c444c672938c57f5573840071ecd73425ee7John McCall      .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
11753019c444c672938c57f5573840071ecd73425ee7John McCall                                                 E->getNumPlacementArgs(),
11763019c444c672938c57f5573840071ecd73425ee7John McCall                                                 E->getOperatorDelete(),
11773019c444c672938c57f5573840071ecd73425ee7John McCall                                                 NewPtr, AllocSize);
11783019c444c672938c57f5573840071ecd73425ee7John McCall    for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1179c6d07821c529bb95e4cf072e49b736c5142f1786Eli Friedman      Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
11803019c444c672938c57f5573840071ecd73425ee7John McCall
11813019c444c672938c57f5573840071ecd73425ee7John McCall    return;
11823019c444c672938c57f5573840071ecd73425ee7John McCall  }
11833019c444c672938c57f5573840071ecd73425ee7John McCall
11843019c444c672938c57f5573840071ecd73425ee7John McCall  // Otherwise, we need to save all this stuff.
1185804b807ea918184d6de63bd745e1ff75a9bfc679John McCall  DominatingValue<RValue>::saved_type SavedNewPtr =
1186804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1187804b807ea918184d6de63bd745e1ff75a9bfc679John McCall  DominatingValue<RValue>::saved_type SavedAllocSize =
1188804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
11893019c444c672938c57f5573840071ecd73425ee7John McCall
11903019c444c672938c57f5573840071ecd73425ee7John McCall  CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
11916f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
11923019c444c672938c57f5573840071ecd73425ee7John McCall                                                 E->getNumPlacementArgs(),
11933019c444c672938c57f5573840071ecd73425ee7John McCall                                                 E->getOperatorDelete(),
11943019c444c672938c57f5573840071ecd73425ee7John McCall                                                 SavedNewPtr,
11953019c444c672938c57f5573840071ecd73425ee7John McCall                                                 SavedAllocSize);
11963019c444c672938c57f5573840071ecd73425ee7John McCall  for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1197804b807ea918184d6de63bd745e1ff75a9bfc679John McCall    Cleanup->setPlacementArg(I,
1198c6d07821c529bb95e4cf072e49b736c5142f1786Eli Friedman                     DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
11993019c444c672938c57f5573840071ecd73425ee7John McCall
12006f103ba42cb69d50005a977c5ea583984ab63fc4John McCall  CGF.initFullExprCleanup();
12017d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall}
12027d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
120316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlssonllvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1204c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // The element type being allocated.
1205c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
12061e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1207c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // 1. Build a call to the allocation function.
1208c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  FunctionDecl *allocator = E->getOperatorNew();
1209c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  const FunctionProtoType *allocatorType =
1210c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    allocator->getType()->castAs<FunctionProtoType>();
121116d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1212c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  CallArgList allocatorArgs;
121316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
121416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  // The allocation size is the first argument.
1215c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  QualType sizeType = getContext().getSizeType();
121616d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
12179203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  // If there is a brace-initializer, cannot allocate fewer elements than inits.
12189203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  unsigned minElements = 0;
12199203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  if (E->isArray() && E->hasInitializer()) {
12209203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
12219203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl      minElements = ILE->getNumInits();
12229203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl  }
12239203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl
12246bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Value *numElements = nullptr;
12256bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Value *allocSizeWithoutCookie = nullptr;
1226c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  llvm::Value *allocSize =
12279203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl    EmitCXXNewAllocSize(*this, E, minElements, numElements,
12289203647221439c6eb04842bb8a22f5f03fd4d2bfSebastian Redl                        allocSizeWithoutCookie);
1229a4d4c019bf477ce6ff7b01517e690f6c5fd6ad71Anders Carlsson
123004c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman  allocatorArgs.add(RValue::get(allocSize), sizeType);
123116d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
123216d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  // We start at 1 here because the first argument (the allocation size)
123316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  // has already been emitted.
1234651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
1235651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines               allocatorType->param_type_begin() + 1,
1236651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines               allocatorType->param_type_end(), E->placement_arg_begin(),
1237651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines               E->placement_arg_end());
123816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1239b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  // Emit the allocation call.  If the allocator is a global placement
1240b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  // operator, just "inline" it directly.
1241b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  RValue RV;
1242b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  if (allocator->isReservedGlobalPlacementOperator()) {
1243b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall    assert(allocatorArgs.size() == 2);
1244b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall    RV = allocatorArgs[1].RV;
1245b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall    // TODO: kill any unnecessary computations done for the size
1246b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall    // argument.
1247b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  } else {
1248ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith    RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1249b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  }
125016d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1251c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // Emit a null check on the allocation result if the allocation
1252c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // function is allowed to return null (because it has a non-throwing
1253c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // exception spec; for this part, we inline
1254c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1255c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  // interesting initializer.
12568026f6d82f7fa544bc0453714fe94bca62a1196eSebastian Redl  bool nullCheck = allocatorType->isNothrow(getContext()) &&
12572aed8b88613863f3c439cdfb205bdf8b608fb205Sebastian Redl    (!allocType.isPODType(getContext()) || E->hasInitializer());
125816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
12596bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::BasicBlock *nullCheckBB = nullptr;
12606bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::BasicBlock *contBB = nullptr;
126116d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1262c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  llvm::Value *allocation = RV.getScalarVal();
1263956a5a17713deb1b5b27893303c4f308a1bd2a62Micah Villmow  unsigned AS = allocation->getType()->getPointerAddressSpace();
126416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1265a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall  // The null-check means that the initializer is conditionally
1266a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall  // evaluated.
1267a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall  ConditionalEvaluation conditional(*this);
1268a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall
1269c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  if (nullCheck) {
1270c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    conditional.begin(*this);
127116d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1272c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    nullCheckBB = Builder.GetInsertBlock();
1273c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1274c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    contBB = createBasicBlock("new.cont");
1275a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall
1276c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1277c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    Builder.CreateCondBr(isNull, contBB, notNullBB);
1278c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    EmitBlock(notNullBB);
127916d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  }
12801e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
12817d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  // If there's an operator delete, enter a cleanup to call it if an
12827d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  // exception is thrown.
1283c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  EHScopeStack::stable_iterator operatorDeleteCleanup;
12846bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Instruction *cleanupDominator = nullptr;
1285b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall  if (E->getOperatorDelete() &&
1286b1c98a35fbd49d6404a72db4aca2ceda352380c7John McCall      !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1287c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1288c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    operatorDeleteCleanup = EHStack.stable_begin();
12896f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    cleanupDominator = Builder.CreateUnreachable();
12907d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  }
12917d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
1292576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman  assert((allocSize == allocSizeWithoutCookie) ==
1293576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman         CalculateCookiePadding(*this, E).isZero());
1294576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman  if (allocSize != allocSizeWithoutCookie) {
1295576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman    assert(E->isArray());
1296576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman    allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1297576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman                                                       numElements,
1298576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman                                                       E, allocType);
1299576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman  }
1300576cf17055c92e7d1ae8fb9fd9f79433a16a4394Eli Friedman
13012acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *elementPtrTy
1302c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    = ConvertTypeForMem(allocType)->getPointerTo(AS);
1303c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
13047d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
1305197056726ed6412501130c2ef2ff69009772aa65John McCall  EmitNewInitializer(*this, E, allocType, result, numElements,
1306197056726ed6412501130c2ef2ff69009772aa65John McCall                     allocSizeWithoutCookie);
13071e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  if (E->isArray()) {
13081e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    // NewPtr is a pointer to the base element type.  If we're
13091e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    // allocating an array of arrays, we'll need to cast back to the
13101e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    // array pointer type.
13112acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *resultType = ConvertTypeForMem(E->getType());
1312c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    if (result->getType() != resultType)
1313c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall      result = Builder.CreateBitCast(result, resultType);
1314ceb43b662bf09b44a08714e8f9d222780ca979d7Fariborz Jahanian  }
13157d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall
13167d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  // Deactivate the 'operator delete' cleanup if we finished
13177d8647f194ae4f2499e5bcd40dcfea34cd21ebc6John McCall  // initialization.
13186f103ba42cb69d50005a977c5ea583984ab63fc4John McCall  if (operatorDeleteCleanup.isValid()) {
13196f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
13206f103ba42cb69d50005a977c5ea583984ab63fc4John McCall    cleanupDominator->eraseFromParent();
13216f103ba42cb69d50005a977c5ea583984ab63fc4John McCall  }
13222aed8b88613863f3c439cdfb205bdf8b608fb205Sebastian Redl
1323c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  if (nullCheck) {
1324a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall    conditional.end(*this);
1325a7f633f522af786e80dc08dbd63e222c9414095bJohn McCall
1326c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1327c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    EmitBlock(contBB);
132816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1329bbf3bacb3e0c1ebb3e8a4a8b1330404a7e379315Jay Foad    llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
1330c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    PHI->addIncoming(result, notNullBB);
1331c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1332c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall                     nullCheckBB);
133316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1334c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall    result = PHI;
133516d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  }
13361e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1337c2f3e7f42c8bf9e8d4393a6e8c4762dafc4f28ddJohn McCall  return result;
133816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson}
133916d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
13405fe05986473c4ff780508dec4cd2cf4822168125Eli Friedmanvoid CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
13415fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman                                     llvm::Value *Ptr,
13425fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman                                     QualType DeleteTy) {
13431e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  assert(DeleteFD->getOverloadedOperator() == OO_Delete);
13441e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
13455fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman  const FunctionProtoType *DeleteFTy =
13465fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman    DeleteFD->getType()->getAs<FunctionProtoType>();
13475fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman
13485fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman  CallArgList DeleteArgs;
13495fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman
1350871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  // Check if we need to pass the size to the delete operator.
13516bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Value *Size = nullptr;
1352871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  QualType SizeTy;
1353651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (DeleteFTy->getNumParams() == 2) {
1354651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    SizeTy = DeleteFTy->getParamType(1);
13554f122ef0ca7683486d78c84ed87455d5f35ee1b1Ken Dyck    CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
13564f122ef0ca7683486d78c84ed87455d5f35ee1b1Ken Dyck    Size = llvm::ConstantInt::get(ConvertType(SizeTy),
13574f122ef0ca7683486d78c84ed87455d5f35ee1b1Ken Dyck                                  DeleteTypeSize.getQuantity());
1358871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  }
1359651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
1360651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  QualType ArgTy = DeleteFTy->getParamType(0);
1361871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
136204c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman  DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1363871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson
1364871d078f5ae5505553c02deeabdd4b83b4820211Anders Carlsson  if (Size)
136504c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman    DeleteArgs.add(RValue::get(Size), SizeTy);
13665fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman
13675fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman  // Emit the call to delete.
1368ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith  EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
13695fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman}
13705fe05986473c4ff780508dec4cd2cf4822168125Eli Friedman
13711e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallnamespace {
13721e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  /// Calls the given 'operator delete' on a single object.
13731e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  struct CallObjectDelete : EHScopeStack::Cleanup {
13741e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    llvm::Value *Ptr;
13751e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    const FunctionDecl *OperatorDelete;
13761e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    QualType ElementType;
13771e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
13781e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    CallObjectDelete(llvm::Value *Ptr,
13791e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                     const FunctionDecl *OperatorDelete,
13801e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                     QualType ElementType)
13811e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
13821e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1383651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    void Emit(CodeGenFunction &CGF, Flags flags) override {
13841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
13851e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
13861e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  };
13871e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall}
13881e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
13891e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall/// Emit the code for deleting a single object.
13901e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallstatic void EmitObjectDelete(CodeGenFunction &CGF,
13911e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                             const FunctionDecl *OperatorDelete,
13921e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                             llvm::Value *Ptr,
1393a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor                             QualType ElementType,
1394a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor                             bool UseGlobalDelete) {
13951e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // Find the destructor for the type, if applicable.  If the
13961e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // destructor is virtual, we'll just emit the vcall and return.
13976bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  const CXXDestructorDecl *Dtor = nullptr;
13981e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  if (const RecordType *RT = ElementType->getAs<RecordType>()) {
13991e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1400aebab72698ce5283395e61597a266fb04e62e390Eli Friedman    if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
14011e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      Dtor = RD->getDestructor();
14021e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14031e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      if (Dtor->isVirtual()) {
1404a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor        if (UseGlobalDelete) {
1405a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor          // If we're supposed to call the global delete, make sure we do so
1406a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor          // even if the destructor throws.
1407ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall
1408ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall          // Derive the complete-object pointer, which is what we need
1409ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall          // to pass to the deallocation function.
1410ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall          llvm::Value *completePtr =
1411ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall            CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1412ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall
1413a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor          CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1414ecd03b447bb0e2ed1954c77441d49a4a17ca8138John McCall                                                    completePtr, OperatorDelete,
1415a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor                                                    ElementType);
1416a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor        }
14170f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov
14184def70d3040e73707c738f7c366737a986135edfRichard Smith        // FIXME: Provide a source location here.
14190f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov        CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
14200f9827f5d6248d7008063768eb5f2c3e6ba83e94Timur Iskhodzhanov        CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
14213b50e8d78c34fc57e25781015a2cb0536ca54f89Stephen Lin                                                      SourceLocation(), Ptr);
14221e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1423a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor        if (UseGlobalDelete) {
1424a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor          CGF.PopCleanupBlock();
1425a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor        }
1426a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor
14271e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        return;
14281e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      }
14291e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
14301e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  }
14311e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14321e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // Make sure that we call delete even if the dtor throws.
14333ad32c8d93eb65d1d4943d7df567fc9b4f55d137John McCall  // This doesn't have to a conditional cleanup because we're going
14343ad32c8d93eb65d1d4943d7df567fc9b4f55d137John McCall  // to pop it off in a second.
14351e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
14361e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                                            Ptr, OperatorDelete, ElementType);
14371e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14381e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  if (Dtor)
14391e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1440378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                              /*ForVirtualBase=*/false,
1441378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                              /*Delegating=*/false,
1442378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                              Ptr);
14434e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (CGF.getLangOpts().ObjCAutoRefCount &&
1444f85e193739c953358c865005855253af4f68a497John McCall           ElementType->isObjCLifetimeType()) {
1445f85e193739c953358c865005855253af4f68a497John McCall    switch (ElementType.getObjCLifetime()) {
1446f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_None:
1447f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_ExplicitNone:
1448f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Autoreleasing:
1449f85e193739c953358c865005855253af4f68a497John McCall      break;
14501e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1451f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Strong: {
1452f85e193739c953358c865005855253af4f68a497John McCall      // Load the pointer value.
1453f85e193739c953358c865005855253af4f68a497John McCall      llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1454f85e193739c953358c865005855253af4f68a497John McCall                                             ElementType.isVolatileQualified());
1455f85e193739c953358c865005855253af4f68a497John McCall
14565b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall      CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
1457f85e193739c953358c865005855253af4f68a497John McCall      break;
1458f85e193739c953358c865005855253af4f68a497John McCall    }
1459f85e193739c953358c865005855253af4f68a497John McCall
1460f85e193739c953358c865005855253af4f68a497John McCall    case Qualifiers::OCL_Weak:
1461f85e193739c953358c865005855253af4f68a497John McCall      CGF.EmitARCDestroyWeak(Ptr);
1462f85e193739c953358c865005855253af4f68a497John McCall      break;
1463f85e193739c953358c865005855253af4f68a497John McCall    }
1464f85e193739c953358c865005855253af4f68a497John McCall  }
1465f85e193739c953358c865005855253af4f68a497John McCall
14661e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  CGF.PopCleanupBlock();
14671e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall}
14681e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14691e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallnamespace {
14701e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  /// Calls the given 'operator delete' on an array of objects.
14711e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  struct CallArrayDelete : EHScopeStack::Cleanup {
14721e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    llvm::Value *Ptr;
14731e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    const FunctionDecl *OperatorDelete;
14741e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    llvm::Value *NumElements;
14751e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    QualType ElementType;
14761e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    CharUnits CookieSize;
14771e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14781e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    CallArrayDelete(llvm::Value *Ptr,
14791e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                    const FunctionDecl *OperatorDelete,
14801e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                    llvm::Value *NumElements,
14811e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                    QualType ElementType,
14821e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall                    CharUnits CookieSize)
14831e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
14841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        ElementType(ElementType), CookieSize(CookieSize) {}
14851e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
1486651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    void Emit(CodeGenFunction &CGF, Flags flags) override {
14871e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      const FunctionProtoType *DeleteFTy =
14881e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        OperatorDelete->getType()->getAs<FunctionProtoType>();
1489651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
14901e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14911e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      CallArgList Args;
14921e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14931e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      // Pass the pointer as the first argument.
1494651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      QualType VoidPtrTy = DeleteFTy->getParamType(0);
14951e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      llvm::Value *DeletePtr
14961e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
149704c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman      Args.add(RValue::get(DeletePtr), VoidPtrTy);
14981e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
14991e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      // Pass the original requested size as the second argument.
1500651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      if (DeleteFTy->getNumParams() == 2) {
1501651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        QualType size_t = DeleteFTy->getParamType(1);
15022acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner        llvm::IntegerType *SizeTy
15031e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall          = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
15041e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15051e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        CharUnits ElementTypeSize =
15061e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall          CGF.CGM.getContext().getTypeSizeInChars(ElementType);
15071e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15081e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        // The size of an element, multiplied by the number of elements.
15091e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        llvm::Value *Size
15101e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall          = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
15111e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        Size = CGF.Builder.CreateMul(Size, NumElements);
15121e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15131e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        // Plus the size of the cookie if applicable.
15141e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        if (!CookieSize.isZero()) {
15151e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall          llvm::Value *CookieSizeV
15161e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall            = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
15171e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall          Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
15181e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall        }
15191e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
152004c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman        Args.add(RValue::get(Size), size_t);
15211e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      }
15221e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15231e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      // Emit the call to delete.
1524ddcff1b310b80b63f1a9ba88f2befeab40c3648fRichard Smith      EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
15251e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    }
15261e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  };
15271e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall}
15281e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15291e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall/// Emit the code for deleting an array of objects.
15301e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCallstatic void EmitArrayDelete(CodeGenFunction &CGF,
15316ec278d1a354517e20f13a877481453ee7940c78John McCall                            const CXXDeleteExpr *E,
15327cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                            llvm::Value *deletedPtr,
15337cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                            QualType elementType) {
15346bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Value *numElements = nullptr;
15356bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::Value *allocatedPtr = nullptr;
15367cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  CharUnits cookieSize;
15377cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
15387cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                                      numElements, allocatedPtr, cookieSize);
15391e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15407cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
15411e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15421e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // Make sure that we call delete even if one of the dtors throws.
15437cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  const FunctionDecl *operatorDelete = E->getOperatorDelete();
15441e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
15457cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                                           allocatedPtr, operatorDelete,
15467cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                                           numElements, elementType,
15477cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                                           cookieSize);
15487cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall
15497cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  // Destroy the elements.
15507cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
15517cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall    assert(numElements && "no element count for a type with a destructor!");
15527cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall
15537cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall    llvm::Value *arrayEnd =
15547cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall      CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
1555fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1556fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    // Note that it is legal to allocate a zero-length array, and we
1557fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    // can never fold the check away because the length should always
1558fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    // come from a cookie.
15597cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall    CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
15607cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                         CGF.getDestroyer(dtorKind),
1561fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall                         /*checkZeroLength*/ true,
15627cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall                         CGF.needsEHCleanup(dtorKind));
15631e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  }
15641e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15657cfd76cb5cec2aa7aaa4176339c806de6ec85a79John McCall  // Pop the cleanup block.
15661e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  CGF.PopCleanupBlock();
15671e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall}
15681e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
156916d81b8db39593b5f1a38b077757272a09c12da8Anders Carlssonvoid CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
15709091656e423f2354e53b2b3baa95b3eb5510badcDouglas Gregor  const Expr *Arg = E->getArgument();
15719091656e423f2354e53b2b3baa95b3eb5510badcDouglas Gregor  llvm::Value *Ptr = EmitScalarExpr(Arg);
157216d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
157316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  // Null check the pointer.
157416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
157516d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
157616d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1577b924124316becf2968a37dab36d0c48ea167666fAnders Carlsson  llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
157816d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
157916d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
158016d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  EmitBlock(DeleteNotNull);
15811e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15821e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // We might be deleting a pointer to array.  If so, GEP down to the
15831e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // first non-array element.
15841e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
15851e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
15861e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  if (DeleteTy->isConstantArrayType()) {
15871e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    llvm::Value *Zero = Builder.getInt32(0);
15885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    SmallVector<llvm::Value*,8> GEP;
15891e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15901e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    GEP.push_back(Zero); // point at the outermost array
15911e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15921e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    // For each layer of array type we're pointing at:
15931e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall    while (const ConstantArrayType *Arr
15941e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall             = getContext().getAsConstantArrayType(DeleteTy)) {
15951e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      // 1. Unpeel the array type.
15961e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      DeleteTy = Arr->getElementType();
15971e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
15981e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      // 2. GEP to the first element of the array.
15991e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall      GEP.push_back(Zero);
160016d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson    }
16011e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
16020f6ac7cf7bc6a02c1a5c19d2c90ec0d1dd7786e7Jay Foad    Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
160316d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  }
160416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
1605eede61a83e90f3cb03ef8665b67d648dccd6ce42Douglas Gregor  assert(ConvertTypeForMem(DeleteTy) ==
1606eede61a83e90f3cb03ef8665b67d648dccd6ce42Douglas Gregor         cast<llvm::PointerType>(Ptr->getType())->getElementType());
16071e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall
16081e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  if (E->isArrayForm()) {
16096ec278d1a354517e20f13a877481453ee7940c78John McCall    EmitArrayDelete(*this, E, Ptr, DeleteTy);
16101e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  } else {
1611a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor    EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1612a8b20f70d562cdc2679f82d409832b79fc415277Douglas Gregor                     E->isGlobalDelete());
16131e7fe751466ea82665fd21e9162fd7cc9c5f412dJohn McCall  }
161416d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson
161516d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson  EmitBlock(DeleteEnd);
161616d81b8db39593b5f1a38b077757272a09c12da8Anders Carlsson}
1617c2e84ae9a6d25cea3e583c768e576b4c981ec028Mike Stump
1618ef8225444452a1486bd721f3285301fe84643b00Stephen Hinesstatic llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
16192acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                         llvm::Type *StdTypeInfoPtrTy) {
16203f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  // Get the vtable pointer.
16213f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
16223f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
16233f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  // C++ [expr.typeid]p2:
16243f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   If the glvalue expression is obtained by applying the unary * operator to
16253f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   a pointer and the pointer is a null pointer value, the typeid expression
16263f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   throws the std::bad_typeid exception.
1627ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  bool IsDeref = false;
1628ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1629ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (UO->getOpcode() == UO_Deref)
1630ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      IsDeref = true;
1631ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
1632ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  QualType SrcRecordTy = E->getType();
1633ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(IsDeref, SrcRecordTy)) {
1634ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    llvm::BasicBlock *BadTypeidBlock =
16353f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson        CGF.createBasicBlock("typeid.bad_typeid");
1636ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
16373f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
1638ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1639ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
16403f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
1641ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CGF.EmitBlock(BadTypeidBlock);
1642ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1643ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    CGF.EmitBlock(EndBlock);
16443f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  }
16453f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
1646ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1647ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                        StdTypeInfoPtrTy);
16483f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson}
16493f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
16503ad32c8d93eb65d1d4943d7df567fc9b4f55d137John McCallllvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
16512acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *StdTypeInfoPtrTy =
16523f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson    ConvertType(E->getType())->getPointerTo();
165331b7f52d8c8d459e80d2a72176cc7fcc4b7d8d38Anders Carlsson
16541d7088d1d9dc99e5478c0184a3e21cafef2a0b53Anders Carlsson  if (E->isTypeOperand()) {
1655fe16aa31fdfaad4c38aed443d853af293714f1c4David Majnemer    llvm::Constant *TypeInfo =
1656fe16aa31fdfaad4c38aed443d853af293714f1c4David Majnemer        CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
16573f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson    return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
16581d7088d1d9dc99e5478c0184a3e21cafef2a0b53Anders Carlsson  }
16594bdbc0cb1e29ac870b7e7985cf4a1b5c34176e8cAnders Carlsson
16603f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  // C++ [expr.typeid]p2:
16613f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   When typeid is applied to a glvalue expression whose type is a
16623f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   polymorphic class type, the result refers to a std::type_info object
16633f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   representing the type of the most derived object (that is, the dynamic
16643f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  //   type) to which the glvalue refers.
16650d729105ecb50a7e3cbe6e57c29149edfa5cf05aRichard Smith  if (E->isPotentiallyEvaluated())
16660d729105ecb50a7e3cbe6e57c29149edfa5cf05aRichard Smith    return EmitTypeidFromVTable(*this, E->getExprOperand(),
16670d729105ecb50a7e3cbe6e57c29149edfa5cf05aRichard Smith                                StdTypeInfoPtrTy);
16683f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson
16693f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  QualType OperandTy = E->getExprOperand()->getType();
16703f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson  return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
16713f6c5e13f6c1662a7173c747fc63f4e8edb91206Anders Carlsson                               StdTypeInfoPtrTy);
1672c2e84ae9a6d25cea3e583c768e576b4c981ec028Mike Stump}
1673c849c052d6b4b70f2651c1969531861a5f230053Mike Stump
16743ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlssonstatic llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
16753ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson                                          QualType DestTy) {
16762acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
16773ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  if (DestTy->isPointerType())
16783ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson    return llvm::Constant::getNullValue(DestLTy);
16793ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson
16803ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  /// C++ [expr.dynamic.cast]p9:
16813ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  ///   A failed cast to reference type throws std::bad_cast
1682ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1683ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    return nullptr;
16843ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson
16853ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
16863ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  return llvm::UndefValue::get(DestLTy);
16873ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson}
16883ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson
1689f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlssonllvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
1690f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson                                              const CXXDynamicCastExpr *DCE) {
1691f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  QualType DestTy = DCE->getTypeAsWritten();
1692c849c052d6b4b70f2651c1969531861a5f230053Mike Stump
16933ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  if (DCE->isAlwaysNull())
1694ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1695ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      return T;
16963ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson
16973ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson  QualType SrcTy = DCE->getSubExpr()->getType();
16983ddcdd5d6c88902d24baa9e6bb240a3da88e68d4Anders Carlsson
1699ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  // C++ [expr.dynamic.cast]p7:
1700ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  //   If T is "pointer to cv void," then the result is a pointer to the most
1701ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  //   derived object pointed to by v.
1702ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  const PointerType *DestPTy = DestTy->getAs<PointerType>();
1703ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
1704ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  bool isDynamicCastToVoid;
1705ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  QualType SrcRecordTy;
1706ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  QualType DestRecordTy;
1707ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (DestPTy) {
1708ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1709ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1710ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    DestRecordTy = DestPTy->getPointeeType();
1711ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  } else {
1712ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    isDynamicCastToVoid = false;
1713ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    SrcRecordTy = SrcTy;
1714ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1715ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  }
1716ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
1717ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1718ef8225444452a1486bd721f3285301fe84643b00Stephen Hines
1719f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  // C++ [expr.dynamic.cast]p4:
1720f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  //   If the value of v is a null pointer value in the pointer case, the result
1721f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  //   is the null pointer value of type T.
1722ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  bool ShouldNullCheckSrcValue =
1723ef8225444452a1486bd721f3285301fe84643b00Stephen Hines      CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1724ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                                         SrcRecordTy);
17256bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
17266bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::BasicBlock *CastNull = nullptr;
17276bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  llvm::BasicBlock *CastNotNull = nullptr;
1728f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1729f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1730f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  if (ShouldNullCheckSrcValue) {
1731f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    CastNull = createBasicBlock("dynamic_cast.null");
1732f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    CastNotNull = createBasicBlock("dynamic_cast.notnull");
1733c849c052d6b4b70f2651c1969531861a5f230053Mike Stump
1734f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    llvm::Value *IsNull = Builder.CreateIsNull(Value);
1735f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1736f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    EmitBlock(CastNotNull);
1737c849c052d6b4b70f2651c1969531861a5f230053Mike Stump  }
1738f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1739ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  if (isDynamicCastToVoid) {
1740ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1741ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                                  DestTy);
1742ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  } else {
1743ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    assert(DestRecordTy->isRecordType() &&
1744ef8225444452a1486bd721f3285301fe84643b00Stephen Hines           "destination type must be a record type!");
1745ef8225444452a1486bd721f3285301fe84643b00Stephen Hines    Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1746ef8225444452a1486bd721f3285301fe84643b00Stephen Hines                                                DestTy, DestRecordTy, CastEnd);
1747ef8225444452a1486bd721f3285301fe84643b00Stephen Hines  }
1748f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1749f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  if (ShouldNullCheckSrcValue) {
1750f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    EmitBranch(CastEnd);
1751f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1752f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    EmitBlock(CastNull);
1753f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    EmitBranch(CastEnd);
1754c849c052d6b4b70f2651c1969531861a5f230053Mike Stump  }
1755f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1756f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  EmitBlock(CastEnd);
1757f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1758f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  if (ShouldNullCheckSrcValue) {
1759f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1760f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    PHI->addIncoming(Value, CastNotNull);
1761f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1762f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson
1763f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson    Value = PHI;
1764c849c052d6b4b70f2651c1969531861a5f230053Mike Stump  }
1765c849c052d6b4b70f2651c1969531861a5f230053Mike Stump
1766f0cb4a6ac7ffcba25309a5d1ad1a4bf869b13a33Anders Carlsson  return Value;
1767c849c052d6b4b70f2651c1969531861a5f230053Mike Stump}
17684c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman
17694c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedmanvoid CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
1770f8823e7ae00d2b0a9395b51b7bd53b505df72031Eli Friedman  RunCleanupsScope Scope(*this);
1771377ecc7996dce6803f7b7b6208cab5e197c9c5b8Eli Friedman  LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1772377ecc7996dce6803f7b7b6208cab5e197c9c5b8Eli Friedman                                 Slot.getAlignment());
1773f8823e7ae00d2b0a9395b51b7bd53b505df72031Eli Friedman
17744c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman  CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
17754c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman  for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
17764c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman                                         e = E->capture_init_end();
1777c07b18ed2b207b17cf8d770966e5c1e52d46f4ecEric Christopher       i != e; ++i, ++CurField) {
17784c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman    // Emit initialization
1779377ecc7996dce6803f7b7b6208cab5e197c9c5b8Eli Friedman
1780581deb3da481053c4993c7600f97acf7768caac5David Blaikie    LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
1781b74ed087469db042325bad76fdf3ff6ed67dec09Eli Friedman    ArrayRef<VarDecl *> ArrayIndexes;
1782b74ed087469db042325bad76fdf3ff6ed67dec09Eli Friedman    if (CurField->getType()->isArrayType())
1783b74ed087469db042325bad76fdf3ff6ed67dec09Eli Friedman      ArrayIndexes = E->getCaptureInitIndexVars(i);
1784581deb3da481053c4993c7600f97acf7768caac5David Blaikie    EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
17854c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman  }
17864c5d8afd100189b6cce4fd89bfb8aec5700acb50Eli Friedman}
1787