https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96419

            Bug ID: 96419
           Summary: Constant propoagation works on global variable, but
                    not in a function
           Product: gcc
           Version: 10.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: milasudril at gmail dot com
  Target Milestone: ---

I tried to implement a map-like data structure, with compile-time keys:

#include <algorithm>
#include <array>
#include <type_traits>

namespace fixed_flatmap_detail
{
    template<class T, size_t N, class Compare>
    constexpr auto sort(std::array<T, N> const& x, Compare const& compare)
    {
        auto tmp = x;
        std::ranges::sort(tmp, compare);
        return tmp;
    }
}

template<class Keys, class Value, class Compare =
std::less<decltype(Keys::items[0])>>
class FixedFlatmap
{
public:
    using key_type   = std::remove_reference_t<decltype(Keys::items[0])>;
    using value_type = Value;

    static constexpr auto size() { return std::size(Keys::items); }

    static constexpr auto const keys() { return s_keys; }

    constexpr auto const values() const { return m_vals; }

    constexpr auto values() { return m_vals; }

    constexpr auto find(key_type const& key) const
    {
        auto i = std::ranges::lower_bound(s_keys, key, Compare{});
        if(i != std::end(s_keys) && !Compare{}(key, *i)) [[likely]]
        {
            return std::begin(m_vals) + (i - std::begin(s_keys));
        }

        return static_cast<value_type const*>(nullptr);
    }

    constexpr auto find(key_type const& key)
    {
        return const_cast<value_type*>(std::as_const(*this).find(key));
    }

private:
    static constexpr auto s_keys = fixed_flatmap_detail::sort(Keys::items,
Compare{});
    std::array<value_type, size()> m_vals;
};

struct KeyStruct
{
    static constexpr std::array<std::string_view, 3> items{"Foo", "Bar",
"Kaka"};
};

FixedFlatmap<KeyStruct, int> my_vals{};
auto this_value_is_computed_at_compile_time = my_vals.find("Kaka");

int* test_lookup(FixedFlatmap<KeyStruct, int>& vals)
{
    return vals.find("Foo");  // == static_cast<int*>(static_cast<byte*>(&vals)
+ sizeof(int))
}

Interestingly gcc succeeds to compute `find` on a global variable, but fails as
soon as the same structure is allocated in a function. I am not an expert in
compilers, but realize that it could be trickier to compute it on a non-global
object (base address is not known at compile-time). However, the binary search
does not even use *this. Thus, `std::lower_bound` and outcome validation should
be possible to compute.

Godbolt: https://gcc.godbolt.org/z/c7E3P9

Reply via email to