pass 管理器
pass管理器的实现在 lib/Transforms/IPO/
中,最主要的是PassManagerBuilder.cpp
。
这个管理器主要起两个作用:
- 协调分析结果
通常,在编译过程中会有一个以上的分析模块(pass)参与分析过程,管理器会协调处理每个pass的分析结果,尽量避免结果的多次重复计算,同时使得某些pass可以有时机去释放内存。 - 统筹分析流程
上一节中我们提到了,各个pass之间会有一定的依赖,更准确的说是先后顺序。管理器会通过用户定义的依赖需求去统筹分析流程,同时保证某一时间段内所有的pass都依次作用于单一函数。
- 可以通过
--debug-pass=Structure
选项来查看各个pass的大致依赖及协同过程:
opt -load=/home/happy/Documents/llvm8_build/lib/IterInsideBB.so -IterInsideBB -licm --debug-pass=Structure < 1.ll >/dev/null
- 可以通过
-time-passes
获取某个pass集合运行所耗费的时间及LLVM IR解析时间:
opt -load=/home/happy/Documents/llvm8_build/lib/IterInsideBB.so -IterInsideBB -time-passes < 1.ll >/dev/null
更多有用的选项可以通过
opt -help-hidden
获取。
llvm 多数的内置pass都是以静态库的形式存在的,同时PassManagerBuilder.cpp
中定义了全局的开关及初始化开关。
调试输出
在编写pass逻辑的过程中,我们多数情况下会需要输出一些调试日志,以方便我们定位问题。
我们可以使用printf或者cout等实现调试信息的输出,但是llvm提供了更为便利的接口。
我们可以在include/llvm/Support/Debug.h
中找到如下的两个宏:
/// DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug
/// information. In the '-debug' option is specified on the commandline, and if
/// this is a debug build, then the code specified as the option to the macro
/// will be executed. Otherwise it will not be. Example:
///
/// DEBUG_WITH_TYPE("bitset", dbgs() << "Bitset contains: " << Bitset << "\n");
///
/// This will emit the debug information if -debug is present, and -debug-only
/// is not specified, or is specified as "bitset".
#define DEBUG_WITH_TYPE(TYPE, X) \
do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)) { X; } \
} while (0)
#else
#define isCurrentDebugType(X) (false)
#define setCurrentDebugType(X)
#define DEBUG_WITH_TYPE(TYPE, X) do { } while (0)
#endif
#define DEBUG(X) DEBUG_WITH_TYPE(DEBUG_TYPE, X)
现在可以为代码加上一些调试输出:
bool runOnFunction(Function &F) override {
Function *tmp = &F;
DEBUG_WITH_TYPE(DEBUG_TYPE, errs() << "charge function:" << tmp->getName() << "\n");
// 遍历函数中的所有基本块
for (Function::iterator bb = tmp->begin(); bb != tmp->end(); ++bb) {
// 遍历基本块中的每条指令
for (BasicBlock::iterator inst = bb->begin();
inst != bb->end();
++inst) {
// 是否是add指令
if (inst->isBinaryOp()) {
if (inst->getOpcode() == Instruction::Add) {
DEBUG_WITH_TYPE(DEBUG_TYPE, errs() << "found add instruction\n");
ob_add(cast<BinaryOperator>(inst));
}
}
}
}
return false;
}
使用opt加载时只需要指定-debug
选项即可看到调试输出。
注意:如果编译LLVM Pass时打开了优化开关(明确来说,是定义了NDEBUG宏),则DEBUG()宏是禁用的。以它们免影响性能。DEBUG()宏还有一个好处,就是可以在gdb中直接使能或者禁用。 用gdb将应用程序调起来后,使用set DebugFlag=1
或者set DebugFlag=0
来实现。
使用这两个宏还有一些很有趣的用法和细节,可以自行参看这里。
调试Pass
关于动态调试pass,总的原则是编译好的独立的pass类似于插件一样被opt加载,因此我们可以直接去调试opt,通过PassManager找到具体的pass入口。
官网上关于这部分的介绍也很鸡肋,感兴趣的同学可以参考这里。
一般来说,熟练的掌握llvm相关接口,加上调试输出,要调试一个pass不是很难。