1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use orzir_core::{verify_error, Context, Op, Ty, VerifyResult};
use thiserror::Error;

pub mod control_flow;

#[derive(Debug, Error)]
#[error("operand is not isolated from above")]
struct NotIsolatedFromAboveError;

/// Verifier `IsIsoaltedFromAbove` for `Op`.
///
/// An verifier indicating that the operation will not refer to any SSA values
/// from above regions.
///
/// Note that symbols can be used.
pub trait IsIsolatedFromAbove: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        let mut pending_regions = Vec::new();
        for region in self.regions() {
            pending_regions.push(region);

            while !pending_regions.is_empty() {
                let pending_region = pending_regions.pop().unwrap().deref(&ctx.regions);
                for block in pending_region.layout().iter() {
                    for op in block.deref(&ctx.blocks).layout().iter() {
                        for operand in op.deref(&ctx.ops).as_ref().operands() {
                            let operand_region = operand.deref(&ctx.values).parent_region(ctx);
                            if !region.deref(&ctx.regions).is_ancestor(ctx, operand_region) {
                                // not isolated from above
                                return verify_error!(NotIsolatedFromAboveError).into();
                            }
                        }

                        if !op.deref(&ctx.ops).as_ref().regions().is_empty()
                            && !op.deref(&ctx.ops).impls::<dyn IsIsolatedFromAbove>(ctx)
                        {
                            for sub_region in op.deref(&ctx.ops).as_ref().regions() {
                                pending_regions.push(sub_region);
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of results: expected {0}, got {1}")]
struct InvalidResultNumberError(usize, usize);

/// Verifier `IsIsolatedFromBelow` for `Op`.
///
/// A verifier indicating that the operation has excatly `N` results.
pub trait NumResults<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_results() != N {
            return verify_error!(InvalidResultNumberError(N, self.num_results())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of operands: expected {0}, got {1}")]
struct InvalidOperandNumberError(usize, usize);

/// Verifier `NumOperands` for `Op`.
///
/// A trait indicating that the operation has excatly `N` operands.
pub trait NumOperands<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_operands() != N {
            return verify_error!(InvalidOperandNumberError(N, self.num_operands())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of regions: expected {0}, got {1}")]
struct InvalidRegionNumberError(usize, usize);

/// Verifier `NumRegions` for `Op`.
///
/// A verifier indicating that the operation has excatly `N` regions.
pub trait NumRegions<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_regions() != N {
            return verify_error!(InvalidRegionNumberError(N, self.num_regions())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of successors: expected {0}, got {1}")]
struct InvalidSuccessorNumberError(usize, usize);

/// Verifier `NumSuccessors` for `Op`
///
/// A verifier indicating that the operation has exactly `N` successors.
pub trait NumSuccessors<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_successors() != N {
            return verify_error!(InvalidSuccessorNumberError(N, self.num_successors())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of results: expected at least {0}, got {1}")]
struct InvalidAtLeastResultNumberError(usize, usize);

/// Verifier `AtLeastNumResults` for `Op`.
///
/// A verifier indicating that the operation has at least `N` results.
pub trait AtLeastNumResults<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_results() < N {
            return verify_error!(InvalidAtLeastResultNumberError(N, self.num_results())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of operands: expected at least {0}, got {1}")]
struct InvalidAtLeastOperandNumberError(usize, usize);

/// Verifier `AtLeastNumOperands` for `Op`.
///
/// A verifier indicating that the operation has at least `N` operands.
pub trait AtLeastNumOperands<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_operands() < N {
            return verify_error!(InvalidAtLeastOperandNumberError(N, self.num_operands())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of regions: expected at least {0}, got {1}")]
struct InvalidAtLeastRegionNumberError(usize, usize);

/// Verifier `AtLeastNumRegions` for `Op`.
///
/// A verifier indicating that the operation has at least `N` regions.
pub trait AtLeastNumRegions<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_regions() < N {
            return verify_error!(InvalidAtLeastRegionNumberError(N, self.num_regions())).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid number of successors: expected at least {0}, got {1}")]
struct InvalidAtLeastSuccessorNumberError(usize, usize);

/// Verifier `AtLeastNumSuccessors` for `Op`.
///
/// A verifier indicating that the operation has at least `N` successors.
pub trait AtLeastNumSuccessors<const N: usize>: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_successors() < N {
            return verify_error!(InvalidAtLeastSuccessorNumberError(N, self.num_successors()))
                .into();
        }
        Ok(())
    }
}

/// Verifier `AtMostNumResults` for `Op`.
///
/// This verifier indicates that the operation has variadic operands.
pub trait VariadicOperands: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> { Ok(()) }
}

/// Verifier `VariadicResults` for `Op`.
///
/// This verifier indicates that the operation has variadic results.
pub trait VariadicResults: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> { Ok(()) }
}

/// Verifier `VariadicRegions` for `Op`.
///
/// This verifier indicates that the operation has variadic regions.
pub trait VariadicRegions: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> { Ok(()) }
}

/// Verifier `VariadicSuccessors` for `Op`.
///
/// This verifier indicates that the operation has variadic successors.
pub trait VariadicSuccessors: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> { Ok(()) }
}

/// Verifier `IsTerminator` for `Ty`.
///
/// This verifier indicates that the type is float-like.
pub trait FloatLikeTy: Ty {
    fn verify(&self, _ctx: &Context) -> VerifyResult<()> { Ok(()) }
}

/// Verifier `IsTerminator` for `Ty`.
///
/// This verifier indicates that the type is integer-like.
pub trait IntegerLikeTy: Ty {
    fn verify(&self, _ctx: &Context) -> VerifyResult<()> { Ok(()) }
}

#[derive(Debug, Error)]
#[error("operand is not float-like")]
struct NotFloatLikeError;

/// Verifier `IsTerminator` for `Op`.
///
/// This verifier indicates that the operation has float-like operands.
pub trait FloatLikeOperands: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.operand_tys(ctx) {
            if !ty.deref(&ctx.tys).impls::<dyn FloatLikeTy>(ctx) {
                return verify_error!(NotFloatLikeError).into();
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("operand is not integer-like")]
struct NotIntegerLikeError;

/// Verifier `IsTerminator` for `Op`.
///
/// This verifier indicates that the operation has integer-like operands.
pub trait IntegerLikeOperands: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.operand_tys(ctx) {
            if !ty.deref(&ctx.tys).impls::<dyn IntegerLikeTy>(ctx) {
                return verify_error!(NotIntegerLikeError).into();
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("result is not float-like")]
struct NotFloatLikeResultError;

/// Verifier `IsTerminator` for `Op`.
///
/// This verifier indicates that the operation has float-like results.
pub trait FloatLikeResults: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.result_tys(ctx) {
            if !ty.deref(&ctx.tys).impls::<dyn FloatLikeTy>(ctx) {
                return verify_error!(NotFloatLikeResultError).into();
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("result is not integer-like")]
struct NotIntegerLikeResultError;

/// Verifier `IsTerminator` for `Op`.
///
/// This verifier indicates that the operation has float-like results.
pub trait IntegerLikeResults: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.result_tys(ctx) {
            if !ty.deref(&ctx.tys).impls::<dyn IntegerLikeTy>(ctx) {
                return verify_error!(NotIntegerLikeResultError).into();
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("operands have different types")]
struct DifferentOperandTypesError;

/// Verifier `SameOperandTys` for `Op`
///
/// This verifier indicates that the operands are all the same types.
pub trait SameOperandTys: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        let operand_tys = self.operand_tys(ctx);

        if operand_tys.is_empty() {
            return Ok(());
        }

        let operand_ty = operand_tys[0];

        for ty in operand_tys {
            if ty != operand_ty {
                return verify_error!(DifferentOperandTypesError).into();
            }
        }

        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("results have different types")]
struct DifferentResultTysError;

/// Verifier `SameResultTys` for `Op`
///
/// This verifier indicates that the results are all the same type.
pub trait SameResultTys: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        let result_tys = self.result_tys(ctx);

        if result_tys.is_empty() {
            return Ok(());
        }

        let result_ty = result_tys[0];
        for ty in result_tys {
            if ty != result_ty {
                return verify_error!(DifferentResultTysError).into();
            }
        }

        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("results and operands have different types")]
struct DifferentOperandAndResultTysError;

/// Verifier `SameOperandAndResultTys` for `Op`.
///
/// This verifier indicates that the results and the operands all share the same
/// type. Note that the numbers of results and operands are not necessarily the
/// same.
pub trait SameOperandAndResultTys: SameOperandTys + SameResultTys {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        <Self as SameOperandTys>::verify(self, ctx)?;
        <Self as SameResultTys>::verify(self, ctx)?;

        let operand_tys = self.operand_tys(ctx);
        let result_tys = self.result_tys(ctx);

        if operand_tys.is_empty() {
            return Ok(());
        }

        let operand_ty = operand_tys[0];

        if result_tys.is_empty() {
            return Ok(());
        }

        let result_ty = result_tys[0];

        if operand_ty != result_ty {
            return verify_error!(DifferentOperandAndResultTysError).into();
        }

        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("results and operands have different numbers")]
struct DifferentOperandAndResultNumberError;

/// Verifier `SameOperandsAndResultsNum` for `Op`.
///
/// This verifier indicates that the numbers of results and operands are the
/// same.
pub trait SameOperandsAndResultsNum: Op {
    fn verify(&self, _: &Context) -> VerifyResult<()> {
        if self.num_operands() != self.num_results() {
            return verify_error!(DifferentOperandAndResultNumberError).into();
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid operand type, expected {0}")]
pub struct InvalidOperandTyError(String);

pub trait OperandTysAre<T: Ty>: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.operand_tys(ctx) {
            if !ty.deref(&ctx.tys).is_a::<T>() {
                return verify_error!(InvalidOperandTyError(T::mnemonic_static().to_string()))
                    .into();
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("invalid result type, expected {0}")]
pub struct InvalidResultTyError(String);

pub trait ResultTysAre<T: Ty>: Op {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        for ty in self.result_tys(ctx) {
            if !ty.deref(&ctx.tys).is_a::<T>() {
                return verify_error!(InvalidResultTyError(T::mnemonic_static().to_string()))
                    .into();
            }
        }
        Ok(())
    }
}