On 7/28/24 3:09 AM, Alejandro Colomar via Gcc-help wrote:
Hi! I'm trying to implement a _Lengthof() operator that is similar to sizeof(), but gets the number of elements of an array. I'm having trouble getting the number of elements for VLAs. The main work is done here: +tree +c_lengthof_type (location_t loc, tree type) +{ + tree nelts_minus_one; + enum tree_code type_code; + unsigned HOST_WIDE_INT nelts; + + type_code = TREE_CODE (type); + if (type_code != ARRAY_TYPE) + { + error_at (loc, "invalid application of %<_Lengthof%> to type %qT", type); + return error_mark_node; + } + + nelts_minus_one = array_type_nelts (type); + nelts = tree_to_uhwi (nelts_minus_one) + 1; + + return size_int (nelts); +} I would directly return array_type_nelts(type), which works for both normal arrays and VLAs, but that's off-by-one so I need to do the trick with tree_to_uhwi() to get an integer, then add one, then get back to a tree. However, tree_to_uhwi() asserts that I use an integer constant, which results in an ICE when trying to use _Lengthof() on a VLA. Is there any other way to get the actual number of elements of an array, which isn't off-by-one and also works for VLAs? Cheers, Alex P.S.: I've attached the work-in-progress patch I'm working on, in case anyone wants to have a look at it.
I think what you want is probably simply to generate a tree that evaluates the expression `array_type_nelts (type) + 1` yourself if there isn't a function that'll do it for you. You probably want to do something similar to `build2(PLUS_EXPR, TREE_TYPE (nelts_minus_one), nelts_minus_one, integer_one_node)` (I have 0 idea if this specific code will work but something like that seems like it should be appropriate)