[flang-commits] [flang] [Flang] Apply nusw nuw flags on array_coor gep's (PR #184573)

Jack Styles via flang-commits flang-commits at lists.llvm.org
Wed Mar 4 02:21:47 PST 2026


================
@@ -2713,6 +2713,25 @@ struct XArrayCoorOpConversion
         baseIsBoxed ? getBoxTypePair(coor.getMemref().getType()) : TypePair{};
     mlir::LLVM::IntegerOverflowFlags nsw =
         mlir::LLVM::IntegerOverflowFlags::nsw;
+    mlir::LLVM::IntegerOverflowFlags nuw =
+        mlir::LLVM::IntegerOverflowFlags::nuw;
+    mlir::LLVM::IntegerOverflowFlags subFlags = nsw;
+    mlir::LLVM::IntegerOverflowFlags addMulFlags = nsw;
+    mlir::LLVM::GEPNoWrapFlags gepFlags = mlir::LLVM::GEPNoWrapFlags::none;
+
+    // In certain cases, where unsigned wrapping is known not to not occur, we
+    // can apply the nuw flag to Add/Mul operations, and `nusw nuw` flags to
+    // getelementptr's. By doing so, this enables better optimization through
+    // slp-vectorizer later in the LLVM pipeline.
+    const bool canUseNuw = !baseIsBoxed && !isShifted && !isSliced &&
+                           coor.getSubcomponent().empty() &&
+                           coor.getLenParams().empty() &&
+                           !coor.getShape().empty();
----------------
Stylie777 wrote:

canUseNuw is designed to only apply NUW is situations where it is certain there is no unsigned wrapping. As these flags are applied at compile time, not runtime, we need to be certain of no unsigned wrapping. 

So the following is checked (with reasoning):
- Must know the shape and not have length parameters. This is a safety step to ensure we are not using dynamic sized array's that may introduced unsigned wrapping situations at runtime.
- Array is not boxed, sliced or shifted. Similar to above, they may be dynamically sized and for these flags can cause issues.

I's designed to allow for vectorisation in the LLVM middle end with the lowest risk of undefined behaviour. 

I have updated the commit message to include this.

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


More information about the flang-commits mailing list