Menooker
Menooker

Reputation: 133

A probable bug of external llvm GlobalVariable with TLS?

I'm trying to make a "thread-local" global variable in LLVM (MSVC, Windows). Usually an external global variable can be initialized like this :

TheExecutionEngine->addGlobalMapping(module->getGlobalVariable("bsp"), &somevalue);

But when I create a TLS GlobalVariable (setting ThreadLocalModel=GlobalVariable::LocalDynamicTLSModel) , addGlobalMapping seems not working. Here is an example:

InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::Module *module = new llvm::Module("top", context);
llvm::IRBuilder<> builder(context); 

GlobalVariable* bsp=new GlobalVariable(*module,Type::getInt32Ty(context),false,GlobalValue::ExternalLinkage,0,"bsp",0,GlobalVariable::LocalDynamicTLSModel);
llvm::FunctionType *funcType =
    llvm::FunctionType::get(builder.getInt32Ty(), false);
llvm::Function *mainFunc =
    llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);

llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
builder.SetInsertPoint(entry);
//builder.CreateStore(ConstInt(32,123),bsp);
builder.CreateRet(builder.CreateLoad(bsp));
module->dump( );

ExecutionEngine *TheExecutionEngine;
long ou=1;
TheExecutionEngine = EngineBuilder(module).create();
module->getGlobalVariable("bsp")->dump();
TheExecutionEngine->addGlobalMapping(module->getGlobalVariable("bsp"),&ou);
typedef int (*PF)();
PF fun=(PF)TheExecutionEngine->getPointerToFunction(mainFunc);

printf("%d %d\n",ou,fun());
system("pause");

Here I create a function "main" in llvm which returns the value of a global variable bsp.

Before I jit the llvm module, I set a variable in C++ ("long ou=1;"), and map the llvm variable bsp to the C++ variable "ou"(TheExecutionEngine->addGlobalMapping(module->getGlobalVariable("bsp"), &ou);).

Finally I jit the function and run it. "fun()" is expected to return value 1, but it returns a random number.

I have tried my codes on llvm 3.4.2 with "old JIT" (not MCJIT) I think the llvm global variable is not successfully mapped to the C++ variable.

Maybe I use thread-local global variable in a wrong way, or it is an llvm bug?

Upvotes: 1

Views: 354

Answers (1)

zevorn
zevorn

Reputation: 1

Your external variable is of long type, which is different from the type of external global variable you construct in IR

Upvotes: 0

Related Questions