[llvm] [LoopInterchange] Improve profitability check for vectorization (PR #133672)

Ryotaro Kasuga via llvm-commits llvm-commits at lists.llvm.org
Tue Jul 15 11:18:27 PDT 2025


================
@@ -1197,27 +1209,57 @@ LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
   return std::nullopt;
 }
 
+static char flipDirection(char Dir) {
+  switch (Dir) {
+  case '<':
+    return '>';
+  case '>':
+    return '<';
+  case '=':
+  case 'I':
+  case '*':
+    return Dir;
+  default:
+    llvm_unreachable("Unknown direction");
+  }
+}
+
 /// Return true if we can vectorize the loop specified by \p LoopId.
-static bool canVectorize(const CharMatrix &DepMatrix, unsigned LoopId) {
+static bool canVectorize(const CharMatrix &DepMatrix,
+                         const BitVector &IsNegatedVec, unsigned LoopId) {
+  // The loop can be vectorized if there are no negative dependencies. Consider
+  // the dependency of `j` in the following example.
+  //
+  //   Positive: ... = A[i][j]       Negative: ... = A[i][j-1]
+  //             A[i][j-1] = ...               A[i][j] = ...
----------------
kasuga-fj wrote:

Thanks a lot for the really thorough explanation! It took me some time to fully understand it, but I believe I got what you meant.

> 
> In the polyhedral model one just assigns numbers to the sequence of statements in the loop which allows doing calculations over statement order as if it was another loop:
> 
> ```c
> for (int i = 0; i < n; ++i) {
>   for (int k = 0; k < 2; ++i) {
>     switch (k) {
>     case 0:
>       use(A[i]);
>       break;
>     case 1:
>       A[i-1] = 42; 
>       break;
>     }
>   }
> }
> ```
> 
> In this view, a forward dependency is when the innermost distance vector element (i.e. `k`) is positive, and a backward dependency is when the innermost dependence vector element is negative. I find this view helpful.

Yes, that made it much clearer. Thanks! And thanks to this, I finally see why you recommended to represent the information about whether a dependency is forward or not by the last element of the direction vector.


> The entire forward/backward nomenclature also breaks down if you allow non-perfectly nested loops.
> 
> I also dislike calling those "lexically" forward/backward. I can use e.g. gotos to change the lexical order of statements:
> 
> ```
> for (int i = 1; i < n; ++i) {
> goto T;
> S:
>   A[i] = 42;
>   goto NEXT;
> T:
>   use(A[i]);
>   goto S;
> NEXT:
> }
> ```

(This is probably off-topic, but seeing this made me realize that I was almost confusing the "lexicographical order" in the context of direction vectors with the "lexical forward/backward" in LAA.)

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


More information about the llvm-commits mailing list