forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathir.rs
More file actions
1816 lines (1639 loc) · 70.2 KB
/
ir.rs
File metadata and controls
1816 lines (1639 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use alloc::collections::VecDeque;
use core::ops;
use crate::{IndexMap, IndexSet, error::InternalError};
use malachite_bigint::BigInt;
use num_traits::ToPrimitive;
use rustpython_compiler_core::{
OneIndexed, SourceLocation,
bytecode::{
AnyInstruction, Arg, CodeFlags, CodeObject, CodeUnit, CodeUnits, ConstantData,
ExceptionTableEntry, InstrDisplayContext, Instruction, InstructionMetadata, Label, OpArg,
PseudoInstruction, PyCodeLocationInfoKind, encode_exception_table, oparg,
},
varint::{write_signed_varint, write_varint},
};
/// Location info for linetable generation (allows line 0 for RESUME)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LineTableLocation {
line: i32,
end_line: i32,
col: i32,
end_col: i32,
}
/// Metadata for a code unit
// = _PyCompile_CodeUnitMetadata
#[derive(Clone, Debug)]
pub struct CodeUnitMetadata {
pub name: String, // u_name (obj_name)
pub qualname: Option<String>, // u_qualname
pub consts: IndexSet<ConstantData>, // u_consts
pub names: IndexSet<String>, // u_names
pub varnames: IndexSet<String>, // u_varnames
pub cellvars: IndexSet<String>, // u_cellvars
pub freevars: IndexSet<String>, // u_freevars
pub fast_hidden: IndexMap<String, bool>, // u_fast_hidden
pub argcount: u32, // u_argcount
pub posonlyargcount: u32, // u_posonlyargcount
pub kwonlyargcount: u32, // u_kwonlyargcount
pub firstlineno: OneIndexed, // u_firstlineno
}
// use rustpython_parser_core::source_code::{LineNumber, SourceLocation};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct BlockIdx(u32);
impl BlockIdx {
pub const NULL: Self = Self::new(u32::MAX);
/// Creates a new instance of [`BlockIdx`] from a [`u32`].
#[must_use]
pub const fn new(value: u32) -> Self {
Self(value)
}
/// Returns the inner value as a [`usize`].
#[must_use]
pub const fn idx(self) -> usize {
self.0 as usize
}
}
impl From<BlockIdx> for u32 {
fn from(block_idx: BlockIdx) -> Self {
block_idx.0
}
}
impl ops::Index<BlockIdx> for [Block] {
type Output = Block;
fn index(&self, idx: BlockIdx) -> &Block {
&self[idx.idx()]
}
}
impl ops::IndexMut<BlockIdx> for [Block] {
fn index_mut(&mut self, idx: BlockIdx) -> &mut Block {
&mut self[idx.idx()]
}
}
impl ops::Index<BlockIdx> for Vec<Block> {
type Output = Block;
fn index(&self, idx: BlockIdx) -> &Block {
&self[idx.idx()]
}
}
impl ops::IndexMut<BlockIdx> for Vec<Block> {
fn index_mut(&mut self, idx: BlockIdx) -> &mut Block {
&mut self[idx.idx()]
}
}
#[derive(Clone, Copy, Debug)]
pub struct InstructionInfo {
pub instr: AnyInstruction,
pub arg: OpArg,
pub target: BlockIdx,
pub location: SourceLocation,
pub end_location: SourceLocation,
pub except_handler: Option<ExceptHandlerInfo>,
/// Override line number for linetable (e.g., line 0 for module RESUME)
pub lineno_override: Option<i32>,
/// Number of CACHE code units emitted after this instruction
pub cache_entries: u32,
}
/// Exception handler information for an instruction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExceptHandlerInfo {
/// Block to jump to when exception occurs
pub handler_block: BlockIdx,
/// Stack depth at handler entry
pub stack_depth: u32,
/// Whether to push lasti before exception
pub preserve_lasti: bool,
}
// spell-checker:ignore petgraph
// TODO: look into using petgraph for handling blocks and stuff? it's heavier than this, but it
// might enable more analysis/optimizations
#[derive(Debug)]
pub struct Block {
pub instructions: Vec<InstructionInfo>,
pub next: BlockIdx,
// Post-codegen analysis fields (set by label_exception_targets)
/// Whether this block is an exception handler target (b_except_handler)
pub except_handler: bool,
/// Whether to preserve lasti for this handler block (b_preserve_lasti)
pub preserve_lasti: bool,
/// Stack depth at block entry, set by stack depth analysis
pub start_depth: Option<u32>,
/// Whether this block is only reachable via exception table (b_cold)
pub cold: bool,
}
impl Default for Block {
fn default() -> Self {
Self {
instructions: Vec::new(),
next: BlockIdx::NULL,
except_handler: false,
preserve_lasti: false,
start_depth: None,
cold: false,
}
}
}
pub struct CodeInfo {
pub flags: CodeFlags,
pub source_path: String,
pub private: Option<String>, // For private name mangling, mostly for class
pub blocks: Vec<Block>,
pub current_block: BlockIdx,
pub metadata: CodeUnitMetadata,
// For class scopes: attributes accessed via self.X
pub static_attributes: Option<IndexSet<String>>,
// True if compiling an inlined comprehension
pub in_inlined_comp: bool,
// Block stack for tracking nested control structures
pub fblock: Vec<crate::compile::FBlockInfo>,
// Reference to the symbol table for this scope
pub symbol_table_index: usize,
// PEP 649: Track nesting depth inside conditional blocks (if/for/while/etc.)
// u_in_conditional_block
pub in_conditional_block: u32,
// PEP 649: Next index for conditional annotation tracking
// u_next_conditional_annotation_index
pub next_conditional_annotation_index: u32,
}
impl CodeInfo {
pub fn finalize_code(
mut self,
opts: &crate::compile::CompileOpts,
) -> crate::InternalResult<CodeObject> {
// Always fold tuple constants
self.fold_tuple_constants();
// Python only applies LOAD_SMALL_INT conversion to module-level code
// (not inside functions). Module code lacks OPTIMIZED flag.
// Note: RustPython incorrectly sets NEWLOCALS on modules, so only check OPTIMIZED
let is_module_level = !self.flags.contains(CodeFlags::OPTIMIZED);
if is_module_level {
self.convert_to_load_small_int();
}
self.remove_unused_consts();
self.remove_nops();
if opts.optimize > 0 {
self.dce();
self.peephole_optimize();
}
// Always apply LOAD_FAST_BORROW optimization
self.optimize_load_fast_borrow();
// Post-codegen CFG analysis passes (flowgraph.c pipeline)
mark_except_handlers(&mut self.blocks);
label_exception_targets(&mut self.blocks);
push_cold_blocks_to_end(&mut self.blocks);
normalize_jumps(&mut self.blocks);
self.optimize_load_global_push_null();
let max_stackdepth = self.max_stackdepth()?;
let cell2arg = self.cell2arg();
let Self {
flags,
source_path,
private: _, // private is only used during compilation
mut blocks,
current_block: _,
metadata,
static_attributes: _,
in_inlined_comp: _,
fblock: _,
symbol_table_index: _,
in_conditional_block: _,
next_conditional_annotation_index: _,
} = self;
let CodeUnitMetadata {
name: obj_name,
qualname,
consts: constants,
names: name_cache,
varnames: varname_cache,
cellvars: cellvar_cache,
freevars: freevar_cache,
fast_hidden: _,
argcount: arg_count,
posonlyargcount: posonlyarg_count,
kwonlyargcount: kwonlyarg_count,
firstlineno: first_line_number,
} = metadata;
let mut instructions = Vec::new();
let mut locations = Vec::new();
let mut linetable_locations: Vec<LineTableLocation> = Vec::new();
// Convert pseudo ops and remove resulting NOPs (keep line-marker NOPs)
convert_pseudo_ops(&mut blocks, varname_cache.len() as u32);
// Remove redundant NOPs, keeping line-marker NOPs only when
// they are needed to preserve tracing.
let mut block_order = Vec::new();
let mut current = BlockIdx(0);
while current != BlockIdx::NULL {
block_order.push(current);
current = blocks[current.idx()].next;
}
for block_idx in block_order {
let bi = block_idx.idx();
let mut src_instructions = core::mem::take(&mut blocks[bi].instructions);
let mut kept = Vec::with_capacity(src_instructions.len());
let mut prev_lineno = -1i32;
for src in 0..src_instructions.len() {
let instr = src_instructions[src];
let lineno = instr
.lineno_override
.unwrap_or_else(|| instr.location.line.get() as i32);
let mut remove = false;
if matches!(instr.instr.real(), Some(Instruction::Nop)) {
// Remove location-less NOPs.
if lineno < 0 || prev_lineno == lineno {
remove = true;
}
// Remove if the next instruction has same line or no line.
else if src < src_instructions.len() - 1 {
let next_lineno =
src_instructions[src + 1]
.lineno_override
.unwrap_or_else(|| {
src_instructions[src + 1].location.line.get() as i32
});
if next_lineno == lineno {
remove = true;
} else if next_lineno < 0 {
src_instructions[src + 1].lineno_override = Some(lineno);
remove = true;
}
}
// Last instruction in block: compare with first real location
// in the next non-empty block.
else {
let mut next = blocks[bi].next;
while next != BlockIdx::NULL && blocks[next.idx()].instructions.is_empty() {
next = blocks[next.idx()].next;
}
if next != BlockIdx::NULL {
let mut next_lineno = None;
for next_instr in &blocks[next.idx()].instructions {
let line = next_instr
.lineno_override
.unwrap_or_else(|| next_instr.location.line.get() as i32);
if matches!(next_instr.instr.real(), Some(Instruction::Nop))
&& line < 0
{
continue;
}
next_lineno = Some(line);
break;
}
if next_lineno.is_some_and(|line| line == lineno) {
remove = true;
}
}
}
}
if !remove {
kept.push(instr);
prev_lineno = lineno;
}
}
blocks[bi].instructions = kept;
}
// Pre-compute cache_entries for real (non-pseudo) instructions
for block in blocks.iter_mut() {
for instr in &mut block.instructions {
if let AnyInstruction::Real(op) = instr.instr {
instr.cache_entries = op.cache_entries() as u32;
}
}
}
let mut block_to_offset = vec![Label(0); blocks.len()];
// block_to_index: maps block idx to instruction index (for exception table)
// This is the index into the final instructions array, including EXTENDED_ARG and CACHE
let mut block_to_index = vec![0u32; blocks.len()];
// The offset (in code units) of END_SEND from SEND in the yield-from sequence.
const END_SEND_OFFSET: u32 = 5;
loop {
let mut num_instructions = 0;
for (idx, block) in iter_blocks(&blocks) {
block_to_offset[idx.idx()] = Label(num_instructions as u32);
// block_to_index uses the same value as block_to_offset but as u32
// because lasti in frame.rs is the index into instructions array
// and instructions array index == byte offset (each instruction is 1 CodeUnit)
block_to_index[idx.idx()] = num_instructions as u32;
for instr in &block.instructions {
num_instructions += instr.arg.instr_size() + instr.cache_entries as usize;
}
}
instructions.reserve_exact(num_instructions);
locations.reserve_exact(num_instructions);
let mut recompile = false;
let mut next_block = BlockIdx(0);
while next_block != BlockIdx::NULL {
let block = &mut blocks[next_block];
// Track current instruction offset for jump direction resolution
let mut current_offset = block_to_offset[next_block.idx()].0;
for info in &mut block.instructions {
let target = info.target;
let mut op = info.instr.expect_real();
let old_arg_size = info.arg.instr_size();
let old_cache_entries = info.cache_entries;
// Keep offsets fixed within this pass: changes in jump
// arg/cache sizes only take effect in the next iteration.
let offset_after = current_offset + old_arg_size as u32 + old_cache_entries;
if target != BlockIdx::NULL {
let target_offset = block_to_offset[target.idx()].0;
// Direction must be based on concrete instruction offsets.
// Empty blocks can share offsets, so block-order-based resolution
// may classify some jumps incorrectly.
op = match op {
Instruction::JumpForward { .. } if target_offset <= current_offset => {
Instruction::JumpBackward {
delta: Arg::marker(),
}
}
Instruction::JumpBackward { .. } if target_offset > current_offset => {
Instruction::JumpForward {
delta: Arg::marker(),
}
}
Instruction::JumpBackwardNoInterrupt { .. }
if target_offset > current_offset =>
{
Instruction::JumpForward {
delta: Arg::marker(),
}
}
_ => op,
};
info.instr = op.into();
let updated_cache = op.cache_entries() as u32;
recompile |= updated_cache != old_cache_entries;
info.cache_entries = updated_cache;
let new_arg = if matches!(op, Instruction::EndAsyncFor) {
let arg = offset_after
.checked_sub(target_offset + END_SEND_OFFSET)
.expect("END_ASYNC_FOR target must be before instruction");
OpArg::new(arg)
} else if matches!(
op,
Instruction::JumpBackward { .. }
| Instruction::JumpBackwardNoInterrupt { .. }
) {
let arg = offset_after
.checked_sub(target_offset)
.expect("backward jump target must be before instruction");
OpArg::new(arg)
} else {
let arg = target_offset
.checked_sub(offset_after)
.expect("forward jump target must be after instruction");
OpArg::new(arg)
};
recompile |= new_arg.instr_size() != old_arg_size;
info.arg = new_arg;
}
let cache_count = info.cache_entries as usize;
let (extras, lo_arg) = info.arg.split();
locations.extend(core::iter::repeat_n(
(info.location, info.end_location),
info.arg.instr_size() + cache_count,
));
// Collect linetable locations with lineno_override support
let lt_loc = LineTableLocation {
line: info
.lineno_override
.unwrap_or_else(|| info.location.line.get() as i32),
end_line: info.end_location.line.get() as i32,
col: info.location.character_offset.to_zero_indexed() as i32,
end_col: info.end_location.character_offset.to_zero_indexed() as i32,
};
linetable_locations.extend(core::iter::repeat_n(lt_loc, info.arg.instr_size()));
// CACHE entries inherit parent instruction's location
if cache_count > 0 {
linetable_locations.extend(core::iter::repeat_n(lt_loc, cache_count));
}
instructions.extend(
extras
.map(|byte| CodeUnit::new(Instruction::ExtendedArg, byte))
.chain([CodeUnit { op, arg: lo_arg }]),
);
// Emit CACHE code units after the instruction (all zeroed)
if cache_count > 0 {
instructions.extend(core::iter::repeat_n(
CodeUnit::new(Instruction::Cache, 0.into()),
cache_count,
));
}
current_offset = offset_after;
}
next_block = block.next;
}
if !recompile {
break;
}
instructions.clear();
locations.clear();
linetable_locations.clear();
}
// Generate linetable from linetable_locations (supports line 0 for RESUME)
let linetable = generate_linetable(
&linetable_locations,
first_line_number.get() as i32,
opts.debug_ranges,
);
// Generate exception table before moving source_path
let exceptiontable = generate_exception_table(&blocks, &block_to_index);
Ok(CodeObject {
flags,
posonlyarg_count,
arg_count,
kwonlyarg_count,
source_path,
first_line_number: Some(first_line_number),
obj_name: obj_name.clone(),
qualname: qualname.unwrap_or(obj_name),
max_stackdepth,
instructions: CodeUnits::from(instructions),
locations: locations.into_boxed_slice(),
constants: constants.into_iter().collect(),
names: name_cache.into_iter().collect(),
varnames: varname_cache.into_iter().collect(),
cellvars: cellvar_cache.into_iter().collect(),
freevars: freevar_cache.into_iter().collect(),
cell2arg,
linetable,
exceptiontable,
})
}
fn cell2arg(&self) -> Option<Box<[i32]>> {
if self.metadata.cellvars.is_empty() {
return None;
}
let total_args = self.metadata.argcount
+ self.metadata.kwonlyargcount
+ self.flags.contains(CodeFlags::VARARGS) as u32
+ self.flags.contains(CodeFlags::VARKEYWORDS) as u32;
let mut found_cellarg = false;
let cell2arg = self
.metadata
.cellvars
.iter()
.map(|var| {
self.metadata
.varnames
.get_index_of(var)
// check that it's actually an arg
.filter(|i| *i < total_args as usize)
.map_or(-1, |i| {
found_cellarg = true;
i as i32
})
})
.collect::<Box<[_]>>();
if found_cellarg { Some(cell2arg) } else { None }
}
fn dce(&mut self) {
for block in &mut self.blocks {
let mut last_instr = None;
for (i, ins) in block.instructions.iter().enumerate() {
if ins.instr.is_scope_exit() || ins.instr.is_unconditional_jump() {
last_instr = Some(i);
break;
}
}
if let Some(i) = last_instr {
block.instructions.truncate(i + 1);
}
}
}
/// Constant folding: fold LOAD_CONST/LOAD_SMALL_INT + BUILD_TUPLE into LOAD_CONST tuple
/// fold_tuple_of_constants
fn fold_tuple_constants(&mut self) {
for block in &mut self.blocks {
let mut i = 0;
while i < block.instructions.len() {
let instr = &block.instructions[i];
// Look for BUILD_TUPLE
let Some(Instruction::BuildTuple { .. }) = instr.instr.real() else {
i += 1;
continue;
};
let tuple_size = u32::from(instr.arg) as usize;
if tuple_size == 0 || i < tuple_size {
i += 1;
continue;
}
// Check if all preceding instructions are constant-loading
let start_idx = i - tuple_size;
let mut elements = Vec::with_capacity(tuple_size);
let mut all_const = true;
for j in start_idx..i {
let load_instr = &block.instructions[j];
match load_instr.instr.real() {
Some(Instruction::LoadConst { .. }) => {
let const_idx = u32::from(load_instr.arg) as usize;
if let Some(constant) =
self.metadata.consts.get_index(const_idx).cloned()
{
elements.push(constant);
} else {
all_const = false;
break;
}
}
Some(Instruction::LoadSmallInt { .. }) => {
// arg is the i32 value stored as u32 (two's complement)
let value = u32::from(load_instr.arg) as i32;
elements.push(ConstantData::Integer {
value: BigInt::from(value),
});
}
_ => {
all_const = false;
break;
}
}
}
if !all_const {
i += 1;
continue;
}
// Note: The first small int is added to co_consts during compilation
// (in compile_default_arguments).
// We don't need to add it here again.
// Create tuple constant and add to consts
let tuple_const = ConstantData::Tuple { elements };
let (const_idx, _) = self.metadata.consts.insert_full(tuple_const);
// Replace preceding LOAD instructions with NOP at the
// BUILD_TUPLE location so remove_nops() can eliminate them.
let folded_loc = block.instructions[i].location;
for j in start_idx..i {
block.instructions[j].instr = Instruction::Nop.into();
block.instructions[j].location = folded_loc;
}
// Replace BUILD_TUPLE with LOAD_CONST
block.instructions[i].instr = Instruction::LoadConst {
consti: Arg::marker(),
}
.into();
block.instructions[i].arg = OpArg::new(const_idx as u32);
i += 1;
}
}
}
/// Peephole optimization: combine consecutive instructions into super-instructions
fn peephole_optimize(&mut self) {
for block in &mut self.blocks {
let mut i = 0;
while i + 1 < block.instructions.len() {
let combined = {
let curr = &block.instructions[i];
let next = &block.instructions[i + 1];
// Only combine if both are real instructions (not pseudo)
let (Some(curr_instr), Some(next_instr)) =
(curr.instr.real(), next.instr.real())
else {
i += 1;
continue;
};
match (curr_instr, next_instr) {
// LoadFast + LoadFast -> LoadFastLoadFast (if both indices < 16)
(Instruction::LoadFast { .. }, Instruction::LoadFast { .. }) => {
let idx1 = u32::from(curr.arg);
let idx2 = u32::from(next.arg);
if idx1 < 16 && idx2 < 16 {
let packed = (idx1 << 4) | idx2;
Some((
Instruction::LoadFastLoadFast {
var_nums: Arg::marker(),
},
OpArg::new(packed),
))
} else {
None
}
}
// StoreFast + StoreFast -> StoreFastStoreFast (if both indices < 16)
(Instruction::StoreFast { .. }, Instruction::StoreFast { .. }) => {
let idx1 = u32::from(curr.arg);
let idx2 = u32::from(next.arg);
if idx1 < 16 && idx2 < 16 {
let packed = (idx1 << 4) | idx2;
Some((
Instruction::StoreFastStoreFast {
var_nums: Arg::marker(),
},
OpArg::new(packed),
))
} else {
None
}
}
(Instruction::LoadConst { consti }, Instruction::ToBool) => {
let consti = consti.get(curr.arg);
let constant = &self.metadata.consts[consti.as_usize()];
if let ConstantData::Boolean { .. } = constant {
Some((curr_instr, OpArg::from(consti.as_u32())))
} else {
None
}
}
(Instruction::LoadConst { consti }, Instruction::UnaryNot) => {
let constant = &self.metadata.consts[consti.get(curr.arg).as_usize()];
match constant {
ConstantData::Boolean { value } => {
let (const_idx, _) = self
.metadata
.consts
.insert_full(ConstantData::Boolean { value: !value });
Some((
(Instruction::LoadConst {
consti: Arg::marker(),
}),
OpArg::new(const_idx as u32),
))
}
_ => None,
}
}
_ => None,
}
};
if let Some((new_instr, new_arg)) = combined {
// Combine: keep first instruction's location, replace with combined instruction
block.instructions[i].instr = new_instr.into();
block.instructions[i].arg = new_arg;
// Remove the second instruction
block.instructions.remove(i + 1);
// Don't increment i - check if we can combine again with the next instruction
} else {
i += 1;
}
}
}
}
/// LOAD_GLOBAL <even> + PUSH_NULL -> LOAD_GLOBAL <odd>, NOP
fn optimize_load_global_push_null(&mut self) {
for block in &mut self.blocks {
let mut i = 0;
while i + 1 < block.instructions.len() {
let curr = &block.instructions[i];
let next = &block.instructions[i + 1];
let (Some(Instruction::LoadGlobal { .. }), Some(Instruction::PushNull)) =
(curr.instr.real(), next.instr.real())
else {
i += 1;
continue;
};
let oparg = u32::from(block.instructions[i].arg);
if (oparg & 1) != 0 {
i += 1;
continue;
}
block.instructions[i].arg = OpArg::new(oparg | 1);
block.instructions.remove(i + 1);
}
}
}
/// Convert LOAD_CONST for small integers to LOAD_SMALL_INT
/// maybe_instr_make_load_smallint
fn convert_to_load_small_int(&mut self) {
for block in &mut self.blocks {
for instr in &mut block.instructions {
// Check if it's a LOAD_CONST instruction
let Some(Instruction::LoadConst { .. }) = instr.instr.real() else {
continue;
};
// Get the constant value
let const_idx = u32::from(instr.arg) as usize;
let Some(constant) = self.metadata.consts.get_index(const_idx) else {
continue;
};
// Check if it's a small integer
let ConstantData::Integer { value } = constant else {
continue;
};
// Check if it's in small int range: -5 to 256 (_PY_IS_SMALL_INT)
if let Some(small) = value.to_i32().filter(|v| (-5..=256).contains(v)) {
// Convert LOAD_CONST to LOAD_SMALL_INT
instr.instr = Instruction::LoadSmallInt { i: Arg::marker() }.into();
// The arg is the i32 value stored as u32 (two's complement)
instr.arg = OpArg::new(small as u32);
}
}
}
}
/// Remove constants that are no longer referenced by LOAD_CONST instructions.
/// remove_unused_consts
fn remove_unused_consts(&mut self) {
let nconsts = self.metadata.consts.len();
if nconsts == 0 {
return;
}
// Mark used constants
// The first constant (index 0) is always kept (may be docstring)
let mut used = vec![false; nconsts];
used[0] = true;
for block in &self.blocks {
for instr in &block.instructions {
if let Some(Instruction::LoadConst { .. }) = instr.instr.real() {
let idx = u32::from(instr.arg) as usize;
if idx < nconsts {
used[idx] = true;
}
}
}
}
// Check if any constants can be removed
let n_used: usize = used.iter().filter(|&&u| u).count();
if n_used == nconsts {
return; // Nothing to remove
}
// Build old_to_new index mapping
let mut old_to_new = vec![0usize; nconsts];
let mut new_idx = 0usize;
for (old_idx, &is_used) in used.iter().enumerate() {
if is_used {
old_to_new[old_idx] = new_idx;
new_idx += 1;
}
}
// Build new consts list
let old_consts: Vec<_> = self.metadata.consts.iter().cloned().collect();
self.metadata.consts.clear();
for (old_idx, constant) in old_consts.into_iter().enumerate() {
if used[old_idx] {
self.metadata.consts.insert(constant);
}
}
// Update LOAD_CONST instruction arguments
for block in &mut self.blocks {
for instr in &mut block.instructions {
if let Some(Instruction::LoadConst { .. }) = instr.instr.real() {
let old_idx = u32::from(instr.arg) as usize;
if old_idx < nconsts {
instr.arg = OpArg::new(old_to_new[old_idx] as u32);
}
}
}
}
}
/// Remove NOP instructions from all blocks, but keep NOPs that introduce
/// a new source line (they serve as line markers for monitoring LINE events).
fn remove_nops(&mut self) {
for block in &mut self.blocks {
let mut prev_line = None;
block.instructions.retain(|ins| {
if matches!(ins.instr.real(), Some(Instruction::Nop)) {
let line = ins.location.line;
if prev_line == Some(line) {
return false;
}
}
prev_line = Some(ins.location.line);
true
});
}
}
/// Optimize LOAD_FAST to LOAD_FAST_BORROW where safe.
///
/// A LOAD_FAST can be converted to LOAD_FAST_BORROW if its value is
/// consumed within the same basic block (not passed to another block).
/// This is a reference counting optimization in CPython; in RustPython
/// we implement it for bytecode compatibility.
fn optimize_load_fast_borrow(&mut self) {
// NOT_LOCAL marker: instruction didn't come from a LOAD_FAST
const NOT_LOCAL: usize = usize::MAX;
for block in &mut self.blocks {
if block.instructions.is_empty() {
continue;
}
// Track which instructions' outputs are still on stack at block end
// For each instruction, we track if its pushed value(s) are unconsumed
let mut unconsumed = vec![false; block.instructions.len()];
// Simulate stack: each entry is the instruction index that pushed it
// (or NOT_LOCAL if not from LOAD_FAST/LOAD_FAST_LOAD_FAST).
//
// CPython (flowgraph.c optimize_load_fast) pre-fills the stack with
// dummy refs for values inherited from predecessor blocks. We take
// the simpler approach of aborting the optimisation for the whole
// block on stack underflow.
let mut stack: Vec<usize> = Vec::new();
let mut underflow = false;
for (i, info) in block.instructions.iter().enumerate() {
let Some(instr) = info.instr.real() else {
continue;
};
let stack_effect_info = instr.stack_effect_info(info.arg.into());
let (pushes, pops) = (stack_effect_info.pushed(), stack_effect_info.popped());
// Pop values from stack
for _ in 0..pops {
if stack.pop().is_none() {
// Stack underflow — block receives values from a predecessor.
// Abort optimisation for the entire block.
underflow = true;
break;
}
}
if underflow {
break;
}
// Push values to stack with source instruction index
let source = match instr {
Instruction::LoadFast { .. } | Instruction::LoadFastLoadFast { .. } => i,
_ => NOT_LOCAL,
};
for _ in 0..pushes {
stack.push(source);
}
}
if underflow {
continue;
}
// Mark instructions whose values remain on stack at block end
for &src in &stack {
if src != NOT_LOCAL {
unconsumed[src] = true;
}
}
// Convert LOAD_FAST to LOAD_FAST_BORROW where value is fully consumed
for (i, info) in block.instructions.iter_mut().enumerate() {
if unconsumed[i] {
continue;
}
let Some(instr) = info.instr.real() else {
continue;
};
match instr {
Instruction::LoadFast { .. } => {
info.instr = Instruction::LoadFastBorrow {
var_num: Arg::marker(),
}
.into();
}
Instruction::LoadFastLoadFast { .. } => {
info.instr = Instruction::LoadFastBorrowLoadFastBorrow {
var_nums: Arg::marker(),
}
.into();
}
_ => {}
}
}
}
}
fn max_stackdepth(&mut self) -> crate::InternalResult<u32> {
let mut maxdepth = 0u32;
let mut stack = Vec::with_capacity(self.blocks.len());
let mut start_depths = vec![u32::MAX; self.blocks.len()];
start_depths[0] = 0;
stack.push(BlockIdx(0));
const DEBUG: bool = false;
// Global iteration limit as safety guard
// The algorithm is monotonic (depths only increase), so it should converge quickly.
// Max iterations = blocks * max_possible_depth_increases per block
let max_iterations = self.blocks.len() * 100;
let mut iterations = 0usize;
'process_blocks: while let Some(block_idx) = stack.pop() {
iterations += 1;
if iterations > max_iterations {
// Safety guard: should never happen in valid code
// Return error instead of silently breaking to avoid underestimated stack depth
return Err(InternalError::StackOverflow);
}
let idx = block_idx.idx();
let mut depth = start_depths[idx];
if DEBUG {
eprintln!("===BLOCK {}===", block_idx.0);