为什么 llvm::Module 存储在 unique_ptr 中?

Why is llvm::Module stored in a unique_ptr?

LLVM Kaleidoscope教程中,我找到了以下代码:

static std::unique_ptr<Module> TheModule;

我很困惑为什么将其存储在 unique_ptr 而不是常规的全局变量中。也许对象太大以至于进行堆分配而不是堆栈会更有效?毕竟,sizeof(Module) 在我的系统上是 728。我能得到一个不基于猜测的具体答案吗?谢谢。

chapter 4TheModule 廉价地移入 JIT(AFAIK 然后在代码生成后删除)然后用新的 Module 重新初始化,这不适用于静态 Module变量。

  auto H = TheJIT->addModule(std::move(TheModule));
  InitializeModuleAndPassManager(); // here a new empty module is created

虽然可以编写 JIT 以将普通 Module 指针传递给 IRCompileLayer,但之后无法用新模块替换静态 Module 变量。

教程是这样说的:

Once the module has been added to the JIT it can no longer be modified, so we also open a new module to hold subsequent code by calling InitializeModuleAndPassManager().

static void InitializeModuleAndPassManager() {
  // Open a new module.
  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);

如果 TheModule 是 Module 而不是 unique_ptr<Module>,则此分配将失败。