MLIR 24.0.0git
Diagnostics.h
Go to the documentation of this file.
1//===- Diagnostics.h - MLIR Diagnostics -------------------------*- 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 diagnostics.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_DIAGNOSTICS_H
14#define MLIR_IR_DIAGNOSTICS_H
15
16#include "mlir/IR/Location.h"
17#include <functional>
18#include <optional>
19
20namespace llvm {
21class MemoryBuffer;
22class SMLoc;
23class SourceMgr;
24} // namespace llvm
25
26namespace mlir {
28class MLIRContext;
29class Operation;
30class OperationName;
31class OpPrintingFlags;
32class OpWithFlags;
33class Type;
34class Value;
35
36namespace detail {
38} // namespace detail
39
40/// Defines the different supported severity of a diagnostic.
47
48//===----------------------------------------------------------------------===//
49// DiagnosticArgument
50//===----------------------------------------------------------------------===//
51
52/// A variant type that holds a single argument for a diagnostic.
54public:
55 /// Note: The constructors below are only exposed due to problems accessing
56 /// constructors from type traits, they should not be used directly by users.
57 // Construct from an Attribute.
58 explicit DiagnosticArgument(Attribute attr);
59 // Construct from a floating point number.
60 explicit DiagnosticArgument(double val)
62 explicit DiagnosticArgument(float val) : DiagnosticArgument(double(val)) {}
63 // Construct from a signed integer.
64 template <typename T>
66 T val, std::enable_if_t<std::is_signed<T>::value &&
67 std::numeric_limits<T>::is_integer &&
68 sizeof(T) <= sizeof(int64_t)> * = nullptr)
70 // Construct from an unsigned integer.
71 template <typename T>
73 T val, std::enable_if_t<std::is_unsigned<T>::value &&
74 std::numeric_limits<T>::is_integer &&
75 sizeof(T) <= sizeof(uint64_t)> * = nullptr)
76 : kind(DiagnosticArgumentKind::Unsigned), unsignedVal(uint64_t(val)) {}
77 // Construct from a string reference.
78 explicit DiagnosticArgument(StringRef val)
80 // Construct from a Type.
81 explicit DiagnosticArgument(Type val);
82
83 /// Enum that represents the different kinds of diagnostic arguments
84 /// supported.
93
94 /// Outputs this argument to a stream.
95 void print(raw_ostream &os) const;
96
97 /// Returns the kind of this argument.
98 DiagnosticArgumentKind getKind() const { return kind; }
99
100 /// Returns this argument as an Attribute.
102
103 /// Returns this argument as a double.
104 double getAsDouble() const {
106 return doubleVal;
107 }
108
109 /// Returns this argument as a signed integer.
112 return integerVal;
113 }
114
115 /// Returns this argument as a string.
116 StringRef getAsString() const {
118 return stringVal;
119 }
120
121 /// Returns this argument as a Type.
122 Type getAsType() const;
123
124 /// Returns this argument as an unsigned integer.
125 uint64_t getAsUnsigned() const {
127 return unsignedVal;
128 }
129
130private:
131 friend class Diagnostic;
132
133 /// The kind of this argument.
135
136 /// The value of this argument.
137 union {
138 double doubleVal;
140 uint64_t unsignedVal;
142 StringRef stringVal;
143 };
144};
145
147 arg.print(os);
148 return os;
149}
150
151//===----------------------------------------------------------------------===//
152// Diagnostic
153//===----------------------------------------------------------------------===//
154
155/// This class contains all of the information necessary to report a diagnostic
156/// to the DiagnosticEngine. It should generally not be constructed directly,
157/// and instead used transitively via InFlightDiagnostic.
158///
159/// A diagnostic may contain multiple message parts that share its location,
160/// severity, metadata, and attached notes. Empty message parts are ignored.
162 using NoteVector = SmallVector<std::unique_ptr<Diagnostic>, 0>;
163
164public:
166 : loc(loc), severity(severity) {}
167 Diagnostic(Diagnostic &&) = default;
169
170 /// Returns the severity of this diagnostic.
171 DiagnosticSeverity getSeverity() const { return severity; }
172
173 /// Returns the source location for this diagnostic.
174 Location getLocation() const { return loc; }
175
176 /// Returns the current list of diagnostic arguments.
178 ArrayRef<DiagnosticArgument> getArguments() const { return arguments; }
179
180 /// Stream operator for inserting new diagnostic arguments.
181 template <typename Arg>
182 std::enable_if_t<!std::is_convertible<Arg, StringRef>::value &&
183 std::is_constructible<DiagnosticArgument, Arg>::value,
184 Diagnostic &>
185 operator<<(Arg &&val) {
186 arguments.push_back(DiagnosticArgument(std::forward<Arg>(val)));
187 return *this;
188 }
189 Diagnostic &operator<<(StringAttr val);
190
191 /// Stream in a string literal.
192 template <size_t n>
193 Diagnostic &operator<<(const char (&val)[n]) {
194 arguments.push_back(DiagnosticArgument(val));
195 return *this;
196 }
197
198 /// Stream in a Twine argument.
199 Diagnostic &operator<<(char val);
200 Diagnostic &operator<<(const Twine &val);
201 Diagnostic &operator<<(Twine &&val);
202
203 /// Stream in an OperationName.
205
206 /// Stream in an Operation.
209 Diagnostic &operator<<(Operation *op) { return *this << *op; }
210 /// Append an operation with the given printing flags.
211 Diagnostic &appendOp(Operation &op, const OpPrintingFlags &flags);
212
213 /// Stream in a Value.
215
216 /// Stream in an enum that has a `stringifyEnum` function.
217 template <typename EnumT>
218 std::enable_if_t<
219 std::is_enum_v<EnumT> &&
220 std::is_convertible_v<decltype(stringifyEnum(std::declval<EnumT>())),
221 StringRef>,
222 Diagnostic &>
223 operator<<(EnumT val) {
224 return *this << stringifyEnum(val);
225 }
226
227 /// Stream in a range.
228 template <typename T, typename ValueT = llvm::detail::ValueOfRange<T>>
229 std::enable_if_t<!std::is_constructible<DiagnosticArgument, T>::value,
230 Diagnostic &>
231 operator<<(T &&range) {
232 return appendRange(range);
233 }
234
235 /// Append a range to the diagnostic. The default delimiter between elements
236 /// is ','.
237 template <typename T>
238 Diagnostic &appendRange(const T &c, const char *delim = ", ") {
239 llvm::interleave(
240 c, [this](const auto &a) { *this << a; }, [&]() { *this << delim; });
241 return *this;
242 }
243
244 /// Append arguments to the diagnostic.
245 template <typename Arg1, typename Arg2, typename... Args>
246 Diagnostic &append(Arg1 &&arg1, Arg2 &&arg2, Args &&...args) {
247 append(std::forward<Arg1>(arg1));
248 return append(std::forward<Arg2>(arg2), std::forward<Args>(args)...);
249 }
250 /// Append one argument to the diagnostic.
251 template <typename Arg>
252 Diagnostic &append(Arg &&arg) {
254 return *this;
255 }
256
257 /// Outputs this diagnostic to a stream. If `messagePartIndex` is provided,
258 /// only that message part is printed; otherwise, all arguments are printed
259 /// without separators between message parts.
260 void print(raw_ostream &os,
261 std::optional<int64_t> messagePartIndex = std::nullopt) const;
262
263 /// Converts the diagnostic to a string, concatenating all the parts if there
264 /// are multiples.
265 std::string str() const;
266
267 /// Converts each message part to a separate string. Returns a single string
268 /// if the diagnostic has not been divided into multiple parts.
270
271 /// Attaches a note to this diagnostic. A new location may be optionally
272 /// provided, if not, then the location defaults to the one specified for this
273 /// diagnostic. Notes may not be attached to other notes.
274 Diagnostic &attachNote(std::optional<Location> noteLoc = std::nullopt);
275
276 using note_iterator = llvm::pointee_iterator<NoteVector::iterator>;
278 llvm::pointee_iterator<NoteVector::const_iterator>;
279
280 /// Returns the notes held by this diagnostic.
282 return llvm::make_pointee_range(notes);
283 }
285 return llvm::make_pointee_range(notes);
286 }
287
288 /// Allow a diagnostic to be converted to 'failure'.
289 operator LogicalResult() const;
290
291 /// Allow a diagnostic to be converted to 'failure'.
292 operator ParseResult() const { return ParseResult(LogicalResult(*this)); }
293
294 /// Allow a diagnostic to be converted to FailureOr<T>. Always results in
295 /// 'failure' because this cast cannot possibly return an object of 'T'.
296 template <typename T>
297 operator FailureOr<T>() const {
298 return failure();
299 }
300
301 /// Returns the current list of diagnostic metadata.
303
304 /// Returns a string argument that refers to a copy of `val` owned by this
305 /// diagnostic, so the argument remains valid for as long as the diagnostic
306 /// does. This is useful for adding a non-constant string to the metadata.
307 DiagnosticArgument getStringArgument(const Twine &val);
308
309 /// Starts a new message part. This has no effect if the current message part
310 /// is empty.
311 void startNewMessagePart();
312
313private:
314 Diagnostic(const Diagnostic &rhs) = delete;
315 Diagnostic &operator=(const Diagnostic &rhs) = delete;
316
317 /// The source location.
318 Location loc;
319
320 /// The severity of this diagnostic.
321 DiagnosticSeverity severity;
322
323 /// The current list of arguments.
325
326 /// A list of string values used as arguments. This is used to guarantee the
327 /// liveness of non-constant strings used in diagnostics.
329
330 /// The exclusive end indices in `arguments` of completed message parts.
331 /// Most diagnostics have only one part, so avoid reserving inline storage.
332 SmallVector<size_t, 0> messagePartEnds;
333
334 /// A list of attached notes.
335 NoteVector notes;
336
337 /// A list of metadata attached to this Diagnostic.
339};
340
342 diag.print(os);
343 return os;
344}
345
346//===----------------------------------------------------------------------===//
347// InFlightDiagnostic
348//===----------------------------------------------------------------------===//
349
350namespace diag {
351/// Starts a new message part in an in-flight diagnostic. Leading, trailing, and
352/// consecutive uses of `next` do not create empty message parts.
354} // namespace diag
355
356/// This class represents a diagnostic that is inflight and set to be reported.
357/// This allows for last minute modifications of the diagnostic before it is
358/// emitted by a DiagnosticEngine.
360public:
363 : owner(rhs.owner), impl(std::move(rhs.impl)) {
364 // Reset the rhs diagnostic.
365 rhs.impl.reset();
366 rhs.abandon();
367 }
369 if (isInFlight())
370 report();
371 }
372
373 /// Stream operator for new diagnostic arguments.
374 template <typename Arg>
376 return append(std::forward<Arg>(arg));
377 }
378 template <typename Arg>
380 return std::move(append(std::forward<Arg>(arg)));
381 }
382
383 /// Enables stream-style manipulators to be chained into the diagnostic.
386 return manip(*this);
387 }
388
391 return std::move(manip(*this));
392 }
393
394 /// Append arguments to the diagnostic.
395 template <typename... Args>
396 InFlightDiagnostic &append(Args &&...args) & {
397 assert(isActive() && "diagnostic not active");
398 if (isInFlight())
399 impl->append(std::forward<Args>(args)...);
400 return *this;
401 }
402 template <typename... Args>
403 InFlightDiagnostic &&append(Args &&...args) && {
404 return std::move(append(std::forward<Args>(args)...));
405 }
406
407 /// Attaches a note to this diagnostic.
408 Diagnostic &attachNote(std::optional<Location> noteLoc = std::nullopt) {
409 assert(isActive() && "diagnostic not active");
410 return impl->attachNote(noteLoc);
411 }
412
413 /// Returns the underlying diagnostic or nullptr if this diagnostic isn't
414 /// active.
415 Diagnostic *getUnderlyingDiagnostic() { return impl ? &*impl : nullptr; }
416
417 /// Reports the diagnostic to the engine.
418 void report();
419
420 /// Abandons this diagnostic so that it will no longer be reported.
421 void abandon();
422
423 /// Allow an inflight diagnostic to be converted to 'failure', otherwise
424 /// 'success' if this is an empty diagnostic.
425 operator LogicalResult() const;
426
427 /// Allow an inflight diagnostic to be converted to 'failure', otherwise
428 /// 'success' if this is an empty diagnostic.
429 operator ParseResult() const { return ParseResult(LogicalResult(*this)); }
430
431 /// Allow an inflight diagnostic to be converted to FailureOr<T>. Always
432 /// results in 'failure' because this cast cannot possibly return an object of
433 /// 'T'.
434 template <typename T>
435 operator FailureOr<T>() const {
436 return failure();
437 }
438
439private:
440 InFlightDiagnostic &operator=(const InFlightDiagnostic &) = delete;
441 InFlightDiagnostic &operator=(InFlightDiagnostic &&) = delete;
443 : owner(owner), impl(std::move(rhs)) {}
444
445 /// Returns true if the diagnostic is still active, i.e. it has a live
446 /// diagnostic.
447 bool isActive() const { return impl.has_value(); }
448
449 /// Returns true if the diagnostic is still in flight to be reported.
450 bool isInFlight() const { return owner; }
451
452 // Allow access to the constructor.
453 friend DiagnosticEngine;
455
456 /// The engine that this diagnostic is to report to.
457 DiagnosticEngine *owner = nullptr;
458
459 /// The raw diagnostic that is inflight to be reported.
460 std::optional<Diagnostic> impl;
461};
462
464 diag.impl->startNewMessagePart();
465 return diag;
466}
467
468//===----------------------------------------------------------------------===//
469// DiagnosticEngine
470//===----------------------------------------------------------------------===//
471
472/// This class is the main interface for diagnostics. The DiagnosticEngine
473/// manages the registration of diagnostic handlers as well as the core API for
474/// diagnostic emission. This class should not be constructed directly, but
475/// instead interfaced with via an MLIRContext instance.
476class DiagnosticEngine {
477public:
479
480 // Diagnostic handler registration and use. MLIR supports the ability for the
481 // IR to carry arbitrary metadata about operation location information. If a
482 // problem is detected by the compiler, it can invoke the emitError /
483 // emitWarning / emitRemark method on an Operation and have it get reported
484 // through this interface.
485 //
486 // Tools using MLIR are encouraged to register error handlers and define a
487 // schema for their location information. If they don't, then warnings and
488 // notes will be dropped and errors will be emitted to errs.
489
490 /// The handler type for MLIR diagnostics. This function takes a diagnostic as
491 /// input, and returns success if the handler has fully processed this
492 /// diagnostic. Returns failure otherwise.
493 using HandlerTy = llvm::unique_function<LogicalResult(Diagnostic &)>;
494
495 /// A handle to a specific registered handler object.
496 using HandlerID = uint64_t;
497
498 /// Register a new handler for diagnostics to the engine. Diagnostics are
499 /// process by handlers in stack-like order, meaning that the last added
500 /// handlers will process diagnostics first. This function returns a unique
501 /// identifier for the registered handler, which can be used to unregister
502 /// this handler at a later time.
504
505 /// Set the diagnostic handler with a function that returns void. This is a
506 /// convenient wrapper for handlers that always completely process the given
507 /// diagnostic.
508 template <typename FuncTy, typename RetT = decltype(std::declval<FuncTy>()(
509 std::declval<Diagnostic &>()))>
510 std::enable_if_t<std::is_same<RetT, void>::value, HandlerID>
511 registerHandler(FuncTy &&handler) {
512 return registerHandler([=](Diagnostic &diag) {
513 handler(diag);
514 return success();
515 });
516 }
517
518 /// Erase the registered diagnostic handler with the given identifier.
519 void eraseHandler(HandlerID id);
520
521 /// Create a new inflight diagnostic with the given location and severity.
523 assert(severity != DiagnosticSeverity::Note &&
524 "notes should not be emitted directly");
525 return InFlightDiagnostic(this, Diagnostic(loc, severity));
526 }
527
528 /// Emit a diagnostic using the registered issue handler if present, or with
529 /// the default behavior if not. The diagnostic instance is consumed in the
530 /// process.
531 void emit(Diagnostic &&diag);
532
533private:
534 friend class MLIRContextImpl;
535 DiagnosticEngine();
536
537 /// The internal implementation of the DiagnosticEngine.
538 std::unique_ptr<detail::DiagnosticEngineImpl> impl;
539};
540
541/// Utility method to emit an error message using this location.
543InFlightDiagnostic emitError(Location loc, const Twine &message);
544
545/// Utility method to emit a warning message using this location.
547InFlightDiagnostic emitWarning(Location loc, const Twine &message);
548
549/// Utility method to emit a remark message using this location.
551InFlightDiagnostic emitRemark(Location loc, const Twine &message);
552
553/// Overloads of the above emission functions that take an optionally null
554/// location. If the location is null, no diagnostic is emitted and a failure is
555/// returned. Given that the provided location may be null, these methods take
556/// the diagnostic arguments directly instead of relying on the returned
557/// InFlightDiagnostic.
558template <typename... Args>
559LogicalResult emitOptionalError(std::optional<Location> loc, Args &&...args) {
560 if (loc)
561 return emitError(*loc).append(std::forward<Args>(args)...);
562 return failure();
563}
564template <typename... Args>
565LogicalResult emitOptionalWarning(std::optional<Location> loc, Args &&...args) {
566 if (loc)
567 return emitWarning(*loc).append(std::forward<Args>(args)...);
568 return failure();
569}
570template <typename... Args>
571LogicalResult emitOptionalRemark(std::optional<Location> loc, Args &&...args) {
572 if (loc)
573 return emitRemark(*loc).append(std::forward<Args>(args)...);
574 return failure();
575}
576
577//===----------------------------------------------------------------------===//
578// ScopedDiagnosticHandler
579//===----------------------------------------------------------------------===//
580
581/// This diagnostic handler is a simple RAII class that registers and erases a
582/// diagnostic handler on a given context. This class can be either be used
583/// directly, or in conjunction with a derived diagnostic handler.
585public:
586 explicit ScopedDiagnosticHandler(MLIRContext *ctx) : handlerID(0), ctx(ctx) {}
587 template <typename FuncTy>
588 ScopedDiagnosticHandler(MLIRContext *ctx, FuncTy &&handler)
589 : handlerID(0), ctx(ctx) {
590 setHandler(std::forward<FuncTy>(handler));
591 }
593
594protected:
595 /// Set the handler to manage via RAII.
596 template <typename FuncTy>
597 void setHandler(FuncTy &&handler) {
598 auto &diagEngine = ctx->getDiagEngine();
599 if (handlerID)
600 diagEngine.eraseHandler(handlerID);
601 handlerID = diagEngine.registerHandler(std::forward<FuncTy>(handler));
602 }
603
604private:
605 /// The unique id for the scoped handler.
607
608 /// The context to erase the handler from.
609 MLIRContext *ctx;
610};
611
612//===----------------------------------------------------------------------===//
613// SourceMgrDiagnosticHandler
614//===----------------------------------------------------------------------===//
615
616namespace detail {
617struct SourceMgrDiagnosticHandlerImpl;
618} // namespace detail
619
620/// This class is a utility diagnostic handler for use with llvm::SourceMgr.
622public:
623 /// This type represents a functor used to filter out locations when printing
624 /// a diagnostic. It should return true if the provided location is okay to
625 /// display, false otherwise. If all locations in a diagnostic are filtered
626 /// out, the first location is used as the sole location. When deciding
627 /// whether or not to filter a location, this function should not recurse into
628 /// any nested location. This recursion is handled automatically by the
629 /// caller.
630 using ShouldShowLocFn = llvm::unique_function<bool(Location)>;
631
632 SourceMgrDiagnosticHandler(llvm::SourceMgr &mgr, MLIRContext *ctx,
635 SourceMgrDiagnosticHandler(llvm::SourceMgr &mgr, MLIRContext *ctx,
638
639 /// Emit the given diagnostic information with the held source manager.
640 void emitDiagnostic(Location loc, Twine message, DiagnosticSeverity kind,
641 bool displaySourceLine = true);
642
643 /// Set the maximum depth that a call stack will be printed. Defaults to 10.
644 void setCallStackLimit(unsigned limit);
645
646protected:
647 /// Emit the given diagnostic with the held source manager.
649
650 /// Get a memory buffer for the given file, or nullptr if no file is
651 /// available.
652 const llvm::MemoryBuffer *getBufferForFile(StringRef filename);
653
654 /// The source manager that we are wrapping.
655 llvm::SourceMgr &mgr;
656
657 /// The output stream to use when printing diagnostics.
659
660 /// A functor used when determining if a location for a diagnostic should be
661 /// shown. If null, all locations should be shown.
663
664private:
665 /// Convert a location into the given memory buffer into an SMLoc.
666 SMLoc convertLocToSMLoc(FileLineColLoc loc);
667
668 /// Given a location, returns the first nested location (including 'loc') that
669 /// can be shown to the user.
670 std::optional<Location> findLocToShow(Location loc);
671
672 /// The maximum depth that a call stack will be printed.
673 unsigned callStackLimit = 10;
674
675 std::unique_ptr<detail::SourceMgrDiagnosticHandlerImpl> impl;
676};
677
678//===----------------------------------------------------------------------===//
679// SourceMgrDiagnosticVerifierHandler
680//===----------------------------------------------------------------------===//
681
682namespace detail {
683struct SourceMgrDiagnosticVerifierHandlerImpl;
684} // namespace detail
685
686/// This class is a utility diagnostic handler for use with llvm::SourceMgr that
687/// verifies that emitted diagnostics match 'expected-*' lines on the
688/// corresponding line of the source file.
690public:
691 enum class Level { None = 0, All, OnlyExpected };
692 SourceMgrDiagnosticVerifierHandler(llvm::SourceMgr &srcMgr, MLIRContext *ctx,
693 raw_ostream &out,
694 Level level = Level::All);
695 SourceMgrDiagnosticVerifierHandler(llvm::SourceMgr &srcMgr, MLIRContext *ctx,
696 Level level = Level::All);
698
699 /// Returns the status of the handler and verifies that all expected
700 /// diagnostics were emitted. This return success if all diagnostics were
701 /// verified correctly, failure otherwise.
702 LogicalResult verify();
703
704 /// Register this handler with `ctx` and return a scoped registration.
705 /// Destroy the returned handle before either this handler or `ctx`.
706 [[nodiscard]] std::unique_ptr<ScopedDiagnosticHandler>
708
709private:
710 /// Process a diagnostic and its notes.
711 void process(Diagnostic &diag);
712
713 /// Process a LocationAttr diagnostic.
714 void process(LocationAttr loc, StringRef msg, DiagnosticSeverity kind);
715
716 std::unique_ptr<detail::SourceMgrDiagnosticVerifierHandlerImpl> impl;
717};
718
719//===----------------------------------------------------------------------===//
720// ParallelDiagnosticHandler
721//===----------------------------------------------------------------------===//
722
723namespace detail {
724struct ParallelDiagnosticHandlerImpl;
725} // namespace detail
726
727/// This class is a utility diagnostic handler for use when multi-threading some
728/// part of the compiler where diagnostics may be emitted. This handler ensures
729/// a deterministic ordering to the emitted diagnostics that mirrors that of a
730/// single-threaded compilation.
732public:
735
736 /// Set the order id for the current thread. This is required to be set by
737 /// each thread that will be emitting diagnostics to this handler. The orderID
738 /// corresponds to the order in which diagnostics would be emitted when
739 /// executing synchronously. For example, if we were processing a list
740 /// of operations [a, b, c] on a single-thread. Diagnostics emitted while
741 /// processing operation 'a' would be emitted before those for 'b' or 'c'.
742 /// This corresponds 1-1 with the 'orderID'. The thread that is processing 'a'
743 /// should set the orderID to '0'; the thread processing 'b' should set it to
744 /// '1'; and so on and so forth. This provides a way for the handler to
745 /// deterministically order the diagnostics that it receives given the thread
746 /// that it is receiving on.
747 ///
748 /// Each set must be paired with an erase on the same thread before the
749 /// handler is destroyed. Nesting distinct handlers on one thread is
750 /// supported; reentrant use of one handler on one thread is not.
751 void setOrderIDForThread(size_t orderID);
752
753 /// Remove the order id for the current thread. This removes the thread from
754 /// diagnostics tracking. Must be called on the same thread that set it,
755 /// before the handler is destroyed.
757
758private:
759 std::unique_ptr<detail::ParallelDiagnosticHandlerImpl> impl;
760};
761} // namespace mlir
762
763#endif
return success()
return MutableOperandRange * this
Attributes are known-constant values of operations.
Definition Attributes.h:25
A variant type that holds a single argument for a diagnostic.
Definition Diagnostics.h:53
DiagnosticArgumentKind
Enum that represents the different kinds of diagnostic arguments supported.
Definition Diagnostics.h:85
StringRef getAsString() const
Returns this argument as a string.
double getAsDouble() const
Returns this argument as a double.
DiagnosticArgument(Attribute attr)
Note: The constructors below are only exposed due to problems accessing constructors from type traits...
Type getAsType() const
Returns this argument as a Type.
int64_t getAsInteger() const
Returns this argument as a signed integer.
DiagnosticArgument(double val)
Definition Diagnostics.h:60
DiagnosticArgumentKind getKind() const
Returns the kind of this argument.
Definition Diagnostics.h:98
Attribute getAsAttribute() const
Returns this argument as an Attribute.
DiagnosticArgument(T val, std::enable_if_t< std::is_unsigned< T >::value &&std::numeric_limits< T >::is_integer &&sizeof(T)<=sizeof(uint64_t)> *=nullptr)
Definition Diagnostics.h:72
void print(raw_ostream &os) const
Outputs this argument to a stream.
DiagnosticArgument(float val)
Definition Diagnostics.h:62
uint64_t getAsUnsigned() const
Returns this argument as an unsigned integer.
DiagnosticArgument(StringRef val)
Definition Diagnostics.h:78
DiagnosticArgument(T val, std::enable_if_t< std::is_signed< T >::value &&std::numeric_limits< T >::is_integer &&sizeof(T)<=sizeof(int64_t)> *=nullptr)
Definition Diagnostics.h:65
This class is the main interface for diagnostics.
uint64_t HandlerID
A handle to a specific registered handler object.
std::enable_if_t< std::is_same< RetT, void >::value, HandlerID > registerHandler(FuncTy &&handler)
Set the diagnostic handler with a function that returns void.
friend class MLIRContextImpl
InFlightDiagnostic emit(Location loc, DiagnosticSeverity severity)
Create a new inflight diagnostic with the given location and severity.
void eraseHandler(HandlerID id)
Erase the registered diagnostic handler with the given identifier.
llvm::unique_function< LogicalResult(Diagnostic &)> HandlerTy
The handler type for MLIR diagnostics.
HandlerID registerHandler(HandlerTy handler)
Register a new handler for diagnostics to the engine.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
DiagnosticSeverity getSeverity() const
Returns the severity of this diagnostic.
std::string str() const
Converts the diagnostic to a string, concatenating all the parts if there are multiples.
Diagnostic & operator<<(const char(&val)[n])
Stream in a string literal.
void startNewMessagePart()
Starts a new message part.
Diagnostic & append(Arg &&arg)
Append one argument to the diagnostic.
Diagnostic & operator<<(Operation *op)
Location getLocation() const
Returns the source location for this diagnostic.
SmallVector< std::string > strs() const
Converts each message part to a separate string.
Diagnostic & attachNote(std::optional< Location > noteLoc=std::nullopt)
Attaches a note to this diagnostic.
MutableArrayRef< DiagnosticArgument > getArguments()
Returns the current list of diagnostic arguments.
llvm::pointee_iterator< NoteVector::iterator > note_iterator
DiagnosticArgument getStringArgument(const Twine &val)
Returns a string argument that refers to a copy of val owned by this diagnostic, so the argument rema...
iterator_range< note_iterator > getNotes()
Returns the notes held by this diagnostic.
Diagnostic(Location loc, DiagnosticSeverity severity)
std::enable_if_t< std::is_enum_v< EnumT > &&std::is_convertible_v< decltype(stringifyEnum(std::declval< EnumT >())), StringRef >, Diagnostic & > operator<<(EnumT val)
Stream in an enum that has a stringifyEnum function.
std::enable_if_t<!std::is_convertible< Arg, StringRef >::value &&std::is_constructible< DiagnosticArgument, Arg >::value, Diagnostic & > operator<<(Arg &&val)
Stream operator for inserting new diagnostic arguments.
void print(raw_ostream &os, std::optional< int64_t > messagePartIndex=std::nullopt) const
Outputs this diagnostic to a stream.
iterator_range< const_note_iterator > getNotes() const
llvm::pointee_iterator< NoteVector::const_iterator > const_note_iterator
Diagnostic & append(Arg1 &&arg1, Arg2 &&arg2, Args &&...args)
Append arguments to the diagnostic.
SmallVectorImpl< DiagnosticArgument > & getMetadata()
Returns the current list of diagnostic metadata.
ArrayRef< DiagnosticArgument > getArguments() const
Diagnostic & appendRange(const T &c, const char *delim=", ")
Append a range to the diagnostic.
Diagnostic & operator=(Diagnostic &&)=default
Diagnostic(Diagnostic &&)=default
Diagnostic & appendOp(Operation &op, const OpPrintingFlags &flags)
Append an operation with the given printing flags.
An instance of this location represents a tuple of file, line number, and column number.
Definition Location.h:176
This class represents a diagnostic that is inflight and set to be reported.
InFlightDiagnostic & operator<<(Arg &&arg) &
Stream operator for new diagnostic arguments.
InFlightDiagnostic && append(Args &&...args) &&
InFlightDiagnostic & append(Args &&...args) &
Append arguments to the diagnostic.
Diagnostic * getUnderlyingDiagnostic()
Returns the underlying diagnostic or nullptr if this diagnostic isn't active.
InFlightDiagnostic && operator<<(Arg &&arg) &&
void report()
Reports the diagnostic to the engine.
Diagnostic & attachNote(std::optional< Location > noteLoc=std::nullopt)
Attaches a note to this diagnostic.
InFlightDiagnostic(InFlightDiagnostic &&rhs)
void abandon()
Abandons this diagnostic so that it will no longer be reported.
Location objects represent source locations information in MLIR.
Definition Location.h:32
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Set of flags used to control the behavior of the various IR print methods (e.g.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void eraseOrderIDForThread()
Remove the order id for the current thread.
ParallelDiagnosticHandler(MLIRContext *ctx)
void setOrderIDForThread(size_t orderID)
Set the order id for the current thread.
ScopedDiagnosticHandler(MLIRContext *ctx)
ScopedDiagnosticHandler(MLIRContext *ctx, FuncTy &&handler)
void setHandler(FuncTy &&handler)
Set the handler to manage via RAII.
void setCallStackLimit(unsigned limit)
Set the maximum depth that a call stack will be printed. Defaults to 10.
void emitDiagnostic(Location loc, Twine message, DiagnosticSeverity kind, bool displaySourceLine=true)
Emit the given diagnostic information with the held source manager.
raw_ostream & os
The output stream to use when printing diagnostics.
SourceMgrDiagnosticHandler(llvm::SourceMgr &mgr, MLIRContext *ctx, raw_ostream &os, ShouldShowLocFn &&shouldShowLocFn={})
ShouldShowLocFn shouldShowLocFn
A functor used when determining if a location for a diagnostic should be shown.
const llvm::MemoryBuffer * getBufferForFile(StringRef filename)
Get a memory buffer for the given file, or nullptr if no file is available.
llvm::SourceMgr & mgr
The source manager that we are wrapping.
llvm::unique_function< bool(Location)> ShouldShowLocFn
This type represents a functor used to filter out locations when printing a diagnostic.
SourceMgrDiagnosticVerifierHandler(llvm::SourceMgr &srcMgr, MLIRContext *ctx, raw_ostream &out, Level level=Level::All)
std::unique_ptr< ScopedDiagnosticHandler > registerInContext(MLIRContext *ctx)
Register this handler with ctx and return a scoped registration.
LogicalResult verify()
Returns the status of the handler and verifies that all expected diagnostics were emitted.
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
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
AttrTypeReplacer.
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Definition Diagnostics.h:41
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
LogicalResult emitOptionalRemark(std::optional< Location > loc, Args &&...args)
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
InFlightDiagnostic emitRemark(Location loc)
Utility method to emit a remark message using this location.
LogicalResult emitOptionalWarning(std::optional< Location > loc, Args &&...args)