assemblycompiler-constructionlinkerllvmllvmlite

How to generate code for initializing global variables with non-const values in LLVM?


In LLVM (specifically llvmlite), how does one declare a global variable and initialize its contents with the result of an arbitrary (runtime) expression?

I see that I can create a GlobalVariable object, but it looks like its initializer argument is expecting a Constant. What if I must run arbitrary code at startup/load time to determine its value? Where does that code go? Whose Builder do I add instructions to? Do I declare a specially-named function and/or add magic attributes to it so that it automatically execs when the module is loaded into memory at runtime?


Solution

  • It entirely depends on your setup. In C or C++ with Visual Studio, C and C++ initialization functions end up getting put into a subsection of the .CRT section, and are executed by the standard runtime library.

    If you compile without the CRT and have these initialization functions, they will not fire because the runtime takes care of that.

    Correction edit: It appears @llvm.global_ctors exists.

    I'm unsure if these will fire correctly in an environment without a runtime library that helps to execute initializers, but there you have it.