From 6ac5fc49ee70b4e3ce3e242c02c66586f652d7ac Mon Sep 17 00:00:00 2001 From: Anders Carlsson Date: Wed, 23 Sep 2009 18:59:48 +0000 Subject: [PATCH] Emit new[] cookie when needed. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@82642 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/CodeGen/CGCXXExpr.cpp | 25 +++++++++++++++++++------ test/CodeGenCXX/new.cpp | 8 ++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/CodeGen/CGCXXExpr.cpp b/lib/CodeGen/CGCXXExpr.cpp index bf08caa3b4..1ee4ceb136 100644 --- a/lib/CodeGen/CGCXXExpr.cpp +++ b/lib/CodeGen/CGCXXExpr.cpp @@ -16,6 +16,9 @@ using namespace clang; using namespace CodeGen; static uint64_t CalculateCookiePadding(ASTContext &Ctx, const CXXNewExpr *E) { + if (!E->isArray()) + return 0; + QualType T = E->getAllocatedType(); const RecordType *RT = T->getAs(); @@ -34,7 +37,7 @@ static uint64_t CalculateCookiePadding(ASTContext &Ctx, const CXXNewExpr *E) { // Padding is the maximum of sizeof(size_t) and alignof(T) return std::max(Ctx.getTypeSize(Ctx.getSizeType()), - static_cast(Ctx.getTypeAlign(T))); + static_cast(Ctx.getTypeAlign(T))) / 8; } static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, @@ -115,11 +118,6 @@ static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, } llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { - if (E->isArray() && CalculateCookiePadding(getContext(), E)) { - ErrorUnsupported(E, "new[] expression"); - return llvm::UndefValue::get(ConvertType(E->getType())); - } - QualType AllocType = E->getAllocatedType(); FunctionDecl *NewFD = E->getOperatorNew(); const FunctionProtoType *NewFTy = NewFD->getType()->getAs(); @@ -199,6 +197,21 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { EmitBlock(NewNotNull); } + if (uint64_t CookiePadding = CalculateCookiePadding(getContext(), E)) { + uint64_t CookieOffset = + CookiePadding - getContext().getTypeSize(SizeTy) / 8; + + llvm::Value *NumElementsPtr = + Builder.CreateConstInBoundsGEP1_64(NewPtr, CookieOffset); + + NumElementsPtr = Builder.CreateBitCast(NumElementsPtr, + ConvertType(SizeTy)->getPointerTo()); + Builder.CreateStore(NumElements, NumElementsPtr); + + // Now add the padding to the new ptr. + NewPtr = Builder.CreateConstInBoundsGEP1_64(NewPtr, CookiePadding); + } + NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType())); EmitNewInitializer(*this, E, NewPtr, NumElements); diff --git a/test/CodeGenCXX/new.cpp b/test/CodeGenCXX/new.cpp index 2cb3b00edf..c6cee18456 100644 --- a/test/CodeGenCXX/new.cpp +++ b/test/CodeGenCXX/new.cpp @@ -55,6 +55,10 @@ void t7() { new int(); } +struct U { + ~U(); +}; + void t8(int n) { new int[10]; new int[n]; @@ -62,4 +66,8 @@ void t8(int n) { // Non-POD new T[10]; new T[n]; + + // Cookie required + new U[10]; + new U[n]; } -- 2.40.0