llvm-project/llvm/lib/Support/StringSaver.cpp
Jan Svoboda efcb07bf6e [llvm][Support] Avoid intermediate heap allocations in StringSaver
The `Twine::str()` function currently always allocates heap memory via `std::string`. However, some instances of `Twine` don't need an intermediate buffer at all, and the rest can attempt to print into a stack buffer first.

This is intentionally not making use of `Twine::isSingleStringLiteral()` from D157010 to skip saving the string in the bump-pointer allocator, since the `StringSaver` documentation suggests that MUST happen for every given string.

Reviewed By: benlangmuir

Differential Revision: https://reviews.llvm.org/D157015
2023-08-03 11:12:05 -07:00

39 lines
1.1 KiB
C++

//===-- StringSaver.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/StringSaver.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
StringRef StringSaver::save(StringRef S) {
char *P = Alloc.Allocate<char>(S.size() + 1);
if (!S.empty())
memcpy(P, S.data(), S.size());
P[S.size()] = '\0';
return StringRef(P, S.size());
}
StringRef StringSaver::save(const Twine &S) {
SmallString<128> Storage;
return save(S.toStringRef(Storage));
}
StringRef UniqueStringSaver::save(StringRef S) {
auto R = Unique.insert(S);
if (R.second) // cache miss, need to actually save the string
*R.first = Strings.save(S); // safe replacement with equal value
return *R.first;
}
StringRef UniqueStringSaver::save(const Twine &S) {
SmallString<128> Storage;
return save(S.toStringRef(Storage));
}