LLVM,全局整数数组零初始值设定项

LLVM, Global integer array zeroinitializer

本文关键字:全局 整数 数组 LLVM      更新时间:2023-10-16

我似乎不知道如何为全局整数数组设置zeroinitializer。目前我的代码输出:

@a = common global [1 x i32], align 4

然而,clang foo.c -S -emit-llvm产生:

@a = common global [1 x i32] zeroinitializer, align 4

我的代码目前是这样的,我的setInitializer()代码不起作用,被注释掉了:

TheModule = (argc > 1) ? new Module(argv[1], Context) : new Module("Filename", Context);
// Unrelated code
// currentGlobal->id is a string, currentGlobal->stype->dimension is the array length
TheModule->getOrInsertGlobal(currentGlobal->id, ArrayType::get(Builder.getInt32Ty(), currentGlobal->stype->dimension));
GlobalVariable* gVar = TheModule->getNamedGlobal(currentGlobal->id);
gVar->setLinkage(GlobalValue::CommonLinkage);
// Not working, not sure if this is how it should be done roughly either
/*gVar->setInitializer(
    ConstantArray::get(
        ArrayType::get(Builder.getInt32Ty(), currentGlobal->stype->dimension),
        ArrayRef(0, currentGlobal->stype->dimension)
    )
);*/
gVar->setAlignment(4);

您需要使用ConstantAggregateZero的实例,而不是ConstantArray的实例。

===注意-以下信息已过时===

通常,如果您想知道如何模拟Clang为特定文件生成的内容,可以使用Clang生成的文件上的C++后端来发出生成相同输出的C++代码。

例如,如果您转到LLVM演示页面,提供代码int a[5] = {0};并选择"LLVM C++API代码"目标,您将得到:

// Type Definitions
ArrayType* ArrayTy_0 = ArrayType::get(IntegerType::get(mod->getContext(), 32), 5);
PointerType* PointerTy_1 = PointerType::get(ArrayTy_0, 0);

// Function Declarations
// Global Variable Declarations

GlobalVariable* gvar_array_a = new GlobalVariable(/*Module=*/*mod, 
/*Type=*/ArrayTy_0,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"a");
gvar_array_a->setAlignment(16);
// Constant Definitions
ConstantAggregateZero* const_array_2 = ConstantAggregateZero::get(ArrayTy_0);
// Global Variable Definitions
gvar_array_a->setInitializer(const_array_2);

您可以在最后一行代码的前一行看到ConstantAggregateZero的使用。