[llvm] r264201 - StringRef::copy shouldn't allocate anything for length 0 strings.

Pete Cooper via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 23 14:49:31 PDT 2016


Author: pete
Date: Wed Mar 23 16:49:31 2016
New Revision: 264201

URL: http://llvm.org/viewvc/llvm-project?rev=264201&view=rev
Log:
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

Modified:
    llvm/trunk/include/llvm/ADT/StringRef.h
    llvm/trunk/unittests/ADT/StringRefTest.cpp

Modified: llvm/trunk/include/llvm/ADT/StringRef.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringRef.h?rev=264201&r1=264200&r2=264201&view=diff
==============================================================================
--- llvm/trunk/include/llvm/ADT/StringRef.h (original)
+++ llvm/trunk/include/llvm/ADT/StringRef.h Wed Mar 23 16:49:31 2016
@@ -133,6 +133,9 @@ namespace llvm {
 
     // copy - Allocate copy in Allocator and return StringRef to it.
     template <typename Allocator> StringRef copy(Allocator &A) const {
+      // Don't request a length 0 copy from the allocator.
+      if (empty())
+        return StringRef();
       char *S = A.template Allocate<char>(Length);
       std::copy(begin(), end(), S);
       return StringRef(S, Length);

Modified: llvm/trunk/unittests/ADT/StringRefTest.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/StringRefTest.cpp?rev=264201&r1=264200&r2=264201&view=diff
==============================================================================
--- llvm/trunk/unittests/ADT/StringRefTest.cpp (original)
+++ llvm/trunk/unittests/ADT/StringRefTest.cpp Wed Mar 23 16:49:31 2016
@@ -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);




More information about the llvm-commits mailing list