LLVM,全局整数数组zeroinitializer

时间:2014-04-27 22:49:42

标签: c++ llvm

我似乎无法弄清楚如何为全局整数数组设置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);

1 个答案:

答案 0 :(得分:7)

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

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

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

例如,如果您转到LLVM demo page,请提供代码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的使用。