Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk? -- >8 -- Here we crash on this invalid code because we seem to infinitely recurse and end up with __type_pack_element with index that doesn't tree_fits_shwi_p which then crashes on tree_to_shwi.
Thanks to Jakub for suggesting a nicer fix than my original one. PR c++/113834 gcc/cp/ChangeLog: * semantics.cc (finish_type_pack_element): Perform range checking before tree_to_shwi. gcc/testsuite/ChangeLog: * g++.dg/ext/type_pack_element4.C: New test. --- gcc/cp/semantics.cc | 7 +++---- gcc/testsuite/g++.dg/ext/type_pack_element4.C | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 gcc/testsuite/g++.dg/ext/type_pack_element4.C diff --git a/gcc/cp/semantics.cc b/gcc/cp/semantics.cc index 3299e270446..57840176863 100644 --- a/gcc/cp/semantics.cc +++ b/gcc/cp/semantics.cc @@ -4650,20 +4650,19 @@ finish_type_pack_element (tree idx, tree types, tsubst_flags_t complain) error ("%<__type_pack_element%> index is not an integral constant"); return error_mark_node; } - HOST_WIDE_INT val = tree_to_shwi (idx); - if (val < 0) + if (tree_int_cst_sgn (idx) < 0) { if (complain & tf_error) error ("%<__type_pack_element%> index is negative"); return error_mark_node; } - if (val >= TREE_VEC_LENGTH (types)) + if (wi::to_widest (idx) >= TREE_VEC_LENGTH (types)) { if (complain & tf_error) error ("%<__type_pack_element%> index is out of range"); return error_mark_node; } - return TREE_VEC_ELT (types, val); + return TREE_VEC_ELT (types, tree_to_shwi (idx)); } /* Implement the __direct_bases keyword: Return the direct base classes diff --git a/gcc/testsuite/g++.dg/ext/type_pack_element4.C b/gcc/testsuite/g++.dg/ext/type_pack_element4.C new file mode 100644 index 00000000000..aa508c79090 --- /dev/null +++ b/gcc/testsuite/g++.dg/ext/type_pack_element4.C @@ -0,0 +1,17 @@ +// PR c++/113834 +// { dg-do compile { target c++17 } } + +template <typename... _Elements> class tuple{}; +template <unsigned long __i, typename... _Elements> +__type_pack_element<__i, _Elements...> &get(tuple<_Elements...> &__t) noexcept; // { dg-error "index is out of range" } +tuple<int,int> data; +template <unsigned long Level> +unsigned take_impl(unsigned idx) { + if constexpr (Level != -1){ + return take_impl<Level - 1>(get<Level - 1>(data)); // { dg-error "" } + } + return 0; +} +int main() { + take_impl<2>(0); +} base-commit: c9bdcb0c3433ce09f5bb713a51a14130858578a2 -- 2.43.0