Search code examples
functional-programmingcompiler-constructionocamlllvm

Can't open Llvm in ocaml


I'm trying to use llvm binding in ocaml, in my file test.ml, I have one line of code:

open Llvm

When I run the command

ocamlbuild -use-ocamlfind test.byte -package llvm

I get this result:

+ ocamlfind ocamldep -package llvm -modules test.ml > test.ml.depends
ocamlfind: Package `llvm' not found
Command exited with code 2.
Compilation unsuccessful after building 1 target (0 cached) in  00:00:00.

What did I do wrong in this? Thanks.

BTW, the _tag file contains:

"src": traverse
<src/{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis

myocamlbuild.ml contains:

open Ocamlbuild_plugin;;
ocaml_lib ~extern:true "llvm";;
ocaml_lib ~extern:true "llvm_analysis";;
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;

Solution

  • I don't know why the instructions that you're using are so complex. You don't have to do anything like this to use llvm bindings in OCaml, provided you have installed them via opam.

    Here is the recipe:

    Install llvm bindings via opam.

    it could be as simple as

    opam install llvm
    

    However, opam may try to install the latest version that is not available on your system, so pick a particular version, that you have and do the following (suppose you have llvm-3.8):

    opam install conf-llvm.3.8
    opam install llvm --criteria=-changed
    

    (The -criteria flag will prevent opam from upgrading conf-llvm to the newest version)

    Once it succeeds, you can easily compile your programs without any additional scaffolding.

    Create and build your project

    1. create a fresh new folder, e.g.,

      mkdir llvm-project
      cd llvm-project
      
    2. create a sample application (borrowed from some tutorial, that I've found online):

      cat >test.ml<<EOF
      open Llvm
      
      let _ =
        let llctx = Llvm.global_context () in
        let llmem = Llvm.MemoryBuffer.of_file Sys.argv.(1) in
        let llm = Llvm_bitreader.parse_bitcode llctx llmem in
        Llvm.dump_module llm ;
        ()
      EOF
      
    3. compile it for bytecode

      ocamlbuild -pkgs llvm,llvm.bitreader test.byte
      

      or to the native code

      ocamlbuild -pkgs llvm,llvm.bitreader test.native
      
    4. run it

      ./test.native mycode.bc