Skip to content

Commit 2e504cc

Browse files
committed
Optimize instruction generation in eBPF C code by combining function calls with variable declarations. Implement a recursive optimization function to enhance code clarity and efficiency during instruction processing.
1 parent 3b13f6c commit 2e504cc

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/ebpf_c_codegen.ml

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2809,8 +2809,37 @@ let generate_c_basic_block ctx ir_block =
28092809
increase_indent ctx
28102810
);
28112811

2812-
(* Generate C code for each IR instruction *)
2813-
List.iter (generate_c_instruction ctx) ir_block.instructions
2812+
(* Optimize function call + variable declaration patterns *)
2813+
let rec optimize_instructions instrs =
2814+
match instrs with
2815+
| call_instr :: decl_instr :: rest ->
2816+
(match call_instr.instr_desc, decl_instr.instr_desc with
2817+
| IRCall (target, args, Some ret_val), IRDeclareVariable (dest_val, typ, None)
2818+
when ret_val.value_desc = dest_val.value_desc ->
2819+
(* Combine function call with variable declaration *)
2820+
let var_name = get_meaningful_var_name ctx
2821+
(match dest_val.value_desc with
2822+
| IRRegister reg -> reg
2823+
| _ -> failwith "IRDeclareVariable target must be a register")
2824+
typ in
2825+
let type_str = ebpf_type_from_ir_type typ in
2826+
let call_str = match target with
2827+
| DirectCall name ->
2828+
let args_str = String.concat ", " (List.map (generate_c_value ctx) args) in
2829+
sprintf "%s(%s)" name args_str
2830+
| _ -> "/* complex call */" in
2831+
emit_line ctx (sprintf "%s %s = %s;" type_str var_name call_str);
2832+
optimize_instructions rest
2833+
| _ ->
2834+
generate_c_instruction ctx call_instr;
2835+
optimize_instructions (decl_instr :: rest))
2836+
| instr :: rest ->
2837+
generate_c_instruction ctx instr;
2838+
optimize_instructions rest
2839+
| [] -> ()
2840+
in
2841+
2842+
optimize_instructions ir_block.instructions
28142843

28152844
(** Collect mapping from registers to variable names *)
28162845
let collect_register_variable_mapping ir_func =

0 commit comments

Comments
 (0)