Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. ;; lisp compiler input
  2. ;; `integer` maps to 64 bit integer / uint64_t / i64
  3.  
  4. (compile-function
  5. 'factorial 'integer '((x . integer))
  6. '((entry (goto-if (= integer x 0) zero else))
  7. (zero (return integer 1))
  8. (else (return integer (* integer x (call integer factorial (integer - integer x 1)))))))
  9.  
  10. ;; LLVM output
  11.  
  12. define i64 @factorial(i64 %x) {
  13. ;; if X = 0, factorial(X) = 1
  14. ;; if X > 0, factorial(X) = x * factorial(X-1)
  15. ENTRY:
  16. %ENTRY0_1 = icmp eq i64 %x, 0 ;; compare X to 0
  17. br i1 %ENTRY0_1, label %ZERO, label %ELSE ;; if X is zero, go to ZERO, else ELSE
  18. ZERO:
  19. ret i64 1 ;; return 1
  20. ELSE:
  21. %ELSE0_1 = sub i64 %x, 1 ;; take 1 from X
  22. %ELSE0_2 = call i64 @factorial(i64 %ELSE0_1) ;; call factorial with the decremented X
  23. %ELSE0_3 = mul i64 %x, %ELSE0_2 ;; multiply it by X
  24. ret i64 %ELSE0_3 ;; return X * factorial(x-1)
  25. }
  26. * ^D
  27.  
  28. $ cat testfact.c
  29. #include <stdint.h>
  30. #include <stdio.h>
  31.  
  32. extern uint64_t factorial(uint64_t x);
  33.  
  34. int main() {
  35. uint64_t x = 10;
  36. printf("%llu! = %llu", x, factorial(x));
  37. return (int)x;
  38. }
  39.  
  40. $ clang -c fact.ll -o fact.o
  41. $ clang fact.o testfact.c -o fact
  42.  
  43. $ ./fact
  44. 10! = 3628800
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement