File size: 13,628 Bytes
3ce1a40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/**
 * AST -> IR lowering.
 *
 * Resolves names against C block scopes, assigns every expression a type using C's
 * usual arithmetic conversions, inserts explicit CONVERTs, and turns && / || into
 * short-circuit control flow. Every failure raises LowerError; the IR it returns is
 * fully typed so a backend never has to infer anything.
 */

import {
  Op, Type, SCALAR_TYPES, Builtin, isFloat,
  makeIdCounter, value, instr, kernel,
} from './ir.js';

export class LowerError extends Error {
  constructor(message) {
    super(message);
    this.name = 'LowerError';
  }
}

const ARITHMETIC = { '+': Op.ADD, '-': Op.SUB, '*': Op.MUL, '/': Op.DIV, '%': Op.REM };
const BITWISE = { '&': Op.BIT_AND, '|': Op.BIT_OR, '^': Op.BIT_XOR };
const SHIFTS = { '<<': Op.SHL, '>>': Op.SHR };
const COMPARISONS = {
  '<': Op.CMP_LT, '>': Op.CMP_GT, '<=': Op.CMP_LE,
  '>=': Op.CMP_GE, '==': Op.CMP_EQ, '!=': Op.CMP_NE,
};

/** Builtins the lowering can read. Only the x dimension is launched today. */
const SUPPORTED_BUILTINS = new Set(Object.values(Builtin));

/** Integer promotion: bool arithmetic happens in int. */
const promote = (type) => (type === Type.BOOL ? Type.I32 : type);

/** C's usual arithmetic conversions, restricted to the supported scalars. */
function commonType(a, b) {
  const pa = promote(a);
  const pb = promote(b);
  for (const type of [Type.F64, Type.F32, Type.U32]) {
    if (pa === type || pb === type) return type;
  }
  return Type.I32;
}

function scalarType(name) {
  const type = SCALAR_TYPES[name];
  if (!type) throw new LowerError(`'${name}' is not a supported value type`);
  return type;
}

export function lower(ast) {
  const ids = makeIdCounter();
  const isVoid = ast.returnType === 'void';
  const returnType = isVoid ? null : scalarType(ast.returnType);

  const params = [];
  const usedNames = new Set();
  const paramScope = new Map();
  for (const p of ast.params) {
    if (usedNames.has(p.name)) throw new LowerError(`Duplicate parameter '${p.name}'`);
    usedNames.add(p.name);
    const param = { name: p.name, kind: p.type.kind, type: scalarType(p.type.scalar), isConst: p.type.isConst };
    params.push(param);
    paramScope.set(p.name, param);
  }

  const locals = [];
  const builtins = new Set();
  const scopes = [paramScope];
  let out = [];
  let loopDepth = 0;

  // ---- helpers ----
  const fresh = (type) => value(ids.next(), type);
  const emit = (ins) => {
    out.push(ins);
    return ins.out;
  };
  /** Runs `fn` with a fresh instruction list and returns what it emitted. */
  const collect = (fn) => {
    const saved = out;
    out = [];
    try {
      fn();
      return out;
    } finally {
      out = saved;
    }
  };
  const scoped = (fn) => {
    scopes.push(new Map());
    try {
      return fn();
    } finally {
      scopes.pop();
    }
  };

  function declareLocal(sourceName, type) {
    let name = sourceName;
    for (let n = 1; usedNames.has(name); n += 1) name = `${sourceName}.${n}`;
    usedNames.add(name);
    const local = { name, kind: 'scalar', type, isConst: false };
    locals.push({ name, type });
    return local;
  }

  function lookup(name) {
    for (let i = scopes.length - 1; i >= 0; i -= 1) {
      const binding = scopes[i].get(name);
      if (binding) return binding;
    }
    throw new LowerError(`Unknown variable '${name}'`);
  }

  const constant = (type, imm) => emit(instr(Op.CONST, { imm }, fresh(type)));

  function convert(val, to) {
    if (val.type === to) return val;
    if (to === Type.BOOL) return toBool(val);
    return emit(instr(Op.CONVERT, { value: val }, fresh(to)));
  }

  function toBool(val) {
    if (val.type === Type.BOOL) return val;
    const zero = constant(val.type, 0);
    return emit(instr(Op.CMP_NE, { left: val, right: zero }, fresh(Type.BOOL)));
  }

  function requireInteger(val, what) {
    if (isFloat(val.type)) throw new LowerError(`${what} requires integer operands`);
  }

  function readBuiltin(name) {
    if (!SUPPORTED_BUILTINS.has(name)) {
      throw new LowerError(`Builtin '${name}' is not supported; only the x dimension is available`);
    }
    if (!isVoid) throw new LowerError(`Builtin '${name}' is only available in void kernels`);
    builtins.add(name);
    return emit(instr(Op.BUILTIN, { name }, fresh(Type.I32)));
  }

  function bufferBinding(expr) {
    if (expr.kind !== 'var') throw new LowerError('Only a buffer parameter can be indexed');
    const binding = lookup(expr.name);
    if (binding.kind !== 'buffer') throw new LowerError(`'${expr.name}' is not a buffer`);
    return binding;
  }

  function lowerIndex(expr) {
    const index = lowerExpr(expr);
    requireInteger(index, 'A buffer index');
    return convert(index, Type.I32);
  }

  /** Applies a binary operator to two already-lowered values. */
  function binaryOp(op, left, right) {
    if (op in ARITHMETIC) {
      const type = commonType(left.type, right.type);
      if (op === '%' && isFloat(type)) throw new LowerError("'%' requires integer operands");
      const l = convert(left, type);
      const r = convert(right, type);
      return emit(instr(ARITHMETIC[op], { left: l, right: r }, fresh(type)));
    }
    if (op in BITWISE) {
      requireInteger(left, `'${op}'`);
      requireInteger(right, `'${op}'`);
      const type = commonType(left.type, right.type);
      return emit(instr(BITWISE[op], { left: convert(left, type), right: convert(right, type) }, fresh(type)));
    }
    if (op in SHIFTS) {
      requireInteger(left, `'${op}'`);
      requireInteger(right, `'${op}'`);
      // The result has the promoted type of the left operand, not the common type.
      const type = promote(left.type);
      return emit(instr(SHIFTS[op], { left: convert(left, type), right: convert(right, type) }, fresh(type)));
    }
    if (op in COMPARISONS) {
      const type = commonType(left.type, right.type);
      const l = convert(left, type);
      const r = convert(right, type);
      return emit(instr(COMPARISONS[op], { left: l, right: r }, fresh(Type.BOOL)));
    }
    throw new LowerError(`Unsupported operator '${op}'`);
  }

  /** a && b / a || b: the right side runs only when it can change the result. */
  function shortCircuit(expr) {
    const result = declareLocal('$sc', Type.BOOL);
    const left = toBool(lowerExpr(expr.left));
    emit(instr(Op.STORE, { name: result.name, value: left }));
    const evalRight = collect(() => {
      const right = toBool(lowerExpr(expr.right));
      emit(instr(Op.STORE, { name: result.name, value: right }));
    });
    const isAnd = expr.op === '&&';
    emit(instr(Op.IF, { cond: left, then: isAnd ? evalRight : [], otherwise: isAnd ? [] : evalRight }));
    return emit(instr(Op.LOAD, { name: result.name }, fresh(Type.BOOL)));
  }

  function lowerAssign(expr) {
    const compound = expr.op === '=' ? null : expr.op.slice(0, -1);

    if (expr.target.kind === 'var') {
      const binding = lookup(expr.target.name);
      if (binding.kind === 'buffer') throw new LowerError(`Cannot assign to buffer '${expr.target.name}'`);
      if (binding.isConst) throw new LowerError(`Cannot assign to const '${expr.target.name}'`);
      let result = lowerExpr(expr.value);
      if (compound) {
        const current = emit(instr(Op.LOAD, { name: binding.name }, fresh(binding.type)));
        result = binaryOp(compound, current, result);
      }
      result = convert(result, binding.type);
      emit(instr(Op.STORE, { name: binding.name, value: result }));
      return result;
    }

    if (expr.target.kind === 'index') {
      const binding = bufferBinding(expr.target.base);
      if (binding.isConst) throw new LowerError(`Cannot write to const buffer '${binding.name}'`);
      const index = lowerIndex(expr.target.index);
      let result = lowerExpr(expr.value);
      if (compound) {
        const current = emit(instr(Op.BUFFER_LOAD, { buffer: binding.name, index }, fresh(binding.type)));
        result = binaryOp(compound, current, result);
      }
      result = convert(result, binding.type);
      emit(instr(Op.BUFFER_STORE, { buffer: binding.name, index, value: result }));
      return result;
    }

    throw new LowerError('The left side of an assignment must be a variable or a buffer element');
  }

  function lowerExpr(expr) {
    switch (expr.kind) {
      case 'int': {
        if (expr.value <= 0x7fffffff) return constant(Type.I32, expr.value);
        if (expr.value <= 0xffffffff) return constant(Type.U32, expr.value);
        throw new LowerError(`Integer literal ${expr.value} does not fit in 32 bits`);
      }
      case 'float':
        return constant(expr.single ? Type.F32 : Type.F64, expr.value);
      case 'bool':
        return constant(Type.BOOL, expr.value ? 1 : 0);
      case 'var': {
        const binding = lookup(expr.name);
        if (binding.kind === 'buffer') throw new LowerError(`Buffer '${expr.name}' must be indexed`);
        return emit(instr(Op.LOAD, { name: binding.name }, fresh(binding.type)));
      }
      case 'builtin':
        return readBuiltin(expr.name);
      case 'call':
        // The parser maps member builtins such as threadIdx.x onto call nodes.
        if (expr.args.length !== 0) throw new LowerError(`Unknown function '${expr.callee}'`);
        return readBuiltin(expr.callee);
      case 'index': {
        const binding = bufferBinding(expr.base);
        const index = lowerIndex(expr.index);
        return emit(instr(Op.BUFFER_LOAD, { buffer: binding.name, index }, fresh(binding.type)));
      }
      case 'unary': {
        const operand = lowerExpr(expr.operand);
        if (expr.op === '!') {
          return emit(instr(Op.NOT, { operand: toBool(operand) }, fresh(Type.BOOL)));
        }
        if (expr.op === '-') {
          const type = promote(operand.type);
          return emit(instr(Op.NEG, { operand: convert(operand, type) }, fresh(type)));
        }
        if (expr.op === '~') {
          requireInteger(operand, "'~'");
          const type = promote(operand.type);
          return emit(instr(Op.BIT_NOT, { operand: convert(operand, type) }, fresh(type)));
        }
        throw new LowerError(`Unsupported unary operator '${expr.op}'`);
      }
      case 'binary':
        if (expr.op === '&&' || expr.op === '||') return shortCircuit(expr);
        return binaryOp(expr.op, lowerExpr(expr.left), lowerExpr(expr.right));
      case 'assign':
        return lowerAssign(expr);
      case 'cast':
        return convert(lowerExpr(expr.operand), scalarType(expr.to));
      default:
        throw new LowerError(`Unsupported expression '${expr.kind}'`);
    }
  }

  function lowerLoopBody(stmts) {
    loopDepth += 1;
    try {
      return collect(() => scoped(() => lowerStmts(stmts)));
    } finally {
      loopDepth -= 1;
    }
  }

  function lowerStmt(stmt) {
    switch (stmt.kind) {
      case 'decl': {
        const type = scalarType(stmt.type);
        if (scopes.at(-1).has(stmt.name)) throw new LowerError(`'${stmt.name}' is already declared in this scope`);
        // Evaluated before the name is in scope, so `int x = x;` reads an outer x.
        // Without an initializer the local is zeroed so loop iterations stay deterministic.
        const init = stmt.init ? convert(lowerExpr(stmt.init), type) : constant(type, 0);
        const local = declareLocal(stmt.name, type);
        scopes.at(-1).set(stmt.name, local);
        emit(instr(Op.STORE, { name: local.name, value: init }));
        return;
      }
      case 'assign':
        lowerAssign(stmt);
        return;
      case 'expr':
        lowerExpr(stmt.value);
        return;
      case 'block':
        scoped(() => lowerStmts(stmt.body));
        return;
      case 'if': {
        const cond = toBool(lowerExpr(stmt.cond));
        const then = collect(() => scoped(() => lowerStmts(stmt.then)));
        const otherwise = collect(() => scoped(() => lowerStmts(stmt.otherwise)));
        emit(instr(Op.IF, { cond, then, otherwise }));
        return;
      }
      case 'while': {
        let cond = null;
        const head = collect(() => { cond = toBool(lowerExpr(stmt.cond)); });
        const body = lowerLoopBody(stmt.body);
        emit(instr(Op.LOOP, { head, cond, body, step: [] }));
        return;
      }
      case 'for':
        scoped(() => {
          if (stmt.init) lowerStmt(stmt.init);
          let cond = null;
          const head = collect(() => { if (stmt.cond) cond = toBool(lowerExpr(stmt.cond)); });
          const body = lowerLoopBody(stmt.body);
          const step = collect(() => { if (stmt.step) lowerExpr(stmt.step); });
          emit(instr(Op.LOOP, { head, cond, body, step }));
        });
        return;
      case 'break':
      case 'continue':
        if (loopDepth === 0) throw new LowerError(`'${stmt.kind}' outside of a loop`);
        emit(instr(stmt.kind === 'break' ? Op.BREAK : Op.CONTINUE));
        return;
      case 'return': {
        if (isVoid) {
          if (stmt.value) throw new LowerError('A void kernel cannot return a value');
          emit(instr(Op.RET, { value: null }));
          return;
        }
        if (!stmt.value) throw new LowerError(`Kernel '${ast.name}' must return a ${ast.returnType}`);
        emit(instr(Op.RET, { value: convert(lowerExpr(stmt.value), returnType) }));
        return;
      }
      default:
        throw new LowerError(`Unsupported statement '${stmt.kind}'`);
    }
  }

  function lowerStmts(stmts) {
    for (const stmt of stmts) lowerStmt(stmt);
  }

  const body = collect(() => scoped(() => lowerStmts(ast.body)));
  return kernel(ast.name, returnType, params, locals, body, [...builtins]);
}