jit.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import modelverse_kernel.primitives as primitive_functions
  2. import modelverse_jit.tree_ir as tree_ir
  3. import modelverse_jit.runtime as jit_runtime
  4. import keyword
  5. # Import JitCompilationFailedException because it used to be defined
  6. # in this module.
  7. JitCompilationFailedException = jit_runtime.JitCompilationFailedException
  8. KWARGS_PARAMETER_NAME = "kwargs"
  9. """The name of the kwargs parameter in jitted functions."""
  10. CALL_FUNCTION_NAME = "__call_function"
  11. """The name of the '__call_function' function, in the jitted function scope."""
  12. GET_INPUT_FUNCTION_NAME = "__get_input"
  13. """The name of the '__get_input' function, in the jitted function scope."""
  14. LOCALS_NODE_NAME = "jit_locals"
  15. """The name of the node that is connected to all JIT locals in a given function call."""
  16. LOCALS_EDGE_NAME = "jit_locals_edge"
  17. """The name of the edge that connects the LOCALS_NODE_NAME node to a user root."""
  18. def get_parameter_names(compiled_function):
  19. """Gets the given compiled function's parameter names."""
  20. if hasattr(compiled_function, '__code__'):
  21. return compiled_function.__code__.co_varnames[
  22. :compiled_function.__code__.co_argcount]
  23. elif hasattr(compiled_function, '__init__'):
  24. return get_parameter_names(compiled_function.__init__)[1:]
  25. else:
  26. raise ValueError("'compiled_function' must be a function or a type.")
  27. def apply_intrinsic(intrinsic_function, named_args):
  28. """Applies the given intrinsic to the given sequence of named arguments."""
  29. param_names = get_parameter_names(intrinsic_function)
  30. if tuple(param_names) == tuple([n for n, _ in named_args]):
  31. # Perfect match. Yay!
  32. return intrinsic_function(**dict(named_args))
  33. else:
  34. # We'll have to store the arguments into locals to preserve
  35. # the order of evaluation.
  36. stored_args = [(name, tree_ir.StoreLocalInstruction(None, arg)) for name, arg in named_args]
  37. arg_value_dict = dict([(name, arg.create_load()) for name, arg in stored_args])
  38. store_instructions = [instruction for _, instruction in stored_args]
  39. return tree_ir.CompoundInstruction(
  40. tree_ir.create_block(*store_instructions),
  41. intrinsic_function(**arg_value_dict))
  42. def map_and_simplify_generator(function, instruction):
  43. """Applies the given mapping function to every instruction in the tree
  44. that has the given instruction as root, and simplifies it on-the-fly.
  45. This is at least as powerful as first mapping and then simplifying, as
  46. maps and simplifications are interspersed.
  47. This function assumes that function creates a generator that returns by
  48. raising a primitive_functions.PrimitiveFinished."""
  49. # First handle the children by mapping on them and then simplifying them.
  50. new_children = []
  51. for inst in instruction.get_children():
  52. new_inst, = yield [("CALL_ARGS", [map_and_simplify_generator, (function, inst)])]
  53. new_children.append(new_inst)
  54. # Then apply the function to the top-level node.
  55. transformed, = yield [("CALL_ARGS", [function, (instruction.create(new_children),)])]
  56. # Finally, simplify the transformed top-level node.
  57. raise primitive_functions.PrimitiveFinished(transformed.simplify_node())
  58. def expand_constant_read(instruction):
  59. """Tries to replace a read of a constant node by a literal."""
  60. if isinstance(instruction, tree_ir.ReadValueInstruction) and \
  61. isinstance(instruction.node_id, tree_ir.LiteralInstruction):
  62. val, = yield [("RV", [instruction.node_id.literal])]
  63. raise primitive_functions.PrimitiveFinished(tree_ir.LiteralInstruction(val))
  64. else:
  65. raise primitive_functions.PrimitiveFinished(instruction)
  66. def optimize_tree_ir(instruction):
  67. """Optimizes an IR tree."""
  68. return map_and_simplify_generator(expand_constant_read, instruction)
  69. class ModelverseJit(object):
  70. """A high-level interface to the modelverse JIT compiler."""
  71. def __init__(self, max_instructions=None, compiled_function_lookup=None):
  72. self.todo_entry_points = set()
  73. self.no_jit_entry_points = set()
  74. self.jitted_entry_points = {}
  75. self.jitted_parameters = {}
  76. self.jit_globals = {
  77. 'PrimitiveFinished' : primitive_functions.PrimitiveFinished,
  78. CALL_FUNCTION_NAME : jit_runtime.call_function,
  79. GET_INPUT_FUNCTION_NAME : jit_runtime.get_input
  80. }
  81. self.jit_count = 0
  82. self.max_instructions = max_instructions
  83. self.compiled_function_lookup = compiled_function_lookup
  84. # jit_intrinsics is a function name -> intrinsic map.
  85. self.jit_intrinsics = {}
  86. self.compilation_dependencies = {}
  87. self.jit_enabled = True
  88. self.direct_calls_allowed = True
  89. self.tracing_enabled = False
  90. self.input_function_enabled = False
  91. self.nop_insertion_enabled = True
  92. def set_jit_enabled(self, is_enabled=True):
  93. """Enables or disables the JIT."""
  94. self.jit_enabled = is_enabled
  95. def allow_direct_calls(self, is_allowed=True):
  96. """Allows or disallows direct calls from jitted to jitted code."""
  97. self.direct_calls_allowed = is_allowed
  98. def use_input_function(self, is_enabled=True):
  99. """Configures the JIT to compile 'input' instructions as function calls."""
  100. self.input_function_enabled = is_enabled
  101. def enable_tracing(self, is_enabled=True):
  102. """Enables or disables tracing for jitted code."""
  103. self.tracing_enabled = is_enabled
  104. def enable_nop_insertion(self, is_enabled=True):
  105. """Enables or disables nop insertion for jitted code. The JIT will insert nops at loop
  106. back-edges. Inserting nops sacrifices performance to keep the jitted code from
  107. blocking the thread of execution by consuming all resources; nops give the
  108. Modelverse server an opportunity to interrupt the currently running code."""
  109. self.nop_insertion_enabled = is_enabled
  110. def mark_entry_point(self, body_id):
  111. """Marks the node with the given identifier as a function entry point."""
  112. if body_id not in self.no_jit_entry_points and body_id not in self.jitted_entry_points:
  113. self.todo_entry_points.add(body_id)
  114. def is_entry_point(self, body_id):
  115. """Tells if the node with the given identifier is a function entry point."""
  116. return body_id in self.todo_entry_points or \
  117. body_id in self.no_jit_entry_points or \
  118. body_id in self.jitted_entry_points
  119. def is_jittable_entry_point(self, body_id):
  120. """Tells if the node with the given identifier is a function entry point that
  121. has not been marked as non-jittable. This only returns `True` if the JIT
  122. is enabled and the function entry point has been marked jittable, or if
  123. the function has already been compiled."""
  124. return ((self.jit_enabled and body_id in self.todo_entry_points) or
  125. self.has_compiled(body_id))
  126. def has_compiled(self, body_id):
  127. """Tests if the function belonging to the given body node has been compiled yet."""
  128. return body_id in self.jitted_entry_points
  129. def get_compiled_name(self, body_id):
  130. """Gets the name of the compiled version of the given body node in the JIT
  131. global state."""
  132. return self.jitted_entry_points[body_id]
  133. def mark_no_jit(self, body_id):
  134. """Informs the JIT that the node with the given identifier is a function entry
  135. point that must never be jitted."""
  136. self.no_jit_entry_points.add(body_id)
  137. if body_id in self.todo_entry_points:
  138. self.todo_entry_points.remove(body_id)
  139. def generate_name(self, infix, suggested_name=None):
  140. """Generates a new name or picks the suggested name if it is still
  141. available."""
  142. if suggested_name is not None \
  143. and suggested_name not in self.jit_globals \
  144. and not keyword.iskeyword(suggested_name):
  145. self.jit_count += 1
  146. return suggested_name
  147. else:
  148. function_name = 'jit_%s%d' % (infix, self.jit_count)
  149. self.jit_count += 1
  150. return function_name
  151. def generate_function_name(self, suggested_name=None):
  152. """Generates a new function name or picks the suggested name if it is still
  153. available."""
  154. return self.generate_name('func', suggested_name)
  155. def register_compiled(self, body_id, compiled_function, function_name=None):
  156. """Registers a compiled entry point with the JIT."""
  157. # Get the function's name.
  158. function_name = self.generate_function_name(function_name)
  159. # Map the body id to the given parameter list.
  160. self.jitted_entry_points[body_id] = function_name
  161. self.jit_globals[function_name] = compiled_function
  162. if body_id in self.todo_entry_points:
  163. self.todo_entry_points.remove(body_id)
  164. def import_value(self, value, suggested_name=None):
  165. """Imports the given value into the JIT's global scope, with the given suggested name.
  166. The actual name of the value (within the JIT's global scope) is returned."""
  167. actual_name = self.generate_name('import', suggested_name)
  168. self.jit_globals[actual_name] = value
  169. return actual_name
  170. def lookup_compiled_function(self, name):
  171. """Looks up a compiled function by name. Returns a matching function,
  172. or None if no function was found."""
  173. if name is None:
  174. return None
  175. elif name in self.jit_globals:
  176. return self.jit_globals[name]
  177. elif self.compiled_function_lookup is not None:
  178. return self.compiled_function_lookup(name)
  179. else:
  180. return None
  181. def get_intrinsic(self, name):
  182. """Tries to find an intrinsic version of the function with the
  183. given name."""
  184. if name in self.jit_intrinsics:
  185. return self.jit_intrinsics[name]
  186. else:
  187. return None
  188. def register_intrinsic(self, name, intrinsic_function):
  189. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  190. the function with the given entry point by an application of the specified function."""
  191. self.jit_intrinsics[name] = intrinsic_function
  192. def register_binary_intrinsic(self, name, operator):
  193. """Registers an intrinsic with the JIT that represents the given binary operation."""
  194. self.register_intrinsic(name, lambda a, b: tree_ir.CreateNodeWithValueInstruction(
  195. tree_ir.BinaryInstruction(
  196. tree_ir.ReadValueInstruction(a),
  197. operator,
  198. tree_ir.ReadValueInstruction(b))))
  199. def register_unary_intrinsic(self, name, operator):
  200. """Registers an intrinsic with the JIT that represents the given unary operation."""
  201. self.register_intrinsic(name, lambda a: tree_ir.CreateNodeWithValueInstruction(
  202. tree_ir.UnaryInstruction(
  203. operator,
  204. tree_ir.ReadValueInstruction(a))))
  205. def register_cast_intrinsic(self, name, target_type):
  206. """Registers an intrinsic with the JIT that represents a unary conversion operator."""
  207. self.register_intrinsic(name, lambda a: tree_ir.CreateNodeWithValueInstruction(
  208. tree_ir.CallInstruction(
  209. tree_ir.LoadGlobalInstruction(target_type.__name__),
  210. [tree_ir.ReadValueInstruction(a)])))
  211. def jit_parameters(self, body_id):
  212. """Acquires the parameter list for the given body id node."""
  213. if body_id not in self.jitted_parameters:
  214. signature_id, = yield [("RRD", [body_id, "body"])]
  215. signature_id = signature_id[0]
  216. param_set_id, = yield [("RD", [signature_id, "params"])]
  217. if param_set_id is None:
  218. self.jitted_parameters[body_id] = ([], [])
  219. else:
  220. param_name_ids, = yield [("RDK", [param_set_id])]
  221. param_names = yield [("RV", [n]) for n in param_name_ids]
  222. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  223. self.jitted_parameters[body_id] = (param_vars, param_names)
  224. raise primitive_functions.PrimitiveFinished(self.jitted_parameters[body_id])
  225. def jit_compile(self, user_root, body_id, suggested_name=None):
  226. """Tries to jit the function defined by the given entry point id and parameter list."""
  227. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  228. # pylint: disable=I0011,W0122
  229. if body_id is None:
  230. raise ValueError('body_id cannot be None')
  231. elif body_id in self.jitted_entry_points:
  232. # We have already compiled this function.
  233. raise primitive_functions.PrimitiveFinished(
  234. self.jit_globals[self.jitted_entry_points[body_id]])
  235. elif body_id in self.no_jit_entry_points:
  236. # We're not allowed to jit this function or have tried and failed before.
  237. raise JitCompilationFailedException(
  238. 'Cannot jit function %s at %d because it is marked non-jittable.' % (
  239. '' if suggested_name is None else "'" + suggested_name + "'",
  240. body_id))
  241. elif not self.jit_enabled:
  242. # We're not allowed to jit anything.
  243. raise JitCompilationFailedException(
  244. 'Cannot jit function %s at %d because the JIT has been disabled.' % (
  245. '' if suggested_name is None else "'" + suggested_name + "'",
  246. body_id))
  247. # Generate a name for the function we're about to analyze, and pretend that
  248. # it already exists. (we need to do this for recursive functions)
  249. function_name = self.generate_function_name(suggested_name)
  250. self.jitted_entry_points[body_id] = function_name
  251. self.jit_globals[function_name] = None
  252. (parameter_ids, parameter_list), = yield [("CALL_ARGS", [self.jit_parameters, (body_id,)])]
  253. param_dict = dict(zip(parameter_ids, parameter_list))
  254. body_param_dict = dict(zip(parameter_ids, [p + "_ptr" for p in parameter_list]))
  255. dependencies = set([body_id])
  256. self.compilation_dependencies[body_id] = dependencies
  257. def handle_jit_exception(exception):
  258. # If analysis fails, then a JitCompilationFailedException will be thrown.
  259. del self.compilation_dependencies[body_id]
  260. for dep in dependencies:
  261. self.mark_no_jit(dep)
  262. if dep in self.jitted_entry_points:
  263. del self.jitted_entry_points[dep]
  264. raise JitCompilationFailedException(
  265. "%s (function '%s' at %d)" % (exception.message, function_name, body_id))
  266. # Try to analyze the function's body.
  267. yield [("TRY", [])]
  268. yield [("CATCH", [JitCompilationFailedException, handle_jit_exception])]
  269. state = AnalysisState(
  270. self, body_id, user_root, body_param_dict,
  271. self.max_instructions)
  272. constructed_body, = yield [("CALL_ARGS", [state.analyze, (body_id,)])]
  273. yield [("END_TRY", [])]
  274. del self.compilation_dependencies[body_id]
  275. # Write a prologue and prepend it to the generated function body.
  276. prologue_statements = []
  277. # Create a LOCALS_NODE_NAME node, and connect it to the user root.
  278. prologue_statements.append(
  279. tree_ir.create_new_local_node(
  280. LOCALS_NODE_NAME,
  281. tree_ir.LoadIndexInstruction(
  282. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME),
  283. tree_ir.LiteralInstruction('user_root')),
  284. LOCALS_EDGE_NAME))
  285. for (key, val) in param_dict.items():
  286. arg_ptr = tree_ir.create_new_local_node(
  287. body_param_dict[key],
  288. tree_ir.LoadLocalInstruction(LOCALS_NODE_NAME))
  289. prologue_statements.append(arg_ptr)
  290. prologue_statements.append(
  291. tree_ir.CreateDictionaryEdgeInstruction(
  292. tree_ir.LoadLocalInstruction(body_param_dict[key]),
  293. tree_ir.LiteralInstruction('value'),
  294. tree_ir.LoadLocalInstruction(val)))
  295. constructed_body = tree_ir.create_block(
  296. *(prologue_statements + [constructed_body]))
  297. # Optimize the function's body.
  298. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  299. # Wrap the IR in a function definition, give it a unique name.
  300. constructed_function = tree_ir.DefineFunctionInstruction(
  301. function_name,
  302. parameter_list + ['**' + KWARGS_PARAMETER_NAME],
  303. constructed_body)
  304. # Convert the function definition to Python code, and compile it.
  305. exec(str(constructed_function), self.jit_globals)
  306. # Extract the compiled function from the JIT global state.
  307. compiled_function = self.jit_globals[function_name]
  308. # print(constructed_function)
  309. raise primitive_functions.PrimitiveFinished(compiled_function)
  310. class AnalysisState(object):
  311. """The state of a bytecode analysis call graph."""
  312. def __init__(self, jit, body_id, user_root, local_mapping, max_instructions=None):
  313. self.analyzed_instructions = set()
  314. self.function_vars = set()
  315. self.local_vars = set()
  316. self.body_id = body_id
  317. self.max_instructions = max_instructions
  318. self.user_root = user_root
  319. self.jit = jit
  320. self.local_mapping = local_mapping
  321. self.function_name = jit.jitted_entry_points[body_id]
  322. def get_local_name(self, local_id):
  323. """Gets the name for a local with the given id."""
  324. if local_id not in self.local_mapping:
  325. self.local_mapping[local_id] = 'local%d' % local_id
  326. return self.local_mapping[local_id]
  327. def register_local_var(self, local_id):
  328. """Registers the given variable node id as a local."""
  329. if local_id in self.function_vars:
  330. raise JitCompilationFailedException(
  331. "Local is used as target of function call.")
  332. self.local_vars.add(local_id)
  333. def register_function_var(self, local_id):
  334. """Registers the given variable node id as a function."""
  335. if local_id in self.local_vars:
  336. raise JitCompilationFailedException(
  337. "Local is used as target of function call.")
  338. self.function_vars.add(local_id)
  339. def retrieve_user_root(self):
  340. """Creates an instruction that stores the user_root variable
  341. in a local."""
  342. return tree_ir.StoreLocalInstruction(
  343. 'user_root',
  344. tree_ir.LoadIndexInstruction(
  345. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME),
  346. tree_ir.LiteralInstruction('user_root')))
  347. def load_kernel(self):
  348. """Creates an instruction that loads the Modelverse kernel."""
  349. return tree_ir.LoadIndexInstruction(
  350. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME),
  351. tree_ir.LiteralInstruction('mvk'))
  352. def analyze(self, instruction_id):
  353. """Tries to build an intermediate representation from the instruction with the
  354. given id."""
  355. # Check the analyzed_instructions set for instruction_id to avoid
  356. # infinite loops.
  357. if instruction_id in self.analyzed_instructions:
  358. raise JitCompilationFailedException('Cannot jit non-tree instruction graph.')
  359. elif (self.max_instructions is not None and
  360. len(self.analyzed_instructions) > self.max_instructions):
  361. raise JitCompilationFailedException('Maximum number of instructions exceeded.')
  362. self.analyzed_instructions.add(instruction_id)
  363. instruction_val, = yield [("RV", [instruction_id])]
  364. instruction_val = instruction_val["value"]
  365. if instruction_val in self.instruction_analyzers:
  366. # If tracing is enabled, then this would be an appropriate time to
  367. # retrieve the debug information.
  368. if self.jit.tracing_enabled:
  369. debug_info, = yield [("RD", [instruction_id, "__debug"])]
  370. if debug_info is not None:
  371. debug_info, = yield [("RV", [debug_info])]
  372. # Analyze the instruction itself.
  373. outer_result, = yield [
  374. ("CALL_ARGS", [self.instruction_analyzers[instruction_val], (self, instruction_id)])]
  375. if self.jit.tracing_enabled:
  376. outer_result = tree_ir.with_debug_info_trace(outer_result, debug_info, self.function_name)
  377. # Check if the instruction has a 'next' instruction.
  378. next_instr, = yield [("RD", [instruction_id, "next"])]
  379. if next_instr is None:
  380. raise primitive_functions.PrimitiveFinished(outer_result)
  381. else:
  382. next_result, = yield [("CALL_ARGS", [self.analyze, (next_instr,)])]
  383. raise primitive_functions.PrimitiveFinished(
  384. tree_ir.CompoundInstruction(
  385. outer_result,
  386. next_result))
  387. else:
  388. raise JitCompilationFailedException(
  389. "Unknown instruction type: '%s'" % (instruction_val))
  390. def analyze_all(self, instruction_ids):
  391. """Tries to compile a list of IR trees from the given list of instruction ids."""
  392. results = []
  393. for inst in instruction_ids:
  394. analyzed_inst, = yield [("CALL_ARGS", [self.analyze, (inst,)])]
  395. results.append(analyzed_inst)
  396. raise primitive_functions.PrimitiveFinished(results)
  397. def analyze_return(self, instruction_id):
  398. """Tries to analyze the given 'return' instruction."""
  399. retval_id, = yield [("RD", [instruction_id, 'value'])]
  400. def create_return(return_value):
  401. return tree_ir.ReturnInstruction(
  402. tree_ir.CompoundInstruction(
  403. return_value,
  404. tree_ir.DeleteEdgeInstruction(
  405. tree_ir.LoadLocalInstruction(LOCALS_EDGE_NAME))))
  406. if retval_id is None:
  407. raise primitive_functions.PrimitiveFinished(
  408. create_return(
  409. tree_ir.EmptyInstruction()))
  410. else:
  411. retval, = yield [("CALL_ARGS", [self.analyze, (retval_id,)])]
  412. raise primitive_functions.PrimitiveFinished(
  413. create_return(retval))
  414. def analyze_if(self, instruction_id):
  415. """Tries to analyze the given 'if' instruction."""
  416. cond, true, false = yield [
  417. ("RD", [instruction_id, "cond"]),
  418. ("RD", [instruction_id, "then"]),
  419. ("RD", [instruction_id, "else"])]
  420. analysis_results, = yield [("CALL_ARGS", [self.analyze_all, (
  421. [cond, true]
  422. if false is None
  423. else [cond, true, false],)])]
  424. if false is None:
  425. cond_r, true_r = analysis_results
  426. false_r = tree_ir.EmptyInstruction()
  427. else:
  428. cond_r, true_r, false_r = analysis_results
  429. raise primitive_functions.PrimitiveFinished(
  430. tree_ir.SelectInstruction(
  431. tree_ir.ReadValueInstruction(cond_r),
  432. true_r,
  433. false_r))
  434. def analyze_while(self, instruction_id):
  435. """Tries to analyze the given 'while' instruction."""
  436. cond, body = yield [
  437. ("RD", [instruction_id, "cond"]),
  438. ("RD", [instruction_id, "body"])]
  439. (cond_r, body_r), = yield [("CALL_ARGS", [self.analyze_all, ([cond, body],)])]
  440. if self.jit.nop_insertion_enabled:
  441. create_loop_body = lambda check, body: tree_ir.create_block(
  442. check,
  443. body_r,
  444. tree_ir.NopInstruction())
  445. else:
  446. create_loop_body = tree_ir.CompoundInstruction
  447. raise primitive_functions.PrimitiveFinished(
  448. tree_ir.LoopInstruction(
  449. create_loop_body(
  450. tree_ir.SelectInstruction(
  451. tree_ir.ReadValueInstruction(cond_r),
  452. tree_ir.EmptyInstruction(),
  453. tree_ir.BreakInstruction()),
  454. body_r)))
  455. def analyze_constant(self, instruction_id):
  456. """Tries to analyze the given 'constant' (literal) instruction."""
  457. node_id, = yield [("RD", [instruction_id, "node"])]
  458. raise primitive_functions.PrimitiveFinished(
  459. tree_ir.LiteralInstruction(node_id))
  460. def analyze_output(self, instruction_id):
  461. """Tries to analyze the given 'output' instruction."""
  462. # The plan is to basically generate this tree:
  463. #
  464. # value = <some tree>
  465. # last_output, last_output_link, new_last_output = \
  466. # yield [("RD", [user_root, "last_output"]),
  467. # ("RDE", [user_root, "last_output"]),
  468. # ("CN", []),
  469. # ]
  470. # _, _, _, _ = \
  471. # yield [("CD", [last_output, "value", value]),
  472. # ("CD", [last_output, "next", new_last_output]),
  473. # ("CD", [user_root, "last_output", new_last_output]),
  474. # ("DE", [last_output_link])
  475. # ]
  476. # yield None
  477. value_id, = yield [("RD", [instruction_id, "value"])]
  478. value_val, = yield [("CALL_ARGS", [self.analyze, (value_id,)])]
  479. value_local = tree_ir.StoreLocalInstruction('value', value_val)
  480. store_user_root = self.retrieve_user_root()
  481. last_output = tree_ir.StoreLocalInstruction(
  482. 'last_output',
  483. tree_ir.ReadDictionaryValueInstruction(
  484. store_user_root.create_load(),
  485. tree_ir.LiteralInstruction('last_output')))
  486. last_output_link = tree_ir.StoreLocalInstruction(
  487. 'last_output_link',
  488. tree_ir.ReadDictionaryEdgeInstruction(
  489. store_user_root.create_load(),
  490. tree_ir.LiteralInstruction('last_output')))
  491. new_last_output = tree_ir.StoreLocalInstruction(
  492. 'new_last_output',
  493. tree_ir.CreateNodeInstruction())
  494. result = tree_ir.create_block(
  495. value_local,
  496. store_user_root,
  497. last_output,
  498. last_output_link,
  499. new_last_output,
  500. tree_ir.CreateDictionaryEdgeInstruction(
  501. last_output.create_load(),
  502. tree_ir.LiteralInstruction('value'),
  503. value_local.create_load()),
  504. tree_ir.CreateDictionaryEdgeInstruction(
  505. last_output.create_load(),
  506. tree_ir.LiteralInstruction('next'),
  507. new_last_output.create_load()),
  508. tree_ir.CreateDictionaryEdgeInstruction(
  509. store_user_root.create_load(),
  510. tree_ir.LiteralInstruction('last_output'),
  511. new_last_output.create_load()),
  512. tree_ir.DeleteEdgeInstruction(last_output_link.create_load()),
  513. tree_ir.NopInstruction())
  514. raise primitive_functions.PrimitiveFinished(result)
  515. def analyze_input(self, _):
  516. """Tries to analyze the given 'input' instruction."""
  517. # Possible alternative to the explicit syntax tree:
  518. if self.jit.input_function_enabled:
  519. raise primitive_functions.PrimitiveFinished(
  520. tree_ir.create_jit_call(
  521. tree_ir.LoadGlobalInstruction(GET_INPUT_FUNCTION_NAME),
  522. [],
  523. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  524. # The plan is to generate this tree:
  525. #
  526. # value = None
  527. # while True:
  528. # _input = yield [("RD", [user_root, "input"])]
  529. # value = yield [("RD", [_input, "value"])]
  530. #
  531. # if value is None:
  532. # kwargs['mvk'].success = False # to avoid blocking
  533. # yield None # nop/interrupt
  534. # else:
  535. # break
  536. #
  537. # _next = yield [("RD", [_input, "next"])]
  538. # yield [("CD", [user_root, "input", _next])]
  539. # yield [("DN", [_input])]
  540. user_root = self.retrieve_user_root()
  541. _input = tree_ir.StoreLocalInstruction(
  542. None,
  543. tree_ir.ReadDictionaryValueInstruction(
  544. user_root.create_load(),
  545. tree_ir.LiteralInstruction('input')))
  546. value = tree_ir.StoreLocalInstruction(
  547. None,
  548. tree_ir.ReadDictionaryValueInstruction(
  549. _input.create_load(),
  550. tree_ir.LiteralInstruction('value')))
  551. raise primitive_functions.PrimitiveFinished(
  552. tree_ir.CompoundInstruction(
  553. tree_ir.create_block(
  554. user_root,
  555. value.create_store(tree_ir.LiteralInstruction(None)),
  556. tree_ir.LoopInstruction(
  557. tree_ir.create_block(
  558. _input,
  559. value,
  560. tree_ir.SelectInstruction(
  561. tree_ir.BinaryInstruction(
  562. value.create_load(),
  563. 'is',
  564. tree_ir.LiteralInstruction(None)),
  565. tree_ir.create_block(
  566. tree_ir.StoreMemberInstruction(
  567. self.load_kernel(),
  568. 'success',
  569. tree_ir.LiteralInstruction(False)),
  570. tree_ir.NopInstruction()),
  571. tree_ir.BreakInstruction()))),
  572. tree_ir.CreateDictionaryEdgeInstruction(
  573. user_root.create_load(),
  574. tree_ir.LiteralInstruction('input'),
  575. tree_ir.ReadDictionaryValueInstruction(
  576. _input.create_load(),
  577. tree_ir.LiteralInstruction('next'))),
  578. tree_ir.DeleteNodeInstruction(_input.create_load())),
  579. value.create_load()))
  580. def analyze_resolve(self, instruction_id):
  581. """Tries to analyze the given 'resolve' instruction."""
  582. var_id, = yield [("RD", [instruction_id, "var"])]
  583. var_name, = yield [("RV", [var_id])]
  584. # To resolve a variable, we'll do something along the
  585. # lines of:
  586. #
  587. # if 'local_var' in locals():
  588. # tmp = local_var
  589. # else:
  590. # _globals, = yield [("RD", [user_root, "globals"])]
  591. # global_var, = yield [("RD", [_globals, var_name])]
  592. #
  593. # if global_var is None:
  594. # raise Exception("Not found as global: %s" % (var_name))
  595. #
  596. # tmp = global_var
  597. name = self.get_local_name(var_id)
  598. if var_name is None:
  599. raise primitive_functions.PrimitiveFinished(
  600. tree_ir.LoadLocalInstruction(name))
  601. user_root = self.retrieve_user_root()
  602. global_var = tree_ir.StoreLocalInstruction(
  603. 'global_var',
  604. tree_ir.ReadDictionaryValueInstruction(
  605. tree_ir.ReadDictionaryValueInstruction(
  606. user_root.create_load(),
  607. tree_ir.LiteralInstruction('globals')),
  608. tree_ir.LiteralInstruction(var_name)))
  609. err_block = tree_ir.SelectInstruction(
  610. tree_ir.BinaryInstruction(
  611. global_var.create_load(),
  612. 'is',
  613. tree_ir.LiteralInstruction(None)),
  614. tree_ir.RaiseInstruction(
  615. tree_ir.CallInstruction(
  616. tree_ir.LoadGlobalInstruction('Exception'),
  617. [tree_ir.LiteralInstruction(
  618. "Not found as global: %s" % var_name)
  619. ])),
  620. tree_ir.EmptyInstruction())
  621. raise primitive_functions.PrimitiveFinished(
  622. tree_ir.SelectInstruction(
  623. tree_ir.LocalExistsInstruction(name),
  624. tree_ir.LoadLocalInstruction(name),
  625. tree_ir.CompoundInstruction(
  626. tree_ir.create_block(
  627. user_root,
  628. global_var,
  629. err_block),
  630. global_var.create_load())))
  631. def analyze_declare(self, instruction_id):
  632. """Tries to analyze the given 'declare' function."""
  633. var_id, = yield [("RD", [instruction_id, "var"])]
  634. self.register_local_var(var_id)
  635. name = self.get_local_name(var_id)
  636. # The following logic declares a local:
  637. #
  638. # if 'local_name' not in locals():
  639. # local_name, = yield [("CN", [])]
  640. # yield [("CE", [LOCALS_NODE_NAME, local_name])]
  641. raise primitive_functions.PrimitiveFinished(
  642. tree_ir.SelectInstruction(
  643. tree_ir.LocalExistsInstruction(name),
  644. tree_ir.EmptyInstruction(),
  645. tree_ir.create_new_local_node(
  646. name,
  647. tree_ir.LoadLocalInstruction(LOCALS_NODE_NAME))))
  648. def analyze_global(self, instruction_id):
  649. """Tries to analyze the given 'global' (declaration) instruction."""
  650. var_id, = yield [("RD", [instruction_id, "var"])]
  651. var_name, = yield [("RV", [var_id])]
  652. # To resolve a variable, we'll do something along the
  653. # lines of:
  654. #
  655. # _globals, = yield [("RD", [user_root, "globals"])]
  656. # global_var = yield [("RD", [_globals, var_name])]
  657. #
  658. # if global_var is None:
  659. # global_var, = yield [("CN", [])]
  660. # yield [("CD", [_globals, var_name, global_var])]
  661. #
  662. # tmp = global_var
  663. user_root = self.retrieve_user_root()
  664. _globals = tree_ir.StoreLocalInstruction(
  665. '_globals',
  666. tree_ir.ReadDictionaryValueInstruction(
  667. user_root.create_load(),
  668. tree_ir.LiteralInstruction('globals')))
  669. global_var = tree_ir.StoreLocalInstruction(
  670. 'global_var',
  671. tree_ir.ReadDictionaryValueInstruction(
  672. _globals.create_load(),
  673. tree_ir.LiteralInstruction(var_name)))
  674. raise primitive_functions.PrimitiveFinished(
  675. tree_ir.CompoundInstruction(
  676. tree_ir.create_block(
  677. user_root,
  678. _globals,
  679. global_var,
  680. tree_ir.SelectInstruction(
  681. tree_ir.BinaryInstruction(
  682. global_var.create_load(),
  683. 'is',
  684. tree_ir.LiteralInstruction(None)),
  685. tree_ir.create_block(
  686. global_var.create_store(
  687. tree_ir.CreateNodeInstruction()),
  688. tree_ir.CreateDictionaryEdgeInstruction(
  689. _globals.create_load(),
  690. tree_ir.LiteralInstruction(var_name),
  691. global_var.create_load())),
  692. tree_ir.EmptyInstruction())),
  693. global_var.create_load()))
  694. def analyze_assign(self, instruction_id):
  695. """Tries to analyze the given 'assign' instruction."""
  696. var_id, value_id = yield [("RD", [instruction_id, "var"]),
  697. ("RD", [instruction_id, "value"])]
  698. (var_r, value_r), = yield [("CALL_ARGS", [self.analyze_all, ([var_id, value_id],)])]
  699. # Assignments work like this:
  700. #
  701. # value_link = yield [("RDE", [variable, "value"])]
  702. # _, _ = yield [("CD", [variable, "value", value]),
  703. # ("DE", [value_link])]
  704. variable = tree_ir.StoreLocalInstruction(None, var_r)
  705. value = tree_ir.StoreLocalInstruction(None, value_r)
  706. value_link = tree_ir.StoreLocalInstruction(
  707. 'value_link',
  708. tree_ir.ReadDictionaryEdgeInstruction(
  709. variable.create_load(),
  710. tree_ir.LiteralInstruction('value')))
  711. raise primitive_functions.PrimitiveFinished(
  712. tree_ir.create_block(
  713. variable,
  714. value,
  715. value_link,
  716. tree_ir.CreateDictionaryEdgeInstruction(
  717. variable.create_load(),
  718. tree_ir.LiteralInstruction('value'),
  719. value.create_load()),
  720. tree_ir.DeleteEdgeInstruction(
  721. value_link.create_load())))
  722. def analyze_access(self, instruction_id):
  723. """Tries to analyze the given 'access' instruction."""
  724. var_id, = yield [("RD", [instruction_id, "var"])]
  725. var_r, = yield [("CALL_ARGS", [self.analyze, (var_id,)])]
  726. # Accessing a variable is pretty easy. It really just boils
  727. # down to reading the value corresponding to the 'value' key
  728. # of the variable.
  729. #
  730. # value, = yield [("RD", [returnvalue, "value"])]
  731. raise primitive_functions.PrimitiveFinished(
  732. tree_ir.ReadDictionaryValueInstruction(
  733. var_r,
  734. tree_ir.LiteralInstruction('value')))
  735. def analyze_direct_call(self, callee_id, callee_name, first_parameter_id):
  736. """Tries to analyze a direct 'call' instruction."""
  737. self.register_function_var(callee_id)
  738. body_id, = yield [("RD", [callee_id, "body"])]
  739. # Make this function dependent on the callee.
  740. if body_id in self.jit.compilation_dependencies:
  741. self.jit.compilation_dependencies[body_id].add(self.body_id)
  742. # Figure out if the function might be an intrinsic.
  743. intrinsic = self.jit.get_intrinsic(callee_name)
  744. if intrinsic is None:
  745. compiled_func = self.jit.lookup_compiled_function(callee_name)
  746. if compiled_func is None:
  747. # Compile the callee.
  748. yield [("CALL_ARGS", [self.jit.jit_compile, (self.user_root, body_id, callee_name)])]
  749. else:
  750. self.jit.register_compiled(body_id, compiled_func, callee_name)
  751. # Get the callee's name.
  752. compiled_func_name = self.jit.get_compiled_name(body_id)
  753. # This handles the corner case where a constant node is called, like
  754. # 'call(constant(9), ...)'. In this case, `callee_name` is `None`
  755. # because 'constant(9)' doesn't give us a name. However, we can look up
  756. # the name of the function at a specific node. If that turns out to be
  757. # an intrinsic, then we still want to pick the intrinsic over a call.
  758. intrinsic = self.jit.get_intrinsic(compiled_func_name)
  759. # Analyze the argument dictionary.
  760. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (first_parameter_id,)])]
  761. if intrinsic is not None:
  762. raise primitive_functions.PrimitiveFinished(
  763. apply_intrinsic(intrinsic, named_args))
  764. else:
  765. raise primitive_functions.PrimitiveFinished(
  766. tree_ir.create_jit_call(
  767. tree_ir.LoadGlobalInstruction(compiled_func_name),
  768. named_args,
  769. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  770. def analyze_arguments(self, first_argument_id):
  771. """Analyzes the parameter-to-argument mapping started by the specified first argument
  772. node."""
  773. next_param = first_argument_id
  774. named_args = []
  775. while next_param is not None:
  776. param_name_id, = yield [("RD", [next_param, "name"])]
  777. param_name, = yield [("RV", [param_name_id])]
  778. param_val_id, = yield [("RD", [next_param, "value"])]
  779. param_val, = yield [("CALL_ARGS", [self.analyze, (param_val_id,)])]
  780. named_args.append((param_name, param_val))
  781. next_param, = yield [("RD", [next_param, "next_param"])]
  782. raise primitive_functions.PrimitiveFinished(named_args)
  783. def analyze_indirect_call(self, func_id, first_arg_id):
  784. """Analyzes a call to an unknown function."""
  785. # First off, let's analyze the callee and the argument list.
  786. func_val, = yield [("CALL_ARGS", [self.analyze, (func_id,)])]
  787. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (first_arg_id,)])]
  788. # Call the __call_function function to run the interpreter, like so:
  789. #
  790. # __call_function(function_id, { first_param_name : first_param_val, ... }, **kwargs)
  791. #
  792. dict_literal = tree_ir.DictionaryLiteralInstruction(
  793. [(tree_ir.LiteralInstruction(key), val) for key, val in named_args])
  794. raise primitive_functions.PrimitiveFinished(
  795. tree_ir.create_jit_call(
  796. tree_ir.LoadGlobalInstruction(CALL_FUNCTION_NAME),
  797. [('function_id', func_val), ('named_arguments', dict_literal)],
  798. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  799. def try_analyze_direct_call(self, func_id, first_param_id):
  800. """Tries to analyze the given 'call' instruction as a direct call."""
  801. if not self.jit.direct_calls_allowed:
  802. raise JitCompilationFailedException('Direct calls are not allowed by the JIT.')
  803. # Figure out what the 'func' instruction's type is.
  804. func_instruction_op, = yield [("RV", [func_id])]
  805. if func_instruction_op['value'] == 'access':
  806. # 'access(resolve(var))' instructions are translated to direct calls.
  807. access_value_id, = yield [("RD", [func_id, "var"])]
  808. access_value_op, = yield [("RV", [access_value_id])]
  809. if access_value_op['value'] == 'resolve':
  810. resolved_var_id, = yield [("RD", [access_value_id, "var"])]
  811. resolved_var_name, = yield [("RV", [resolved_var_id])]
  812. # Try to look up the name as a global.
  813. _globals, = yield [("RD", [self.user_root, "globals"])]
  814. global_var, = yield [("RD", [_globals, resolved_var_name])]
  815. global_val, = yield [("RD", [global_var, "value"])]
  816. if global_val is not None:
  817. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  818. global_val, resolved_var_name, first_param_id)])]
  819. raise primitive_functions.PrimitiveFinished(result)
  820. elif func_instruction_op['value'] == 'constant':
  821. # 'const(func_id)' instructions are also translated to direct calls.
  822. function_val_id, = yield [("RD", [func_id, "node"])]
  823. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  824. function_val_id, None, first_param_id)])]
  825. raise primitive_functions.PrimitiveFinished(result)
  826. raise JitCompilationFailedException(
  827. "Cannot JIT function calls that target an unknown value as direct calls.")
  828. def analyze_call(self, instruction_id):
  829. """Tries to analyze the given 'call' instruction."""
  830. func_id, first_param_id, = yield [("RD", [instruction_id, "func"]),
  831. ("RD", [instruction_id, "params"])]
  832. def handle_exception(exception):
  833. # Looks like we'll have to compile it as an indirect call.
  834. gen = self.analyze_indirect_call(func_id, first_param_id)
  835. result, = yield [("CALL", [gen])]
  836. raise primitive_functions.PrimitiveFinished(result)
  837. # Try to analyze the call as a direct call.
  838. yield [("TRY", [])]
  839. yield [("CATCH", [JitCompilationFailedException, handle_exception])]
  840. result, = yield [("CALL_ARGS", [self.try_analyze_direct_call, (func_id, first_param_id)])]
  841. yield [("END_TRY", [])]
  842. raise primitive_functions.PrimitiveFinished(result)
  843. instruction_analyzers = {
  844. 'if' : analyze_if,
  845. 'while' : analyze_while,
  846. 'return' : analyze_return,
  847. 'constant' : analyze_constant,
  848. 'resolve' : analyze_resolve,
  849. 'declare' : analyze_declare,
  850. 'global' : analyze_global,
  851. 'assign' : analyze_assign,
  852. 'access' : analyze_access,
  853. 'output' : analyze_output,
  854. 'input' : analyze_input,
  855. 'call' : analyze_call
  856. }