1 //! Alias analysis, consisting of a "last store" pass and a "memory
2 //! values" pass. These two passes operate as one fused pass, and so
3 //! are implemented together here.
4 //!
5 //! We partition memory state into several *disjoint pieces* of
6 //! "abstract state". There are a finite number of such pieces:
7 //! currently, we call them "heap", "table", "vmctx", and "other".Any
8 //! given address in memory belongs to exactly one disjoint piece.
9 //!
10 //! One never tracks which piece a concrete address belongs to at
11 //! runtime; this is a purely static concept. Instead, all
12 //! memory-accessing instructions (loads and stores) are labeled with
13 //! one of these four categories in the `MemFlags`. It is forbidden
14 //! for a load or store to access memory under one category and a
15 //! later load or store to access the same memory under a different
16 //! category. This is ensured to be true by construction during
17 //! frontend translation into CLIF and during legalization.
18 //!
19 //! Given that this non-aliasing property is ensured by the producer
20 //! of CLIF, we can compute a *may-alias* property: one load or store
21 //! may-alias another load or store if both access the same category
22 //! of abstract state.
23 //!
24 //! The "last store" pass helps to compute this aliasing: it scans the
25 //! code, finding at each program point the last instruction that
26 //! *might have* written to a given part of abstract state.
27 //!
28 //! We can't say for sure that the "last store" *did* actually write
29 //! that state, but we know for sure that no instruction *later* than
30 //! it (up to the current instruction) did. However, we can get a
31 //! must-alias property from this: if at a given load or store, we
32 //! look backward to the "last store", *AND* we find that it has
33 //! exactly the same address expression and type, then we know that
34 //! the current instruction's access *must* be to the same memory
35 //! location.
36 //!
37 //! To get this must-alias property, we compute a sparse table of
38 //! "memory values": these are known equivalences between SSA `Value`s
39 //! and particular locations in memory. The memory-values table is a
40 //! mapping from (last store, address expression, type) to SSA
41 //! value. At a store, we can insert into this table directly. At a
42 //! load, we can also insert, if we don't already have a value (from
43 //! the store that produced the load's value).
44 //!
45 //! Then we can do two optimizations at once given this table. If a
46 //! load accesses a location identified by a (last store, address,
47 //! type) key already in the table, we replace it with the SSA value
48 //! for that memory location. This is usually known as "redundant load
49 //! elimination" if the value came from an earlier load of the same
50 //! location, or "store-to-load forwarding" if the value came from an
51 //! earlier store to the same location.
52 //!
53 //! In theory we could also do *dead-store elimination*, where if a
54 //! store overwrites a key in the table, *and* if no other load/store
55 //! to the abstract state category occurred, *and* no other trapping
56 //! instruction occurred (at which point we need an up-to-date memory
57 //! state because post-trap-termination memory state can be observed),
58 //! *and* we can prove the original store could not have trapped, then
59 //! we can eliminate the original store. Because this is so complex,
60 //! and the conditions for doing it correctly when post-trap state
61 //! must be correct likely reduce the potential benefit, we don't yet
62 //! do this.
63 
64 use crate::{
65     cursor::{Cursor, FuncCursor},
66     dominator_tree::DominatorTree,
67     fx::{FxHashMap, FxHashSet},
68     inst_predicates::{
69         has_memory_fence_semantics, inst_addr_offset_type, inst_store_data, visit_block_succs,
70     },
71     ir::{immediates::Offset32, Block, Function, Inst, Opcode, Type, Value},
72 };
73 use cranelift_entity::{packed_option::PackedOption, EntityRef};
74 
75 /// For a given program point, the vector of last-store instruction
76 /// indices for each disjoint category of abstract state.
77 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78 struct LastStores {
79     heap: PackedOption<Inst>,
80     table: PackedOption<Inst>,
81     vmctx: PackedOption<Inst>,
82     other: PackedOption<Inst>,
83 }
84 
85 impl LastStores {
86     fn update(&mut self, func: &Function, inst: Inst) {
87         let opcode = func.dfg[inst].opcode();
88         if has_memory_fence_semantics(opcode) {
89             self.heap = inst.into();
90             self.table = inst.into();
91             self.vmctx = inst.into();
92             self.other = inst.into();
93         } else if opcode.can_store() {
94             if let Some(memflags) = func.dfg[inst].memflags() {
95                 if memflags.heap() {
96                     self.heap = inst.into();
97                 } else if memflags.table() {
98                     self.table = inst.into();
99                 } else if memflags.vmctx() {
100                     self.vmctx = inst.into();
101                 } else {
102                     self.other = inst.into();
103                 }
104             } else {
105                 self.heap = inst.into();
106                 self.table = inst.into();
107                 self.vmctx = inst.into();
108                 self.other = inst.into();
109             }
110         }
111     }
112 
113     fn get_last_store(&self, func: &Function, inst: Inst) -> PackedOption<Inst> {
114         if let Some(memflags) = func.dfg[inst].memflags() {
115             if memflags.heap() {
116                 self.heap
117             } else if memflags.table() {
118                 self.table
119             } else if memflags.vmctx() {
120                 self.vmctx
121             } else {
122                 self.other
123             }
124         } else if func.dfg[inst].opcode().can_load() || func.dfg[inst].opcode().can_store() {
125             inst.into()
126         } else {
127             PackedOption::default()
128         }
129     }
130 
131     fn meet_from(&mut self, other: &LastStores, loc: Inst) {
132         let meet = |a: PackedOption<Inst>, b: PackedOption<Inst>| -> PackedOption<Inst> {
133             match (a.into(), b.into()) {
134                 (None, None) => None.into(),
135                 (Some(a), None) => a,
136                 (None, Some(b)) => b,
137                 (Some(a), Some(b)) if a == b => a,
138                 _ => loc.into(),
139             }
140         };
141 
142         self.heap = meet(self.heap, other.heap);
143         self.table = meet(self.table, other.table);
144         self.vmctx = meet(self.vmctx, other.vmctx);
145         self.other = meet(self.other, other.other);
146     }
147 }
148 
149 /// A key identifying a unique memory location.
150 ///
151 /// For the result of a load to be equivalent to the result of another
152 /// load, or the store data from a store, we need for (i) the
153 /// "version" of memory (here ensured by having the same last store
154 /// instruction to touch the disjoint category of abstract state we're
155 /// accessing); (ii) the address must be the same (here ensured by
156 /// having the same SSA value, which doesn't change after computed);
157 /// (iii) the offset must be the same; and (iv) the accessed type and
158 /// extension mode (e.g., 8-to-32, signed) must be the same.
159 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
160 struct MemoryLoc {
161     last_store: PackedOption<Inst>,
162     address: Value,
163     offset: Offset32,
164     ty: Type,
165     /// We keep the *opcode* of the instruction that produced the
166     /// value we record at this key if the opcode is anything other
167     /// than an ordinary load or store. This is needed when we
168     /// consider loads that extend the value: e.g., an 8-to-32
169     /// sign-extending load will produce a 32-bit value from an 8-bit
170     /// value in memory, so we can only reuse that (as part of RLE)
171     /// for another load with the same extending opcode.
172     ///
173     /// We could improve the transform to insert explicit extend ops
174     /// in place of extending loads when we know the memory value, but
175     /// we haven't yet done this.
176     extending_opcode: Option<Opcode>,
177 }
178 
179 /// An alias-analysis pass.
180 pub struct AliasAnalysis<'a> {
181     /// The function we're analyzing.
182     func: &'a mut Function,
183 
184     /// The domtree for the function.
185     domtree: &'a DominatorTree,
186 
187     /// Input state to a basic block.
188     block_input: FxHashMap<Block, LastStores>,
189 
190     /// Known memory-value equivalences. This is the result of the
191     /// analysis. This is a mapping from (last store, address
192     /// expression, offset, type) to SSA `Value`.
193     ///
194     /// We keep the defining inst around for quick dominance checks.
195     mem_values: FxHashMap<MemoryLoc, (Inst, Value)>,
196 }
197 
198 impl<'a> AliasAnalysis<'a> {
199     /// Perform an alias analysis pass.
200     pub fn new(func: &'a mut Function, domtree: &'a DominatorTree) -> AliasAnalysis<'a> {
201         log::trace!("alias analysis: input is:\n{:?}", func);
202         let mut analysis = AliasAnalysis {
203             func,
204             domtree,
205             block_input: FxHashMap::default(),
206             mem_values: FxHashMap::default(),
207         };
208 
209         analysis.compute_block_input_states();
210         analysis
211     }
212 
213     fn compute_block_input_states(&mut self) {
214         let mut queue = vec![];
215         let mut queue_set = FxHashSet::default();
216         let entry = self.func.layout.entry_block().unwrap();
217         queue.push(entry);
218         queue_set.insert(entry);
219 
220         while let Some(block) = queue.pop() {
221             queue_set.remove(&block);
222             let mut state = self
223                 .block_input
224                 .entry(block)
225                 .or_insert_with(|| LastStores::default())
226                 .clone();
227 
228             log::trace!(
229                 "alias analysis: input to block{} is {:?}",
230                 block.index(),
231                 state
232             );
233 
234             for inst in self.func.layout.block_insts(block) {
235                 state.update(self.func, inst);
236                 log::trace!("after inst{}: state is {:?}", inst.index(), state);
237             }
238 
239             visit_block_succs(self.func, block, |_inst, succ| {
240                 let succ_first_inst = self
241                     .func
242                     .layout
243                     .block_insts(succ)
244                     .into_iter()
245                     .next()
246                     .unwrap();
247                 let updated = match self.block_input.get_mut(&succ) {
248                     Some(succ_state) => {
249                         let old = succ_state.clone();
250                         succ_state.meet_from(&state, succ_first_inst);
251                         *succ_state != old
252                     }
253                     None => {
254                         self.block_input.insert(succ, state.clone());
255                         true
256                     }
257                 };
258 
259                 if updated && queue_set.insert(succ) {
260                     queue.push(succ);
261                 }
262             });
263         }
264     }
265 
266     /// Make a pass and update known-redundant loads to aliased
267     /// values. We interleave the updates with the memory-location
268     /// tracking because resolving some aliases may expose others
269     /// (e.g. in cases of double-indirection with two separate chains
270     /// of loads).
271     pub fn compute_and_update_aliases(&mut self) {
272         let mut pos = FuncCursor::new(self.func);
273 
274         while let Some(block) = pos.next_block() {
275             let mut state = self
276                 .block_input
277                 .get(&block)
278                 .cloned()
279                 .unwrap_or_else(|| LastStores::default());
280 
281             while let Some(inst) = pos.next_inst() {
282                 log::trace!(
283                     "alias analysis: scanning at inst{} with state {:?} ({:?})",
284                     inst.index(),
285                     state,
286                     pos.func.dfg[inst],
287                 );
288 
289                 if let Some((address, offset, ty)) = inst_addr_offset_type(pos.func, inst) {
290                     let address = pos.func.dfg.resolve_aliases(address);
291                     let opcode = pos.func.dfg[inst].opcode();
292 
293                     if opcode.can_store() {
294                         let store_data = inst_store_data(pos.func, inst).unwrap();
295                         let store_data = pos.func.dfg.resolve_aliases(store_data);
296                         let mem_loc = MemoryLoc {
297                             last_store: inst.into(),
298                             address,
299                             offset,
300                             ty,
301                             extending_opcode: get_ext_opcode(opcode),
302                         };
303                         log::trace!(
304                             "alias analysis: at inst{}: store with data v{} at loc {:?}",
305                             inst.index(),
306                             store_data.index(),
307                             mem_loc
308                         );
309                         self.mem_values.insert(mem_loc, (inst, store_data));
310                     } else if opcode.can_load() {
311                         let last_store = state.get_last_store(pos.func, inst);
312                         let load_result = pos.func.dfg.inst_results(inst)[0];
313                         let mem_loc = MemoryLoc {
314                             last_store,
315                             address,
316                             offset,
317                             ty,
318                             extending_opcode: get_ext_opcode(opcode),
319                         };
320                         log::trace!(
321                             "alias analysis: at inst{}: load with last_store inst{} at loc {:?}",
322                             inst.index(),
323                             last_store.map(|inst| inst.index()).unwrap_or(usize::MAX),
324                             mem_loc
325                         );
326 
327                         // Is there a Value already known to be stored
328                         // at this specific memory location?  If so,
329                         // we can alias the load result to this
330                         // already-known Value.
331                         //
332                         // Check if the definition dominates this
333                         // location; it might not, if it comes from a
334                         // load (stores will always dominate though if
335                         // their `last_store` survives through
336                         // meet-points to this use-site).
337                         let aliased = if let Some((def_inst, value)) =
338                             self.mem_values.get(&mem_loc).cloned()
339                         {
340                             log::trace!(
341                                 " -> sees known value v{} from inst{}",
342                                 value.index(),
343                                 def_inst.index()
344                             );
345                             if self.domtree.dominates(def_inst, inst, &pos.func.layout) {
346                                 log::trace!(
347                                     " -> dominates; value equiv from v{} to v{} inserted",
348                                     load_result.index(),
349                                     value.index()
350                                 );
351 
352                                 pos.func.dfg.detach_results(inst);
353                                 pos.func.dfg.change_to_alias(load_result, value);
354                                 pos.remove_inst_and_step_back();
355                                 true
356                             } else {
357                                 false
358                             }
359                         } else {
360                             false
361                         };
362 
363                         // Otherwise, we can keep *this* load around
364                         // as a new equivalent value.
365                         if !aliased {
366                             log::trace!(
367                                 " -> inserting load result v{} at loc {:?}",
368                                 load_result.index(),
369                                 mem_loc
370                             );
371                             self.mem_values.insert(mem_loc, (inst, load_result));
372                         }
373                     }
374                 }
375 
376                 state.update(pos.func, inst);
377             }
378         }
379     }
380 }
381 
382 fn get_ext_opcode(op: Opcode) -> Option<Opcode> {
383     debug_assert!(op.can_load() || op.can_store());
384     match op {
385         Opcode::Load | Opcode::Store => None,
386         _ => Some(op),
387     }
388 }
389