Skip to main content

cranelift_codegen/ir/
function.rs

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
6use crate::HashMap;
7use crate::entity::{PrimaryMap, SecondaryMap};
8use crate::ir::DebugTags;
9use crate::ir::{
10    self, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, DynamicStackSlots,
11    DynamicType, ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Inst, JumpTable,
12    JumpTableData, Layout, ReplaceBuilder, SigRef, Signature, SourceLocs, StackSlot, StackSlotData,
13    StackSlots, Type,
14};
15use crate::isa::CallConv;
16use crate::write::{write_function, write_function_spec};
17#[cfg(feature = "enable-serde")]
18use alloc::string::String;
19use core::fmt;
20
21#[cfg(feature = "enable-serde")]
22use serde::de::{Deserializer, Error};
23#[cfg(feature = "enable-serde")]
24use serde::ser::Serializer;
25#[cfg(feature = "enable-serde")]
26use serde::{Deserialize, Serialize};
27
28use super::entities::UserExternalNameRef;
29use super::extname::UserFuncName;
30use super::{RelSourceLoc, SourceLoc, UserExternalName};
31
32/// A version marker used to ensure that serialized clif ir is never deserialized with a
33/// different version of Cranelift.
34#[derive(Default, Copy, Clone, Debug, PartialEq, Hash)]
35pub struct VersionMarker;
36
37#[cfg(feature = "enable-serde")]
38impl Serialize for VersionMarker {
39    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
40    where
41        S: Serializer,
42    {
43        crate::VERSION.serialize(serializer)
44    }
45}
46
47#[cfg(feature = "enable-serde")]
48impl<'de> Deserialize<'de> for VersionMarker {
49    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
50    where
51        D: Deserializer<'de>,
52    {
53        let version = String::deserialize(deserializer)?;
54        if version != crate::VERSION {
55            return Err(D::Error::custom(&format!(
56                "Expected a clif ir function for version {}, found one for version {}",
57                crate::VERSION,
58                version,
59            )));
60        }
61        Ok(VersionMarker)
62    }
63}
64
65/// Function parameters used when creating this function, and that will become applied after
66/// compilation to materialize the final `CompiledCode`.
67#[derive(Clone, PartialEq)]
68#[cfg_attr(
69    feature = "enable-serde",
70    derive(serde_derive::Serialize, serde_derive::Deserialize)
71)]
72pub 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
84impl 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(
154    feature = "enable-serde",
155    derive(serde_derive::Serialize, serde_derive::Deserialize)
156)]
157pub struct FunctionStencil {
158    /// A version marker used to ensure that serialized clif ir is never deserialized with a
159    /// different version of Cranelift.
160    // Note: This must be the first field to ensure that Serde will deserialize it before
161    // attempting to deserialize other fields that are potentially changed between versions.
162    pub version_marker: VersionMarker,
163
164    /// Signature of this function.
165    pub signature: Signature,
166
167    /// Sized stack slots allocated in this function.
168    pub sized_stack_slots: StackSlots,
169
170    /// Dynamic stack slots allocated in this function.
171    pub dynamic_stack_slots: DynamicStackSlots,
172
173    /// Global values referenced.
174    pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>,
175
176    /// Data flow graph containing the primary definition of all instructions, blocks and values.
177    pub dfg: DataFlowGraph,
178
179    /// Layout of blocks and instructions in the function body.
180    pub layout: Layout,
181
182    /// Source locations.
183    ///
184    /// Track the original source location for each instruction. The source locations are not
185    /// interpreted by Cranelift, only preserved.
186    pub srclocs: SourceLocs,
187
188    /// Opaque debug-info tags on sequence-point and call
189    /// instructions.
190    ///
191    /// These tags are not interpreted by Cranelift, and are passed
192    /// through to compilation-result metadata. The only semantic
193    /// structure that Cranelift imposes is that when inlining, it
194    /// prepends the callsite call instruction's tags to the tags on
195    /// inlined instructions.
196    ///
197    /// In order to ensure clarity around guaranteed compiler
198    /// behavior, tags are only permitted on instructions whose
199    /// presence and sequence will remain the same in the compiled
200    /// output: namely, `sequence_point` instructions and ordinary
201    /// call instructions.
202    pub debug_tags: DebugTags,
203
204    /// An optional global value which represents an expression evaluating to
205    /// the stack limit for this function. This `GlobalValue` will be
206    /// interpreted in the prologue, if necessary, to insert a stack check to
207    /// ensure that a trap happens if the stack pointer goes below the
208    /// threshold specified here.
209    pub stack_limit: Option<ir::GlobalValue>,
210}
211
212impl FunctionStencil {
213    fn clear(&mut self) {
214        self.signature.clear(CallConv::Fast);
215        self.sized_stack_slots.clear();
216        self.dynamic_stack_slots.clear();
217        self.global_values.clear();
218        self.dfg.clear();
219        self.layout.clear();
220        self.srclocs.clear();
221        self.debug_tags.clear();
222        self.stack_limit = None;
223    }
224
225    /// Create a `ReplaceBuilder` that will replace `inst` with a new
226    /// instruction in place.
227    ///
228    /// `inst` must be present in the function's layout.
229    pub fn replace(&mut self, inst: Inst) -> ReplaceBuilder<'_> {
230        ReplaceBuilder::new(&mut self.dfg, &mut self.layout, inst)
231    }
232
233    /// Creates a jump table in the function, to be used by `br_table` instructions.
234    pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable {
235        self.dfg.jump_tables.push(data)
236    }
237
238    /// Creates a sized stack slot in the function, to be used by `stack_load`, `stack_store`
239    /// and `stack_addr` instructions.
240    pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot {
241        self.sized_stack_slots.push(data)
242    }
243
244    /// Creates a dynamic stack slot in the function, to be used by `dynamic_stack_load`,
245    /// `dynamic_stack_store` and `dynamic_stack_addr` instructions.
246    pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot {
247        self.dynamic_stack_slots.push(data)
248    }
249
250    /// Adds a signature which can later be used to declare an external function import.
251    pub fn import_signature(&mut self, signature: Signature) -> SigRef {
252        self.dfg.signatures.push(signature)
253    }
254
255    /// Declares a global value accessible to the function.
256    pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue {
257        self.global_values.push(data)
258    }
259
260    /// Find the global dyn_scale value associated with given DynamicType.
261    pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue {
262        self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale
263    }
264
265    /// Find the global dyn_scale for the given stack slot.
266    pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue {
267        let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty;
268        self.get_dyn_scale(dyn_ty)
269    }
270
271    /// Get a concrete `Type` from a user defined `DynamicType`.
272    pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> {
273        self.dfg
274            .dynamic_types
275            .get(ty)
276            .unwrap_or_else(|| panic!("Undeclared dynamic vector type: {ty}"))
277            .concrete()
278    }
279
280    /// Find a presumed unique special-purpose function parameter value.
281    ///
282    /// Returns the value of the last `purpose` parameter, or `None` if no such parameter exists.
283    pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> {
284        let entry = self.layout.entry_block().expect("Function is empty");
285        self.signature
286            .special_param_index(purpose)
287            .map(|i| self.dfg.block_params(entry)[i])
288    }
289
290    /// Starts collection of debug information.
291    pub fn collect_debug_info(&mut self) {
292        self.dfg.collect_debug_info();
293    }
294
295    /// Rewrite the branch destination to `new_dest` if the destination matches `old_dest`.
296    /// Does nothing if called with a non-jump or non-branch instruction.
297    pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) {
298        for dest in self.dfg.insts[inst]
299            .branch_destination_mut(&mut self.dfg.jump_tables, &mut self.dfg.exception_tables)
300        {
301            if dest.block(&self.dfg.value_lists) == old_dest {
302                dest.set_block(new_dest, &mut self.dfg.value_lists)
303            }
304        }
305    }
306
307    /// Checks that the specified block can be encoded as a basic block.
308    ///
309    /// On error, returns the first invalid instruction and an error message.
310    pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> {
311        let dfg = &self.dfg;
312        let inst_iter = self.layout.block_insts(block);
313
314        // Ignore all instructions prior to the first branch.
315        let mut inst_iter = inst_iter.skip_while(|&inst| !dfg.insts[inst].opcode().is_branch());
316
317        if let Some(_branch) = inst_iter.next() {
318            if let Some(next) = inst_iter.next() {
319                return Err((next, "post-terminator instruction"));
320            }
321        }
322
323        Ok(())
324    }
325
326    /// Returns an iterator over the blocks succeeding the given block.
327    pub fn block_successors(&self, block: Block) -> impl DoubleEndedIterator<Item = Block> + '_ {
328        self.layout.last_inst(block).into_iter().flat_map(|inst| {
329            self.dfg.insts[inst]
330                .branch_destination(&self.dfg.jump_tables, &self.dfg.exception_tables)
331                .iter()
332                .map(|block| block.block(&self.dfg.value_lists))
333        })
334    }
335
336    /// Replace the `dst` instruction's data with the `src` instruction's data
337    /// and then remove `src`.
338    ///
339    /// `src` and its result values should not be used at all, as any uses would
340    /// be left dangling after calling this method.
341    ///
342    /// `src` and `dst` must have the same number of resulting values, and
343    /// `src`'s i^th value must have the same type as `dst`'s i^th value.
344    pub fn transplant_inst(&mut self, dst: Inst, src: Inst) {
345        debug_assert_eq!(
346            self.dfg.inst_results(dst).len(),
347            self.dfg.inst_results(src).len()
348        );
349        debug_assert!(
350            self.dfg
351                .inst_results(dst)
352                .iter()
353                .zip(self.dfg.inst_results(src))
354                .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b))
355        );
356
357        self.dfg.insts[dst] = self.dfg.insts[src];
358        self.layout.remove_inst(src);
359    }
360
361    /// Size occupied by all stack slots associated with this function.
362    ///
363    /// Does not include any padding necessary due to offsets
364    pub fn fixed_stack_size(&self) -> u32 {
365        self.sized_stack_slots.values().map(|ss| ss.size).sum()
366    }
367
368    /// Returns the list of relative source locations for this function.
369    pub(crate) fn rel_srclocs(&self) -> &SecondaryMap<Inst, RelSourceLoc> {
370        &self.srclocs
371    }
372}
373
374/// Functions can be cloned, but it is not a very fast operation.
375/// The clone will have all the same entity numbers as the original.
376#[derive(Clone, PartialEq)]
377#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
378pub struct Function {
379    /// Name of this function.
380    ///
381    /// Mostly used by `.clif` files, only there for debugging / naming purposes.
382    pub name: UserFuncName,
383
384    /// All the fields required for compiling a function, independently of details irrelevant to
385    /// compilation and that are stored in the `FunctionParameters` `params` field instead.
386    pub stencil: FunctionStencil,
387
388    /// All the parameters that can be applied onto the function stencil, that is, that don't
389    /// matter when caching compilation artifacts.
390    pub params: FunctionParameters,
391}
392
393impl core::ops::Deref for Function {
394    type Target = FunctionStencil;
395
396    fn deref(&self) -> &Self::Target {
397        &self.stencil
398    }
399}
400
401impl core::ops::DerefMut for Function {
402    fn deref_mut(&mut self) -> &mut Self::Target {
403        &mut self.stencil
404    }
405}
406
407impl Function {
408    /// Create a function with the given name and signature.
409    pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self {
410        Self {
411            name,
412            stencil: FunctionStencil {
413                version_marker: VersionMarker,
414                signature: sig,
415                sized_stack_slots: StackSlots::new(),
416                dynamic_stack_slots: DynamicStackSlots::new(),
417                global_values: PrimaryMap::new(),
418                dfg: DataFlowGraph::new(),
419                layout: Layout::new(),
420                srclocs: SecondaryMap::new(),
421                stack_limit: None,
422                debug_tags: DebugTags::default(),
423            },
424            params: FunctionParameters::new(),
425        }
426    }
427
428    /// Clear all data structures in this function.
429    pub fn clear(&mut self) {
430        self.stencil.clear();
431        self.params.clear();
432        self.name = UserFuncName::default();
433    }
434
435    /// Create a new empty, anonymous function with a Fast calling convention.
436    pub fn new() -> Self {
437        Self::with_name_signature(Default::default(), Signature::new(CallConv::Fast))
438    }
439
440    /// Return an object that can display this function with correct ISA-specific annotations.
441    pub fn display(&self) -> DisplayFunction<'_> {
442        DisplayFunction(self)
443    }
444
445    /// Return an object that can display this function's name and signature.
446    pub fn display_spec(&self) -> DisplayFunctionSpec<'_> {
447        DisplayFunctionSpec(self)
448    }
449
450    /// Sets an absolute source location for the given instruction.
451    ///
452    /// If no base source location has been set yet, records it at the same time.
453    pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc) {
454        let base = self.params.ensure_base_srcloc(srcloc);
455        self.stencil.srclocs[inst] = RelSourceLoc::from_base_offset(base, srcloc);
456    }
457
458    /// Returns an absolute source location for the given instruction.
459    pub fn srcloc(&self, inst: Inst) -> SourceLoc {
460        let base = self.params.base_srcloc();
461        self.stencil.srclocs[inst].expand(base)
462    }
463
464    /// Declare a user-defined external function import, to be referenced in `ExtFuncData::User` later.
465    pub fn declare_imported_user_function(
466        &mut self,
467        name: UserExternalName,
468    ) -> UserExternalNameRef {
469        self.params.ensure_user_func_name(name)
470    }
471
472    /// Declare an external function import.
473    pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef {
474        self.stencil.dfg.ext_funcs.push(data)
475    }
476}
477
478/// Wrapper type capable of displaying a `Function`.
479pub struct DisplayFunction<'a>(&'a Function);
480
481impl<'a> fmt::Display for DisplayFunction<'a> {
482    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
483        write_function(fmt, self.0)
484    }
485}
486
487impl fmt::Display for Function {
488    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
489        write_function(fmt, self)
490    }
491}
492
493impl fmt::Debug for Function {
494    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
495        write_function(fmt, self)
496    }
497}
498
499/// Wrapper type capable of displaying a 'Function's name and signature.
500pub struct DisplayFunctionSpec<'a>(&'a Function);
501
502impl<'a> fmt::Display for DisplayFunctionSpec<'a> {
503    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
504        write_function_spec(fmt, self.0)
505    }
506}
507
508impl<'a> fmt::Debug for DisplayFunctionSpec<'a> {
509    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
510        write_function_spec(fmt, self.0)
511    }
512}