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
use crate::{backend::riscv::from_ir::register_assign::RegisterAssign, ir};

use super::{statement, FunctionCompileContext};

/// Emit assembly code for a [`ir::function::basic_block::BasicBlock`].
pub fn emit_code(
    basic_block: &ir::function::basic_block::BasicBlock,
    ctx: &mut FunctionCompileContext,
) -> String {
    let ir::function::basic_block::BasicBlock { name, content } = basic_block;
    let mut result = String::new();
    if let Some(name) = name {
        result.push_str(format!("{name}:\n").as_str());
    }
    if let Some((terminator, content)) = content.split_last() {
        for statement in content {
            let statement_code = statement::emit_code(statement, ctx);
            result.push_str(&statement_code);
        }
        result.push_str(&append_phi_insert(ctx, basic_block));
        let terminator_code = statement::emit_code(terminator, ctx);
        result.push_str(&terminator_code);
        result
    } else {
        String::new()
    }
}

fn append_phi_insert(
    ctx: &mut FunctionCompileContext,
    basic_block: &ir::function::basic_block::BasicBlock,
) -> String {
    let mut result = String::new();
    if let Some(phi_insert) = ctx
        .phi_constant_assign
        .get(basic_block.name.as_ref().unwrap())
    {
        for (register_assign, constant) in phi_insert {
            match register_assign {
                RegisterAssign::Register(register) => {
                    result.push_str(format!("    li {register}, {constant}\n").as_str());
                }
                RegisterAssign::StackRef(offset) => {
                    result.push_str(format!("    li t0, {constant}\n").as_str());
                    result.push_str(format!("    sw t0, {offset}(sp)\n").as_str());
                }
                RegisterAssign::StackValue(offset) => {
                    result.push_str(format!("    li t0, {constant}\n").as_str());
                    result.push_str(format!("    sw t0, {offset}(sp)\n").as_str());
                }
                RegisterAssign::MultipleRegisters(_) => {
                    unreachable!()
                }
            }
        }
    }
    result
}

#[cfg(test)]
mod tests {
    #![allow(clippy::borrow_interior_mutable_const)]

    use super::*;
    use std::collections::HashMap;

    use crate::{
        backend::riscv::from_ir::{register_assign::RegisterAssign, Context},
        ir::{
            self,
            function::{basic_block::BasicBlock, test_util::*},
            statement::{phi::PhiSource, Phi},
            RegisterName,
        },
        utility::data_type::{self, Type},
    };

    #[test]
    fn phi_insert() {
        let function = ir::FunctionDefinition {
            header: ir::FunctionHeader {
                name: "f".to_string(),
                parameters: Vec::new(),
                return_type: Type::None,
            },
            content: vec![
                BasicBlock {
                    name: Some("f_entry".to_string()),
                    content: vec![binop_constant("reg1"), branch("bb1", "bb2")],
                },
                BasicBlock {
                    name: Some("bb1".to_string()),
                    content: vec![binop_constant("reg2"), jump("bb3")],
                },
                BasicBlock {
                    name: Some("bb2".to_string()),
                    content: vec![binop_constant("reg3"), jump("bb3")],
                },
                BasicBlock {
                    name: Some("bb3".to_string()),
                    content: vec![Phi {
                        to: RegisterName("reg0".to_string()),
                        data_type: data_type::I32.clone(),
                        from: vec![
                            PhiSource {
                                value: 1.into(),
                                block: "bb1".to_string(),
                            },
                            PhiSource {
                                value: 2.into(),
                                block: "bb2".to_string(),
                            },
                        ],
                    }
                    .into()],
                },
            ],
        };
        let mut register_assign = HashMap::new();
        register_assign.insert(
            RegisterName("reg0".to_string()),
            RegisterAssign::Register("t2".to_string()),
        );
        register_assign.insert(
            RegisterName("reg1".to_string()),
            RegisterAssign::Register("t3".to_string()),
        );
        register_assign.insert(
            RegisterName("reg2".to_string()),
            RegisterAssign::Register("t4".to_string()),
        );
        register_assign.insert(
            RegisterName("reg3".to_string()),
            RegisterAssign::Register("t5".to_string()),
        );
        let mut ctx = Context {
            struct_definitions: HashMap::new(),
        };
        let mut context = FunctionCompileContext {
            parent_context: &mut ctx,
            local_assign: register_assign,
            cleanup_label: None,
            phi_constant_assign: HashMap::new(),
        };
        context.phi_constant_assign.insert(
            "bb1".to_string(),
            vec![(RegisterAssign::Register("t2".to_string()), 1.into())],
        );
        context.phi_constant_assign.insert(
            "bb2".to_string(),
            vec![(RegisterAssign::Register("t2".to_string()), 2.into())],
        );
        let code = emit_code(&function.content[1], &mut context);
        assert_eq!(
            code,
            r#"bb1:
    li t0, 1
    li t1, 2
    add t4, t0, t1
    li t2, 1
    j bb3
"#
        );
        let code = emit_code(&function.content[2], &mut context);
        assert_eq!(
            code,
            r#"bb2:
    li t0, 1
    li t1, 2
    add t5, t0, t1
    li t2, 2
    j bb3
"#
        )
    }
}