rtlola-streamir 0.1.0

A framework for the compilation of stream-based languages through an 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
//! A framework for optimizing the StreamIR through rewriting rules
//! Applies the rewriting rules alternating until no rule does any changes anymore.

use std::{
    collections::{HashMap, HashSet, VecDeque},
    ops::{Add, AddAssign},
};

use thiserror::Error;

use crate::ir::{
    memory::{Memory, StreamBuffer, StreamMemory},
    Guard, IfStmt, LivetimeEquivalences, Stmt, StreamIr, StreamReference,
};
mod common_guards_outside;
pub use common_guards_outside::MoveCommonGuardsOutside;
mod remove_close;
pub use remove_close::RemoveClose;
mod remove_spawn;
pub use remove_spawn::RemoveSpawn;
mod assign;
pub use assign::IterateAssign;
mod combine_if;
pub use combine_if::CombineIf;
mod combine_iterate;
pub use combine_iterate::CombineIterate;
mod combine_seq;
pub use combine_seq::CombineSeq;
mod fast_guards;
pub use fast_guards::FastGuards;
mod if_outside;
pub use if_outside::MoveIfOutside;
mod implied_guards;
pub use implied_guards::ImpliedGuards;
mod memory_optimizations;
pub use memory_optimizations::MemoryOptimizations;
mod nested_ifs;
pub use nested_ifs::CombineNestedIf;
mod partial_evaluation;
pub use partial_evaluation::EvaluateGuards;
mod remove_ifs;
pub use remove_ifs::RemoveIfs;
mod remove_shift;
pub use remove_shift::RemoveShift;
mod simplify_guard;
pub use simplify_guard::SimplifyGuard;
mod skip;
pub use skip::RemoveSkip;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// A global change that can be a side effect from a rewriting rule
enum GlobalChangeInstruction {
    /// A change to memory
    #[allow(dead_code)]
    ReplaceMemory(StreamReference, Memory),
}

impl GlobalChangeInstruction {
    fn apply(self, ir: &mut StreamIr) {
        match self {
            GlobalChangeInstruction::ReplaceMemory(sr, memory) => {
                *ir.sr2memory.get_mut(&sr).unwrap() = memory
            }
        }
    }
}

type GlobalChangeSet = HashSet<GlobalChangeInstruction>;

#[derive(Debug, Clone, Default)]
/// The result from applying a rewriting rule.
///
/// Does indicate whether the rewriting rule changed something and holds the global changes
pub struct ChangeSet {
    local_change: bool,
    global_instructions: GlobalChangeSet,
}

impl ChangeSet {
    fn local_change() -> ChangeSet {
        ChangeSet {
            local_change: true,
            global_instructions: HashSet::new(),
        }
    }
}

impl Add<ChangeSet> for ChangeSet {
    type Output = ChangeSet;

    fn add(self, rhs: ChangeSet) -> Self::Output {
        let global_instructions = self
            .global_instructions
            .union(&rhs.global_instructions)
            .cloned()
            .collect();
        Self {
            local_change: self.local_change || rhs.local_change,
            global_instructions,
        }
    }
}

impl AddAssign for ChangeSet {
    #[allow(clippy::suspicious_op_assign_impl)]
    fn add_assign(&mut self, rhs: Self) {
        let ChangeSet {
            local_change,
            global_instructions,
        } = rhs;
        self.global_instructions.extend(global_instructions);
        self.local_change |= local_change;
    }
}

#[derive(Error, Debug)]
/// An error that can occour during rewriting
pub enum RewriteError {
    #[error("other error: {0}")]
    /// An error that does not fit any of the other categories
    Other(String),
}

/// A trait representing a rewriting rule
/// Desribes rewriting to different parts of the StreamIR.
pub trait RewriteRule: std::fmt::Debug {
    /// Rewrite a statement.
    /// Is called recursively for all children automatically.
    fn rewrite_stmt(
        &self,
        stmt: Stmt,
        _memory: &HashMap<StreamReference, Memory>,
        _liveness_equivalences: &LivetimeEquivalences,
    ) -> Result<(Stmt, ChangeSet), RewriteError> {
        Ok((stmt, ChangeSet::default()))
    }

    /// Rewrite a guard.
    /// Is called recursively for all children automatically.
    fn rewrite_guard(
        &self,
        guard: Guard,
        _memory: &HashMap<StreamReference, Memory>,
        _liveness_equivalences: &LivetimeEquivalences,
    ) -> Result<(Guard, ChangeSet), RewriteError> {
        Ok((guard, ChangeSet::default()))
    }

    /// Rewrites the memory of a stream.
    fn rewrite_memory(
        &self,
        _sr: StreamReference,
        memory: StreamMemory,
    ) -> Result<(StreamMemory, ChangeSet), RewriteError> {
        Ok((memory, ChangeSet::default()))
    }

    /// Rewrites the buffer of the memory of a stream.
    fn rewrite_buffer(
        &self,
        _sr: StreamReference,
        memory: StreamBuffer,
    ) -> Result<(StreamBuffer, ChangeSet), RewriteError> {
        Ok((memory, ChangeSet::default()))
    }

    /// Rewrites the top level statement.
    /// Is NOT called automatically for all children.
    fn apply_stmt(
        &self,
        mut stmt: Stmt,
        memory: &HashMap<StreamReference, Memory>,
        livetime_equivalences: &LivetimeEquivalences,
    ) -> Result<(Stmt, ChangeSet), RewriteError> {
        let mut cs = ChangeSet::default();
        stmt = match stmt {
            old @ (Stmt::Skip
            | Stmt::Input(_)
            | Stmt::Shift(_)
            | Stmt::Spawn { .. }
            | Stmt::Eval { .. }
            | Stmt::Close { .. }) => old,
            Stmt::Seq(stmts) => {
                let inner = stmts
                    .into_iter()
                    .map(|stmt| {
                        let (stmt, c) = self.apply_stmt(stmt, memory, livetime_equivalences)?;
                        cs += c;
                        Ok(stmt)
                    })
                    .collect::<Result<_, _>>()?;
                Stmt::Seq(inner)
            }
            Stmt::Parallel(stmts) => {
                let inner = stmts
                    .into_iter()
                    .map(|stmt| {
                        let (stmt, c) = self.apply_stmt(stmt, memory, livetime_equivalences)?;
                        cs += c;
                        Ok(stmt)
                    })
                    .collect::<Result<_, _>>()?;
                Stmt::Parallel(inner)
            }
            Stmt::If(IfStmt { guard, cons, alt }) => {
                let (guard, guard_cs) = self.apply_guard(guard, memory, livetime_equivalences)?;
                let (cons, cons_cs) = self.apply_stmt(*cons, memory, livetime_equivalences)?;
                let (alt, alt_cs) = self.apply_stmt(*alt, memory, livetime_equivalences)?;
                cs += guard_cs + cons_cs + alt_cs;
                Stmt::If(IfStmt {
                    guard,
                    cons: Box::new(cons),
                    alt: Box::new(alt),
                })
            }
            Stmt::Iterate { sr, stmt } => {
                let (stmt, c) = self.apply_stmt(*stmt, memory, livetime_equivalences)?;
                cs += c;
                Stmt::Iterate {
                    sr,
                    stmt: Box::new(stmt),
                }
            }
            Stmt::Assign {
                parameter_expr,
                sr,
                stmt,
            } => {
                let (stmt, c) = self.apply_stmt(*stmt, memory, livetime_equivalences)?;
                cs += c;
                Stmt::Assign {
                    parameter_expr,
                    sr,
                    stmt: Box::new(stmt),
                }
            }
        };
        let (new_stmt, cur_cs) = self.rewrite_stmt(stmt, memory, livetime_equivalences)?;
        stmt = new_stmt;
        cs += cur_cs;
        Ok((stmt, cs))
    }

    /// Rewrites the top level guard.
    /// Is NOT called automatically for all children.
    fn apply_guard(
        &self,
        guard: Guard,
        memory: &HashMap<StreamReference, Memory>,
        livetime_equivalences: &LivetimeEquivalences,
    ) -> Result<(Guard, ChangeSet), RewriteError> {
        let mut cs = ChangeSet::default();
        let mut guard = match guard {
            Guard::And { lhs, rhs } => {
                let (lhs, cs1) = self.apply_guard(*lhs, memory, livetime_equivalences)?;
                let (rhs, cs2) = self.apply_guard(*rhs, memory, livetime_equivalences)?;
                cs += cs1 + cs2;
                Guard::And {
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                }
            }
            Guard::Or { lhs, rhs } => {
                let (lhs, cs1) = self.apply_guard(*lhs, memory, livetime_equivalences)?;
                let (rhs, cs2) = self.apply_guard(*rhs, memory, livetime_equivalences)?;
                cs += cs1 + cs2;
                Guard::Or {
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                }
            }
            other => other,
        };

        let (new_guard, cur_cs) = self.rewrite_guard(guard, memory, livetime_equivalences)?;
        guard = new_guard;
        cs += cur_cs;

        Ok((guard, cs))
    }

    /// Rewrites the whole memory.
    fn apply_memory(
        &self,
        memory: HashMap<StreamReference, Memory>,
        _livetime_equivalences: &LivetimeEquivalences,
    ) -> Result<(HashMap<StreamReference, Memory>, ChangeSet), RewriteError> {
        let mut cs = ChangeSet::default();
        let new_memory = memory
            .into_iter()
            .map(|(sr, Memory { buffer, ty, name })| {
                let (new_buffer, cur_cs) = self.rewrite_memory(sr, buffer)?;
                let new_buffer = match new_buffer {
                    StreamMemory::NoMemory => StreamMemory::NoMemory,
                    StreamMemory::Static(buffer) => {
                        let (new_buffer, cur_cs) = self.rewrite_buffer(sr, buffer)?;
                        cs += cur_cs;
                        StreamMemory::Static(new_buffer)
                    }
                    StreamMemory::Dynamic {
                        buffer,
                        has_spawn,
                        has_close,
                    } => {
                        let (new_buffer, cur_cs) = self.rewrite_buffer(sr, buffer)?;
                        cs += cur_cs;
                        StreamMemory::Dynamic {
                            buffer: new_buffer,
                            has_spawn,
                            has_close,
                        }
                    }
                    StreamMemory::Instances { buffer, parameter } => {
                        let (new_buffer, cur_cs) = self.rewrite_buffer(sr, buffer)?;
                        cs += cur_cs;
                        StreamMemory::Instances {
                            buffer: new_buffer,
                            parameter,
                        }
                    }
                };
                cs += cur_cs;
                Ok((
                    sr,
                    Memory {
                        buffer: new_buffer,
                        ty,
                        name,
                    },
                ))
            })
            .collect::<Result<_, _>>()?;
        Ok((new_memory, cs))
    }

    /// A set of rewrite rules that are applied directly after the given rewrite rules
    fn cleanup_rules(&self) -> Vec<Box<dyn RewriteRule>> {
        Vec::new()
    }
}

#[derive(Debug)]
/// A rewriter that holds a set of rewriting rules and can apply them to StreamIR's.
pub struct Rewriter {
    rules: Vec<Box<dyn RewriteRule>>,
}

impl Rewriter {
    /// Construct a new Rewriter with the given rules.
    pub fn new(rules: Vec<Box<dyn RewriteRule>>) -> Self {
        let original_length = rules.len();
        let mut stack = rules
            .into_iter()
            .rev()
            .collect::<VecDeque<Box<dyn RewriteRule>>>();
        let mut rules = Vec::new();
        while let Some(rule) = stack.pop_back() {
            let cleanup = rule.cleanup_rules();
            rules.push(rule);
            stack.extend(cleanup);
            if rules.len() > original_length * 10 {
                panic!("possible infinite loop in rewrite rule expansion")
            }
        }
        Self { rules }
    }

    /// Run the rewriting on the given StreamIR until a fixedpoint is reached.
    pub fn run(&self, mut ir: StreamIr) -> Result<StreamIr, RewriteError> {
        let mut changed = true;
        while changed {
            (ir, changed) = self.apply(ir)?;
        }
        Ok(ir)
    }

    /// Apply all rewriting rules once. Returns the resulting StreamIR and a boolean indicating
    /// whether something changed for any of the rules.
    fn apply(&self, mut ir: StreamIr) -> Result<(StreamIr, bool), RewriteError> {
        let mut changed = false;
        for rule in &self.rules {
            let StreamIr {
                stmt,
                sr2memory,
                wref2window,
                lref2lfreq,
                livetime_equivalences,
                static_schedule,
                triggers,
                accesses,
                accessed_by,
            } = ir;

            let (sr2memory, cs_memory) = rule.apply_memory(sr2memory, &livetime_equivalences)?;
            let (stmt, cs_stmt) = rule.apply_stmt(stmt, &sr2memory, &livetime_equivalences)?;

            ir = StreamIr {
                stmt,
                sr2memory,
                wref2window,
                lref2lfreq,
                livetime_equivalences,
                static_schedule,
                triggers,
                accesses,
                accessed_by,
            };
            let ChangeSet {
                local_change,
                global_instructions,
            } = cs_memory + cs_stmt;
            changed |= local_change || !global_instructions.is_empty();
            for i in global_instructions {
                i.apply(&mut ir);
            }
        }
        Ok((ir, changed))
    }
}