109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200 | def materialize_loop(
rewriter: PatternRewriter, generic_op: memref_stream.GenericOp, index: int
) -> Sequence[Operation]:
"""
Replaces a given generic op with a for loop containing an op with the upper bound at
the specified index set to 1.
"""
if (
generic_op.iterator_types.data[index].data
!= memref_stream.IteratorType.PARALLEL
):
raise DiagnosticException(
"Cannot materialize a loop for a non-parallel iterator"
)
ops: list[Operation] = [
zero_op := arith.ConstantOp(IntegerAttr.from_index_int_value(0)),
one_op := arith.ConstantOp(IntegerAttr.from_index_int_value(1)),
ub_op := arith.ConstantOp(generic_op.bounds.data[index]),
]
zero_val = zero_op.result
zero_val.name_hint = "c0"
one_op.result.name_hint = "c1"
ub_op.result.name_hint = "ub"
for_block = Block((yield_op := scf.YieldOp(),), arg_types=(IndexType(),))
loc = InsertPoint.before(yield_op)
ops.append(scf.ForOp(zero_op, ub_op, one_op, (), Region(for_block)))
index_val = for_block.args[0]
index_val.name_hint = "i"
input_apply_operands: list[SSAValue] = [zero_val] * len(generic_op.iterator_types)
input_apply_operands[index] = index_val
output_apply_operands: list[SSAValue] = [zero_val] * (
len(generic_op.iterator_types)
- sum(
it.data == memref_stream.IteratorType.REDUCTION
for it in generic_op.iterator_types
)
)
output_apply_operands[index] = index_val
input_upper_bounds = list(ub.value.data for ub in generic_op.bounds)
input_upper_bounds[index] = 1
output_upper_bounds = list(
ub.value.data
for (it, ub) in zip(generic_op.iterator_types, generic_op.bounds)
if it.data != memref_stream.IteratorType.REDUCTION
)
output_upper_bounds[index] = 1
num_inputs = len(generic_op.inputs)
new_inputs = tuple(
insert_subview(input_val, m.data, input_apply_operands, input_upper_bounds, loc)
for input_val, m in zip(
generic_op.inputs, generic_op.indexing_maps.data[:num_inputs], strict=True
)
)
new_outputs = tuple(
insert_subview(
output_val, m.data, output_apply_operands, output_upper_bounds, loc
)
for output_val, m in zip(
generic_op.outputs, generic_op.indexing_maps.data[num_inputs:], strict=True
)
)
new_bounds = list(generic_op.bounds)
new_bounds[index] = IntegerAttr.from_index_int_value(1)
new_generic_op = memref_stream.GenericOp(
new_inputs,
new_outputs,
generic_op.inits,
Rewriter.move_region_contents_to_new_regions(generic_op.body),
generic_op.indexing_maps,
generic_op.iterator_types,
ArrayAttr(new_bounds),
generic_op.init_indices,
generic_op.doc,
generic_op.library_call,
)
Rewriter.insert_op(new_generic_op, loc)
rewriter.replace_op(generic_op, ops)
return ops
|