From 6904cbb1f21002317387e8fc7b14b7f8c09d198f Mon Sep 17 00:00:00 2001 From: Fariborz Jahanian Date: Thu, 6 Aug 2009 01:02:49 +0000 Subject: [PATCH] Patch to optimize away copy constructor call when appropriate. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@78267 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/CodeGen/CGCXX.cpp | 15 ++++++++++- test/CodeGenCXX/copy-constructor-elim.cpp | 31 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 test/CodeGenCXX/copy-constructor-elim.cpp diff --git a/lib/CodeGen/CGCXX.cpp b/lib/CodeGen/CGCXX.cpp index 5324cc622f..0f76266acc 100644 --- a/lib/CodeGen/CGCXX.cpp +++ b/lib/CodeGen/CGCXX.cpp @@ -255,7 +255,20 @@ CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, cast(E->getType()->getAs()->getDecl()); if (RD->hasTrivialConstructor()) return; - + + // Code gen optimization to eliminate copy constructor and return + // its first argument instead. + const CXXConstructorDecl *CDecl = E->getConstructor(); + if (E->getNumArgs() == 1 && + CDecl->isCopyConstructor(getContext())) { + CXXConstructExpr::const_arg_iterator i = E->arg_begin(); + const Expr *SubExpr = (*i); + // FIXME. Any other cases can be optimized away? + if (isa(SubExpr) || isa(SubExpr)) { + EmitAggExpr(SubExpr, Dest, false); + return; + } + } // Call the constructor. EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, E->arg_begin(), E->arg_end()); diff --git a/test/CodeGenCXX/copy-constructor-elim.cpp b/test/CodeGenCXX/copy-constructor-elim.cpp new file mode 100644 index 0000000000..5a1109d7f7 --- /dev/null +++ b/test/CodeGenCXX/copy-constructor-elim.cpp @@ -0,0 +1,31 @@ +// RUN: clang-cc -emit-llvm -o %t %s && +// RUN: grep "_ZN1CC1ERK1C" %t | count 0 + +extern "C" int printf(...); + + +struct C { + C() : iC(6) {printf("C()\n"); } + C(const C& c) { printf("C(const C& c)\n"); } + int iC; +}; + +C foo() { + return C(); +}; + +class X { // ... +public: + X(int) {} + X(const X&, int i = 1, int j = 2, C c = foo()) { + printf("X(const X&, %d, %d, %d)\n", i, j, c.iC); + } +}; + +int main() +{ + X a(1); + X b(a, 2); + X c = b; + X d(a, 5, 6); +} -- 2.40.0