From 552f3d8472bff7068e626305c25419dbcc33e7b7 Mon Sep 17 00:00:00 2001 From: Pete Cooper Date: Wed, 23 Mar 2016 21:49:31 +0000 Subject: [PATCH] StringRef::copy shouldn't allocate anything for length 0 strings. The BumpPtrAllocator currently doesn't handle zero length allocations well. The discussion for how to fix that is ongoing. However, there's no need for StringRef::copy to actually allocate anything here anyway, so just return StringRef() when we get a zero length copy. Reviewed by David Blaikie git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@264201 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/ADT/StringRef.h | 3 +++ unittests/ADT/StringRefTest.cpp | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/include/llvm/ADT/StringRef.h b/include/llvm/ADT/StringRef.h index 90d0a159dcd..f1189690ffb 100644 --- a/include/llvm/ADT/StringRef.h +++ b/include/llvm/ADT/StringRef.h @@ -133,6 +133,9 @@ namespace llvm { // copy - Allocate copy in Allocator and return StringRef to it. template StringRef copy(Allocator &A) const { + // Don't request a length 0 copy from the allocator. + if (empty()) + return StringRef(); char *S = A.template Allocate(Length); std::copy(begin(), end(), S); return StringRef(S, Length); diff --git a/unittests/ADT/StringRefTest.cpp b/unittests/ADT/StringRefTest.cpp index 6354026d7ae..66e5944b56e 100644 --- a/unittests/ADT/StringRefTest.cpp +++ b/unittests/ADT/StringRefTest.cpp @@ -589,6 +589,15 @@ TEST(StringRefTest, joinStrings) { TEST(StringRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; + // First test empty strings. We don't want these to allocate anything on the + // allocator. + StringRef StrEmpty = ""; + StringRef StrEmptyc = StrEmpty.copy(Alloc); + EXPECT_TRUE(StrEmpty.equals(StrEmptyc)); + EXPECT_EQ(StrEmptyc.data(), nullptr); + EXPECT_EQ(StrEmptyc.size(), 0u); + EXPECT_EQ(Alloc.getTotalMemory(), 0u); + StringRef Str1 = "hello"; StringRef Str2 = "bye"; StringRef Str1c = Str1.copy(Alloc);