runtime.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import modelverse_kernel.primitives as primitive_functions
  2. class JitCompilationFailedException(Exception):
  3. """A type of exception that is raised when the jit fails to compile a function."""
  4. pass
  5. MUTABLE_FUNCTION_KEY = "mutable"
  6. """A dictionary key for functions that are mutable."""
  7. FUNCTION_BODY_KEY = "body"
  8. """A dictionary key for function bodies."""
  9. KWARGS_PARAMETER_NAME = "kwargs"
  10. """The name of the kwargs parameter in jitted functions."""
  11. CALL_FUNCTION_NAME = "__call_function"
  12. """The name of the '__call_function' function, in the jitted function scope."""
  13. GET_INPUT_FUNCTION_NAME = "__get_input"
  14. """The name of the '__get_input' function, in the jitted function scope."""
  15. JIT_THUNK_CONSTANT_FUNCTION_NAME = "__jit_thunk_constant"
  16. """The name of the jit_thunk_constant function in the JIT's global context."""
  17. JIT_THUNK_GLOBAL_FUNCTION_NAME = "__jit_thunk_global"
  18. """The name of the jit_thunk_global function in the JIT's global context."""
  19. LOCALS_NODE_NAME = "jit_locals"
  20. """The name of the node that is connected to all JIT locals in a given function call."""
  21. LOCALS_EDGE_NAME = "jit_locals_edge"
  22. """The name of the edge that connects the LOCALS_NODE_NAME node to a user root."""
  23. GLOBAL_NOT_FOUND_MESSAGE_FORMAT = "Not found as global: %s"
  24. """The format of the 'not found as global' message. Takes a single argument."""
  25. def format_trace_message(debug_info, function_name, source='JIT'):
  26. """Creates a formatted trace message."""
  27. if debug_info is None:
  28. debug_info = 'unknown location '
  29. if function_name is None:
  30. function_name = 'unknown function'
  31. return 'TRACE: %s(%s, %s)' % (debug_info, function_name, source)
  32. def call_function(function_id, named_arguments, **kwargs):
  33. """Runs the function with the given id, passing it the specified argument dictionary."""
  34. task_root = kwargs['task_root']
  35. kernel = kwargs['mvk']
  36. body_id, is_mutable = yield [
  37. ("RD", [function_id, FUNCTION_BODY_KEY]),
  38. ("RD", [function_id, MUTABLE_FUNCTION_KEY])]
  39. # Try to jit the function here. We might be able to avoid building the stack
  40. # frame.
  41. def handle_jit_failed(_):
  42. """Interprets the function."""
  43. interpreter_args = {'body_id' : body_id, 'named_arguments' : named_arguments}
  44. interpreter_args.update(kwargs)
  45. yield [("TAIL_CALL_KWARGS", [interpret_function_body, interpreter_args])]
  46. if is_mutable is not None:
  47. kernel.jit.mark_no_jit(body_id)
  48. yield [("TAIL_CALL_ARGS", [handle_jit_failed, ()])]
  49. else:
  50. kernel.jit.mark_entry_point(body_id)
  51. yield [("TRY", [])]
  52. yield [("CATCH", [JitCompilationFailedException, handle_jit_failed])]
  53. # Try to compile.
  54. compiled_func, = yield [("CALL_ARGS", [kernel.jit_compile, (task_root, body_id)])]
  55. yield [("END_TRY", [])]
  56. # Add the keyword arguments to the argument dictionary.
  57. named_arguments.update(kwargs)
  58. # Run the function.
  59. yield [("TAIL_CALL_KWARGS", [compiled_func, named_arguments])]
  60. def interpret_function(function_id, named_arguments, **kwargs):
  61. """Makes the interpreter run the function with the given id for the specified
  62. argument dictionary."""
  63. body_id, = yield [("RD", [function_id, FUNCTION_BODY_KEY])]
  64. args = {'body_id' : body_id, named_arguments : named_arguments}
  65. args.update(kwargs)
  66. yield [("TAIL_CALL_KWARGS", [interpret_function_body, args])]
  67. def interpret_function_body(body_id, named_arguments, **kwargs):
  68. """Makes the interpreter run the function body with the given id for the specified
  69. argument dictionary."""
  70. task_root = kwargs['task_root']
  71. kernel = kwargs['mvk']
  72. user_frame, = yield [("RD", [task_root, "frame"])]
  73. inst, = yield [("RD", [user_frame, "IP"])]
  74. kernel.jit.mark_entry_point(body_id)
  75. # Create a new stack frame.
  76. frame_link, new_phase, new_frame, new_evalstack, new_symbols, \
  77. new_returnvalue, intrinsic_return = \
  78. yield [("RDE", [task_root, "frame"]),
  79. ("CNV", ["init"]),
  80. ("CN", []),
  81. ("CN", []),
  82. ("CN", []),
  83. ("CN", []),
  84. ("CN", [])
  85. ]
  86. _, _, _, _, _, _, _, _, _, _ = \
  87. yield [("CD", [task_root, "frame", new_frame]),
  88. ("CD", [new_frame, "evalstack", new_evalstack]),
  89. ("CD", [new_frame, "symbols", new_symbols]),
  90. ("CD", [new_frame, "returnvalue", new_returnvalue]),
  91. ("CD", [new_frame, "caller", inst]),
  92. ("CD", [new_frame, "phase", new_phase]),
  93. ("CD", [new_frame, "IP", body_id]),
  94. ("CD", [new_frame, "prev", user_frame]),
  95. ("CD", [
  96. new_frame,
  97. primitive_functions.EXCEPTION_RETURN_KEY,
  98. intrinsic_return]),
  99. ("DE", [frame_link])
  100. ]
  101. # Put the parameters in the new stack frame's symbol table.
  102. (parameter_vars, parameter_names, _), = yield [
  103. ("CALL_ARGS", [kernel.jit.jit_signature, (body_id,)])]
  104. parameter_dict = dict(zip(parameter_names, parameter_vars))
  105. for (key, value) in named_arguments.items():
  106. param_var = parameter_dict[key]
  107. variable, = yield [("CN", [])]
  108. yield [("CD", [variable, "value", value])]
  109. symbol_edge, = yield [("CE", [new_symbols, variable])]
  110. yield [("CE", [symbol_edge, param_var])]
  111. taskname = kwargs['taskname']
  112. def exception_handler(ex):
  113. # print('Returning from interpreted function. Result: %s' % ex.result)
  114. raise primitive_functions.PrimitiveFinished(ex.result)
  115. # Create an exception handler to catch and translate InterpretedFunctionFinished.
  116. yield [("TRY", [])]
  117. yield [("CATCH", [primitive_functions.InterpretedFunctionFinished, exception_handler])]
  118. while 1:
  119. result, = yield [("CALL_ARGS", [kernel.execute_rule, (taskname,)])]
  120. # An instruction has completed. Forward it.
  121. yield result
  122. def get_input(**parameters):
  123. """Retrieves input."""
  124. mvk = parameters["mvk"]
  125. task_root = parameters["task_root"]
  126. while 1:
  127. yield [("CALL_ARGS", [mvk.input_init, (task_root,)])]
  128. # Finished
  129. if mvk.success:
  130. # Got some input, so we can access it
  131. raise primitive_functions.PrimitiveFinished(mvk.input_value)
  132. else:
  133. # No input, so yield None but don't stop
  134. yield None