[llvm] [SCEV] Avoid erase+insert in constant folding (PR #101642)

Philip Reames via llvm-commits llvm-commits at lists.llvm.org
Thu Aug 15 08:55:56 PDT 2024


================
@@ -844,34 +844,39 @@ static const SCEV *
 constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
                         SmallVectorImpl<const SCEV *> &Ops, FoldT Fold,
                         IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
-  const SCEVConstant *Folded = nullptr;
+  bool HasConst = false;
   for (unsigned Idx = 0; Idx < Ops.size();) {
     const SCEV *Op = Ops[Idx];
     if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
-      if (!Folded)
-        Folded = C;
-      else
-        Folded = cast<SCEVConstant>(
-            SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
-      Ops.erase(Ops.begin() + Idx);
-      continue;
+      if (!HasConst) {
+        // Move the constant to the start.
+        std::swap(Ops[0], Ops[Idx]);
----------------
preames wrote:

Rather than swap, can we shift the elements between 0 and Idx up one, and then insert the constant?  This would keep the operand order unchanged.  I'm a bit leery of the downstream effects of mutating the order of the unordered elements.  Who knows what missed optimization we might trigger.  

https://github.com/llvm/llvm-project/pull/101642


More information about the llvm-commits mailing list