jit.py 44 KB

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