functions.sv 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // Common useful functions
  3. //
  4. // ceil(ilog2(a))
  5. function int ilog2c(int a);
  6. int b = 0;
  7. while ((1 << b) < a)
  8. b++;
  9. ilog2c = b;
  10. endfunction // ilog2c
  11. // floor(ilog2(a))
  12. function int ilog2f(int a);
  13. ilog2f = ilog2c(a+1)-1;
  14. endfunction // ilog2f
  15. function int max(int a, int b);
  16. max = a > b ? a : b;
  17. endfunction // max
  18. function int max3(int a, int b, int c);
  19. max3 = max(max(a,b),c);
  20. endfunction // max3
  21. function int max4(int a, int b, int c, int d);
  22. max4 = max(max(a,b),max(c,d));
  23. endfunction // max4
  24. function int min(int a, int b);
  25. min = a < b ? a : b;
  26. endfunction // min
  27. function int min3(int a, int b, int c);
  28. min3 = min(min(a,b),c);
  29. endfunction // min3
  30. function int min4(int a, int b, int c, int d);
  31. min4 = min(min(a,b),min(c,d));
  32. endfunction // min4
  33. // Quartus doesn't support $sformatf() for synthesis, sigh...
  34. // This is highly useful to create synthetic attribute strings;
  35. // the rather clumsy design is specifically in order to be handled
  36. // correctly by synthesis.
  37. function string tostr(input integer i);
  38. if (i < 0)
  39. tostr = {"-",tostr(-i)};
  40. else if (i >= 10)
  41. tostr = {tostr(i/10), tostr(i%10)};
  42. else if (i == 0)
  43. tostr = "0";
  44. else if (i == 1)
  45. tostr = "1";
  46. else if (i == 2)
  47. tostr = "2";
  48. else if (i == 3)
  49. tostr = "3";
  50. else if (i == 4)
  51. tostr = "4";
  52. else if (i == 5)
  53. tostr = "5";
  54. else if (i == 6)
  55. tostr = "6";
  56. else if (i == 7)
  57. tostr = "7";
  58. else if (i == 8)
  59. tostr = "8";
  60. else
  61. tostr = "9";
  62. endfunction