Skip to content

Commit

Permalink
Refactor to the while codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
Shiritai committed Nov 7, 2024
1 parent 20f4216 commit c2d1bdd
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 49 deletions.
2 changes: 1 addition & 1 deletion src/dominance.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def convert(cls,
"""
# TODO: Compute immediate dominators based on the dominator sets.
idom: dict[BasicBlock, Optional[BasicBlock]] = {}
for (bb, bb_dom) in dom.items():
for bb, bb_dom in dom.items():
candidates = { d: len(dom[d]) for d in bb_dom if d != bb }
if len(candidates) == 0: # first block
idom[bb] = None
Expand Down
18 changes: 18 additions & 0 deletions src/instruction/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

@unique
class ValType(Enum):
"""General value type
"""

@classmethod
def register(cls, tp: type['ValType']):
val_types.update({t.value: t for t in tp})
Expand All @@ -28,11 +31,26 @@ def py_type(self) -> object:
"""Return the corresponding type in Python, default to `None`
"""
return None

@property
def random_val(self):
"""Generate a random value of this type in python data structure
"""
return None

@property
def random_bril_val(self):
"""Generate a random value of this type in bril format
"""
raise NotImplementedError

op_types: Dict[str, 'OpType'] = {}

@unique
class OpType(Enum):
"""General operator type
"""

@classmethod
def register(cls, tp: type['OpType']):
op_types.update({t.value: t for t in tp})
Expand Down
18 changes: 1 addition & 17 deletions src/instruction/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def nargs(self) -> int:
return 2

class CompOpType(OpType):
"""Core comparision operator
"""Core comparison operator
"""

EQ = "eq"
Expand All @@ -34,14 +34,6 @@ class CompOpType(OpType):

@property
def nargs(self) -> int:
"""Get the number of the arguments of `op`
Args:
op (OpType): operator
Returns:
int: the number of the arguments
"""
return 2

class LogicOpType(OpType):
Expand All @@ -54,14 +46,6 @@ class LogicOpType(OpType):

@property
def nargs(self) -> int:
"""Get the number of the arguments of `op`
Args:
op (OpType): operator
Returns:
int: the number of the arguments
"""
return 2 if self != self.NOT else 1

def register_type():
Expand Down
18 changes: 15 additions & 3 deletions src/instruction/value.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import random
from typing import Dict, Union
from instruction.common import ValType

Expand All @@ -17,10 +18,21 @@ class CoreValType(ValType):
def py_type(self):
mapping: Dict[CoreValType, Union[bool, int]] = {
CoreValType.BOOL: bool,
CoreValType.INT: int
}
CoreValType.INT: int}
return mapping[self]


@property
def random_val(self):
rnd = random.randint(0, 1024)
mapping: Dict[CoreValType, Union[bool, int]] = {
CoreValType.BOOL: rnd & 1 == 0,
CoreValType.INT: rnd}
return mapping[self]

@property
def random_bril_val(self):
return f"{self.random_val}".lower()

class NullityType(ValType):
"""Unknown, undefined types
"""
Expand Down
62 changes: 34 additions & 28 deletions src/ssa_construct.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from collections import deque
from bril import Const, EffectOperation, Function, Instruction, Label, ValueOperation
from bril import Const, Function, Instruction, Label, ValueOperation
from cfg import CFG, BasicBlock
from instruction.value import NullityType
from instruction.common import ValType
from instruction.ssa import SsaOpType
from util import new_name
Expand Down Expand Up @@ -98,59 +99,64 @@ def rename_variables(cfg: CFG,
# TODO: Implement variable renaming
names = set(defs)
rename_stacks: dict[str, list[int]] = {}
sep = '.'

def rename(var: str):
renamed_var = new_name(f"{var}.", names, 0)
renamed_var = new_name(f"{var}{sep}", names, 0)
names.add(renamed_var)
rename_stacks.setdefault(var, []).append(renamed_var)
return renamed_var

def scan_and_rename(bb: BasicBlock, depth = 0):

def scan_and_rename(bb: BasicBlock):
# Snapshot current stack for restoration
# at the end of this recursive function
snapshot = { k: list(v) for k, v in rename_stacks.items() }

# Rename dest of phis
for phi in bb.get_by_op(SsaOpType.PHI):
phi.dest = rename(phi.dest)

local_defs: set[str] = set()
# Rename all the variables in the successor renamed in this BB
local_defs: set[str] = set() # local definition of the successor
for i in bb.insts:
if (isinstance(i, (ValueOperation, Const)) and
i.op != SsaOpType.PHI):
if hasattr(i, 'args') and i.args is not None:
i.args = [rename_stacks[arg][-1] if arg in rename_stacks else arg
for arg in i.args]
if i.dest in global_names or i.dest in local_defs or i.dest.find('.') == -1:
i.dest = rename(i.dest)
local_defs.add(i.dest)
if (isinstance(i, EffectOperation) and
i.op != SsaOpType.PHI):
if i.op != SsaOpType.PHI:
if hasattr(i, 'args') and i.args is not None:
i.args = [rename_stacks[arg][-1] if arg in rename_stacks else arg
for arg in i.args]
if hasattr(i, 'dest') and i.dest is not None:
if i.dest in global_names or i.dest in local_defs or sep not in i.dest:
i.dest = rename(i.dest)
local_defs.add(i.dest)

# rename phi in succ
# rename phi arguments in successor
for sbb in bb.succs:
for i in sbb.insts:
if (isinstance(i, ValueOperation) and
i.op == SsaOpType.PHI):
# TODO fill in phi parameters
dot = i.dest.find('.')
var = i.dest if dot == -1 else i.dest[:dot]
if rename_stacks.get(var) is not None:
if i.op == SsaOpType.PHI:
if not isinstance(i.dest, str):
err = ValueError(f"Invalid destination for inst {i}")
logger.error(err)
raise err
dot = i.dest.split(sep)
var = sep.join(dot if len(dot) == 1 else dot[:-1])
if var in rename_stacks:
i.args.append(rename_stacks[var][-1])
i.labels.append(bb.label)
else:
i.args.append(f"{var}.undefined")
i.labels.append(bb.label)
i.args.append(f"{var}.{NullityType.UNDEFINED.name}")
# Add corresponding label
i.labels.append(bb.label)

# Recursive rename based on the dominator tree
for sbb in dom_tree.children.get(bb.label, []):
scan_and_rename(sbb, depth + 1)
scan_and_rename(sbb)

# Restore stack state
rename_stacks.clear()
rename_stacks.update(snapshot)

# Include function arguments
for arg_idx in range(len(cfg.function.args)):
cfg.function.args[arg_idx]['name'] = rename(cfg.function.args[arg_idx]['name'])
for arg in cfg.function.args:
arg['name'] = rename(arg['name'])
# Start recursive rename
scan_and_rename(cfg.entry_block)

def reconstruct_instructions(cfg: CFG) -> list[Instruction]:
Expand Down

0 comments on commit c2d1bdd

Please sign in to comment.