在 LLVM 中查找指令的后继列表
Finding the list of successors of an Instruction in LLVM
我想获取 llvm 中每条指令的后继列表。如果我没理解错的话,对于除了branch(br)之外的所有指令,后继指令就是下一条。但是对于分支指令来说有点棘手。
例如,如果我有以下 C 代码:
int main() {
int a = 7;
int b = a * 2;
int x;
if (a < 3) {
x = 10 + b;
} else {
x = 20 + a;
}
return b;
}
我得到以下字节码:
define i32 @main() #0 {
%1 = mul nsw i32 7, 2
%2 = icmp slt i32 7, 3
br i1 %2, label %3, label %5
; <label>:3: ; preds = %0
%4 = add nsw i32 10, %1
br label %7
; <label>:5: ; preds = %0
%6 = add nsw i32 20, 7
br label %7
; <label>:7: ; preds = %5, %3
ret i32 %1
}
所以说明
br i1 %2, label %3, label %5
有 2 个继任者:
{%4 = add new i32 10, %1, %6 = add nsw i32 20, 7}
如何从指令中获取后继者?
注意:我实际上想做的是消除死代码。我知道 llvm 在实时分析库中有一些方法,例如 IsInstructionTriviallyDead() 。出于练习目的,我不打算使用它们。
您可以使用 getSuccessor(unsigned)
& getNumSuccessors()
methods on BranchInst
. Given a BasicBlock *BB
, you can then access the first instruction via BB->front()
.
获取指令可以分支到的基本块
我想获取 llvm 中每条指令的后继列表。如果我没理解错的话,对于除了branch(br)之外的所有指令,后继指令就是下一条。但是对于分支指令来说有点棘手。
例如,如果我有以下 C 代码:
int main() {
int a = 7;
int b = a * 2;
int x;
if (a < 3) {
x = 10 + b;
} else {
x = 20 + a;
}
return b;
}
我得到以下字节码:
define i32 @main() #0 {
%1 = mul nsw i32 7, 2
%2 = icmp slt i32 7, 3
br i1 %2, label %3, label %5
; <label>:3: ; preds = %0
%4 = add nsw i32 10, %1
br label %7
; <label>:5: ; preds = %0
%6 = add nsw i32 20, 7
br label %7
; <label>:7: ; preds = %5, %3
ret i32 %1
}
所以说明
br i1 %2, label %3, label %5
有 2 个继任者:
{%4 = add new i32 10, %1, %6 = add nsw i32 20, 7}
如何从指令中获取后继者?
注意:我实际上想做的是消除死代码。我知道 llvm 在实时分析库中有一些方法,例如 IsInstructionTriviallyDead() 。出于练习目的,我不打算使用它们。
您可以使用 getSuccessor(unsigned)
& getNumSuccessors()
methods on BranchInst
. Given a BasicBlock *BB
, you can then access the first instruction via BB->front()
.