Loading [MathJax]/extensions/tex2jax.js
CIRCT 22.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
support.py
Go to the documentation of this file.
1# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2# See https://llvm.org/LICENSE.txt for license information.
3# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5from . import ir
6
7from ._mlir_libs._circt._support import _walk_with_filter
8from .ir import Operation
9from contextlib import AbstractContextManager
10from contextvars import ContextVar
11from typing import List
12
13_current_backedge_builder = ContextVar("current_bb")
14
15
17 pass
18
19
21
22 def __init__(self, module: str, port_names: List[str]):
23 super().__init__(
24 f"Ports {port_names} unconnected in design module {module}.")
25
26
27def get_value(obj) -> ir.Value:
28 """Resolve a Value from a few supported types."""
29
30 if isinstance(obj, ir.Value):
31 return obj
32 if hasattr(obj, "result"):
33 return obj.result
34 if hasattr(obj, "value"):
35 return obj.value
36 return None
37
38
39def connect(destination, source):
40 """A convenient way to use BackedgeBuilder."""
41 if not isinstance(destination, OpOperand):
42 raise TypeError(
43 f"cannot connect to destination of type {type(destination)}. "
44 "Must be OpOperand.")
45 value = get_value(source)
46 if value is None:
47 raise TypeError(f"cannot connect from source of type {type(source)}")
48
49 index = destination.index
50 destination.operation.operands[index] = value
51 if destination.backedge_owner and \
52 index in destination.backedge_owner.backedges:
53 destination.backedge_owner.backedges[index].erase()
54 del destination.backedge_owner.backedges[index]
55
56
57def var_to_attribute(obj, none_on_fail: bool = False) -> ir.Attribute:
58 """Create an MLIR attribute from a Python object for a few common cases."""
59 if isinstance(obj, ir.Attribute):
60 return obj
61 if isinstance(obj, bool):
62 return ir.BoolAttr.get(obj)
63 if isinstance(obj, int):
64 attrTy = ir.IntegerType.get_signless(64)
65 return ir.IntegerAttr.get(attrTy, obj)
66 if isinstance(obj, str):
67 return ir.StringAttr.get(obj)
68 if isinstance(obj, list):
69 arr = [var_to_attribute(x, none_on_fail) for x in obj]
70 if all(arr):
71 return ir.ArrayAttr.get(arr)
72 return None
73 if none_on_fail:
74 return None
75 raise TypeError(f"Cannot convert type '{type(obj)}' to MLIR attribute")
76
77
78# There is currently no support in MLIR for querying type types. The
79# conversation regarding how to achieve this is ongoing and I expect it to be a
80# long one. This is a way that works for now.
81def type_to_pytype(t) -> ir.Type:
82
83 if not isinstance(t, ir.Type):
84 raise TypeError("type_to_pytype only accepts MLIR Type objects")
85
86 # If it's not the root type, assume it's already been downcasted and don't do
87 # the expensive probing below.
88 if t.__class__ != ir.Type:
89 return t
90
91 from .dialects import esi, hw, seq, rtg, rtgtest
92 if ir.IntegerType.isinstance(t):
93 return ir.IntegerType(t)
94 if ir.NoneType.isinstance(t):
95 return ir.NoneType(t)
96 if ir.TupleType.isinstance(t):
97 return ir.TupleType(t)
98 if hw.ArrayType.isinstance(t):
99 return hw.ArrayType(t)
100 if hw.StructType.isinstance(t):
101 return hw.StructType(t)
102 if hw.TypeAliasType.isinstance(t):
103 return hw.TypeAliasType(t)
104 if hw.InOutType.isinstance(t):
105 return hw.InOutType(t)
106 if seq.ClockType.isinstance(t):
107 return seq.ClockType(t)
108 if esi.ChannelType.isinstance(t):
109 return esi.ChannelType(t)
110 if esi.AnyType.isinstance(t):
111 return esi.AnyType(t)
112 if esi.BundleType.isinstance(t):
113 return esi.BundleType(t)
114 if rtg.LabelType.isinstance(t):
115 return rtg.LabelType(t)
116 if rtg.SetType.isinstance(t):
117 return rtg.SetType(t)
118 if rtg.BagType.isinstance(t):
119 return rtg.BagType(t)
120 if rtg.SequenceType.isinstance(t):
121 return rtg.SequenceType(t)
122 if rtg.RandomizedSequenceType.isinstance(t):
123 return rtg.RandomizedSequenceType(t)
124 if rtg.DictType.isinstance(t):
125 return rtg.DictType(t)
126 if rtg.ImmediateType.isinstance(t):
127 return rtg.ImmediateType(t)
128 if rtg.ArrayType.isinstance(t):
129 return rtg.ArrayType(t)
130 if rtg.MemoryType.isinstance(t):
131 return rtg.MemoryType(t)
132 if rtg.MemoryBlockType.isinstance(t):
133 return rtg.MemoryBlockType(t)
134 if rtg.TupleType.isinstance(t):
135 return rtg.TupleType(t)
136 if rtgtest.IntegerRegisterType.isinstance(t):
137 return rtgtest.IntegerRegisterType(t)
138 if rtgtest.CPUType.isinstance(t):
139 return rtgtest.CPUType(t)
140
141 raise TypeError(f"Cannot convert {repr(t)} to python type")
142
143
144# There is currently no support in MLIR for querying attribute types. The
145# conversation regarding how to achieve this is ongoing and I expect it to be a
146# long one. This is a way that works for now.
147def attribute_to_var(attr):
148
149 if attr is None:
150 return None
151 if not isinstance(attr, ir.Attribute):
152 raise TypeError("attribute_to_var only accepts MLIR Attributes")
153
154 # If it's not the root type, assume it's already been downcasted and don't do
155 # the expensive probing below.
156 if attr.__class__ != ir.Attribute and hasattr(attr, "value"):
157 return attr.value
158
159 from .dialects import hw, om
160 if ir.BoolAttr.isinstance(attr):
161 return ir.BoolAttr(attr).value
162 if ir.IntegerAttr.isinstance(attr):
163 return ir.IntegerAttr(attr).value
164 if hw.InnerSymAttr.isinstance(attr):
165 return ir.StringAttr(hw.InnerSymAttr(attr).symName).value
166 if ir.StringAttr.isinstance(attr):
167 return ir.StringAttr(attr).value
168 if ir.FlatSymbolRefAttr.isinstance(attr):
169 return ir.FlatSymbolRefAttr(attr).value
170 if ir.TypeAttr.isinstance(attr):
171 return ir.TypeAttr(attr).value
172 if ir.ArrayAttr.isinstance(attr):
173 arr = ir.ArrayAttr(attr)
174 return [attribute_to_var(x) for x in arr]
175 if ir.DictAttr.isinstance(attr):
176 dict = ir.DictAttr(attr)
177 return {i.name: attribute_to_var(i.attr) for i in dict}
178 if om.ReferenceAttr.isinstance(attr):
179 return attribute_to_var(om.ReferenceAttr(attr).inner_ref)
180 if hw.InnerRefAttr.isinstance(attr):
181 ref = hw.InnerRefAttr(attr)
182 return (ir.StringAttr(ref.module).value, ir.StringAttr(ref.name).value)
183 if om.ListAttr.isinstance(attr):
184 return list(map(attribute_to_var, om.ListAttr(attr)))
185 if om.OMIntegerAttr.isinstance(attr):
186 return int(str(om.OMIntegerAttr(attr)))
187 if om.PathAttr.isinstance(attr):
188 return om.PathAttr(attr).value
189
190 raise TypeError(f"Cannot convert {repr(attr)} to python value")
191
192
193def get_self_or_inner(mlir_type):
194 from .dialects import hw
195 if type(mlir_type) is ir.Type:
196 mlir_type = type_to_pytype(mlir_type)
197 if isinstance(mlir_type, hw.TypeAliasType):
198 return type_to_pytype(mlir_type.inner_type)
199 return mlir_type
200
201
202class BackedgeBuilder(AbstractContextManager):
203
204 class Edge:
205
206 def __init__(self,
207 creator,
208 type: ir.Type,
209 backedge_name: str,
210 op_view,
211 instance_of: ir.Operation,
212 loc: ir.Location = None):
213 self.creator: BackedgeBuilder = creator
214 self.dummy_op = ir.Operation.create("builtin.unrealized_conversion_cast",
215 [type],
216 loc=loc)
217 self.instance_of = instance_of
218 self.op_view = op_view
219 self.port_name = backedge_name
220 self.loc = loc
221 self.erased = False
222
223 @property
224 def result(self):
225 return self.dummy_op.result
226
227 def erase(self):
228 if self.erased:
229 return
230 if self in self.creator.edges:
231 self.creator.edges.remove(self)
232 self.dummy_op.operation.erase()
233
234 def __init__(self, circuit_name: str = ""):
235 self.circuit_name = circuit_name
236 self.edges = set()
237
238 @staticmethod
239 def current():
240 bb = _current_backedge_builder.get(None)
241 if bb is None:
242 raise RuntimeError("No backedge builder found in context!")
243 return bb
244
245 @staticmethod
246 def create(*args, **kwargs):
247 return BackedgeBuilder.current()._create(*args, **kwargs)
248
249 def _create(self,
250 type: ir.Type,
251 port_name: str,
252 op_view,
253 instance_of: ir.Operation = None,
254 loc: ir.Location = None):
255 edge = BackedgeBuilder.Edge(self, type, port_name, op_view, instance_of,
256 loc)
257 self.edges.add(edge)
258 return edge
259
260 def __enter__(self):
261 self.old_bb_token = _current_backedge_builder.set(self)
262
263 def __exit__(self, exc_type, exc_value, traceback):
264 if exc_value is not None:
265 return
266 _current_backedge_builder.reset(self.old_bb_token)
267 errors = []
268 for edge in list(self.edges):
269 # TODO: Make this use `UnconnectedSignalError`.
270 msg = "Backedge: " + edge.port_name + "\n"
271 if edge.instance_of is not None:
272 msg += "InstanceOf: " + str(edge.instance_of).split(" {")[0] + "\n"
273 if edge.op_view is not None:
274 op = edge.op_view.operation
275 msg += "Instance: " + str(op)
276 if edge.loc is not None:
277 msg += "Location: " + str(edge.loc)
278 errors.append(msg)
279
280 if errors:
281 errors.insert(
282 0, f"Uninitialized backedges remain in module '{self.circuit_name}'")
283 raise RuntimeError("\n".join(errors))
284
285
287 __slots__ = ["index", "operation", "value", "backedge_owner"]
288
289 def __init__(self,
290 operation: ir.Operation,
291 index: int,
292 value,
293 backedge_owner=None):
294 if not isinstance(index, int):
295 raise TypeError("Index must be int")
296 self.index = index
297
298 if not hasattr(operation, "operands"):
299 raise TypeError("Operation must be have 'operands' attribute")
300 self.operation = operation
301
302 self.value = value
303 self.backedge_owner = backedge_owner
304
305 @property
306 def type(self):
307 return self.value.type
308
309
311 """Helper class to incrementally construct an instance of an operation that
312 names its operands and results"""
313
314 def __init__(self,
315 cls,
316 data_type=None,
317 input_port_mapping=None,
318 pre_args=None,
319 post_args=None,
320 needs_result_type=False,
321 **kwargs):
322 # Set defaults
323 if input_port_mapping is None:
324 input_port_mapping = {}
325 if pre_args is None:
326 pre_args = []
327 if post_args is None:
328 post_args = []
329
330 # Set result_indices to name each result.
331 result_names = self.result_names()
332 result_indices = {}
333 for i in range(len(result_names)):
334 result_indices[result_names[i]] = i
335
336 # Set operand_indices to name each operand. Give them an initial value,
337 # either from input_port_mapping or a default value.
338 backedges = {}
339 operand_indices = {}
340 operand_values = []
341 operand_names = self.operand_names()
342 for i in range(len(operand_names)):
343 arg_name = operand_names[i]
344 operand_indices[arg_name] = i
345 if arg_name in input_port_mapping:
346 value = get_value(input_port_mapping[arg_name])
347 operand = value
348 else:
349 backedge = self.create_default_value(i, data_type, arg_name)
350 backedges[i] = backedge
351 operand = backedge.result
352 operand_values.append(operand)
353
354 # Some ops take a list of operand values rather than splatting them out.
355 if isinstance(data_type, list):
356 operand_values = [operand_values]
357
358 # In many cases, result types are inferred, and we do not need to pass
359 # data_type to the underlying constructor. It must be provided to
360 # NamedValueOpView in cases where we need to build backedges, but should
361 # generally not be passed to the underlying constructor in this case. There
362 # are some oddball ops that must pass it, even when building backedges, and
363 # these set needs_result_type=True.
364 if data_type is not None and (needs_result_type or len(backedges) == 0):
365 pre_args.insert(0, data_type)
366
367 self.opview = cls(*pre_args, *operand_values, *post_args, **kwargs)
368 self.operand_indices = operand_indices
369 self.result_indices = result_indices
370 self.backedges = backedges
371
372 def __getattr__(self, name):
373 # Check for the attribute in the arg name set.
374 if "operand_indices" in dir(self) and name in self.operand_indices:
375 index = self.operand_indices[name]
376 value = self.opview.operands[index]
377 return OpOperand(self.opview.operation, index, value, self)
378
379 # Check for the attribute in the result name set.
380 if "result_indices" in dir(self) and name in self.result_indices:
381 index = self.result_indices[name]
382 value = self.opview.results[index]
383 return OpOperand(self.opview.operation, index, value, self)
384
385 # Forward "attributes" attribute from the operation.
386 if name == "attributes":
387 return self.opview.operation.attributes
388
389 # If we fell through to here, the name isn't a result.
390 raise AttributeError(f"unknown port name {name}")
391
392 def create_default_value(self, index, data_type, arg_name):
393 return BackedgeBuilder.create(data_type, arg_name, self)
394
395 @property
396 def operation(self):
397 """Get the operation associated with this builder."""
398 return self.opview.operation
399
400
401# Helper function to walk operation with a filter on operation names.
402# `op_views` is a list of operation views to visit. This is a wrapper
403# around the C++ implementation of walk_with_filter.
404def walk_with_filter(operation: Operation, op_views: List[ir.OpView], callback,
405 walk_order):
406 op_names_identifiers = [name.OPERATION_NAME for name in op_views]
407 return _walk_with_filter(operation, op_names_identifiers, callback,
408 walk_order)
__init__(self, creator, ir.Type type, str backedge_name, op_view, ir.Operation instance_of, ir.Location loc=None)
Definition support.py:212
__init__(self, str circuit_name="")
Definition support.py:234
create(*args, **kwargs)
Definition support.py:246
_create(self, ir.Type type, str port_name, op_view, ir.Operation instance_of=None, ir.Location loc=None)
Definition support.py:254
__exit__(self, exc_type, exc_value, traceback)
Definition support.py:263
__init__(self, cls, data_type=None, input_port_mapping=None, pre_args=None, post_args=None, needs_result_type=False, **kwargs)
Definition support.py:321
create_default_value(self, index, data_type, arg_name)
Definition support.py:392
__init__(self, ir.Operation operation, int index, value, backedge_owner=None)
Definition support.py:293
__init__(self, str module, List[str] port_names)
Definition support.py:22
The "any" type is a special type which can be used to represent any type, as identified by the type i...
Definition Types.h:92
Bundles represent a collection of channels.
Definition Types.h:44
Channels are the basic communication primitives.
Definition Types.h:70
get_self_or_inner(mlir_type)
Definition support.py:193
walk_with_filter(Operation operation, List[ir.OpView] op_views, callback, walk_order)
Definition support.py:405
ir.Type type_to_pytype(t)
Definition support.py:81
connect(destination, source)
Definition support.py:39