1 //! Intermediate representation of a function.
2 //!
3 //! The `Function` struct defined in this module owns all of its basic blocks and
4 //! instructions.
5 
6 use crate::entity::{PrimaryMap, SecondaryMap};
7 use crate::ir;
8 use crate::ir::JumpTables;
9 use crate::ir::{
10     instructions::BranchInfo, Block, DynamicStackSlot, DynamicStackSlotData, DynamicType,
11     ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Heap, HeapData, Inst, InstructionData,
12     JumpTable, JumpTableData, Opcode, SigRef, StackSlot, StackSlotData, Table, TableData, Type,
13 };
14 use crate::ir::{DataFlowGraph, Layout, Signature};
15 use crate::ir::{DynamicStackSlots, SourceLocs, StackSlots};
16 use crate::isa::CallConv;
17 use crate::value_label::ValueLabelsRanges;
18 use crate::write::write_function;
19 use crate::HashMap;
20 #[cfg(feature = "enable-serde")]
21 use alloc::string::String;
22 use core::fmt;
23 
24 #[cfg(feature = "enable-serde")]
25 use serde::de::{Deserializer, Error};
26 #[cfg(feature = "enable-serde")]
27 use serde::ser::Serializer;
28 #[cfg(feature = "enable-serde")]
29 use serde::{Deserialize, Serialize};
30 
31 use super::entities::UserExternalNameRef;
32 use super::extname::UserFuncName;
33 use super::{RelSourceLoc, SourceLoc, UserExternalName};
34 
35 /// A version marker used to ensure that serialized clif ir is never deserialized with a
36 /// different version of Cranelift.
37 #[derive(Copy, Clone, Debug, PartialEq, Hash)]
38 pub struct VersionMarker;
39 
40 #[cfg(feature = "enable-serde")]
41 impl Serialize for VersionMarker {
42     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
43     where
44         S: Serializer,
45     {
46         crate::VERSION.serialize(serializer)
47     }
48 }
49 
50 #[cfg(feature = "enable-serde")]
51 impl<'de> Deserialize<'de> for VersionMarker {
52     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53     where
54         D: Deserializer<'de>,
55     {
56         let version = String::deserialize(deserializer)?;
57         if version != crate::VERSION {
58             return Err(D::Error::custom(&format!(
59                 "Expected a clif ir function for version {}, found one for version {}",
60                 crate::VERSION,
61                 version,
62             )));
63         }
64         Ok(VersionMarker)
65     }
66 }
67 
68 /// Function parameters used when creating this function, and that will become applied after
69 /// compilation to materialize the final `CompiledCode`.
70 #[derive(Clone)]
71 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
72 pub struct FunctionParameters {
73     /// The first `SourceLoc` appearing in the function, serving as a base for every relative
74     /// source loc in the function.
75     base_srcloc: Option<SourceLoc>,
76 
77     /// External user-defined function references.
78     user_named_funcs: PrimaryMap<UserExternalNameRef, UserExternalName>,
79 
80     /// Inverted mapping of `user_named_funcs`, to deduplicate internally.
81     user_ext_name_to_ref: HashMap<UserExternalName, UserExternalNameRef>,
82 }
83 
84 impl FunctionParameters {
85     /// Creates a new `FunctionParameters` with the given name.
86     pub fn new() -> Self {
87         Self {
88             base_srcloc: None,
89             user_named_funcs: Default::default(),
90             user_ext_name_to_ref: Default::default(),
91         }
92     }
93 
94     /// Returns the base `SourceLoc`.
95     ///
96     /// If it was never explicitly set with `ensure_base_srcloc`, will return an invalid
97     /// `SourceLoc`.
98     pub fn base_srcloc(&self) -> SourceLoc {
99         self.base_srcloc.unwrap_or_default()
100     }
101 
102     /// Sets the base `SourceLoc`, if not set yet, and returns the base value.
103     pub fn ensure_base_srcloc(&mut self, srcloc: SourceLoc) -> SourceLoc {
104         match self.base_srcloc {
105             Some(val) => val,
106             None => {
107                 self.base_srcloc = Some(srcloc);
108                 srcloc
109             }
110         }
111     }
112 
113     /// Retrieve a `UserExternalNameRef` for the given name, or add a new one.
114     ///
115     /// This method internally deduplicates same `UserExternalName` so they map to the same
116     /// reference.
117     pub fn ensure_user_func_name(&mut self, name: UserExternalName) -> UserExternalNameRef {
118         if let Some(reff) = self.user_ext_name_to_ref.get(&name) {
119             *reff
120         } else {
121             let reff = self.user_named_funcs.push(name.clone());
122             self.user_ext_name_to_ref.insert(name, reff);
123             reff
124         }
125     }
126 
127     /// Resets an already existing user function name to a new value.
128     pub fn reset_user_func_name(&mut self, index: UserExternalNameRef, name: UserExternalName) {
129         if let Some(prev_name) = self.user_named_funcs.get_mut(index) {
130             self.user_ext_name_to_ref.remove(prev_name);
131             *prev_name = name.clone();
132             self.user_ext_name_to_ref.insert(name, index);
133         }
134     }
135 
136     /// Returns the internal mapping of `UserExternalNameRef` to `UserExternalName`.
137     pub fn user_named_funcs(&self) -> &PrimaryMap<UserExternalNameRef, UserExternalName> {
138         &self.user_named_funcs
139     }
140 
141     fn clear(&mut self) {
142         self.base_srcloc = None;
143         self.user_named_funcs.clear();
144         self.user_ext_name_to_ref.clear();
145     }
146 }
147 
148 /// Function fields needed when compiling a function.
149 ///
150 /// Additionally, these fields can be the same for two functions that would be compiled the same
151 /// way, and finalized by applying `FunctionParameters` onto their `CompiledCodeStencil`.
152 #[derive(Clone, PartialEq, Hash)]
153 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
154 pub struct FunctionStencil {
155     /// A version marker used to ensure that serialized clif ir is never deserialized with a
156     /// different version of Cranelift.
157     // Note: This must be the first field to ensure that Serde will deserialize it before
158     // attempting to deserialize other fields that are potentially changed between versions.
159     pub version_marker: VersionMarker,
160 
161     /// Signature of this function.
162     pub signature: Signature,
163 
164     /// Sized stack slots allocated in this function.
165     pub sized_stack_slots: StackSlots,
166 
167     /// Dynamic stack slots allocated in this function.
168     pub dynamic_stack_slots: DynamicStackSlots,
169 
170     /// Global values referenced.
171     pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>,
172 
173     /// Heaps referenced.
174     pub heaps: PrimaryMap<ir::Heap, ir::HeapData>,
175 
176     /// Tables referenced.
177     pub tables: PrimaryMap<ir::Table, ir::TableData>,
178 
179     /// Jump tables used in this function.
180     pub jump_tables: JumpTables,
181 
182     /// Data flow graph containing the primary definition of all instructions, blocks and values.
183     pub dfg: DataFlowGraph,
184 
185     /// Layout of blocks and instructions in the function body.
186     pub layout: Layout,
187 
188     /// Source locations.
189     ///
190     /// Track the original source location for each instruction. The source locations are not
191     /// interpreted by Cranelift, only preserved.
192     pub srclocs: SourceLocs,
193 
194     /// An optional global value which represents an expression evaluating to
195     /// the stack limit for this function. This `GlobalValue` will be
196     /// interpreted in the prologue, if necessary, to insert a stack check to
197     /// ensure that a trap happens if the stack pointer goes below the
198     /// threshold specified here.
199     pub stack_limit: Option<ir::GlobalValue>,
200 }
201 
202 impl FunctionStencil {
203     fn clear(&mut self) {
204         self.signature.clear(CallConv::Fast);
205         self.sized_stack_slots.clear();
206         self.dynamic_stack_slots.clear();
207         self.global_values.clear();
208         self.heaps.clear();
209         self.tables.clear();
210         self.jump_tables.clear();
211         self.dfg.clear();
212         self.layout.clear();
213         self.srclocs.clear();
214         self.stack_limit = None;
215     }
216 
217     /// Creates a jump table in the function, to be used by `br_table` instructions.
218     pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable {
219         self.jump_tables.push(data)
220     }
221 
222     /// Creates a sized stack slot in the function, to be used by `stack_load`, `stack_store`
223     /// and `stack_addr` instructions.
224     pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot {
225         self.sized_stack_slots.push(data)
226     }
227 
228     /// Creates a dynamic stack slot in the function, to be used by `dynamic_stack_load`,
229     /// `dynamic_stack_store` and `dynamic_stack_addr` instructions.
230     pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot {
231         self.dynamic_stack_slots.push(data)
232     }
233 
234     /// Adds a signature which can later be used to declare an external function import.
235     pub fn import_signature(&mut self, signature: Signature) -> SigRef {
236         self.dfg.signatures.push(signature)
237     }
238 
239     /// Declares a global value accessible to the function.
240     pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue {
241         self.global_values.push(data)
242     }
243 
244     /// Find the global dyn_scale value associated with given DynamicType
245     pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue {
246         self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale
247     }
248 
249     /// Find the global dyn_scale for the given stack slot.
250     pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue {
251         let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty;
252         self.get_dyn_scale(dyn_ty)
253     }
254 
255     /// Get a concrete `Type` from a user defined `DynamicType`.
256     pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> {
257         self.dfg
258             .dynamic_types
259             .get(ty)
260             .unwrap_or_else(|| panic!("Undeclared dynamic vector type: {}", ty))
261             .concrete()
262     }
263 
264     /// Declares a heap accessible to the function.
265     pub fn create_heap(&mut self, data: HeapData) -> Heap {
266         self.heaps.push(data)
267     }
268 
269     /// Declares a table accessible to the function.
270     pub fn create_table(&mut self, data: TableData) -> Table {
271         self.tables.push(data)
272     }
273 
274     /// Find a presumed unique special-purpose function parameter value.
275     ///
276     /// Returns the value of the last `purpose` parameter, or `None` if no such parameter exists.
277     pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> {
278         let entry = self.layout.entry_block().expect("Function is empty");
279         self.signature
280             .special_param_index(purpose)
281             .map(|i| self.dfg.block_params(entry)[i])
282     }
283 
284     /// Starts collection of debug information.
285     pub fn collect_debug_info(&mut self) {
286         self.dfg.collect_debug_info();
287     }
288 
289     /// Changes the destination of a jump or branch instruction.
290     /// Does nothing if called with a non-jump or non-branch instruction.
291     ///
292     /// Note that this method ignores multi-destination branches like `br_table`.
293     pub fn change_branch_destination(&mut self, inst: Inst, new_dest: Block) {
294         match self.dfg[inst].branch_destination_mut() {
295             None => (),
296             Some(inst_dest) => *inst_dest = new_dest,
297         }
298     }
299 
300     /// Rewrite the branch destination to `new_dest` if the destination matches `old_dest`.
301     /// Does nothing if called with a non-jump or non-branch instruction.
302     ///
303     /// Unlike [change_branch_destination](FunctionStencil::change_branch_destination), this method
304     /// rewrite the destinations of multi-destination branches like `br_table`.
305     pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) {
306         match self.dfg.analyze_branch(inst) {
307             BranchInfo::SingleDest(dest, ..) => {
308                 if dest == old_dest {
309                     self.change_branch_destination(inst, new_dest);
310                 }
311             }
312 
313             BranchInfo::Table(table, default_dest) => {
314                 self.jump_tables[table].iter_mut().for_each(|entry| {
315                     if *entry == old_dest {
316                         *entry = new_dest;
317                     }
318                 });
319 
320                 if default_dest == Some(old_dest) {
321                     match &mut self.dfg[inst] {
322                         InstructionData::BranchTable { destination, .. } => {
323                             *destination = new_dest;
324                         }
325                         _ => panic!(
326                             "Unexpected instruction {} having default destination",
327                             self.dfg.display_inst(inst)
328                         ),
329                     }
330                 }
331             }
332 
333             BranchInfo::NotABranch => {}
334         }
335     }
336 
337     /// Checks that the specified block can be encoded as a basic block.
338     ///
339     /// On error, returns the first invalid instruction and an error message.
340     pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> {
341         let dfg = &self.dfg;
342         let inst_iter = self.layout.block_insts(block);
343 
344         // Ignore all instructions prior to the first branch.
345         let mut inst_iter = inst_iter.skip_while(|&inst| !dfg[inst].opcode().is_branch());
346 
347         // A conditional branch is permitted in a basic block only when followed
348         // by a terminal jump instruction.
349         if let Some(_branch) = inst_iter.next() {
350             if let Some(next) = inst_iter.next() {
351                 match dfg[next].opcode() {
352                     Opcode::Jump => (),
353                     _ => return Err((next, "post-branch instruction not jump")),
354                 }
355             }
356         }
357 
358         Ok(())
359     }
360 
361     /// Returns true if the function is function that doesn't call any other functions. This is not
362     /// to be confused with a "leaf function" in Windows terminology.
363     pub fn is_leaf(&self) -> bool {
364         // Conservative result: if there's at least one function signature referenced in this
365         // function, assume it is not a leaf.
366         self.dfg.signatures.is_empty()
367     }
368 
369     /// Replace the `dst` instruction's data with the `src` instruction's data
370     /// and then remove `src`.
371     ///
372     /// `src` and its result values should not be used at all, as any uses would
373     /// be left dangling after calling this method.
374     ///
375     /// `src` and `dst` must have the same number of resulting values, and
376     /// `src`'s i^th value must have the same type as `dst`'s i^th value.
377     pub fn transplant_inst(&mut self, dst: Inst, src: Inst) {
378         debug_assert_eq!(
379             self.dfg.inst_results(dst).len(),
380             self.dfg.inst_results(src).len()
381         );
382         debug_assert!(self
383             .dfg
384             .inst_results(dst)
385             .iter()
386             .zip(self.dfg.inst_results(src))
387             .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b)));
388 
389         self.dfg[dst] = self.dfg[src];
390         self.layout.remove_inst(src);
391     }
392 
393     /// Size occupied by all stack slots associated with this function.
394     ///
395     /// Does not include any padding necessary due to offsets
396     pub fn fixed_stack_size(&self) -> u32 {
397         self.sized_stack_slots.values().map(|ss| ss.size).sum()
398     }
399 
400     /// Returns the list of relative source locations for this function.
401     pub(crate) fn rel_srclocs(&self) -> &SecondaryMap<Inst, RelSourceLoc> {
402         &self.srclocs
403     }
404 }
405 
406 /// Functions can be cloned, but it is not a very fast operation.
407 /// The clone will have all the same entity numbers as the original.
408 #[derive(Clone)]
409 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
410 pub struct Function {
411     /// Name of this function.
412     ///
413     /// Mostly used by `.clif` files, only there for debugging / naming purposes.
414     pub name: UserFuncName,
415 
416     /// All the fields required for compiling a function, independently of details irrelevant to
417     /// compilation and that are stored in the `FunctionParameters` `params` field instead.
418     pub stencil: FunctionStencil,
419 
420     /// All the parameters that can be applied onto the function stencil, that is, that don't
421     /// matter when caching compilation artifacts.
422     pub params: FunctionParameters,
423 }
424 
425 impl core::ops::Deref for Function {
426     type Target = FunctionStencil;
427 
428     fn deref(&self) -> &Self::Target {
429         &self.stencil
430     }
431 }
432 
433 impl core::ops::DerefMut for Function {
434     fn deref_mut(&mut self) -> &mut Self::Target {
435         &mut self.stencil
436     }
437 }
438 
439 impl Function {
440     /// Create a function with the given name and signature.
441     pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self {
442         Self {
443             name,
444             stencil: FunctionStencil {
445                 version_marker: VersionMarker,
446                 signature: sig,
447                 sized_stack_slots: StackSlots::new(),
448                 dynamic_stack_slots: DynamicStackSlots::new(),
449                 global_values: PrimaryMap::new(),
450                 heaps: PrimaryMap::new(),
451                 tables: PrimaryMap::new(),
452                 jump_tables: PrimaryMap::new(),
453                 dfg: DataFlowGraph::new(),
454                 layout: Layout::new(),
455                 srclocs: SecondaryMap::new(),
456                 stack_limit: None,
457             },
458             params: FunctionParameters::new(),
459         }
460     }
461 
462     /// Clear all data structures in this function.
463     pub fn clear(&mut self) {
464         self.stencil.clear();
465         self.params.clear();
466         self.name = UserFuncName::default();
467     }
468 
469     /// Create a new empty, anonymous function with a Fast calling convention.
470     pub fn new() -> Self {
471         Self::with_name_signature(Default::default(), Signature::new(CallConv::Fast))
472     }
473 
474     /// Return an object that can display this function with correct ISA-specific annotations.
475     pub fn display(&self) -> DisplayFunction<'_> {
476         DisplayFunction(self, Default::default())
477     }
478 
479     /// Return an object that can display this function with correct ISA-specific annotations.
480     pub fn display_with<'a>(
481         &'a self,
482         annotations: DisplayFunctionAnnotations<'a>,
483     ) -> DisplayFunction<'a> {
484         DisplayFunction(self, annotations)
485     }
486 
487     /// Sets an absolute source location for the given instruction.
488     ///
489     /// If no base source location has been set yet, records it at the same time.
490     pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc) {
491         let base = self.params.ensure_base_srcloc(srcloc);
492         self.stencil.srclocs[inst] = RelSourceLoc::from_base_offset(base, srcloc);
493     }
494 
495     /// Returns an absolute source location for the given instruction.
496     pub fn srcloc(&self, inst: Inst) -> SourceLoc {
497         let base = self.params.base_srcloc();
498         self.stencil.srclocs[inst].expand(base)
499     }
500 
501     /// Declare a user-defined external function import, to be referenced in `ExtFuncData::User` later.
502     pub fn declare_imported_user_function(
503         &mut self,
504         name: UserExternalName,
505     ) -> UserExternalNameRef {
506         self.params.ensure_user_func_name(name)
507     }
508 
509     /// Declare an external function import.
510     pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef {
511         self.stencil.dfg.ext_funcs.push(data)
512     }
513 }
514 
515 /// Additional annotations for function display.
516 #[derive(Default)]
517 pub struct DisplayFunctionAnnotations<'a> {
518     /// Enable value labels annotations.
519     pub value_ranges: Option<&'a ValueLabelsRanges>,
520 }
521 
522 /// Wrapper type capable of displaying a `Function` with correct ISA annotations.
523 pub struct DisplayFunction<'a>(&'a Function, DisplayFunctionAnnotations<'a>);
524 
525 impl<'a> fmt::Display for DisplayFunction<'a> {
526     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
527         write_function(fmt, self.0)
528     }
529 }
530 
531 impl fmt::Display for Function {
532     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
533         write_function(fmt, self)
534     }
535 }
536 
537 impl fmt::Debug for Function {
538     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
539         write_function(fmt, self)
540     }
541 }
542