MLIR 24.0.0git
Remarks.h
Go to the documentation of this file.
1//===- Remarks.h - MLIR Optimization Remark ----------------------*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines utilities for emitting optimization remarks.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_REMARKS_H
14#define MLIR_IR_REMARKS_H
15
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLFunctionalExtras.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/IR/DiagnosticInfo.h"
20#include "llvm/Remarks/Remark.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/Regex.h"
23
24#include "mlir/IR/Diagnostics.h"
25#include "mlir/IR/MLIRContext.h"
26#include "mlir/IR/Value.h"
27
28#include <atomic>
29#include <mutex>
30#include <optional>
31#include <utility>
32
33namespace mlir::remark {
34
35//===----------------------------------------------------------------------===//
36// RemarkId - Unique identifier for linking related remarks
37//===----------------------------------------------------------------------===//
38
39/// A unique identifier for a remark, used to link related remarks together.
40/// An invalid/empty ID has value 0.
41class RemarkId {
42public:
43 RemarkId() : id(0) {}
44 explicit RemarkId(uint64_t id) : id(id) {}
45
46 /// Check if this is a valid (non-zero) ID.
47 explicit operator bool() const { return id != 0; }
48
49 /// Get the raw ID value.
50 uint64_t getValue() const { return id; }
51
52 bool operator==(const RemarkId &other) const { return id == other.id; }
53 bool operator!=(const RemarkId &other) const { return id != other.id; }
54
55 /// Print the ID.
56 void print(llvm::raw_ostream &os) const { os << "remark-" << id; }
57
58private:
59 uint64_t id;
60};
61
62inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, RemarkId id) {
63 id.print(os);
64 return os;
65}
66
67/// Define an the set of categories to accept. By default none are, the provided
68/// regex matches against the category names for each kind of remark.
70 std::optional<std::string> all, passed, missed, analysis, failed;
71};
72
73/// Categories describe the outcome of an transformation, not the mechanics of
74/// emitting/serializing remarks.
75enum class RemarkKind {
77
78 /// An optimization was applied.
80
81 /// A profitable optimization opportunity was found but not applied.
83
84 /// The compiler attempted the optimization but failed (e.g., legality
85 /// checks, or better opportunites).
87
88 /// Informational context (e.g., analysis numbers) without a pass/fail
89 /// outcome.
91};
92
93using namespace llvm;
94
95namespace detail {
96class InFlightRemark; // forward declaration
97class RemarkEngine;
98} // namespace detail
99
100/// Options to create a Remark
102 StringRef remarkName; // Identifiable name
103 StringRef categoryName; // Category name (subject to regex filtering)
104 StringRef subCategoryName; // Subcategory name
105 StringRef functionName; // Function name if available
106
107 /// Link to a related remark by explicit ID.
109
110 // Construct RemarkOpts from a remark name.
111 static RemarkOpts name(StringRef n) {
112 RemarkOpts o;
113 o.remarkName = n;
114 return o;
115 }
116
117 /// Return a copy with the category set.
118 RemarkOpts category(StringRef v) const {
119 auto copy = *this;
120 copy.categoryName = v;
121 return copy;
122 }
123 /// Return a copy with the subcategory set.
124 RemarkOpts subCategory(StringRef v) const {
125 auto copy = *this;
126 copy.subCategoryName = v;
127 return copy;
128 }
129 /// Return a copy with the function name set.
130 RemarkOpts function(StringRef v) const {
131 auto copy = *this;
132 copy.functionName = v;
133 return copy;
134 }
135
136 /// Link this remark to a previously emitted remark by explicit ID.
138 auto copy = *this;
139 copy.relatedId = id;
140 return copy;
141 }
142
143 /// Link to an in-flight remark's ID. Final removes the link if the target is
144 /// replaced in the same batch.
145 inline RemarkOpts relatedTo(const detail::InFlightRemark &r) const;
146};
147
148/// Exact-match criteria for searching emitted or pending remarks. Unspecified
149/// fields match any value; a specified empty string matches an empty field.
150/// Strings are owned by the query. Locations belong to their MLIRContext and
151/// must not outlive it. A location match does not imply operation identity.
153public:
154 /// Construct a query matching the given remark name.
155 [[nodiscard]] static RemarkQuery named(StringRef value) {
156 return RemarkQuery().name(value);
157 }
158
159 [[nodiscard]] RemarkQuery name(StringRef value) const & {
160 return RemarkQuery(*this).name(value);
161 }
162 [[nodiscard]] RemarkQuery name(StringRef value) && {
163 remarkName = value.str();
164 return std::move(*this);
165 }
166 /// Match the base category, without the subcategory.
167 [[nodiscard]] RemarkQuery category(StringRef value) const & {
168 return RemarkQuery(*this).category(value);
169 }
170 [[nodiscard]] RemarkQuery category(StringRef value) && {
171 categoryName = value.str();
172 return std::move(*this);
173 }
174 [[nodiscard]] RemarkQuery subCategory(StringRef value) const & {
175 return RemarkQuery(*this).subCategory(value);
176 }
177 [[nodiscard]] RemarkQuery subCategory(StringRef value) && {
178 subCategoryName = value.str();
179 return std::move(*this);
180 }
181 [[nodiscard]] RemarkQuery function(StringRef value) const & {
182 return RemarkQuery(*this).function(value);
183 }
184 [[nodiscard]] RemarkQuery function(StringRef value) && {
185 functionName = value.str();
186 return std::move(*this);
187 }
188 [[nodiscard]] RemarkQuery kind(RemarkKind value) const & {
189 return RemarkQuery(*this).kind(value);
190 }
191 [[nodiscard]] RemarkQuery kind(RemarkKind value) && {
192 remarkKind = value;
193 return std::move(*this);
194 }
195 /// Match the complete location, including any wrapping locations.
196 [[nodiscard]] RemarkQuery at(Location value) const & {
197 return RemarkQuery(*this).at(value);
198 }
199 [[nodiscard]] RemarkQuery at(Location value) && {
200 location = value;
201 return std::move(*this);
202 }
203
204private:
206 std::optional<std::string> remarkName, categoryName, subCategoryName,
207 functionName;
208 std::optional<RemarkKind> remarkKind;
209 std::optional<Location> location;
210};
211} // namespace mlir::remark
212
213namespace mlir::remark::detail {
214//===----------------------------------------------------------------------===//
215// Remark Base Class
216//===----------------------------------------------------------------------===//
217class Remark {
218
219public:
221 RemarkOpts opts)
223 categoryName(opts.categoryName.str()),
225 remarkName(opts.remarkName.str()) {
226 if (!categoryName.empty() && !subCategoryName.empty()) {
227 (llvm::Twine(categoryName) + ":" + subCategoryName)
228 .toVector(fullCategoryName);
229 }
230 // Explicit ID linking from opts.
231 if (opts.relatedId)
233 }
234
235 // Remark argument that is a key-value pair that can be printed as machine
236 // parsable args. For Attribute arguments, the original attribute is also
237 // stored to allow custom streamers to handle them specially.
238 struct Arg {
239 std::string key;
240 std::string val;
241 /// Optional attribute storage for Attribute-based args. Allows streamers
242 /// to access the original attribute for custom handling.
243 std::optional<Attribute> attr;
244 /// Generated RelatedTo argument, distinct from a user-supplied argument.
245 bool isLink = false;
246
247 Arg(llvm::StringRef m) : key("Remark"), val(m) {}
248 Arg(llvm::StringRef k, llvm::StringRef v) : key(k), val(v) {}
249 Arg(llvm::StringRef k, std::string v) : key(k), val(std::move(v)) {}
250 Arg(llvm::StringRef k, const char *v) : Arg(k, llvm::StringRef(v)) {}
251 Arg(llvm::StringRef k, Value v);
252 Arg(llvm::StringRef k, Type t);
253 Arg(llvm::StringRef k, Attribute a);
254 Arg(llvm::StringRef k, bool b) : key(k), val(b ? "true" : "false") {}
255
256 /// Check if this arg has an associated attribute.
257 bool hasAttribute() const { return attr.has_value(); }
258
259 /// Get the attribute if present.
260 Attribute getAttribute() const { return attr.value_or(Attribute()); }
261
262 // One constructor for all arithmetic types except bool.
263 template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T> &&
264 !std::is_same_v<T, bool>>>
265 Arg(llvm::StringRef k, T v) : key(k) {
266 if constexpr (std::is_floating_point_v<T>) {
267 llvm::raw_string_ostream os(val);
268 os << v;
269 } else if constexpr (std::is_signed_v<T>) {
270 val = llvm::itostr(static_cast<long long>(v));
271 } else {
272 val = llvm::utostr(static_cast<unsigned long long>(v));
273 }
274 }
275 };
276
277 void insert(llvm::StringRef s);
278 void insert(Arg a);
279
280 void print(llvm::raw_ostream &os, bool printLocation = false) const;
281
282 Location getLocation() const { return loc; }
283 /// Diagnostic -> Remark
284 llvm::remarks::Remark generateRemark() const;
285
286 StringRef getFunction() const {
287 if (!functionName.empty())
288 return functionName;
289 return "<unknown function>";
290 }
291
292 /// Return the stored function name, which may be empty.
293 StringRef getRawFunction() const { return functionName; }
294
295 llvm::StringRef getCategoryName() const { return categoryName; }
296
297 llvm::StringRef getSubCategoryName() const { return subCategoryName; }
298
299 llvm::StringRef getCombinedCategoryName() const {
300 if (categoryName.empty() && subCategoryName.empty())
301 return {};
302 if (subCategoryName.empty())
303 return categoryName;
304 if (categoryName.empty())
305 return subCategoryName;
306 return fullCategoryName;
307 }
308
309 StringRef getRemarkName() const {
310 if (remarkName.empty())
311 return "<unknown remark name>";
312 return remarkName;
313 }
314
315 /// Return the stored remark name, which may be empty.
316 StringRef getRawRemarkName() const { return remarkName; }
317
318 std::string getMsg() const;
319
320 /// Return arguments, owned until mutation or destruction.
321 ArrayRef<Arg> getArgs() const { return args; }
322
323 llvm::remarks::Type getRemarkType() const;
324
325 //===--------------------------------------------------------------------===//
326 // Remark Linking Support
327 //===--------------------------------------------------------------------===//
328
329 /// Get this remark's unique ID (0 if not assigned).
330 RemarkId getId() const { return id; }
331
332 /// Set this remark's unique ID. Also adds it as an Arg for serialization.
333 void setId(RemarkId newId) {
334 id = newId;
335 if (id)
336 args.emplace_back("RemarkId", llvm::utostr(id.getValue()));
337 }
338
339 /// Get the list of related remark IDs.
341
342 /// Replace the list of related remark IDs.
344
345 /// Add a related ID and its generated argument.
346 void addRelatedRemark(RemarkId relatedId) {
347 if (!relatedId)
348 return;
349 relatedRemarks.push_back(relatedId);
350 Arg &arg =
351 args.emplace_back("RelatedTo", llvm::utostr(relatedId.getValue()));
352 arg.isLink = true;
353 }
354
355 /// Check if this remark has any related remarks.
356 bool hasRelatedRemarks() const { return !relatedRemarks.empty(); }
357
358 /// Get the remark kind.
360
361 StringRef getRemarkTypeString() const;
362
363protected:
364 /// Keeps the MLIR diagnostic kind, which is used to determine the
365 /// diagnostic kind in the LLVM remark streamer.
367 /// Name of the covering function like interface.
368 /// Stored as std::string to ensure the Remark owns its data.
369 std::string functionName;
370
372 /// Category name e.g., "Unroll" or "UnrollAndJam".
373 /// Stored as std::string to ensure the Remark owns its data.
374 std::string categoryName;
375
376 /// Sub category name e.g., "Loop Optimizer".
377 /// Stored as std::string to ensure the Remark owns its data.
378 std::string subCategoryName;
379
380 /// Combined name for category and sub-category
382
383 /// Remark identifier.
384 /// Stored as std::string to ensure the Remark owns its data.
385 std::string remarkName;
386
387 /// Args collected via the streaming interface.
389
390 /// Unique ID for this remark (assigned by RemarkEngine).
392
393 /// IDs of related remarks (e.g., parent analysis that enabled this opt).
395
396private:
397 /// Convert the MLIR diagnostic severity to LLVM diagnostic severity.
398 static llvm::DiagnosticSeverity
399 makeLLVMSeverity(DiagnosticSeverity severity) {
400 switch (severity) {
402 return llvm::DiagnosticSeverity::DS_Note;
404 return llvm::DiagnosticSeverity::DS_Warning;
406 return llvm::DiagnosticSeverity::DS_Error;
408 return llvm::DiagnosticSeverity::DS_Remark;
409 }
410 llvm_unreachable("Unknown diagnostic severity");
411 }
412 /// Convert the MLIR remark kind to LLVM diagnostic kind.
413 static llvm::DiagnosticKind makeLLVMKind(RemarkKind remarkKind) {
414 switch (remarkKind) {
416 return llvm::DiagnosticKind::DK_Generic;
418 return llvm::DiagnosticKind::DK_OptimizationRemark;
420 return llvm::DiagnosticKind::DK_OptimizationRemarkMissed;
422 return llvm::DiagnosticKind::DK_OptimizationFailure;
424 return llvm::DiagnosticKind::DK_OptimizationRemarkAnalysis;
425 }
426 llvm_unreachable("Unknown diagnostic kind");
427 }
428};
429
430inline Remark &operator<<(Remark &r, StringRef s) {
431 r.insert(s);
432 return r;
433}
434inline Remark &&operator<<(Remark &&r, StringRef s) {
435 r.insert(s);
436 return std::move(r);
437}
438inline Remark &operator<<(Remark &r, const Remark::Arg &kv) {
439 r.insert(kv);
440 return r;
441}
442
443//===----------------------------------------------------------------------===//
444// Shorthand aliases for different kinds of remarks.
445//===----------------------------------------------------------------------===//
446
447template <RemarkKind K, DiagnosticSeverity S>
448class OptRemarkBase final : public Remark {
449public:
451 : Remark(K, S, loc, opts) {}
452};
453
456
459
462
465
466class RemarkEngine;
467
468//===----------------------------------------------------------------------===//
469// InFlightRemark
470//===----------------------------------------------------------------------===//
471
472/// Lazy text building for zero cost string formatting.
474 llvm::StringRef key;
475 std::function<std::string()> thunk;
476};
477
478/// Resolves a query when inserted into an in-flight remark.
482
483/// InFlightRemark is a RAII class that holds a reference to a Remark
484/// instance and allows to build the remark using the << operator. The remark
485/// is emitted when the InFlightRemark instance is destroyed, which happens
486/// when the scope ends or when the InFlightRemark instance is moved.
487/// Similar to InFlightDiagnostic, but for remarks.
489public:
490 explicit InFlightRemark(std::unique_ptr<Remark> diag)
491 : remark(std::move(diag)) {}
492
493 InFlightRemark(RemarkEngine &eng, std::unique_ptr<Remark> diag)
494 : owner(&eng), remark(std::move(diag)) {}
495
496 InFlightRemark() = default; // empty ctor
497
499 if (remark)
500 *remark << Remark::Arg(l.key, l.thunk());
501 return *this;
502 }
503
505
506 // Generic path, excluding wrappers handled by dedicated overloads.
507 template <typename T,
508 typename = std::enable_if_t<
509 !std::is_same_v<std::decay_t<T>, LazyTextBuild> &&
510 !std::is_same_v<std::decay_t<T>, RelatedRemarkQuery>>>
512 if (remark)
513 *remark << std::forward<T>(arg);
514 return *this;
515 }
516
517 explicit operator bool() const { return remark != nullptr; }
518
519 /// Get this remark's unique ID (for linking from other remarks).
520 RemarkId getId() const { return remark ? remark->getId() : RemarkId(); }
521
523
528
529private:
530 RemarkEngine *owner{nullptr};
531 std::unique_ptr<Remark> remark;
532};
533
534//===----------------------------------------------------------------------===//
535// Pluggable Remark Utilities
536//===----------------------------------------------------------------------===//
537
538/// Base class for MLIR remark streamers that is used to stream
539/// optimization remarks to the underlying remark streamer. The derived classes
540/// should implement the `streamOptimizationRemark` method to provide the
541/// actual streaming implementation.
543public:
544 virtual ~MLIRRemarkStreamerBase() = default;
545 /// Stream an optimization remark to the underlying remark streamer. It is
546 /// called by the RemarkEngine to stream the optimization remarks.
547 ///
548 /// It must be overridden by the derived classes to provide
549 /// the actual streaming implementation.
550 virtual void streamOptimizationRemark(const Remark &remark) = 0;
551
552 virtual void finalize() {} // optional
553};
554
555using ReportFn = llvm::unique_function<void(const Remark &)>;
556
557/// Base class for MLIR remark emitting policies that is used to emit
558/// optimization remarks to the underlying remark streamer. The derived classes
559/// should implement the `reportRemark` method to provide the actual emitting
560/// implementation.
562protected:
564
565public:
567 virtual ~RemarkEmittingPolicyBase() = default;
568
569 void initialize(ReportFn fn) { reportImpl = std::move(fn); }
570
571 virtual void reportRemark(const Remark &remark) = 0;
572 virtual void finalize() = 0;
573
574 /// Visit remarks retained for future emission. findRemarks calls this; do not
575 /// call findRemarks while holding the lock taken here. The callback must not
576 /// reenter the policy or retain references. The default visits nothing.
578 llvm::function_ref<void(const Remark &)> callback) const {}
579
580 /// Visit pending remarks at the complete location. The default filters the
581 /// existing visitor; policies may override this to use a location index.
583 Location loc, llvm::function_ref<void(const Remark &)> callback) const {
585 if (remark.getLocation() == loc)
586 callback(remark);
587 });
588 }
589};
590
591//===----------------------------------------------------------------------===//
592// Remark Engine (MLIR Context will own this class)
593//===----------------------------------------------------------------------===//
594
596private:
597 /// Regex that filters missed optimization remarks: only matching one are
598 /// reported.
599 std::optional<llvm::Regex> missFilter;
600 /// The category for passed optimization remarks.
601 std::optional<llvm::Regex> passedFilter;
602 /// The category for analysis remarks.
603 std::optional<llvm::Regex> analysisFilter;
604 /// The category for failed optimization remarks.
605 std::optional<llvm::Regex> failedFilter;
606 /// History records metadata for remarks selected for emission by the policy.
607 /// Its mutex has a stable lifetime; retained storage is allocated on demand.
608 /// Declared before the streamer and the policy so that a policy destructor
609 /// that still reports finds them alive.
610 struct RemarkHistory;
611 std::unique_ptr<RemarkHistory> history;
612 std::atomic<bool> historyEnabled{false};
613 /// The MLIR remark streamer that will be used to emit the remarks.
614 std::unique_ptr<MLIRRemarkStreamerBase> remarkStreamer;
615 /// The MLIR remark policy that will be used to emit the remarks.
616 std::unique_ptr<RemarkEmittingPolicyBase> remarkEmittingPolicy;
617 /// When is enabled, engine also prints remarks as mlir::emitRemarks.
618 bool printAsEmitRemarks = false;
619 /// Atomic counter for generating unique remark IDs.
620 std::atomic<uint64_t> nextRemarkId{1};
621
622 /// Emit a remark using the given maker function, which should return
623 /// a Remark instance. The remark will be emitted using the main
624 /// remark streamer.
625 template <typename RemarkT>
626 InFlightRemark makeRemark(Location loc, RemarkOpts opts);
627
628 template <typename RemarkT>
629 InFlightRemark emitIfEnabled(Location loc, RemarkOpts opts,
630 bool (RemarkEngine::*isEnabled)(StringRef)
631 const);
632 /// Report a remark.
633 void reportImpl(const Remark &remark);
634
635public:
636 /// Default constructor is deleted, use the other constructor.
637 RemarkEngine() = delete;
638
639 /// Constructs Remark engine with optional category names. If a category
640 /// name is not provided, it is not enabled. The category names are used to
641 /// filter the remarks that are emitted.
642 RemarkEngine(bool printAsEmitRemarks, const RemarkCategories &cats);
643
644 /// Destructor that will close the output file and reset the
645 /// main remark streamer.
647
648 /// Setup the remark engine with the given output path and format.
649 LogicalResult
650 initialize(std::unique_ptr<MLIRRemarkStreamerBase> streamer,
651 std::unique_ptr<RemarkEmittingPolicyBase> remarkEmittingPolicy,
652 std::string *errMsg);
653
654 /// Get the remark emitting policy.
656 return remarkEmittingPolicy.get();
657 }
658
659 /// Generate a unique ID for a new remark.
661 return RemarkId(nextRemarkId.fetch_add(1, std::memory_order_relaxed));
662 }
663
664 //===--------------------------------------------------------------------===//
665 // Remark Filtering - query which remarks are enabled
666 //===--------------------------------------------------------------------===//
667
668 /// Return true if missed optimization remarks are enabled for the given
669 /// category.
670 bool isMissedOptRemarkEnabled(StringRef categoryName) const;
671
672 /// Return true if passed optimization remarks are enabled for the given
673 /// category.
674 bool isPassedOptRemarkEnabled(StringRef categoryName) const;
675
676 /// Return true if analysis remarks are enabled for the given category.
677 bool isAnalysisOptRemarkEnabled(StringRef categoryName) const;
678
679 /// Return true if failed optimization remarks are enabled for the given
680 /// category.
681 bool isFailedOptRemarkEnabled(StringRef categoryName) const;
682
683 /// Return true if remarks of the given kind are enabled for the given
684 /// category. Always returns false for `RemarkKind::RemarkUnknown`.
685 bool isRemarkEnabled(RemarkKind kind, StringRef categoryName) const;
686
687 /// Return true if any kind of remark is enabled for the given category.
688 bool isAnyRemarkEnabled(StringRef categoryName) const {
689 return isMissedOptRemarkEnabled(categoryName) ||
690 isPassedOptRemarkEnabled(categoryName) ||
691 isFailedOptRemarkEnabled(categoryName) ||
692 isAnalysisOptRemarkEnabled(categoryName);
693 }
694
695 /// Return true if any kind of remark is enabled for any category, i.e. if at
696 /// least one category filter is active. This is a cheap check that external
697 /// remark producers can use before doing any work to build a remark.
698 bool isAnyRemarkEnabled() const {
699 return missFilter.has_value() || passedFilter.has_value() ||
700 analysisFilter.has_value() || failedFilter.has_value();
701 }
702
703 //===--------------------------------------------------------------------===//
704 // Remark Linking - query emitted and pending remarks
705 //===--------------------------------------------------------------------===//
706
707 /// Enable or disable history. Enabling records subsequent emissions and makes
708 /// pending policy remarks searchable; disabling discards the recorded
709 /// metadata and suppresses queries.
710 void enableHistory(bool enable = true);
711
712 /// Discard recorded metadata without changing whether history is enabled.
713 void clearHistory();
714
715 /// Find matching emitted remarks and pending candidates in ID order, each
716 /// once. Returns empty without history. Queries with a location use indexes
717 /// for emitted and Final's pending remarks; other queries scan all remarks.
718 /// Candidates may be replaced before emission. Queries may
719 /// overlap reports, but not Final::finalize(). Cross-function matches depend
720 /// on thread timing; scope queries with function().
722
723 /// Search using nonempty option fields as exact-match criteria. The related
724 /// ID in opts is ignored. Use RemarkQuery to match empty fields or a
725 /// location.
727 findRemarks(const RemarkOpts &opts,
728 std::optional<RemarkKind> kind = std::nullopt) const;
729
730 /// Report a remark.
731 void report(const Remark &&remark);
732
733 /// Report a successful remark, this will create an InFlightRemark
734 /// that can be used to build the remark using the << operator.
736
737 /// Report a missed optimization remark
738 /// that can be used to build the remark using the << operator.
740
741 /// Report a failed optimization remark, this will create an InFlightRemark
742 /// that can be used to build the remark using the << operator.
744
745 /// Report an analysis remark, this will create an InFlightRemark
746 /// that can be used to build the remark using the << operator.
748};
749
750template <typename Fn, typename... Args>
751inline InFlightRemark withEngine(Fn fn, Location loc, Args &&...args) {
752 MLIRContext *ctx = loc->getContext();
753
754 RemarkEngine *enginePtr = ctx->getRemarkEngine();
755
756 if (LLVM_UNLIKELY(enginePtr))
757 return (enginePtr->*fn)(loc, std::forward<Args>(args)...);
758
759 return {};
760}
761
762} // namespace mlir::remark::detail
763
764// Deferred definition: needs InFlightRemark to be complete.
769
770namespace mlir::remark {
771/// Link to all remarks matching the query, each once, when inserted into an
772/// in-flight remark. Requires history; no match adds no links. Final drops
773/// links to targets replaced in the same finalization batch.
775 return {std::move(query)};
776}
777
778//===----------------------------------------------------------------------===//
779// Remark Emitting Policies
780//===----------------------------------------------------------------------===//
781
782/// Policy that emits all remarks.
784public:
786
787 void reportRemark(const detail::Remark &remark) override {
788 assert(reportImpl && "reportImpl is not set");
790 }
791 void finalize() override {}
792};
793
794/// Policy that emits only the last remark reported for each identity, see
795/// DenseMapInfo<Remark>. Remarks are stored until finalize().
797public:
799
800 void reportRemark(const detail::Remark &remark) override;
801
802 /// Visit pending candidates. Must not overlap finalize().
804 llvm::function_ref<void(const detail::Remark &)> callback) const override;
806 Location loc,
807 llvm::function_ref<void(const detail::Remark &)> callback) const override;
808
809 /// Emit each survivor once, grouping related remarks after their parents.
810 /// Visit roots with IDs in ID order, then ID-less roots in unspecified order.
811 /// Finally, start traversals from any unvisited remarks in ID order.
812 /// Links to IDs replaced in this batch are removed; IDs outside this batch
813 /// are preserved without validation. Call after reports and queries stop.
814 /// Callbacks must not reenter the policy. Later calls emit only new remarks.
815 void finalize() override;
816
817private:
818 struct RemarkPtrInfo {
819 static unsigned
820 getHashValue(const std::unique_ptr<detail::Remark> &remark) {
821 return getHashValue(*remark);
822 }
823 static unsigned getHashValue(const detail::Remark &remark);
824 static bool isEqual(const std::unique_ptr<detail::Remark> &lhs,
825 const std::unique_ptr<detail::Remark> &rhs) {
826 return isEqual(*lhs, rhs);
827 }
828 static bool isEqual(const detail::Remark &lhs,
829 const std::unique_ptr<detail::Remark> &rhs);
830 };
831
832 mutable std::mutex mutex;
833 // Stable addresses keep the location index valid when the set grows.
834 llvm::DenseSet<std::unique_ptr<detail::Remark>, RemarkPtrInfo> pendingRemarks;
835 using LocationIndex =
837 /// Built on the first location query and released when the batch drains.
838 mutable std::unique_ptr<LocationIndex> pendingByLocation;
839 /// IDs replaced in the current batch.
840 llvm::DenseSet<uint64_t> discardedIds;
841};
842
843/// Create a Reason with llvm::formatv formatting.
844template <class... Ts>
845inline detail::LazyTextBuild reason(const char *fmt, Ts &&...ts) {
846 return {"Reason", [=] { return llvm::formatv(fmt, ts...).str(); }};
847}
848
849/// Create a Suggestion with llvm::formatv formatting.
850template <class... Ts>
851inline detail::LazyTextBuild suggest(const char *fmt, Ts &&...ts) {
852 return {"Suggestion", [=] { return llvm::formatv(fmt, ts...).str(); }};
853}
854
855/// Create a Remark with llvm::formatv formatting.
856template <class... Ts>
857inline detail::LazyTextBuild add(const char *fmt, Ts &&...ts) {
858 return {"Remark", [=] { return llvm::formatv(fmt, ts...).str(); }};
859}
860
861template <class V>
862inline detail::LazyTextBuild metric(StringRef key, V &&v) {
863 using DV = std::decay_t<V>;
864 return {key, [key, vv = DV(std::forward<V>(v))]() mutable {
865 // Reuse Arg's formatting logic and return just the value string.
866 return detail::Remark::Arg(key, std::move(vv)).val;
867 }};
868}
869
870//===----------------------------------------------------------------------===//
871// Emitters
872//===----------------------------------------------------------------------===//
873
874/// Report an optimization remark that was passed.
876 return withEngine(&detail::RemarkEngine::emitOptimizationRemark, loc, opts);
877}
878
879/// Report an optimization remark that was missed.
882 opts);
883}
884
885/// Report an optimization remark that failed.
888 opts);
889}
890
891/// Report an optimization analysis remark.
894 opts);
895}
896
897//===----------------------------------------------------------------------===//
898// Setup
899//===----------------------------------------------------------------------===//
900
901/// Setup remarks for the context. This function will enable the remark engine
902/// and set the streamer to be used for optimization remarks. The remark
903/// categories are used to filter the remarks that will be emitted by the
904/// remark engine. If a category is not specified, it will not be emitted. If
905/// `printAsEmitRemarks` is true, the remarks will be printed as
906/// mlir::emitRemarks. 'streamer' must inherit from MLIRRemarkStreamerBase and
907/// will be used to stream the remarks.
909 MLIRContext &ctx,
910 std::unique_ptr<remark::detail::MLIRRemarkStreamerBase> streamer,
911 std::unique_ptr<remark::detail::RemarkEmittingPolicyBase>
912 remarkEmittingPolicy,
913 const remark::RemarkCategories &cats, bool printAsEmitRemarks = false);
914
915} // namespace mlir::remark
916
917/// Two remarks are the same for RemarkEmittingPolicyFinal when they have the
918/// same location, remark name, combined category name and kind.
919namespace llvm {
920template <>
921struct DenseMapInfo<mlir::remark::detail::Remark> {
922 static unsigned getHashValue(const mlir::remark::detail::Remark &remark) {
923 return llvm::hash_combine(
925 llvm::hash_value(remark.getRemarkName()),
926 llvm::hash_value(remark.getCombinedCategoryName()),
927 static_cast<unsigned>(remark.getRemarkKind()));
928 }
929
930 static bool isEqual(const mlir::remark::detail::Remark &lhs,
931 const mlir::remark::detail::Remark &rhs) {
932 return lhs.getLocation() == rhs.getLocation() &&
933 lhs.getRemarkName() == rhs.getRemarkName() &&
934 lhs.getCombinedCategoryName() == rhs.getCombinedCategoryName() &&
935 lhs.getRemarkKind() == rhs.getRemarkKind();
936 }
937};
938} // namespace llvm
939#endif // MLIR_IR_REMARKS_H
if(failed(verifyVectorMemoryOp(getOperation(), memrefType, getVectorType()))) return failure()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
#define add(a, b)
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
const void * getAsOpaquePointer() const
Methods for supporting PointerLikeTypeTraits.
Definition Location.h:105
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
remark::detail::RemarkEngine * getRemarkEngine()
Returns the remark engine for this context, or nullptr if none has been set.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void reportRemark(const detail::Remark &remark) override
Definition Remarks.h:787
void finalize() override
Emit each survivor once, grouping related remarks after their parents.
Definition Remarks.cpp:608
void forEachPendingRemarkAt(Location loc, llvm::function_ref< void(const detail::Remark &)> callback) const override
Visit pending remarks at the complete location.
Definition Remarks.cpp:593
void forEachPendingRemark(llvm::function_ref< void(const detail::Remark &)> callback) const override
Visit pending candidates. Must not overlap finalize().
Definition Remarks.cpp:586
void reportRemark(const detail::Remark &remark) override
Definition Remarks.cpp:568
A unique identifier for a remark, used to link related remarks together.
Definition Remarks.h:41
bool operator!=(const RemarkId &other) const
Definition Remarks.h:53
void print(llvm::raw_ostream &os) const
Print the ID.
Definition Remarks.h:56
bool operator==(const RemarkId &other) const
Definition Remarks.h:52
uint64_t getValue() const
Get the raw ID value.
Definition Remarks.h:50
RemarkId(uint64_t id)
Definition Remarks.h:44
Exact-match criteria for searching emitted or pending remarks.
Definition Remarks.h:152
RemarkQuery at(Location value) &&
Definition Remarks.h:199
RemarkQuery kind(RemarkKind value) const &
Definition Remarks.h:188
RemarkQuery kind(RemarkKind value) &&
Definition Remarks.h:191
RemarkQuery subCategory(StringRef value) const &
Definition Remarks.h:174
RemarkQuery name(StringRef value) const &
Definition Remarks.h:159
RemarkQuery subCategory(StringRef value) &&
Definition Remarks.h:177
RemarkQuery at(Location value) const &
Match the complete location, including any wrapping locations.
Definition Remarks.h:196
RemarkQuery function(StringRef value) &&
Definition Remarks.h:184
RemarkQuery function(StringRef value) const &
Definition Remarks.h:181
RemarkQuery category(StringRef value) const &
Match the base category, without the subcategory.
Definition Remarks.h:167
RemarkQuery category(StringRef value) &&
Definition Remarks.h:170
static RemarkQuery named(StringRef value)
Construct a query matching the given remark name.
Definition Remarks.h:155
RemarkQuery name(StringRef value) &&
Definition Remarks.h:162
InFlightRemark is a RAII class that holds a reference to a Remark instance and allows to build the re...
Definition Remarks.h:488
InFlightRemark(RemarkEngine &eng, std::unique_ptr< Remark > diag)
Definition Remarks.h:493
InFlightRemark(std::unique_ptr< Remark > diag)
Definition Remarks.h:490
InFlightRemark(const InFlightRemark &)=delete
InFlightRemark & operator<<(const LazyTextBuild &l)
Definition Remarks.h:498
RemarkId getId() const
Get this remark's unique ID (for linking from other remarks).
Definition Remarks.h:520
InFlightRemark(InFlightRemark &&)=default
InFlightRemark & operator=(InFlightRemark &&)=default
InFlightRemark & operator<<(T &&arg)
Definition Remarks.h:511
InFlightRemark & operator=(const InFlightRemark &)=delete
Base class for MLIR remark streamers that is used to stream optimization remarks to the underlying re...
Definition Remarks.h:542
virtual void streamOptimizationRemark(const Remark &remark)=0
Stream an optimization remark to the underlying remark streamer.
OptRemarkBase(Location loc, RemarkOpts opts)
Definition Remarks.h:450
Base class for MLIR remark emitting policies that is used to emit optimization remarks to the underly...
Definition Remarks.h:561
virtual void forEachPendingRemarkAt(Location loc, llvm::function_ref< void(const Remark &)> callback) const
Visit pending remarks at the complete location.
Definition Remarks.h:582
virtual void reportRemark(const Remark &remark)=0
virtual void forEachPendingRemark(llvm::function_ref< void(const Remark &)> callback) const
Visit remarks retained for future emission.
Definition Remarks.h:577
InFlightRemark emitOptimizationRemarkFailure(Location loc, RemarkOpts opts)
Report a failed optimization remark, this will create an InFlightRemark that can be used to build the...
Definition Remarks.cpp:404
bool isAnyRemarkEnabled(StringRef categoryName) const
Return true if any kind of remark is enabled for the given category.
Definition Remarks.h:688
bool isPassedOptRemarkEnabled(StringRef categoryName) const
Return true if passed optimization remarks are enabled for the given category.
Definition Remarks.cpp:363
bool isAnyRemarkEnabled() const
Return true if any kind of remark is enabled for any category, i.e.
Definition Remarks.h:698
void report(const Remark &&remark)
Report a remark.
Definition Remarks.cpp:441
bool isMissedOptRemarkEnabled(StringRef categoryName) const
Return true if missed optimization remarks are enabled for the given category.
Definition Remarks.cpp:359
RemarkId generateRemarkId()
Generate a unique ID for a new remark.
Definition Remarks.h:660
InFlightRemark emitOptimizationRemark(Location loc, RemarkOpts opts)
Report a successful remark, this will create an InFlightRemark that can be used to build the remark u...
Definition Remarks.cpp:392
RemarkEmittingPolicyBase * getRemarkEmittingPolicy() const
Get the remark emitting policy.
Definition Remarks.h:655
void clearHistory()
Discard recorded metadata without changing whether history is enabled.
Definition Remarks.cpp:258
LogicalResult initialize(std::unique_ptr< MLIRRemarkStreamerBase > streamer, std::unique_ptr< RemarkEmittingPolicyBase > remarkEmittingPolicy, std::string *errMsg)
Setup the remark engine with the given output path and format.
Definition Remarks.cpp:454
RemarkEngine()=delete
Default constructor is deleted, use the other constructor.
void enableHistory(bool enable=true)
Enable or disable history.
Definition Remarks.cpp:247
bool isAnalysisOptRemarkEnabled(StringRef categoryName) const
Return true if analysis remarks are enabled for the given category.
Definition Remarks.cpp:367
bool isRemarkEnabled(RemarkKind kind, StringRef categoryName) const
Return true if remarks of the given kind are enabled for the given category.
Definition Remarks.cpp:375
InFlightRemark emitOptimizationRemarkMiss(Location loc, RemarkOpts opts)
Report a missed optimization remark that can be used to build the remark using the << operator.
Definition Remarks.cpp:398
~RemarkEngine()
Destructor that will close the output file and reset the main remark streamer.
Definition Remarks.cpp:446
bool isFailedOptRemarkEnabled(StringRef categoryName) const
Return true if failed optimization remarks are enabled for the given category.
Definition Remarks.cpp:371
SmallVector< RemarkId > findRemarks(const RemarkQuery &query) const
Find matching emitted remarks and pending candidates in ID order, each once.
Definition Remarks.cpp:267
InFlightRemark emitOptimizationRemarkAnalysis(Location loc, RemarkOpts opts)
Report an analysis remark, this will create an InFlightRemark that can be used to build the remark us...
Definition Remarks.cpp:410
void setRelatedRemarkIds(ArrayRef< RemarkId > ids)
Replace the list of related remark IDs.
Definition Remarks.cpp:49
StringRef getRawRemarkName() const
Return the stored remark name, which may be empty.
Definition Remarks.h:316
RemarkId id
Unique ID for this remark (assigned by RemarkEngine).
Definition Remarks.h:391
std::string functionName
Name of the covering function like interface.
Definition Remarks.h:369
bool hasRelatedRemarks() const
Check if this remark has any related remarks.
Definition Remarks.h:356
void print(llvm::raw_ostream &os, bool printLocation=false) const
Print the remark to the given output stream.
Definition Remarks.cpp:91
void setId(RemarkId newId)
Set this remark's unique ID. Also adds it as an Arg for serialization.
Definition Remarks.h:333
RemarkId getId() const
Get this remark's unique ID (0 if not assigned).
Definition Remarks.h:330
ArrayRef< Arg > getArgs() const
Return arguments, owned until mutation or destruction.
Definition Remarks.h:321
SmallVector< Arg, 4 > args
Args collected via the streaming interface.
Definition Remarks.h:388
llvm::StringRef getCategoryName() const
Definition Remarks.h:295
StringRef getFunction() const
Definition Remarks.h:286
Remark(RemarkKind remarkKind, DiagnosticSeverity severity, Location loc, RemarkOpts opts)
Definition Remarks.h:220
llvm::remarks::Type getRemarkType() const
Definition Remarks.cpp:138
StringRef getRemarkTypeString() const
Definition Remarks.cpp:122
std::string remarkName
Remark identifier.
Definition Remarks.h:385
Location getLocation() const
Definition Remarks.h:282
std::string subCategoryName
Sub category name e.g., "Loop Optimizer".
Definition Remarks.h:378
RemarkKind getRemarkKind() const
Get the remark kind.
Definition Remarks.h:359
llvm::StringRef getCombinedCategoryName() const
Definition Remarks.h:299
llvm::StringRef getSubCategoryName() const
Definition Remarks.h:297
void addRelatedRemark(RemarkId relatedId)
Add a related ID and its generated argument.
Definition Remarks.h:346
RemarkKind remarkKind
Keeps the MLIR diagnostic kind, which is used to determine the diagnostic kind in the LLVM remark str...
Definition Remarks.h:366
StringRef getRemarkName() const
Definition Remarks.h:309
SmallString< 64 > fullCategoryName
Combined name for category and sub-category.
Definition Remarks.h:381
SmallVector< RemarkId > relatedRemarks
IDs of related remarks (e.g., parent analysis that enabled this opt).
Definition Remarks.h:394
ArrayRef< RemarkId > getRelatedRemarkIds() const
Get the list of related remark IDs.
Definition Remarks.h:340
void insert(llvm::StringRef s)
Definition Remarks.cpp:46
StringRef getRawFunction() const
Return the stored function name, which may be empty.
Definition Remarks.h:293
llvm::remarks::Remark generateRemark() const
Diagnostic -> Remark.
Definition Remarks.cpp:154
std::string categoryName
Category name e.g., "Unroll" or "UnrollAndJam".
Definition Remarks.h:374
std::string getMsg() const
Definition Remarks.cpp:114
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
AttrTypeReplacer.
OptRemarkBase< RemarkKind::RemarkMissed, DiagnosticSeverity::Remark > OptRemarkMissed
Definition Remarks.h:460
llvm::unique_function< void(const Remark &)> ReportFn
Definition Remarks.h:555
OptRemarkBase< RemarkKind::RemarkPassed, DiagnosticSeverity::Remark > OptRemarkPass
Definition Remarks.h:457
OptRemarkBase< RemarkKind::RemarkFailure, DiagnosticSeverity::Remark > OptRemarkFailure
Definition Remarks.h:463
OptRemarkBase< RemarkKind::RemarkAnalysis, DiagnosticSeverity::Remark > OptRemarkAnalysis
Definition Remarks.h:454
InFlightRemark withEngine(Fn fn, Location loc, Args &&...args)
Definition Remarks.h:751
Remark & operator<<(Remark &r, StringRef s)
Definition Remarks.h:430
detail::LazyTextBuild suggest(const char *fmt, Ts &&...ts)
Create a Suggestion with llvm::formatv formatting.
Definition Remarks.h:851
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
detail::InFlightRemark missed(Location loc, RemarkOpts opts)
Report an optimization remark that was missed.
Definition Remarks.h:880
detail::InFlightRemark analysis(Location loc, RemarkOpts opts)
Report an optimization analysis remark.
Definition Remarks.h:892
LogicalResult enableOptimizationRemarks(MLIRContext &ctx, std::unique_ptr< remark::detail::MLIRRemarkStreamerBase > streamer, std::unique_ptr< remark::detail::RemarkEmittingPolicyBase > remarkEmittingPolicy, const remark::RemarkCategories &cats, bool printAsEmitRemarks=false)
Setup remarks for the context.
detail::InFlightRemark passed(Location loc, RemarkOpts opts)
Report an optimization remark that was passed.
Definition Remarks.h:875
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, RemarkId id)
Definition Remarks.h:62
detail::LazyTextBuild metric(StringRef key, V &&v)
Definition Remarks.h:862
detail::LazyTextBuild reason(const char *fmt, Ts &&...ts)
Create a Reason with llvm::formatv formatting.
Definition Remarks.h:845
detail::RelatedRemarkQuery relatedTo(RemarkQuery query)
Link to all remarks matching the query, each once, when inserted into an in-flight remark.
Definition Remarks.h:774
RemarkKind
Categories describe the outcome of an transformation, not the mechanics of emitting/serializing remar...
Definition Remarks.h:75
@ RemarkPassed
An optimization was applied.
Definition Remarks.h:79
@ RemarkAnalysis
Informational context (e.g., analysis numbers) without a pass/fail outcome.
Definition Remarks.h:90
@ RemarkMissed
A profitable optimization opportunity was found but not applied.
Definition Remarks.h:82
@ RemarkFailure
The compiler attempted the optimization but failed (e.g., legality checks, or better opportunites).
Definition Remarks.h:86
Include the generated interface declarations.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Definition Diagnostics.h:41
static bool isEqual(const mlir::remark::detail::Remark &lhs, const mlir::remark::detail::Remark &rhs)
Definition Remarks.h:930
static unsigned getHashValue(const mlir::remark::detail::Remark &remark)
Definition Remarks.h:922
Define an the set of categories to accept.
Definition Remarks.h:69
std::optional< std::string > missed
Definition Remarks.h:70
std::optional< std::string > all
Definition Remarks.h:70
std::optional< std::string > passed
Definition Remarks.h:70
std::optional< std::string > analysis
Definition Remarks.h:70
std::optional< std::string > failed
Definition Remarks.h:70
Options to create a Remark.
Definition Remarks.h:101
RemarkOpts function(StringRef v) const
Return a copy with the function name set.
Definition Remarks.h:130
StringRef subCategoryName
Definition Remarks.h:104
RemarkOpts subCategory(StringRef v) const
Return a copy with the subcategory set.
Definition Remarks.h:124
RemarkOpts relatedTo(RemarkId id) const
Link this remark to a previously emitted remark by explicit ID.
Definition Remarks.h:137
RemarkOpts category(StringRef v) const
Return a copy with the category set.
Definition Remarks.h:118
RemarkId relatedId
Link to a related remark by explicit ID.
Definition Remarks.h:108
static RemarkOpts name(StringRef n)
Definition Remarks.h:111
Lazy text building for zero cost string formatting.
Definition Remarks.h:473
std::function< std::string()> thunk
Definition Remarks.h:475
Resolves a query when inserted into an in-flight remark.
Definition Remarks.h:479
Arg(llvm::StringRef k, T v)
Definition Remarks.h:265
Arg(llvm::StringRef k, llvm::StringRef v)
Definition Remarks.h:248
Arg(llvm::StringRef k, std::string v)
Definition Remarks.h:249
Arg(llvm::StringRef k, const char *v)
Definition Remarks.h:250
bool isLink
Generated RelatedTo argument, distinct from a user-supplied argument.
Definition Remarks.h:245
Attribute getAttribute() const
Get the attribute if present.
Definition Remarks.h:260
bool hasAttribute() const
Check if this arg has an associated attribute.
Definition Remarks.h:257
Arg(llvm::StringRef k, bool b)
Definition Remarks.h:254
std::optional< Attribute > attr
Optional attribute storage for Attribute-based args.
Definition Remarks.h:243