[llvm] [LoadStoreVectorizer] Propagate alignment through contiguous chain (PR #145733)

Drew Kersnar via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 9 09:17:30 PDT 2025


================
@@ -1634,3 +1638,32 @@ std::optional<APInt> Vectorizer::getConstantOffset(Value *PtrA, Value *PtrB,
         .sextOrTrunc(OrigBitWidth);
   return std::nullopt;
 }
+
+void Vectorizer::propagateBestAlignmentsInChain(ArrayRef<ChainElem> C) const {
+  auto PropagateAlignments = [](auto ChainIt) {
+    ChainElem BestAlignedElem = *ChainIt.begin();
+    Align BestAlignSoFar = getLoadStoreAlignment(BestAlignedElem.Inst);
+
+    for (const ChainElem &E : ChainIt) {
+      Align OrigAlign = getLoadStoreAlignment(E.Inst);
+      if (OrigAlign > BestAlignSoFar) {
+        BestAlignedElem = E;
+        BestAlignSoFar = OrigAlign;
+        continue;
+      }
+
+      APInt DeltaFromBestAlignedElem =
+          APIntOps::abdu(E.OffsetFromLeader, BestAlignedElem.OffsetFromLeader);
+      // commonAlignment is equivalent to a greatest common power-of-two
+      // divisor; it returns the largest power of 2 that divides both A and B.
+      Align NewAlign = commonAlignment(
+          BestAlignSoFar, DeltaFromBestAlignedElem.getLimitedValue());
+      if (NewAlign > OrigAlign)
+        setLoadStoreAlignment(E.Inst, NewAlign);
+    }
+  };
+
+  // Propagate forwards and backwards.
+  PropagateAlignments(C);
+  PropagateAlignments(reverse(C));
----------------
dakersnar wrote:

> What if the alignment info at the beginning/end of the chain conflict?

I think this isn't possible if the input IR is correct, right? For example, if one piece of analysis proves that a load is aligned to 4, and another proves it is aligned to 16, they are both correct, it's just that the 16 is a more precise result, and thus we should prefer it as it gives us more information.

> I think we should only propagate alignment info in one direction, forward, as it's the alignment of the base pointer that's the ground truth there.

I can't really argue against that from a practicality perspective, as I haven't come up with a use case for the reverse propagation. But it would be correct, as the alignment argument on any load/store input IR has to be accurate, right? https://llvm.org/docs/LangRef.html#load-instruction for reference. "It is the responsibility of the code emitter to ensure that the alignment information is correct. Overestimating the alignment results in undefined behavior. Underestimating the alignment may produce less efficient code."

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


More information about the llvm-commits mailing list