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