CIRCT 21.0.0git
Loading...
Searching...
No Matches
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 try:
93 return ir.IntegerType(t)
94 except ValueError:
95 pass
96 try:
97 return ir.NoneType(t)
98 except ValueError:
99 pass
100 try:
101 return hw.ArrayType(t)
102 except ValueError:
103 pass
104 try:
105 return hw.StructType(t)
106 except ValueError:
107 pass
108 try:
109 return hw.TypeAliasType(t)
110 except ValueError:
111 pass
112 try:
113 return hw.InOutType(t)
114 except ValueError:
115 pass
116 try:
117 return seq.ClockType(t)
118 except ValueError:
119 pass
120 try:
121 return esi.ChannelType(t)
122 except ValueError:
123 pass
124 try:
125 return esi.AnyType(t)
126 except ValueError:
127 pass
128 try:
129 return esi.BundleType(t)
130 except ValueError:
131 pass
132 try:
133 return rtg.LabelType(t)
134 except ValueError:
135 pass
136 try:
137 return rtg.SetType(t)
138 except ValueError:
139 pass
140 try:
141 return rtg.BagType(t)
142 except ValueError:
143 pass
144 try:
145 return rtg.SequenceType(t)
146 except ValueError:
147 pass
148 try:
149 return rtg.RandomizedSequenceType(t)
150 except ValueError:
151 pass
152 try:
153 return rtg.DictType(t)
154 except ValueError:
155 pass
156 try:
157 return rtg.ImmediateType(t)
158 except ValueError:
159 pass
160 try:
161 return rtg.ArrayType(t)
162 except ValueError:
163 pass
164 try:
165 return rtgtest.IntegerRegisterType(t)
166 except ValueError:
167 pass
168
169 raise TypeError(f"Cannot convert {repr(t)} to python type")
170
171
172# There is currently no support in MLIR for querying attribute types. The
173# conversation regarding how to achieve this is ongoing and I expect it to be a
174# long one. This is a way that works for now.
175def attribute_to_var(attr):
176
177 if attr is None:
178 return None
179 if not isinstance(attr, ir.Attribute):
180 raise TypeError("attribute_to_var only accepts MLIR Attributes")
181
182 # If it's not the root type, assume it's already been downcasted and don't do
183 # the expensive probing below.
184 if attr.__class__ != ir.Attribute and hasattr(attr, "value"):
185 return attr.value
186
187 from .dialects import hw, om
188 try:
189 return ir.BoolAttr(attr).value
190 except ValueError:
191 pass
192 try:
193 return ir.IntegerAttr(attr).value
194 except ValueError:
195 pass
196 try:
197 return ir.StringAttr(hw.InnerSymAttr(attr).symName).value
198 except ValueError:
199 pass
200 try:
201 return ir.StringAttr(attr).value
202 except ValueError:
203 pass
204 try:
205 return ir.FlatSymbolRefAttr(attr).value
206 except ValueError:
207 pass
208 try:
209 return ir.TypeAttr(attr).value
210 except ValueError:
211 pass
212 try:
213 arr = ir.ArrayAttr(attr)
214 return [attribute_to_var(x) for x in arr]
215 except ValueError:
216 pass
217 try:
218 dict = ir.DictAttr(attr)
219 return {i.name: attribute_to_var(i.attr) for i in dict}
220 except ValueError:
221 pass
222 try:
223 return attribute_to_var(om.ReferenceAttr(attr).inner_ref)
224 except ValueError:
225 pass
226 try:
227 ref = hw.InnerRefAttr(attr)
228 return (ir.StringAttr(ref.module).value, ir.StringAttr(ref.name).value)
229 except ValueError:
230 pass
231 try:
232 return list(map(attribute_to_var, om.ListAttr(attr)))
233 except ValueError:
234 pass
235 try:
236 return {name: attribute_to_var(value) for name, value in om.MapAttr(attr)}
237 except ValueError:
238 pass
239 try:
240 return int(str(om.OMIntegerAttr(attr)))
241 except ValueError:
242 pass
243 try:
244 return om.PathAttr(attr).value
245 except ValueError:
246 pass
247
248 raise TypeError(f"Cannot convert {repr(attr)} to python value")
249
250
251def get_self_or_inner(mlir_type):
252 from .dialects import hw
253 if type(mlir_type) is ir.Type:
254 mlir_type = type_to_pytype(mlir_type)
255 if isinstance(mlir_type, hw.TypeAliasType):
256 return type_to_pytype(mlir_type.inner_type)
257 return mlir_type
258
259
260class BackedgeBuilder(AbstractContextManager):
261
262 class Edge:
263
264 def __init__(self,
265 creator,
266 type: ir.Type,
267 backedge_name: str,
268 op_view,
269 instance_of: ir.Operation,
270 loc: ir.Location = None):
271 self.creator: BackedgeBuilder = creator
272 self.dummy_op = ir.Operation.create("builtin.unrealized_conversion_cast",
273 [type],
274 loc=loc)
275 self.instance_of = instance_of
276 self.op_view = op_view
277 self.port_name = backedge_name
278 self.loc = loc
279 self.erased = False
280
281 @property
282 def result(self):
283 return self.dummy_op.result
284
285 def erase(self):
286 if self.erased:
287 return
288 if self in self.creator.edges:
289 self.creator.edges.remove(self)
290 self.dummy_op.operation.erase()
291
292 def __init__(self, circuit_name: str = ""):
293 self.circuit_name = circuit_name
294 self.edges = set()
295
296 @staticmethod
297 def current():
298 bb = _current_backedge_builder.get(None)
299 if bb is None:
300 raise RuntimeError("No backedge builder found in context!")
301 return bb
302
303 @staticmethod
304 def create(*args, **kwargs):
305 return BackedgeBuilder.current()._create(*args, **kwargs)
306
307 def _create(self,
308 type: ir.Type,
309 port_name: str,
310 op_view,
311 instance_of: ir.Operation = None,
312 loc: ir.Location = None):
313 edge = BackedgeBuilder.Edge(self, type, port_name, op_view, instance_of,
314 loc)
315 self.edges.add(edge)
316 return edge
317
318 def __enter__(self):
319 self.old_bb_token = _current_backedge_builder.set(self)
320
321 def __exit__(self, exc_type, exc_value, traceback):
322 if exc_value is not None:
323 return
324 _current_backedge_builder.reset(self.old_bb_token)
325 errors = []
326 for edge in list(self.edges):
327 # TODO: Make this use `UnconnectedSignalError`.
328 msg = "Backedge: " + edge.port_name + "\n"
329 if edge.instance_of is not None:
330 msg += "InstanceOf: " + str(edge.instance_of).split(" {")[0] + "\n"
331 if edge.op_view is not None:
332 op = edge.op_view.operation
333 msg += "Instance: " + str(op)
334 if edge.loc is not None:
335 msg += "Location: " + str(edge.loc)
336 errors.append(msg)
337
338 if errors:
339 errors.insert(
340 0, f"Uninitialized backedges remain in module '{self.circuit_name}'")
341 raise RuntimeError("\n".join(errors))
342
343
345 __slots__ = ["index", "operation", "value", "backedge_owner"]
346
347 def __init__(self,
348 operation: ir.Operation,
349 index: int,
350 value,
351 backedge_owner=None):
352 if not isinstance(index, int):
353 raise TypeError("Index must be int")
354 self.index = index
355
356 if not hasattr(operation, "operands"):
357 raise TypeError("Operation must be have 'operands' attribute")
358 self.operation = operation
359
360 self.value = value
361 self.backedge_owner = backedge_owner
362
363 @property
364 def type(self):
365 return self.value.type
366
367
369 """Helper class to incrementally construct an instance of an operation that
370 names its operands and results"""
371
372 def __init__(self,
373 cls,
374 data_type=None,
375 input_port_mapping=None,
376 pre_args=None,
377 post_args=None,
378 needs_result_type=False,
379 **kwargs):
380 # Set defaults
381 if input_port_mapping is None:
382 input_port_mapping = {}
383 if pre_args is None:
384 pre_args = []
385 if post_args is None:
386 post_args = []
387
388 # Set result_indices to name each result.
389 result_names = self.result_names()
390 result_indices = {}
391 for i in range(len(result_names)):
392 result_indices[result_names[i]] = i
393
394 # Set operand_indices to name each operand. Give them an initial value,
395 # either from input_port_mapping or a default value.
396 backedges = {}
397 operand_indices = {}
398 operand_values = []
399 operand_names = self.operand_names()
400 for i in range(len(operand_names)):
401 arg_name = operand_names[i]
402 operand_indices[arg_name] = i
403 if arg_name in input_port_mapping:
404 value = get_value(input_port_mapping[arg_name])
405 operand = value
406 else:
407 backedge = self.create_default_value(i, data_type, arg_name)
408 backedges[i] = backedge
409 operand = backedge.result
410 operand_values.append(operand)
411
412 # Some ops take a list of operand values rather than splatting them out.
413 if isinstance(data_type, list):
414 operand_values = [operand_values]
415
416 # In many cases, result types are inferred, and we do not need to pass
417 # data_type to the underlying constructor. It must be provided to
418 # NamedValueOpView in cases where we need to build backedges, but should
419 # generally not be passed to the underlying constructor in this case. There
420 # are some oddball ops that must pass it, even when building backedges, and
421 # these set needs_result_type=True.
422 if data_type is not None and (needs_result_type or len(backedges) == 0):
423 pre_args.insert(0, data_type)
424
425 self.opview = cls(*pre_args, *operand_values, *post_args, **kwargs)
426 self.operand_indices = operand_indices
427 self.result_indices = result_indices
428 self.backedges = backedges
429
430 def __getattr__(self, name):
431 # Check for the attribute in the arg name set.
432 if "operand_indices" in dir(self) and name in self.operand_indices:
433 index = self.operand_indices[name]
434 value = self.opview.operands[index]
435 return OpOperand(self.opview.operation, index, value, self)
436
437 # Check for the attribute in the result name set.
438 if "result_indices" in dir(self) and name in self.result_indices:
439 index = self.result_indices[name]
440 value = self.opview.results[index]
441 return OpOperand(self.opview.operation, index, value, self)
442
443 # Forward "attributes" attribute from the operation.
444 if name == "attributes":
445 return self.opview.operation.attributes
446
447 # If we fell through to here, the name isn't a result.
448 raise AttributeError(f"unknown port name {name}")
449
450 def create_default_value(self, index, data_type, arg_name):
451 return BackedgeBuilder.create(data_type, arg_name, self)
452
453 @property
454 def operation(self):
455 """Get the operation associated with this builder."""
456 return self.opview.operation
457
458
459# Helper function to walk operation with a filter on operation names.
460# `op_views` is a list of operation views to visit. This is a wrapper
461# around the C++ implementation of walk_with_filter.
462def walk_with_filter(operation: Operation, op_views: List[ir.OpView], callback,
463 walk_order):
464 op_names_identifiers = [name.OPERATION_NAME for name in op_views]
465 return _walk_with_filter(operation, op_names_identifiers, callback,
466 walk_order)
__init__(self, creator, ir.Type type, str backedge_name, op_view, ir.Operation instance_of, ir.Location loc=None)
Definition support.py:270
__init__(self, str circuit_name="")
Definition support.py:292
create(*args, **kwargs)
Definition support.py:304
_create(self, ir.Type type, str port_name, op_view, ir.Operation instance_of=None, ir.Location loc=None)
Definition support.py:312
__exit__(self, exc_type, exc_value, traceback)
Definition support.py:321
__init__(self, cls, data_type=None, input_port_mapping=None, pre_args=None, post_args=None, needs_result_type=False, **kwargs)
Definition support.py:379
create_default_value(self, index, data_type, arg_name)
Definition support.py:450
__init__(self, ir.Operation operation, int index, value, backedge_owner=None)
Definition support.py:351
__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:251
walk_with_filter(Operation operation, List[ir.OpView] op_views, callback, walk_order)
Definition support.py:463
ir.Type type_to_pytype(t)
Definition support.py:81
connect(destination, source)
Definition support.py:39