Skip to content

Commit

Permalink
Combine string constants in combine_strings() (halide#6717)
Browse files Browse the repository at this point in the history
* Combine string constants in combine_strings()

This is a pretty trivial optimization, but when printing (or enabling `debug`), it cuts the number of `halide_string_to_string()` calls we generate by ~half.

* Update IROperator.cpp
  • Loading branch information
steven-johnson authored and ardier committed Mar 3, 2024
1 parent 4b9eeec commit 540828f
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/IROperator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ Expr stringify(const std::vector<Expr> &args) {
}

Expr combine_strings(const std::vector<Expr> &args) {
if (args.empty()) {
return Expr("");
}

// Insert spaces between each expr.
std::vector<Expr> strings(args.size() * 2);
for (size_t i = 0; i < args.size(); i++) {
Expand All @@ -73,6 +77,20 @@ Expr combine_strings(const std::vector<Expr> &args) {
}
}

// Now combine all adjacent string literals, which is
// useful to reduce emitted code size when printing
size_t i = 0;
while (i < strings.size() - 1) {
const auto *cur_str = strings[i].as<Internal::StringImm>();
const auto *next_str = strings[i + 1].as<Internal::StringImm>();
if (cur_str && next_str) {
strings[i] = Internal::StringImm::make(cur_str->value + next_str->value);
strings.erase(strings.begin() + i + 1);
continue;
}
i++;
}

return stringify(strings);
}

Expand Down

0 comments on commit 540828f

Please sign in to comment.