functions.sv 2.0 KB

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