[libcxx-commits] [libcxx] [libc++] Add basic constant folding for std::format (PR #107197)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed Nov 6 09:00:22 PST 2024


================
@@ -448,13 +450,44 @@ format_to(_OutIt __out_it, wformat_string<_Args...> __fmt, _Args&&... __args) {
 }
 #  endif
 
+template <class _CharT>
+[[nodiscard]] _LIBCPP_HIDE_FROM_ABI optional<basic_string<_CharT>> __try_constant_folding(
+    basic_string_view<_CharT> __fmt,
+    basic_format_args<basic_format_context<back_insert_iterator<__format::__output_buffer<_CharT>>, _CharT>> __args) {
+  return nullopt;
+  if (bool __is_identity = std::ranges::find_first_of(__fmt, array{'{', '}'}) == __fmt.end();
----------------
ldionne wrote:

It would be nice to ensure that the compiler doesn't end up generating any code for this call (and the other `if` condition below) even when `__builtin_constant_p(__is_identity)` is false. I could imagine this happening if e.g. the compiler didn't inline `find_first_of` and couldn't figure out that the function doesn't have side effects. In that case, it may have to still call the function even though its return value is not being used.

As you suggested, you might be able to wrap some of this code into a `[[pure]]` lambda to let the compiler know about this.

https://github.com/llvm/llvm-project/pull/107197


More information about the libcxx-commits mailing list