MCPcopy Index your code
hub / github.com/RustPython/RustPython / fold_unary_negative

Method fold_unary_negative

crates/codegen/src/ir.rs:653–705  ·  view source on GitHub ↗

Fold LOAD_CONST/LOAD_SMALL_INT + UNARY_NEGATIVE → LOAD_CONST (negative value)

(&mut self)

Source from the content-addressed store, hash-verified

651
652 /// Fold LOAD_CONST/LOAD_SMALL_INT + UNARY_NEGATIVE → LOAD_CONST (negative value)
653 fn fold_unary_negative(&mut self) {
654 for block in &mut self.blocks {
655 let mut i = 0;
656 while i + 1 < block.instructions.len() {
657 let next = &block.instructions[i + 1];
658 let Some(Instruction::UnaryNegative) = next.instr.real() else {
659 i += 1;
660 continue;
661 };
662 let curr = &block.instructions[i];
663 let value = match curr.instr.real() {
664 Some(Instruction::LoadConst { .. }) => {
665 let idx = u32::from(curr.arg) as usize;
666 match self.metadata.consts.get_index(idx) {
667 Some(ConstantData::Integer { value }) => {
668 Some(ConstantData::Integer { value: -value })
669 }
670 Some(ConstantData::Float { value }) => {
671 Some(ConstantData::Float { value: -value })
672 }
673 _ => None,
674 }
675 }
676 Some(Instruction::LoadSmallInt { .. }) => {
677 let v = u32::from(curr.arg) as i32;
678 Some(ConstantData::Integer {
679 value: BigInt::from(-v),
680 })
681 }
682 _ => None,
683 };
684 if let Some(neg_const) = value {
685 let (const_idx, _) = self.metadata.consts.insert_full(neg_const);
686 // Replace LOAD_CONST/LOAD_SMALL_INT with new LOAD_CONST
687 let load_location = block.instructions[i].location;
688 block.instructions[i].instr = Instruction::LoadConst {
689 consti: Arg::marker(),
690 }
691 .into();
692 block.instructions[i].arg = OpArg::new(const_idx as u32);
693 // Replace UNARY_NEGATIVE with NOP, inheriting the LOAD_CONST
694 // location so that remove_nops can clean it up
695 block.instructions[i + 1].instr = Instruction::Nop.into();
696 block.instructions[i + 1].location = load_location;
697 block.instructions[i + 1].end_location = block.instructions[i].end_location;
698 // Skip the NOP, don't re-check
699 i += 2;
700 } else {
701 i += 1;
702 }
703 }
704 }
705 }
706
707 /// Constant folding: fold LOAD_CONST/LOAD_SMALL_INT + LOAD_CONST/LOAD_SMALL_INT + BINARY_OP
708 /// into a single LOAD_CONST when the result is computable at compile time.

Callers 1

finalize_codeMethod · 0.80

Calls 5

newFunction · 0.85
get_indexMethod · 0.80
SomeClass · 0.50
lenMethod · 0.45
realMethod · 0.45

Tested by

no test coverage detected