Skip to content

Commit be1e50f

Browse files
authored
[flang] Avoid unnecessary looping for constants (#156403)
Going through and doing `convertToAttribute` for all elements, if they are the same can be costly. If the elements are the same, we can just call `convertToAttribute` once. This does give us a significant speed-up: ```console $ hyperfine --warmup 1 --runs 5 ./slow.sh ./fast.sh Benchmark 1: ./slow.sh Time (mean ± σ): 1.606 s ± 0.014 s [User: 1.393 s, System: 0.087 s] Range (min … max): 1.591 s … 1.628 s 5 runs Benchmark 2: ./fast.sh Time (mean ± σ): 452.9 ms ± 7.6 ms [User: 249.9 ms, System: 83.3 ms] Range (min … max): 443.9 ms … 461.7 ms 5 runs Summary ./fast.sh ran 3.55 ± 0.07 times faster than ./slow.sh ``` Fixes #125444
1 parent 759a2ac commit be1e50f

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

flang/lib/Lower/ConvertConstant.cpp

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,34 @@ class DenseGlobalBuilder {
145145
fir::FirOpBuilder &builder,
146146
const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>>
147147
&constant) {
148+
using Element =
149+
Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>;
150+
148151
static_assert(TC != Fortran::common::TypeCategory::Character,
149152
"must be numerical or logical");
150153
auto attrTc = TC == Fortran::common::TypeCategory::Logical
151154
? Fortran::common::TypeCategory::Integer
152155
: TC;
153156
attributeElementType =
154157
Fortran::lower::getFIRType(builder.getContext(), attrTc, KIND, {});
155-
for (auto element : constant.values())
158+
159+
const std::vector<Element> &values = constant.values();
160+
auto sameElements = [&]() -> bool {
161+
if (values.empty())
162+
return false;
163+
164+
return std::all_of(values.begin(), values.end(),
165+
[&](const auto &v) { return v == values.front(); });
166+
};
167+
168+
if (sameElements()) {
169+
auto attr = convertToAttribute<TC, KIND>(builder, values.front(),
170+
attributeElementType);
171+
attributes.assign(values.size(), attr);
172+
return;
173+
}
174+
175+
for (auto element : values)
156176
attributes.push_back(
157177
convertToAttribute<TC, KIND>(builder, element, attributeElementType));
158178
}

0 commit comments

Comments
 (0)