159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
359486a2dSAnders Carlsson //                     The LLVM Compiler Infrastructure
459486a2dSAnders Carlsson //
559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source
659486a2dSAnders Carlsson // License. See LICENSE.TXT for details.
759486a2dSAnders Carlsson //
859486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
959486a2dSAnders Carlsson //
1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1159486a2dSAnders Carlsson //
1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1359486a2dSAnders Carlsson 
1491bbb554SDevang Patel #include "clang/Frontend/CodeGenOptions.h"
1559486a2dSAnders Carlsson #include "CodeGenFunction.h"
165d865c32SJohn McCall #include "CGCXXABI.h"
1760d215b6SFariborz Jahanian #include "CGObjCRuntime.h"
1891bbb554SDevang Patel #include "CGDebugInfo.h"
1926008e07SChris Lattner #include "llvm/Intrinsics.h"
2059486a2dSAnders Carlsson using namespace clang;
2159486a2dSAnders Carlsson using namespace CodeGen;
2259486a2dSAnders Carlsson 
2327da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
2427da15baSAnders Carlsson                                           llvm::Value *Callee,
2527da15baSAnders Carlsson                                           ReturnValueSlot ReturnValue,
2627da15baSAnders Carlsson                                           llvm::Value *This,
27e36a6b3eSAnders Carlsson                                           llvm::Value *VTT,
2827da15baSAnders Carlsson                                           CallExpr::const_arg_iterator ArgBeg,
2927da15baSAnders Carlsson                                           CallExpr::const_arg_iterator ArgEnd) {
3027da15baSAnders Carlsson   assert(MD->isInstance() &&
3127da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
3227da15baSAnders Carlsson 
3327da15baSAnders Carlsson   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3427da15baSAnders Carlsson 
3527da15baSAnders Carlsson   CallArgList Args;
3627da15baSAnders Carlsson 
3727da15baSAnders Carlsson   // Push the this ptr.
3827da15baSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(This),
3927da15baSAnders Carlsson                                 MD->getThisType(getContext())));
4027da15baSAnders Carlsson 
41e36a6b3eSAnders Carlsson   // If there is a VTT parameter, emit it.
42e36a6b3eSAnders Carlsson   if (VTT) {
43e36a6b3eSAnders Carlsson     QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44e36a6b3eSAnders Carlsson     Args.push_back(std::make_pair(RValue::get(VTT), T));
45e36a6b3eSAnders Carlsson   }
46e36a6b3eSAnders Carlsson 
4727da15baSAnders Carlsson   // And the rest of the call args
4827da15baSAnders Carlsson   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
4927da15baSAnders Carlsson 
50ab26cfa5SJohn McCall   QualType ResultType = FPT->getResultType();
5199cc30c3STilmann Scheller   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
5299cc30c3STilmann Scheller                                                  FPT->getExtInfo()),
53c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
5427da15baSAnders Carlsson }
5527da15baSAnders Carlsson 
561ae64c5aSAnders Carlsson static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
576b3afd7dSAnders Carlsson   const Expr *E = Base;
586b3afd7dSAnders Carlsson 
596b3afd7dSAnders Carlsson   while (true) {
606b3afd7dSAnders Carlsson     E = E->IgnoreParens();
616b3afd7dSAnders Carlsson     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
626b3afd7dSAnders Carlsson       if (CE->getCastKind() == CK_DerivedToBase ||
636b3afd7dSAnders Carlsson           CE->getCastKind() == CK_UncheckedDerivedToBase ||
646b3afd7dSAnders Carlsson           CE->getCastKind() == CK_NoOp) {
656b3afd7dSAnders Carlsson         E = CE->getSubExpr();
666b3afd7dSAnders Carlsson         continue;
676b3afd7dSAnders Carlsson       }
686b3afd7dSAnders Carlsson     }
696b3afd7dSAnders Carlsson 
706b3afd7dSAnders Carlsson     break;
716b3afd7dSAnders Carlsson   }
726b3afd7dSAnders Carlsson 
736b3afd7dSAnders Carlsson   QualType DerivedType = E->getType();
741ae64c5aSAnders Carlsson   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
751ae64c5aSAnders Carlsson     DerivedType = PTy->getPointeeType();
761ae64c5aSAnders Carlsson 
771ae64c5aSAnders Carlsson   return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
781ae64c5aSAnders Carlsson }
791ae64c5aSAnders Carlsson 
8027da15baSAnders Carlsson /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
8127da15baSAnders Carlsson /// expr can be devirtualized.
82252a47f6SFariborz Jahanian static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
83252a47f6SFariborz Jahanian                                                const Expr *Base,
84a7911fa3SAnders Carlsson                                                const CXXMethodDecl *MD) {
85a7911fa3SAnders Carlsson 
861ae64c5aSAnders Carlsson   // When building with -fapple-kext, all calls must go through the vtable since
871ae64c5aSAnders Carlsson   // the kernel linker can do runtime patching of vtables.
88252a47f6SFariborz Jahanian   if (Context.getLangOptions().AppleKext)
89252a47f6SFariborz Jahanian     return false;
90252a47f6SFariborz Jahanian 
911ae64c5aSAnders Carlsson   // If the most derived class is marked final, we know that no subclass can
921ae64c5aSAnders Carlsson   // override this member function and so we can devirtualize it. For example:
931ae64c5aSAnders Carlsson   //
941ae64c5aSAnders Carlsson   // struct A { virtual void f(); }
951ae64c5aSAnders Carlsson   // struct B final : A { };
961ae64c5aSAnders Carlsson   //
971ae64c5aSAnders Carlsson   // void f(B *b) {
981ae64c5aSAnders Carlsson   //   b->f();
991ae64c5aSAnders Carlsson   // }
1001ae64c5aSAnders Carlsson   //
1011ae64c5aSAnders Carlsson   const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1021ae64c5aSAnders Carlsson   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1031ae64c5aSAnders Carlsson     return true;
1041ae64c5aSAnders Carlsson 
10519588aa4SAnders Carlsson   // If the member function is marked 'final', we know that it can't be
106b00c2144SAnders Carlsson   // overridden and can therefore devirtualize it.
1071eb95961SAnders Carlsson   if (MD->hasAttr<FinalAttr>())
108a7911fa3SAnders Carlsson     return true;
109a7911fa3SAnders Carlsson 
11019588aa4SAnders Carlsson   // Similarly, if the class itself is marked 'final' it can't be overridden
11119588aa4SAnders Carlsson   // and we can therefore devirtualize the member function call.
1121eb95961SAnders Carlsson   if (MD->getParent()->hasAttr<FinalAttr>())
113b00c2144SAnders Carlsson     return true;
114b00c2144SAnders Carlsson 
11527da15baSAnders Carlsson   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11627da15baSAnders Carlsson     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
11727da15baSAnders Carlsson       // This is a record decl. We know the type and can devirtualize it.
11827da15baSAnders Carlsson       return VD->getType()->isRecordType();
11927da15baSAnders Carlsson     }
12027da15baSAnders Carlsson 
12127da15baSAnders Carlsson     return false;
12227da15baSAnders Carlsson   }
12327da15baSAnders Carlsson 
12427da15baSAnders Carlsson   // We can always devirtualize calls on temporary object expressions.
125a682427eSEli Friedman   if (isa<CXXConstructExpr>(Base))
12627da15baSAnders Carlsson     return true;
12727da15baSAnders Carlsson 
12827da15baSAnders Carlsson   // And calls on bound temporaries.
12927da15baSAnders Carlsson   if (isa<CXXBindTemporaryExpr>(Base))
13027da15baSAnders Carlsson     return true;
13127da15baSAnders Carlsson 
13227da15baSAnders Carlsson   // Check if this is a call expr that returns a record type.
13327da15baSAnders Carlsson   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
13427da15baSAnders Carlsson     return CE->getCallReturnType()->isRecordType();
13527da15baSAnders Carlsson 
13627da15baSAnders Carlsson   // We can't devirtualize the call.
13727da15baSAnders Carlsson   return false;
13827da15baSAnders Carlsson }
13927da15baSAnders Carlsson 
14064225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
14164225794SFrancois Pichet // extensions allowing explicit constructor function call.
14227da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
14327da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
14427da15baSAnders Carlsson   if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
14527da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
14627da15baSAnders Carlsson 
14727da15baSAnders Carlsson   const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
14827da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
14927da15baSAnders Carlsson 
15091bbb554SDevang Patel   CGDebugInfo *DI = getDebugInfo();
151401c916cSDevang Patel   if (DI && CGM.getCodeGenOpts().LimitDebugInfo
152401c916cSDevang Patel       && !isa<CallExpr>(ME->getBase())) {
15391bbb554SDevang Patel     QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
15491bbb554SDevang Patel     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
15591bbb554SDevang Patel       DI->getOrCreateRecordType(PTy->getPointeeType(),
15691bbb554SDevang Patel                                 MD->getParent()->getLocation());
15791bbb554SDevang Patel     }
15891bbb554SDevang Patel   }
15991bbb554SDevang Patel 
16027da15baSAnders Carlsson   if (MD->isStatic()) {
16127da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
16227da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
16327da15baSAnders Carlsson     return EmitCall(getContext().getPointerType(MD->getType()), Callee,
16427da15baSAnders Carlsson                     ReturnValue, CE->arg_begin(), CE->arg_end());
16527da15baSAnders Carlsson   }
16627da15baSAnders Carlsson 
1670d635f53SJohn McCall   // Compute the object pointer.
16827da15baSAnders Carlsson   llvm::Value *This;
16927da15baSAnders Carlsson   if (ME->isArrow())
17027da15baSAnders Carlsson     This = EmitScalarExpr(ME->getBase());
171f93ac894SFariborz Jahanian   else
172e26a872bSJohn McCall     This = EmitLValue(ME->getBase()).getAddress();
17327da15baSAnders Carlsson 
1740d635f53SJohn McCall   if (MD->isTrivial()) {
1750d635f53SJohn McCall     if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
17664225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
17764225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
17864225794SFrancois Pichet       return RValue::get(0);
1790d635f53SJohn McCall 
18064225794SFrancois Pichet     if (MD->isCopyAssignmentOperator()) {
18127da15baSAnders Carlsson       // We don't like to generate the trivial copy assignment operator when
18227da15baSAnders Carlsson       // it isn't necessary; just produce the proper effect here.
18327da15baSAnders Carlsson       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
18427da15baSAnders Carlsson       EmitAggregateCopy(This, RHS, CE->getType());
18527da15baSAnders Carlsson       return RValue::get(This);
18627da15baSAnders Carlsson     }
18727da15baSAnders Carlsson 
18864225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
18964225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
19064225794SFrancois Pichet       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
19164225794SFrancois Pichet       EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
19264225794SFrancois Pichet                                      CE->arg_begin(), CE->arg_end());
19364225794SFrancois Pichet       return RValue::get(This);
19464225794SFrancois Pichet     }
19564225794SFrancois Pichet     llvm_unreachable("unknown trivial member function");
19664225794SFrancois Pichet   }
19764225794SFrancois Pichet 
1980d635f53SJohn McCall   // Compute the function type we're calling.
19964225794SFrancois Pichet   const CGFunctionInfo *FInfo = 0;
20064225794SFrancois Pichet   if (isa<CXXDestructorDecl>(MD))
20164225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
20264225794SFrancois Pichet                                            Dtor_Complete);
20364225794SFrancois Pichet   else if (isa<CXXConstructorDecl>(MD))
20464225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
20564225794SFrancois Pichet                                             Ctor_Complete);
20664225794SFrancois Pichet   else
20764225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(MD);
2080d635f53SJohn McCall 
2090d635f53SJohn McCall   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
2100d635f53SJohn McCall   const llvm::Type *Ty
21164225794SFrancois Pichet     = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
2120d635f53SJohn McCall 
21327da15baSAnders Carlsson   // C++ [class.virtual]p12:
21427da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
21527da15baSAnders Carlsson   //   virtual call mechanism.
21627da15baSAnders Carlsson   //
21727da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
21827da15baSAnders Carlsson   // because then we know what the type is.
21947609b08SFariborz Jahanian   bool UseVirtualCall;
22047609b08SFariborz Jahanian   UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
221252a47f6SFariborz Jahanian                    && !canDevirtualizeMemberFunctionCalls(getContext(),
222252a47f6SFariborz Jahanian                                                           ME->getBase(), MD);
22327da15baSAnders Carlsson   llvm::Value *Callee;
2240d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
2250d635f53SJohn McCall     if (UseVirtualCall) {
2260d635f53SJohn McCall       Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
22727da15baSAnders Carlsson     } else {
228265c325eSFariborz Jahanian       if (getContext().getLangOptions().AppleKext &&
229265c325eSFariborz Jahanian           MD->isVirtual() &&
230265c325eSFariborz Jahanian           ME->hasQualifier())
2317f6f81baSFariborz Jahanian         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
232265c325eSFariborz Jahanian       else
2330d635f53SJohn McCall         Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
23427da15baSAnders Carlsson     }
23564225794SFrancois Pichet   } else if (const CXXConstructorDecl *Ctor =
23664225794SFrancois Pichet                dyn_cast<CXXConstructorDecl>(MD)) {
23764225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2380d635f53SJohn McCall   } else if (UseVirtualCall) {
23927da15baSAnders Carlsson       Callee = BuildVirtualCall(MD, This, Ty);
24027da15baSAnders Carlsson   } else {
241252a47f6SFariborz Jahanian     if (getContext().getLangOptions().AppleKext &&
2429f9438b3SFariborz Jahanian         MD->isVirtual() &&
243252a47f6SFariborz Jahanian         ME->hasQualifier())
2447f6f81baSFariborz Jahanian       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
245252a47f6SFariborz Jahanian     else
24627da15baSAnders Carlsson       Callee = CGM.GetAddrOfFunction(MD, Ty);
24727da15baSAnders Carlsson   }
24827da15baSAnders Carlsson 
249e36a6b3eSAnders Carlsson   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
25027da15baSAnders Carlsson                            CE->arg_begin(), CE->arg_end());
25127da15baSAnders Carlsson }
25227da15baSAnders Carlsson 
25327da15baSAnders Carlsson RValue
25427da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
25527da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
25627da15baSAnders Carlsson   const BinaryOperator *BO =
25727da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
25827da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
25927da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
26027da15baSAnders Carlsson 
26127da15baSAnders Carlsson   const MemberPointerType *MPT =
26227da15baSAnders Carlsson     MemFnExpr->getType()->getAs<MemberPointerType>();
263475999dcSJohn McCall 
26427da15baSAnders Carlsson   const FunctionProtoType *FPT =
26527da15baSAnders Carlsson     MPT->getPointeeType()->getAs<FunctionProtoType>();
26627da15baSAnders Carlsson   const CXXRecordDecl *RD =
26727da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
26827da15baSAnders Carlsson 
26927da15baSAnders Carlsson   // Get the member function pointer.
270a1dee530SJohn McCall   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
27127da15baSAnders Carlsson 
27227da15baSAnders Carlsson   // Emit the 'this' pointer.
27327da15baSAnders Carlsson   llvm::Value *This;
27427da15baSAnders Carlsson 
275e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
27627da15baSAnders Carlsson     This = EmitScalarExpr(BaseExpr);
27727da15baSAnders Carlsson   else
27827da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
27927da15baSAnders Carlsson 
280475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
281475999dcSJohn McCall   llvm::Value *Callee =
282ad7c5c16SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
28327da15baSAnders Carlsson 
28427da15baSAnders Carlsson   CallArgList Args;
28527da15baSAnders Carlsson 
28627da15baSAnders Carlsson   QualType ThisType =
28727da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
28827da15baSAnders Carlsson 
28927da15baSAnders Carlsson   // Push the this ptr.
29027da15baSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(This), ThisType));
29127da15baSAnders Carlsson 
29227da15baSAnders Carlsson   // And the rest of the call args
29327da15baSAnders Carlsson   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
294ab26cfa5SJohn McCall   const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
29599cc30c3STilmann Scheller   return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
29699cc30c3STilmann Scheller                   ReturnValue, Args);
29727da15baSAnders Carlsson }
29827da15baSAnders Carlsson 
29927da15baSAnders Carlsson RValue
30027da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
30127da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
30227da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
30327da15baSAnders Carlsson   assert(MD->isInstance() &&
30427da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
305e26a872bSJohn McCall   LValue LV = EmitLValue(E->getArg(0));
306e26a872bSJohn McCall   llvm::Value *This = LV.getAddress();
307e26a872bSJohn McCall 
308ec3bec0cSDouglas Gregor   if (MD->isCopyAssignmentOperator()) {
30927da15baSAnders Carlsson     const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
31027da15baSAnders Carlsson     if (ClassDecl->hasTrivialCopyAssignment()) {
31127da15baSAnders Carlsson       assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
31227da15baSAnders Carlsson              "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
31327da15baSAnders Carlsson       llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
31427da15baSAnders Carlsson       QualType Ty = E->getType();
31527da15baSAnders Carlsson       EmitAggregateCopy(This, Src, Ty);
31627da15baSAnders Carlsson       return RValue::get(This);
31727da15baSAnders Carlsson     }
31827da15baSAnders Carlsson   }
31927da15baSAnders Carlsson 
32027da15baSAnders Carlsson   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
32127da15baSAnders Carlsson   const llvm::Type *Ty =
32227da15baSAnders Carlsson     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
32327da15baSAnders Carlsson                                    FPT->isVariadic());
32427da15baSAnders Carlsson   llvm::Value *Callee;
32547609b08SFariborz Jahanian   if (MD->isVirtual() &&
326252a47f6SFariborz Jahanian       !canDevirtualizeMemberFunctionCalls(getContext(),
327252a47f6SFariborz Jahanian                                            E->getArg(0), MD))
32827da15baSAnders Carlsson     Callee = BuildVirtualCall(MD, This, Ty);
32927da15baSAnders Carlsson   else
33027da15baSAnders Carlsson     Callee = CGM.GetAddrOfFunction(MD, Ty);
33127da15baSAnders Carlsson 
332e36a6b3eSAnders Carlsson   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
33327da15baSAnders Carlsson                            E->arg_begin() + 1, E->arg_end());
33427da15baSAnders Carlsson }
33527da15baSAnders Carlsson 
33627da15baSAnders Carlsson void
3377a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
3387a626f63SJohn McCall                                       AggValueSlot Dest) {
3397a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
34027da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
341630c76efSDouglas Gregor 
342630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
343630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
344630c76efSDouglas Gregor   // constructor, emit the zero initialization now.
345e3b3464dSDouglas Gregor   if (E->requiresZeroInitialization())
3467a626f63SJohn McCall     EmitNullInitialization(Dest.getAddr(), E->getType());
347630c76efSDouglas Gregor 
348630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
349630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
35027da15baSAnders Carlsson     return;
351630c76efSDouglas Gregor 
3528ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
3538ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
3548ea46b66SJohn McCall   // returns.
35527da15baSAnders Carlsson   if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
3568ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
3578ea46b66SJohn McCall                                                E->getArg(0)->getType()));
3587a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
3597a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
36027da15baSAnders Carlsson       return;
36127da15baSAnders Carlsson     }
362222cf0efSDouglas Gregor   }
363630c76efSDouglas Gregor 
364630c76efSDouglas Gregor   const ConstantArrayType *Array
365630c76efSDouglas Gregor     = getContext().getAsConstantArrayType(E->getType());
36627da15baSAnders Carlsson   if (Array) {
36727da15baSAnders Carlsson     QualType BaseElementTy = getContext().getBaseElementType(Array);
36827da15baSAnders Carlsson     const llvm::Type *BasePtr = ConvertType(BaseElementTy);
36927da15baSAnders Carlsson     BasePtr = llvm::PointerType::getUnqual(BasePtr);
37027da15baSAnders Carlsson     llvm::Value *BaseAddrPtr =
3717a626f63SJohn McCall       Builder.CreateBitCast(Dest.getAddr(), BasePtr);
37227da15baSAnders Carlsson 
37327da15baSAnders Carlsson     EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
37427da15baSAnders Carlsson                                E->arg_begin(), E->arg_end());
37527da15baSAnders Carlsson   }
376e11f9ce9SAnders Carlsson   else {
377e11f9ce9SAnders Carlsson     CXXCtorType Type =
378e11f9ce9SAnders Carlsson       (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
379e11f9ce9SAnders Carlsson       ? Ctor_Complete : Ctor_Base;
380e11f9ce9SAnders Carlsson     bool ForVirtualBase =
381e11f9ce9SAnders Carlsson       E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
382e11f9ce9SAnders Carlsson 
38327da15baSAnders Carlsson     // Call the constructor.
3847a626f63SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
38527da15baSAnders Carlsson                            E->arg_begin(), E->arg_end());
38627da15baSAnders Carlsson   }
387e11f9ce9SAnders Carlsson }
38827da15baSAnders Carlsson 
389e988bdacSFariborz Jahanian void
390e988bdacSFariborz Jahanian CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
391e988bdacSFariborz Jahanian                                             llvm::Value *Src,
39250198098SFariborz Jahanian                                             const Expr *Exp) {
3935d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
394e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
395e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
396e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
397e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
398e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
399e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
400e988bdacSFariborz Jahanian 
401e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
402e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
403e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
404e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
405e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
406e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
407e988bdacSFariborz Jahanian 
40899da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
40999da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
410e988bdacSFariborz Jahanian   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
411e988bdacSFariborz Jahanian                                  E->arg_begin(), E->arg_end());
412e988bdacSFariborz Jahanian }
413e988bdacSFariborz Jahanian 
414aa4149a2SJohn McCall /// Check whether the given operator new[] is the global placement
415aa4149a2SJohn McCall /// operator new[].
416aa4149a2SJohn McCall static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
417aa4149a2SJohn McCall                                         const FunctionDecl *Fn) {
418aa4149a2SJohn McCall   // Must be in global scope.  Note that allocation functions can't be
419aa4149a2SJohn McCall   // declared in namespaces.
42050c68258SSebastian Redl   if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
421aa4149a2SJohn McCall     return false;
422aa4149a2SJohn McCall 
423aa4149a2SJohn McCall   // Signature must be void *operator new[](size_t, void*).
424aa4149a2SJohn McCall   // The size_t is common to all operator new[]s.
425aa4149a2SJohn McCall   if (Fn->getNumParams() != 2)
426aa4149a2SJohn McCall     return false;
427aa4149a2SJohn McCall 
428aa4149a2SJohn McCall   CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
429aa4149a2SJohn McCall   return (ParamType == Ctx.VoidPtrTy);
430aa4149a2SJohn McCall }
431aa4149a2SJohn McCall 
4328ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4338ed55a54SJohn McCall                                         const CXXNewExpr *E) {
43421122cf6SAnders Carlsson   if (!E->isArray())
4353eb55cfeSKen Dyck     return CharUnits::Zero();
43621122cf6SAnders Carlsson 
437399f499fSAnders Carlsson   // No cookie is required if the new operator being used is
438399f499fSAnders Carlsson   // ::operator new[](size_t, void*).
439399f499fSAnders Carlsson   const FunctionDecl *OperatorNew = E->getOperatorNew();
4408ed55a54SJohn McCall   if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
4413eb55cfeSKen Dyck     return CharUnits::Zero();
442399f499fSAnders Carlsson 
443284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
44459486a2dSAnders Carlsson }
44559486a2dSAnders Carlsson 
44647b4629bSFariborz Jahanian static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
44747b4629bSFariborz Jahanian                                         CodeGenFunction &CGF,
44859486a2dSAnders Carlsson                                         const CXXNewExpr *E,
44905fc5be3SDouglas Gregor                                         llvm::Value *&NumElements,
45005fc5be3SDouglas Gregor                                         llvm::Value *&SizeWithoutCookie) {
4517648fb46SArgyrios Kyrtzidis   QualType ElemType = E->getAllocatedType();
45259486a2dSAnders Carlsson 
4538ed55a54SJohn McCall   const llvm::IntegerType *SizeTy =
4548ed55a54SJohn McCall     cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
4558ed55a54SJohn McCall 
4567648fb46SArgyrios Kyrtzidis   CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
4578ed55a54SJohn McCall 
4588ed55a54SJohn McCall   if (!E->isArray()) {
45905fc5be3SDouglas Gregor     SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
46005fc5be3SDouglas Gregor     return SizeWithoutCookie;
46105fc5be3SDouglas Gregor   }
46259486a2dSAnders Carlsson 
4638ed55a54SJohn McCall   // Figure out the cookie size.
4648ed55a54SJohn McCall   CharUnits CookieSize = CalculateCookiePadding(CGF, E);
4658ed55a54SJohn McCall 
46659486a2dSAnders Carlsson   // Emit the array size expression.
4677648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
4687648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
46959486a2dSAnders Carlsson   NumElements = CGF.EmitScalarExpr(E->getArraySize());
4708ed55a54SJohn McCall   assert(NumElements->getType() == SizeTy && "element count not a size_t");
4718ed55a54SJohn McCall 
4728ed55a54SJohn McCall   uint64_t ArraySizeMultiplier = 1;
4737648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
4747648fb46SArgyrios Kyrtzidis              = CGF.getContext().getAsConstantArrayType(ElemType)) {
4757648fb46SArgyrios Kyrtzidis     ElemType = CAT->getElementType();
4768ed55a54SJohn McCall     ArraySizeMultiplier *= CAT->getSize().getZExtValue();
4777648fb46SArgyrios Kyrtzidis   }
47859486a2dSAnders Carlsson 
4798ed55a54SJohn McCall   llvm::Value *Size;
48032ac583dSChris Lattner 
48132ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
48232ac583dSChris Lattner   // Don't bloat the -O0 code.
48332ac583dSChris Lattner   if (llvm::ConstantInt *NumElementsC =
48432ac583dSChris Lattner         dyn_cast<llvm::ConstantInt>(NumElements)) {
48532ac583dSChris Lattner     llvm::APInt NEC = NumElementsC->getValue();
4868ed55a54SJohn McCall     unsigned SizeWidth = NEC.getBitWidth();
48732ac583dSChris Lattner 
4888ed55a54SJohn McCall     // Determine if there is an overflow here by doing an extended multiply.
4896d4db0c8SJay Foad     NEC = NEC.zext(SizeWidth*2);
4908ed55a54SJohn McCall     llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
49132ac583dSChris Lattner     SC *= NEC;
49232ac583dSChris Lattner 
4938ed55a54SJohn McCall     if (!CookieSize.isZero()) {
4948ed55a54SJohn McCall       // Save the current size without a cookie.  We don't care if an
4958ed55a54SJohn McCall       // overflow's already happened because SizeWithoutCookie isn't
4968ed55a54SJohn McCall       // used if the allocator returns null or throws, as it should
4978ed55a54SJohn McCall       // always do on an overflow.
4986d4db0c8SJay Foad       llvm::APInt SWC = SC.trunc(SizeWidth);
4998ed55a54SJohn McCall       SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
5008ed55a54SJohn McCall 
5018ed55a54SJohn McCall       // Add the cookie size.
5028ed55a54SJohn McCall       SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
5038ed55a54SJohn McCall     }
5048ed55a54SJohn McCall 
5058ed55a54SJohn McCall     if (SC.countLeadingZeros() >= SizeWidth) {
5066d4db0c8SJay Foad       SC = SC.trunc(SizeWidth);
5078ed55a54SJohn McCall       Size = llvm::ConstantInt::get(SizeTy, SC);
50832ac583dSChris Lattner     } else {
50932ac583dSChris Lattner       // On overflow, produce a -1 so operator new throws.
5108ed55a54SJohn McCall       Size = llvm::Constant::getAllOnesValue(SizeTy);
51132ac583dSChris Lattner     }
51232ac583dSChris Lattner 
5138ed55a54SJohn McCall     // Scale NumElements while we're at it.
5148ed55a54SJohn McCall     uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
5158ed55a54SJohn McCall     NumElements = llvm::ConstantInt::get(SizeTy, N);
51647b4629bSFariborz Jahanian 
5178ed55a54SJohn McCall   // Otherwise, we don't need to do an overflow-checked multiplication if
5188ed55a54SJohn McCall   // we're multiplying by one.
5198ed55a54SJohn McCall   } else if (TypeSize.isOne()) {
5208ed55a54SJohn McCall     assert(ArraySizeMultiplier == 1);
521f2f38701SChris Lattner 
5228ed55a54SJohn McCall     Size = NumElements;
523f2f38701SChris Lattner 
5248ed55a54SJohn McCall     // If we need a cookie, add its size in with an overflow check.
5258ed55a54SJohn McCall     // This is maybe a little paranoid.
5268ed55a54SJohn McCall     if (!CookieSize.isZero()) {
52705fc5be3SDouglas Gregor       SizeWithoutCookie = Size;
528f2f38701SChris Lattner 
5298ed55a54SJohn McCall       llvm::Value *CookieSizeV
5308ed55a54SJohn McCall         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
5318ed55a54SJohn McCall 
5328ed55a54SJohn McCall       const llvm::Type *Types[] = { SizeTy };
5338ed55a54SJohn McCall       llvm::Value *UAddF
5348ed55a54SJohn McCall         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
5358ed55a54SJohn McCall       llvm::Value *AddRes
5368ed55a54SJohn McCall         = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
5378ed55a54SJohn McCall 
5388ed55a54SJohn McCall       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
5398ed55a54SJohn McCall       llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
5408ed55a54SJohn McCall       Size = CGF.Builder.CreateSelect(DidOverflow,
5418ed55a54SJohn McCall                                       llvm::ConstantInt::get(SizeTy, -1),
5428ed55a54SJohn McCall                                       Size);
5438ed55a54SJohn McCall     }
5448ed55a54SJohn McCall 
5458ed55a54SJohn McCall   // Otherwise use the int.umul.with.overflow intrinsic.
5468ed55a54SJohn McCall   } else {
5478ed55a54SJohn McCall     llvm::Value *OutermostElementSize
5488ed55a54SJohn McCall       = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
5498ed55a54SJohn McCall 
5508ed55a54SJohn McCall     llvm::Value *NumOutermostElements = NumElements;
5518ed55a54SJohn McCall 
5528ed55a54SJohn McCall     // Scale NumElements by the array size multiplier.  This might
5538ed55a54SJohn McCall     // overflow, but only if the multiplication below also overflows,
5548ed55a54SJohn McCall     // in which case this multiplication isn't used.
5558ed55a54SJohn McCall     if (ArraySizeMultiplier != 1)
5568ed55a54SJohn McCall       NumElements = CGF.Builder.CreateMul(NumElements,
5578ed55a54SJohn McCall                          llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
5588ed55a54SJohn McCall 
5598ed55a54SJohn McCall     // The requested size of the outermost array is non-constant.
5608ed55a54SJohn McCall     // Multiply that by the static size of the elements of that array;
5618ed55a54SJohn McCall     // on unsigned overflow, set the size to -1 to trigger an
5628ed55a54SJohn McCall     // exception from the allocation routine.  This is sufficient to
5638ed55a54SJohn McCall     // prevent buffer overruns from the allocator returning a
5648ed55a54SJohn McCall     // seemingly valid pointer to insufficient space.  This idea comes
5658ed55a54SJohn McCall     // originally from MSVC, and GCC has an open bug requesting
5668ed55a54SJohn McCall     // similar behavior:
5678ed55a54SJohn McCall     //   http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
5688ed55a54SJohn McCall     //
5698ed55a54SJohn McCall     // This will not be sufficient for C++0x, which requires a
5708ed55a54SJohn McCall     // specific exception class (std::bad_array_new_length).
5718ed55a54SJohn McCall     // That will require ABI support that has not yet been specified.
5728ed55a54SJohn McCall     const llvm::Type *Types[] = { SizeTy };
5738ed55a54SJohn McCall     llvm::Value *UMulF
5748ed55a54SJohn McCall       = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
5758ed55a54SJohn McCall     llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
5768ed55a54SJohn McCall                                                   OutermostElementSize);
5778ed55a54SJohn McCall 
5788ed55a54SJohn McCall     // The overflow bit.
5798ed55a54SJohn McCall     llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
5808ed55a54SJohn McCall 
5818ed55a54SJohn McCall     // The result of the multiplication.
5828ed55a54SJohn McCall     Size = CGF.Builder.CreateExtractValue(MulRes, 0);
5838ed55a54SJohn McCall 
5848ed55a54SJohn McCall     // If we have a cookie, we need to add that size in, too.
5858ed55a54SJohn McCall     if (!CookieSize.isZero()) {
5868ed55a54SJohn McCall       SizeWithoutCookie = Size;
5878ed55a54SJohn McCall 
5888ed55a54SJohn McCall       llvm::Value *CookieSizeV
5898ed55a54SJohn McCall         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
5908ed55a54SJohn McCall       llvm::Value *UAddF
5918ed55a54SJohn McCall         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
5928ed55a54SJohn McCall       llvm::Value *AddRes
5938ed55a54SJohn McCall         = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
5948ed55a54SJohn McCall 
5958ed55a54SJohn McCall       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
5968ed55a54SJohn McCall 
5978ed55a54SJohn McCall       llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
5988ed55a54SJohn McCall       DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
5998ed55a54SJohn McCall     }
6008ed55a54SJohn McCall 
6018ed55a54SJohn McCall     Size = CGF.Builder.CreateSelect(DidOverflow,
6028ed55a54SJohn McCall                                     llvm::ConstantInt::get(SizeTy, -1),
6038ed55a54SJohn McCall                                     Size);
6048ed55a54SJohn McCall   }
6058ed55a54SJohn McCall 
6068ed55a54SJohn McCall   if (CookieSize.isZero())
6078ed55a54SJohn McCall     SizeWithoutCookie = Size;
6088ed55a54SJohn McCall   else
6098ed55a54SJohn McCall     assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
61059486a2dSAnders Carlsson 
61132ac583dSChris Lattner   return Size;
61259486a2dSAnders Carlsson }
61359486a2dSAnders Carlsson 
614d5202e09SFariborz Jahanian static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
615d5202e09SFariborz Jahanian                                     llvm::Value *NewPtr) {
616d5202e09SFariborz Jahanian 
617d5202e09SFariborz Jahanian   assert(E->getNumConstructorArgs() == 1 &&
618d5202e09SFariborz Jahanian          "Can only have one argument to initializer of POD type.");
619d5202e09SFariborz Jahanian 
620d5202e09SFariborz Jahanian   const Expr *Init = E->getConstructorArg(0);
621d5202e09SFariborz Jahanian   QualType AllocType = E->getAllocatedType();
622d5202e09SFariborz Jahanian 
6230381634aSDaniel Dunbar   unsigned Alignment =
6240381634aSDaniel Dunbar     CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
625d5202e09SFariborz Jahanian   if (!CGF.hasAggregateLLVMType(AllocType))
626d5202e09SFariborz Jahanian     CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
6270381634aSDaniel Dunbar                           AllocType.isVolatileQualified(), Alignment,
6280381634aSDaniel Dunbar                           AllocType);
629d5202e09SFariborz Jahanian   else if (AllocType->isAnyComplexType())
630d5202e09SFariborz Jahanian     CGF.EmitComplexExprIntoAddr(Init, NewPtr,
631d5202e09SFariborz Jahanian                                 AllocType.isVolatileQualified());
6327a626f63SJohn McCall   else {
6337a626f63SJohn McCall     AggValueSlot Slot
6347a626f63SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
6357a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
6367a626f63SJohn McCall   }
637d5202e09SFariborz Jahanian }
638d5202e09SFariborz Jahanian 
639d5202e09SFariborz Jahanian void
640d5202e09SFariborz Jahanian CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
641d5202e09SFariborz Jahanian                                          llvm::Value *NewPtr,
642d5202e09SFariborz Jahanian                                          llvm::Value *NumElements) {
643b66b08efSFariborz Jahanian   // We have a POD type.
644b66b08efSFariborz Jahanian   if (E->getNumConstructorArgs() == 0)
645b66b08efSFariborz Jahanian     return;
646b66b08efSFariborz Jahanian 
647d5202e09SFariborz Jahanian   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
648d5202e09SFariborz Jahanian 
649d5202e09SFariborz Jahanian   // Create a temporary for the loop index and initialize it with 0.
650d5202e09SFariborz Jahanian   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
651d5202e09SFariborz Jahanian   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
652d5202e09SFariborz Jahanian   Builder.CreateStore(Zero, IndexPtr);
653d5202e09SFariborz Jahanian 
654d5202e09SFariborz Jahanian   // Start the loop with a block that tests the condition.
655d5202e09SFariborz Jahanian   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
656d5202e09SFariborz Jahanian   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
657d5202e09SFariborz Jahanian 
658d5202e09SFariborz Jahanian   EmitBlock(CondBlock);
659d5202e09SFariborz Jahanian 
660d5202e09SFariborz Jahanian   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
661d5202e09SFariborz Jahanian 
662d5202e09SFariborz Jahanian   // Generate: if (loop-index < number-of-elements fall to the loop body,
663d5202e09SFariborz Jahanian   // otherwise, go to the block after the for-loop.
664d5202e09SFariborz Jahanian   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
665d5202e09SFariborz Jahanian   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
666d5202e09SFariborz Jahanian   // If the condition is true, execute the body.
667d5202e09SFariborz Jahanian   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
668d5202e09SFariborz Jahanian 
669d5202e09SFariborz Jahanian   EmitBlock(ForBody);
670d5202e09SFariborz Jahanian 
671d5202e09SFariborz Jahanian   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
672d5202e09SFariborz Jahanian   // Inside the loop body, emit the constructor call on the array element.
673d5202e09SFariborz Jahanian   Counter = Builder.CreateLoad(IndexPtr);
674d5202e09SFariborz Jahanian   llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
675d5202e09SFariborz Jahanian                                                    "arrayidx");
676d5202e09SFariborz Jahanian   StoreAnyExprIntoOneUnit(*this, E, Address);
677d5202e09SFariborz Jahanian 
678d5202e09SFariborz Jahanian   EmitBlock(ContinueBlock);
679d5202e09SFariborz Jahanian 
680d5202e09SFariborz Jahanian   // Emit the increment of the loop counter.
681d5202e09SFariborz Jahanian   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
682d5202e09SFariborz Jahanian   Counter = Builder.CreateLoad(IndexPtr);
683d5202e09SFariborz Jahanian   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
684d5202e09SFariborz Jahanian   Builder.CreateStore(NextVal, IndexPtr);
685d5202e09SFariborz Jahanian 
686d5202e09SFariborz Jahanian   // Finally, branch back up to the condition for the next iteration.
687d5202e09SFariborz Jahanian   EmitBranch(CondBlock);
688d5202e09SFariborz Jahanian 
689d5202e09SFariborz Jahanian   // Emit the fall-through block.
690d5202e09SFariborz Jahanian   EmitBlock(AfterFor, true);
691d5202e09SFariborz Jahanian }
692d5202e09SFariborz Jahanian 
69305fc5be3SDouglas Gregor static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
69405fc5be3SDouglas Gregor                            llvm::Value *NewPtr, llvm::Value *Size) {
695ad7c5c16SJohn McCall   CGF.EmitCastToVoidPtr(NewPtr);
696705ba07eSKen Dyck   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
697acc6b4e2SBenjamin Kramer   CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
698705ba07eSKen Dyck                            Alignment.getQuantity(), false);
69905fc5be3SDouglas Gregor }
70005fc5be3SDouglas Gregor 
70159486a2dSAnders Carlsson static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
70259486a2dSAnders Carlsson                                llvm::Value *NewPtr,
70305fc5be3SDouglas Gregor                                llvm::Value *NumElements,
70405fc5be3SDouglas Gregor                                llvm::Value *AllocSizeWithoutCookie) {
7053a202f60SAnders Carlsson   if (E->isArray()) {
706d040e6b2SAnders Carlsson     if (CXXConstructorDecl *Ctor = E->getConstructor()) {
70705fc5be3SDouglas Gregor       bool RequiresZeroInitialization = false;
70805fc5be3SDouglas Gregor       if (Ctor->getParent()->hasTrivialConstructor()) {
70905fc5be3SDouglas Gregor         // If new expression did not specify value-initialization, then there
71005fc5be3SDouglas Gregor         // is no initialization.
71105fc5be3SDouglas Gregor         if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
71205fc5be3SDouglas Gregor           return;
71305fc5be3SDouglas Gregor 
714614dbdcdSJohn McCall         if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
71505fc5be3SDouglas Gregor           // Optimization: since zero initialization will just set the memory
71605fc5be3SDouglas Gregor           // to all zeroes, generate a single memset to do it in one shot.
71705fc5be3SDouglas Gregor           EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
71805fc5be3SDouglas Gregor                          AllocSizeWithoutCookie);
7193a202f60SAnders Carlsson           return;
7203a202f60SAnders Carlsson         }
72105fc5be3SDouglas Gregor 
72205fc5be3SDouglas Gregor         RequiresZeroInitialization = true;
72305fc5be3SDouglas Gregor       }
72405fc5be3SDouglas Gregor 
72505fc5be3SDouglas Gregor       CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
72605fc5be3SDouglas Gregor                                      E->constructor_arg_begin(),
72705fc5be3SDouglas Gregor                                      E->constructor_arg_end(),
72805fc5be3SDouglas Gregor                                      RequiresZeroInitialization);
72905fc5be3SDouglas Gregor       return;
73005fc5be3SDouglas Gregor     } else if (E->getNumConstructorArgs() == 1 &&
73105fc5be3SDouglas Gregor                isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
73205fc5be3SDouglas Gregor       // Optimization: since zero initialization will just set the memory
73305fc5be3SDouglas Gregor       // to all zeroes, generate a single memset to do it in one shot.
73405fc5be3SDouglas Gregor       EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
73505fc5be3SDouglas Gregor                      AllocSizeWithoutCookie);
73605fc5be3SDouglas Gregor       return;
73705fc5be3SDouglas Gregor     } else {
738d5202e09SFariborz Jahanian       CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
739d5202e09SFariborz Jahanian       return;
740d040e6b2SAnders Carlsson     }
741d5202e09SFariborz Jahanian   }
74259486a2dSAnders Carlsson 
74359486a2dSAnders Carlsson   if (CXXConstructorDecl *Ctor = E->getConstructor()) {
744747eb784SDouglas Gregor     // Per C++ [expr.new]p15, if we have an initializer, then we're performing
745747eb784SDouglas Gregor     // direct initialization. C++ [dcl.init]p5 requires that we
746747eb784SDouglas Gregor     // zero-initialize storage if there are no user-declared constructors.
747747eb784SDouglas Gregor     if (E->hasInitializer() &&
748747eb784SDouglas Gregor         !Ctor->getParent()->hasUserDeclaredConstructor() &&
749747eb784SDouglas Gregor         !Ctor->getParent()->isEmpty())
750747eb784SDouglas Gregor       CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
751747eb784SDouglas Gregor 
752e11f9ce9SAnders Carlsson     CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
753e11f9ce9SAnders Carlsson                                NewPtr, E->constructor_arg_begin(),
75459486a2dSAnders Carlsson                                E->constructor_arg_end());
75559486a2dSAnders Carlsson 
75659486a2dSAnders Carlsson     return;
75759486a2dSAnders Carlsson   }
758b66b08efSFariborz Jahanian   // We have a POD type.
759b66b08efSFariborz Jahanian   if (E->getNumConstructorArgs() == 0)
760b66b08efSFariborz Jahanian     return;
76159486a2dSAnders Carlsson 
762d5202e09SFariborz Jahanian   StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
76359486a2dSAnders Carlsson }
76459486a2dSAnders Carlsson 
765824c2f53SJohn McCall namespace {
766824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
767824c2f53SJohn McCall   /// abnormal exit from a new expression.
768824c2f53SJohn McCall   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
769824c2f53SJohn McCall     size_t NumPlacementArgs;
770824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
771824c2f53SJohn McCall     llvm::Value *Ptr;
772824c2f53SJohn McCall     llvm::Value *AllocSize;
773824c2f53SJohn McCall 
774824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
775824c2f53SJohn McCall 
776824c2f53SJohn McCall   public:
777824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
778824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
779824c2f53SJohn McCall     }
780824c2f53SJohn McCall 
781824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
782824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
783824c2f53SJohn McCall                         llvm::Value *Ptr,
784824c2f53SJohn McCall                         llvm::Value *AllocSize)
785824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
786824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
787824c2f53SJohn McCall 
788824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
789824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
790824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
791824c2f53SJohn McCall     }
792824c2f53SJohn McCall 
793824c2f53SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
794824c2f53SJohn McCall       const FunctionProtoType *FPT
795824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
796824c2f53SJohn McCall       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
797d441b1e6SJohn McCall              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
798824c2f53SJohn McCall 
799824c2f53SJohn McCall       CallArgList DeleteArgs;
800824c2f53SJohn McCall 
801824c2f53SJohn McCall       // The first argument is always a void*.
802824c2f53SJohn McCall       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
803824c2f53SJohn McCall       DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
804824c2f53SJohn McCall 
805824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
806824c2f53SJohn McCall       if (FPT->getNumArgs() == NumPlacementArgs + 2)
807824c2f53SJohn McCall         DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
808824c2f53SJohn McCall 
809824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
810824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
811824c2f53SJohn McCall         DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
812824c2f53SJohn McCall 
813824c2f53SJohn McCall       // Call 'operator delete'.
81499cc30c3STilmann Scheller       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
815824c2f53SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
816824c2f53SJohn McCall                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
817824c2f53SJohn McCall     }
818824c2f53SJohn McCall   };
8197f9c92a9SJohn McCall 
8207f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
8217f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
8227f9c92a9SJohn McCall   /// conditional.
8237f9c92a9SJohn McCall   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
8247f9c92a9SJohn McCall     size_t NumPlacementArgs;
8257f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
826cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
827cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
8287f9c92a9SJohn McCall 
829cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
830cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
8317f9c92a9SJohn McCall     }
8327f9c92a9SJohn McCall 
8337f9c92a9SJohn McCall   public:
8347f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
835cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
8367f9c92a9SJohn McCall     }
8377f9c92a9SJohn McCall 
8387f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
8397f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
840cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
841cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
8427f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
8437f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
8447f9c92a9SJohn McCall 
845cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
8467f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
8477f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
8487f9c92a9SJohn McCall     }
8497f9c92a9SJohn McCall 
8507f9c92a9SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
8517f9c92a9SJohn McCall       const FunctionProtoType *FPT
8527f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
8537f9c92a9SJohn McCall       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
8547f9c92a9SJohn McCall              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
8557f9c92a9SJohn McCall 
8567f9c92a9SJohn McCall       CallArgList DeleteArgs;
8577f9c92a9SJohn McCall 
8587f9c92a9SJohn McCall       // The first argument is always a void*.
8597f9c92a9SJohn McCall       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
860cb5f77f0SJohn McCall       DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
8617f9c92a9SJohn McCall 
8627f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
8637f9c92a9SJohn McCall       if (FPT->getNumArgs() == NumPlacementArgs + 2) {
864cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
8657f9c92a9SJohn McCall         DeleteArgs.push_back(std::make_pair(RV, *AI++));
8667f9c92a9SJohn McCall       }
8677f9c92a9SJohn McCall 
8687f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
8697f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
870cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
8717f9c92a9SJohn McCall         DeleteArgs.push_back(std::make_pair(RV, *AI++));
8727f9c92a9SJohn McCall       }
8737f9c92a9SJohn McCall 
8747f9c92a9SJohn McCall       // Call 'operator delete'.
87599cc30c3STilmann Scheller       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
8767f9c92a9SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
8777f9c92a9SJohn McCall                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
8787f9c92a9SJohn McCall     }
8797f9c92a9SJohn McCall   };
8807f9c92a9SJohn McCall }
8817f9c92a9SJohn McCall 
8827f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
8837f9c92a9SJohn McCall /// new-expression throws.
8847f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
8857f9c92a9SJohn McCall                                   const CXXNewExpr *E,
8867f9c92a9SJohn McCall                                   llvm::Value *NewPtr,
8877f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
8887f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
8897f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
8907f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
8917f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
8927f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
8937f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
8947f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
8957f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
8967f9c92a9SJohn McCall                                                  NewPtr, AllocSize);
8977f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
8987f9c92a9SJohn McCall       Cleanup->setPlacementArg(I, NewArgs[I+1].first);
8997f9c92a9SJohn McCall 
9007f9c92a9SJohn McCall     return;
9017f9c92a9SJohn McCall   }
9027f9c92a9SJohn McCall 
9037f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
904cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
905cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
906cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
907cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
9087f9c92a9SJohn McCall 
9097f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
9107f9c92a9SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
9117f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
9127f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
9137f9c92a9SJohn McCall                                                  SavedNewPtr,
9147f9c92a9SJohn McCall                                                  SavedAllocSize);
9157f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
916cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
917cb5f77f0SJohn McCall                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
9187f9c92a9SJohn McCall 
9197f9c92a9SJohn McCall   CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
920824c2f53SJohn McCall }
921824c2f53SJohn McCall 
92259486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
92375f9498aSJohn McCall   // The element type being allocated.
92475f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
9258ed55a54SJohn McCall 
92675f9498aSJohn McCall   // 1. Build a call to the allocation function.
92775f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
92875f9498aSJohn McCall   const FunctionProtoType *allocatorType =
92975f9498aSJohn McCall     allocator->getType()->castAs<FunctionProtoType>();
93059486a2dSAnders Carlsson 
93175f9498aSJohn McCall   CallArgList allocatorArgs;
93259486a2dSAnders Carlsson 
93359486a2dSAnders Carlsson   // The allocation size is the first argument.
93475f9498aSJohn McCall   QualType sizeType = getContext().getSizeType();
93559486a2dSAnders Carlsson 
93675f9498aSJohn McCall   llvm::Value *numElements = 0;
93775f9498aSJohn McCall   llvm::Value *allocSizeWithoutCookie = 0;
93875f9498aSJohn McCall   llvm::Value *allocSize =
93975f9498aSJohn McCall     EmitCXXNewAllocSize(getContext(), *this, E, numElements,
94075f9498aSJohn McCall                         allocSizeWithoutCookie);
94159486a2dSAnders Carlsson 
94275f9498aSJohn McCall   allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
94359486a2dSAnders Carlsson 
94459486a2dSAnders Carlsson   // Emit the rest of the arguments.
94559486a2dSAnders Carlsson   // FIXME: Ideally, this should just use EmitCallArgs.
94675f9498aSJohn McCall   CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
94759486a2dSAnders Carlsson 
94859486a2dSAnders Carlsson   // First, use the types from the function type.
94959486a2dSAnders Carlsson   // We start at 1 here because the first argument (the allocation size)
95059486a2dSAnders Carlsson   // has already been emitted.
95175f9498aSJohn McCall   for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
95275f9498aSJohn McCall        ++i, ++placementArg) {
95375f9498aSJohn McCall     QualType argType = allocatorType->getArgType(i);
95459486a2dSAnders Carlsson 
95575f9498aSJohn McCall     assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
95675f9498aSJohn McCall                                                placementArg->getType()) &&
95759486a2dSAnders Carlsson            "type mismatch in call argument!");
95859486a2dSAnders Carlsson 
959*32ea9694SJohn McCall     EmitCallArg(allocatorArgs, *placementArg, argType);
96059486a2dSAnders Carlsson   }
96159486a2dSAnders Carlsson 
96259486a2dSAnders Carlsson   // Either we've emitted all the call args, or we have a call to a
96359486a2dSAnders Carlsson   // variadic function.
96475f9498aSJohn McCall   assert((placementArg == E->placement_arg_end() ||
96575f9498aSJohn McCall           allocatorType->isVariadic()) &&
96675f9498aSJohn McCall          "Extra arguments to non-variadic function!");
96759486a2dSAnders Carlsson 
96859486a2dSAnders Carlsson   // If we still have any arguments, emit them using the type of the argument.
96975f9498aSJohn McCall   for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
97075f9498aSJohn McCall        placementArg != placementArgsEnd; ++placementArg) {
971*32ea9694SJohn McCall     EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
97259486a2dSAnders Carlsson   }
97359486a2dSAnders Carlsson 
97475f9498aSJohn McCall   // Emit the allocation call.
97559486a2dSAnders Carlsson   RValue RV =
97675f9498aSJohn McCall     EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
97775f9498aSJohn McCall              CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
97875f9498aSJohn McCall              allocatorArgs, allocator);
97959486a2dSAnders Carlsson 
98075f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
98175f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
98275f9498aSJohn McCall   // exception spec; for this part, we inline
98375f9498aSJohn McCall   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
98475f9498aSJohn McCall   // interesting initializer.
98575f9498aSJohn McCall   bool nullCheck = allocatorType->hasNonThrowingExceptionSpec() &&
98675f9498aSJohn McCall     !(allocType->isPODType() && !E->hasInitializer());
98759486a2dSAnders Carlsson 
98875f9498aSJohn McCall   llvm::BasicBlock *nullCheckBB = 0;
98975f9498aSJohn McCall   llvm::BasicBlock *contBB = 0;
99059486a2dSAnders Carlsson 
99175f9498aSJohn McCall   llvm::Value *allocation = RV.getScalarVal();
99275f9498aSJohn McCall   unsigned AS =
99375f9498aSJohn McCall     cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
99459486a2dSAnders Carlsson 
995f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
996f7dcf320SJohn McCall   // evaluated.
997f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
998f7dcf320SJohn McCall 
99975f9498aSJohn McCall   if (nullCheck) {
1000f7dcf320SJohn McCall     conditional.begin(*this);
100175f9498aSJohn McCall 
100275f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
100375f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
100475f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
100575f9498aSJohn McCall 
100675f9498aSJohn McCall     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
100775f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
100875f9498aSJohn McCall     EmitBlock(notNullBB);
100959486a2dSAnders Carlsson   }
101059486a2dSAnders Carlsson 
101175f9498aSJohn McCall   assert((allocSize == allocSizeWithoutCookie) ==
10128ed55a54SJohn McCall          CalculateCookiePadding(*this, E).isZero());
101375f9498aSJohn McCall   if (allocSize != allocSizeWithoutCookie) {
10148ed55a54SJohn McCall     assert(E->isArray());
101575f9498aSJohn McCall     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
101675f9498aSJohn McCall                                                        numElements,
101775f9498aSJohn McCall                                                        E, allocType);
101859486a2dSAnders Carlsson   }
101959486a2dSAnders Carlsson 
1020824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1021824c2f53SJohn McCall   // exception is thrown.
102275f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
1023824c2f53SJohn McCall   if (E->getOperatorDelete()) {
102475f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
102575f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1026824c2f53SJohn McCall   }
1027824c2f53SJohn McCall 
102875f9498aSJohn McCall   const llvm::Type *elementPtrTy
102975f9498aSJohn McCall     = ConvertTypeForMem(allocType)->getPointerTo(AS);
103075f9498aSJohn McCall   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
1031824c2f53SJohn McCall 
10328ed55a54SJohn McCall   if (E->isArray()) {
103375f9498aSJohn McCall     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
10348ed55a54SJohn McCall 
10358ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
10368ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
10378ed55a54SJohn McCall     // array pointer type.
103875f9498aSJohn McCall     const llvm::Type *resultType = ConvertTypeForMem(E->getType());
103975f9498aSJohn McCall     if (result->getType() != resultType)
104075f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
10418ed55a54SJohn McCall   } else {
104275f9498aSJohn McCall     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
104347b4629bSFariborz Jahanian   }
104459486a2dSAnders Carlsson 
1045824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1046824c2f53SJohn McCall   // initialization.
104775f9498aSJohn McCall   if (operatorDeleteCleanup.isValid())
104875f9498aSJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup);
1049824c2f53SJohn McCall 
105075f9498aSJohn McCall   if (nullCheck) {
1051f7dcf320SJohn McCall     conditional.end(*this);
1052f7dcf320SJohn McCall 
105375f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
105475f9498aSJohn McCall     EmitBlock(contBB);
105559486a2dSAnders Carlsson 
105675f9498aSJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(result->getType());
105759486a2dSAnders Carlsson     PHI->reserveOperandSpace(2);
105875f9498aSJohn McCall     PHI->addIncoming(result, notNullBB);
105975f9498aSJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
106075f9498aSJohn McCall                      nullCheckBB);
106159486a2dSAnders Carlsson 
106275f9498aSJohn McCall     result = PHI;
106359486a2dSAnders Carlsson   }
106459486a2dSAnders Carlsson 
106575f9498aSJohn McCall   return result;
106659486a2dSAnders Carlsson }
106759486a2dSAnders Carlsson 
106859486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
106959486a2dSAnders Carlsson                                      llvm::Value *Ptr,
107059486a2dSAnders Carlsson                                      QualType DeleteTy) {
10718ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
10728ed55a54SJohn McCall 
107359486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
107459486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
107559486a2dSAnders Carlsson 
107659486a2dSAnders Carlsson   CallArgList DeleteArgs;
107759486a2dSAnders Carlsson 
107821122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
107921122cf6SAnders Carlsson   llvm::Value *Size = 0;
108021122cf6SAnders Carlsson   QualType SizeTy;
108121122cf6SAnders Carlsson   if (DeleteFTy->getNumArgs() == 2) {
108221122cf6SAnders Carlsson     SizeTy = DeleteFTy->getArgType(1);
10837df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
10847df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
10857df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
108621122cf6SAnders Carlsson   }
108721122cf6SAnders Carlsson 
108859486a2dSAnders Carlsson   QualType ArgTy = DeleteFTy->getArgType(0);
108959486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
109059486a2dSAnders Carlsson   DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
109159486a2dSAnders Carlsson 
109221122cf6SAnders Carlsson   if (Size)
109359486a2dSAnders Carlsson     DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
109459486a2dSAnders Carlsson 
109559486a2dSAnders Carlsson   // Emit the call to delete.
109699cc30c3STilmann Scheller   EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
109761a401caSAnders Carlsson            CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
109859486a2dSAnders Carlsson            DeleteArgs, DeleteFD);
109959486a2dSAnders Carlsson }
110059486a2dSAnders Carlsson 
11018ed55a54SJohn McCall namespace {
11028ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
11038ed55a54SJohn McCall   struct CallObjectDelete : EHScopeStack::Cleanup {
11048ed55a54SJohn McCall     llvm::Value *Ptr;
11058ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
11068ed55a54SJohn McCall     QualType ElementType;
11078ed55a54SJohn McCall 
11088ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
11098ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
11108ed55a54SJohn McCall                      QualType ElementType)
11118ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
11128ed55a54SJohn McCall 
11138ed55a54SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
11148ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
11158ed55a54SJohn McCall     }
11168ed55a54SJohn McCall   };
11178ed55a54SJohn McCall }
11188ed55a54SJohn McCall 
11198ed55a54SJohn McCall /// Emit the code for deleting a single object.
11208ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
11218ed55a54SJohn McCall                              const FunctionDecl *OperatorDelete,
11228ed55a54SJohn McCall                              llvm::Value *Ptr,
11238ed55a54SJohn McCall                              QualType ElementType) {
11248ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
11258ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
11268ed55a54SJohn McCall   const CXXDestructorDecl *Dtor = 0;
11278ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
11288ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
11298ed55a54SJohn McCall     if (!RD->hasTrivialDestructor()) {
11308ed55a54SJohn McCall       Dtor = RD->getDestructor();
11318ed55a54SJohn McCall 
11328ed55a54SJohn McCall       if (Dtor->isVirtual()) {
11338ed55a54SJohn McCall         const llvm::Type *Ty =
11340d635f53SJohn McCall           CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
11350d635f53SJohn McCall                                                                Dtor_Complete),
11368ed55a54SJohn McCall                                          /*isVariadic=*/false);
11378ed55a54SJohn McCall 
11388ed55a54SJohn McCall         llvm::Value *Callee
11398ed55a54SJohn McCall           = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
11408ed55a54SJohn McCall         CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
11418ed55a54SJohn McCall                               0, 0);
11428ed55a54SJohn McCall 
11438ed55a54SJohn McCall         // The dtor took care of deleting the object.
11448ed55a54SJohn McCall         return;
11458ed55a54SJohn McCall       }
11468ed55a54SJohn McCall     }
11478ed55a54SJohn McCall   }
11488ed55a54SJohn McCall 
11498ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1150e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1151e4df6c8dSJohn McCall   // to pop it off in a second.
11528ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
11538ed55a54SJohn McCall                                             Ptr, OperatorDelete, ElementType);
11548ed55a54SJohn McCall 
11558ed55a54SJohn McCall   if (Dtor)
11568ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
11578ed55a54SJohn McCall                               /*ForVirtualBase=*/false, Ptr);
11588ed55a54SJohn McCall 
11598ed55a54SJohn McCall   CGF.PopCleanupBlock();
11608ed55a54SJohn McCall }
11618ed55a54SJohn McCall 
11628ed55a54SJohn McCall namespace {
11638ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
11648ed55a54SJohn McCall   struct CallArrayDelete : EHScopeStack::Cleanup {
11658ed55a54SJohn McCall     llvm::Value *Ptr;
11668ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
11678ed55a54SJohn McCall     llvm::Value *NumElements;
11688ed55a54SJohn McCall     QualType ElementType;
11698ed55a54SJohn McCall     CharUnits CookieSize;
11708ed55a54SJohn McCall 
11718ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
11728ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
11738ed55a54SJohn McCall                     llvm::Value *NumElements,
11748ed55a54SJohn McCall                     QualType ElementType,
11758ed55a54SJohn McCall                     CharUnits CookieSize)
11768ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
11778ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
11788ed55a54SJohn McCall 
11798ed55a54SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
11808ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
11818ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
11828ed55a54SJohn McCall       assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
11838ed55a54SJohn McCall 
11848ed55a54SJohn McCall       CallArgList Args;
11858ed55a54SJohn McCall 
11868ed55a54SJohn McCall       // Pass the pointer as the first argument.
11878ed55a54SJohn McCall       QualType VoidPtrTy = DeleteFTy->getArgType(0);
11888ed55a54SJohn McCall       llvm::Value *DeletePtr
11898ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
11908ed55a54SJohn McCall       Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
11918ed55a54SJohn McCall 
11928ed55a54SJohn McCall       // Pass the original requested size as the second argument.
11938ed55a54SJohn McCall       if (DeleteFTy->getNumArgs() == 2) {
11948ed55a54SJohn McCall         QualType size_t = DeleteFTy->getArgType(1);
11958ed55a54SJohn McCall         const llvm::IntegerType *SizeTy
11968ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
11978ed55a54SJohn McCall 
11988ed55a54SJohn McCall         CharUnits ElementTypeSize =
11998ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
12008ed55a54SJohn McCall 
12018ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
12028ed55a54SJohn McCall         llvm::Value *Size
12038ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
12048ed55a54SJohn McCall         Size = CGF.Builder.CreateMul(Size, NumElements);
12058ed55a54SJohn McCall 
12068ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
12078ed55a54SJohn McCall         if (!CookieSize.isZero()) {
12088ed55a54SJohn McCall           llvm::Value *CookieSizeV
12098ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
12108ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
12118ed55a54SJohn McCall         }
12128ed55a54SJohn McCall 
12138ed55a54SJohn McCall         Args.push_back(std::make_pair(RValue::get(Size), size_t));
12148ed55a54SJohn McCall       }
12158ed55a54SJohn McCall 
12168ed55a54SJohn McCall       // Emit the call to delete.
121799cc30c3STilmann Scheller       CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
12188ed55a54SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
12198ed55a54SJohn McCall                    ReturnValueSlot(), Args, OperatorDelete);
12208ed55a54SJohn McCall     }
12218ed55a54SJohn McCall   };
12228ed55a54SJohn McCall }
12238ed55a54SJohn McCall 
12248ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
12258ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1226284c48ffSJohn McCall                             const CXXDeleteExpr *E,
12278ed55a54SJohn McCall                             llvm::Value *Ptr,
12288ed55a54SJohn McCall                             QualType ElementType) {
12298ed55a54SJohn McCall   llvm::Value *NumElements = 0;
12308ed55a54SJohn McCall   llvm::Value *AllocatedPtr = 0;
12318ed55a54SJohn McCall   CharUnits CookieSize;
1232284c48ffSJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
12338ed55a54SJohn McCall                                       NumElements, AllocatedPtr, CookieSize);
12348ed55a54SJohn McCall 
12358ed55a54SJohn McCall   assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
12368ed55a54SJohn McCall 
12378ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1238284c48ffSJohn McCall   const FunctionDecl *OperatorDelete = E->getOperatorDelete();
12398ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
12408ed55a54SJohn McCall                                            AllocatedPtr, OperatorDelete,
12418ed55a54SJohn McCall                                            NumElements, ElementType,
12428ed55a54SJohn McCall                                            CookieSize);
12438ed55a54SJohn McCall 
12448ed55a54SJohn McCall   if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
12458ed55a54SJohn McCall     if (!RD->hasTrivialDestructor()) {
12468ed55a54SJohn McCall       assert(NumElements && "ReadArrayCookie didn't find element count"
12478ed55a54SJohn McCall                             " for a class with destructor");
12488ed55a54SJohn McCall       CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
12498ed55a54SJohn McCall     }
12508ed55a54SJohn McCall   }
12518ed55a54SJohn McCall 
12528ed55a54SJohn McCall   CGF.PopCleanupBlock();
12538ed55a54SJohn McCall }
12548ed55a54SJohn McCall 
125559486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
125659486a2dSAnders Carlsson 
125759486a2dSAnders Carlsson   // Get at the argument before we performed the implicit conversion
125859486a2dSAnders Carlsson   // to void*.
125959486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
126059486a2dSAnders Carlsson   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1261e302792bSJohn McCall     if (ICE->getCastKind() != CK_UserDefinedConversion &&
126259486a2dSAnders Carlsson         ICE->getType()->isVoidPointerType())
126359486a2dSAnders Carlsson       Arg = ICE->getSubExpr();
126459486a2dSAnders Carlsson     else
126559486a2dSAnders Carlsson       break;
126659486a2dSAnders Carlsson   }
126759486a2dSAnders Carlsson 
126859486a2dSAnders Carlsson   llvm::Value *Ptr = EmitScalarExpr(Arg);
126959486a2dSAnders Carlsson 
127059486a2dSAnders Carlsson   // Null check the pointer.
127159486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
127259486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
127359486a2dSAnders Carlsson 
127459486a2dSAnders Carlsson   llvm::Value *IsNull =
127559486a2dSAnders Carlsson     Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
127659486a2dSAnders Carlsson                          "isnull");
127759486a2dSAnders Carlsson 
127859486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
127959486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
128059486a2dSAnders Carlsson 
12818ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
12828ed55a54SJohn McCall   // first non-array element.
12838ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
12848ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
12858ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
12868ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
12878ed55a54SJohn McCall     llvm::SmallVector<llvm::Value*,8> GEP;
128859486a2dSAnders Carlsson 
12898ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
12908ed55a54SJohn McCall 
12918ed55a54SJohn McCall     // For each layer of array type we're pointing at:
12928ed55a54SJohn McCall     while (const ConstantArrayType *Arr
12938ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
12948ed55a54SJohn McCall       // 1. Unpeel the array type.
12958ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
12968ed55a54SJohn McCall 
12978ed55a54SJohn McCall       // 2. GEP to the first element of the array.
12988ed55a54SJohn McCall       GEP.push_back(Zero);
12998ed55a54SJohn McCall     }
13008ed55a54SJohn McCall 
13018ed55a54SJohn McCall     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
13028ed55a54SJohn McCall   }
13038ed55a54SJohn McCall 
130404f36218SDouglas Gregor   assert(ConvertTypeForMem(DeleteTy) ==
130504f36218SDouglas Gregor          cast<llvm::PointerType>(Ptr->getType())->getElementType());
13068ed55a54SJohn McCall 
130759486a2dSAnders Carlsson   if (E->isArrayForm()) {
1308284c48ffSJohn McCall     EmitArrayDelete(*this, E, Ptr, DeleteTy);
13098ed55a54SJohn McCall   } else {
13108ed55a54SJohn McCall     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
131159486a2dSAnders Carlsson   }
131259486a2dSAnders Carlsson 
131359486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
131459486a2dSAnders Carlsson }
131559486a2dSAnders Carlsson 
131659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
131759486a2dSAnders Carlsson   QualType Ty = E->getType();
131859486a2dSAnders Carlsson   const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
1319fd7dfeb7SAnders Carlsson 
13203f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
13213f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
13223f4336cbSAnders Carlsson       CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
13233f4336cbSAnders Carlsson     return Builder.CreateBitCast(TypeInfo, LTy);
13243f4336cbSAnders Carlsson   }
1325fd7dfeb7SAnders Carlsson 
132659486a2dSAnders Carlsson   Expr *subE = E->getExprOperand();
132759486a2dSAnders Carlsson   Ty = subE->getType();
132859486a2dSAnders Carlsson   CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
132959486a2dSAnders Carlsson   Ty = CanTy.getUnqualifiedType().getNonReferenceType();
133059486a2dSAnders Carlsson   if (const RecordType *RT = Ty->getAs<RecordType>()) {
133159486a2dSAnders Carlsson     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
133259486a2dSAnders Carlsson     if (RD->isPolymorphic()) {
133359486a2dSAnders Carlsson       // FIXME: if subE is an lvalue do
133459486a2dSAnders Carlsson       LValue Obj = EmitLValue(subE);
133559486a2dSAnders Carlsson       llvm::Value *This = Obj.getAddress();
133659486a2dSAnders Carlsson       // We need to do a zero check for *p, unless it has NonNullAttr.
133759486a2dSAnders Carlsson       // FIXME: PointerType->hasAttr<NonNullAttr>()
133859486a2dSAnders Carlsson       bool CanBeZero = false;
133959486a2dSAnders Carlsson       if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
1340e302792bSJohn McCall         if (UO->getOpcode() == UO_Deref)
134159486a2dSAnders Carlsson           CanBeZero = true;
134259486a2dSAnders Carlsson       if (CanBeZero) {
134359486a2dSAnders Carlsson         llvm::BasicBlock *NonZeroBlock = createBasicBlock();
134459486a2dSAnders Carlsson         llvm::BasicBlock *ZeroBlock = createBasicBlock();
134559486a2dSAnders Carlsson 
13468fc50c29SDan Gohman         llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
13478fc50c29SDan Gohman         Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
134859486a2dSAnders Carlsson                              NonZeroBlock, ZeroBlock);
134959486a2dSAnders Carlsson         EmitBlock(ZeroBlock);
135059486a2dSAnders Carlsson         /// Call __cxa_bad_typeid
1351ad7c5c16SJohn McCall         const llvm::Type *ResultType = llvm::Type::getVoidTy(getLLVMContext());
135259486a2dSAnders Carlsson         const llvm::FunctionType *FTy;
135359486a2dSAnders Carlsson         FTy = llvm::FunctionType::get(ResultType, false);
135459486a2dSAnders Carlsson         llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
135559486a2dSAnders Carlsson         Builder.CreateCall(F)->setDoesNotReturn();
135659486a2dSAnders Carlsson         Builder.CreateUnreachable();
135759486a2dSAnders Carlsson         EmitBlock(NonZeroBlock);
135859486a2dSAnders Carlsson       }
13598fc50c29SDan Gohman       llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
136059486a2dSAnders Carlsson       V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
136159486a2dSAnders Carlsson       V = Builder.CreateLoad(V);
136259486a2dSAnders Carlsson       return V;
136359486a2dSAnders Carlsson     }
136459486a2dSAnders Carlsson   }
13653f4336cbSAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
136659486a2dSAnders Carlsson }
136759486a2dSAnders Carlsson 
136859486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
136959486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
13703f4336cbSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
13713f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
13723f4336cbSAnders Carlsson   QualType InnerType = DestTy->getPointeeType();
13733f4336cbSAnders Carlsson 
137459486a2dSAnders Carlsson   const llvm::Type *LTy = ConvertType(DCE->getType());
137559486a2dSAnders Carlsson 
137659486a2dSAnders Carlsson   bool CanBeZero = false;
137759486a2dSAnders Carlsson   bool ToVoid = false;
137859486a2dSAnders Carlsson   bool ThrowOnBad = false;
13793f4336cbSAnders Carlsson   if (DestTy->isPointerType()) {
138059486a2dSAnders Carlsson     // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
138159486a2dSAnders Carlsson     CanBeZero = true;
138259486a2dSAnders Carlsson     if (InnerType->isVoidType())
138359486a2dSAnders Carlsson       ToVoid = true;
138459486a2dSAnders Carlsson   } else {
138559486a2dSAnders Carlsson     LTy = LTy->getPointerTo();
1386fa8b4955SDouglas Gregor 
1387fa8b4955SDouglas Gregor     // FIXME: What if exceptions are disabled?
138859486a2dSAnders Carlsson     ThrowOnBad = true;
138959486a2dSAnders Carlsson   }
139059486a2dSAnders Carlsson 
13913f4336cbSAnders Carlsson   if (SrcTy->isPointerType() || SrcTy->isReferenceType())
13923f4336cbSAnders Carlsson     SrcTy = SrcTy->getPointeeType();
13933f4336cbSAnders Carlsson   SrcTy = SrcTy.getUnqualifiedType();
13943f4336cbSAnders Carlsson 
13950087bc85SAnders Carlsson   if (DestTy->isPointerType() || DestTy->isReferenceType())
13963f4336cbSAnders Carlsson     DestTy = DestTy->getPointeeType();
13973f4336cbSAnders Carlsson   DestTy = DestTy.getUnqualifiedType();
139859486a2dSAnders Carlsson 
139959486a2dSAnders Carlsson   llvm::BasicBlock *ContBlock = createBasicBlock();
140059486a2dSAnders Carlsson   llvm::BasicBlock *NullBlock = 0;
140159486a2dSAnders Carlsson   llvm::BasicBlock *NonZeroBlock = 0;
140259486a2dSAnders Carlsson   if (CanBeZero) {
140359486a2dSAnders Carlsson     NonZeroBlock = createBasicBlock();
140459486a2dSAnders Carlsson     NullBlock = createBasicBlock();
14053f4336cbSAnders Carlsson     Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
140659486a2dSAnders Carlsson     EmitBlock(NonZeroBlock);
140759486a2dSAnders Carlsson   }
140859486a2dSAnders Carlsson 
140959486a2dSAnders Carlsson   llvm::BasicBlock *BadCastBlock = 0;
141059486a2dSAnders Carlsson 
14113f4336cbSAnders Carlsson   const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
141259486a2dSAnders Carlsson 
141359486a2dSAnders Carlsson   // See if this is a dynamic_cast(void*)
141459486a2dSAnders Carlsson   if (ToVoid) {
141559486a2dSAnders Carlsson     llvm::Value *This = V;
14168fc50c29SDan Gohman     V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
141759486a2dSAnders Carlsson     V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
141859486a2dSAnders Carlsson     V = Builder.CreateLoad(V, "offset to top");
1419ad7c5c16SJohn McCall     This = EmitCastToVoidPtr(This);
142059486a2dSAnders Carlsson     V = Builder.CreateInBoundsGEP(This, V);
142159486a2dSAnders Carlsson     V = Builder.CreateBitCast(V, LTy);
142259486a2dSAnders Carlsson   } else {
142359486a2dSAnders Carlsson     /// Call __dynamic_cast
1424ad7c5c16SJohn McCall     const llvm::Type *ResultType = Int8PtrTy;
142559486a2dSAnders Carlsson     const llvm::FunctionType *FTy;
142659486a2dSAnders Carlsson     std::vector<const llvm::Type*> ArgTys;
1427ad7c5c16SJohn McCall     ArgTys.push_back(Int8PtrTy);
1428ad7c5c16SJohn McCall     ArgTys.push_back(Int8PtrTy);
1429ad7c5c16SJohn McCall     ArgTys.push_back(Int8PtrTy);
143059486a2dSAnders Carlsson     ArgTys.push_back(PtrDiffTy);
143159486a2dSAnders Carlsson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
143259486a2dSAnders Carlsson 
143359486a2dSAnders Carlsson     // FIXME: Calculate better hint.
143459486a2dSAnders Carlsson     llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
14353f4336cbSAnders Carlsson 
14363f4336cbSAnders Carlsson     assert(SrcTy->isRecordType() && "Src type must be record type!");
14373f4336cbSAnders Carlsson     assert(DestTy->isRecordType() && "Dest type must be record type!");
14383f4336cbSAnders Carlsson 
1439247894b3SDouglas Gregor     llvm::Value *SrcArg
1440247894b3SDouglas Gregor       = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1441247894b3SDouglas Gregor     llvm::Value *DestArg
1442247894b3SDouglas Gregor       = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
14433f4336cbSAnders Carlsson 
1444ad7c5c16SJohn McCall     V = Builder.CreateBitCast(V, Int8PtrTy);
144559486a2dSAnders Carlsson     V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
14463f4336cbSAnders Carlsson                             V, SrcArg, DestArg, hint);
144759486a2dSAnders Carlsson     V = Builder.CreateBitCast(V, LTy);
144859486a2dSAnders Carlsson 
144959486a2dSAnders Carlsson     if (ThrowOnBad) {
145059486a2dSAnders Carlsson       BadCastBlock = createBasicBlock();
14513f4336cbSAnders Carlsson       Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
145259486a2dSAnders Carlsson       EmitBlock(BadCastBlock);
1453fa8b4955SDouglas Gregor       /// Invoke __cxa_bad_cast
1454ad7c5c16SJohn McCall       ResultType = llvm::Type::getVoidTy(getLLVMContext());
145559486a2dSAnders Carlsson       const llvm::FunctionType *FBadTy;
145659486a2dSAnders Carlsson       FBadTy = llvm::FunctionType::get(ResultType, false);
145759486a2dSAnders Carlsson       llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
1458fa8b4955SDouglas Gregor       if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1459fa8b4955SDouglas Gregor         llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1460fa8b4955SDouglas Gregor         Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1461fa8b4955SDouglas Gregor         EmitBlock(Cont);
1462fa8b4955SDouglas Gregor       } else {
1463fa8b4955SDouglas Gregor         // FIXME: Does this ever make sense?
146459486a2dSAnders Carlsson         Builder.CreateCall(F)->setDoesNotReturn();
1465fa8b4955SDouglas Gregor       }
146659486a2dSAnders Carlsson       Builder.CreateUnreachable();
146759486a2dSAnders Carlsson     }
146859486a2dSAnders Carlsson   }
146959486a2dSAnders Carlsson 
147059486a2dSAnders Carlsson   if (CanBeZero) {
147159486a2dSAnders Carlsson     Builder.CreateBr(ContBlock);
147259486a2dSAnders Carlsson     EmitBlock(NullBlock);
147359486a2dSAnders Carlsson     Builder.CreateBr(ContBlock);
147459486a2dSAnders Carlsson   }
147559486a2dSAnders Carlsson   EmitBlock(ContBlock);
147659486a2dSAnders Carlsson   if (CanBeZero) {
147759486a2dSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(LTy);
147859486a2dSAnders Carlsson     PHI->reserveOperandSpace(2);
147959486a2dSAnders Carlsson     PHI->addIncoming(V, NonZeroBlock);
148059486a2dSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
148159486a2dSAnders Carlsson     V = PHI;
148259486a2dSAnders Carlsson   }
148359486a2dSAnders Carlsson 
148459486a2dSAnders Carlsson   return V;
148559486a2dSAnders Carlsson }
1486