Skip to content

Instantly share code, notes, and snippets.

@larsr
Created January 17, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsr/f560f015701297e5ab8254ec3916c00a to your computer and use it in GitHub Desktop.
Save larsr/f560f015701297e5ab8254ec3916c00a to your computer and use it in GitHub Desktop.
Example compiling haskell to llvm IR code and then linking it with the necessary libraries to run it. (I installed ghc and llvm with brew)
cat >demo.hs <<EOF
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
main = print(quicksort([5,2,1,0,8,3]))
EOF
# get demo.ll (this also produces a .c file in tmp that we will need)
rm -rf tmp demo *ll \
&& mkdir -p tmp \
&& ghc -v -keep-llvm-file \
-tmpdir tmp -keep-tmp-files \
demo.hs \
&& rm demo.o demo demo.hi
# get main.ll (from ghc_5.c)
GHC=/usr/local/Cellar/ghc/8.8.1
clang -S -I${GHC}/lib/ghc-8.8.1/include -emit-llvm tmp/*/*.c -o main.ll
# remove tmp
rm -rf tmp
clang \
-O3 \
-DTABLES_NEXT_TO_CODE \
-o \
demo \
-Wl,-no_compact_unwind \
main.ll \
demo.ll \
-L$GHC/lib/ghc-8.8.1/{base-4.13.0.0,integer-gmp-1.0.2.0,ghc-prim-0.5.3,rts} \
-lHS{base-4.13.0.0,integer-gmp-1.0.2.0,ghc-prim-0.5.3,rts} \
-L$GHC/libexec/integer-gmp/lib \
-lgmp \
-lCffi \
-liconv \
-lm \
-ldl
./demo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment