1use 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, SigRef, Signature, SourceLocs, StackSlot, StackSlotData, StackSlots,
13 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#[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#[derive(Clone, PartialEq)]
68#[cfg_attr(
69 feature = "enable-serde",
70 derive(serde_derive::Serialize, serde_derive::Deserialize)
71)]
72pub struct FunctionParameters {
73 base_srcloc: Option<SourceLoc>,
76
77 user_named_funcs: PrimaryMap<UserExternalNameRef, UserExternalName>,
79
80 user_ext_name_to_ref: HashMap<UserExternalName, UserExternalNameRef>,
82}
83
84impl FunctionParameters {
85 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 pub fn base_srcloc(&self) -> SourceLoc {
99 self.base_srcloc.unwrap_or_default()
100 }
101
102 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 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 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 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#[derive(Clone, PartialEq, Hash)]
153#[cfg_attr(
154 feature = "enable-serde",
155 derive(serde_derive::Serialize, serde_derive::Deserialize)
156)]
157pub struct FunctionStencil {
158 pub version_marker: VersionMarker,
163
164 pub signature: Signature,
166
167 pub sized_stack_slots: StackSlots,
169
170 pub dynamic_stack_slots: DynamicStackSlots,
172
173 pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>,
175
176 pub dfg: DataFlowGraph,
178
179 pub layout: Layout,
181
182 pub srclocs: SourceLocs,
187
188 pub debug_tags: DebugTags,
203
204 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 pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable {
227 self.dfg.jump_tables.push(data)
228 }
229
230 pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot {
233 self.sized_stack_slots.push(data)
234 }
235
236 pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot {
239 self.dynamic_stack_slots.push(data)
240 }
241
242 pub fn import_signature(&mut self, signature: Signature) -> SigRef {
244 self.dfg.signatures.push(signature)
245 }
246
247 pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue {
249 self.global_values.push(data)
250 }
251
252 pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue {
254 self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale
255 }
256
257 pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue {
259 let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty;
260 self.get_dyn_scale(dyn_ty)
261 }
262
263 pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> {
265 self.dfg
266 .dynamic_types
267 .get(ty)
268 .unwrap_or_else(|| panic!("Undeclared dynamic vector type: {ty}"))
269 .concrete()
270 }
271
272 pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> {
276 let entry = self.layout.entry_block().expect("Function is empty");
277 self.signature
278 .special_param_index(purpose)
279 .map(|i| self.dfg.block_params(entry)[i])
280 }
281
282 pub fn collect_debug_info(&mut self) {
284 self.dfg.collect_debug_info();
285 }
286
287 pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) {
290 for dest in self.dfg.insts[inst]
291 .branch_destination_mut(&mut self.dfg.jump_tables, &mut self.dfg.exception_tables)
292 {
293 if dest.block(&self.dfg.value_lists) == old_dest {
294 dest.set_block(new_dest, &mut self.dfg.value_lists)
295 }
296 }
297 }
298
299 pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> {
303 let dfg = &self.dfg;
304 let inst_iter = self.layout.block_insts(block);
305
306 let mut inst_iter = inst_iter.skip_while(|&inst| !dfg.insts[inst].opcode().is_branch());
308
309 if let Some(_branch) = inst_iter.next() {
310 if let Some(next) = inst_iter.next() {
311 return Err((next, "post-terminator instruction"));
312 }
313 }
314
315 Ok(())
316 }
317
318 pub fn block_successors(&self, block: Block) -> impl DoubleEndedIterator<Item = Block> + '_ {
320 self.layout.last_inst(block).into_iter().flat_map(|inst| {
321 self.dfg.insts[inst]
322 .branch_destination(&self.dfg.jump_tables, &self.dfg.exception_tables)
323 .iter()
324 .map(|block| block.block(&self.dfg.value_lists))
325 })
326 }
327
328 pub fn transplant_inst(&mut self, dst: Inst, src: Inst) {
337 debug_assert_eq!(
338 self.dfg.inst_results(dst).len(),
339 self.dfg.inst_results(src).len()
340 );
341 debug_assert!(
342 self.dfg
343 .inst_results(dst)
344 .iter()
345 .zip(self.dfg.inst_results(src))
346 .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b))
347 );
348
349 self.dfg.insts[dst] = self.dfg.insts[src];
350 self.layout.remove_inst(src);
351 }
352
353 pub fn fixed_stack_size(&self) -> u32 {
357 self.sized_stack_slots.values().map(|ss| ss.size).sum()
358 }
359
360 pub(crate) fn rel_srclocs(&self) -> &SecondaryMap<Inst, RelSourceLoc> {
362 &self.srclocs
363 }
364}
365
366#[derive(Clone, PartialEq)]
369#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
370pub struct Function {
371 pub name: UserFuncName,
375
376 pub stencil: FunctionStencil,
379
380 pub params: FunctionParameters,
383}
384
385impl core::ops::Deref for Function {
386 type Target = FunctionStencil;
387
388 fn deref(&self) -> &Self::Target {
389 &self.stencil
390 }
391}
392
393impl core::ops::DerefMut for Function {
394 fn deref_mut(&mut self) -> &mut Self::Target {
395 &mut self.stencil
396 }
397}
398
399impl Function {
400 pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self {
402 Self {
403 name,
404 stencil: FunctionStencil {
405 version_marker: VersionMarker,
406 signature: sig,
407 sized_stack_slots: StackSlots::new(),
408 dynamic_stack_slots: DynamicStackSlots::new(),
409 global_values: PrimaryMap::new(),
410 dfg: DataFlowGraph::new(),
411 layout: Layout::new(),
412 srclocs: SecondaryMap::new(),
413 stack_limit: None,
414 debug_tags: DebugTags::default(),
415 },
416 params: FunctionParameters::new(),
417 }
418 }
419
420 pub fn clear(&mut self) {
422 self.stencil.clear();
423 self.params.clear();
424 self.name = UserFuncName::default();
425 }
426
427 pub fn new() -> Self {
429 Self::with_name_signature(Default::default(), Signature::new(CallConv::Fast))
430 }
431
432 pub fn display(&self) -> DisplayFunction<'_> {
434 DisplayFunction(self)
435 }
436
437 pub fn display_spec(&self) -> DisplayFunctionSpec<'_> {
439 DisplayFunctionSpec(self)
440 }
441
442 pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc) {
446 let base = self.params.ensure_base_srcloc(srcloc);
447 self.stencil.srclocs[inst] = RelSourceLoc::from_base_offset(base, srcloc);
448 }
449
450 pub fn srcloc(&self, inst: Inst) -> SourceLoc {
452 let base = self.params.base_srcloc();
453 self.stencil.srclocs[inst].expand(base)
454 }
455
456 pub fn declare_imported_user_function(
458 &mut self,
459 name: UserExternalName,
460 ) -> UserExternalNameRef {
461 self.params.ensure_user_func_name(name)
462 }
463
464 pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef {
466 self.stencil.dfg.ext_funcs.push(data)
467 }
468}
469
470pub struct DisplayFunction<'a>(&'a Function);
472
473impl<'a> fmt::Display for DisplayFunction<'a> {
474 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
475 write_function(fmt, self.0)
476 }
477}
478
479impl fmt::Display for Function {
480 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
481 write_function(fmt, self)
482 }
483}
484
485impl fmt::Debug for Function {
486 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
487 write_function(fmt, self)
488 }
489}
490
491pub struct DisplayFunctionSpec<'a>(&'a Function);
493
494impl<'a> fmt::Display for DisplayFunctionSpec<'a> {
495 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
496 write_function_spec(fmt, self.0)
497 }
498}
499
500impl<'a> fmt::Debug for DisplayFunctionSpec<'a> {
501 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
502 write_function_spec(fmt, self.0)
503 }
504}