[gcc r15-7547] libstdc++: Improve list assumption after constructor [PR118865]

Andrew Pinski pinskia@gcc.gnu.org
Fri Feb 14 23:11:17 GMT 2025


https://gcc.gnu.org/g:0c3cc57f0e71a7a945fb10c817260dd8a7894e7f

commit r15-7547-g0c3cc57f0e71a7a945fb10c817260dd8a7894e7f
Author: Andrew Pinski <quic_apinski@quicinc.com>
Date:   Thu Feb 13 14:10:06 2025 -0800

    libstdc++: Improve list assumption after constructor [PR118865]
    
    The code example here does:
    ```
    if (begin == end) __builtin_unreachable();
    std::list nl(begin, end);
    
    for (auto it = nl.begin(); it != nl.end(); it++)
    {
    ...
    }
    /* Remove the first element of the list. */
    nl.erase(nl.begin());
    ```
    
    And we get a warning because because we jump threaded the case were we
    think the list was empty from the for loop BUT we populated it without
    an empty array. So can help the compiler here by adding that after initializing
    the list with non empty array, that the list will not be empty either.
    
    This is able to remove the -Wfree-nonheap-object warning in the first reduced
    testcase (with the fix for `begin == end` case added) in the PR 118865; the second
    reduced testcase has been filed off as PR 118867.
    
    Bootstrapped and tested on x86_64-linux-gnu.
    
    libstdc++-v3/ChangeLog:
    
            PR libstdc++/118865
            * include/bits/stl_list.h (_M_initialize_dispatch): Add an
            unreachable if the iterator was not empty that the list will
            now be not empty.
    
    Signed-off-by: Andrew Pinski <quic_apinski@quicinc.com>

Diff:
---
 libstdc++-v3/include/bits/stl_list.h | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/libstdc++-v3/include/bits/stl_list.h b/libstdc++-v3/include/bits/stl_list.h
index be33eeb03d44..f987d8b9d0a3 100644
--- a/libstdc++-v3/include/bits/stl_list.h
+++ b/libstdc++-v3/include/bits/stl_list.h
@@ -2384,12 +2384,18 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
 	_M_initialize_dispatch(_InputIterator __first, _InputIterator __last,
 			       __false_type)
 	{
+	  bool __notempty = __first != __last;
 	  for (; __first != __last; ++__first)
 #if __cplusplus >= 201103L
 	    emplace_back(*__first);
 #else
 	    push_back(*__first);
 #endif
+	 if (__notempty)
+	   {
+	     if (begin() == end())
+	       __builtin_unreachable();
+	   }
 	}
 
       // Called by list(n,v,a), and the range constructor when it turns out


More information about the Libstdc++-cvs mailing list