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
use log::debug;
use std::collections::HashSet;
use std::fmt;

use crate::constants::UsefulConstants;
use crate::file_definition::FileID;
use crate::ir::declarations::{Declaration, Declarations};
use crate::ir::degree_meta::{DegreeEnvironment, Degree};
use crate::ir::value_meta::ValueEnvironment;
use crate::ir::variable_meta::VariableMeta;
use crate::ir::{VariableName, VariableType};
use crate::ssa::dominator_tree::DominatorTree;
use crate::ssa::errors::SSAResult;
use crate::ssa::{insert_phi_statements, insert_ssa_variables};

use super::basic_block::BasicBlock;
use super::parameters::Parameters;
use super::ssa_impl;
use super::ssa_impl::{Config, Environment};

/// Basic block index type.
pub type Index = usize;

#[derive(Clone)]
pub enum DefinitionType {
    Function,
    Template,
    CustomTemplate,
}

impl fmt::Display for DefinitionType {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            DefinitionType::Function => write!(f, "function"),
            DefinitionType::Template => write!(f, "template"),
            DefinitionType::CustomTemplate => write!(f, "custom template"),
        }
    }
}

pub struct Cfg {
    name: String,
    constants: UsefulConstants,
    parameters: Parameters,
    declarations: Declarations,
    basic_blocks: Vec<BasicBlock>,
    definition_type: DefinitionType,
    dominator_tree: DominatorTree<BasicBlock>,
}

impl Cfg {
    pub(crate) fn new(
        name: String,
        constants: UsefulConstants,
        definition_type: DefinitionType,
        parameters: Parameters,
        declarations: Declarations,
        basic_blocks: Vec<BasicBlock>,
        dominator_tree: DominatorTree<BasicBlock>,
    ) -> Cfg {
        Cfg {
            name,
            constants,
            parameters,
            declarations,
            basic_blocks,
            definition_type,
            dominator_tree,
        }
    }
    /// Returns the entry (first) block of the CFG.
    #[must_use]
    pub fn entry_block(&self) -> &BasicBlock {
        &self.basic_blocks[Index::default()]
    }

    #[must_use]
    pub fn get_basic_block(&self, index: Index) -> Option<&BasicBlock> {
        self.basic_blocks.get(index)
    }

    /// Returns the number of basic blocks in the CFG.
    #[must_use]
    pub fn len(&self) -> usize {
        self.basic_blocks.len()
    }

    /// Returns true if the CFG is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.basic_blocks.is_empty()
    }

    /// Convert the CFG into SSA form.
    pub fn into_ssa(mut self) -> SSAResult<Cfg> {
        debug!("converting `{}` CFG to SSA", self.name());

        // 1. Insert phi statements and convert variables to SSA.
        let mut env = Environment::new(self.parameters(), self.declarations());
        insert_phi_statements::<Config>(&mut self.basic_blocks, &self.dominator_tree, &mut env);
        insert_ssa_variables::<Config>(&mut self.basic_blocks, &self.dominator_tree, &mut env)?;

        // 2. Update parameters to SSA form.
        for name in self.parameters.iter_mut() {
            *name = name.with_version(0);
        }

        // 3. Update declarations to track SSA variables.
        self.declarations =
            ssa_impl::update_declarations(&mut self.basic_blocks, &self.parameters, &env);

        // 4. Propagate metadata to all child nodes. Since determining variable
        // use requires that variable types are available, type propagation must
        // run before caching variable use.
        self.propagate_types();
        self.propagate_values();
        self.propagate_degrees();
        self.cache_variable_use();

        // 5. Print trace output of CFG.
        for basic_block in self.basic_blocks.iter() {
            debug!(
                "basic block {}: (predecessors: {:?}, successors: {:?})",
                basic_block.index(),
                basic_block.predecessors(),
                basic_block.successors(),
            );
            for stmt in basic_block.iter() {
                debug!("    {stmt:?}")
            }
        }
        Ok(self)
    }

    /// Get the name of the corresponding function or template.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the file ID for the corresponding function or template.
    #[must_use]
    pub fn file_id(&self) -> &Option<FileID> {
        self.parameters.file_id()
    }

    #[must_use]
    pub fn definition_type(&self) -> &DefinitionType {
        &self.definition_type
    }

    #[must_use]
    pub fn constants(&self) -> &UsefulConstants {
        &self.constants
    }

    /// Returns the parameter data for the corresponding function or template.
    #[must_use]
    pub fn parameters(&self) -> &Parameters {
        &self.parameters
    }

    /// Returns the variable declaration for the CFG.
    #[must_use]
    pub fn declarations(&self) -> &Declarations {
        &self.declarations
    }

    /// Returns an iterator over the set of variables defined by the CFG.
    pub fn variables(&self) -> impl Iterator<Item = &VariableName> {
        self.declarations.iter().map(|(name, _)| name)
    }

    /// Returns the declaration of the given variable.
    #[must_use]
    pub fn get_declaration(&self, name: &VariableName) -> Option<&Declaration> {
        self.declarations.get_declaration(name)
    }

    /// Returns the type of the given variable.
    #[must_use]
    pub fn get_type(&self, name: &VariableName) -> Option<&VariableType> {
        self.declarations.get_type(name)
    }

    /// Returns an iterator over the basic blocks in the CFG. This iterator
    /// guarantees that if `i` dominates `j`, then `i` comes before `j`.
    pub fn iter(&self) -> impl Iterator<Item = &BasicBlock> {
        self.basic_blocks.iter()
    }

    /// Returns a mutable iterator over the basic blocks in the CFG.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut BasicBlock> {
        self.basic_blocks.iter_mut()
    }

    /// Returns the dominators of the given basic block. The basic block `i`
    /// dominates `j` if any path from the entry point to `j` must contain `i`.
    /// (Note that this relation is reflexive, so `i` always dominates itself.)
    #[must_use]
    pub fn get_dominators(&self, basic_block: &BasicBlock) -> Vec<&BasicBlock> {
        self.dominator_tree
            .get_dominators(basic_block.index())
            .iter()
            .map(|&i| &self.basic_blocks[i])
            .collect()
    }

    /// Returns the immediate dominator of the basic block (that is, the
    /// predecessor of the node in the CFG dominator tree), if it exists.
    #[must_use]
    pub fn get_immediate_dominator(&self, basic_block: &BasicBlock) -> Option<&BasicBlock> {
        self.dominator_tree
            .get_immediate_dominator(basic_block.index())
            .map(|i| &self.basic_blocks[i])
    }

    /// Get immediate successors of the basic block in the CFG dominator tree.
    /// (For a definition of the dominator relation, see `CFG::get_dominators`.)
    #[must_use]
    pub fn get_dominator_successors(&self, basic_block: &BasicBlock) -> Vec<&BasicBlock> {
        self.dominator_tree
            .get_dominator_successors(basic_block.index())
            .iter()
            .map(|&i| &self.basic_blocks[i])
            .collect()
    }

    /// Returns the dominance frontier of the basic block. The _dominance
    /// frontier_ of `i` is defined as all basic blocks `j` such that `i`
    /// dominates an immediate predecessor of `j`, but i does not strictly
    /// dominate `j`. (`j` is where `i`s dominance ends.)
    #[must_use]
    pub fn get_dominance_frontier(&self, basic_block: &BasicBlock) -> Vec<&BasicBlock> {
        self.dominator_tree
            .get_dominance_frontier(basic_block.index())
            .iter()
            .map(|&i| &self.basic_blocks[i])
            .collect()
    }

    /// Returns the predecessors of the given basic block.
    pub fn get_predecessors(&self, basic_block: &BasicBlock) -> Vec<&BasicBlock> {
        let mut predecessors = HashSet::new();
        let mut update = HashSet::from([basic_block.index()]);
        while !update.is_subset(&predecessors) {
            predecessors.extend(update.iter().cloned());
            update = update
                .iter()
                .flat_map(|index| {
                    self.get_basic_block(*index)
                        .expect("in control-flow graph")
                        .predecessors()
                        .iter()
                        .cloned()
                })
                .collect();
        }
        // Remove the initial block.
        predecessors.remove(&basic_block.index());
        predecessors
            .iter()
            .map(|index| self.get_basic_block(*index).expect("in control-flow graph"))
            .collect::<Vec<_>>()
    }

    /// Returns the successors of the given basic block.
    pub fn get_successors(&self, basic_block: &BasicBlock) -> Vec<&BasicBlock> {
        let mut successors = HashSet::new();
        let mut update = HashSet::from([basic_block.index()]);
        while !update.is_subset(&successors) {
            successors.extend(update.iter().cloned());
            update = update
                .iter()
                .flat_map(|index| {
                    self.get_basic_block(*index)
                        .expect("in control-flow graph")
                        .successors()
                        .iter()
                        .cloned()
                })
                .collect();
        }
        // Remove the initial block.
        successors.remove(&basic_block.index());
        successors
            .iter()
            .map(|index| self.get_basic_block(*index).expect("in control-flow graph"))
            .collect::<Vec<_>>()
    }

    /// Returns all block in the interval [start_block, end_block). That is, all
    /// successors of the starting block (including the starting block) which
    /// are also predecessors of the end block.
    pub fn get_interval(
        &self,
        start_block: &BasicBlock,
        end_block: &BasicBlock,
    ) -> Vec<&BasicBlock> {
        // Compute the successors of the start block (including the start block).
        let mut successors = HashSet::new();
        let mut update = HashSet::from([start_block.index()]);
        while !update.is_subset(&successors) {
            successors.extend(update.iter().cloned());
            update = update
                .iter()
                .flat_map(|index| {
                    self.get_basic_block(*index)
                        .expect("in control-flow graph")
                        .successors()
                        .iter()
                        .cloned()
                })
                .collect();
        }

        // Compute the strict predecessors of the end block.
        let mut predecessors = HashSet::new();
        let mut update = HashSet::from([end_block.index()]);
        while !update.is_subset(&predecessors) {
            predecessors.extend(update.iter().cloned());
            update = update
                .iter()
                .flat_map(|index| {
                    self.get_basic_block(*index)
                        .expect("in control-flow graph")
                        .predecessors()
                        .iter()
                        .cloned()
                })
                .collect();
        }
        predecessors.remove(&end_block.index());

        // Return the basic blocks corresponding to the intersection of the two
        // sets.
        successors
            .intersection(&predecessors)
            .map(|index| self.get_basic_block(*index).expect("in control-flow graph"))
            .collect::<Vec<_>>()
    }

    /// Returns the basic blocks corresponding to the true branch of the
    /// if-statement at the end of the given header block.
    ///
    /// # Panics
    ///
    /// This method panics if the given block does not end with an if-statement node.
    pub fn get_true_branch(&self, header_block: &BasicBlock) -> Vec<&BasicBlock> {
        use crate::ir::Statement::*;
        if let Some(IfThenElse { true_index, .. }) = header_block.statements().last() {
            let start_block = self.get_basic_block(*true_index).expect("in control-flow graph");
            let end_blocks = self.get_dominance_frontier(start_block);

            if end_blocks.is_empty() {
                // True and false branches do not join up.
                let mut result = self.get_successors(start_block);
                result.push(start_block);
                result
            } else {
                // True and false branches join up at the dominance frontier.
                let mut result = Vec::new();
                for end_block in end_blocks {
                    result.extend(self.get_interval(start_block, end_block))
                }
                result
            }
        } else {
            panic!("the given header block does not end with an if-statement");
        }
    }

    /// Returns the basic blocks corresponding to the false branch of the
    /// if-statement at the end of the given header block.
    ///
    /// # Panics
    ///
    /// This method panics if the given block does not end with an if-statement node.
    pub fn get_false_branch(&self, header_block: &BasicBlock) -> Vec<&BasicBlock> {
        use crate::ir::Statement::*;
        if let Some(IfThenElse { true_index, false_index, .. }) = header_block.statements().last() {
            if let Some(false_index) = false_index {
                if self.dominator_tree.get_dominance_frontier(*true_index).contains(false_index) {
                    // The false branch is empty.
                    return Vec::new();
                }
                let start_block =
                    self.get_basic_block(*false_index).expect("in control-flow graph");
                let end_blocks = self.get_dominance_frontier(start_block);

                if end_blocks.is_empty() {
                    // True and false branches do not join up.
                    let mut result = self.get_successors(start_block);
                    result.push(start_block);
                    result
                } else {
                    // True and false branches join up at the dominance frontier.
                    let mut result = Vec::new();
                    for end_block in end_blocks {
                        result.extend(self.get_interval(start_block, end_block))
                    }
                    result
                }
            } else {
                Vec::new()
            }
        } else {
            panic!("the given header block does not end with an if-statement");
        }
    }

    /// Cache variable use for each node in the CFG.
    pub(crate) fn cache_variable_use(&mut self) {
        debug!("computing variable use for `{}`", self.name());
        for basic_block in self.iter_mut() {
            basic_block.cache_variable_use();
        }
    }

    /// Propagate expression degrees along the CFG.
    pub(crate) fn propagate_degrees(&mut self) {
        debug!("propagating expression degrees for `{}`", self.name());
        let mut env = DegreeEnvironment::new();
        for param in self.parameters().iter() {
            env.set_type(param, &VariableType::Local);
            env.set_degree(param, &Degree::Constant.into())
        }
        for basic_block in self.iter_mut() {
            basic_block.propagate_degrees(&mut env);
        }
    }

    /// Propagate constant values along the CFG.
    pub(crate) fn propagate_values(&mut self) {
        debug!("propagating constant values for `{}`", self.name());
        let mut env = ValueEnvironment::new(&self.constants);
        let mut rerun = true;
        while rerun {
            // Rerun value propagation if a single child node was updated.
            rerun = false;
            for basic_block in self.iter_mut() {
                rerun = rerun || basic_block.propagate_values(&mut env);
            }
        }
    }

    /// Propagate variable types along the CFG.
    pub(crate) fn propagate_types(&mut self) {
        debug!("propagating variable types for `{}`", self.name());
        // Need to clone declarations here since we cannot borrow self both
        // mutably and immutably.
        let declarations = self.declarations.clone();
        for basic_block in self.iter_mut() {
            basic_block.propagate_types(&declarations);
        }
    }
}

impl fmt::Debug for Cfg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for basic_block in self.iter() {
            writeln!(
                f,
                "basic block {}, predecessors: {:?}, successors: {:?}",
                basic_block.index(),
                basic_block.predecessors(),
                basic_block.successors(),
            )?;
            write!(f, "{:?}", basic_block)?;
        }
        Ok(())
    }
}