pliron 0.15.0

Programming Languages Intermediate RepresentatiON
Documentation
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! A utility for inserting [Operation]s from a specified insertion point.
//! Similar in spirit to LLVM's IRBuilder, but does not build operations.

use crate::{
    basic_block::BasicBlock,
    common_traits::Named,
    context::{Context, Ptr},
    identifier::Identifier,
    irbuild::listener::InsertionListener,
    op::Op,
    operation::Operation,
    printable::{self, Printable},
    region::Region,
    r#type::TypeObj,
};

/// Insertion point specification for inserting [Operation]s using [IRInserter].
#[derive(Debug, Clone, Copy, Default)]
pub enum OpInsertionPoint {
    #[default]
    Unset,
    AtBlockStart(Ptr<BasicBlock>),
    AtBlockEnd(Ptr<BasicBlock>),
    AfterOperation(Ptr<Operation>),
    BeforeOperation(Ptr<Operation>),
}

/// Insertion point specification for insertion [BasicBlock]s using [IRInserter].
#[derive(Debug, Clone, Copy, Default)]
pub enum BlockInsertionPoint {
    #[default]
    Unset,
    AtRegionStart(Ptr<Region>),
    AtRegionEnd(Ptr<Region>),
    AfterBlock(Ptr<BasicBlock>),
    BeforeBlock(Ptr<BasicBlock>),
}

impl Printable for OpInsertionPoint {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &printable::State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            OpInsertionPoint::Unset => write!(f, "Op Insertion Point not set"),
            OpInsertionPoint::AtBlockStart(block) => {
                write!(
                    f,
                    "At start of BasicBlock {}",
                    block.deref(ctx).unique_name(ctx)
                )
            }
            OpInsertionPoint::AtBlockEnd(block) => {
                write!(
                    f,
                    "At end of BasicBlock {}",
                    block.deref(ctx).unique_name(ctx)
                )
            }
            OpInsertionPoint::AfterOperation(op) => {
                write!(f, "After Operation {}", op.disp(ctx))
            }
            OpInsertionPoint::BeforeOperation(op) => {
                write!(f, "Before Operation {}", op.disp(ctx))
            }
        }
    }
}

impl Printable for BlockInsertionPoint {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &printable::State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            BlockInsertionPoint::Unset => write!(f, "Block Insertion Point not set"),
            BlockInsertionPoint::AtRegionStart(region) => {
                write!(
                    f,
                    "At start of Region {}",
                    region.deref(ctx).find_index_in_parent(ctx)
                )
            }
            BlockInsertionPoint::AtRegionEnd(region) => {
                write!(
                    f,
                    "At end of Region {}",
                    region.deref(ctx).find_index_in_parent(ctx)
                )
            }
            BlockInsertionPoint::AfterBlock(block) => {
                write!(f, "After BasicBlock {}", block.deref(ctx).unique_name(ctx))
            }
            BlockInsertionPoint::BeforeBlock(block) => {
                write!(f, "Before BasicBlock {}", block.deref(ctx).unique_name(ctx))
            }
        }
    }
}

impl OpInsertionPoint {
    /// Get the insertion block if set.
    pub fn get_insertion_block(&self, ctx: &Context) -> Option<Ptr<BasicBlock>> {
        match self {
            OpInsertionPoint::AtBlockStart(block) => Some(*block),
            OpInsertionPoint::AtBlockEnd(block) => Some(*block),
            OpInsertionPoint::AfterOperation(op) => op.deref(ctx).get_parent_block(),
            OpInsertionPoint::BeforeOperation(op) => op.deref(ctx).get_parent_block(),
            OpInsertionPoint::Unset => None,
        }
    }

    /// Is the insertion point set?
    pub fn is_set(&self) -> bool {
        !matches!(self, OpInsertionPoint::Unset)
    }
}

impl BlockInsertionPoint {
    /// Get the insertion region if set.
    pub fn get_insertion_region(&self, ctx: &Context) -> Option<Ptr<Region>> {
        match self {
            BlockInsertionPoint::AtRegionStart(region) => Some(*region),
            BlockInsertionPoint::AtRegionEnd(region) => Some(*region),
            BlockInsertionPoint::AfterBlock(block) => block.deref(ctx).get_parent_region(),
            BlockInsertionPoint::BeforeBlock(block) => block.deref(ctx).get_parent_region(),
            BlockInsertionPoint::Unset => None,
        }
    }

    /// Is the insertion point set?
    pub fn is_set(&self) -> bool {
        !matches!(self, BlockInsertionPoint::Unset)
    }
}

/// An interface for insertion of IR entities.
/// Use [DummyListener](super::listener::DummyListener) if no listener is needed.
pub trait Inserter<L: InsertionListener> {
    /// Appends an [Operation] at the current insertion point.
    /// The insertion point is updated to be after this newly inserted [Operation].
    fn append_operation(&mut self, ctx: &Context, operation: Ptr<Operation>);

    /// Appends an [Op] at the current insertion point.
    /// The insertion point is updated to be after this newly inserted [Op].
    fn append_op(&mut self, ctx: &Context, op: impl Op);

    /// Inserts an [Operation] at the current insertion point.
    /// To insert a sequence in-order, use [append_operation](Self::append_operation).
    fn insert_operation(&mut self, ctx: &Context, operation: Ptr<Operation>);

    /// Inserts an [Op] at the current insertion point.
    /// To insert a sequence in-order, use [append_op](Self::append_op).
    fn insert_op(&mut self, ctx: &Context, op: impl Op);

    /// Insert [BasicBlock] at the provided insertion point.
    fn insert_block(
        &mut self,
        ctx: &Context,
        insertion_point: BlockInsertionPoint,
        block: Ptr<BasicBlock>,
    );

    /// Create a new [BasicBlock] and insert it at the provided insertion point.
    /// The internal [OpInsertionPoint] is updated to be at the end of the newly created block.
    fn create_block(
        &mut self,
        ctx: &mut Context,
        insertion_point: BlockInsertionPoint,
        label: Option<Identifier>,
        arg_types: Vec<Ptr<TypeObj>>,
    ) -> Ptr<BasicBlock>;

    /// Gets the current insertion point.
    fn get_insertion_point(&self) -> OpInsertionPoint;

    /// Is insertion point set?
    fn is_insertion_point_set(&self) -> bool {
        self.get_insertion_point().is_set()
    }

    /// Get the [BasicBlock], if known, in which the next [Op] insertion will occur.
    fn get_insertion_block(&self, ctx: &Context) -> Option<Ptr<BasicBlock>> {
        self.get_insertion_point().get_insertion_block(ctx)
    }

    /// Set the insertion point.
    fn set_insertion_point(&mut self, point: OpInsertionPoint);

    /// Sets the insertion point to the start of the given block.
    fn set_insertion_point_to_block_start(&mut self, block: Ptr<BasicBlock>) {
        self.set_insertion_point(OpInsertionPoint::AtBlockStart(block));
    }

    /// Sets the insertion point to the end of the given block.
    fn set_insertion_point_to_block_end(&mut self, block: Ptr<BasicBlock>) {
        self.set_insertion_point(OpInsertionPoint::AtBlockEnd(block));
    }

    /// Sets the insertion point to after the given operation.
    fn set_insertion_point_after_operation(&mut self, op: Ptr<Operation>) {
        self.set_insertion_point(OpInsertionPoint::AfterOperation(op));
    }

    /// Sets the insertion point to before the given operation.
    fn set_insertion_point_before_operation(&mut self, op: Ptr<Operation>) {
        self.set_insertion_point(OpInsertionPoint::BeforeOperation(op));
    }

    /// Sets the listener for insertion events.
    fn set_listener(&mut self, listener: L);

    /// Gets a reference to the listener for insertion events.
    fn get_listener(&self) -> &L;

    /// Gets a mutable reference to the listener for insertion events.
    fn get_listener_mut(&mut self) -> &mut L;
}

/// A utility for inserting [Operation]s from a specified insertion point.
/// Use [DummyListener](super::listener::DummyListener) if no listener is needed.
pub struct IRInserter<L: InsertionListener> {
    op_insertion_point: OpInsertionPoint,
    listener: L,
}

impl<L: InsertionListener> Default for IRInserter<L> {
    fn default() -> Self {
        Self {
            op_insertion_point: OpInsertionPoint::default(),
            listener: L::default(),
        }
    }
}

impl<L: InsertionListener> IRInserter<L> {
    /// Creates a new [Inserter] with insert point set to the provided argument.
    pub fn new(insertion_point: OpInsertionPoint) -> Self {
        Self {
            op_insertion_point: insertion_point,
            listener: L::default(),
        }
    }

    /// Creates a new [Inserter] that inserts the next operation
    /// at the start of the given [BasicBlock].
    pub fn new_at_block_start(block: Ptr<BasicBlock>) -> Self {
        Self {
            op_insertion_point: OpInsertionPoint::AtBlockStart(block),
            listener: L::default(),
        }
    }

    /// Creates a new [Inserter] that inserts the next operation
    /// at the end of the given [BasicBlock].
    pub fn new_at_block_end(block: Ptr<BasicBlock>) -> Self {
        Self {
            op_insertion_point: OpInsertionPoint::AtBlockEnd(block),
            listener: L::default(),
        }
    }

    /// Creates a new [Inserter] that inserts the next operation
    /// after the given [Operation].
    pub fn new_after_operation(op: Ptr<Operation>) -> Self {
        Self {
            op_insertion_point: OpInsertionPoint::AfterOperation(op),
            listener: L::default(),
        }
    }

    /// Creates a new [Inserter] that inserts the next operation
    /// before the given [Operation].
    pub fn new_before_operation(op: Ptr<Operation>) -> Self {
        Self {
            op_insertion_point: OpInsertionPoint::BeforeOperation(op),
            listener: L::default(),
        }
    }

    /// Creates a new [Inserter] that inserts the next operation
    /// just before the terminator of the given [BasicBlock].
    pub fn new_before_block_terminator(block: Ptr<BasicBlock>, ctx: &Context) -> Self {
        let terminator_op = block
            .deref(ctx)
            .get_terminator(ctx)
            .expect("BasicBlock must have a terminator operation");
        Self::new_before_operation(terminator_op)
    }
}

impl<L: InsertionListener> Inserter<L> for IRInserter<L> {
    fn append_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        // Insert the operation at the current insertion point
        self.insert_operation(ctx, operation);
        // Update the insertion point to be after the newly inserted operation
        self.op_insertion_point = OpInsertionPoint::AfterOperation(operation);
    }

    fn append_op(&mut self, ctx: &Context, op: impl Op) {
        let operation = op.get_operation();
        self.append_operation(ctx, operation);
    }

    fn insert_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        assert!(
            !operation.is_linked(ctx),
            "Cannot insert an already linked operation"
        );
        match self.op_insertion_point {
            OpInsertionPoint::AtBlockStart(block) => {
                // Insert operation at the start of the block
                operation.insert_at_front(block, ctx);
            }
            OpInsertionPoint::AtBlockEnd(block) => {
                // Insert operation at the end of the block
                operation.insert_at_back(block, ctx);
            }
            OpInsertionPoint::AfterOperation(op) => {
                // Insert operation after the specified operation
                operation.insert_after(ctx, op);
            }
            OpInsertionPoint::BeforeOperation(op) => {
                // Insert operation before the specified operation
                operation.insert_before(ctx, op);
            }
            OpInsertionPoint::Unset => {
                panic!("Insertion point is not set");
            }
        }
        // Notify the listener if present
        self.listener.notify_operation_inserted(ctx, operation);
    }

    fn insert_op(&mut self, ctx: &Context, op: impl Op) {
        let operation = op.get_operation();
        self.insert_operation(ctx, operation);
    }

    fn insert_block(
        &mut self,
        ctx: &Context,
        insertion_point: BlockInsertionPoint,
        block: Ptr<BasicBlock>,
    ) {
        match insertion_point {
            BlockInsertionPoint::AtRegionStart(region) => {
                block.insert_at_front(region, ctx);
            }
            BlockInsertionPoint::AtRegionEnd(region) => {
                block.insert_at_back(region, ctx);
            }
            BlockInsertionPoint::AfterBlock(prev_block) => {
                block.insert_after(ctx, prev_block);
            }
            BlockInsertionPoint::BeforeBlock(next_block) => {
                block.insert_before(ctx, next_block);
            }
            BlockInsertionPoint::Unset => {
                panic!("Block insertion point is not set");
            }
        }
        // Notify the listener if present
        self.listener.notify_block_inserted(ctx, block);
    }

    fn create_block(
        &mut self,
        ctx: &mut Context,
        insertion_point: BlockInsertionPoint,
        label: Option<Identifier>,
        arg_types: Vec<Ptr<TypeObj>>,
    ) -> Ptr<BasicBlock> {
        let block = BasicBlock::new(ctx, label, arg_types);
        self.insert_block(ctx, insertion_point, block);
        self.op_insertion_point = OpInsertionPoint::AtBlockEnd(block);
        block
    }

    fn get_insertion_point(&self) -> OpInsertionPoint {
        self.op_insertion_point
    }

    fn set_insertion_point(&mut self, point: OpInsertionPoint) {
        self.op_insertion_point = point;
    }

    /// Sets the listener for insertion events.
    fn set_listener(&mut self, listener: L) {
        self.listener = listener;
    }

    /// Gets a reference to the listener for insertion events.
    fn get_listener(&self) -> &L {
        &self.listener
    }

    /// Gets a mutable reference to the listener for insertion events.
    fn get_listener_mut(&mut self) -> &mut L {
        &mut self.listener
    }
}

/// A scoped inserter that sets the insertion point for the duration of its lifetime.
/// On drop, it restores the previous insertion point.
/// Implements [Inserter] by forwarding calls to the wrapped inserter.
/// ```rust
/// # use pliron::{context::Context,
/// #   builtin::{ops::ModuleOp, op_interfaces::SingleBlockRegionInterface}};
/// # use pliron::irbuild::{listener::DummyListener,
/// #   inserter::{Inserter, IRInserter, ScopedInserter, OpInsertionPoint}};
/// let ctx = &mut Context::new();
/// let module = ModuleOp::new(ctx, "test_module".try_into().unwrap());
/// let mut inserter = IRInserter::<DummyListener>::default();
/// inserter.set_insertion_point(OpInsertionPoint::AtBlockEnd(module.get_body(ctx, 0)));
/// {
///     // We can create a scoped inserter with a different insertion point,
///     // and it will restore the original insertion point after this block.
///     let mut scoped_inserter = ScopedInserter::new(&mut inserter, OpInsertionPoint::Unset);
///     assert!(!scoped_inserter.get_insertion_point().is_set());
/// }
/// assert!(inserter.get_insertion_point().is_set());
/// ```
pub struct ScopedInserter<'a, L: InsertionListener, I: Inserter<L>> {
    inserter: &'a mut I,
    prev_insertion_point: OpInsertionPoint,
    _phantom: std::marker::PhantomData<L>,
}

impl<'a, L: InsertionListener, I: Inserter<L>> ScopedInserter<'a, L, I> {
    pub fn new(inserter: &'a mut I, insertion_point: OpInsertionPoint) -> Self {
        let prev_insertion_point = inserter.get_insertion_point();
        inserter.set_insertion_point(insertion_point);
        Self {
            inserter,
            prev_insertion_point,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<'a, L: InsertionListener, I: Inserter<L>> Drop for ScopedInserter<'a, L, I> {
    fn drop(&mut self) {
        self.inserter.set_insertion_point(self.prev_insertion_point);
    }
}

impl<'a, L: InsertionListener, I: Inserter<L>> Inserter<L> for ScopedInserter<'a, L, I> {
    fn append_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.inserter.append_operation(ctx, operation);
    }

    fn append_op(&mut self, ctx: &Context, op: impl Op) {
        self.inserter.append_op(ctx, op);
    }

    fn insert_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.inserter.insert_operation(ctx, operation);
    }

    fn insert_op(&mut self, ctx: &Context, op: impl Op) {
        self.inserter.insert_op(ctx, op);
    }

    fn insert_block(
        &mut self,
        ctx: &Context,
        insertion_point: BlockInsertionPoint,
        block: Ptr<BasicBlock>,
    ) {
        self.inserter.insert_block(ctx, insertion_point, block);
    }

    fn create_block(
        &mut self,
        ctx: &mut Context,
        insertion_point: BlockInsertionPoint,
        label: Option<Identifier>,
        arg_types: Vec<Ptr<TypeObj>>,
    ) -> Ptr<BasicBlock> {
        self.inserter
            .create_block(ctx, insertion_point, label, arg_types)
    }

    fn get_insertion_point(&self) -> OpInsertionPoint {
        self.inserter.get_insertion_point()
    }

    fn set_insertion_point(&mut self, point: OpInsertionPoint) {
        self.inserter.set_insertion_point(point);
    }

    fn set_listener(&mut self, listener: L) {
        self.inserter.set_listener(listener);
    }

    fn get_listener(&self) -> &L {
        self.inserter.get_listener()
    }

    fn get_listener_mut(&mut self) -> &mut L {
        self.inserter.get_listener_mut()
    }
}