-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_blocks.ts
46 lines (40 loc) · 1.49 KB
/
basic_blocks.ts
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
import { Function, Program } from "../bril/bril-ts/bril.ts";
import { readStdin } from "../bril/bril-ts/util.ts";
import { Block } from "./types.ts";
let currentBlockNumber = 0;
const generateNewBlock = () => ({ successors: [], insts: [], id: currentBlockNumber++ });
export const formBasicBlocks = (f: Function): Block[] => {
const blocks = [];
let currentBlock: Block = generateNewBlock();
for (const inst of f.instrs) {
if ("label" in inst) {
if (currentBlock.insts.length > 0) {
currentBlock.successors = [inst.label];
blocks.push(currentBlock);
}
currentBlock = { successors: [], insts: [inst], id: inst.label };
} else { // instruction
currentBlock.insts.push(inst);
if (["jmp", "br", "ret"].includes(inst.op)) {
if ("labels" in inst && inst.labels) {
currentBlock.successors = inst.labels;
}
blocks.push(currentBlock);
currentBlock = generateNewBlock();
}
}
}
if (currentBlock.insts.length > 0) {
blocks.push(currentBlock);
}
return blocks;
}
const main = async () => {
const ast: Program = JSON.parse(await readStdin());
for (const func of ast.functions) {
const blocks = formBasicBlocks(func);
console.log(`For function ${func.name}, ${blocks.length} basic blocks:`)
console.log(blocks);
}
}
if (import.meta.main) main();