cfg_optimization.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. """Optimizes and analyzes CFG-IR."""
  2. from collections import defaultdict
  3. import modelverse_jit.cfg_ir as cfg_ir
  4. import modelverse_jit.cfg_dominators as cfg_dominators
  5. import modelverse_jit.cfg_ssa_construction as cfg_ssa_construction
  6. def is_empty_block(block):
  7. """Tests if the given block contains no parameters or definitions."""
  8. return len(block.parameters) == 0 and len(block.definitions) == 0
  9. def optimize_flow(block):
  10. """Optimizes the given block's flow instruction."""
  11. changed = True
  12. while changed:
  13. changed = False
  14. # Select flow with a literal condition can be optimized to a direct jump.
  15. if (isinstance(block.flow, cfg_ir.SelectFlow)
  16. and cfg_ir.is_literal_def(block.flow.condition)):
  17. literal = cfg_ir.get_literal_def_value(block.flow.condition)
  18. block.flow = cfg_ir.JumpFlow(
  19. block.flow.if_branch if literal else block.flow.else_branch)
  20. changed = True
  21. # Jumps to blocks which contain no parameters or definitions can be replaced
  22. # by the target block's flow.
  23. if (isinstance(block.flow, cfg_ir.JumpFlow)
  24. and is_empty_block(block.flow.branch.block)
  25. and block.flow.branch.block is not block):
  26. block.flow = block.flow.branch.block.flow
  27. changed = True
  28. # Branches to blocks which contain nothing but a jump can be replaced by branches
  29. # to the jump's target.
  30. for branch in block.flow.branches():
  31. if (is_empty_block(branch.block)
  32. and branch.block is not block
  33. and isinstance(branch.block.flow, cfg_ir.JumpFlow)):
  34. new_branch = branch.block.flow.branch
  35. branch.block = new_branch.block
  36. branch.arguments = new_branch.arguments
  37. changed = True
  38. def optimize_graph_flow(entry_point):
  39. """Optimizes all flow instructions in the graph defined by the given entry point."""
  40. for block in cfg_ir.get_all_blocks(entry_point):
  41. optimize_flow(block)
  42. def merge_blocks(entry_point):
  43. """Merges blocks which have exactly one predecessor with said predecessor, if the
  44. predecessor has a jump flow instruction."""
  45. predecessor_map = cfg_ir.get_all_predecessor_blocks(entry_point)
  46. queue = list(predecessor_map.keys())
  47. def __do_merge(source, target):
  48. for target_param, branch_arg in zip(target.parameters, source.flow.branch.arguments):
  49. source.append_definition(target_param)
  50. target_param.redefine(branch_arg)
  51. for target_def in target.definitions:
  52. source.append_definition(target_def)
  53. source.flow = target.flow
  54. for pred_set in predecessor_map.values():
  55. if target in pred_set:
  56. pred_set.remove(target)
  57. pred_set.add(source)
  58. while len(queue) > 0:
  59. block = queue.pop()
  60. preds = predecessor_map[block]
  61. if len(preds) == 1:
  62. single_pred = next(iter(preds))
  63. if isinstance(single_pred.flow, cfg_ir.JumpFlow):
  64. __do_merge(single_pred, block)
  65. def elide_local_checks(entry_point):
  66. """Tries to elide redundant checks on local variables."""
  67. # The plan here is to replace all check-local-exists defs by literals if
  68. # they are either dominated by an appropriate declare-local or not reachable
  69. # from a declare-local.
  70. local_checks = defaultdict(set)
  71. local_defs = defaultdict(set)
  72. for block in cfg_ir.get_all_blocks(entry_point):
  73. for definition in block.definitions:
  74. if cfg_ir.is_value_def(definition, cfg_ir.CheckLocalExists):
  75. local_checks[cfg_ir.get_def_variable(definition).node_id].add(definition)
  76. elif cfg_ir.is_value_def(definition, cfg_ir.DeclareLocal):
  77. local_defs[cfg_ir.get_def_variable(definition).node_id].add(definition)
  78. dominator_tree = cfg_dominators.get_dominator_tree(entry_point)
  79. reachable_blocks = cfg_ir.get_all_reachable_blocks(entry_point)
  80. for (variable, all_checks) in local_checks.items():
  81. for check in all_checks:
  82. is_reachable = False
  83. for local_def in local_defs[variable]:
  84. if dominator_tree.dominates_instruction(local_def, check):
  85. # Check is dominated by a definition. Replace it by a 'True' literal.
  86. check.redefine(cfg_ir.Literal(True))
  87. is_reachable = True
  88. break
  89. elif check.block in reachable_blocks[local_def.block]:
  90. is_reachable = True
  91. if not is_reachable:
  92. # Check cannot be reached from any definition. Replace it by a 'False' literal.
  93. check.redefine(cfg_ir.Literal(False))
  94. def eliminate_unused_definitions(entry_point):
  95. """Tries to eliminate unused definitions in the control-flow graphb defined by the
  96. given entry point."""
  97. def_dependencies = {}
  98. root_defs = set()
  99. for block in cfg_ir.get_all_blocks(entry_point):
  100. for definition in block.definitions:
  101. def_dependencies[definition] = set(
  102. [dep for dep in definition.get_all_dependencies()
  103. if isinstance(dep, cfg_ir.Definition)])
  104. if definition.has_side_effects():
  105. root_defs.add(definition)
  106. for dep in block.flow.get_all_dependencies():
  107. if isinstance(dep, cfg_ir.Definition):
  108. root_defs.add(dep)
  109. live_defs = set()
  110. def __mark_live(definition):
  111. if definition in live_defs:
  112. return
  113. live_defs.add(definition)
  114. if definition in def_dependencies:
  115. for dep in def_dependencies[definition]:
  116. __mark_live(dep)
  117. for root in root_defs:
  118. __mark_live(root)
  119. dead_defs = set.difference(set(def_dependencies.keys()), live_defs)
  120. for dead_def in dead_defs:
  121. dead_def.block.remove_definition(dead_def)
  122. def eliminate_trivial_phis(entry_point):
  123. """Eliminates trivial block parameters, i.e., block parameters which are really
  124. aliases."""
  125. phi_values = defaultdict(set)
  126. all_blocks = list(cfg_ir.get_all_blocks(entry_point))
  127. for block in all_blocks:
  128. for branch in block.flow.branches():
  129. for phi, arg in zip(branch.block.parameters, branch.arguments):
  130. phi_values[phi].add(arg)
  131. replacements = []
  132. for block in all_blocks:
  133. block_parameters = list(block.parameters)
  134. for parameter_def in block_parameters:
  135. trivial_phi_val = cfg_ir.get_trivial_phi_value(
  136. parameter_def, phi_values[parameter_def])
  137. if trivial_phi_val is not None:
  138. replacements.append((parameter_def, trivial_phi_val))
  139. erase_parameters(entry_point, set([parameter_def for parameter_def, _ in replacements]))
  140. for parameter_def, trivial_phi_val in replacements:
  141. block = parameter_def.block
  142. parameter_def.redefine(trivial_phi_val)
  143. block.prepend_definition(parameter_def)
  144. def erase_parameters(entry_point, parameters_to_erase):
  145. """Erases all arguments for the given set of parameters, and then takes out the
  146. parameters themselves."""
  147. for block in cfg_ir.get_all_blocks(entry_point):
  148. for branch in block.flow.branches():
  149. new_arg_list = []
  150. for parameter, arg in zip(branch.block.parameters, branch.arguments):
  151. if parameter not in parameters_to_erase:
  152. new_arg_list.append(arg)
  153. branch.arguments = new_arg_list
  154. for parameter_def in parameters_to_erase:
  155. parameter_def.block.remove_parameter(parameter_def)
  156. def apply_cfg_intrinsic(intrinsic_function, original_definition, named_args):
  157. """Applies the given intrinsic to the given sequence of named arguments."""
  158. kwargs = dict(named_args)
  159. kwargs['original_def'] = original_definition
  160. return intrinsic_function(**kwargs)
  161. def try_redefine_as_direct_call(definition, jit, called_globals):
  162. """Tries to redefine the given indirect call definition as a direct call."""
  163. call = cfg_ir.get_def_value(definition)
  164. if not isinstance(call, cfg_ir.IndirectFunctionCall):
  165. return
  166. target = cfg_ir.get_def_value(call.target)
  167. if isinstance(target, cfg_ir.LoadPointer):
  168. loaded_ptr = cfg_ir.get_def_value(target.pointer)
  169. if isinstance(loaded_ptr, cfg_ir.ResolveGlobal):
  170. resolved_var_name = loaded_ptr.variable.name
  171. called_globals.add(loaded_ptr)
  172. # Try to resolve the callee as an intrinsic.
  173. intrinsic = jit.get_cfg_intrinsic(resolved_var_name)
  174. if intrinsic is not None:
  175. apply_cfg_intrinsic(intrinsic, definition, call.argument_list)
  176. else:
  177. # Otherwise, build a thunk.
  178. thunk_name = jit.jit_thunk_global(resolved_var_name)
  179. definition.redefine(
  180. cfg_ir.DirectFunctionCall(
  181. thunk_name, call.argument_list, cfg_ir.JIT_CALLING_CONVENTION))
  182. called_globals.add(loaded_ptr)
  183. elif isinstance(target, cfg_ir.Literal):
  184. node_id = target.literal
  185. thunk_name = jit.jit_thunk_constant(node_id)
  186. definition.redefine(
  187. cfg_ir.DirectFunctionCall(
  188. thunk_name, call.argument_list, cfg_ir.JIT_CALLING_CONVENTION))
  189. def get_checked_global(definition):
  190. """If the definition is a check that tests if a global does not exist, then
  191. the instruction that resolves the global is returned; otherwise None."""
  192. def_value = cfg_ir.get_def_value(definition)
  193. if not isinstance(def_value, cfg_ir.Binary):
  194. return None
  195. if def_value.operator != 'is':
  196. return None
  197. def __get_checked_global_single_dir(lhs, rhs):
  198. if (isinstance(lhs, cfg_ir.ResolveGlobal)
  199. and isinstance(rhs, cfg_ir.Literal)
  200. and rhs.literal is None):
  201. return lhs
  202. else:
  203. return None
  204. bin_lhs = cfg_ir.get_def_value(def_value.lhs)
  205. bin_rhs = cfg_ir.get_def_value(def_value.rhs)
  206. result = __get_checked_global_single_dir(bin_lhs, bin_rhs)
  207. if result is None:
  208. result = __get_checked_global_single_dir(bin_rhs, bin_lhs)
  209. return result
  210. def optimize_calls(entry_point, jit):
  211. """Converts indirect calls to direct calls in the control-flow graph defined by the
  212. given entry point."""
  213. called_globals = set()
  214. global_exists_defs = defaultdict(list)
  215. all_blocks = list(cfg_ir.get_all_blocks(entry_point))
  216. for block in all_blocks:
  217. for definition in block.definitions:
  218. checked_global = get_checked_global(definition)
  219. if checked_global is not None:
  220. global_exists_defs[checked_global].append(definition)
  221. else:
  222. try_redefine_as_direct_call(definition, jit, called_globals)
  223. for resolve_global in called_globals:
  224. for exists_def in global_exists_defs[resolve_global]:
  225. exists_def.redefine(cfg_ir.Literal(False))
  226. def simplify_values(entry_point):
  227. """Simplifies values in the control-flow graph defined by the given entry point."""
  228. for block in cfg_ir.get_all_blocks(entry_point):
  229. for definition in block.definitions:
  230. def_val = cfg_ir.get_def_value(definition)
  231. if isinstance(def_val, cfg_ir.Read):
  232. read_node = cfg_ir.get_def_value(def_val.node)
  233. if isinstance(read_node, cfg_ir.CreateNode):
  234. definition.redefine(read_node.value)
  235. elif isinstance(def_val, cfg_ir.Binary):
  236. lhs = cfg_ir.get_def_value(def_val.lhs)
  237. rhs = cfg_ir.get_def_value(def_val.rhs)
  238. if isinstance(lhs, cfg_ir.Literal) and isinstance(rhs, cfg_ir.Literal):
  239. definition.redefine(
  240. cfg_ir.Literal(
  241. eval('%r %s %r' % (lhs.literal, def_val.operator, rhs.literal))))
  242. def inline_constants(entry_point):
  243. """Replaces reads of constant nodes by the literals they contain."""
  244. for block in cfg_ir.get_all_blocks(entry_point):
  245. for definition in block.definitions:
  246. def_val = cfg_ir.get_def_value(definition)
  247. if isinstance(def_val, cfg_ir.Read):
  248. read_node = cfg_ir.get_def_value(def_val.node)
  249. if isinstance(read_node, cfg_ir.Literal):
  250. val, = yield [("RV", [read_node.literal])]
  251. definition.redefine(cfg_ir.Literal(val))
  252. def expand_indirect_definitions(entry_point):
  253. """Replaces indirect definitions by the values referred to by those definitions."""
  254. def __expand_indirect_defs(value):
  255. dependencies = value.get_dependencies()
  256. if len(dependencies) == 0:
  257. return value
  258. else:
  259. new_dependencies = []
  260. for dep in dependencies:
  261. new_dep = dep
  262. if isinstance(new_dep, cfg_ir.Definition):
  263. while isinstance(new_dep.value, cfg_ir.Definition):
  264. new_dep = dep.value
  265. else:
  266. new_dep = __expand_indirect_defs(new_dep)
  267. new_dependencies.append(new_dep)
  268. return value.create(new_dependencies)
  269. for block in cfg_ir.get_all_blocks(entry_point):
  270. block_definitions = list(block.definitions)
  271. for definition in block_definitions:
  272. if isinstance(definition.value, cfg_ir.Definition):
  273. block.remove_definition(definition)
  274. else:
  275. definition.redefine(
  276. __expand_indirect_defs(definition.value))
  277. block.flow = __expand_indirect_defs(block.flow)
  278. def optimize(entry_point, jit):
  279. """Optimizes the control-flow graph defined by the given entry point."""
  280. optimize_graph_flow(entry_point)
  281. elide_local_checks(entry_point)
  282. optimize_graph_flow(entry_point)
  283. eliminate_trivial_phis(entry_point)
  284. # cfg_ssa_construction.construct_ssa_form(entry_point)
  285. optimize_calls(entry_point, jit)
  286. yield [("CALL_ARGS", [inline_constants, (entry_point,)])]
  287. simplify_values(entry_point)
  288. eliminate_unused_definitions(entry_point)
  289. optimize_graph_flow(entry_point)
  290. merge_blocks(entry_point)
  291. expand_indirect_definitions(entry_point)
  292. eliminate_unused_definitions(entry_point)