-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.ts
More file actions
529 lines (469 loc) · 20.3 KB
/
binary.ts
File metadata and controls
529 lines (469 loc) · 20.3 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import { Expression, SourceLocation, NumberNode } from "../../../ast/types.js";
import type { IStringGenerator } from "../../infrastructure/generator-context.js";
interface ControlFlowGeneratorLike {
generateLogicalOp(op: string, left: Expression, right: Expression, params: string[]): string;
}
export interface BinaryExpressionGeneratorContext {
nextTemp(): string;
nextLabel(prefix: string): string;
getCurrentLabel(): string;
emit(instruction: string): void;
emitIcmp(pred: string, type: string, lhs: string, rhs: string): string;
emitBr(label: string): void;
emitBrCond(cond: string, thenLabel: string, elseLabel: string): void;
emitLabel(name: string): void;
emitCall(retType: string, func: string, args: string): string;
emitBitcast(value: string, fromType: string, toType: string): string;
isStringExpression(expr: Expression): boolean;
variableTypes: Map<string, string>;
getVariableType(name: string): string | undefined;
setVariableType(name: string, type: string): void;
ensureDouble(value: string): string;
ensureI64(value: string): string;
controlFlowGen: ControlFlowGeneratorLike;
readonly stringGen: IStringGenerator;
generateExpression(expr: Expression, params: string[]): string;
emitError(message: string, loc?: SourceLocation, suggestion?: string): never;
}
/**
* BinaryExpressionGenerator
*
* Handles binary operations:
* - Logical operators (&&, ||) with short-circuit evaluation
* - String concatenation (+)
* - Arithmetic operators (+, -, *, /, %)
* - Bitwise operators (&, |, ^, <<, >>)
* - Comparison operators (<, >, <=, >=, ==, !=, ===, !==)
* - String comparisons use strcmp
* - Numeric comparisons use fcmp
*/
export class BinaryExpressionGenerator {
constructor(private ctx: BinaryExpressionGeneratorContext) {}
generate(op: string, left: Expression, right: Expression, params: string[]): string {
// Logical operators need short-circuit evaluation
if (op === "&&" || op === "||" || op === "??") {
return this.ctx.controlFlowGen.generateLogicalOp(op, left, right, params);
}
// Check for string concatenation (+ with at least one string operand)
if (op === "+" && (this.ctx.isStringExpression(left) || this.ctx.isStringExpression(right))) {
return this.ctx.stringGen.doGenerateStringConcat(left, right, params);
}
const leftValue = this.ctx.generateExpression(left, params);
const rightValue = this.ctx.generateExpression(right, params);
// Arithmetic operators (floating-point)
const arithMap: { [key: string]: string } = {
"+": "fadd fast",
"-": "fsub fast",
"*": "fmul fast",
"/": "fdiv fast",
};
// Bitwise operators (need to convert double -> i64 -> operate -> double)
const bitwiseMap: { [key: string]: string } = {
"&": "and",
"|": "or",
"^": "xor",
"<<": "shl",
">>": "ashr", // arithmetic shift right (preserves sign)
};
// Comparison operators (fcmp returns i1, need to extend to i32)
const cmpMap: { [key: string]: string } = {
"<": "olt", // ordered less than
">": "ogt", // ordered greater than
"<=": "ole", // ordered less or equal
">=": "oge", // ordered greater or equal
"==": "oeq", // ordered equal
"!=": "one", // ordered not equal
"===": "oeq", // Strict equality (same as == for double)
"!==": "one", // Strict inequality (same as != for double)
};
if (op === "%") {
return this.generateModulo(leftValue, rightValue, left, right);
} else if (arithMap[op]) {
return this.generateArithmetic(op, arithMap[op], leftValue, rightValue);
} else if (bitwiseMap[op]) {
return this.generateBitwise(op, bitwiseMap[op], leftValue, rightValue);
} else if (cmpMap[op]) {
return this.generateComparison(op, cmpMap[op], leftValue, rightValue, left, right);
} else {
return this.ctx.emitError(
"Unknown operator: " + op,
undefined,
"supported operators: +, -, *, /, %, **, ==, !=, <, >, <=, >=, &&, ||, ??",
);
}
}
private generateArithmetic(_op: string, llvmOp: string, left: string, right: string): string {
const leftType = this.ctx.getVariableType(left);
const rightType = this.ctx.getVariableType(right);
if (leftType === "i64" && rightType === "i64" && _op !== "/") {
const i64Op = _op === "+" ? "add" : _op === "-" ? "sub" : "mul";
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = ${i64Op} i64 ${left}, ${right}`);
this.ctx.setVariableType(temp, "i64");
return temp;
}
if (leftType === "i8*" || (leftType && leftType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${leftType} ${left} to i64`);
const asDouble = this.ctx.nextTemp();
this.ctx.emit(`${asDouble} = sitofp i64 ${asInt} to double`);
left = asDouble;
} else {
left = this.ctx.ensureDouble(left);
}
if (rightType === "i8*" || (rightType && rightType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${rightType} ${right} to i64`);
const asDouble = this.ctx.nextTemp();
this.ctx.emit(`${asDouble} = sitofp i64 ${asInt} to double`);
right = asDouble;
} else {
right = this.ctx.ensureDouble(right);
}
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = ${llvmOp} double ${left}, ${right}`);
this.ctx.setVariableType(temp, "double");
return temp;
}
private isKnownInteger(expr: Expression): boolean {
const exprTyped = expr as NumberNode;
if (exprTyped.type === "number" && typeof exprTyped.value === "number") {
return Number.isInteger(exprTyped.value);
}
return false;
}
private generateModulo(
left: string,
right: string,
leftExpr: Expression,
rightExpr: Expression,
): string {
const leftType = this.ctx.getVariableType(left);
const rightType = this.ctx.getVariableType(right);
if (leftType === "i64" && rightType === "i64") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = srem i64 ${left}, ${right}`);
this.ctx.setVariableType(temp, "i64");
return temp;
}
if (leftType === "i8*" || (leftType && leftType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${leftType} ${left} to i64`);
const asDouble = this.ctx.nextTemp();
this.ctx.emit(`${asDouble} = sitofp i64 ${asInt} to double`);
left = asDouble;
} else {
left = this.ctx.ensureDouble(left);
}
if (rightType === "i8*" || (rightType && rightType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${rightType} ${right} to i64`);
const asDouble = this.ctx.nextTemp();
this.ctx.emit(`${asDouble} = sitofp i64 ${asInt} to double`);
right = asDouble;
} else {
right = this.ctx.ensureDouble(right);
}
const leftIsKnown = this.isKnownInteger(leftExpr);
const rightIsKnown = this.isKnownInteger(rightExpr);
if (leftIsKnown && rightIsKnown) {
const leftInt = this.ctx.nextTemp();
this.ctx.emit(`${leftInt} = fptosi double ${left} to i64`);
const rightInt = this.ctx.nextTemp();
this.ctx.emit(`${rightInt} = fptosi double ${right} to i64`);
const sremResult = this.ctx.nextTemp();
this.ctx.emit(`${sremResult} = srem i64 ${leftInt}, ${rightInt}`);
const result = this.ctx.nextTemp();
this.ctx.emit(`${result} = sitofp i64 ${sremResult} to double`);
this.ctx.setVariableType(result, "double");
return result;
}
let bothInt: string;
if (leftIsKnown) {
const rightTrunc = this.ctx.emitCall("double", "@llvm.trunc.f64", `double ${right}`);
bothInt = this.ctx.nextTemp();
this.ctx.emit(`${bothInt} = fcmp oeq double ${right}, ${rightTrunc}`);
} else if (rightIsKnown) {
const leftTrunc = this.ctx.emitCall("double", "@llvm.trunc.f64", `double ${left}`);
bothInt = this.ctx.nextTemp();
this.ctx.emit(`${bothInt} = fcmp oeq double ${left}, ${leftTrunc}`);
} else {
const leftTrunc = this.ctx.emitCall("double", "@llvm.trunc.f64", `double ${left}`);
const leftIsInt = this.ctx.nextTemp();
this.ctx.emit(`${leftIsInt} = fcmp oeq double ${left}, ${leftTrunc}`);
const rightTrunc = this.ctx.emitCall("double", "@llvm.trunc.f64", `double ${right}`);
const rightIsInt = this.ctx.nextTemp();
this.ctx.emit(`${rightIsInt} = fcmp oeq double ${right}, ${rightTrunc}`);
bothInt = this.ctx.nextTemp();
this.ctx.emit(`${bothInt} = and i1 ${leftIsInt}, ${rightIsInt}`);
}
const intModLabel = this.ctx.nextLabel("mod_int");
const floatModLabel = this.ctx.nextLabel("mod_float");
const mergeLabel = this.ctx.nextLabel("mod_merge");
this.ctx.emitBrCond(bothInt, intModLabel, floatModLabel);
this.ctx.emitLabel(intModLabel);
const leftInt = this.ctx.nextTemp();
this.ctx.emit(`${leftInt} = fptosi double ${left} to i64`);
const rightInt = this.ctx.nextTemp();
this.ctx.emit(`${rightInt} = fptosi double ${right} to i64`);
const sremResult = this.ctx.nextTemp();
this.ctx.emit(`${sremResult} = srem i64 ${leftInt}, ${rightInt}`);
const intResult = this.ctx.nextTemp();
this.ctx.emit(`${intResult} = sitofp i64 ${sremResult} to double`);
const intBranchEnd = this.ctx.getCurrentLabel();
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(floatModLabel);
const fremResult = this.ctx.nextTemp();
this.ctx.emit(`${fremResult} = frem fast double ${left}, ${right}`);
const floatBranchEnd = this.ctx.getCurrentLabel();
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(mergeLabel);
const result = this.ctx.nextTemp();
this.ctx.emit(
`${result} = phi double [ ${intResult}, %${intBranchEnd} ], [ ${fremResult}, %${floatBranchEnd} ]`,
);
this.ctx.setVariableType(result, "double");
return result;
}
private generateBitwise(_op: string, llvmOp: string, left: string, right: string): string {
const leftType = this.ctx.getVariableType(left);
const rightType = this.ctx.getVariableType(right);
let leftInt: string;
if (leftType === "i64") {
leftInt = left;
} else if (leftType === "i8*" || (leftType && leftType.indexOf("*") !== -1)) {
leftInt = this.ctx.nextTemp();
this.ctx.emit(`${leftInt} = ptrtoint ${leftType} ${left} to i64`);
} else {
leftInt = this.ctx.nextTemp();
this.ctx.emit(`${leftInt} = fptosi double ${left} to i64`);
}
let rightInt: string;
if (rightType === "i64") {
rightInt = right;
} else if (rightType === "i8*" || (rightType && rightType.indexOf("*") !== -1)) {
rightInt = this.ctx.nextTemp();
this.ctx.emit(`${rightInt} = ptrtoint ${rightType} ${right} to i64`);
} else {
rightInt = this.ctx.nextTemp();
this.ctx.emit(`${rightInt} = fptosi double ${right} to i64`);
}
const resultInt = this.ctx.nextTemp();
this.ctx.emit(`${resultInt} = ${llvmOp} i64 ${leftInt}, ${rightInt}`);
this.ctx.setVariableType(resultInt, "i64");
return resultInt;
}
private generateComparison(
op: string,
cond: string,
leftValue: string,
rightValue: string,
leftExpr: Expression,
rightExpr: Expression,
): string {
const leftExprTyped = leftExpr as { type: string };
const rightExprTyped = rightExpr as { type: string };
const leftIsNullish = leftExprTyped.type === "null" || leftExprTyped.type === "undefined";
const rightIsNullish = rightExprTyped.type === "null" || rightExprTyped.type === "undefined";
if (leftIsNullish || rightIsNullish) {
return this.generatePointerNullComparison(op, leftValue, rightValue);
}
const leftIsString = this.ctx.isStringExpression(leftExpr);
const rightIsString = this.ctx.isStringExpression(rightExpr);
const leftType = this.ctx.getVariableType(leftValue) || "double";
const rightType = this.ctx.getVariableType(rightValue) || "double";
const leftIsStringType = leftType === "i8*" || leftValue.startsWith("@.str");
const rightIsStringType = rightType === "i8*" || rightValue.startsWith("@.str");
const leftIsJSONi32 = leftType === "i32";
const rightIsJSONi32 = rightType === "i32";
const isStringOp =
((leftIsString || leftIsStringType) && (rightIsString || rightIsStringType)) ||
(leftIsJSONi32 && (rightIsString || rightIsStringType)) ||
((leftIsString || leftIsStringType) && rightIsJSONi32) ||
(leftIsJSONi32 && rightIsJSONi32);
if (isStringOp) {
return this.generateStringComparison(op, leftValue, rightValue);
}
return this.generateNumericComparison(cond, leftValue, rightValue);
}
private generateStringComparison(op: string, left: string, right: string): string {
const leftType = this.ctx.getVariableType(left);
const rightType = this.ctx.getVariableType(right);
let leftPtr = left;
let rightPtr = right;
if (leftType === "i32") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i32 ${left} to i8*`);
leftPtr = temp;
}
if (rightType === "i32") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i32 ${right} to i8*`);
rightPtr = temp;
}
const leftNull = this.ctx.emitIcmp("eq", "i8*", leftPtr, "null");
const rightNull = this.ctx.emitIcmp("eq", "i8*", rightPtr, "null");
const eitherNull = this.ctx.nextTemp();
this.ctx.emit(`${eitherNull} = or i1 ${leftNull}, ${rightNull}`);
const nullCheckLabel = this.ctx.nextLabel("strcmp_null_check");
const strcmpLabel = this.ctx.nextLabel("strcmp_call");
const mergeLabel = this.ctx.nextLabel("strcmp_merge");
this.ctx.emitBrCond(eitherNull, nullCheckLabel, strcmpLabel);
this.ctx.emitLabel(nullCheckLabel);
const bothNull = this.ctx.nextTemp();
this.ctx.emit(`${bothNull} = and i1 ${leftNull}, ${rightNull}`);
let nullResult: string;
if (op === "==" || op === "===") {
nullResult = bothNull;
} else if (op === "!=" || op === "!==") {
const notBothNull = this.ctx.nextTemp();
this.ctx.emit(`${notBothNull} = xor i1 ${bothNull}, true`);
nullResult = notBothNull;
} else {
const falseVal = this.ctx.emitIcmp("eq", "i32", "0", "1");
nullResult = falseVal;
}
const nullResultInt = this.ctx.nextTemp();
this.ctx.emit(`${nullResultInt} = zext i1 ${nullResult} to i32`);
const nullBranchEnd = this.ctx.getCurrentLabel();
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(strcmpLabel);
const strcmpResult = this.ctx.emitCall("i32", "@strcmp", `i8* ${leftPtr}, i8* ${rightPtr}`);
let cmpResult: string;
if (op === "==" || op === "===") {
cmpResult = this.ctx.emitIcmp("eq", "i32", strcmpResult, "0");
} else if (op === "!=" || op === "!==") {
cmpResult = this.ctx.emitIcmp("ne", "i32", strcmpResult, "0");
} else if (op === "<") {
cmpResult = this.ctx.emitIcmp("slt", "i32", strcmpResult, "0");
} else if (op === ">") {
cmpResult = this.ctx.emitIcmp("sgt", "i32", strcmpResult, "0");
} else if (op === "<=") {
cmpResult = this.ctx.emitIcmp("sle", "i32", strcmpResult, "0");
} else if (op === ">=") {
cmpResult = this.ctx.emitIcmp("sge", "i32", strcmpResult, "0");
} else {
cmpResult = this.ctx.emitIcmp("eq", "i32", strcmpResult, "0");
}
const strcmpResultInt = this.ctx.nextTemp();
this.ctx.emit(`${strcmpResultInt} = zext i1 ${cmpResult} to i32`);
const strcmpBranchEnd = this.ctx.getCurrentLabel();
this.ctx.emitBr(mergeLabel);
this.ctx.emitLabel(mergeLabel);
const i32Result = this.ctx.nextTemp();
this.ctx.emit(
`${i32Result} = phi i32 [ ${nullResultInt}, %${nullBranchEnd} ], [ ${strcmpResultInt}, %${strcmpBranchEnd} ]`,
);
const extResult = this.ctx.nextTemp();
this.ctx.emit(`${extResult} = sitofp i32 ${i32Result} to double`);
this.ctx.setVariableType(extResult, "double");
return extResult;
}
private generateNumericComparison(cond: string, left: string, right: string): string {
const leftType = this.ctx.getVariableType(left);
const rightType = this.ctx.getVariableType(right);
if (leftType === "i64" && rightType === "i64") {
const icmpCond =
cond === "olt"
? "slt"
: cond === "ogt"
? "sgt"
: cond === "ole"
? "sle"
: cond === "oge"
? "sge"
: cond === "oeq"
? "eq"
: "ne";
const cmpResult = this.ctx.emitIcmp(icmpCond, "i64", left, right);
const i64Result = this.ctx.nextTemp();
this.ctx.emit(`${i64Result} = zext i1 ${cmpResult} to i64`);
this.ctx.setVariableType(i64Result, "i64");
return i64Result;
}
let leftDouble = left;
let rightDouble = right;
if (leftType === "i32") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = sitofp i32 ${left} to double`);
leftDouble = temp;
} else if (leftType === "i8*" || (leftType && leftType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${leftType} ${left} to i64`);
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = sitofp i64 ${asInt} to double`);
leftDouble = temp;
} else {
leftDouble = this.ctx.ensureDouble(left);
}
if (rightType === "i32") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = sitofp i32 ${right} to double`);
rightDouble = temp;
} else if (rightType === "i8*" || (rightType && rightType.indexOf("*") !== -1)) {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = ptrtoint ${rightType} ${right} to i64`);
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = sitofp i64 ${asInt} to double`);
rightDouble = temp;
} else {
rightDouble = this.ctx.ensureDouble(right);
}
const cmpResult = this.ctx.nextTemp();
this.ctx.emit(`${cmpResult} = fcmp fast ${cond} double ${leftDouble}, ${rightDouble}`);
// Convert boolean result to double (JavaScript semantics: comparisons return numbers)
const i32Result = this.ctx.nextTemp();
this.ctx.emit(`${i32Result} = zext i1 ${cmpResult} to i32`);
const doubleResult = this.ctx.nextTemp();
this.ctx.emit(`${doubleResult} = sitofp i32 ${i32Result} to double`);
this.ctx.setVariableType(doubleResult, "double");
return doubleResult;
}
private generatePointerNullComparison(op: string, left: string, right: string): string {
const leftType = this.ctx.getVariableType(left) || "i8*";
const rightType = this.ctx.getVariableType(right) || "i8*";
let leftPtr = left;
let rightPtr = right;
if (leftType !== "i8*" && leftType.indexOf("*") !== -1) {
leftPtr = this.ctx.emitBitcast(left, leftType, "i8*");
} else if (leftType === "double") {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = bitcast double ${left} to i64`);
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i64 ${asInt} to i8*`);
leftPtr = temp;
} else if (leftType === "i64") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i64 ${left} to i8*`);
leftPtr = temp;
}
if (rightType !== "i8*" && rightType.indexOf("*") !== -1) {
rightPtr = this.ctx.emitBitcast(right, rightType, "i8*");
} else if (rightType === "double") {
const asInt = this.ctx.nextTemp();
this.ctx.emit(`${asInt} = bitcast double ${right} to i64`);
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i64 ${asInt} to i8*`);
rightPtr = temp;
} else if (rightType === "i64") {
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = inttoptr i64 ${right} to i8*`);
rightPtr = temp;
}
let cond = "";
if (op === "==" || op === "===") {
cond = "eq";
} else if (op === "!=" || op === "!==") {
cond = "ne";
} else {
cond = "eq";
}
const cmpResult = this.ctx.emitIcmp(cond, "i8*", leftPtr, rightPtr);
const i32Result = this.ctx.nextTemp();
this.ctx.emit(`${i32Result} = zext i1 ${cmpResult} to i32`);
const doubleResult = this.ctx.nextTemp();
this.ctx.emit(`${doubleResult} = sitofp i32 ${i32Result} to double`);
this.ctx.setVariableType(doubleResult, "double");
return doubleResult;
}
}