jit.py 43 KB

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