1//===- Remarks.cpp - MLIR Remarks -----------------------------------------===//
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#include "mlir/IR/Remarks.h"
10
11#include "mlir/IR/BuiltinAttributes.h"
12#include "mlir/IR/Diagnostics.h"
13#include "mlir/IR/Value.h"
14
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/StringSaver.h"
21
22#include <mutex>
23#include <vector>
24
25using namespace mlir::remark::detail;
26using namespace mlir::remark;
27//------------------------------------------------------------------------------
28// Remark
29//------------------------------------------------------------------------------
30
31Remark::Arg::Arg(llvm::StringRef k, Value v) : key(k) {
32 llvm::raw_string_ostream os(val);
33 os << v;
34}
35
36Remark::Arg::Arg(llvm::StringRef k, Type t) : key(k) {
37 llvm::raw_string_ostream os(val);
38 os << t;
39}
40
41Remark::Arg::Arg(llvm::StringRef k, Attribute a) : key(k), attr(a) {
42 llvm::raw_string_ostream os(val);
43 os << a;
44}
45
46void Remark::insert(llvm::StringRef s) { args.emplace_back(Args&: s); }
47void Remark::insert(Arg a) { args.push_back(Elt: std::move(a)); }
48
49void Remark::setRelatedRemarkIds(ArrayRef<RemarkId> ids) {
50 SmallVector<RemarkId> copy(ids);
51 llvm::erase_if(C&: args, P: [](const Arg &arg) { return arg.isLink; });
52 relatedRemarks.clear();
53 for (RemarkId id : copy)
54 addRelatedRemark(relatedId: id);
55}
56
57// Simple helper to print key=val list (sorted).
58static void printArgs(llvm::raw_ostream &os, llvm::ArrayRef<Remark::Arg> args) {
59 if (args.empty())
60 return;
61
62 // Preserve the relative order of repeated keys, including related IDs.
63 llvm::SmallVector<Remark::Arg, 8> sorted(args.begin(), args.end());
64 llvm::stable_sort(Range&: sorted, C: [](const Remark::Arg &a, const Remark::Arg &b) {
65 return a.key < b.key;
66 });
67
68 for (size_t i = 0; i < sorted.size(); ++i) {
69 const auto &a = sorted[i];
70 os << a.key << "=";
71
72 llvm::StringRef val(a.val);
73 bool needsQuote = val.contains(C: ' ') || val.contains(C: ',') ||
74 val.contains(C: '{') || val.contains(C: '}');
75 if (needsQuote)
76 os << '"' << val << '"';
77 else
78 os << val;
79
80 if (i + 1 < sorted.size())
81 os << ", ";
82 }
83}
84
85/// Print the remark to the given output stream.
86/// Example output:
87// clang-format off
88/// [Missed] Category: Loop | Pass:Unroller | Function=main | Reason="tripCount=4 < threshold=256"
89/// [Failure] LoopOptimizer | Reason="failed due to unsupported pattern"
90// clang-format on
91void Remark::print(llvm::raw_ostream &os, bool printLocation) const {
92 // Header: [Type] pass:remarkName
93 StringRef type = getRemarkTypeString();
94 StringRef categoryName = getCombinedCategoryName();
95 StringRef name = remarkName;
96
97 os << '[' << type << "] ";
98 os << name << " | ";
99 if (!categoryName.empty())
100 os << "Category:" << categoryName << " | ";
101 if (!functionName.empty())
102 os << "Function=" << getFunction() << " | ";
103
104 if (printLocation) {
105 if (auto flc = getLocation()->findInstanceOf<FileLineColLoc>()) {
106 os << " @" << flc.getFilename() << ":" << flc.getLine() << ":"
107 << flc.getColumn();
108 }
109 }
110
111 printArgs(os, args: getArgs());
112}
113
114std::string Remark::getMsg() const {
115 std::string s;
116 llvm::raw_string_ostream os(s);
117 print(os);
118 os.flush();
119 return s;
120}
121
122llvm::StringRef Remark::getRemarkTypeString() const {
123 switch (remarkKind) {
124 case RemarkKind::RemarkUnknown:
125 return "Unknown";
126 case RemarkKind::RemarkPassed:
127 return "Passed";
128 case RemarkKind::RemarkMissed:
129 return "Missed";
130 case RemarkKind::RemarkFailure:
131 return "Failure";
132 case RemarkKind::RemarkAnalysis:
133 return "Analysis";
134 }
135 llvm_unreachable("Unknown remark kind");
136}
137
138llvm::remarks::Type Remark::getRemarkType() const {
139 switch (remarkKind) {
140 case RemarkKind::RemarkUnknown:
141 return llvm::remarks::Type::Unknown;
142 case RemarkKind::RemarkPassed:
143 return llvm::remarks::Type::Passed;
144 case RemarkKind::RemarkMissed:
145 return llvm::remarks::Type::Missed;
146 case RemarkKind::RemarkFailure:
147 return llvm::remarks::Type::Failure;
148 case RemarkKind::RemarkAnalysis:
149 return llvm::remarks::Type::Analysis;
150 }
151 llvm_unreachable("Unknown remark kind");
152}
153
154llvm::remarks::Remark Remark::generateRemark() const {
155 auto locLambda = [&]() -> llvm::remarks::RemarkLocation {
156 // Remarks are often emitted at name, fused or call-site locations wrapping
157 // a file location; use the first file location found inside.
158 if (auto flc = getLocation()->findInstanceOf<FileLineColLoc>())
159 return {.SourceFilePath: flc.getFilename(), .SourceLine: flc.getLine(), .SourceColumn: flc.getColumn()};
160 return {.SourceFilePath: "<unknown file>", .SourceLine: 0, .SourceColumn: 0};
161 };
162
163 llvm::remarks::Remark r; // The result.
164 r.RemarkType = getRemarkType();
165 r.RemarkName = getRemarkName();
166 // MLIR does not use passes; instead, it has categories and sub-categories.
167 r.PassName = getCombinedCategoryName();
168 r.FunctionName = getFunction();
169 r.Loc = locLambda();
170 // Keep serialized strings owned by the source remark.
171 for (const Remark::Arg &arg : getArgs()) {
172 r.Args.emplace_back();
173 r.Args.back().Key = arg.key;
174 r.Args.back().Val = arg.val;
175 }
176 return r;
177}
178
179//===----------------------------------------------------------------------===//
180// InFlightRemark
181//===----------------------------------------------------------------------===//
182
183InFlightRemark &InFlightRemark::operator<<(const RelatedRemarkQuery &related) {
184 if (!remark || !owner)
185 return *this;
186 // Link each target once, even if an explicit link or an earlier query
187 // already added it.
188 llvm::SmallDenseSet<uint64_t> linked;
189 for (RemarkId id : remark->getRelatedRemarkIds())
190 linked.insert(V: id.getValue());
191 for (RemarkId id : owner->findRemarks(query: related.query))
192 if (linked.insert(V: id.getValue()).second)
193 remark->addRelatedRemark(relatedId: id);
194 return *this;
195}
196
197InFlightRemark::~InFlightRemark() {
198 if (remark && owner)
199 owner->report(remark: std::move(*remark));
200 owner = nullptr;
201}
202
203//===----------------------------------------------------------------------===//
204// Remark Engine
205//===----------------------------------------------------------------------===//
206
207struct RemarkEngine::RemarkHistory {
208 struct Entry {
209 RemarkId id;
210 RemarkKind kind;
211 Location location;
212 StringRef name, category, subCategory, function;
213
214 static Entry from(const Remark &remark) {
215 return {.id: remark.getId(), .kind: remark.getRemarkKind(),
216 .location: remark.getLocation(), .name: remark.getRawRemarkName(),
217 .category: remark.getCategoryName(), .subCategory: remark.getSubCategoryName(),
218 .function: remark.getRawFunction()};
219 }
220
221 static Entry from(const Remark &remark, llvm::UniqueStringSaver &strings) {
222 Entry entry = from(remark);
223 entry.name = strings.save(S: entry.name);
224 entry.category = strings.save(S: entry.category);
225 entry.subCategory = strings.save(S: entry.subCategory);
226 entry.function = strings.save(S: entry.function);
227 return entry;
228 }
229 };
230
231 struct Storage {
232 llvm::BumpPtrAllocator allocator;
233 llvm::UniqueStringSaver strings{allocator};
234 std::vector<Entry> entries;
235 llvm::DenseMap<Location, SmallVector<size_t, 1>> entriesByLocation;
236 size_t indexedEntries = 0;
237 // IDs already recorded.
238 llvm::DenseSet<uint64_t> recordedIds;
239 };
240
241 // Keep the mutex alive for the engine's lifetime so disabling history cannot
242 // destroy it while another thread is about to lock it. Storage is opt-in.
243 std::mutex mutex;
244 std::unique_ptr<Storage> storage;
245};
246
247void RemarkEngine::enableHistory(bool enable) {
248 std::scoped_lock<std::mutex> lock(history->mutex);
249 if (enable) {
250 if (!history->storage)
251 history->storage = std::make_unique<RemarkHistory::Storage>();
252 } else {
253 history->storage.reset();
254 }
255 historyEnabled.store(i: enable, m: std::memory_order_release);
256}
257
258void RemarkEngine::clearHistory() {
259 if (!historyEnabled.load(m: std::memory_order_acquire))
260 return;
261 std::scoped_lock<std::mutex> lock(history->mutex);
262 if (history->storage)
263 history->storage = std::make_unique<RemarkHistory::Storage>();
264}
265
266SmallVector<RemarkId>
267RemarkEngine::findRemarks(const RemarkQuery &query) const {
268 SmallVector<RemarkId> result;
269 if (!historyEnabled.load(m: std::memory_order_acquire))
270 return result;
271
272 auto matches = [](const auto &filter, const auto &value) {
273 return !filter || *filter == value;
274 };
275 auto matchesQuery = [&](const RemarkHistory::Entry &entry) {
276 return matches(query.location, entry.location) &&
277 matches(query.remarkKind, entry.kind) &&
278 matches(query.remarkName, entry.name) &&
279 matches(query.categoryName, entry.category) &&
280 matches(query.subCategoryName, entry.subCategory) &&
281 matches(query.functionName, entry.function);
282 };
283 // Call policies without holding the history lock.
284 if (remarkEmittingPolicy) {
285 auto addMatch = [&](const Remark &remark) {
286 if (remark.getId() && matchesQuery(RemarkHistory::Entry::from(remark)))
287 result.push_back(Elt: remark.getId());
288 };
289 if (query.location)
290 remarkEmittingPolicy->forEachPendingRemarkAt(loc: *query.location, callback: addMatch);
291 else
292 remarkEmittingPolicy->forEachPendingRemark(callback: addMatch);
293 }
294
295 {
296 std::scoped_lock<std::mutex> lock(history->mutex);
297 if (!history->storage)
298 return {};
299 auto &storage = *history->storage;
300 if (query.location) {
301 while (storage.indexedEntries < storage.entries.size()) {
302 size_t i = storage.indexedEntries;
303 storage.entriesByLocation[storage.entries[i].location].push_back(Elt: i);
304 ++storage.indexedEntries;
305 }
306 auto entries = storage.entriesByLocation.find(Val: *query.location);
307 if (entries != storage.entriesByLocation.end())
308 for (size_t index : entries->second) {
309 const auto &entry = storage.entries[index];
310 if (matchesQuery(entry))
311 result.push_back(Elt: entry.id);
312 }
313 } else {
314 for (const RemarkHistory::Entry &entry : storage.entries)
315 if (matchesQuery(entry))
316 result.push_back(Elt: entry.id);
317 }
318 }
319 llvm::sort(C&: result, Comp: [](RemarkId lhs, RemarkId rhs) {
320 return lhs.getValue() < rhs.getValue();
321 });
322 result.erase(CS: llvm::unique(R&: result), CE: result.end());
323 return result;
324}
325
326SmallVector<RemarkId>
327RemarkEngine::findRemarks(const RemarkOpts &opts,
328 std::optional<RemarkKind> kind) const {
329 RemarkQuery query;
330 if (!opts.remarkName.empty())
331 query.remarkName = opts.remarkName.str();
332 if (!opts.categoryName.empty())
333 query.categoryName = opts.categoryName.str();
334 if (!opts.subCategoryName.empty())
335 query.subCategoryName = opts.subCategoryName.str();
336 if (!opts.functionName.empty())
337 query.functionName = opts.functionName.str();
338 query.remarkKind = kind;
339 return findRemarks(query);
340}
341
342template <typename RemarkT>
343InFlightRemark RemarkEngine::makeRemark(Location loc, RemarkOpts opts) {
344 static_assert(std::is_base_of_v<Remark, RemarkT>,
345 "RemarkT must derive from Remark");
346 auto remark = std::make_unique<RemarkT>(loc, opts);
347 remark->setId(generateRemarkId());
348 return InFlightRemark(*this, std::move(remark));
349}
350
351template <typename RemarkT>
352InFlightRemark
353RemarkEngine::emitIfEnabled(Location loc, RemarkOpts opts,
354 bool (RemarkEngine::*isEnabled)(StringRef) const) {
355 return (this->*isEnabled)(opts.categoryName) ? makeRemark<RemarkT>(loc, opts)
356 : InFlightRemark{};
357}
358
359bool RemarkEngine::isMissedOptRemarkEnabled(StringRef categoryName) const {
360 return missFilter && missFilter->match(String: categoryName);
361}
362
363bool RemarkEngine::isPassedOptRemarkEnabled(StringRef categoryName) const {
364 return passedFilter && passedFilter->match(String: categoryName);
365}
366
367bool RemarkEngine::isAnalysisOptRemarkEnabled(StringRef categoryName) const {
368 return analysisFilter && analysisFilter->match(String: categoryName);
369}
370
371bool RemarkEngine::isFailedOptRemarkEnabled(StringRef categoryName) const {
372 return failedFilter && failedFilter->match(String: categoryName);
373}
374
375bool RemarkEngine::isRemarkEnabled(RemarkKind kind,
376 StringRef categoryName) const {
377 switch (kind) {
378 case RemarkKind::RemarkUnknown:
379 return false;
380 case RemarkKind::RemarkPassed:
381 return isPassedOptRemarkEnabled(categoryName);
382 case RemarkKind::RemarkMissed:
383 return isMissedOptRemarkEnabled(categoryName);
384 case RemarkKind::RemarkFailure:
385 return isFailedOptRemarkEnabled(categoryName);
386 case RemarkKind::RemarkAnalysis:
387 return isAnalysisOptRemarkEnabled(categoryName);
388 }
389 llvm_unreachable("Unknown remark kind");
390}
391
392InFlightRemark RemarkEngine::emitOptimizationRemark(Location loc,
393 RemarkOpts opts) {
394 return emitIfEnabled<OptRemarkPass>(loc, opts,
395 isEnabled: &RemarkEngine::isPassedOptRemarkEnabled);
396}
397
398InFlightRemark RemarkEngine::emitOptimizationRemarkMiss(Location loc,
399 RemarkOpts opts) {
400 return emitIfEnabled<OptRemarkMissed>(
401 loc, opts, isEnabled: &RemarkEngine::isMissedOptRemarkEnabled);
402}
403
404InFlightRemark RemarkEngine::emitOptimizationRemarkFailure(Location loc,
405 RemarkOpts opts) {
406 return emitIfEnabled<OptRemarkFailure>(
407 loc, opts, isEnabled: &RemarkEngine::isFailedOptRemarkEnabled);
408}
409
410InFlightRemark RemarkEngine::emitOptimizationRemarkAnalysis(Location loc,
411 RemarkOpts opts) {
412 return emitIfEnabled<OptRemarkAnalysis>(
413 loc, opts, isEnabled: &RemarkEngine::isAnalysisOptRemarkEnabled);
414}
415
416//===----------------------------------------------------------------------===//
417// RemarkEngine
418//===----------------------------------------------------------------------===//
419
420void RemarkEngine::reportImpl(const Remark &remark) {
421 if (historyEnabled.load(m: std::memory_order_acquire)) {
422 std::scoped_lock<std::mutex> lock(history->mutex);
423 if (history->storage && remark.getId()) {
424 auto &storage = *history->storage;
425 // A policy may deliver the same event repeatedly.
426 if (storage.recordedIds.insert(V: remark.getId().getValue()).second)
427 storage.entries.push_back(
428 x: RemarkHistory::Entry::from(remark, strings&: storage.strings));
429 }
430 }
431 // Stream the remark
432 if (remarkStreamer) {
433 remarkStreamer->streamOptimizationRemark(remark);
434 }
435
436 // Print using MLIR's diagnostic
437 if (printAsEmitRemarks)
438 emitRemark(loc: remark.getLocation(), message: remark.getMsg());
439}
440
441void RemarkEngine::report(const Remark &&remark) {
442 if (remarkEmittingPolicy)
443 remarkEmittingPolicy->reportRemark(remark);
444}
445
446RemarkEngine::~RemarkEngine() {
447 if (remarkEmittingPolicy)
448 remarkEmittingPolicy->finalize();
449
450 if (remarkStreamer)
451 remarkStreamer->finalize();
452}
453
454llvm::LogicalResult RemarkEngine::initialize(
455 std::unique_ptr<MLIRRemarkStreamerBase> streamer,
456 std::unique_ptr<RemarkEmittingPolicyBase> remarkEmittingPolicy,
457 std::string *errMsg) {
458 remarkStreamer = std::move(streamer);
459
460 auto reportFunc = llvm::bind_front<&RemarkEngine::reportImpl>(BindArgs: this);
461 remarkEmittingPolicy->initialize(fn: ReportFn(std::move(reportFunc)));
462
463 this->remarkEmittingPolicy = std::move(remarkEmittingPolicy);
464 return success();
465}
466
467/// Returns true if filter is already anchored like ^...$
468static bool isAnchored(llvm::StringRef s) {
469 s = s.trim();
470 return s.starts_with(Prefix: "^") && s.ends_with(Suffix: "$"); // note: startswith/endswith
471}
472
473/// Anchor the entire pattern so it matches the whole string.
474static std::string anchorWhole(llvm::StringRef filter) {
475 if (isAnchored(s: filter))
476 return filter.str();
477 return (llvm::Twine("^(") + filter + ")$").str();
478}
479
480/// Build a combined filter from cats.all and a category-specific pattern.
481/// If neither is present, return std::nullopt. Otherwise "(all|specific)"
482/// and anchor once. Also validate before returning.
483static std::optional<llvm::Regex>
484buildFilter(const mlir::remark::RemarkCategories &cats,
485 const std::optional<std::string> &specific) {
486 llvm::SmallVector<llvm::StringRef, 2> parts;
487 if (cats.all && !cats.all->empty())
488 parts.emplace_back(Args: *cats.all);
489 if (specific && !specific->empty())
490 parts.emplace_back(Args: *specific);
491
492 if (parts.empty())
493 return std::nullopt;
494
495 std::string joined = llvm::join(R&: parts, Separator: "|");
496 std::string anchored = anchorWhole(filter: joined);
497
498 llvm::Regex rx(anchored);
499 std::string err;
500 if (!rx.isValid(Error&: err))
501 return std::nullopt;
502
503 return std::make_optional<llvm::Regex>(t: std::move(rx));
504}
505
506RemarkEngine::RemarkEngine(bool printAsEmitRemarks,
507 const RemarkCategories &cats)
508 : history(std::make_unique<RemarkHistory>()),
509 printAsEmitRemarks(printAsEmitRemarks) {
510 if (cats.passed)
511 passedFilter = buildFilter(cats, specific: cats.passed);
512 if (cats.missed)
513 missFilter = buildFilter(cats, specific: cats.missed);
514 if (cats.analysis)
515 analysisFilter = buildFilter(cats, specific: cats.analysis);
516 if (cats.failed)
517 failedFilter = buildFilter(cats, specific: cats.failed);
518}
519
520llvm::LogicalResult mlir::remark::enableOptimizationRemarks(
521 MLIRContext &ctx, std::unique_ptr<detail::MLIRRemarkStreamerBase> streamer,
522 std::unique_ptr<detail::RemarkEmittingPolicyBase> remarkEmittingPolicy,
523 const RemarkCategories &cats, bool printAsEmitRemarks) {
524 auto engine =
525 std::make_unique<detail::RemarkEngine>(args&: printAsEmitRemarks, args: cats);
526
527 std::string errMsg;
528 if (failed(Result: engine->initialize(streamer: std::move(streamer),
529 remarkEmittingPolicy: std::move(remarkEmittingPolicy), errMsg: &errMsg))) {
530 llvm::report_fatal_error(
531 reason: llvm::Twine("Failed to initialize remark engine. Error: ") + errMsg);
532 }
533 ctx.setRemarkEngine(std::move(engine));
534
535 return success();
536}
537
538//===----------------------------------------------------------------------===//
539// Remark emitting policies
540//===----------------------------------------------------------------------===//
541
542namespace mlir::remark {
543RemarkEmittingPolicyAll::RemarkEmittingPolicyAll() = default;
544
545RemarkEmittingPolicyFinal::RemarkEmittingPolicyFinal() = default;
546
547unsigned RemarkEmittingPolicyFinal::RemarkPtrInfo::getHashValue(
548 const detail::Remark &remark) {
549 return llvm::DenseMapInfo<detail::Remark>::getHashValue(remark);
550}
551
552bool RemarkEmittingPolicyFinal::RemarkPtrInfo::isEqual(
553 const detail::Remark &lhs, const std::unique_ptr<detail::Remark> &rhs) {
554 return llvm::DenseMapInfo<detail::Remark>::isEqual(lhs, rhs: *rhs);
555}
556
557static void dropDiscardedLinks(detail::Remark &remark,
558 const llvm::DenseSet<uint64_t> &discardedIds) {
559 if (discardedIds.empty())
560 return;
561 auto ids = llvm::to_vector(Range: remark.getRelatedRemarkIds());
562 llvm::erase_if(
563 C&: ids, P: [&](RemarkId id) { return discardedIds.contains(V: id.getValue()); });
564 if (ids.size() != remark.getRelatedRemarkIds().size())
565 remark.setRelatedRemarkIds(ids);
566}
567
568void RemarkEmittingPolicyFinal::reportRemark(const detail::Remark &remark) {
569 detail::Remark copy = remark;
570 std::scoped_lock<std::mutex> lock(mutex);
571 auto previous = pendingRemarks.find_as(Val: copy);
572 if (previous != pendingRemarks.end()) {
573 auto &stored = **previous;
574 if (stored.getId() && stored.getId() != copy.getId())
575 discardedIds.insert(V: stored.getId().getValue());
576 // Replacement preserves the identity and address indexed by both maps.
577 stored = std::move(copy);
578 return;
579 }
580 auto stored = std::make_unique<detail::Remark>(args: std::move(copy));
581 if (pendingByLocation)
582 (*pendingByLocation)[stored->getLocation()].push_back(Elt: stored.get());
583 pendingRemarks.insert(V: std::move(stored));
584}
585
586void RemarkEmittingPolicyFinal::forEachPendingRemark(
587 llvm::function_ref<void(const detail::Remark &)> callback) const {
588 std::scoped_lock<std::mutex> lock(mutex);
589 for (const auto &remark : pendingRemarks)
590 callback(*remark);
591}
592
593void RemarkEmittingPolicyFinal::forEachPendingRemarkAt(
594 Location loc,
595 llvm::function_ref<void(const detail::Remark &)> callback) const {
596 std::scoped_lock<std::mutex> lock(mutex);
597 if (!pendingByLocation) {
598 pendingByLocation = std::make_unique<LocationIndex>();
599 for (const auto &remark : pendingRemarks)
600 (*pendingByLocation)[remark->getLocation()].push_back(Elt: remark.get());
601 }
602 auto remarks = pendingByLocation->find(Val: loc);
603 if (remarks != pendingByLocation->end())
604 for (const auto *remark : remarks->second)
605 callback(*remark);
606}
607
608void RemarkEmittingPolicyFinal::finalize() {
609 assert(reportImpl && "reportImpl is not set");
610
611 SmallVector<detail::Remark, 0> remarks;
612 llvm::DenseSet<uint64_t> discarded;
613 {
614 std::scoped_lock<std::mutex> lock(mutex);
615 remarks.reserve(N: pendingRemarks.size());
616 for (const auto &remark : pendingRemarks)
617 remarks.push_back(Elt: std::move(*remark));
618 pendingRemarks.clear();
619 pendingByLocation.reset();
620 discarded.swap(RHS&: discardedIds);
621 }
622
623 // A re-reported ID that survives is still a valid target.
624 for (const auto &remark : remarks)
625 if (remark.getId())
626 discarded.erase(V: remark.getId().getValue());
627 for (auto &remark : remarks)
628 dropDiscardedLinks(remark, discardedIds: discarded);
629
630 llvm::sort(C&: remarks, Comp: [](const auto &lhs, const auto &rhs) {
631 if (!lhs.getId())
632 return false;
633 if (!rhs.getId())
634 return true;
635 return lhs.getId().getValue() < rhs.getId().getValue();
636 });
637
638 // Build ID -> Remark* lookup for resolving related remark references.
639 llvm::DenseMap<uint64_t, const detail::Remark *> idMap;
640 llvm::DenseSet<uint64_t> childIds; // IDs referenced as children
641
642 for (const auto &remark : remarks) {
643 if (remark.getId())
644 idMap[remark.getId().getValue()] = &remark;
645 for (auto relId : remark.getRelatedRemarkIds())
646 childIds.insert(V: relId.getValue());
647 }
648
649 // Visit by address so ID-less remarks remain distinct.
650 llvm::DenseSet<const detail::Remark *> emitted;
651 SmallVector<const detail::Remark *> worklist;
652 auto emit = [&](const detail::Remark &root) {
653 worklist.push_back(Elt: &root);
654 while (!worklist.empty()) {
655 const auto *remark = worklist.pop_back_val();
656 if (!emitted.insert(V: remark).second)
657 continue;
658 reportImpl(*remark);
659 for (RemarkId id : llvm::reverse(C: remark->getRelatedRemarkIds()))
660 if (const auto *related = idMap.lookup(Val: id.getValue()))
661 worklist.push_back(Elt: related);
662 }
663 };
664
665 for (const auto &remark : remarks) {
666 if (remark.getId() && childIds.contains(V: remark.getId().getValue()))
667 continue;
668 emit(remark);
669 }
670 // Cycles have no root.
671 for (const auto &remark : remarks)
672 if (!emitted.contains(V: &remark))
673 emit(remark);
674}
675
676} // namespace mlir::remark
677