diff --git a/src/basic_block.rs b/src/basic_block.rs index 7bed19a3168..e0adc785c45 100644 --- a/src/basic_block.rs +++ b/src/basic_block.rs @@ -275,6 +275,41 @@ impl<'ctx> BasicBlock<'ctx> { unsafe { Some(InstructionValue::new(value)) } } + /// Obtains a instruction based on the name + /// + /// # Example + /// ```rust + /// use inkwell::context::Context; + /// use inkwell::AddressSpace; + /// + /// let context = Context::create(); + /// let module = context.create_module("ret"); + /// let builder = context.create_builder(); + /// + /// let void_type = context.void_type(); + /// let i32_type = context.i32_type(); + /// let i32_ptr_type = i32_type.ptr_type(AddressSpace::default()); + /// + /// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false); + /// let fn_value = module.add_function("ret", fn_type, None); + /// let entry = context.append_basic_block(fn_value, "entry"); + /// builder.position_at_end(entry); + /// + /// let var = builder.build_alloca(i32_type, "some_number"); + /// builder.build_store(var, i32_type.const_int(1 as u64, false)); + /// builder.build_return(None); + /// + /// let block = fn_value.get_first_basic_block().unwrap(); + /// let some_number = block.get_instruction_with_name("some_number"); + /// + /// assert!(some_number.is_some()); + /// assert_eq!( some_number.unwrap().get_name().unwrap().to_str(), Ok("some_number")) + /// ``` + pub fn get_instruction_with_name(self, name: impl AsRef) -> Option> { + let instruction = self.get_first_instruction()?; + instruction.get_instruction_with_name(name) + } + /// Obtains the terminating `InstructionValue` in this `BasicBlock`, if any. A `BasicBlock` must have a terminating instruction to be valid. /// /// # Example diff --git a/src/values/instruction_value.rs b/src/values/instruction_value.rs index 47f44e91c86..9a5ff56d6fe 100644 --- a/src/values/instruction_value.rs +++ b/src/values/instruction_value.rs @@ -150,6 +150,19 @@ impl<'ctx> InstructionValue<'ctx> { } } + /// Get a instruction with it's name + /// + /// Compares against all instructions after self, and self. + pub fn get_instruction_with_name(&self, name:impl AsRef) -> Option> { + let Some(ins_name) = self.get_name() else { + return self.get_next_instruction()?.get_instruction_with_name(name); + }; + if ins_name.to_str() == Ok(name.as_ref()) { + return Some(*self); + } + None + } + /// Set name of the `InstructionValue`. pub fn set_name(&self, name: &str) -> Result<(), &'static str> { if self.get_type().is_void_type() {