Overflow(?) issue with ASTContext::getConstantArrayType

Hi everyone,

When using clang's API to generate C source code, I can create array types of size up to 1 << 26, but anything more than that results in a 0-sized array:

     // This works ok
     auto type1 = ast_ctx.getConstantArrayType(
       elm_type, llvm::APInt(64, 1ull << 26), nullptr,
       clang::ArrayType::ArraySizeModifier::Normal, 0);

     // This generates a 0-sized array type
     auto type2 = ast_ctx.getConstantArrayType(
       elm_type, llvm::APInt(64, 1ull << 27), nullptr,
       clang::ArrayType::ArraySizeModifier::Normal, 0);

Is this a known bug or am I holding the API wrong?


The ConstantArrayType stores the APInt it is given directly, HOWEVER, there is a modification of the size to 'max pointer width' on your target. When you try to create this outside of the API, we error when this is the case, though for the platforms I looked into, the lowest was 1 <<30 that caused problems.

ASTContext.getConstantArrayType is zeroExtOrTrunc'ing the APInt you pass down to the "MaxPointerWidth" size for the target, though I only see ones that would cut it down to 64/32, or 16, not 26 (though AMDGPU and NVPTX do some funny business).

Can you try confirming what happens when you do (1ull << 27 + 5)? If so, line 3488 here (clang: lib/AST/ASTContext.cpp Source File) might be what is changing your type size. What target are you compiling for?

I've tried pinpointing the exact value with this

   for (auto i{1ull << 26}; i < (1ull << 27); ++i) {
     llvm::APInt sz{64, i};
     auto& ast_ctx{ast_unit->getASTContext()};
     auto type{ast_ctx.getConstantArrayType(
         ast_ctx.CharTy, sz, nullptr,
         clang::ArrayType::ArraySizeModifier::Normal, 0)};
     auto atype{ast_ctx.getAsArrayType(type)};
     auto catype{clang::cast<clang::ConstantArrayType>(atype)};
     CHECK_EQ(catype->getSize().getZExtValue(), i);

which unfortunately didn't work, which I guess tells me the bug lies somewhere else in the path from type to generating declarations.
I shall investigate more and report back! Thanks for now!