jit.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import math
  2. import keyword
  3. from collections import defaultdict
  4. import modelverse_kernel.primitives as primitive_functions
  5. class ModelverseJit(object):
  6. """A high-level interface to the modelverse JIT compiler."""
  7. def __init__(self):
  8. self.todo_entry_points = set()
  9. self.jitted_parameters = {}
  10. self.jit_globals = {
  11. 'PrimitiveFinished' : primitive_functions.PrimitiveFinished,
  12. }
  13. # jitted_entry_points maps body ids to values in jit_globals.
  14. self.jitted_entry_points = {}
  15. # global_functions maps global value names to body ids.
  16. self.global_functions = {}
  17. # global_functions_inv maps body ids to global value names.
  18. self.global_functions_inv = {}
  19. # jitted_function_aliases maps body ids to known aliases.
  20. self.jitted_function_aliases = defaultdict(set)
  21. self.jit_count = 0
  22. self.compilation_dependencies = {}
  23. def mark_entry_point(self, body_id):
  24. """Marks the node with the given identifier as a function entry point."""
  25. if body_id not in self.jitted_entry_points:
  26. self.todo_entry_points.add(body_id)
  27. def is_jittable_entry_point(self, body_id):
  28. """Tells if the node with the given identifier is a function entry point that
  29. has not been marked as non-jittable. This only returns `True` if the JIT
  30. is enabled and the function entry point has been marked jittable, or if
  31. the function has already been compiled."""
  32. return ((body_id in self.todo_entry_points) or (body_id in self.jitted_entry_points))
  33. def generate_name(self, infix, suggested_name=None):
  34. """Generates a new name or picks the suggested name if it is still
  35. available."""
  36. if suggested_name is not None \
  37. and suggested_name not in self.jit_globals \
  38. and not keyword.iskeyword(suggested_name):
  39. self.jit_count += 1
  40. return suggested_name
  41. else:
  42. function_name = 'jit_%s%d' % (infix, self.jit_count)
  43. self.jit_count += 1
  44. return function_name
  45. def generate_function_name(self, body_id, suggested_name=None):
  46. """Generates a new function name or picks the suggested name if it is still
  47. available."""
  48. if suggested_name is None:
  49. suggested_name = self.get_global_name(body_id)
  50. return self.generate_name('func', suggested_name)
  51. def register_global(self, body_id, global_name):
  52. """Associates the given body id with the given global name."""
  53. self.global_functions[global_name] = body_id
  54. self.global_functions_inv[body_id] = global_name
  55. def get_global_name(self, body_id):
  56. """Gets the name of the global function with the given body id.
  57. Returns None if no known global exists with the given id."""
  58. if body_id in self.global_functions_inv:
  59. return self.global_functions_inv[body_id]
  60. else:
  61. return None
  62. def get_global_body_id(self, global_name):
  63. """Gets the body id of the global function with the given name.
  64. Returns None if no known global exists with the given name."""
  65. if global_name in self.global_functions:
  66. return self.global_functions[global_name]
  67. else:
  68. return None
  69. def register_compiled(self, body_id, compiled_function, function_name=None):
  70. """Registers a compiled entry point with the JIT."""
  71. # Get the function's name.
  72. actual_function_name = self.generate_function_name(body_id, function_name)
  73. # Map the body id to the given parameter list.
  74. self.jitted_entry_points[body_id] = actual_function_name
  75. self.jit_globals[actual_function_name] = compiled_function
  76. if function_name is not None:
  77. self.register_global(body_id, function_name)
  78. if body_id in self.todo_entry_points:
  79. self.todo_entry_points.remove(body_id)
  80. def __lookup_compiled_body_impl(self, body_id):
  81. """Looks up a compiled function by body id. Returns a matching function,
  82. or None if no function was found."""
  83. if body_id is not None and body_id in self.jitted_entry_points:
  84. return self.jit_globals[self.jitted_entry_points[body_id]]
  85. else:
  86. return None
  87. def __lookup_external_body_impl(self, global_name, body_id):
  88. """Looks up an external function by global name. Returns a matching function,
  89. or None if no function was found."""
  90. if global_name is not None and self.compiled_function_lookup is not None:
  91. result = self.compiled_function_lookup(global_name)
  92. if result is not None and body_id is not None:
  93. self.register_compiled(body_id, result, global_name)
  94. return result
  95. else:
  96. return None
  97. def lookup_compiled_body(self, body_id):
  98. """Looks up a compiled function by body id. Returns a matching function,
  99. or None if no function was found."""
  100. result = self.__lookup_compiled_body_impl(body_id)
  101. if result is not None:
  102. return result
  103. else:
  104. global_name = self.get_global_name(body_id)
  105. return self.__lookup_external_body_impl(global_name, body_id)
  106. def lookup_compiled_function(self, global_name):
  107. """Looks up a compiled function by global name. Returns a matching function,
  108. or None if no function was found."""
  109. body_id = self.get_global_body_id(global_name)
  110. result = self.__lookup_compiled_body_impl(body_id)
  111. if result is not None:
  112. return result
  113. else:
  114. return self.__lookup_external_body_impl(global_name, body_id)
  115. def jit_signature(self, body_id):
  116. """Acquires the signature for the given body id node, which consists of the
  117. parameter variables, parameter name and a flag that tells if the given function
  118. is mutable."""
  119. if body_id not in self.jitted_parameters:
  120. signature_id, = yield [("RRD", [body_id, "body"])]
  121. signature_id = signature_id[0]
  122. param_set_id, is_mutable = yield [
  123. ("RD", [signature_id, "params"]),
  124. ("RD", [signature_id, "mutable"])]
  125. if param_set_id is None:
  126. self.jitted_parameters[body_id] = ([], [], is_mutable)
  127. else:
  128. param_name_ids, = yield [("RDK", [param_set_id])]
  129. param_names = yield [("RV", [n]) for n in param_name_ids]
  130. #NOTE Patch up strange links...
  131. param_names = [i for i in param_names if i is not None]
  132. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  133. #NOTE that variables might not be in the correct order, as we just read them out!
  134. lst = sorted([(name, var) for name, var in zip(param_names, param_vars)])
  135. param_vars = [i[1] for i in lst]
  136. param_names = [i[0] for i in lst]
  137. self.jitted_parameters[body_id] = (param_vars, param_names, is_mutable)
  138. raise primitive_functions.PrimitiveFinished(self.jitted_parameters[body_id])
  139. def check_jittable(self, body_id, suggested_name=None):
  140. """Checks if the function with the given body id is obviously non-jittable. If it's
  141. non-jittable, then a `JitCompilationFailedException` exception is thrown."""
  142. if body_id is None:
  143. raise ValueError('body_id cannot be None: ' + suggested_name)
  144. def jit_define_function(self, function_name, function_def):
  145. """Converts the given tree-IR function definition to Python code, defines it,
  146. and extracts the resulting function."""
  147. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  148. # pylint: disable=I0011,W0122
  149. if self.jit_code_log_function is not None:
  150. self.jit_code_log_function(function_def)
  151. # Convert the function definition to Python code, and compile it.
  152. code_generator = tree_ir.PythonGenerator()
  153. function_def.generate_python_def(code_generator)
  154. source_map_name = self.get_source_map_name(function_name)
  155. if source_map_name is not None:
  156. self.jit_globals[source_map_name] = code_generator.source_map_builder.source_map
  157. exec(str(code_generator), self.jit_globals)
  158. # Extract the compiled function from the JIT global state.
  159. return self.jit_globals[function_name]
  160. def jit_delete_function(self, function_name):
  161. """Deletes the function with the given function name."""
  162. del self.jit_globals[function_name]
  163. import modelverse_kernel.primitives as primitive_functions
  164. class JitCompilationFailedException(Exception):
  165. """A type of exception that is raised when the jit fails to compile a function."""
  166. pass