Search code examples
llvmllvm-ir

How to initialize LLVM global array with bitcasts?


I'm trying to create llvm.used array to keep globals from being optimized out. But they have different types, so I need to use bitcasts. Expected result

@a = internal global i32 zeroinitializer, section "ab"
@b = internal global i64 zeroinitializer, section "ab"

@llvm.used = appending global [2 x i8*] [
        i8* bitcast (i32* @a to i8*),
        i8* bitcast (i64* @b to i8*)
    ], section "llvm.metadata"

I'm able to create that array, but how put bitcasts to initializer?

BitCastInst* B1 = new BitCastInst(variableA, Type::getInt8PtrTy(context));
BitCastInst* B2 = new BitCastInst(variableB, Type::getInt8PtrTy(context));
std::vector<Instruction*> elements;
elements.push_back(B1);
elements.push_back(B2);
LU->setInitializer(ConstantArray::get(T, elements));

This doesn't work because ConstantArray expect some array of Constants, but I have array of Instructions


Solution

  • You can use a constant array of constants and make constant casts using getBitCast(); ConstantExpr also contains some other casts you can use.