源码路径
llvm\include\llvm\IR\GVMaterializer.h
llvm\include\llvm\IR\AutoUpgrade.h
llvm\Bitcode\BitcodeReader.h
llvm\lib\Bitcode\Reader\BitcodeReader.cpp
llvm GVMaterializer Class
llvm中使用GVMaterializer类作为加载Module的类的抽象接口,比如llvm的BitcodeReader就是该类的实体类:
class GVMaterializer {
public:
virtual Error materialize(GlobalValue *GV) = 0;
virtual Error materializeModule() = 0;
virtual Error materializeMetadata() = 0;
virtual void setStripDebugInfo() = 0;
virtual std::vector<StructType *> getIdentifiedStructTypes() const = 0;
};
以BitcodeReader类为例,加载Module的实现如下:
Error BitcodeReader::materializeModule() {
if (Error Err = materializeMetadata())
return Err;
// Promise to materialize all forward references.
WillMaterializeAllForwardRefs = true;
// Iterate over the module, deserializing any functions that are still on
// disk.
for (Function &F : *TheModule) {
if (Error Err = materialize(&F))
return Err;
}
// At this point, if there are any function bodies, parse the rest of
// the bits in the module past the last function block we have recorded
// through either lazy scanning or the VST.
if (LastFunctionBlockBit || NextUnreadBit)
if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
? LastFunctionBlockBit
: NextUnreadBit))
return Err;
// Check that all block address forward references got resolved (as we
// promised above).
if (!BasicBlockFwdRefs.empty())
return error("Never resolved function from blockaddress");
// Upgrade any intrinsic calls that slipped through (should not happen!) and
// delete the old functions to clean up. We can't do this unless the entire
// module is materialized because there could always be another function body
// with calls to the old function.
for (auto &I : UpgradedIntrinsics) {
for (auto *U : I.first->users()) {
if (CallInst *CI = dyn_cast<CallInst>(U))
UpgradeIntrinsicCall(CI, I.second);
}
if (!I.first->use_empty())
I.first->replaceAllUsesWith(I.second);
I.first->eraseFromParent();
}
UpgradedIntrinsics.clear();
// Do the same for remangled intrinsics
for (auto &I : RemangledIntrinsics) {
I.first->replaceAllUsesWith(I.second);
I.first->eraseFromParent();
}
RemangledIntrinsics.clear();
UpgradeDebugInfo(*TheModule);
UpgradeModuleFlags(*TheModule);
UpgradeARCRuntime(*TheModule);
return Error::success();
}
Module的加载过程如下(更新的工作由AutoUpgrade类实现):
- 加载Metadata。
- 加载Function。
- Resolve前向引用。
- 更新Intrinsic Call(兼容老的IR)。
- 更新调试信息
- 更新Module Flags
- 更新ARC(ObjectC中的Automatic Reference Counting)