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
use std::{
fmt::Debug,
ops::{Index, IndexMut},
};
use zhc_utils::{Dumpable, Store};
use crate::{ValIdRaw, val_ref::ValRef};
use super::{Dialect, IR, State, ValId};
/// A map that associates values with value IDs.
///
/// Maintains the same active/inactive structure as the source IR, allowing
/// efficient mapping of values to analysis results or other metadata.
/// Only active values can store data, and the map tracks how many
/// entries are currently stored.
#[derive(Clone, PartialEq, Eq)]
pub struct ValMap<T> {
store: Store<ValId, State<Option<T>>>,
n_stored: ValIdRaw,
n_inactive: ValIdRaw,
}
impl<T> ValMap<T> {
fn may_store(&self, k: &ValId) -> bool {
k.0 < self.store.len() && self.store[k].is_active()
}
/// Creates an empty value map with the same structure as the IR.
///
/// The resulting map preserves the active/inactive state of values
/// from the source IR but contains no stored data.
pub fn new_empty<D: Dialect>(ir: &IR<D>) -> Self {
ValMap {
store: ir
.val_states
.iter()
.map(|s| match s {
State::Active(_) => State::Active(None),
State::Inactive(_) => State::Inactive(None),
})
.collect(),
n_stored: 0,
n_inactive: ir.raw_n_vals() - ir.n_vals(),
}
}
/// Creates a value map filled with the specified value for all active values.
///
/// Every active value in the source IR will be associated with a clone
/// of `v`. Inactive values remain unmapped.
pub fn new_filled<D: Dialect>(ir: &IR<D>, v: T) -> Self
where
T: Clone,
{
ValMap {
store: ir
.val_states
.iter()
.map(|s| match s {
State::Active(_) => State::Active(Some(v.clone())),
State::Inactive(_) => State::Inactive(None),
})
.collect(),
n_stored: ir.n_vals(),
n_inactive: ir.raw_n_vals() - ir.n_vals(),
}
}
/// Creates a value map by selectively applying a function to active values.
///
/// The function returns `None` for values that should not have entries
/// in the resulting map. Only values for which the function returns
/// `Some(value)` will be stored.
pub fn new_partially_mapped<D: Dialect>(
ir: &IR<D>,
mut f: impl FnMut(ValRef<D>) -> Option<T>,
) -> Self {
ValMap {
store: ir
.raw_walk_vals_linear()
.map(|val| {
if val.is_active() {
State::Active(f(val))
} else {
State::Inactive(None)
}
})
.collect(),
n_stored: ir.n_vals(),
n_inactive: ir.raw_n_vals() - ir.n_vals(),
}
}
/// Creates a value map by applying a function to all active values.
///
/// Every active value will have an entry in the resulting map,
/// as the function must return a value rather than an option.
pub fn new_totally_mapped<D: Dialect>(ir: &IR<D>, mut f: impl FnMut(ValRef<D>) -> T) -> Self {
ValMap {
store: ir
.raw_walk_vals_linear()
.map(|val| {
if val.is_active() {
State::Active(Some(f(val)))
} else {
State::Inactive(None)
}
})
.collect(),
n_stored: ir.n_vals(),
n_inactive: ir.raw_n_vals() - ir.n_vals(),
}
}
/// Returns the number of values that have stored data.
pub fn len(&self) -> ValIdRaw {
self.n_stored
}
/// Returns `true` if all active values have stored data.
pub fn is_filled(&self) -> bool {
self.n_stored + self.n_inactive == self.store.len()
}
/// Returns `true` if no values have stored data.
pub fn is_empty(&self) -> bool {
self.n_stored == 0
}
/// Returns `true` if the specified value has stored data.
///
/// # Panics
///
/// Panics if the value ID is out of bounds or refers to an inactive value.
pub fn contains_key(&self, k: &ValId) -> bool {
assert!(self.may_store(k));
self.store[k].as_ref().unwrap_active().is_some()
}
/// Returns a reference to the data for the specified value.
///
/// Returns `None` if no data is stored for the value.
///
/// # Panics
///
/// Panics if the value ID is out of bounds or refers to an inactive value.
pub fn get(&self, k: &ValId) -> Option<&T> {
assert!(self.may_store(k));
self.store[k].as_ref().unwrap_active().as_ref()
}
/// Returns a mutable guard for the data at the specified value.
///
/// Returns `None` if no data is stored for the value. The guard
/// automatically tracks changes when dropped.
///
/// # Panics
///
/// Panics if the value ID is out of bounds or refers to an inactive value.
pub fn get_mut(&mut self, k: &ValId) -> Option<&mut T> {
assert!(self.may_store(k));
self.store[k].as_mut_ref().unwrap_active().as_mut()
}
/// Stores data for the specified value.
///
/// Returns the previous data if it existed, otherwise `None`.
///
/// # Panics
///
/// Panics if the value ID is out of bounds or refers to an inactive value.
pub fn insert(&mut self, k: ValId, v: T) -> Option<T>
where
T: PartialEq,
{
assert!(self.may_store(&k));
let v = State::Active(Some(v));
let out = std::mem::replace(&mut self.store[k], v).unwrap_active();
if out.is_none() {
self.n_stored += 1;
}
out
}
/// Removes and returns the data for the specified value.
///
/// Returns `None` if no data was stored for the value.
///
/// # Panics
///
/// Panics if the value ID is out of bounds or refers to an inactive value.
pub fn remove(&mut self, k: &ValId) -> Option<T> {
assert!(self.may_store(&k));
let v = State::Active(None);
let out = std::mem::replace(&mut self.store[k], v).unwrap_active();
if out.is_some() {
self.n_stored -= 1;
}
out
}
/// Returns an iterator over value IDs and their stored data.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (ValId, &T)> {
self.store.enumerate_iter().filter_map(|(i, a)| match a {
State::Active(Some(v)) => Some((i, v)),
_ => None,
})
}
/// Returns an iterator over value IDs and mutable references to their data.
pub fn iter_mut(&mut self) -> impl Iterator<Item = (ValId, &mut T)> {
self.store
.enumerate_iter_mut()
.filter_map(|(i, a)| match a {
State::Active(Some(v)) => Some((i, v)),
_ => None,
})
}
/// Consumes the map and returns an iterator over value IDs and their stored data.
pub fn into_iter(self) -> impl DoubleEndedIterator<Item = (ValId, T)> {
self.store
.enumerate_into_iter()
.filter_map(|(i, a)| match a {
State::Active(Some(v)) => Some((i, v)),
_ => None,
})
}
/// Transforms stored values by applying `f`, preserving map structure.
///
/// Active slots with a value are mapped through `f`; empty active slots
/// and inactive slots remain unchanged. Counters and change flag are
/// carried over as-is.
pub fn map<TN>(self, mut f: impl FnMut(T) -> TN) -> ValMap<TN> {
let ValMap {
store,
n_stored,
n_inactive,
} = self;
let store = store
.into_iter()
.map(|a| match a {
State::Active(o) => State::Active(o.map(&mut f)),
State::Inactive(_) => State::Inactive(None),
})
.collect();
ValMap {
store,
n_stored,
n_inactive,
}
}
}
impl<T> Index<ValId> for ValMap<T> {
type Output = T;
fn index(&self, index: ValId) -> &Self::Output {
match self.get(&index) {
Some(a) => a,
None => panic!("Tried to get unmapped index {:?}", index),
}
}
}
impl<T> IndexMut<ValId> for ValMap<T> {
fn index_mut(&mut self, index: ValId) -> &mut Self::Output {
match self.get_mut(&index) {
Some(a) => a,
None => panic!("Tried to get unmapped index {:?}", index),
}
}
}
impl<T: Debug> Debug for ValMap<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<T: Dumpable> Dumpable for ValMap<T> {
fn dump_to_string(&self) -> String {
self.iter()
.map(|(id, v)| format!("{:?}: {}", id, v.dump_to_string()))
.collect::<Vec<_>>()
.join("\n")
}
}