How can I create an anonymous global variable in LLVM IR C++ API?
I can create a named global variable as follows:
GlobalVariable *createGlobalVariable(
Module *module,
Type *type,
std::string name
) {
module->getOrInsertGlobal(name, type);
return module->getNamedGlobal(name);
}
For example:
auto context = new LLVMContext();
auto module = new Module("Module", *context);
auto type = IntegerType::getInt32Ty(*context);
auto globalVariable = createGlobalVariable(
module,
type,
"globalVariableName"
);
auto constantInt = ConstantInt::getIntegerValue(
type,
APInt(32, 42)
);
globalVariable->setInitializer(constantInt);
module->dump();
It will generate:
; ModuleID = 'Module'
source_filename = "Module"
@globalVariableName = global i32 42
How can I create an anonymous global variable?
I would like to generate somethings like:
; ModuleID = 'Module'
source_filename = "Module"
@0 = global i32 42
@0
is a unique identifiers
In comment, @IlCapitano said that Pass "" as name
I try
auto context = new LLVMContext();
auto module = new Module("Module", *context);
auto type = IntegerType::getInt32Ty(*context);
auto constant = module->getOrInsertGlobal("", type);
module->dump();
It generates:
; ModuleID = 'Module'
source_filename = "Module"
@0 = external global i32
But if I set initializer, will be Segmentation fault
auto constant = module->getOrInsertGlobal("", type);
auto anonymousGlobalVariable = module->getNamedGlobal(constant->getName());
anonymousGlobalVariable->setInitializer(constantInt);
// -> Segmentation fault
The correct way is creating GlobalVariable by using constructor:
auto context = new LLVMContext();
auto module = new Module("Module", *context);
auto type = IntegerType::getInt32Ty(*context);
auto constantInt = ConstantInt::getIntegerValue(type, APInt(32, 42));
auto anonymousGlobalVariable = new GlobalVariable(
*module,
type,
false,
GlobalValue::CommonLinkage,
constantInt,
""
);
module->dump();
Nice
; ModuleID = 'Module'
source_filename = "Module"
@0 = common global i32 42