[clang] [CIR] Implement loop-hint lowering (PR #247320)

Konstantinos Parasyris via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 30 13:50:41 PST 2026


================
@@ -5186,6 +5192,414 @@ void ConvertCIRToLLVMPass::resolveBlockAddressOp(
   blockInfoAddr.clearUnresolvedMap();
 }
 
+namespace {
+/// Converts a `#cir.loop_hint` to the `llvm.loop_annotation` that lowers to the
+/// same `!llvm.loop` metadata as classic codegen's `LoopInfo::createMetadata`.
+/// Each `create*` function below corresponds to the function of the same name
+/// in CGLoopInfo.cpp, and the transformations are chained in the same order:
+/// full unroll, distribute, vectorize, unroll-and-jam, partial unroll, and
+/// pipelining. A hint that has to be applied after an earlier transformation
+/// goes into that transformation's follow-up.
+class LoopHintConverter {
+public:
+  LoopHintConverter(mlir::MLIRContext *ctx, cir::LoopHintAttr hints)
+      : ctx(ctx), hints(hints) {}
+
+  /// Returns the annotation of the loop. Like classic codegen, a loop that has
+  /// hints always gets a node of its own, even when it has no properties, as
+  /// is the case for a loop that is jammed into its parent. \p loopID makes the
+  /// annotation unique to one loop.
+  mlir::LLVM::LoopAnnotationAttr convert(mlir::Attribute loopID) {
+    Fields props;
+    props.mustProgress = hints.getMustProgress() != nullptr;
+    props.licmDisabled = hints.getLicmDisabled() != nullptr;
+    props.codeAlign = hints.getCodeAlign();
+
+    // TODO(cir): `parallel` needs an access group on the memory operations of
+    // the loop, which the LLVM dialect's loop annotation refers to.
+    assert(!cir::MissingFeatures::loopParallelAccesses());
+
+    bool hasTransforms = false;
+    return createFullUnroll(props, hasTransforms).toAttr(ctx, loopID);
+  }
+
+private:
+  /// The properties of one `!llvm.loop` node (or one of its follow-ups). Each
+  /// member maps to the member of the LLVM dialect's loop annotation that is
+  /// named in the comment.
+  struct Fields {
+    bool mustProgress = false;   // mustProgress
+    bool licmDisabled = false;   // licm.disable
+    uint32_t codeAlign = 0;      // align
+    mlir::BoolAttr isVectorized; // isVectorized
+
+    mlir::BoolAttr vectorizeDisable;   // vectorize.disable (negated)
+    mlir::BoolAttr vectorizePredicate; // vectorize.predicateEnable
+    mlir::BoolAttr vectorizeScalable;  // vectorize.scalableEnable
+    mlir::IntegerAttr vectorizeWidth;  // vectorize.width
+    mlir::LLVM::LoopAnnotationAttr vectorizeFollowup;
+    mlir::IntegerAttr interleaveCount; // interleave.count
+
+    mlir::BoolAttr unrollDisable; // unroll.disable (enable if false)
+    mlir::IntegerAttr unrollCount;
+    mlir::BoolAttr unrollFull;
+    mlir::LLVM::LoopAnnotationAttr unrollFollowup;
+
+    mlir::BoolAttr unrollAndJamDisable;
+    mlir::IntegerAttr unrollAndJamCount;
+    mlir::LLVM::LoopAnnotationAttr unrollAndJamFollowup;
+    mlir::LLVM::LoopAnnotationAttr unrollAndJamFollowupInner;
+
+    mlir::BoolAttr distributeDisable;
+    mlir::LLVM::LoopAnnotationAttr distributeFollowup;
+
+    mlir::BoolAttr pipelineDisable;
+    mlir::IntegerAttr pipelineInterval;
+
+    /// Add the properties of \p other that are not already set.
+    void merge(const Fields &other) {
+      mustProgress |= other.mustProgress;
+      licmDisabled |= other.licmDisabled;
+      if (!codeAlign)
+        codeAlign = other.codeAlign;
+      auto take = [](auto &mine, auto theirs) {
+        if (!mine)
+          mine = theirs;
+      };
+      take(isVectorized, other.isVectorized);
+      take(vectorizeDisable, other.vectorizeDisable);
+      take(vectorizePredicate, other.vectorizePredicate);
+      take(vectorizeScalable, other.vectorizeScalable);
+      take(vectorizeWidth, other.vectorizeWidth);
+      take(vectorizeFollowup, other.vectorizeFollowup);
+      take(interleaveCount, other.interleaveCount);
+      take(unrollDisable, other.unrollDisable);
+      take(unrollCount, other.unrollCount);
+      take(unrollFull, other.unrollFull);
+      take(unrollFollowup, other.unrollFollowup);
+      take(unrollAndJamDisable, other.unrollAndJamDisable);
+      take(unrollAndJamCount, other.unrollAndJamCount);
+      take(unrollAndJamFollowup, other.unrollAndJamFollowup);
+      take(unrollAndJamFollowupInner, other.unrollAndJamFollowupInner);
+      take(distributeDisable, other.distributeDisable);
+      take(distributeFollowup, other.distributeFollowup);
+      take(pipelineDisable, other.pipelineDisable);
+      take(pipelineInterval, other.pipelineInterval);
+    }
+
+    mlir::LLVM::LoopAnnotationAttr toAttr(mlir::MLIRContext *ctx,
+                                          mlir::Attribute loopID = {}) const {
+      using namespace mlir::LLVM;
+      LoopVectorizeAttr vectorize;
+      if (vectorizeDisable || vectorizePredicate || vectorizeScalable ||
+          vectorizeWidth || vectorizeFollowup)
+        vectorize = LoopVectorizeAttr::get(
+            ctx, vectorizeDisable, vectorizePredicate, vectorizeScalable,
+            vectorizeWidth, /*followupVectorized=*/{}, /*followupEpilogue=*/{},
+            vectorizeFollowup);
+
+      LoopInterleaveAttr interleave;
+      if (interleaveCount)
+        interleave = LoopInterleaveAttr::get(ctx, interleaveCount);
+
+      LoopUnrollAttr unroll;
+      if (unrollDisable || unrollCount || unrollFull || unrollFollowup)
+        unroll = LoopUnrollAttr::get(ctx, unrollDisable, unrollCount,
+                                     /*runtimeDisable=*/{}, unrollFull,
+                                     /*followupUnrolled=*/{},
+                                     /*followupRemainder=*/{}, unrollFollowup);
+
+      LoopUnrollAndJamAttr unrollAndJam;
+      if (unrollAndJamDisable || unrollAndJamCount || unrollAndJamFollowup ||
+          unrollAndJamFollowupInner)
+        unrollAndJam = LoopUnrollAndJamAttr::get(
+            ctx, unrollAndJamDisable, unrollAndJamCount,
+            /*followupOuter=*/unrollAndJamFollowup,
+            /*followupInner=*/unrollAndJamFollowupInner,
+            /*followupRemainderOuter=*/{}, /*followupRemainderInner=*/{},
+            /*followupAll=*/{});
+
+      LoopLICMAttr licm;
+      if (licmDisabled)
+        licm = LoopLICMAttr::get(ctx, mlir::BoolAttr::get(ctx, true),
+                                 /*versioningDisable=*/{});
+
+      LoopDistributeAttr distribute;
+      if (distributeDisable || distributeFollowup)
+        distribute = LoopDistributeAttr::get(
+            ctx, distributeDisable, /*followupCoincident=*/{},
+            /*followupSequential=*/{}, /*followupFallback=*/{},
+            distributeFollowup);
+
+      LoopPipelineAttr pipeline;
+      if (pipelineDisable || pipelineInterval)
+        pipeline =
+            LoopPipelineAttr::get(ctx, pipelineDisable, pipelineInterval);
+
+      mlir::DistinctAttr loopIdDistinct =
+          mlir::cast_if_present<mlir::DistinctAttr>(loopID);
+
+      return LoopAnnotationAttr::get(
+          ctx, loopIdDistinct, /*disableNonforced=*/{}, vectorize, interleave,
+          unroll, unrollAndJam, licm, distribute, pipeline, /*peeled=*/{},
+          /*unswitch=*/{},
+          mustProgress ? mlir::BoolAttr::get(ctx, true) : mlir::BoolAttr(),
+          isVectorized, codeAlign, /*startLoc=*/{}, /*endLoc=*/{},
+          /*parallelAccesses=*/{});
+    }
+  };
+
+  mlir::IntegerAttr i32(uint32_t value) const {
+    return mlir::IntegerAttr::get(mlir::IntegerType::get(ctx, 32), value);
+  }
+  mlir::BoolAttr boolAttr(bool value) const {
+    return mlir::BoolAttr::get(ctx, value);
+  }
+
+  /// Builds a follow-up from the result of the next transformation.
+  mlir::LLVM::LoopAnnotationAttr followup(const Fields &fields) const {
+    return fields.toAttr(ctx);
+  }
+
+  Fields createPipelining(const Fields &props, bool &hasTransforms) const {
+    std::optional<bool> enabled;
+    if (hints.getPipelineDisabled())
+      enabled = false;
+    else if (hints.getPipelineInitiationInterval() != 0)
+      enabled = true;
+
+    Fields args = props;
+    if (enabled != true) {
+      if (enabled == false)
+        args.pipelineDisable = boolAttr(true);
+      return args;
+    }
+
+    args.pipelineInterval = i32(hints.getPipelineInitiationInterval());
+    // No follow-up: this is the last transformation.
+    hasTransforms = true;
+    return args;
+  }
+
+  Fields createPartialUnroll(const Fields &props, bool &hasTransforms) const {
+    std::optional<cir::LoopUnrollMode> mode = hints.getUnroll();
+    std::optional<bool> enabled;
+    if (mode == cir::LoopUnrollMode::Disable)
+      enabled = false;
+    else if (mode == cir::LoopUnrollMode::Full)
+      enabled = std::nullopt;
+    else if (mode || hints.getUnrollCount() != 0)
+      enabled = true;
+
+    // createFullUnroll already disabled unrolling if that was requested.
+    if (enabled != true)
+      return createPipelining(props, hasTransforms);
+
+    // Don't unroll an already unrolled loop.
+    Fields followupProps = props;
+    followupProps.unrollDisable = boolAttr(true);
+    bool followupHasTransforms = false;
+    Fields next = createPipelining(followupProps, followupHasTransforms);
+
+    Fields args = props;
+    if (hints.getUnrollCount() > 0)
+      args.unrollCount = i32(hints.getUnrollCount());
+    if (mode == cir::LoopUnrollMode::Enable)
+      args.unrollDisable = boolAttr(false);
+    if (followupHasTransforms)
+      args.unrollFollowup = followup(next);
+
+    hasTransforms = true;
+    return args;
+  }
+
+  Fields createUnrollAndJam(const Fields &props, bool &hasTransforms) const {
+    std::optional<cir::LoopUnrollMode> mode = hints.getUnrollAndJam();
+    std::optional<bool> enabled;
+    if (mode == cir::LoopUnrollMode::Disable)
+      enabled = false;
+    else if (mode == cir::LoopUnrollMode::Enable ||
+             hints.getUnrollAndJamCount() != 0)
+      enabled = true;
+
+    if (enabled != true) {
+      Fields newProps = props;
+      if (enabled == false)
+        newProps.unrollAndJamDisable = boolAttr(true);
+      return createPartialUnroll(newProps, hasTransforms);
+    }
+
+    Fields followupProps = props;
+    followupProps.unrollAndJamDisable = boolAttr(true);
+    bool followupHasTransforms = false;
+    Fields next = createPartialUnroll(followupProps, followupHasTransforms);
+
+    Fields args = props;
+    if (hints.getUnrollAndJamCount() > 0)
+      args.unrollAndJamCount = i32(hints.getUnrollAndJamCount());
+    if (mode == cir::LoopUnrollMode::Enable)
+      args.unrollAndJamDisable = boolAttr(false);
+    if (followupHasTransforms)
+      args.unrollAndJamFollowup = followup(next);
+
+    // CIR codegen has already split the hints of the first loop inside of this
+    // one into the ones before and after the jam, like classic codegen does,
+    // so the latter are what is left to do to that loop after the jam. When it
+    // was vectorized before, which the hints say, it must not be again.
+    if (auto inner = mlir::cast_if_present<cir::LoopHintAttr>(
+            hints.getUnrollAndJamInner())) {
+      Fields innerProps;
+      if (inner.getVectorized())
+        innerProps.isVectorized = boolAttr(true);
+      bool innerHasTransforms = false;
+      Fields innerFields =
+          LoopHintConverter(ctx, inner)
+              .createFullUnroll(innerProps, innerHasTransforms);
+      if (innerHasTransforms)
+        args.unrollAndJamFollowupInner = followup(innerFields);
+    }
+
+    hasTransforms = true;
+    return args;
+  }
+
+  Fields createVectorize(const Fields &props, bool &hasTransforms) const {
+    mlir::BoolAttr predicate = hints.getVectorizePredicate();
+    mlir::BoolAttr scalable = hints.getVectorizeScalable();
+    uint32_t width = hints.getVectorizeWidth();
+    bool enabled = hints.getVectorizeEnable() || predicate || scalable ||
+                   hints.getInterleaveCount() != 0 || width != 0;
----------------
koparasy wrote:

You need here somehting like:
```
mlir::BoolAttr vectorize = hints.getVectorizeEnable();
bool vectorizeOn = vectorize && vectorize.getValue();
```

and use vectorizeOn accordingly.

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


More information about the cfe-commits mailing list