Skip to content

Commit

Permalink
Implement conditional breaks in switch cases.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 607343929
  • Loading branch information
Sean Purser-Haskell authored and copybara-github committed Feb 15, 2024
1 parent c7fe0b1 commit cbc1da9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
13 changes: 9 additions & 4 deletions xls/contrib/xlscc/translator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5125,12 +5125,17 @@ absl::Status Translator::GenerateIR_Stmt(const clang::Stmt* stmt,
// We use the original condition because we only care about
// enclosing conditions, such as if(...) { break; }
// Not if(...) {return;} break;
if (context().full_condition_on_enter_block.node() !=
if (context().full_condition_on_enter_block.node() ==
context().full_switch_cond.node()) {
return absl::UnimplementedError(
ErrorMessage(loc, "Conditional breaks are not supported"));
context().hit_break = true;
} else {
context().relative_break_condition =
context().relative_condition_bval(loc);

// Make the rest of the block no-op
XLS_RETURN_IF_ERROR(
and_condition(context().fb->Literal(xls::UBits(0, 1), loc), loc));
}
context().hit_break = true;
}
} else if (clang::isa<clang::CompoundStmt>(stmt)) {
PushContextGuard context_guard(*this, loc);
Expand Down
31 changes: 27 additions & 4 deletions xls/contrib/xlscc/unit_tests/translator_logic_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,29 @@ TEST_F(TranslatorLogicTest, SwitchStmtWithUnrollInCase) {
Run({{"a", 3}}, 300, content);
}

TEST_F(TranslatorLogicTest, SwitchConditionalBreakReturn) {
std::string_view content = R"(
long long my_package(long long a, long long b) {
long long ret;
switch(a) {
case 1:
ret = 100;
break;
case 2:
ret = 200;
if(b) return 55;
default:
return 300;
}
return ret;
})";

Run({{"a", 1}, {"b", 0}}, 100, content);
Run({{"a", 2}, {"b", 0}}, 300, content);
Run({{"a", 2}, {"b", 1}}, 55, content);
Run({{"a", 3}, {"b", 0}}, 300, content);
}

TEST_F(TranslatorLogicTest, SwitchConditionalBreak) {
std::string_view content = R"(
long long my_package(long long a, long long b) {
Expand All @@ -973,10 +996,10 @@ TEST_F(TranslatorLogicTest, SwitchConditionalBreak) {
return ret;
})";

ASSERT_THAT(SourceToIr(content).status(),
xls::status_testing::StatusIs(
absl::StatusCode::kUnimplemented,
testing::HasSubstr("Conditional breaks are not supported")));
Run({{"a", 1}, {"b", 0}}, 100, content);
Run({{"a", 2}, {"b", 0}}, 300, content);
Run({{"a", 2}, {"b", 1}}, 200, content);
Run({{"a", 3}, {"b", 0}}, 300, content);
}

TEST_F(TranslatorLogicTest, SwitchStmtDefaultTop) {
Expand Down

0 comments on commit cbc1da9

Please sign in to comment.