Skip to content

Commit

Permalink
Optimization: remove unreachable if/else branch
Browse files Browse the repository at this point in the history
  • Loading branch information
belijzajac committed Apr 27, 2024
1 parent 0e39898 commit aa33efb
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
33 changes: 32 additions & 1 deletion src/backend/intermediate/IRGenerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,38 @@ void IRGenerator::visit(AST::IfStmt &node) {
};

node.getCondition()->accept(*this);
const auto &[token, _] = getExpression(*node.getCondition());
const auto &[token, _] = getExpression(*node.getCondition(), false);

if (token->isLiteralType()) {
// compile-time optimization

bool canElseBranchBeRemoved;
switch (token->getType()) {
case TType::LIT_INT:
canElseBranchBeRemoved = token->getValue<int>() > 0;
break;
case TType::KW_TRUE:
canElseBranchBeRemoved = true;
break;
case TType::KW_FALSE:
canElseBranchBeRemoved = false;
break;
default:
throw InstructionError{fmt::format("Unsupported expression in if statement in {}:{}",
token->getPosition().getFileName(),
token->getPosition().getLineNo())};
}

if (canElseBranchBeRemoved) {
node.getBody()->accept(*this);
} else {
for (const auto &stmt : node.getElseStatements()) {
stmt->accept(*this);
}
}

return;
}

Operation comparisonOp = m_instructions.back().get()->getOperation();
Operation jumpOp;
Expand Down
30 changes: 26 additions & 4 deletions tests/programs/ProgramTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -986,12 +986,14 @@ TEST_F(ProgramTest, ConditionalBooleanFollowup) {
TEST_F(ProgramTest, ConditionalBooleanNested) {
constexpr auto program = R"(
fn main() {
bool value = true;
if (value) {
bool value1 = true;
bool value2 = true;
bool value3 = true;
if (value1) {
print("true");
if (value) {
if (value2) {
print("true");
if (value) {
if (value3) {
print("true");
}
}
Expand All @@ -1000,3 +1002,23 @@ TEST_F(ProgramTest, ConditionalBooleanNested) {
SetUp(program);
EXPECT_PROGRAM_OUTPUT(exec("./a.out"), "truetruetrue");
}

TEST_F(ProgramTest, ConditionalOptimizationRemoveElseBranch) {
constexpr auto program = R"(
fn main() {
if (5) { print("true"); } else { print("false"); }
if (true) { print("true"); } else { print("false"); }
})"sv;
SetUp(program);
EXPECT_PROGRAM_OUTPUT(exec("./a.out"), "truetrue");
}

TEST_F(ProgramTest, ConditionalOptimizationRemoveIfBranch) {
constexpr auto program = R"(
fn main() {
if (0) { print("true"); } else { print("false"); }
if (false) { print("true"); } else { print("false"); }
})"sv;
SetUp(program);
EXPECT_PROGRAM_OUTPUT(exec("./a.out"), "falsefalse");
}

0 comments on commit aa33efb

Please sign in to comment.