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
use std::{cell::OnceCell, collections::HashMap};

use itertools::Itertools;

use crate::{
    ir::{
        self,
        editor::action::Action,
        function::FunctionDefinitionIndex,
        quantity::Quantity,
        statement::{IRStatement, IsIRStatement},
        FunctionDefinition, RegisterName,
    },
    utility::data_type::Type,
};

use super::IsAnalyzer;

/// [`MemoryAccessInfo`] is about how a range of memory space is accessed.
#[derive(Debug, Clone, Default)]
pub struct MemoryAccessInfo {
    /// alloca statement index
    pub alloca: Option<FunctionDefinitionIndex>,
    // store statements index, in order
    pub store: Vec<FunctionDefinitionIndex>,
    // load statements index, in order
    pub load: Vec<FunctionDefinitionIndex>,
    store_group_by_basic_block: OnceCell<HashMap<usize, Vec<usize>>>,
    load_group_by_basic_block: OnceCell<HashMap<usize, Vec<usize>>>,
}

impl MemoryAccessInfo {
    /// Group store statements by basic block.
    fn store_group_by_basic_block(&self) -> &HashMap<usize, Vec<usize>> {
        self.store_group_by_basic_block.get_or_init(|| {
            self.store
                .iter()
                .group_by(|it| it.0)
                .into_iter()
                .map(|(basic_block_id, it)| {
                    (basic_block_id, it.into_iter().map(|it| it.1).collect())
                })
                .collect()
        })
    }

    /// Group load statements by basic block.
    fn load_group_by_basic_block(&self) -> &HashMap<usize, Vec<usize>> {
        self.load_group_by_basic_block.get_or_init(|| {
            self.load
                .iter()
                .group_by(|it| it.0)
                .into_iter()
                .map(|(basic_block_id, it)| {
                    (basic_block_id, it.into_iter().map(|it| it.1).collect())
                })
                .collect()
        })
    }

    /// Find all loades which are
    /// - in the same basic block as the given store
    /// - appear after the given store
    pub fn loads_dorminated_by_store_in_block(
        &self,
        store: &FunctionDefinitionIndex,
    ) -> Vec<FunctionDefinitionIndex> {
        let store_in_basic_block = self.store_group_by_basic_block().get(&store.0).unwrap();
        let next_store_index = store_in_basic_block
            .iter()
            .find(|&&it| it > store.1)
            .cloned()
            .unwrap_or(usize::MAX);
        self.load_group_by_basic_block()
            .get(&store.0)
            .unwrap_or(&Vec::new())
            .iter()
            .filter(|&&it| it > store.1 && it < next_store_index)
            .map(|it| (store.0, *it).into())
            .collect_vec()
    }
}

/// [`MemoryUsage`] is for analyzing how a function uses stack memory.
#[derive(Debug, Default)]
pub struct MemoryUsage {
    memory_access: OnceCell<HashMap<RegisterName, MemoryAccessInfo>>,
}

impl MemoryUsage {
    /// Create a new [`MemoryUsage`].
    pub fn new() -> Self {
        Self {
            memory_access: OnceCell::new(),
        }
    }

    /// Get the [`MemoryAccessInfo`] of the given variable.
    fn memory_access_info(
        &self,
        function: &ir::FunctionDefinition,
        variable_name: &RegisterName,
    ) -> &MemoryAccessInfo {
        self.memory_access(function).get(variable_name).unwrap()
    }

    /// All variables which are allocated on stack.
    fn memory_access_variables(
        &self,
        function: &ir::FunctionDefinition,
    ) -> impl Iterator<Item = &RegisterName> {
        self.memory_access(function).keys()
    }

    /// All variables and their type which are allocated on stack.
    fn memory_access_variables_and_types(
        &self,
        function: &ir::FunctionDefinition,
    ) -> HashMap<RegisterName, Type> {
        self.memory_access(function)
            .iter()
            .map(|(variable, info)| {
                let data_type = function[info.alloca.clone().unwrap()]
                    .as_alloca()
                    .alloc_type
                    .clone();
                (variable.clone(), data_type)
            })
            .collect()
    }

    fn memory_access(
        &self,
        function: &ir::FunctionDefinition,
    ) -> &HashMap<RegisterName, MemoryAccessInfo> {
        self.memory_access
            .get_or_init(|| self.init_memory_access(function))
    }

    fn init_memory_access(
        &self,
        function: &ir::FunctionDefinition,
    ) -> HashMap<RegisterName, MemoryAccessInfo> {
        let mut memory_access: HashMap<RegisterName, MemoryAccessInfo> = HashMap::new();
        for (index, statement) in function.iter().function_definition_index_enumerate() {
            match statement {
                IRStatement::Alloca(_) => {
                    memory_access
                        .entry(statement.generate_register().unwrap().0)
                        .or_default()
                        .alloca = Some(index.clone());
                }
                IRStatement::Store(store) => {
                    if let Quantity::RegisterName(local) = &store.target {
                        memory_access
                            .entry(local.clone())
                            .or_default()
                            .store
                            .push(index);
                    }
                }
                IRStatement::Load(load) => {
                    if let Quantity::RegisterName(local) = &load.from {
                        memory_access
                            .entry(local.clone())
                            .or_default()
                            .load
                            .push(index);
                    }
                }
                _ => (),
            }
        }
        memory_access
    }
}

pub struct BindedMemoryUsage<'item, 'bind: 'item> {
    bind_on: &'bind FunctionDefinition,
    item: &'item MemoryUsage,
}

impl<'item, 'bind: 'item> BindedMemoryUsage<'item, 'bind> {
    pub fn memory_access_info(&self, variable_name: &RegisterName) -> &MemoryAccessInfo {
        self.item.memory_access_info(self.bind_on, variable_name)
    }
    pub fn memory_access_variables(&self) -> impl Iterator<Item = &RegisterName> {
        self.item.memory_access_variables(self.bind_on)
    }
    pub fn memory_access_variables_and_types(&self) -> HashMap<RegisterName, Type> {
        self.item.memory_access_variables_and_types(self.bind_on)
    }
}

impl<'item, 'bind: 'item> IsAnalyzer<'item, 'bind> for MemoryUsage {
    fn on_action(&mut self, _action: &Action) {
        // todo: optimization
        self.memory_access.take();
    }

    type Binded = BindedMemoryUsage<'item, 'bind>;

    fn bind(&'item self, content: &'bind ir::FunctionDefinition) -> Self::Binded {
        BindedMemoryUsage {
            bind_on: content,
            item: self,
        }
    }
}