I’m currently working on HLS(high level synthesis) project that involves using the llvm (version 10) In my analysis, I need to determine the length of arrays in C function parameters to generate BRAM.
However, I noticed that when Clang generates IR, array parameters are represented as pointers (e.g., i32* for int array[4]). As a result, the array length information is lost during the Clang AST phase.
My question is whether there is any possibility to obtain the array length (only in situations like int a[4]) in C function parameters or to somehow preserve this information in the LLVM IR.
I have considered custom attribute or metadata to store the array length information, but I’m unsure if this is feasible or if there are any existing mechanisms in Clang to achieve this.
To clarify, I’m looking for a way to access the array length (only in situations like int a[4]) in the Clang AST phase before the generation of LLVM IR. If there’s a way to accomplish this or if you have any suggestions or insights, I’d greatly appreciate your help.
This information is tracked by the type system for constant-sized arrays. Assuming you’ve got access to a QualType named QT, you could do something like:
if (const auto *CAT = dyn_cast<ConstantArrayType>(QT.getTypePtr())) {
APInt APExtent = CAT->getSize();
uint64_t Extent = APExtent.getZExtValue();
...
}
Indeed, in this situation, C also cannot obtain the array’s length since it has already been converted into a pointer. However, users write this kind of code with the intention of using an array of length 4, which is why I asked if it is possible to obtain the array’s length.
I had missed the fact that this was in a function parameter. In C, function parameters of array type are decayed into a pointer type: Compiler Explorer
Try out:
if (const auto *DT = dyn_cast<DecayedType>(getType().getTypePtr())) {
if (const auto *CAT = Context.getAsConstantArrayType(DT->getOriginalType())) {
...
}
}