'How to create global variable as dso_local in llvm ir builder for c++?

I am trying to create a global variable that looks like the following using the c++ llvm ir builder:

@test = dso_local global i8* null, align 8

The problem is when I create a global variable using the following code:

auto global_variable = TheModule->getOrInsertGlobal("gvar", llvm::Type::getInt8PtrTy(TheContext))

there are no options that allow me to set the global variable to my desired syntax. I would like to know how I would go about creating that global variable using the llvm ir builder for c++.



Solution 1:[1]

Sorry cannot make a comment... There is a second overload of getOrInsertGlobal which takes a callback function, presumably this callback will be passed the created global variable (llvm::GlobalVariable). You can change the attributes of the variable then.

Solution 2:[2]

You can simply use the GlobalValue::setDSOLocal function to mark a global variable or a function as dso_local.
For example:

Function *randFunc = (Function*)M.getOrInsertFunction("rand", FunctionType::getInt32Ty(*CONTEXT)).getCallee();
randFunc->setDSOLocal(true);
CallInst *rand = CallInst::Create(randFunc->getFunctionType(), randFunc, "", I);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DaOnly Owner
Solution 2 34r7hm4n