Skip to content

Conversation

@joker-eph
Copy link
Collaborator

Also improve a bit the doc in the LDBG() implementation

@joker-eph joker-eph requested review from Copilot and jpienaar August 16, 2025 16:07
@llvmbot llvmbot added mlir:core MLIR Core Infrastructure mlir llvm:support labels Aug 16, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR updates the GreedyRewriter in MLIR to use the LDBG() debug log mechanism instead of direct llvm::dbgs() calls, providing more consistent debug logging with proper prefixing. It also improves documentation and variable naming in the LDBG() implementation.

Key changes:

  • Replace direct llvm::dbgs() calls with LDBG() macro for consistent debug logging
  • Update debug log prefix format to include ":1" suffix for consistency
  • Improve variable naming and comments in the LDBG() implementation

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp Migrates debug logging to LDBG() mechanism and adds necessary headers
mlir/lib/Transforms/Utils/DialectConversion.cpp Updates debug log prefix format for consistency
llvm/include/llvm/Support/DebugLog.h Improves variable naming and documentation in LDBG() implementation

@llvmbot
Copy link
Member

llvmbot commented Aug 16, 2025

@llvm/pr-subscribers-mlir-core
@llvm/pr-subscribers-llvm-support

@llvm/pr-subscribers-mlir

Author: Mehdi Amini (joker-eph)

Changes

Also improve a bit the doc in the LDBG() implementation


Full diff: https://github.com/llvm/llvm-project/pull/153961.diff

3 Files Affected:

  • (modified) llvm/include/llvm/Support/DebugLog.h (+10-10)
  • (modified) mlir/lib/Transforms/Utils/DialectConversion.cpp (+2-2)
  • (modified) mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp (+17-13)
diff --git a/llvm/include/llvm/Support/DebugLog.h b/llvm/include/llvm/Support/DebugLog.h
index a94e578c0aa1e..8cc05796374b8 100644
--- a/llvm/include/llvm/Support/DebugLog.h
+++ b/llvm/include/llvm/Support/DebugLog.h
@@ -89,22 +89,22 @@ namespace impl {
 class LLVM_ABI raw_ldbg_ostream final : public raw_ostream {
   std::string Prefix;
   raw_ostream &Os;
-  bool HasPendingNewline;
+  bool ShouldPrefixNextString;
 
   /// Split the line on newlines and insert the prefix before each
   /// newline. Forward everything to the underlying stream.
   void write_impl(const char *Ptr, size_t Size) final {
     auto Str = StringRef(Ptr, Size);
-    // Handle the initial prefix.
-    if (!Str.empty())
-      writeWithPrefix(StringRef());
-
     auto Eol = Str.find('\n');
+    // Hangle `\n` occuring the string, ensure to print the prefix at the
+    // beginning of each line.
     while (Eol != StringRef::npos) {
+      // Take the line up to the newline (including the newline).
       StringRef Line = Str.take_front(Eol + 1);
       if (!Line.empty())
         writeWithPrefix(Line);
-      HasPendingNewline = true;
+      // We printed a newline, record here to print a prefix.
+      ShouldPrefixNextString = true;
       Str = Str.drop_front(Eol + 1);
       Eol = Str.find('\n');
     }
@@ -119,16 +119,16 @@ class LLVM_ABI raw_ldbg_ostream final : public raw_ostream {
 
 public:
   explicit raw_ldbg_ostream(std::string Prefix, raw_ostream &Os,
-                            bool HasPendingNewline = true)
+                            bool ShouldPrefixNextString = true)
       : Prefix(std::move(Prefix)), Os(Os),
-        HasPendingNewline(HasPendingNewline) {
+        ShouldPrefixNextString(ShouldPrefixNextString) {
     SetUnbuffered();
   }
   ~raw_ldbg_ostream() final { flushEol(); }
   void flushEol() {
-    if (HasPendingNewline) {
+    if (ShouldPrefixNextString) {
       emitPrefix();
-      HasPendingNewline = false;
+      ShouldPrefixNextString = false;
     }
   }
 
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index ff34a58965763..2877090354588 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -1138,8 +1138,8 @@ struct ConversionPatternRewriterImpl : public RewriterBase::Listener {
   SmallPtrSet<Operation *, 1> pendingRootUpdates;
 
   /// A raw output stream used to prefix the debug log.
-  llvm::impl::raw_ldbg_ostream os{(Twine("[") + DEBUG_TYPE + "] ").str(),
-                                  llvm::dbgs(), /*HasPendingNewline=*/false};
+  llvm::impl::raw_ldbg_ostream os{(Twine("[") + DEBUG_TYPE + ":1] ").str(),
+                                  llvm::dbgs()};
 
   /// A logger used to emit diagnostics during the conversion process.
   llvm::ScopedPrinter logger{os};
diff --git a/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp b/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
index 607b86cb86315..e7b49b4b494dc 100644
--- a/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
+++ b/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
@@ -15,6 +15,8 @@
 #include "mlir/Config/mlir-config.h"
 #include "mlir/IR/Action.h"
 #include "mlir/IR/Matchers.h"
+#include "mlir/IR/Operation.h"
+#include "mlir/IR/OperationSupport.h"
 #include "mlir/IR/Verifier.h"
 #include "mlir/Interfaces/SideEffectInterfaces.h"
 #include "mlir/Rewrite/PatternApplicator.h"
@@ -23,7 +25,7 @@
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/ScopeExit.h"
-#include "llvm/Support/Debug.h"
+#include "llvm/Support/DebugLog.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -178,9 +180,8 @@ static Operation *getDumpRootOp(Operation *op) {
   return op;
 }
 static void logSuccessfulFolding(Operation *op) {
-  llvm::dbgs() << "// *** IR Dump After Successful Folding ***\n";
-  op->dump();
-  llvm::dbgs() << "\n\n";
+  LDBG() << "// *** IR Dump After Successful Folding ***\n"
+         << OpWithFlags(op, OpPrintingFlags().elideLargeElementsAttrs());
 }
 #endif // NDEBUG
 
@@ -394,8 +395,13 @@ class GreedyPatternRewriteDriver : public RewriterBase::Listener {
                      function_ref<void(Diagnostic &)> reasonCallback) override;
 
 #ifndef NDEBUG
+  /// A raw output stream used to prefix the debug log.
+
+  llvm::impl::RAIINewLineStream dbgsWithNewLine{llvm::dbgs()};
+  llvm::impl::raw_ldbg_ostream os{(Twine("[") + DEBUG_TYPE + ":1] ").str(),
+                                  dbgsWithNewLine};
   /// A logger used to emit information during the application process.
-  llvm::ScopedPrinter logger{llvm::dbgs()};
+  llvm::ScopedPrinter logger{os};
 #endif
 
   /// The low-level pattern applicator.
@@ -917,10 +923,9 @@ mlir::applyPatternsGreedily(Region &region,
   RegionPatternRewriteDriver driver(region.getContext(), patterns, config,
                                     region);
   LogicalResult converged = std::move(driver).simplify(changed);
-  LLVM_DEBUG(if (failed(converged)) {
-    llvm::dbgs() << "The pattern rewrite did not converge after scanning "
-                 << config.getMaxIterations() << " times\n";
-  });
+  if (failed(converged))
+    LDBG() << "The pattern rewrite did not converge after scanning "
+           << config.getMaxIterations() << " times\n";
   return converged;
 }
 
@@ -1052,9 +1057,8 @@ LogicalResult mlir::applyOpPatternsGreedily(
   LogicalResult converged = std::move(driver).simplify(ops, changed);
   if (allErased)
     *allErased = surviving.empty();
-  LLVM_DEBUG(if (failed(converged)) {
-    llvm::dbgs() << "The pattern rewrite did not converge after "
-                 << config.getMaxNumRewrites() << " rewrites";
-  });
+  if (failed(converged))
+    LDBG() << "The pattern rewrite did not converge after "
+           << config.getMaxNumRewrites() << " rewrites";
   return converged;
 }

@joker-eph joker-eph force-pushed the ldbg_greedy branch 3 times, most recently from 4270f9c to 1ff0f7e Compare August 17, 2025 09:20
@github-actions
Copy link

github-actions bot commented Aug 17, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

@joker-eph joker-eph force-pushed the ldbg_greedy branch 2 times, most recently from 4d25e59 to d1018c2 Compare August 18, 2025 09:03
Also improve a bit the doc in the LDBG() implementation
@joker-eph joker-eph enabled auto-merge (squash) August 18, 2025 20:40
@joker-eph joker-eph merged commit 89abccc into llvm:main Aug 18, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llvm:support mlir:core MLIR Core Infrastructure mlir

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants