Lab4: Implement basic scalar optimizations and lower Phi nodes to assembly

This commit is contained in:
2026-05-05 10:20:15 +08:00
committed by CGH0S7
parent 0b0bc04be3
commit 8f7e0ac5b4
17 changed files with 1318 additions and 35 deletions

View File

@@ -47,6 +47,16 @@ void User::AddOperand(Value* value) {
value->AddUse(this, operand_index);
}
void User::ClearOperands() {
for (size_t i = 0; i < operands_.size(); ++i) {
auto* old = operands_[i];
if (old) {
old->RemoveUse(this, i);
}
}
operands_.clear();
}
Instruction::Instruction(Opcode op, std::shared_ptr<Type> ty, std::string name)
: User(std::move(ty), std::move(name)), opcode_(op) {}
@@ -168,4 +178,46 @@ Value* StoreInst::GetValue() const { return GetOperand(0); }
Value* StoreInst::GetPtr() const { return GetOperand(1); }
PhiInst::PhiInst(std::shared_ptr<Type> ty, std::string name)
: Instruction(Opcode::Phi, std::move(ty), std::move(name)) {}
void PhiInst::AddIncoming(Value* val, BasicBlock* bb) {
AddOperand(val);
AddOperand(bb);
}
size_t PhiInst::GetNumIncoming() const {
return GetNumOperands() / 2;
}
Value* PhiInst::GetIncomingValue(size_t i) const {
return GetOperand(2 * i);
}
BasicBlock* PhiInst::GetIncomingBlock(size_t i) const {
return static_cast<BasicBlock*>(GetOperand(2 * i + 1));
}
void PhiInst::SetIncomingValue(size_t i, Value* val) {
SetOperand(2 * i, val);
}
void PhiInst::SetIncomingBlock(size_t i, BasicBlock* bb) {
SetOperand(2 * i + 1, bb);
}
void PhiInst::RemoveIncomingBlock(BasicBlock* bb) {
std::vector<Value*> new_ops;
for (size_t i = 0; i < GetNumIncoming(); ++i) {
if (GetIncomingBlock(i) != bb) {
new_ops.push_back(GetIncomingValue(i));
new_ops.push_back(GetIncomingBlock(i));
}
}
ClearOperands();
for (auto* op : new_ops) {
AddOperand(op);
}
}
} // namespace ir