You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// 死代码删除( DCE) :
// - 删除无用指令与无用基本块
// - 标记-清扫算法:先标记有用指令,再清除未标记的
# include "ir/IR.h"
# include <unordered_set>
# include <vector>
namespace ir {
namespace {
bool HasSideEffect ( Instruction * inst ) {
switch ( inst - > GetOpcode ( ) ) {
case Opcode : : Store :
case Opcode : : Call :
case Opcode : : Br :
case Opcode : : CondBr :
case Opcode : : Ret :
return true ;
default :
return false ;
}
}
} // namespace
bool RunDCE ( Function & func ) {
bool changed = false ;
for ( auto & bb : func . GetBlocks ( ) ) {
// 收集要删除的指令
std : : vector < Instruction * > to_remove ;
for ( auto & inst : bb - > GetInstructions ( ) ) {
auto * ip = inst . get ( ) ;
if ( ip - > IsTerminator ( ) ) continue ;
if ( HasSideEffect ( ip ) ) continue ;
// 检查该指令是否有使用者
bool has_use = false ;
for ( const auto & use : ip - > GetUses ( ) ) {
if ( use . GetUser ( ) ) {
has_use = true ;
break ;
}
}
if ( ! has_use ) {
to_remove . push_back ( ip ) ;
}
}
for ( auto * ip : to_remove ) {
// 断开该指令对操作数的引用
for ( size_t i = 0 ; i < ip - > GetNumOperands ( ) ; + + i ) {
ip - > SetOperand ( i , nullptr ) ;
}
ip - > RemoveFromParent ( ) ;
changed = true ;
}
bb - > SweepDeadInstructions ( ) ;
}
return changed ;
}
} // namespace ir