runtime.py 7.0 KB

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