cubecl-opt 0.10.0

Compiler optimizations for CubeCL
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
use std::{fmt::Display, rc::Rc};

use petgraph::visit::EdgeRef;

use crate::{
    BasicBlock, ControlFlow,
    analyses::{
        liveness::{
            Liveness,
            shared::{SharedLiveness, SmemAllocation},
        },
        uniformity::Uniformity,
    },
    gvn::{BlockSets, Expression, GlobalValues, Instruction, Local, Value, ValueTable},
};

use super::Optimizer;

const DEBUG_GVN: bool = false;

/// Debug display for the program state.
impl Display for Optimizer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let global_nums = self
            .analysis_cache
            .try_get::<GlobalValues>()
            .unwrap_or_default();
        let liveness = self
            .analysis_cache
            .try_get::<Liveness>()
            .unwrap_or_else(|| Rc::new(Liveness::empty(self)));
        let shared_liveness = self
            .analysis_cache
            .try_get::<SharedLiveness>()
            .unwrap_or_else(|| Rc::new(SharedLiveness::empty(self)));
        let uniformity = self
            .analysis_cache
            .try_get::<Uniformity>()
            .unwrap_or_default();

        if DEBUG_GVN {
            writeln!(f, "# Value Table:")?;
            writeln!(f, "{}", global_nums.borrow().values)?;
        }

        let smems = shared_liveness
            .allocations
            .values()
            .map(|it| format!("    {it}"));
        let smems = smems.collect::<Vec<_>>().join(",\n");
        writeln!(f, "Shared memories: [\n{smems}\n]\n")?;

        for node in self.program.node_indices() {
            let id = node.index();
            let bb = &self.program[node];
            let uniform = match uniformity.is_block_uniform(node) {
                true => "uniform ",
                false => "",
            };
            writeln!(f, "{uniform}bb{id} {{")?;
            if DEBUG_GVN {
                let block_sets = &global_nums
                    .borrow()
                    .block_sets
                    .get(&node)
                    .cloned()
                    .unwrap_or_default();
                writeln!(f, "{block_sets}")?;
            }

            if !bb.block_use.is_empty() {
                writeln!(f, "    Uses: {:?}", bb.block_use)?;
            }
            let live_vars = liveness.at_block(node).iter();
            let live_vars = live_vars.map(|it| format!("local({it})"));
            let live_vars = live_vars.collect::<Vec<_>>();
            writeln!(f, "    Live variables: [{}]\n", live_vars.join(", "))?;
            let live_shared = shared_liveness.at_block(node).iter();
            let live_shared = live_shared.map(|it| format!("shared({it})"));
            let live_shared = live_shared.collect::<Vec<_>>();
            writeln!(
                f,
                "    Live shared memories: [{}]\n",
                live_shared.join(", ")
            )?;

            for phi in bb.phi_nodes.borrow().iter() {
                write!(f, "    {} = phi ", phi.out)?;
                for entry in &phi.entries {
                    write!(f, "[bb{}: ", entry.block.index())?;
                    write!(f, "{}]", entry.value)?;
                }
                let is_uniform = match uniformity.is_var_uniform(phi.out) {
                    true => " @ uniform",
                    false => "",
                };
                writeln!(f, ";{is_uniform}\n")?;
            }
            if !bb.phi_nodes.borrow().is_empty() {
                writeln!(f)?;
            }

            for op in bb.ops.borrow_mut().values_mut() {
                let op_fmt = op.to_string();
                if op_fmt.is_empty() {
                    continue;
                }

                let is_uniform = match op.out.is_some_and(|out| uniformity.is_var_uniform(out)) {
                    true => " @ uniform",
                    false => "",
                };
                writeln!(f, "    {op_fmt};{is_uniform}")?;
            }
            match &*bb.control_flow.borrow() {
                ControlFlow::IfElse {
                    cond,
                    then,
                    or_else,
                    merge,
                } => {
                    writeln!(
                        f,
                        "    {cond} ? bb{} : bb{}; merge: {}",
                        then.index(),
                        or_else.index(),
                        merge
                            .as_ref()
                            .map(|it| format!("bb{}", it.index()))
                            .unwrap_or("None".to_string())
                    )?;
                }
                super::ControlFlow::Switch {
                    value,
                    default,
                    branches,
                    ..
                } => {
                    write!(f, "    switch({value}) ")?;
                    for (val, block) in branches {
                        write!(f, "[{val}: bb{}] ", block.index())?;
                    }
                    writeln!(f, "[default: bb{}];", default.index())?;
                }
                super::ControlFlow::Loop {
                    body,
                    continue_target,
                    merge,
                } => {
                    writeln!(
                        f,
                        "    loop(continue: bb{}, merge: bb{})",
                        continue_target.index(),
                        merge.index()
                    )?;
                    writeln!(f, "    branch bb{};", body.index())?
                }
                super::ControlFlow::LoopBreak {
                    break_cond,
                    body,
                    continue_target,
                    merge,
                } => {
                    writeln!(
                        f,
                        "    loop(cond: {}, body: bb{} continue: bb{}, break: bb{})",
                        break_cond,
                        body.index(),
                        continue_target.index(),
                        merge.index()
                    )?;
                }
                super::ControlFlow::Return => writeln!(f, "    return;")?,
                super::ControlFlow::Unreachable => writeln!(f, "    unreachable;")?,
                super::ControlFlow::None => {
                    let edge = self.program.edges(node).next();
                    let target = edge.map(|it| it.target().index()).unwrap_or(255);
                    writeln!(f, "    branch bb{target};")?;
                }
            }
            f.write_str("}\n\n")?;
        }

        Ok(())
    }
}

impl Display for BlockSets {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut exp_gen = self.exp_gen.iter().collect::<Vec<_>>();
        exp_gen.sort_by_key(|it| it.0);
        let exp_gen = exp_gen
            .into_iter()
            .map(|(val, expr)| format!("{val}: {expr}"))
            .collect::<Vec<_>>();
        let mut phi_gen = self.phi_gen.iter().collect::<Vec<_>>();
        phi_gen.sort_by_key(|it| it.0);
        let phi_gen = phi_gen
            .into_iter()
            .map(|(val, expr)| format!("{val}: {expr}"))
            .collect::<Vec<_>>();
        let tmp_gen = self
            .tmp_gen
            .iter()
            .map(|it| format!("{it}"))
            .collect::<Vec<_>>();
        let mut leaders = self.leaders.iter().collect::<Vec<_>>();
        leaders.sort_by_key(|it| it.0);
        let leaders = leaders
            .into_iter()
            .map(|(val, expr)| format!("{val}: {expr}"))
            .collect::<Vec<_>>();
        let mut antic_out = self.antic_out.iter().collect::<Vec<_>>();
        antic_out.sort_by_key(|it| it.0);
        let antic_out = antic_out
            .into_iter()
            .map(|(val, expr)| format!("{val}: {expr}"))
            .collect::<Vec<_>>();
        let mut antic_in = self.antic_in.iter().collect::<Vec<_>>();
        antic_in.sort_by_key(|it| it.0);
        let antic_in = antic_in
            .into_iter()
            .map(|(val, expr)| format!("{val}: {expr}"))
            .collect::<Vec<_>>();

        writeln!(f, "    exp_gen: [{}]", exp_gen.join(", "))?;
        writeln!(f, "    phi_gen: [{}]", phi_gen.join(", "))?;
        writeln!(f, "    tmp_gen: [{}]", tmp_gen.join(", "))?;
        writeln!(f, "    leaders: [{}]", leaders.join(", "))?;
        writeln!(f, "    antic_in: [{}]", antic_in.join(", "))?;
        writeln!(f, "    antic_out: [{}]", antic_out.join(", "))
    }
}

impl Display for ValueTable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut values = self.value_numbers.iter().collect::<Vec<_>>();
        values.sort_by_key(|it| it.1);
        writeln!(f, "values: [")?;
        for (val, num) in values {
            writeln!(f, "    {num}: {val},")?;
        }
        writeln!(f, "]")?;
        writeln!(f, "expressions: [")?;
        let mut expressions = self.expression_numbers.iter().collect::<Vec<_>>();
        expressions.sort_by_key(|it| it.1);
        for (expr, val) in expressions {
            writeln!(f, "    {val}: {expr},")?;
        }
        writeln!(f, "]")
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Constant(constant, _) => write!(f, "{constant}"),
            Value::Local(local) => write!(f, "{local}"),
            Value::Input(id, _) => write!(f, "input({id})"),
            Value::Scalar(id, elem) => write!(f, "scalar({elem}, {id})"),
            Value::ConstArray(id, _, _, _) => write!(f, "const_array({id})"),
            Value::Builtin(builtin, _) => write!(f, "{builtin:?}"),
            Value::Output(id, _) => write!(f, "output({id})"),
        }
    }
}

impl Display for Local {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.version {
            0 => write!(f, "binding({})", self.id),
            v => write!(f, "local({}).v{v}", self.id),
        }
    }
}

impl Display for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Expression::Instruction(instruction) => write!(f, "{instruction}"),
            Expression::Copy(val, _) => write!(f, "copy({val})"),
            Expression::Value(value) => write!(f, "{value}"),
            Expression::Volatile(value) => write!(f, "volatile({value})"),
            Expression::Phi(entries) => write!(
                f,
                "phi({})",
                entries
                    .iter()
                    .map(|(val, b)| format!("{val}: bb{}", b.index()))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }
}

impl Display for Instruction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}: [{:?}]", self.op, self.args)
    }
}

impl Display for BasicBlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for phi in self.phi_nodes.borrow().iter() {
            write!(f, "    {} = phi ", phi.out)?;
            for entry in &phi.entries {
                write!(f, "[bb{}: ", entry.block.index())?;
                write!(f, "{}]", entry.value)?;
            }
            writeln!(f, ";\n")?;
        }
        if !self.phi_nodes.borrow().is_empty() {
            writeln!(f)?;
        }

        for op in self.ops.borrow_mut().values_mut() {
            let op_fmt = op.to_string();
            if op_fmt.is_empty() {
                continue;
            }

            writeln!(f, "    {op_fmt};")?;
        }
        match &*self.control_flow.borrow() {
            ControlFlow::IfElse {
                cond,
                then,
                or_else,
                merge,
            } => {
                writeln!(
                    f,
                    "    {cond} ? bb{} : bb{}; merge: {}",
                    then.index(),
                    or_else.index(),
                    merge
                        .as_ref()
                        .map(|it| format!("bb{}", it.index()))
                        .unwrap_or("None".to_string())
                )?;
            }
            super::ControlFlow::Switch {
                value,
                default,
                branches,
                ..
            } => {
                write!(f, "    switch({value}) ")?;
                for (val, block) in branches {
                    write!(f, "[{val}: bb{}] ", block.index())?;
                }
                writeln!(f, "[default: bb{}];", default.index())?;
            }
            super::ControlFlow::Loop {
                body,
                continue_target,
                merge,
            } => {
                writeln!(
                    f,
                    "    loop(continue: bb{}, merge: bb{})",
                    continue_target.index(),
                    merge.index()
                )?;
                writeln!(f, "    branch bb{};", body.index())?
            }
            super::ControlFlow::LoopBreak {
                break_cond,
                body,
                continue_target,
                merge,
            } => {
                writeln!(
                    f,
                    "    loop(cond: {}, body: bb{} continue: bb{}, break: bb{})",
                    break_cond,
                    body.index(),
                    continue_target.index(),
                    merge.index()
                )?;
            }
            super::ControlFlow::Return => writeln!(f, "    return;")?,
            super::ControlFlow::Unreachable => writeln!(f, "    unreachable;")?,
            super::ControlFlow::None => {
                writeln!(f, "    branch;")?;
            }
        }
        Ok(())
    }
}

impl Display for SmemAllocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.smem {
            crate::SharedMemory::Array {
                id,
                length,
                ty,
                align,
            } => {
                write!(
                    f,
                    "shared_array(id: {id}, offset: {}, length: {length}, align: {align}, ty: {ty})",
                    self.offset,
                )
            }
            crate::SharedMemory::Value { id, ty, align } => {
                write!(
                    f,
                    "shared(id: {id}, offset: {}, align: {align}, ty: {ty})",
                    self.offset,
                )
            }
        }
    }
}