[LLVMdev] Fibonacci example in OCaml

Jon Harrop jon at ffconsultancy.com
Sun Nov 25 14:04:37 PST 2007


Here's my translation of the Fibonacci example into OCaml:

open Printf
open Llvm

let build_fib m =
   let fibf =
     define_function "fib" (function_type i32_type [| i32_type |]) m in

   let bb = builder_at_end (entry_block fibf) in

   let one = const_int i32_type 1 and two = const_int i32_type 2 in

   let argx = param fibf 0 in
   set_value_name "AnArg" argx;

   let retbb = append_block "return" fibf in
   let retb = builder_at_end retbb in
   let recursebb = append_block "recurse" fibf in
   let recurseb = builder_at_end recursebb in

   let condinst = build_icmp Icmp_sle argx two "cond" bb in
   ignore(build_cond_br condinst retbb recursebb bb);
   ignore(build_ret one retb);

   let sub = build_sub argx one "arg" recurseb in
   let callfibx1 = build_call fibf [|sub|] "fibx1" recurseb in

   let sub = build_sub argx two "arg" recurseb in
   let callfibx2 = build_call fibf [|sub|] "fibx2" recurseb in

   let sum = build_add callfibx1 callfibx2 "addresult" recurseb in

   build_ret sum recurseb;

   fibf

let main filename =
   let m = create_module filename in

   let puts =
     declare_function "puts"
       (function_type i32_type [|pointer_type i8_type|]) m in

   let fib = build_fib m in

   let main = define_function "main" (function_type i32_type [| |]) m in
   let at_entry = builder_at_end (entry_block main) in   
   let n = build_call fib [| const_int i32_type 40 |] "" at_entry in
   ignore (build_ret (const_null i32_type) at_entry);

   if not (Llvm_bitwriter.write_bitcode_file m filename) then exit 1;
   dispose_module m

let () = match Sys.argv with
  | [|_; filename|] -> main filename
  | _ as a -> eprintf "Usage: %s <file>\n" a.(0)

I'd appreciate it if someone could gloss over this and let me know if I'm 
going in the correct direction. Also, I have a really stupid question: what 
is the easiest way to print the int result!? :-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?e



More information about the llvm-dev mailing list