Skip to main content

sbpf_assembler/optimizer/
mod.rs

1mod canonicalize;
2
3pub(crate) use canonicalize::{
4    canonicalize_control_flow_targets, remove_temp_control_flow_target_labels,
5};
6use {
7    crate::{ast::AST, astnode::ASTNode},
8    sbpf_analyze::remove_dead_functions,
9    sbpf_common::instruction::Instruction,
10    sbpf_ir::{Cfg, CfgRodata, InputNode, control_flow_graph},
11    std::collections::{HashMap, HashSet},
12};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum CfgDumpStage {
16    BeforeDfe,
17    AfterDfe,
18}
19
20impl CfgDumpStage {
21    pub fn file_name(self) -> &'static str {
22        match self {
23            Self::BeforeDfe => "dfe-before.dot",
24            Self::AfterDfe => "dfe-after.dot",
25        }
26    }
27}
28
29/// Runs every CFG optimization on a single CFG built from the AST, then writes
30/// the result back once: dead-function elimination, then the ALU32 extension
31/// and signed division fix-ups.
32pub fn optimize(ast: &mut AST) {
33    optimize_with_observer(ast, |_, _| {});
34}
35
36/// Like [`optimize`], and exposes the CFG before and after dead-function
37/// elimination. The observer owns any optional diagnostics or I/O, keeping the
38/// passes themselves pure.
39pub fn optimize_with_observer<F>(ast: &mut AST, mut observe: F)
40where
41    F: FnMut(CfgDumpStage, &Cfg),
42{
43    let mut cfg = cfg_for_ast(ast);
44    observe(CfgDumpStage::BeforeDfe, &cfg);
45    remove_dead_functions(&mut cfg);
46    observe(CfgDumpStage::AfterDfe, &cfg);
47    sbpf_analyze::fix_alu32_extension(&mut cfg);
48    sbpf_analyze::fix_signed_div(&mut cfg);
49    write_cfg_to_ast(ast, &cfg);
50}
51
52/// Removes functions not reachable from the entry via `call imm`.
53pub fn eliminate_unreachable_functions(ast: &mut AST) {
54    let mut cfg = cfg_for_ast(ast);
55    remove_dead_functions(&mut cfg);
56    write_cfg_to_ast(ast, &cfg);
57}
58
59/// Makes eBPF's ALU32 zero-extension hold under SBPF, where `add32`, `sub32` and
60/// `mul32` sign-extend. Each such instruction is kept, promoted to its 64-bit form,
61/// or zero-extended. Assumes the AST follows eBPF semantics (LLVM output).
62pub fn fix_alu32_extension(ast: &mut AST) {
63    let mut cfg = cfg_for_ast(ast);
64    sbpf_analyze::fix_alu32_extension(&mut cfg);
65    write_cfg_to_ast(ast, &cfg);
66}
67
68/// Builds the CFG for the AST's text section. Each CFG node records the index of
69/// the AST node it came from, which [`write_cfg_to_ast`] uses to map back.
70pub(crate) fn cfg_for_ast(ast: &AST) -> Cfg {
71    let function_entries = function_entries(ast);
72    let entry_label = ast.nodes.iter().find_map(|node| {
73        if let ASTNode::GlobalDecl { global_decl } = node {
74            Some(global_decl.entry_label.as_str())
75        } else {
76            None
77        }
78    });
79    let nodes = ast.nodes.iter().map(|node| match node {
80        ASTNode::Label { label, .. } => InputNode::Label(label.name.as_str()),
81        ASTNode::Instruction { instruction, .. } => InputNode::Instruction(instruction),
82        _ => InputNode::Other,
83    });
84    let mut cfg = control_flow_graph(nodes, &function_entries, entry_label);
85    if !ast.rodata_nodes.is_empty() {
86        let rodata = ast.rodata_nodes.iter().filter_map(|node| {
87            let ASTNode::ROData { rodata, offset } = node else {
88                return None;
89            };
90            Some(CfgRodata::new(&rodata.name, *offset, rodata.get_size()))
91        });
92        let references = ast
93            .rodata_relocations()
94            .iter()
95            .map(|relocation| (relocation.offset, relocation.target.as_str()));
96        cfg.set_rodata(rodata, references);
97    }
98    cfg
99}
100
101/// Writes a CFG built by [`cfg_for_ast`] back into the AST, then recomputes
102/// offsets:
103/// - labels and instructions no longer in the CFG (e.g. removed functions) are
104///   dropped;
105/// - each instruction takes its CFG node's current form, followed by any
106///   instructions a pass inserted after it;
107/// - every other node (e.g. `GlobalDecl`) is kept as is.
108pub(crate) fn write_cfg_to_ast(ast: &mut AST, cfg: &Cfg) {
109    let live: HashSet<usize> = cfg
110        .all_blocks()
111        .flat_map(|(_, block)| block.node_ids().iter().copied())
112        .collect();
113
114    let mut rewritten: HashMap<usize, Vec<Instruction>> = HashMap::new();
115    for (_, block) in cfg.all_blocks() {
116        let mut last_source = None;
117        for node in block.instructions() {
118            let Some(instruction) = node.instruction() else {
119                continue;
120            };
121            match node.source_node_id() {
122                Some(id) => {
123                    rewritten.insert(id, vec![instruction.clone()]);
124                    last_source = Some(id);
125                }
126                None => {
127                    let id = last_source
128                        .expect("inserted instructions follow a source instruction in their block");
129                    rewritten
130                        .get_mut(&id)
131                        .expect("source instruction was recorded")
132                        .push(instruction.clone());
133                }
134            }
135        }
136    }
137
138    ast.nodes = std::mem::take(&mut ast.nodes)
139        .into_iter()
140        .enumerate()
141        .flat_map(|(idx, node)| match node {
142            ASTNode::Label { .. } if !live.contains(&idx) => vec![],
143            ASTNode::Instruction { .. } => rewritten
144                .remove(&idx)
145                .unwrap_or_default()
146                .into_iter()
147                .map(|instruction| ASTNode::Instruction {
148                    instruction,
149                    offset: 0,
150                })
151                .collect(),
152            node => vec![node],
153        })
154        .collect();
155
156    assign_offsets(ast);
157}
158
159/// Recomputes byte offsets for all labels and instructions in the AST from
160/// scratch, in node order. Called after any pass that alters the node list so
161/// there is a single authoritative place that assigns offsets.
162pub fn assign_offsets(ast: &mut AST) {
163    let mut text_offset = 0u64;
164    let mut text_size = 0u64;
165    for node in &mut ast.nodes {
166        match node {
167            ASTNode::Label { offset, .. } => *offset = text_offset,
168            ASTNode::Instruction {
169                instruction,
170                offset,
171            } => {
172                *offset = text_offset;
173                let size = instruction.get_size();
174                text_offset += size;
175                text_size += size;
176            }
177            _ => {}
178        }
179    }
180    ast.set_text_size(text_size);
181}
182
183fn function_entries(ast: &AST) -> HashSet<String> {
184    ast.function_entries().clone()
185}
186
187#[cfg(test)]
188mod tests {
189    use {
190        super::*,
191        crate::{
192            SbpfArch,
193            ast::{OptimizationConfig, build_program},
194            astnode::{GlobalDecl, Label, ROData},
195            parser::Token,
196        },
197        either::Either,
198        sbpf_common::{
199            inst_param::{Number, Register},
200            instruction::Instruction,
201            opcode::Opcode,
202        },
203    };
204
205    #[test]
206    fn test_optimizer_preserves_unreachable_blocks_in_reachable_function() {
207        let mut ast = AST::new();
208        ast.add_function_entry("entrypoint".to_string());
209        ast.nodes = vec![
210            label_node("entrypoint", 0),
211            instruction_node(
212                Opcode::Ja,
213                None,
214                0,
215                Some(Either::Left("target".to_string())),
216            ),
217            instruction_node(Opcode::Mov64Imm, Some(0), 8, None),
218            label_node("target", 16),
219            instruction_node(Opcode::Exit, None, 16, None),
220        ];
221        ast.set_text_size(24);
222
223        eliminate_unreachable_functions(&mut ast);
224
225        assert_eq!(ast.nodes.len(), 5);
226        assert!(matches!(
227            &ast.nodes[1],
228            ASTNode::Instruction { instruction, offset }
229                if instruction.opcode == Opcode::Ja
230                    && instruction.off == Some(Either::Left("target".to_string()))
231                    && *offset == 0
232        ));
233        assert!(matches!(
234            &ast.nodes[2],
235            ASTNode::Instruction { instruction, offset }
236                if instruction.opcode == Opcode::Mov64Imm && *offset == 8
237        ));
238        assert!(matches!(
239            &ast.nodes[3],
240            ASTNode::Label { label, offset } if label.name == "target" && *offset == 16
241        ));
242        assert!(matches!(
243            &ast.nodes[4],
244            ASTNode::Instruction { instruction, offset }
245                if instruction.opcode == Opcode::Exit && *offset == 16
246        ));
247    }
248
249    #[test]
250    fn test_optimizer_removes_uncalled_function_only() {
251        let mut ast = AST::new();
252        ast.add_function_entry("entrypoint".to_string());
253        ast.add_function_entry("dead".to_string());
254        ast.add_function_entry("callee".to_string());
255        ast.nodes = vec![
256            label_node("entrypoint", 0),
257            call_node("callee", 0),
258            instruction_node(Opcode::Exit, None, 8, None),
259            label_node("dead", 16),
260            instruction_node(Opcode::Exit, None, 16, None),
261            label_node("callee", 24),
262            instruction_node(Opcode::Exit, None, 24, None),
263        ];
264        ast.set_text_size(32);
265
266        eliminate_unreachable_functions(&mut ast);
267
268        assert!(
269            !ast.nodes
270                .iter()
271                .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
272        );
273        assert!(
274            ast.nodes
275                .iter()
276                .any(|node| matches!(node, ASTNode::Label { label, offset }
277                if label.name == "callee" && *offset == 16))
278        );
279        assert_eq!(
280            ast.nodes
281                .iter()
282                .filter(|node| matches!(node, ASTNode::Instruction { .. }))
283                .count(),
284            3
285        );
286    }
287
288    #[test]
289    fn test_optimizer_uses_declared_entry_when_it_is_not_first() {
290        let mut ast = AST::new();
291        ast.add_function_entry("helper".to_string());
292        ast.add_function_entry("dead".to_string());
293        ast.add_function_entry("entrypoint".to_string());
294        ast.nodes = vec![
295            ASTNode::GlobalDecl {
296                global_decl: GlobalDecl {
297                    entry_label: "entrypoint".to_string(),
298                    span: 0..0,
299                },
300            },
301            label_node("helper", 0),
302            instruction_node(Opcode::Exit, None, 0, None),
303            label_node("dead", 8),
304            instruction_node(Opcode::Exit, None, 8, None),
305            label_node("entrypoint", 16),
306            call_node("helper", 16),
307            instruction_node(Opcode::Exit, None, 24, None),
308        ];
309        ast.set_text_size(32);
310
311        let cfg = cfg_for_ast(&ast);
312        assert_eq!(cfg.functions()[0].name(), "entrypoint");
313        assert_eq!(cfg.functions()[0].entry_block_id(), Some(2)); // entrypoint is block 2 in source order
314
315        eliminate_unreachable_functions(&mut ast);
316
317        assert!(ast.nodes.iter().any(
318            |node| matches!(node, ASTNode::Label { label, .. } if label.name == "entrypoint")
319        ));
320        assert!(
321            ast.nodes
322                .iter()
323                .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "helper"))
324        );
325        assert!(
326            !ast.nodes
327                .iter()
328                .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
329        );
330    }
331
332    #[test]
333    fn test_optimizer_preserves_function_targeted_by_rodata_relocation() {
334        let mut ast = AST::new();
335        ast.add_function_entry("entrypoint".to_string());
336        ast.add_function_entry("target".to_string());
337        ast.add_function_entry("dead".to_string());
338        ast.nodes = vec![
339            ASTNode::GlobalDecl {
340                global_decl: GlobalDecl {
341                    entry_label: "entrypoint".to_string(),
342                    span: 0..0,
343                },
344            },
345            label_node("entrypoint", 0),
346            instruction_node(Opcode::Exit, None, 0, None),
347            label_node("target", 8),
348            instruction_node(Opcode::Exit, None, 8, None),
349            label_node("dead", 16),
350            instruction_node(Opcode::Exit, None, 16, None),
351        ];
352        ast.rodata_nodes.push(ASTNode::ROData {
353            rodata: ROData {
354                name: "pointer".to_string(),
355                args: vec![
356                    Token::Directive("quad".to_string(), 0..0),
357                    Token::VectorLiteral(vec![Number::Int(0)], 0..0),
358                ],
359                span: 0..0,
360            },
361            offset: 0,
362        });
363        ast.set_text_size(24);
364        ast.set_rodata_size(8);
365        ast.add_rodata_relocation(0, "target".to_string());
366
367        eliminate_unreachable_functions(&mut ast);
368
369        assert!(ast.nodes.iter().any(
370            |node| matches!(node, ASTNode::Label { label, .. } if label.name == "entrypoint")
371        ));
372        assert!(
373            ast.nodes
374                .iter()
375                .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "target"))
376        );
377        assert!(
378            !ast.nodes
379                .iter()
380                .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
381        );
382    }
383
384    #[test]
385    fn test_write_back_drops_dead_functions_and_recomputes_offsets_cumulatively() {
386        let mut ast = AST::new();
387        for name in ["entrypoint", "dead_a", "live", "dead_b", "target"] {
388            ast.add_function_entry(name.to_string());
389        }
390        ast.nodes = vec![
391            label_node("entrypoint", 0),
392            call_node("live", 0),
393            call_node("target", 8),
394            instruction_node(Opcode::Exit, None, 16, None),
395            label_node("dead_a", 24),
396            instruction_node(Opcode::Exit, None, 24, None),
397            label_node("live", 32),
398            instruction_node(Opcode::Exit, None, 32, None),
399            label_node("dead_b", 40),
400            instruction_node(Opcode::Exit, None, 40, None),
401            label_node("target", 48),
402            instruction_node(Opcode::Exit, None, 48, None),
403        ];
404        ast.set_text_size(56);
405
406        eliminate_unreachable_functions(&mut ast);
407
408        assert_eq!(
409            listing(&ast.nodes),
410            [
411                ("entrypoint:".to_string(), 0),
412                ("call".to_string(), 0),
413                ("call".to_string(), 8),
414                ("exit".to_string(), 16),
415                ("live:".to_string(), 24),
416                ("exit".to_string(), 24),
417                ("target:".to_string(), 32),
418                ("exit".to_string(), 32),
419            ]
420        );
421    }
422
423    #[test]
424    fn test_assign_offsets_recomputes_from_scratch() {
425        let mut ast = AST::new();
426        ast.nodes = vec![
427            label_node("entrypoint", 999),
428            instruction_node(Opcode::Exit, None, 999, None),
429            label_node("next", 999),
430            instruction_node(Opcode::Exit, None, 999, None),
431        ];
432
433        assign_offsets(&mut ast);
434
435        assert!(matches!(
436            &ast.nodes[0],
437            ASTNode::Label { label, offset } if label.name == "entrypoint" && *offset == 0
438        ));
439        assert!(matches!(
440            &ast.nodes[1],
441            ASTNode::Instruction { offset, .. } if *offset == 0
442        ));
443        assert!(matches!(
444            &ast.nodes[2],
445            ASTNode::Label { label, offset } if label.name == "next" && *offset == 8
446        ));
447    }
448
449    fn alu_node(opcode: Opcode, dst: u8, src: Option<u8>, imm: Option<i64>) -> ASTNode {
450        ASTNode::Instruction {
451            instruction: Instruction {
452                opcode,
453                dst: Some(Register { n: dst }),
454                src: src.map(|n| Register { n }),
455                off: None,
456                imm: imm.map(|v| Either::Right(Number::Int(v))),
457                span: 0..0,
458            },
459            offset: 0,
460        }
461    }
462
463    /// `add32 r1, r2` whose full 64-bit result is shifted and returned, then a
464    /// later label. The shift reads r1 directly, so the def itself is fixed up.
465    fn alu32_program() -> AST {
466        let mut ast = AST::new();
467        ast.add_function_entry("entrypoint".to_string());
468        ast.nodes = vec![
469            label_node("entrypoint", 0),
470            alu_node(Opcode::Add32Reg, 1, Some(2), None),
471            instruction_node(Opcode::Ja, None, 8, Some(Either::Left("done".to_string()))),
472            label_node("done", 16),
473            alu_node(Opcode::Lsh64Imm, 1, None, Some(1)),
474            alu_node(Opcode::Mov64Reg, 0, Some(1), None),
475            instruction_node(Opcode::Exit, None, 32, None),
476        ];
477        ast.set_text_size(40);
478        ast
479    }
480
481    fn listing(nodes: &[ASTNode]) -> Vec<(String, u64)> {
482        nodes
483            .iter()
484            .filter_map(|node| match node {
485                ASTNode::Label { label, offset } => Some((format!("{}:", label.name), *offset)),
486                ASTNode::Instruction {
487                    instruction,
488                    offset,
489                } => Some((instruction.opcode.to_string(), *offset)),
490                _ => None,
491            })
492            .collect()
493    }
494
495    #[test]
496    fn test_fix_alu32_extension_inserts_fixup_and_reassigns_offsets() {
497        let mut ast = alu32_program();
498
499        fix_alu32_extension(&mut ast);
500
501        assert_eq!(
502            listing(&ast.nodes),
503            [
504                ("entrypoint:".to_string(), 0),
505                ("add32".to_string(), 0),
506                ("mov32".to_string(), 8),
507                ("ja".to_string(), 16),
508                ("done:".to_string(), 24),
509                ("lsh64".to_string(), 24),
510                ("mov64".to_string(), 32),
511                ("exit".to_string(), 40),
512            ]
513        );
514        let ASTNode::Instruction { instruction, .. } = &ast.nodes[2] else {
515            panic!("expected the inserted instruction");
516        };
517        assert_eq!(instruction.opcode, Opcode::Mov32Reg);
518        assert_eq!(instruction.dst, Some(Register { n: 1 }));
519        assert_eq!(instruction.src, Some(Register { n: 1 }));
520    }
521
522    #[test]
523    fn test_fix_alu32_extension_narrows_copy_in_place() {
524        let mut ast = AST::new();
525        ast.add_function_entry("entrypoint".to_string());
526        ast.nodes = vec![
527            label_node("entrypoint", 0),
528            alu_node(Opcode::Add32Reg, 1, Some(2), None),
529            alu_node(Opcode::Mov64Reg, 0, Some(1), None),
530            instruction_node(Opcode::Exit, None, 16, None),
531        ];
532        ast.set_text_size(24);
533
534        fix_alu32_extension(&mut ast);
535
536        assert_eq!(
537            listing(&ast.nodes),
538            [
539                ("entrypoint:".to_string(), 0),
540                ("add32".to_string(), 0),
541                ("mov32".to_string(), 8),
542                ("exit".to_string(), 16),
543            ]
544        );
545        let ASTNode::Instruction { instruction, .. } = &ast.nodes[2] else {
546            panic!("expected the narrowed copy");
547        };
548        assert_eq!(instruction.opcode, Opcode::Mov32Reg);
549        assert_eq!(instruction.dst, Some(Register { n: 0 }));
550        assert_eq!(instruction.src, Some(Register { n: 1 }));
551    }
552
553    #[test]
554    fn test_fix_alu32_extension_promotes_in_place() {
555        let mut ast = AST::new();
556        ast.add_function_entry("entrypoint".to_string());
557        ast.nodes = vec![
558            label_node("entrypoint", 0),
559            alu_node(Opcode::Lddw, 1, None, Some(0x9000_0000)),
560            alu_node(Opcode::Sub32Imm, 1, None, Some(1)),
561            alu_node(Opcode::Mov64Reg, 0, Some(1), None),
562            instruction_node(Opcode::Exit, None, 32, None),
563        ];
564        ast.set_text_size(40);
565
566        fix_alu32_extension(&mut ast);
567
568        assert_eq!(
569            listing(&ast.nodes),
570            [
571                ("entrypoint:".to_string(), 0),
572                ("lddw".to_string(), 0),
573                ("sub64".to_string(), 16),
574                ("mov64".to_string(), 24),
575                ("exit".to_string(), 32),
576            ]
577        );
578    }
579
580    #[test]
581    fn test_fix_alu32_extension_leaves_unaffected_program_untouched() {
582        let mut ast = AST::new();
583        ast.add_function_entry("entrypoint".to_string());
584        ast.nodes = vec![
585            label_node("entrypoint", 0),
586            alu_node(Opcode::Add32Reg, 1, Some(2), None),
587            alu_node(Opcode::Mov32Reg, 0, Some(1), None),
588            instruction_node(Opcode::Exit, None, 16, None),
589        ];
590        assign_offsets(&mut ast);
591        let before = listing(&ast.nodes);
592
593        fix_alu32_extension(&mut ast);
594
595        assert_eq!(listing(&ast.nodes), before);
596    }
597
598    #[test]
599    fn test_build_program_runs_fixup_only_when_optimizing() {
600        for arch in [SbpfArch::V0, SbpfArch::V3] {
601            let disabled =
602                build_program(alu32_program(), arch, OptimizationConfig::disabled()).unwrap();
603            assert!(
604                !listing(disabled.code_section.get_nodes())
605                    .iter()
606                    .any(|(op, _)| op == "mov32"),
607                "{arch:?}: disabled must not rewrite"
608            );
609
610            let enabled =
611                build_program(alu32_program(), arch, OptimizationConfig::enabled()).unwrap();
612            let ops: Vec<String> = listing(enabled.code_section.get_nodes())
613                .into_iter()
614                .map(|(op, _)| op)
615                .collect();
616            assert_eq!(
617                ops,
618                [
619                    "entrypoint:",
620                    "add32",
621                    "mov32",
622                    "ja",
623                    "done:",
624                    "lsh64",
625                    "mov64",
626                    "exit"
627                ],
628                "{arch:?}"
629            );
630        }
631    }
632
633    fn label_node(name: &str, offset: u64) -> ASTNode {
634        ASTNode::Label {
635            label: Label {
636                name: name.to_string(),
637                span: 0..0,
638            },
639            offset,
640        }
641    }
642
643    fn instruction_node(
644        opcode: Opcode,
645        dst: Option<u8>,
646        offset: u64,
647        off: Option<Either<String, i16>>,
648    ) -> ASTNode {
649        ASTNode::Instruction {
650            instruction: Instruction {
651                opcode,
652                dst: dst.map(|n| Register { n }),
653                src: None,
654                off,
655                imm: None,
656                span: 0..0,
657            },
658            offset,
659        }
660    }
661
662    fn call_node(target: &str, offset: u64) -> ASTNode {
663        ASTNode::Instruction {
664            instruction: Instruction {
665                opcode: Opcode::Call,
666                dst: None,
667                src: None,
668                off: None,
669                imm: Some(Either::Left(target.to_string())),
670                span: 0..0,
671            },
672            offset,
673        }
674    }
675}