bytecode_to_cfg.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Converts bytecode IR to CFG IR."""
  2. import modelverse_jit.bytecode_ir as bytecode_ir
  3. import modelverse_jit.cfg_ir as cfg_ir
  4. import modelverse_jit.runtime as jit_runtime
  5. class AnalysisState(object):
  6. """State that is common to the bytecode->CFG transformation of a function."""
  7. def __init__(self):
  8. self.counter = cfg_ir.SharedCounter()
  9. self.analyzed_instructions = set()
  10. self.loop_instructions = {}
  11. self.entry_point = cfg_ir.BasicBlock(self.counter)
  12. self.current_block = self.entry_point
  13. self.root_node = None
  14. self.__write_prolog()
  15. def __write_prolog(self):
  16. # Write a prolog in CFG IR.
  17. # We want to create the following definition:
  18. #
  19. # !entry_point():
  20. # $jit_locals = alloc-root-node
  21. #
  22. # We also want to store '$jit_locals' in an attribute, so we can
  23. # use it to shield locals from the GC.
  24. self.root_node = self.current_block.append_definition(cfg_ir.AllocateRootNode())
  25. def analyze(self, instruction):
  26. """Analyzes the given instruction as a basic block."""
  27. if instruction in self.analyzed_instructions:
  28. raise jit_runtime.JitCompilationFailedException(
  29. 'Cannot jit non-tree instruction graph.')
  30. self.analyzed_instructions.add(instruction)
  31. # Find an analyzer.
  32. instruction_type = type(instruction)
  33. if instruction_type in self.instruction_analyzers:
  34. # Analyze the instruction.
  35. result = self.instruction_analyzers[instruction_type](self, instruction)
  36. # Check if the instruction has a 'next' instruction. If so, analyze it!
  37. if instruction.next_instruction is not None:
  38. next_result = self.analyze(instruction.next_instruction)
  39. if next_result.value.has_value() or (not result.value.has_value()):
  40. result = next_result
  41. return result
  42. else:
  43. raise jit_runtime.JitCompilationFailedException(
  44. "Unknown instruction type: '%s'" % type(instruction))
  45. def emit_select(self, create_condition, create_if_body, create_else_body):
  46. """Emits a 'select' instruction."""
  47. # Create blocks that look like this:
  48. #
  49. # !current_block(...):
  50. # ...
  51. # $cond = <condition>
  52. # select $cond, !if_block(), !else_block()
  53. #
  54. # !if_block():
  55. # $if_result = <if-body>
  56. # jump !phi_block($if_result)
  57. #
  58. # !else_block():
  59. # $else_result = <else-body>
  60. # jump !phi_block($else_result)
  61. #
  62. # !phi_block($result = block-parameter):
  63. # ...
  64. #
  65. if_block = cfg_ir.BasicBlock(self.counter)
  66. else_block = cfg_ir.BasicBlock(self.counter)
  67. phi_block = cfg_ir.BasicBlock(self.counter)
  68. param_def = phi_block.append_parameter(cfg_ir.BlockParameter())
  69. condition = create_condition()
  70. self.current_block.flow = cfg_ir.SelectFlow(
  71. condition, cfg_ir.Branch(if_block), cfg_ir.Branch(else_block))
  72. self.current_block = if_block
  73. if_result = create_if_body()
  74. self.current_block.flow = cfg_ir.create_jump(phi_block, [if_result])
  75. self.current_block = else_block
  76. else_result = create_else_body()
  77. self.current_block.flow = cfg_ir.create_jump(phi_block, [else_result])
  78. self.current_block = phi_block
  79. return param_def
  80. def analyze_if(self, instruction):
  81. """Analyzes an 'if' instruction."""
  82. return self.emit_select(
  83. lambda: self.analyze(instruction.condition),
  84. lambda: self.analyze(instruction.if_clause),
  85. lambda:
  86. self.current_block.append_definition(cfg_ir.Literal(None))
  87. if instruction.else_clause is None
  88. else self.analyze(instruction.else_clause))
  89. def analyze_while(self, instruction):
  90. """Analyzes a 'while' instruction."""
  91. # Create blocks that look like this:
  92. #
  93. # !current_block(...):
  94. # ...
  95. # jump !loop_condition()
  96. #
  97. # !loop_condition():
  98. # $condition = <condition>
  99. # select $condition, !loop_body(), !loop_exit()
  100. #
  101. # !loop_body():
  102. # $result = <body>
  103. # jump !loop_condition()
  104. #
  105. # !loop_exit():
  106. # $nothing = literal None
  107. # ...
  108. loop_condition_block = cfg_ir.BasicBlock(self.counter)
  109. loop_body_block = cfg_ir.BasicBlock(self.counter)
  110. loop_exit_block = cfg_ir.BasicBlock(self.counter)
  111. self.loop_instructions[instruction] = (loop_condition_block, loop_exit_block)
  112. self.current_block.flow = cfg_ir.create_jump(loop_condition_block)
  113. self.current_block = loop_condition_block
  114. condition_value = self.analyze(instruction.condition)
  115. self.current_block.flow = cfg_ir.SelectFlow(
  116. condition_value, cfg_ir.Branch(loop_body_block), cfg_ir.Branch(loop_exit_block))
  117. self.current_block = loop_body_block
  118. self.analyze(instruction.body)
  119. self.current_block.flow = cfg_ir.create_jump(loop_condition_block)
  120. self.current_block = loop_exit_block
  121. return loop_exit_block.append_definition(cfg_ir.Literal(None))
  122. def analyze_return(self, instruction):
  123. """Analyzes a 'return' instruction."""
  124. if instruction.value is None:
  125. return_value = self.current_block.append_definition(cfg_ir.Literal(None))
  126. else:
  127. return_value = self.analyze(instruction.value)
  128. # Don't forget to deallocate the root node.
  129. self.current_block.append_definition(cfg_ir.DeallocateRootNode(self.root_node))
  130. self.current_block.flow = cfg_ir.ReturnFlow(return_value)
  131. self.current_block = cfg_ir.BasicBlock(self.counter)
  132. return self.current_block.append_definition(cfg_ir.Literal(None))
  133. def analyze_constant(self, instruction):
  134. """Analyzes a 'constant' instruction."""
  135. return self.current_block.append_definition(cfg_ir.Literal(instruction.constant_id))
  136. def analyze_resolve(self, instruction):
  137. """Analyzes a 'resolve' instruction."""
  138. return self.emit_select(
  139. lambda:
  140. self.current_block.append_definition(
  141. cfg_ir.CheckLocalExists(instruction.variable)),
  142. lambda:
  143. self.current_block.append_definition(
  144. cfg_ir.ResolveLocal(instruction.variable)),
  145. lambda:
  146. self.current_block.append_definition(
  147. cfg_ir.ResolveGlobal(instruction.variable)))
  148. def analyze_declare(self, instruction):
  149. """Analyzes a 'declare' instruction."""
  150. return self.current_block.append_definition(
  151. cfg_ir.DeclareLocal(instruction.variable, self.root_node))
  152. def analyze_global(self, instruction):
  153. """Analyzes a 'global' instruction."""
  154. return self.current_block.append_definition(cfg_ir.DeclareGlobal(instruction.variable))
  155. def analyze_assign(self, instruction):
  156. """Analyzes an 'assign' instruction."""
  157. pointer_result = self.analyze(instruction.pointer)
  158. value_result = self.analyze(instruction.value)
  159. return self.current_block.append_definition(
  160. cfg_ir.StoreAtPointer(pointer_result, value_result))
  161. def analyze_access(self, instruction):
  162. """Analyzes an 'access' instruction."""
  163. pointer_result = self.analyze(instruction.pointer)
  164. return self.current_block.append_definition(cfg_ir.LoadPointer(pointer_result))
  165. def analyze_output(self, instruction):
  166. """Analyzes an 'output' instruction."""
  167. value_result = self.analyze(instruction.value)
  168. return self.current_block.append_definition(cfg_ir.Output(value_result))
  169. def analyze_input(self, _):
  170. """Analyzes an 'input' instruction."""
  171. return self.current_block.append_definition(cfg_ir.Input())
  172. def analyze_break(self, instruction):
  173. """Analyzes a 'break' instruction."""
  174. if instruction.loop not in self.loop_instructions:
  175. raise jit_runtime.JitCompilationFailedException(
  176. "'break' instruction targets a 'while' loop that has not been defined yet.")
  177. _, exit_block = self.loop_instructions[instruction.loop]
  178. self.current_block.flow = cfg_ir.create_jump(exit_block)
  179. self.current_block = cfg_ir.BasicBlock(self.counter)
  180. return self.current_block.append_definition(cfg_ir.Literal(None))
  181. def analyze_continue(self, instruction):
  182. """Analyzes a 'continue' instruction."""
  183. if instruction.loop not in self.loop_instructions:
  184. raise jit_runtime.JitCompilationFailedException(
  185. "'continue' instruction targets a 'while' loop that has not been defined yet.")
  186. cond_block, _ = self.loop_instructions[instruction.loop]
  187. self.current_block.flow = cfg_ir.create_jump(cond_block)
  188. self.current_block = cfg_ir.BasicBlock(self.counter)
  189. return self.current_block.append_definition(cfg_ir.Literal(None))
  190. def analyze_call(self, instruction):
  191. """Analyzes the given 'call' instruction."""
  192. target = self.analyze(instruction.target)
  193. arg_list = []
  194. for key, arg_instruction in instruction.argument_list:
  195. arg_list.append((key, self.analyze(arg_instruction)))
  196. return self.current_block.append_definition(cfg_ir.JitFunctionCall(target, arg_list))
  197. instruction_analyzers = {
  198. bytecode_ir.SelectInstruction : analyze_if,
  199. bytecode_ir.WhileInstruction : analyze_while,
  200. bytecode_ir.ReturnInstruction : analyze_return,
  201. bytecode_ir.ConstantInstruction : analyze_constant,
  202. bytecode_ir.ResolveInstruction : analyze_resolve,
  203. bytecode_ir.DeclareInstruction : analyze_declare,
  204. bytecode_ir.GlobalInstruction : analyze_global,
  205. bytecode_ir.AssignInstruction : analyze_assign,
  206. bytecode_ir.AccessInstruction : analyze_access,
  207. bytecode_ir.OutputInstruction : analyze_output,
  208. bytecode_ir.InputInstruction : analyze_input,
  209. bytecode_ir.CallInstruction : analyze_call,
  210. bytecode_ir.BreakInstruction : analyze_break,
  211. bytecode_ir.ContinueInstruction : analyze_continue
  212. }