Clang如何实现模板实例化?

我使用Clang作为库来编译一些模板代码:

template<typename T>
T getSevenTemplated() {
  return 7;
}

int getSeven() {
  return getSevenTemplated<int>();
}

不幸的是,编译的LLVM IR实际上并不包含getSevenTemplated<int>

; ModuleID = './test.cpp'
source_filename = "./test.cpp"
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.12.0"

; Function Attrs: ssp uwtable
define i32 @_Z8getSevenv() #0 {
entry:
  %call = call i32 @_Z17getSevenTemplatedIiET_v()
  ret i32 %call
}

declare i32 @_Z17getSevenTemplatedIiET_v() #1

attributes #0 = { ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"clang version 5.0.0 (trunk 292778)"}

以下是我用来生成LLVM模块的代码:

auto* context = new llvm::LLVMContext(); // TODO: Fix leak 

auto codeGenerator =
  std::shared_ptr<clang::CodeGenerator>(
    clang::CreateLLVMCodeGen(
      compilerInstance.getDiagnostics(), 
      filePath,
      compilerInstance.getHeaderSearchOpts(), 
      preprocessor.getPreprocessorOpts(),
      compilerInstance.getCodeGenOpts(), 
      *context, 
      nullptr));

codeGenerator->Initialize(compilerInstance.getASTContext());

// declGroups are found by calling ParseAST with a special ASTConsumer earlier
for (auto declGroup : declGroups) { 
  codeGenerator->HandleTopLevelDecl(declGroup);
}

codeGenerator->HandleTranslationUnit(compilerInstance.getASTContext());

为了调查为什么,我查看了源代码,发现CodeGenerator具有处理模板的特定逻辑:它似乎忽略了函数模板实例化! 我认为它处理生成的函数,但我不知道它是如何工作的。

我的问题是:

  • 在高层次上,Clang如何去实例化模板并将它们传递给ASTConsumer进行代码生成?
  • 是否有任何特殊技巧可以为实例化模板生成函数体? 我从上面的代码中错过了什么?

  • 问题是我开启了增量分析。 启用此设置后, ParseAST函数不会调用clang::Sema::ActOnEndOfTranslationUnit ,它会触发模板的实例化。

    诀窍是在处理你的decls后添加这个调用:

    // This triggers the instantiation of templated functions
    sema.ActOnEndOfTranslationUnit();
    
    链接地址: http://www.djcxy.com/p/38365.html

    上一篇: How do template instantiations get compiled by Clang?

    下一篇: Azure IoT Hub, EventHub and Functions