jit.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. import keyword
  2. import modelverse_kernel.primitives as primitive_functions
  3. import modelverse_jit.bytecode_parser as bytecode_parser
  4. import modelverse_jit.bytecode_to_tree as bytecode_to_tree
  5. import modelverse_jit.bytecode_to_cfg as bytecode_to_cfg
  6. import modelverse_jit.cfg_optimization as cfg_optimization
  7. import modelverse_jit.cfg_to_tree as cfg_to_tree
  8. import modelverse_jit.cfg_ir as cfg_ir
  9. import modelverse_jit.tree_ir as tree_ir
  10. import modelverse_jit.runtime as jit_runtime
  11. # Import JitCompilationFailedException because it used to be defined
  12. # in this module.
  13. JitCompilationFailedException = jit_runtime.JitCompilationFailedException
  14. def map_and_simplify_generator(function, instruction):
  15. """Applies the given mapping function to every instruction in the tree
  16. that has the given instruction as root, and simplifies it on-the-fly.
  17. This is at least as powerful as first mapping and then simplifying, as
  18. maps and simplifications are interspersed.
  19. This function assumes that function creates a generator that returns by
  20. raising a primitive_functions.PrimitiveFinished."""
  21. # First handle the children by mapping on them and then simplifying them.
  22. new_children = []
  23. for inst in instruction.get_children():
  24. new_inst, = yield [("CALL_ARGS", [map_and_simplify_generator, (function, inst)])]
  25. new_children.append(new_inst)
  26. # Then apply the function to the top-level node.
  27. transformed, = yield [("CALL_ARGS", [function, (instruction.create(new_children),)])]
  28. # Finally, simplify the transformed top-level node.
  29. raise primitive_functions.PrimitiveFinished(transformed.simplify_node())
  30. def expand_constant_read(instruction):
  31. """Tries to replace a read of a constant node by a literal."""
  32. if isinstance(instruction, tree_ir.ReadValueInstruction) and \
  33. isinstance(instruction.node_id, tree_ir.LiteralInstruction):
  34. val, = yield [("RV", [instruction.node_id.literal])]
  35. raise primitive_functions.PrimitiveFinished(tree_ir.LiteralInstruction(val))
  36. else:
  37. raise primitive_functions.PrimitiveFinished(instruction)
  38. def optimize_tree_ir(instruction):
  39. """Optimizes an IR tree."""
  40. return map_and_simplify_generator(expand_constant_read, instruction)
  41. def create_bare_function(function_name, parameter_list, function_body):
  42. """Creates a function definition from the given function name, parameter list
  43. and function body. No prolog is included."""
  44. # Wrap the IR in a function definition, give it a unique name.
  45. return tree_ir.DefineFunctionInstruction(
  46. function_name,
  47. parameter_list + ['**' + jit_runtime.KWARGS_PARAMETER_NAME],
  48. function_body)
  49. def create_function(
  50. function_name, parameter_list, param_dict,
  51. body_param_dict, function_body, source_map_name=None):
  52. """Creates a function from the given function name, parameter list,
  53. variable-to-parameter name map, variable-to-local name map and
  54. function body. An optional source map can be included, too."""
  55. # Write a prologue and prepend it to the generated function body.
  56. prolog_statements = []
  57. # If the source map is not None, then we should generate a "DEBUG_INFO"
  58. # request.
  59. if source_map_name is not None:
  60. prolog_statements.append(
  61. tree_ir.RegisterDebugInfoInstruction(
  62. tree_ir.LiteralInstruction(function_name),
  63. tree_ir.LoadGlobalInstruction(source_map_name),
  64. tree_ir.LiteralInstruction(jit_runtime.BASELINE_JIT_ORIGIN_NAME)))
  65. # Create a LOCALS_NODE_NAME node, and connect it to the user root.
  66. prolog_statements.append(
  67. tree_ir.create_new_local_node(
  68. jit_runtime.LOCALS_NODE_NAME,
  69. tree_ir.LoadIndexInstruction(
  70. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  71. tree_ir.LiteralInstruction('task_root')),
  72. jit_runtime.LOCALS_EDGE_NAME))
  73. for (key, val) in param_dict.items():
  74. arg_ptr = tree_ir.create_new_local_node(
  75. body_param_dict[key],
  76. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))
  77. prolog_statements.append(arg_ptr)
  78. prolog_statements.append(
  79. tree_ir.CreateDictionaryEdgeInstruction(
  80. tree_ir.LoadLocalInstruction(body_param_dict[key]),
  81. tree_ir.LiteralInstruction('value'),
  82. tree_ir.LoadLocalInstruction(val)))
  83. constructed_body = tree_ir.create_block(
  84. *(prolog_statements + [function_body]))
  85. # Shield temporaries from the GC.
  86. constructed_body = tree_ir.protect_temporaries_from_gc(
  87. constructed_body, tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))
  88. return create_bare_function(function_name, parameter_list, constructed_body)
  89. def print_value(val):
  90. """A thin wrapper around 'print'."""
  91. print(val)
  92. class ModelverseJit(object):
  93. """A high-level interface to the modelverse JIT compiler."""
  94. def __init__(self, max_instructions=None, compiled_function_lookup=None):
  95. self.todo_entry_points = set()
  96. self.no_jit_entry_points = set()
  97. self.jitted_parameters = {}
  98. self.jit_globals = {
  99. 'PrimitiveFinished' : primitive_functions.PrimitiveFinished,
  100. jit_runtime.CALL_FUNCTION_NAME : jit_runtime.call_function,
  101. jit_runtime.GET_INPUT_FUNCTION_NAME : jit_runtime.get_input,
  102. jit_runtime.JIT_THUNK_CONSTANT_FUNCTION_NAME : self.jit_thunk_constant_function,
  103. jit_runtime.JIT_THUNK_GLOBAL_FUNCTION_NAME : self.jit_thunk_global,
  104. jit_runtime.JIT_REJIT_FUNCTION_NAME : self.jit_rejit,
  105. jit_runtime.JIT_COMPILE_FUNCTION_BODY_FAST_FUNCTION_NAME : compile_function_body_fast,
  106. jit_runtime.UNREACHABLE_FUNCTION_NAME : jit_runtime.unreachable
  107. }
  108. # jitted_entry_points maps body ids to values in jit_globals.
  109. self.jitted_entry_points = {}
  110. # global_functions maps global value names to body ids.
  111. self.global_functions = {}
  112. # global_functions_inv maps body ids to global value names.
  113. self.global_functions_inv = {}
  114. # bytecode_graphs maps body ids to their parsed bytecode graphs.
  115. self.bytecode_graphs = {}
  116. self.jit_count = 0
  117. self.max_instructions = max_instructions
  118. self.compiled_function_lookup = compiled_function_lookup
  119. # jit_intrinsics is a function name -> intrinsic map.
  120. self.jit_intrinsics = {}
  121. # cfg_jit_intrinsics is a function name -> intrinsic map.
  122. self.cfg_jit_intrinsics = {}
  123. self.compilation_dependencies = {}
  124. self.jit_enabled = True
  125. self.direct_calls_allowed = True
  126. self.tracing_enabled = False
  127. self.source_maps_enabled = True
  128. self.input_function_enabled = False
  129. self.nop_insertion_enabled = True
  130. self.thunks_enabled = True
  131. self.jit_success_log_function = None
  132. self.jit_code_log_function = None
  133. self.compile_function_body = compile_function_body_baseline
  134. def set_jit_enabled(self, is_enabled=True):
  135. """Enables or disables the JIT."""
  136. self.jit_enabled = is_enabled
  137. def allow_direct_calls(self, is_allowed=True):
  138. """Allows or disallows direct calls from jitted to jitted code."""
  139. self.direct_calls_allowed = is_allowed
  140. def use_input_function(self, is_enabled=True):
  141. """Configures the JIT to compile 'input' instructions as function calls."""
  142. self.input_function_enabled = is_enabled
  143. def enable_tracing(self, is_enabled=True):
  144. """Enables or disables tracing for jitted code."""
  145. self.tracing_enabled = is_enabled
  146. def enable_source_maps(self, is_enabled=True):
  147. """Enables or disables the creation of source maps for jitted code. Source maps
  148. convert lines in the generated code to debug information.
  149. Source maps are enabled by default."""
  150. self.source_maps_enabled = is_enabled
  151. def enable_nop_insertion(self, is_enabled=True):
  152. """Enables or disables nop insertion for jitted code. If enabled, the JIT will
  153. insert nops at loop back-edges. Inserting nops sacrifices performance to
  154. keep the jitted code from blocking the thread of execution and consuming
  155. all resources; nops give the Modelverse server an opportunity to interrupt
  156. the currently running code."""
  157. self.nop_insertion_enabled = is_enabled
  158. def enable_thunks(self, is_enabled=True):
  159. """Enables or disables thunks for jitted code. Thunks delay the compilation of
  160. functions until they are actually used. Thunks generally reduce start-up
  161. time.
  162. Thunks are enabled by default."""
  163. self.thunks_enabled = is_enabled
  164. def set_jit_success_log(self, log_function=print_value):
  165. """Configures this JIT instance with a function that prints output to a log.
  166. Success and failure messages for specific functions are then sent to said log."""
  167. self.jit_success_log_function = log_function
  168. def set_jit_code_log(self, log_function=print_value):
  169. """Configures this JIT instance with a function that prints output to a log.
  170. Function definitions of jitted functions are then sent to said log."""
  171. self.jit_code_log_function = log_function
  172. def set_function_body_compiler(self, compile_function_body):
  173. """Sets the function that the JIT uses to compile function bodies."""
  174. self.compile_function_body = compile_function_body
  175. def mark_entry_point(self, body_id):
  176. """Marks the node with the given identifier as a function entry point."""
  177. if body_id not in self.no_jit_entry_points and body_id not in self.jitted_entry_points:
  178. self.todo_entry_points.add(body_id)
  179. def is_entry_point(self, body_id):
  180. """Tells if the node with the given identifier is a function entry point."""
  181. return body_id in self.todo_entry_points or \
  182. body_id in self.no_jit_entry_points or \
  183. body_id in self.jitted_entry_points
  184. def is_jittable_entry_point(self, body_id):
  185. """Tells if the node with the given identifier is a function entry point that
  186. has not been marked as non-jittable. This only returns `True` if the JIT
  187. is enabled and the function entry point has been marked jittable, or if
  188. the function has already been compiled."""
  189. return ((self.jit_enabled and body_id in self.todo_entry_points) or
  190. self.has_compiled(body_id))
  191. def has_compiled(self, body_id):
  192. """Tests if the function belonging to the given body node has been compiled yet."""
  193. return body_id in self.jitted_entry_points
  194. def get_compiled_name(self, body_id):
  195. """Gets the name of the compiled version of the given body node in the JIT
  196. global state."""
  197. if body_id in self.jitted_entry_points:
  198. return self.jitted_entry_points[body_id]
  199. else:
  200. return None
  201. def mark_no_jit(self, body_id):
  202. """Informs the JIT that the node with the given identifier is a function entry
  203. point that must never be jitted."""
  204. self.no_jit_entry_points.add(body_id)
  205. if body_id in self.todo_entry_points:
  206. self.todo_entry_points.remove(body_id)
  207. def generate_name(self, infix, suggested_name=None):
  208. """Generates a new name or picks the suggested name if it is still
  209. available."""
  210. if suggested_name is not None \
  211. and suggested_name not in self.jit_globals \
  212. and not keyword.iskeyword(suggested_name):
  213. self.jit_count += 1
  214. return suggested_name
  215. else:
  216. function_name = 'jit_%s%d' % (infix, self.jit_count)
  217. self.jit_count += 1
  218. return function_name
  219. def generate_function_name(self, body_id, suggested_name=None):
  220. """Generates a new function name or picks the suggested name if it is still
  221. available."""
  222. if suggested_name is None:
  223. suggested_name = self.get_global_name(body_id)
  224. return self.generate_name('func', suggested_name)
  225. def register_global(self, body_id, global_name):
  226. """Associates the given body id with the given global name."""
  227. self.global_functions[global_name] = body_id
  228. self.global_functions_inv[body_id] = global_name
  229. def get_global_name(self, body_id):
  230. """Gets the name of the global function with the given body id.
  231. Returns None if no known global exists with the given id."""
  232. if body_id in self.global_functions_inv:
  233. return self.global_functions_inv[body_id]
  234. else:
  235. return None
  236. def get_global_body_id(self, global_name):
  237. """Gets the body id of the global function with the given name.
  238. Returns None if no known global exists with the given name."""
  239. if global_name in self.global_functions:
  240. return self.global_functions[global_name]
  241. else:
  242. return None
  243. def register_compiled(self, body_id, compiled_function, function_name=None):
  244. """Registers a compiled entry point with the JIT."""
  245. # Get the function's name.
  246. actual_function_name = self.generate_function_name(body_id, function_name)
  247. # Map the body id to the given parameter list.
  248. self.jitted_entry_points[body_id] = actual_function_name
  249. self.jit_globals[actual_function_name] = compiled_function
  250. if function_name is not None:
  251. self.register_global(body_id, function_name)
  252. if body_id in self.todo_entry_points:
  253. self.todo_entry_points.remove(body_id)
  254. def import_value(self, value, suggested_name=None):
  255. """Imports the given value into the JIT's global scope, with the given suggested name.
  256. The actual name of the value (within the JIT's global scope) is returned."""
  257. actual_name = self.generate_name('import', suggested_name)
  258. self.jit_globals[actual_name] = value
  259. return actual_name
  260. def __lookup_compiled_body_impl(self, body_id):
  261. """Looks up a compiled function by body id. Returns a matching function,
  262. or None if no function was found."""
  263. if body_id is not None and body_id in self.jitted_entry_points:
  264. return self.jit_globals[self.jitted_entry_points[body_id]]
  265. else:
  266. return None
  267. def __lookup_external_body_impl(self, global_name, body_id):
  268. """Looks up an external function by global name. Returns a matching function,
  269. or None if no function was found."""
  270. if global_name is not None and self.compiled_function_lookup is not None:
  271. result = self.compiled_function_lookup(global_name)
  272. if result is not None and body_id is not None:
  273. self.register_compiled(body_id, result, global_name)
  274. return result
  275. else:
  276. return None
  277. def lookup_compiled_body(self, body_id):
  278. """Looks up a compiled function by body id. Returns a matching function,
  279. or None if no function was found."""
  280. result = self.__lookup_compiled_body_impl(body_id)
  281. if result is not None:
  282. return result
  283. else:
  284. global_name = self.get_global_name(body_id)
  285. return self.__lookup_external_body_impl(global_name, body_id)
  286. def lookup_compiled_function(self, global_name):
  287. """Looks up a compiled function by global name. Returns a matching function,
  288. or None if no function was found."""
  289. body_id = self.get_global_body_id(global_name)
  290. result = self.__lookup_compiled_body_impl(body_id)
  291. if result is not None:
  292. return result
  293. else:
  294. return self.__lookup_external_body_impl(global_name, body_id)
  295. def get_intrinsic(self, name):
  296. """Tries to find an intrinsic version of the function with the
  297. given name."""
  298. if name in self.jit_intrinsics:
  299. return self.jit_intrinsics[name]
  300. else:
  301. return None
  302. def get_cfg_intrinsic(self, name):
  303. """Tries to find an intrinsic version of the function with the
  304. given name that is specialized for CFGs."""
  305. if name in self.cfg_jit_intrinsics:
  306. return self.cfg_jit_intrinsics[name]
  307. else:
  308. return None
  309. def register_intrinsic(self, name, intrinsic_function, cfg_intrinsic_function=None):
  310. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  311. the function with the given entry point by an application of the specified function."""
  312. self.jit_intrinsics[name] = intrinsic_function
  313. if cfg_intrinsic_function is not None:
  314. self.register_cfg_intrinsic(name, cfg_intrinsic_function)
  315. def register_cfg_intrinsic(self, name, cfg_intrinsic_function):
  316. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  317. the function with the given entry point by an application of the specified function."""
  318. self.cfg_jit_intrinsics[name] = cfg_intrinsic_function
  319. def register_binary_intrinsic(self, name, operator):
  320. """Registers an intrinsic with the JIT that represents the given binary operation."""
  321. self.register_intrinsic(
  322. name,
  323. lambda a, b:
  324. tree_ir.CreateNodeWithValueInstruction(
  325. tree_ir.BinaryInstruction(
  326. tree_ir.ReadValueInstruction(a),
  327. operator,
  328. tree_ir.ReadValueInstruction(b))),
  329. lambda original_def, a, b:
  330. original_def.redefine(
  331. cfg_ir.CreateNode(
  332. original_def.insert_before(
  333. cfg_ir.Binary(
  334. original_def.insert_before(cfg_ir.Read(a)),
  335. operator,
  336. original_def.insert_before(cfg_ir.Read(b)))))))
  337. def register_unary_intrinsic(self, name, operator):
  338. """Registers an intrinsic with the JIT that represents the given unary operation."""
  339. self.register_intrinsic(
  340. name,
  341. lambda a:
  342. tree_ir.CreateNodeWithValueInstruction(
  343. tree_ir.UnaryInstruction(
  344. operator,
  345. tree_ir.ReadValueInstruction(a))),
  346. lambda original_def, a:
  347. original_def.redefine(
  348. cfg_ir.CreateNode(
  349. original_def.insert_before(
  350. cfg_ir.Unary(
  351. operator,
  352. original_def.insert_before(cfg_ir.Read(a)))))))
  353. def register_cast_intrinsic(self, name, target_type):
  354. """Registers an intrinsic with the JIT that represents a unary conversion operator."""
  355. self.register_intrinsic(
  356. name,
  357. lambda a:
  358. tree_ir.CreateNodeWithValueInstruction(
  359. tree_ir.CallInstruction(
  360. tree_ir.LoadGlobalInstruction(target_type.__name__),
  361. [tree_ir.ReadValueInstruction(a)])),
  362. lambda original_def, a:
  363. original_def.redefine(
  364. cfg_ir.CreateNode(
  365. original_def.insert_before(
  366. cfg_ir.create_pure_simple_call(
  367. target_type.__name__,
  368. original_def.insert_before(cfg_ir.Read(a)))))))
  369. def jit_signature(self, body_id):
  370. """Acquires the signature for the given body id node, which consists of the
  371. parameter variables, parameter name and a flag that tells if the given function
  372. is mutable."""
  373. if body_id not in self.jitted_parameters:
  374. signature_id, = yield [("RRD", [body_id, jit_runtime.FUNCTION_BODY_KEY])]
  375. signature_id = signature_id[0]
  376. param_set_id, is_mutable = yield [
  377. ("RD", [signature_id, "params"]),
  378. ("RD", [signature_id, jit_runtime.MUTABLE_FUNCTION_KEY])]
  379. if param_set_id is None:
  380. self.jitted_parameters[body_id] = ([], [], is_mutable)
  381. else:
  382. param_name_ids, = yield [("RDK", [param_set_id])]
  383. param_names = yield [("RV", [n]) for n in param_name_ids]
  384. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  385. self.jitted_parameters[body_id] = (param_vars, param_names, is_mutable)
  386. raise primitive_functions.PrimitiveFinished(self.jitted_parameters[body_id])
  387. def jit_parse_bytecode(self, body_id):
  388. """Parses the given function body as a bytecode graph."""
  389. if body_id in self.bytecode_graphs:
  390. raise primitive_functions.PrimitiveFinished(self.bytecode_graphs[body_id])
  391. parser = bytecode_parser.BytecodeParser()
  392. result, = yield [("CALL_ARGS", [parser.parse_instruction, (body_id,)])]
  393. self.bytecode_graphs[body_id] = result
  394. raise primitive_functions.PrimitiveFinished(result)
  395. def check_jittable(self, body_id, suggested_name=None):
  396. """Checks if the function with the given body id is obviously non-jittable. If it's
  397. non-jittable, then a `JitCompilationFailedException` exception is thrown."""
  398. if body_id is None:
  399. raise ValueError('body_id cannot be None')
  400. elif body_id in self.no_jit_entry_points:
  401. # We're not allowed to jit this function or have tried and failed before.
  402. raise JitCompilationFailedException(
  403. 'Cannot jit function %s at %d because it is marked non-jittable.' % (
  404. '' if suggested_name is None else "'" + suggested_name + "'",
  405. body_id))
  406. elif not self.jit_enabled:
  407. # We're not allowed to jit anything.
  408. raise JitCompilationFailedException(
  409. 'Cannot jit function %s at %d because the JIT has been disabled.' % (
  410. '' if suggested_name is None else "'" + suggested_name + "'",
  411. body_id))
  412. def jit_recompile(self, task_root, body_id, function_name, compile_function_body=None):
  413. """Replaces the function with the given name by compiling the bytecode at the given
  414. body id."""
  415. if compile_function_body is None:
  416. compile_function_body = self.compile_function_body
  417. self.check_jittable(body_id, function_name)
  418. # Generate a name for the function we're about to analyze, and pretend that
  419. # it already exists. (we need to do this for recursive functions)
  420. self.jitted_entry_points[body_id] = function_name
  421. self.jit_globals[function_name] = None
  422. (_, _, is_mutable), = yield [
  423. ("CALL_ARGS", [self.jit_signature, (body_id,)])]
  424. dependencies = set([body_id])
  425. self.compilation_dependencies[body_id] = dependencies
  426. def handle_jit_exception(exception):
  427. # If analysis fails, then a JitCompilationFailedException will be thrown.
  428. del self.compilation_dependencies[body_id]
  429. for dep in dependencies:
  430. self.mark_no_jit(dep)
  431. if dep in self.jitted_entry_points:
  432. del self.jitted_entry_points[dep]
  433. failure_message = "%s (function '%s' at %d)" % (
  434. exception.message, function_name, body_id)
  435. if self.jit_success_log_function is not None:
  436. self.jit_success_log_function('JIT compilation failed: %s' % failure_message)
  437. raise JitCompilationFailedException(failure_message)
  438. # Try to analyze the function's body.
  439. yield [("TRY", [])]
  440. yield [("CATCH", [JitCompilationFailedException, handle_jit_exception])]
  441. if is_mutable:
  442. # We can't just JIT mutable functions. That'd be dangerous.
  443. raise JitCompilationFailedException(
  444. "Function was marked '%s'." % jit_runtime.MUTABLE_FUNCTION_KEY)
  445. constructed_function, = yield [
  446. ("CALL_ARGS", [compile_function_body, (self, function_name, body_id, task_root)])]
  447. yield [("END_TRY", [])]
  448. del self.compilation_dependencies[body_id]
  449. # Convert the function definition to Python code, and compile it.
  450. compiled_function = self.jit_define_function(function_name, constructed_function)
  451. if self.jit_success_log_function is not None:
  452. self.jit_success_log_function(
  453. "JIT compilation successful: (function '%s' at %d)" % (function_name, body_id))
  454. raise primitive_functions.PrimitiveFinished(compiled_function)
  455. def get_source_map_name(self, function_name):
  456. """Gets the name of the given jitted function's source map. None is returned if source maps
  457. are disabled."""
  458. if self.source_maps_enabled:
  459. return function_name + "_source_map"
  460. else:
  461. return None
  462. def get_can_rejit_name(self, function_name):
  463. """Gets the name of the given jitted function's can-rejit flag."""
  464. return function_name + "_can_rejit"
  465. def jit_define_function(self, function_name, function_def):
  466. """Converts the given tree-IR function definition to Python code, defines it,
  467. and extracts the resulting function."""
  468. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  469. # pylint: disable=I0011,W0122
  470. if self.jit_code_log_function is not None:
  471. self.jit_code_log_function(function_def)
  472. # Convert the function definition to Python code, and compile it.
  473. code_generator = tree_ir.PythonGenerator()
  474. function_def.generate_python_def(code_generator)
  475. source_map_name = self.get_source_map_name(function_name)
  476. if source_map_name is not None:
  477. self.jit_globals[source_map_name] = code_generator.source_map_builder.source_map
  478. exec(str(code_generator), self.jit_globals)
  479. # Extract the compiled function from the JIT global state.
  480. return self.jit_globals[function_name]
  481. def jit_delete_function(self, function_name):
  482. """Deletes the function with the given function name."""
  483. del self.jit_globals[function_name]
  484. def jit_compile(self, task_root, body_id, suggested_name=None):
  485. """Tries to jit the function defined by the given entry point id and parameter list."""
  486. if body_id is None:
  487. raise ValueError('body_id cannot be None')
  488. elif body_id in self.jitted_entry_points:
  489. # We have already compiled this function.
  490. raise primitive_functions.PrimitiveFinished(
  491. self.jit_globals[self.jitted_entry_points[body_id]])
  492. # Generate a name for the function we're about to analyze, and 're-compile'
  493. # it for the first time.
  494. function_name = self.generate_function_name(body_id, suggested_name)
  495. yield [("TAIL_CALL_ARGS", [self.jit_recompile, (task_root, body_id, function_name)])]
  496. def jit_rejit(self, task_root, body_id, function_name, compile_function_body=None):
  497. """Re-compiles the given function. If compilation fails, then the can-rejit
  498. flag is set to false."""
  499. old_jitted_func = self.jitted_entry_points[body_id]
  500. def __handle_jit_failed(_):
  501. self.jit_globals[self.get_can_rejit_name(function_name)] = False
  502. self.jitted_entry_points[body_id] = old_jitted_func
  503. self.no_jit_entry_points.remove(body_id)
  504. raise primitive_functions.PrimitiveFinished(None)
  505. yield [("TRY", [])]
  506. yield [("CATCH", [jit_runtime.JitCompilationFailedException, __handle_jit_failed])]
  507. yield [
  508. ("CALL_ARGS",
  509. [self.jit_recompile, (task_root, body_id, function_name, compile_function_body)])]
  510. yield [("END_TRY", [])]
  511. def jit_thunk(self, get_function_body, global_name=None):
  512. """Creates a thunk from the given IR tree that computes the function's body id.
  513. This thunk is a function that will invoke the function whose body id is retrieved.
  514. The thunk's name in the JIT's global context is returned."""
  515. # The general idea is to first create a function that looks a bit like this:
  516. #
  517. # def jit_get_function_body(**kwargs):
  518. # raise primitive_functions.PrimitiveFinished(<get_function_body>)
  519. #
  520. get_function_body_name = self.generate_name('get_function_body')
  521. get_function_body_func_def = create_function(
  522. get_function_body_name, [], {}, {}, tree_ir.ReturnInstruction(get_function_body))
  523. get_function_body_func = self.jit_define_function(
  524. get_function_body_name, get_function_body_func_def)
  525. # Next, we want to create a thunk that invokes said function, and then replaces itself.
  526. thunk_name = self.generate_name('thunk', global_name)
  527. def __jit_thunk(**kwargs):
  528. # Compute the body id, and delete the function that computes the body id; we won't
  529. # be needing it anymore after this call.
  530. body_id, = yield [("CALL_KWARGS", [get_function_body_func, kwargs])]
  531. self.jit_delete_function(get_function_body_name)
  532. # Try to associate the global name with the body id, if that's at all possible.
  533. if global_name is not None:
  534. self.register_global(body_id, global_name)
  535. compiled_function = self.lookup_compiled_body(body_id)
  536. if compiled_function is not None:
  537. # Replace this thunk by the compiled function.
  538. self.jit_globals[thunk_name] = compiled_function
  539. else:
  540. def __handle_jit_exception(_):
  541. # Replace this thunk by a different thunk: one that calls the interpreter
  542. # directly, without checking if the function is jittable.
  543. (_, parameter_names, _), = yield [
  544. ("CALL_ARGS", [self.jit_signature, (body_id,)])]
  545. def __interpreter_thunk(**new_kwargs):
  546. named_arg_dict = {name : new_kwargs[name] for name in parameter_names}
  547. return jit_runtime.interpret_function_body(
  548. body_id, named_arg_dict, **new_kwargs)
  549. self.jit_globals[thunk_name] = __interpreter_thunk
  550. yield [("TRY", [])]
  551. yield [("CATCH", [JitCompilationFailedException, __handle_jit_exception])]
  552. compiled_function, = yield [
  553. ("CALL_ARGS",
  554. [self.jit_recompile, (kwargs['task_root'], body_id, thunk_name)])]
  555. yield [("END_TRY", [])]
  556. # Call the compiled function.
  557. yield [("TAIL_CALL_KWARGS", [compiled_function, kwargs])]
  558. self.jit_globals[thunk_name] = __jit_thunk
  559. return thunk_name
  560. def jit_thunk_constant_body(self, body_id):
  561. """Creates a thunk from the given body id.
  562. This thunk is a function that will invoke the function whose body id is given.
  563. The thunk's name in the JIT's global context is returned."""
  564. self.lookup_compiled_body(body_id)
  565. compiled_name = self.get_compiled_name(body_id)
  566. if compiled_name is not None:
  567. # We might have compiled the function with the given body id already. In that case,
  568. # we need not bother with constructing the thunk; we can return the compiled function
  569. # right away.
  570. return compiled_name
  571. else:
  572. # Looks like we'll just have to build that thunk after all.
  573. return self.jit_thunk(tree_ir.LiteralInstruction(body_id))
  574. def jit_thunk_constant_function(self, body_id):
  575. """Creates a thunk from the given function id.
  576. This thunk is a function that will invoke the function whose function id is given.
  577. The thunk's name in the JIT's global context is returned."""
  578. return self.jit_thunk(
  579. tree_ir.ReadDictionaryValueInstruction(
  580. tree_ir.LiteralInstruction(body_id),
  581. tree_ir.LiteralInstruction(jit_runtime.FUNCTION_BODY_KEY)))
  582. def jit_thunk_global(self, global_name):
  583. """Creates a thunk from given global name.
  584. This thunk is a function that will invoke the function whose body id is given.
  585. The thunk's name in the JIT's global context is returned."""
  586. # We might have compiled the function with the given name already. In that case,
  587. # we need not bother with constructing the thunk; we can return the compiled function
  588. # right away.
  589. body_id = self.get_global_body_id(global_name)
  590. if body_id is not None:
  591. self.lookup_compiled_body(body_id)
  592. compiled_name = self.get_compiled_name(body_id)
  593. if compiled_name is not None:
  594. return compiled_name
  595. # Looks like we'll just have to build that thunk after all.
  596. # We want to look up the global function like so
  597. #
  598. # _globals, = yield [("RD", [kwargs['task_root'], "globals"])]
  599. # global_var, = yield [("RD", [_globals, global_name])]
  600. # function_id, = yield [("RD", [global_var, "value"])]
  601. # body_id, = yield [("RD", [function_id, jit_runtime.FUNCTION_BODY_KEY])]
  602. #
  603. return self.jit_thunk(
  604. tree_ir.ReadDictionaryValueInstruction(
  605. tree_ir.ReadDictionaryValueInstruction(
  606. tree_ir.ReadDictionaryValueInstruction(
  607. tree_ir.ReadDictionaryValueInstruction(
  608. tree_ir.LoadIndexInstruction(
  609. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  610. tree_ir.LiteralInstruction('task_root')),
  611. tree_ir.LiteralInstruction('globals')),
  612. tree_ir.LiteralInstruction(global_name)),
  613. tree_ir.LiteralInstruction('value')),
  614. tree_ir.LiteralInstruction(jit_runtime.FUNCTION_BODY_KEY)),
  615. global_name)
  616. def compile_function_body_baseline(jit, function_name, body_id, task_root, header=None):
  617. """Have the baseline JIT compile the function with the given name and body id."""
  618. (parameter_ids, parameter_list, _), = yield [
  619. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  620. param_dict = dict(zip(parameter_ids, parameter_list))
  621. body_param_dict = dict(zip(parameter_ids, [p + "_ptr" for p in parameter_list]))
  622. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  623. state = bytecode_to_tree.AnalysisState(
  624. jit, body_id, task_root, body_param_dict,
  625. jit.max_instructions)
  626. constructed_body, = yield [("CALL_ARGS", [state.analyze, (body_bytecode,)])]
  627. if header is not None:
  628. constructed_body = tree_ir.create_block(header, constructed_body)
  629. # Optimize the function's body.
  630. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  631. # Wrap the tree IR in a function definition.
  632. raise primitive_functions.PrimitiveFinished(
  633. create_function(
  634. function_name, parameter_list, param_dict,
  635. body_param_dict, constructed_body, jit.get_source_map_name(function_name)))
  636. def compile_function_body_fast(jit, function_name, body_id, _):
  637. """Have the fast JIT compile the function with the given name and body id."""
  638. (parameter_ids, parameter_list, _), = yield [
  639. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  640. param_dict = dict(zip(parameter_ids, parameter_list))
  641. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  642. bytecode_analyzer = bytecode_to_cfg.AnalysisState(jit, function_name, param_dict)
  643. bytecode_analyzer.analyze(body_bytecode)
  644. entry_point, = yield [
  645. ("CALL_ARGS", [cfg_optimization.optimize, (bytecode_analyzer.entry_point, jit)])]
  646. if jit.jit_code_log_function is not None:
  647. jit.jit_code_log_function(
  648. "CFG for function '%s' at '%d':\n%s" % (
  649. function_name, body_id,
  650. '\n'.join(map(str, cfg_ir.get_all_reachable_blocks(entry_point)))))
  651. # Lower the CFG to tree IR.
  652. constructed_body = cfg_to_tree.lower_flow_graph(entry_point, jit)
  653. # Optimize the tree that was generated.
  654. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  655. raise primitive_functions.PrimitiveFinished(
  656. create_bare_function(
  657. function_name, parameter_list,
  658. constructed_body))
  659. def favor_large_functions(body_bytecode):
  660. """Computes the initial temperature of a function based on the size of
  661. its body bytecode. Larger functions are favored and the temperature
  662. is incremented by one on every call."""
  663. return (
  664. len(body_bytecode.get_reachable()),
  665. lambda old_value:
  666. tree_ir.BinaryInstruction(
  667. old_value,
  668. '+',
  669. tree_ir.LiteralInstruction(1)))
  670. ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD = 200
  671. """The threshold temperature at which fast-jit will be used."""
  672. def compile_function_body_adaptive(
  673. jit, function_name, body_id, task_root,
  674. temperature_heuristic=favor_large_functions):
  675. """Compile the function with the given name and body id. An execution engine is picked
  676. automatically, and the function may be compiled again at a later time."""
  677. # The general idea behind this compilation technique is to first use the baseline JIT
  678. # to compile a function, and then switch to the fast JIT when we determine that doing
  679. # so would be a good idea. We maintain a 'temperature' counter, which has an initial value
  680. # and gets incremented every time the function is executed.
  681. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  682. initial_temperature, increment_temperature = temperature_heuristic(body_bytecode)
  683. if initial_temperature >= ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD:
  684. # Initial temperature exceeds the fast-jit threshold.
  685. # Compile this thing with fast-jit right away.
  686. yield [
  687. ("TAIL_CALL_ARGS",
  688. [compile_function_body_fast, (jit, function_name, body_id, task_root)])]
  689. (_, parameter_list, _), = yield [
  690. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  691. temperature_counter_name = jit.import_value(
  692. initial_temperature, function_name + "_temperature_counter")
  693. can_rejit_name = jit.get_can_rejit_name(function_name)
  694. jit.jit_globals[can_rejit_name] = True
  695. # This tree represents the following logic:
  696. #
  697. # if can_rejit:
  698. # global temperature_counter
  699. # temperature_counter = increment_temperature(temperature_counter)
  700. # if temperature_counter >= ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD:
  701. # yield [("CALL_KWARGS", [jit_runtime.JIT_REJIT_FUNCTION_NAME, {...}])]
  702. # yield [("TAIL_CALL_KWARGS", [function_name, {...}])]
  703. header = tree_ir.SelectInstruction(
  704. tree_ir.LoadGlobalInstruction(can_rejit_name),
  705. tree_ir.create_block(
  706. tree_ir.DeclareGlobalInstruction(temperature_counter_name),
  707. tree_ir.IgnoreInstruction(
  708. tree_ir.StoreGlobalInstruction(
  709. temperature_counter_name,
  710. increment_temperature(
  711. tree_ir.LoadGlobalInstruction(temperature_counter_name)))),
  712. tree_ir.SelectInstruction(
  713. tree_ir.BinaryInstruction(
  714. tree_ir.LoadGlobalInstruction(temperature_counter_name),
  715. '>=',
  716. tree_ir.LiteralInstruction(ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD)),
  717. tree_ir.create_block(
  718. tree_ir.RunGeneratorFunctionInstruction(
  719. tree_ir.LoadGlobalInstruction(jit_runtime.JIT_REJIT_FUNCTION_NAME),
  720. tree_ir.DictionaryLiteralInstruction([
  721. (tree_ir.LiteralInstruction('task_root'),
  722. bytecode_to_tree.load_task_root()),
  723. (tree_ir.LiteralInstruction('body_id'),
  724. tree_ir.LiteralInstruction(body_id)),
  725. (tree_ir.LiteralInstruction('function_name'),
  726. tree_ir.LiteralInstruction(function_name)),
  727. (tree_ir.LiteralInstruction('compile_function_body'),
  728. tree_ir.LoadGlobalInstruction(
  729. jit_runtime.JIT_COMPILE_FUNCTION_BODY_FAST_FUNCTION_NAME))]),
  730. result_type=tree_ir.NO_RESULT_TYPE),
  731. tree_ir.create_jit_call(
  732. tree_ir.LoadGlobalInstruction(function_name),
  733. [(name, tree_ir.LoadLocalInstruction(name)) for name in parameter_list],
  734. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  735. tree_ir.RunTailGeneratorFunctionInstruction)),
  736. tree_ir.EmptyInstruction())),
  737. tree_ir.EmptyInstruction())
  738. # Compile with the baseline JIT, and insert the header.
  739. yield [
  740. ("TAIL_CALL_ARGS",
  741. [compile_function_body_baseline,
  742. (jit, function_name, body_id, task_root, header)])]