Skip to content

Commit fcd9e15

Browse files
committed
compile-time computation ramblings
1 parent df26e5c commit fcd9e15

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

content/english/hpc/compilation/constexpr.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,54 @@ weight: 8
44
---
55

66
A compiler can compute constants on its own, but it doesn't *have to*.
7+
8+
```c++
9+
const int b = 4, B = (1 << b);
10+
11+
// is it tight enough?
12+
constexpr int round(int k) {
13+
return k / B * B; // (k & ~(B - 1));
14+
}
15+
16+
constexpr int height(int m) {
17+
return (m == 0 ? 0 : height(m / B) + 1);
18+
}
19+
20+
constexpr int offset(int h) {
21+
int res = 0;
22+
int m = N;
23+
while (h--) {
24+
res += round(m) + B;
25+
m /= B;
26+
}
27+
return res;
28+
}
29+
30+
constexpr int h = height(N);
31+
alignas(64) int t[offset(h)];
32+
//int t[N * B / (B - 1)]; // +1?
33+
34+
struct Meta {
35+
alignas(64) int mask[B][B];
36+
37+
constexpr Meta() : mask{} {
38+
for (int k = 0; k < B; k++)
39+
for (int i = 0; i < B; i++)
40+
mask[k][i] = (i > k ? -1 : 0);
41+
}
42+
};
43+
44+
constexpr Meta T;
45+
```
46+
47+
### Code Generation
48+
49+
There are plenty of languages that support computing *data* during compile-time, but none can produce efficient code at all times.
50+
51+
One huge example is generating lexers and parsers: which is usually done in.
52+
53+
For example, CUDA and OpenCL are mostly C, and have no support for metaprogramming.
54+
55+
At some point (and perhaps to this day), these languages had no way to unroll loops, so people would write a [jinja template](https://jinja.palletsprojects.com/en/3.0.x/), call the thing from Python, and then compile.
56+
57+
It is not uncommon to use a templating engine to generate code. For example, CUDA (a GPU programming language) has no loop unrolling

0 commit comments

Comments
 (0)