CIRCT 24.0.0git
Loading...
Searching...
No Matches
FIRRTLAnnotations.h
Go to the documentation of this file.
1//===- FIRRTLAnnotations.h - Code for working with Annotations --*- 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 declares helpers for working with FIRRTL annotations.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef CIRCT_DIALECT_FIRRTL_ANNOTATIONS_H
14#define CIRCT_DIALECT_FIRRTL_ANNOTATIONS_H
15
16#include "circt/Support/LLVM.h"
17#include "mlir/IR/BuiltinAttributes.h"
18#include "mlir/IR/BuiltinTypes.h"
19#include "mlir/IR/Operation.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/PointerLikeTypeTraits.h"
23
24namespace circt {
25namespace hw {
27} // namespace hw
28namespace firrtl {
29
31class FModuleOp;
32class FModuleLike;
33class MemOp;
34class InstanceOp;
35class FIRRTLType;
36
37/// Return the name of the attribute used for annotations on FIRRTL ops.
38inline StringRef getAnnotationAttrName() { return "annotations"; }
39
40/// Return the name of the attribute used for port annotations on FIRRTL ops.
41inline StringRef getPortAnnotationAttrName() { return "portAnnotations"; }
42
43inline ArrayAttr getAnnotationsIfPresent(Operation *op) {
44 return op->getAttrOfType<ArrayAttr>(getAnnotationAttrName());
45}
46
47/// This class provides a read-only projection of an annotation.
49public:
50 Annotation() = default;
51
52 explicit Annotation(Attribute attr) : attr(attr) {
53 assert(attr && "null attributes not allowed");
54 }
55
56 // Make a new annotation which is a clone of anno with a new fieldID.
57 Annotation(Annotation anno, uint64_t fieldID) : attr(anno.attr) {
58 auto oldFieldID = anno.getMember<IntegerAttr>("circt.fieldID");
59 if (oldFieldID && !fieldID) {
60 removeMember("circt.fieldID");
61 return;
62 }
63 if (fieldID)
64 setMember("circt.fieldID",
65 IntegerAttr::get(IntegerType::get(anno.attr.getContext(), 32),
66 APInt(32, fieldID)));
67 }
68
69 /// Get the data dictionary of this attribute.
70 DictionaryAttr getDict() const;
71
72 /// Set the data dictionary of this attribute.
73 void setDict(DictionaryAttr dict);
74
75 /// Get the field id this attribute targets.
76 unsigned getFieldID() const;
77
78 /// Get the underlying attribute.
79 Attribute getAttr() const { return attr; }
80
81 /// Return the 'class' that this annotation is representing.
82 StringAttr getClassAttr() const;
83 StringRef getClass() const;
84
85 /// Return true if this annotation matches any of the specified class names.
86 template <typename... Args>
87 bool isClass(Args... names) const {
88 return ClassIsa{getClassAttr()}(names...);
89 }
90
91 /// Return a member of the annotation.
92 template <typename AttrClass = Attribute>
93 AttrClass getMember(StringAttr name) const {
94 return getDict().getAs<AttrClass>(name);
95 }
96 template <typename AttrClass = Attribute>
97 AttrClass getMember(StringRef name) const {
98 return getDict().getAs<AttrClass>(name);
99 }
100
101 /// Add or set a member of the annotation to a value.
102 void setMember(StringAttr name, Attribute value);
103 void setMember(StringRef name, Attribute value);
104
105 /// Remove a member of the annotation.
106 void removeMember(StringAttr name);
107 void removeMember(StringRef name);
108
109 using iterator = llvm::ArrayRef<NamedAttribute>::iterator;
110 iterator begin() const { return getDict().begin(); }
111 iterator end() const { return getDict().end(); }
112
113 bool operator==(const Annotation &other) const { return attr == other.attr; }
114 bool operator!=(const Annotation &other) const { return !(*this == other); }
115 explicit operator bool() const { return bool(attr); }
116 bool operator!() const { return attr == nullptr; }
117
118#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
119 LLVM_DUMP_METHOD void dump();
120#endif
121
122private:
123 Attribute attr;
124
125 /// Helper struct to perform variadic class equality check.
126 struct ClassIsa {
127 StringAttr cls;
128
129 bool operator()() const { return false; }
130 template <typename T, typename... Rest>
131 bool operator()(T name, Rest... rest) const {
132 return compare(name) || (*this)(rest...);
133 }
134
135 private:
136 bool compare(StringAttr name) const { return cls == name; }
137 bool compare(StringRef name) const { return cls && cls.getValue() == name; }
138 };
139};
140
141/// This class provides a read-only projection over the MLIR attributes that
142/// represent a set of annotations. It is intended to make this work less
143/// stringly typed and fiddly for clients.
144///
146public:
148
149 /// Form an empty annotation set.
150 explicit AnnotationSet(MLIRContext *context)
151 : annotations(ArrayAttr::get(context, {})) {}
152
153 /// Form an annotation set from an array of annotation attributes.
154 explicit AnnotationSet(ArrayRef<Attribute> annotations, MLIRContext *context);
155
156 /// Form an annotation set from an array of annotations.
157 explicit AnnotationSet(ArrayRef<Annotation> annotations,
158 MLIRContext *context);
159
160 /// Form an annotation set with a non-null ArrayAttr.
162 assert(annotations && "Cannot use null attribute set");
163 }
164
165 /// Form an annotation set with a possibly-null ArrayAttr.
166 explicit AnnotationSet(ArrayAttr annotations, MLIRContext *context);
167
168 /// Get an annotation set for the specified operation.
169 explicit AnnotationSet(Operation *op);
170
171 /// Get an annotation set for the specified port.
172 static AnnotationSet forPort(FModuleLike op, size_t portNo);
173 static AnnotationSet forPort(MemOp op, size_t portNo);
174
175 /// Get an annotation set for the specified value.
176 static AnnotationSet get(Value v);
177
178 /// Return all the raw annotations that exist.
179 ArrayRef<Attribute> getArray() const { return annotations.getValue(); }
180
181 /// Return this annotation set as an ArrayAttr.
182 ArrayAttr getArrayAttr() const {
183 assert(annotations && "Cannot use null attribute set");
184 return annotations;
185 }
186
187 /// Store the annotations in this set in an operation's `annotations`
188 /// attribute, overwriting any existing annotations. Removes the `annotations`
189 /// attribute if the set is empty. Returns true if the operation was modified,
190 /// false otherwise.
191 bool applyToOperation(Operation *op) const;
192
193 /// Store the annotations in this set in an operation's `portAnnotations`
194 /// attribute, overwriting any existing annotations for this port. Returns
195 /// true if the operation was modified, false otherwise.
196 bool applyToPort(FModuleLike op, size_t portNo) const;
197 bool applyToPort(MemOp op, size_t portNo) const;
198
199 /// Return true if we have an annotation with the specified class name.
200 bool hasAnnotation(StringRef className) const {
201 return !annotations.empty() && hasAnnotationImpl(className);
202 }
203 bool hasAnnotation(StringAttr className) const {
204 return !annotations.empty() && hasAnnotationImpl(className);
205 }
206
207 /// Return true if we have an annotation with the specified class name.
208 template <typename... Args>
209 static bool hasAnnotation(Operation *op, Args... args) {
210 auto annosArray = getAnnotationsIfPresent(op);
211 if (!annosArray)
212 return false;
213 AnnotationSet annotations(annosArray);
214 return !annotations.empty() && (... || annotations.hasAnnotationImpl(args));
215 }
216
217 /// If this annotation set has an annotation with the specified class name,
218 /// return it. Otherwise return a null DictionaryAttr.
219 Annotation getAnnotation(StringRef className) const {
220 if (annotations.empty())
221 return {};
222 return getAnnotationImpl(className);
223 }
224 Annotation getAnnotation(StringAttr className) const {
225 if (annotations.empty())
226 return {};
227 return getAnnotationImpl(className);
228 }
229
231 iterator begin() const;
232 iterator end() const;
233
234 /// Return the MLIRContext corresponding to this AnnotationSet.
235 MLIRContext *getContext() const { return annotations.getContext(); }
236
237 // Support for widely used annotations.
238
239 /// firrtl.transforms.DontTouchAnnotation
240 bool hasDontTouch() const;
241 bool setDontTouch(bool dontTouch);
242 bool addDontTouch();
243 bool removeDontTouch();
244 static bool hasDontTouch(Operation *op);
245 static bool setDontTouch(Operation *op, bool dontTouch);
246 static bool addDontTouch(Operation *op);
247 static bool removeDontTouch(Operation *op);
248
249 bool operator==(const AnnotationSet &other) const {
250 return annotations == other.annotations;
251 }
252 bool operator!=(const AnnotationSet &other) const {
253 return !(*this == other);
254 }
255
256 bool empty() const { return annotations.empty(); }
257
258 size_t size() const { return annotations.size(); }
259
260 /// Add more annotations to this annotation set.
261 void addAnnotations(ArrayRef<Annotation> annotations);
262 void addAnnotations(ArrayRef<Attribute> annotations);
263 void addAnnotations(ArrayAttr annotations);
264
265 /// Remove an annotation from this annotation set. Returns true if any were
266 /// removed, false otherwise.
267 bool removeAnnotation(Annotation anno);
268 bool removeAnnotation(Attribute anno);
269 bool removeAnnotation(StringRef className);
270
271 /// Remove all annotations from this annotation set for which `predicate`
272 /// returns true. The predicate is guaranteed to be called on every
273 /// annotation, such that this method can be used to partition the set by
274 /// extracting and removing annotations at the same time. Returns true if any
275 /// annotations were removed, false otherwise.
276 bool removeAnnotations(llvm::function_ref<bool(Annotation)> predicate);
277
278 /// Remove all annotations with one of the given classes from this annotation
279 /// set.
280 template <typename... Args>
281 bool removeAnnotationsWithClass(Args... names) {
282 return removeAnnotations(
283 [&](Annotation anno) { return anno.isClass(names...); });
284 }
285
286 /// Remove all annotations from an operation for which `predicate` returns
287 /// true. The predicate is guaranteed to be called on every annotation, such
288 /// that this method can be used to partition the set by extracting and
289 /// removing annotations at the same time. Returns true if any annotations
290 /// were removed, false otherwise.
291 static bool removeAnnotations(Operation *op,
292 llvm::function_ref<bool(Annotation)> predicate);
293 static bool removeAnnotations(Operation *op, StringRef className);
294
295 /// Remove all port annotations from a module or extmodule for which
296 /// `predicate` returns true. The predicate is guaranteed to be called on
297 /// every annotation, such that this method can be used to partition a
298 /// module's port annotations by extracting and removing annotations at the
299 /// same time. Returns true if any annotations were removed, false otherwise.
300 static bool removePortAnnotations(
301 Operation *module,
302 llvm::function_ref<bool(unsigned, Annotation)> predicate);
303
304private:
305 bool hasAnnotationImpl(StringAttr className) const;
306 bool hasAnnotationImpl(StringRef className) const;
307 Annotation getAnnotationImpl(StringAttr className) const;
308 Annotation getAnnotationImpl(StringRef className) const;
309
310 ArrayAttr annotations;
311};
312
313// Iteration over the annotation set.
315 : public llvm::indexed_accessor_iterator<AnnotationSetIterator,
316 AnnotationSet, Annotation,
317 Annotation, Annotation> {
318public:
319 // Index into this iterator.
320 Annotation operator*() const;
321
322private:
323 AnnotationSetIterator(AnnotationSet owner, ptrdiff_t curIndex)
324 : llvm::indexed_accessor_iterator<AnnotationSetIterator, AnnotationSet,
326 owner, curIndex) {}
327 friend llvm::indexed_accessor_iterator<AnnotationSetIterator, AnnotationSet,
329 friend class AnnotationSet;
330};
331
332inline auto AnnotationSet::begin() const -> iterator {
333 return AnnotationSetIterator(*this, 0);
334}
335inline auto AnnotationSet::end() const -> iterator {
336 return iterator(*this, annotations.size());
337}
338
339//===----------------------------------------------------------------------===//
340// AnnoTarget
341//===----------------------------------------------------------------------===//
342
343namespace detail {
345 /* implicit */ AnnoTargetImpl(Operation *op) : op(op), portNo(~0UL) {}
346
347 AnnoTargetImpl(Operation *op, unsigned portNo) : op(op), portNo(portNo) {}
348
349 operator bool() const { return getOp(); }
350 bool operator==(const AnnoTargetImpl &other) const {
351 return op == other.op && portNo == other.portNo;
352 }
353 bool operator!=(const AnnoTargetImpl &other) const {
354 return !(*this == other);
355 }
356
357 bool isPort() const { return op && portNo != ~0UL; }
358 bool isOp() const { return op && portNo == ~0UL; }
359
360 Operation *getOp() const { return op; }
361 void setOp(Operation *op) { this->op = op; }
362
363 unsigned getPortNo() const { return portNo; }
364 void setPortNo(unsigned portNo) { this->portNo = portNo; }
365
366protected:
367 Operation *op;
368 size_t portNo;
369};
370} // namespace detail
371
372/// An annotation target is used to keep track of something that is targeted by
373/// an Annotation.
376
377 operator bool() const { return impl; }
378 bool operator==(const AnnoTarget &other) const { return impl == other.impl; }
379 bool operator!=(const AnnoTarget &other) const { return !(*this == other); }
380
381 Operation *getOp() const { return getImpl().getOp(); }
382 void setOp(Operation *op) { getImpl().setOp(op); }
383
384 /// Get the annotations associated with the target.
386
387 /// Set the annotations associated with the target.
388 void setAnnotations(AnnotationSet annotations) const;
389
390 /// Get the parent module of the target.
391 FModuleLike getModule() const;
392
393 /// Get a reference to this target suitable for use in an NLA.
394 Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const;
395
396 /// Get the type of the target.
397 FIRRTLType getType() const;
398
400
401protected:
403};
404
405/// This represents an annotation targeting a specific operation.
406struct OpAnnoTarget : public AnnoTarget {
408
409 OpAnnoTarget(Operation *op) : AnnoTarget(op) {}
410
412 void setAnnotations(AnnotationSet annotations) const;
413 Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const;
414 FIRRTLType getType() const;
415
416 static bool classof(const AnnoTarget &annoTarget) {
417 return annoTarget.getImpl().isOp();
418 }
419};
420
421/// This represents an annotation targeting a specific port of a module, memory,
422/// or instance.
423struct PortAnnoTarget : public AnnoTarget {
425
426 PortAnnoTarget(FModuleLike op, unsigned portNo);
427 PortAnnoTarget(MemOp op, unsigned portNo);
428
429 unsigned getPortNo() const { return getImpl().getPortNo(); }
430 void setPortNo(unsigned portNo) { getImpl().setPortNo(portNo); }
431
433 void setAnnotations(AnnotationSet annotations) const;
434 Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const;
435 FIRRTLType getType() const;
436
437 static bool classof(const AnnoTarget &annoTarget) {
438 return annoTarget.getImpl().isPort();
439 }
440};
441
442} // namespace firrtl
443} // namespace circt
444
445//===----------------------------------------------------------------------===//
446// Traits
447//===----------------------------------------------------------------------===//
448
449namespace llvm {
450
451/// Add support for llvm style casts to AnnoTarget.
452template <typename To, typename From>
453struct CastInfo<
454 To, From,
455 std::enable_if_t<std::is_base_of_v<::circt::firrtl::AnnoTarget, From>>>
457 DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
458 static inline bool isPossible(From target) {
459 // Allow constant upcasting. This also gets around the fact that AnnoTarget
460 // does not implement classof.
461 if constexpr (std::is_base_of_v<To, From>)
462 return true;
463 else
464 return To::classof(target);
465 }
466 static inline To doCast(From target) { return To(target.getImpl()); }
467};
468
469/// Make `Annotation` behave like a `Attribute` in terms of pointer-likeness.
470template <>
471struct PointerLikeTypeTraits<circt::firrtl::Annotation>
472 : PointerLikeTypeTraits<mlir::Attribute> {
474 static inline void *getAsVoidPointer(Annotation v) {
475 return const_cast<void *>(v.getAttr().getAsOpaquePointer());
476 }
477 static inline Annotation getFromVoidPointer(void *p) {
478 return Annotation(mlir::DictionaryAttr::getFromOpaquePointer(p));
479 }
480};
481
482/// Make `Annotation` hash just like `Attribute`.
483template <>
484struct DenseMapInfo<circt::firrtl::Annotation> {
486 static unsigned getHashValue(Annotation val) {
487 return mlir::hash_value(val.getAttr());
488 }
489 static bool isEqual(Annotation lhs, Annotation rhs) { return lhs == rhs; }
490};
491
492/// Make `AnnoTarget` hash.
493template <>
494struct DenseMapInfo<circt::firrtl::AnnoTarget> {
497 static unsigned getHashValue(AnnoTarget val) {
498 auto impl = val.getImpl();
499 return hash_combine(impl.getOp(), impl.getPortNo());
500 }
501 static bool isEqual(AnnoTarget lhs, AnnoTarget rhs) { return lhs == rhs; }
502};
503
504} // namespace llvm
505
506#endif // CIRCT_DIALECT_FIRRTL_ANNOTATIONS_H
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
AnnotationSetIterator(AnnotationSet owner, ptrdiff_t curIndex)
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
MLIRContext * getContext() const
Return the MLIRContext corresponding to this AnnotationSet.
bool hasDontTouch() const
firrtl.transforms.DontTouchAnnotation
bool hasAnnotationImpl(StringAttr className) const
bool removeAnnotations(llvm::function_ref< bool(Annotation)> predicate)
Remove all annotations from this annotation set for which predicate returns true.
Annotation getAnnotationImpl(StringAttr className) const
bool applyToPort(FModuleLike op, size_t portNo) const
Store the annotations in this set in an operation's portAnnotations attribute, overwriting any existi...
ArrayAttr getArrayAttr() const
Return this annotation set as an ArrayAttr.
AnnotationSet(ArrayAttr annotations)
Form an annotation set with a non-null ArrayAttr.
bool removeAnnotation(Annotation anno)
Remove an annotation from this annotation set.
static bool hasAnnotation(Operation *op, Args... args)
Return true if we have an annotation with the specified class name.
bool removeAnnotationsWithClass(Args... names)
Remove all annotations with one of the given classes from this annotation set.
static AnnotationSet get(Value v)
Get an annotation set for the specified value.
Annotation getAnnotation(StringAttr className) const
bool hasAnnotation(StringAttr className) const
bool operator!=(const AnnotationSet &other) const
bool applyToOperation(Operation *op) const
Store the annotations in this set in an operation's annotations attribute, overwriting any existing a...
void addAnnotations(ArrayRef< Annotation > annotations)
Add more annotations to this annotation set.
bool hasAnnotation(StringRef className) const
Return true if we have an annotation with the specified class name.
ArrayRef< Attribute > getArray() const
Return all the raw annotations that exist.
AnnotationSet(MLIRContext *context)
Form an empty annotation set.
static bool removePortAnnotations(Operation *module, llvm::function_ref< bool(unsigned, Annotation)> predicate)
Remove all port annotations from a module or extmodule for which predicate returns true.
static AnnotationSet forPort(FModuleLike op, size_t portNo)
Get an annotation set for the specified port.
Annotation getAnnotation(StringRef className) const
If this annotation set has an annotation with the specified class name, return it.
bool operator==(const AnnotationSet &other) const
AnnotationSetIterator iterator
This class provides a read-only projection of an annotation.
Attribute getAttr() const
Get the underlying attribute.
DictionaryAttr getDict() const
Get the data dictionary of this attribute.
void setDict(DictionaryAttr dict)
Set the data dictionary of this attribute.
bool operator==(const Annotation &other) const
unsigned getFieldID() const
Get the field id this attribute targets.
AttrClass getMember(StringAttr name) const
Return a member of the annotation.
void setMember(StringAttr name, Attribute value)
Add or set a member of the annotation to a value.
Annotation(Annotation anno, uint64_t fieldID)
void removeMember(StringAttr name)
Remove a member of the annotation.
bool operator!=(const Annotation &other) const
AttrClass getMember(StringRef name) const
StringRef getClass() const
Return the 'class' that this annotation is representing.
StringAttr getClassAttr() const
Return the 'class' that this annotation is representing.
llvm::ArrayRef< NamedAttribute >::iterator iterator
LLVM_DUMP_METHOD void dump()
bool isClass(Args... names) const
Return true if this annotation matches any of the specified class names.
StringRef getAnnotationAttrName()
Return the name of the attribute used for annotations on FIRRTL ops.
StringRef getPortAnnotationAttrName()
Return the name of the attribute used for port annotations on FIRRTL ops.
ArrayAttr getAnnotationsIfPresent(Operation *op)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
llvm::hash_code hash_value(const T &e)
An annotation target is used to keep track of something that is targeted by an Annotation.
FIRRTLType getType() const
Get the type of the target.
bool operator!=(const AnnoTarget &other) const
Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const
Get a reference to this target suitable for use in an NLA.
detail::AnnoTargetImpl getImpl() const
detail::AnnoTargetImpl impl
FModuleLike getModule() const
Get the parent module of the target.
AnnotationSet getAnnotations() const
Get the annotations associated with the target.
void setAnnotations(AnnotationSet annotations) const
Set the annotations associated with the target.
bool operator==(const AnnoTarget &other) const
AnnoTarget(detail::AnnoTargetImpl impl=nullptr)
Helper struct to perform variadic class equality check.
bool compare(StringRef name) const
bool compare(StringAttr name) const
bool operator()(T name, Rest... rest) const
Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const
void setAnnotations(AnnotationSet annotations) const
static bool classof(const AnnoTarget &annoTarget)
AnnotationSet getAnnotations() const
AnnoTarget(detail::AnnoTargetImpl impl=nullptr)
static bool classof(const AnnoTarget &annoTarget)
void setPortNo(unsigned portNo)
AnnotationSet getAnnotations() const
void setAnnotations(AnnotationSet annotations) const
Attribute getNLAReference(hw::InnerSymbolNamespace &moduleNamespace) const
PortAnnoTarget(FModuleLike op, unsigned portNo)
AnnoTarget(detail::AnnoTargetImpl impl=nullptr)
bool operator!=(const AnnoTargetImpl &other) const
bool operator==(const AnnoTargetImpl &other) const
AnnoTargetImpl(Operation *op, unsigned portNo)
static bool isEqual(AnnoTarget lhs, AnnoTarget rhs)
circt::firrtl::detail::AnnoTargetImpl AnnoTargetImpl
static bool isEqual(Annotation lhs, Annotation rhs)