You can place the function into a separate file and use the `include compiler directive to include the function inside both modules:
--- M1.v ---
module M1();
`include "functions.v"
endmodule
--- M2.v -----
module M2();
`include "functions.v"
// Use f() here
endmodule