Skip to content

Commit

Permalink
support for constants
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelsamenezes committed Jul 1, 2024
1 parent caaba81 commit ad660ab
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 3 deletions.
38 changes: 35 additions & 3 deletions src/bounded-loop-unroller/frontend_visitor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@

namespace BoundedLoopUnroller {

const clang::IntegerLiteral *
get_init_value_from_decl(const clang::VarDecl *const decl) {
if (!decl || !decl->hasInit())
return nullptr;

if (const clang::IntegerLiteral *const value_cast =
llvm::dyn_cast<clang::IntegerLiteral>(decl->getInit()->IgnoreCasts()))
return value_cast;

return nullptr;
}

std::string frontend_visitor::get_original_source(const clang::Stmt *const E) const {
const char *e_start = sm.getCharacterData(E->getBeginLoc()),
*e_end = sm.getCharacterData(E->getEndLoc());
Expand Down Expand Up @@ -93,9 +105,29 @@ namespace BoundedLoopUnroller {
assert(bin_op);

const clang::DeclRefExpr *const condition_var =
llvm::dyn_cast<clang::DeclRefExpr>(bin_op->getLHS()->IgnoreCasts());
const clang::IntegerLiteral *const condition_limit =
llvm::dyn_cast<clang::IntegerLiteral>(bin_op->getRHS()->IgnoreCasts());
llvm::dyn_cast<clang::DeclRefExpr>(bin_op->getLHS()->IgnoreCasts());

const clang::IntegerLiteral * condition_limit;


if (const clang::IntegerLiteral *const value_cast =
llvm::dyn_cast<clang::IntegerLiteral>(bin_op->getRHS()->IgnoreCasts())) {
condition_limit = value_cast;
} else if (const clang::DeclRefExpr *const value_cast =
llvm::dyn_cast<clang::DeclRefExpr>(
bin_op->getRHS()->IgnoreCasts())) {
if (!value_cast->getType().isConstant(context))
return CONTINUE_SEARCH;
const clang::VarDecl *const decl =
llvm::dyn_cast<clang::VarDecl>(value_cast->getDecl());
condition_limit = get_init_value_from_decl(decl);
} else
return CONTINUE_SEARCH;







const std::array SUPPORTED_OP{clang::BinaryOperator::Opcode::BO_GE, clang::BinaryOperator::Opcode::BO_GT, clang::BinaryOperator::Opcode::BO_LE, clang::BinaryOperator::Opcode::BO_LT, };
Expand Down
34 changes: 34 additions & 0 deletions unit/bounded-loop-unroller.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,37 @@ int main() {
REQUIRE(actual == expected);
}

TEST_CASE("One-line <= For-Loops are detected with const condition", "[for]") {
auto initial = R"(
int main() { const int N = 3; int a; for (int i = 0; i <= N; i++) a++; return 0; })";
auto expected = R"(
int main() {
const int N = 3;
int a;
int i = 0;
{
a++;
i++;
}
{
a++;
i++;
}
{
a++;
i++;
}
{
a++;
i++;
}
return 0;
})";
auto actual = run_test(initial);
REQUIRE(actual == expected);
}

0 comments on commit ad660ab

Please sign in to comment.