inkwell icon indicating copy to clipboard operation
inkwell copied to clipboard

The cloned instructions always lose information on their names and parent basic blocks

Open taquangtrung opened this issue 2 years ago • 1 comments

Describe the Bug

I'm implementing the function to find the predecessor blocks of a basic block by looking through the terminator instructions that use the current block.

However, when getting the parent blocks of the found terminator instructions, they always return None, indicating that these terminator instructions do not have a parent.

Below is my code fragment:

fn get_predecessors(&self) -> Vec<BasicBlock<'a>> {
    let mut predecessors = vec![];
    let mut self_use = self.get_first_use();

    while let Some(v) = self_use {
        let self_user = v.get_user();
        if self_user.is_instruction_value() {
            let inst = self_user.into_instruction_value();  // convert the user value into `InstructionValue`
            if let Some(blk) = inst.get_parent() {          // `inst` returns `None` since it's a cloned instruction.
                predecessors.push(blk)
            }
        }
        self_use = v.get_next_use()
    }

    predecessors
}

I found out that the reason is that in the code about, inst, which is obtained from getting users of the current block, and converting them into InstructionValue is a cloned instruction. And according to the implementation of the Clone trait, the cloned instruction is produced by LLVMInstructionClone, hence it does not have a parent

https://github.com/TheDan64/inkwell/blob/064fe096823e82d538a04536064ada7ad7936df5/src/values/instruction_value.rs#L659-L665

impl Clone for InstructionValue<'_> {
    /// Creates a clone of this `InstructionValue`, and returns it.
    /// The clone will have no parent, and no name.
    fn clone(&self) -> Self {
        unsafe { InstructionValue::new(LLVMInstructionClone(self.as_value_ref())) }
    }
}

To Reproduce

The reproduced code is as above.

Expected Behavior

For my application, I expect that the cloned instruction must point to the same parent as the original instruction.

But I'm not sure if this will affect other applications. What is the main reason for the implementation of Clone using LLVMInstructionClone?

So, I'd like to discuss more to find a better implementation for the Clone trait.

LLVM Version (please complete the following information):

  • LLVM Version: 13.0
  • Inkwell Branch Used: 13.0

Desktop (please complete the following information):

  • OS: Linux Mint 20.03

taquangtrung avatar Jun 11 '22 16:06 taquangtrung

I'm not sure I follow - your example code doesn't call Clone on the instruction and neither does into_instruction_value. Where is this clone occurring, exactly?

TheDan64 avatar Jun 17 '22 02:06 TheDan64