bytecode_to_tree.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. """Naively converts bytecode IR to tree IR."""
  2. import modelverse_jit.bytecode_ir as bytecode_ir
  3. import modelverse_jit.tree_ir as tree_ir
  4. import modelverse_jit.runtime as jit_runtime
  5. import modelverse_kernel.primitives as primitive_functions
  6. def get_parameter_names(compiled_function):
  7. """Gets the given compiled function's parameter names."""
  8. if hasattr(compiled_function, '__code__'):
  9. return compiled_function.__code__.co_varnames[
  10. :compiled_function.__code__.co_argcount]
  11. elif hasattr(compiled_function, '__init__'):
  12. return get_parameter_names(compiled_function.__init__)[1:]
  13. else:
  14. raise ValueError("'compiled_function' must be a function or a type.")
  15. def apply_intrinsic(intrinsic_function, named_args):
  16. """Applies the given intrinsic to the given sequence of named arguments."""
  17. param_names = get_parameter_names(intrinsic_function)
  18. if tuple(param_names) == tuple([n for n, _ in named_args]):
  19. # Perfect match. Yay!
  20. return intrinsic_function(**dict(named_args))
  21. else:
  22. # We'll have to store the arguments into locals to preserve
  23. # the order of evaluation.
  24. stored_args = [(name, tree_ir.StoreLocalInstruction(None, arg)) for name, arg in named_args]
  25. arg_value_dict = dict([(name, arg.create_load()) for name, arg in stored_args])
  26. store_instructions = [instruction for _, instruction in stored_args]
  27. return tree_ir.CompoundInstruction(
  28. tree_ir.create_block(*store_instructions),
  29. intrinsic_function(**arg_value_dict))
  30. def retrieve_task_root():
  31. """Creates an instruction that stores the task_root variable in a local."""
  32. return tree_ir.StoreLocalInstruction(
  33. 'task_root', load_task_root())
  34. def load_task_root():
  35. """Creates an instruction that loads the task_root variable."""
  36. return tree_ir.LoadIndexInstruction(
  37. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  38. tree_ir.LiteralInstruction('task_root'))
  39. def load_kernel():
  40. """Creates an instruction that loads the Modelverse kernel."""
  41. return tree_ir.LoadIndexInstruction(
  42. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  43. tree_ir.LiteralInstruction('mvk'))
  44. def create_access(pointer):
  45. """Creates a tree that loads the given pointer's value."""
  46. # Accessing a variable is pretty easy. It really just boils
  47. # down to reading the value corresponding to the 'value' key
  48. # of the variable.
  49. #
  50. # value, = yield [("RD", [returnvalue, "value"])]
  51. #
  52. return tree_ir.ReadDictionaryValueInstruction(
  53. pointer,
  54. tree_ir.LiteralInstruction('value'))
  55. def create_assign(pointer, value):
  56. """Creates a tree that assigns the given value to the given pointer."""
  57. # Assignments work like this:
  58. #
  59. # value_link = yield [("RDE", [variable, "value"])]
  60. # _, _ = yield [("CD", [variable, "value", value]),
  61. # ("DE", [value_link])]
  62. #
  63. variable = tree_ir.StoreLocalInstruction(None, pointer)
  64. value = tree_ir.StoreLocalInstruction(None, value)
  65. value_link = tree_ir.StoreLocalInstruction(
  66. 'value_link',
  67. tree_ir.ReadDictionaryEdgeInstruction(
  68. variable.create_load(),
  69. tree_ir.LiteralInstruction('value')))
  70. return tree_ir.create_block(
  71. variable,
  72. value,
  73. value_link,
  74. tree_ir.CreateDictionaryEdgeInstruction(
  75. variable.create_load(),
  76. tree_ir.LiteralInstruction('value'),
  77. value.create_load()),
  78. tree_ir.DeleteEdgeInstruction(
  79. value_link.create_load()))
  80. def create_input(use_input_function=False):
  81. """Creates an instruction that pops a value from the input queue."""
  82. # Possible alternative to the explicit syntax tree: just call the jit_runtime.__get_input
  83. # function.
  84. if use_input_function:
  85. return tree_ir.create_jit_call(
  86. tree_ir.LoadGlobalInstruction(jit_runtime.GET_INPUT_FUNCTION_NAME),
  87. [],
  88. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME))
  89. # The plan is to generate this tree:
  90. #
  91. # value = None
  92. # while True:
  93. # _input = yield [("RD", [task_root, "input"])]
  94. # value = yield [("RD", [_input, "value"])]
  95. #
  96. # if value is None:
  97. # kwargs['mvk'].success = False # to avoid blocking
  98. # yield None # nop/interrupt
  99. # else:
  100. # break
  101. #
  102. # _next = yield [("RD", [_input, "next"])]
  103. # yield [("CD", [task_root, "input", _next])]
  104. # yield [("CE", [jit_locals, value])]
  105. # yield [("DN", [_input])]
  106. task_root = retrieve_task_root()
  107. _input = tree_ir.StoreLocalInstruction(
  108. None,
  109. tree_ir.ReadDictionaryValueInstruction(
  110. task_root.create_load(),
  111. tree_ir.LiteralInstruction('input')))
  112. value = tree_ir.StoreLocalInstruction(
  113. None,
  114. tree_ir.ReadDictionaryValueInstruction(
  115. _input.create_load(),
  116. tree_ir.LiteralInstruction('value')))
  117. raise primitive_functions.PrimitiveFinished(
  118. tree_ir.CompoundInstruction(
  119. tree_ir.create_block(
  120. task_root,
  121. value.create_store(tree_ir.LiteralInstruction(None)),
  122. tree_ir.LoopInstruction(
  123. tree_ir.create_block(
  124. _input,
  125. value,
  126. tree_ir.SelectInstruction(
  127. tree_ir.BinaryInstruction(
  128. value.create_load(),
  129. 'is',
  130. tree_ir.LiteralInstruction(None)),
  131. tree_ir.create_block(
  132. tree_ir.StoreMemberInstruction(
  133. load_kernel(),
  134. 'success',
  135. tree_ir.LiteralInstruction(False)),
  136. tree_ir.NopInstruction()),
  137. tree_ir.BreakInstruction()))),
  138. tree_ir.CreateDictionaryEdgeInstruction(
  139. task_root.create_load(),
  140. tree_ir.LiteralInstruction('input'),
  141. tree_ir.ReadDictionaryValueInstruction(
  142. _input.create_load(),
  143. tree_ir.LiteralInstruction('next'))),
  144. tree_ir.CreateEdgeInstruction(
  145. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME),
  146. value.create_load()),
  147. tree_ir.DeleteNodeInstruction(_input.create_load())),
  148. value.create_load()))
  149. def create_output(output_value):
  150. """Creates an output instruction that outputs the given value."""
  151. # The plan is to basically generate this tree:
  152. #
  153. # value = <some tree>
  154. # last_output, last_output_link, new_last_output = \
  155. # yield [("RD", [task_root, "last_output"]),
  156. # ("RDE", [task_root, "last_output"]),
  157. # ("CN", []),
  158. # ]
  159. # _, _, _, _ = \
  160. # yield [("CD", [last_output, "value", value]),
  161. # ("CD", [last_output, "next", new_last_output]),
  162. # ("CD", [task_root, "last_output", new_last_output]),
  163. # ("DE", [last_output_link])
  164. # ]
  165. # yield None
  166. value_local = tree_ir.StoreLocalInstruction('value', output_value)
  167. store_task_root = retrieve_task_root()
  168. last_output = tree_ir.StoreLocalInstruction(
  169. 'last_output',
  170. tree_ir.ReadDictionaryValueInstruction(
  171. store_task_root.create_load(),
  172. tree_ir.LiteralInstruction('last_output')))
  173. last_output_link = tree_ir.StoreLocalInstruction(
  174. 'last_output_link',
  175. tree_ir.ReadDictionaryEdgeInstruction(
  176. store_task_root.create_load(),
  177. tree_ir.LiteralInstruction('last_output')))
  178. new_last_output = tree_ir.StoreLocalInstruction(
  179. 'new_last_output',
  180. tree_ir.CreateNodeInstruction())
  181. return tree_ir.create_block(
  182. value_local,
  183. store_task_root,
  184. last_output,
  185. last_output_link,
  186. new_last_output,
  187. tree_ir.CreateDictionaryEdgeInstruction(
  188. last_output.create_load(),
  189. tree_ir.LiteralInstruction('value'),
  190. value_local.create_load()),
  191. tree_ir.CreateDictionaryEdgeInstruction(
  192. last_output.create_load(),
  193. tree_ir.LiteralInstruction('next'),
  194. new_last_output.create_load()),
  195. tree_ir.CreateDictionaryEdgeInstruction(
  196. store_task_root.create_load(),
  197. tree_ir.LiteralInstruction('last_output'),
  198. new_last_output.create_load()),
  199. tree_ir.DeleteEdgeInstruction(last_output_link.create_load()),
  200. tree_ir.NopInstruction())
  201. def create_indirect_call(target, argument_list):
  202. """Creates an indirect call to the function defined by the node with the id computed
  203. by the first argument."""
  204. # Call the __call_function function to run the interpreter, like so:
  205. #
  206. # __call_function(function_id, { first_param_name : first_param_val, ... }, **kwargs)
  207. #
  208. dict_literal = tree_ir.DictionaryLiteralInstruction(
  209. [(tree_ir.LiteralInstruction(key), val) for key, val in argument_list])
  210. return tree_ir.create_jit_call(
  211. tree_ir.LoadGlobalInstruction(jit_runtime.CALL_FUNCTION_NAME),
  212. [('function_id', target), ('named_arguments', dict_literal)],
  213. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME))
  214. def with_debug_info_trace(instruction, debug_info, function_name):
  215. """Prepends the given instruction with a tracing instruction that prints
  216. the given debug information and function name."""
  217. if debug_info is None and function_name is None:
  218. return instruction
  219. else:
  220. return tree_ir.create_block(
  221. tree_ir.PrintInstruction(
  222. tree_ir.LiteralInstruction(
  223. jit_runtime.format_trace_message(
  224. debug_info, function_name,
  225. jit_runtime.BASELINE_JIT_ORIGIN_NAME))),
  226. instruction)
  227. class LocalNameMap(object):
  228. """A map that converts local variable nodes to identifiers."""
  229. def __init__(self, local_mapping=None):
  230. if local_mapping is None:
  231. local_mapping = {}
  232. self.local_mapping = local_mapping
  233. def get_local_name(self, local_variable_id):
  234. """Gets the name for the local variable node with the given id."""
  235. if local_variable_id not in self.local_mapping:
  236. self.local_mapping[local_variable_id] = 'local%d' % local_variable_id
  237. return self.local_mapping[local_variable_id]
  238. class AnalysisState(object):
  239. """The state of a bytecode analysis call graph."""
  240. def __init__(self, jit, body_id, task_root, local_mapping, max_instructions=None):
  241. self.analyzed_instructions = set()
  242. self.function_vars = set()
  243. self.local_vars = set()
  244. self.body_id = body_id
  245. self.max_instructions = max_instructions
  246. self.task_root = task_root
  247. self.jit = jit
  248. self.local_name_map = LocalNameMap(local_mapping)
  249. self.function_name = jit.jitted_entry_points[body_id]
  250. self.enclosing_loop_instruction = None
  251. def register_local_var(self, local_id):
  252. """Registers the given variable node id as a local."""
  253. if local_id in self.function_vars:
  254. raise jit_runtime.JitCompilationFailedException(
  255. "Local is used as target of function call.")
  256. self.local_vars.add(local_id)
  257. def register_function_var(self, local_id):
  258. """Registers the given variable node id as a function."""
  259. if local_id in self.local_vars:
  260. raise jit_runtime.JitCompilationFailedException(
  261. "Local is used as target of function call.")
  262. self.function_vars.add(local_id)
  263. def analyze(self, instruction):
  264. """Tries to build an intermediate representation from the instruction with the
  265. given id."""
  266. # Check the analyzed_instructions set for instruction_id to avoid
  267. # infinite loops.
  268. if instruction in self.analyzed_instructions:
  269. raise jit_runtime.JitCompilationFailedException(
  270. 'Cannot jit non-tree instruction graph.')
  271. elif (self.max_instructions is not None and
  272. len(self.analyzed_instructions) > self.max_instructions):
  273. raise jit_runtime.JitCompilationFailedException(
  274. 'Maximum number of instructions exceeded.')
  275. self.analyzed_instructions.add(instruction)
  276. instruction_type = type(instruction)
  277. if instruction_type in self.instruction_analyzers:
  278. # Analyze the instruction itself.
  279. outer_result, = yield [
  280. ("CALL_ARGS", [self.instruction_analyzers[instruction_type], (self, instruction)])]
  281. if instruction.debug_information is not None:
  282. if self.jit.tracing_enabled:
  283. outer_result = with_debug_info_trace(
  284. outer_result, instruction.debug_information, self.function_name)
  285. if self.jit.source_maps_enabled:
  286. outer_result = tree_ir.DebugInfoInstruction(
  287. outer_result, instruction.debug_information)
  288. # Check if the instruction has a 'next' instruction.
  289. if instruction.next_instruction is None:
  290. raise primitive_functions.PrimitiveFinished(outer_result)
  291. else:
  292. next_result, = yield [
  293. ("CALL_ARGS", [self.analyze, (instruction.next_instruction,)])]
  294. raise primitive_functions.PrimitiveFinished(
  295. tree_ir.CompoundInstruction(
  296. outer_result,
  297. next_result))
  298. else:
  299. raise jit_runtime.JitCompilationFailedException(
  300. "Unknown instruction type: '%s'" % type(instruction))
  301. def analyze_all(self, instruction_ids):
  302. """Tries to compile a list of IR trees from the given list of instruction ids."""
  303. results = []
  304. for inst in instruction_ids:
  305. analyzed_inst, = yield [("CALL_ARGS", [self.analyze, (inst,)])]
  306. results.append(analyzed_inst)
  307. raise primitive_functions.PrimitiveFinished(results)
  308. def analyze_return(self, instruction):
  309. """Tries to analyze the given 'return' instruction."""
  310. def create_return(return_value):
  311. return tree_ir.ReturnInstruction(
  312. tree_ir.CompoundInstruction(
  313. return_value,
  314. tree_ir.DeleteEdgeInstruction(
  315. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_EDGE_NAME))))
  316. if instruction.value is None:
  317. raise primitive_functions.PrimitiveFinished(
  318. create_return(
  319. tree_ir.EmptyInstruction()))
  320. else:
  321. retval, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  322. raise primitive_functions.PrimitiveFinished(
  323. create_return(retval))
  324. def analyze_if(self, instruction):
  325. """Tries to analyze the given 'if' instruction."""
  326. if instruction.else_clause is None:
  327. (cond_r, true_r), = yield [
  328. ("CALL_ARGS",
  329. [self.analyze_all,
  330. ([instruction.condition, instruction.if_clause],)])]
  331. false_r = tree_ir.EmptyInstruction()
  332. else:
  333. (cond_r, true_r, false_r), = yield [
  334. ("CALL_ARGS",
  335. [self.analyze_all,
  336. ([instruction.condition, instruction.if_clause, instruction.else_clause],)])]
  337. raise primitive_functions.PrimitiveFinished(
  338. tree_ir.SelectInstruction(
  339. tree_ir.ReadValueInstruction(cond_r),
  340. true_r,
  341. false_r))
  342. def analyze_while(self, instruction):
  343. """Tries to analyze the given 'while' instruction."""
  344. # Analyze the condition.
  345. cond_r, = yield [("CALL_ARGS", [self.analyze, (instruction.condition,)])]
  346. # Store the old enclosing loop on the stack, and make this loop the
  347. # new enclosing loop.
  348. old_loop_instruction = self.enclosing_loop_instruction
  349. self.enclosing_loop_instruction = instruction
  350. body_r, = yield [("CALL_ARGS", [self.analyze, (instruction.body,)])]
  351. # Restore hte old enclosing loop.
  352. self.enclosing_loop_instruction = old_loop_instruction
  353. if self.jit.nop_insertion_enabled:
  354. create_loop_body = lambda check, body: tree_ir.create_block(
  355. check,
  356. body_r,
  357. tree_ir.NopInstruction())
  358. else:
  359. create_loop_body = tree_ir.CompoundInstruction
  360. raise primitive_functions.PrimitiveFinished(
  361. tree_ir.LoopInstruction(
  362. create_loop_body(
  363. tree_ir.SelectInstruction(
  364. tree_ir.ReadValueInstruction(cond_r),
  365. tree_ir.EmptyInstruction(),
  366. tree_ir.BreakInstruction()),
  367. body_r)))
  368. def analyze_constant(self, instruction):
  369. """Tries to analyze the given 'constant' (literal) instruction."""
  370. raise primitive_functions.PrimitiveFinished(
  371. tree_ir.LiteralInstruction(instruction.constant_id))
  372. def analyze_output(self, instruction):
  373. """Tries to analyze the given 'output' instruction."""
  374. value_val, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  375. raise primitive_functions.PrimitiveFinished(create_output(value_val))
  376. def analyze_input(self, _):
  377. """Tries to analyze the given 'input' instruction."""
  378. raise primitive_functions.PrimitiveFinished(create_input(self.jit.input_function_enabled))
  379. def analyze_resolve(self, instruction):
  380. """Tries to analyze the given 'resolve' instruction."""
  381. # To resolve a variable, we'll do something along the
  382. # lines of:
  383. #
  384. # if 'local_var' in locals():
  385. # tmp = local_var
  386. # else:
  387. # _globals, = yield [("RD", [task_root, "globals"])]
  388. # global_var, = yield [("RD", [_globals, var_name])]
  389. #
  390. # if global_var is None:
  391. # raise Exception("Not found as global: %s" % (var_name))
  392. #
  393. # tmp = global_var
  394. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  395. if instruction.variable.name is None:
  396. raise primitive_functions.PrimitiveFinished(
  397. tree_ir.LoadLocalInstruction(name))
  398. task_root = retrieve_task_root()
  399. global_var = tree_ir.StoreLocalInstruction(
  400. 'global_var',
  401. tree_ir.ReadDictionaryValueInstruction(
  402. tree_ir.ReadDictionaryValueInstruction(
  403. task_root.create_load(),
  404. tree_ir.LiteralInstruction('globals')),
  405. tree_ir.LiteralInstruction(instruction.variable.name)))
  406. err_block = tree_ir.SelectInstruction(
  407. tree_ir.BinaryInstruction(
  408. global_var.create_load(),
  409. 'is',
  410. tree_ir.LiteralInstruction(None)),
  411. tree_ir.RaiseInstruction(
  412. tree_ir.CallInstruction(
  413. tree_ir.LoadGlobalInstruction('Exception'),
  414. [tree_ir.LiteralInstruction(
  415. jit_runtime.GLOBAL_NOT_FOUND_MESSAGE_FORMAT % instruction.variable.name)
  416. ])),
  417. tree_ir.EmptyInstruction())
  418. raise primitive_functions.PrimitiveFinished(
  419. tree_ir.SelectInstruction(
  420. tree_ir.LocalExistsInstruction(name),
  421. tree_ir.LoadLocalInstruction(name),
  422. tree_ir.CompoundInstruction(
  423. tree_ir.create_block(
  424. task_root,
  425. global_var,
  426. err_block),
  427. global_var.create_load())))
  428. def analyze_declare(self, instruction):
  429. """Tries to analyze the given 'declare' function."""
  430. self.register_local_var(instruction.variable.node_id)
  431. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  432. # The following logic declares a local:
  433. #
  434. # if 'local_name' not in locals():
  435. # local_name, = yield [("CN", [])]
  436. # yield [("CE", [LOCALS_NODE_NAME, local_name])]
  437. raise primitive_functions.PrimitiveFinished(
  438. tree_ir.SelectInstruction(
  439. tree_ir.LocalExistsInstruction(name),
  440. tree_ir.EmptyInstruction(),
  441. tree_ir.create_new_local_node(
  442. name,
  443. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))))
  444. def analyze_global(self, instruction):
  445. """Tries to analyze the given 'global' (declaration) instruction."""
  446. # To declare a variable, we'll do something along the
  447. # lines of:
  448. #
  449. # _globals, = yield [("RD", [task_root, "globals"])]
  450. # global_var = yield [("RD", [_globals, var_name])]
  451. #
  452. # if global_var is None:
  453. # global_var, = yield [("CN", [])]
  454. # yield [("CD", [_globals, var_name, global_var])]
  455. #
  456. # tmp = global_var
  457. task_root = retrieve_task_root()
  458. _globals = tree_ir.StoreLocalInstruction(
  459. '_globals',
  460. tree_ir.ReadDictionaryValueInstruction(
  461. task_root.create_load(),
  462. tree_ir.LiteralInstruction('globals')))
  463. global_var = tree_ir.StoreLocalInstruction(
  464. 'global_var',
  465. tree_ir.ReadDictionaryValueInstruction(
  466. _globals.create_load(),
  467. tree_ir.LiteralInstruction(instruction.variable.name)))
  468. raise primitive_functions.PrimitiveFinished(
  469. tree_ir.CompoundInstruction(
  470. tree_ir.create_block(
  471. task_root,
  472. _globals,
  473. global_var,
  474. tree_ir.SelectInstruction(
  475. tree_ir.BinaryInstruction(
  476. global_var.create_load(),
  477. 'is',
  478. tree_ir.LiteralInstruction(None)),
  479. tree_ir.create_block(
  480. global_var.create_store(
  481. tree_ir.CreateNodeInstruction()),
  482. tree_ir.CreateDictionaryEdgeInstruction(
  483. _globals.create_load(),
  484. tree_ir.LiteralInstruction(
  485. instruction.variable.name),
  486. global_var.create_load())),
  487. tree_ir.EmptyInstruction())),
  488. global_var.create_load()))
  489. def analyze_assign(self, instruction):
  490. """Tries to analyze the given 'assign' instruction."""
  491. (var_r, value_r), = yield [
  492. ("CALL_ARGS", [self.analyze_all, ([instruction.pointer, instruction.value],)])]
  493. raise primitive_functions.PrimitiveFinished(create_assign(var_r, value_r))
  494. def analyze_access(self, instruction):
  495. """Tries to analyze the given 'access' instruction."""
  496. var_r, = yield [("CALL_ARGS", [self.analyze, (instruction.pointer,)])]
  497. raise primitive_functions.PrimitiveFinished(create_access(var_r))
  498. def analyze_direct_call(self, callee_id, callee_name, argument_list):
  499. """Tries to analyze a direct 'call' instruction."""
  500. body_id, = yield [("RD", [callee_id, jit_runtime.FUNCTION_BODY_KEY])]
  501. # Make this function dependent on the callee.
  502. if body_id in self.jit.compilation_dependencies:
  503. self.jit.compilation_dependencies[body_id].add(self.body_id)
  504. # Figure out if the function might be an intrinsic.
  505. intrinsic = self.jit.get_intrinsic(callee_name)
  506. if intrinsic is None:
  507. if callee_name is not None:
  508. self.jit.register_global(body_id, callee_name)
  509. compiled_func = self.jit.lookup_compiled_function(callee_name)
  510. else:
  511. compiled_func = None
  512. if compiled_func is None:
  513. # Compile the callee.
  514. yield [
  515. ("CALL_ARGS", [self.jit.jit_compile, (self.task_root, body_id, callee_name)])]
  516. # Get the callee's name.
  517. compiled_func_name = self.jit.get_compiled_name(body_id)
  518. # This handles the corner case where a constant node is called, like
  519. # 'call(constant(9), ...)'. In this case, `callee_name` is `None`
  520. # because 'constant(9)' doesn't give us a name. However, we can look up
  521. # the name of the function at a specific node. If that turns out to be
  522. # an intrinsic, then we still want to pick the intrinsic over a call.
  523. intrinsic = self.jit.get_intrinsic(compiled_func_name)
  524. # Analyze the argument dictionary.
  525. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  526. if intrinsic is not None:
  527. raise primitive_functions.PrimitiveFinished(
  528. apply_intrinsic(intrinsic, named_args))
  529. else:
  530. raise primitive_functions.PrimitiveFinished(
  531. tree_ir.create_jit_call(
  532. tree_ir.LoadGlobalInstruction(compiled_func_name),
  533. named_args,
  534. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  535. def analyze_arguments(self, argument_list):
  536. """Analyzes the given parameter-to-value mapping."""
  537. named_args = []
  538. for param_name, arg in argument_list:
  539. param_val, = yield [("CALL_ARGS", [self.analyze, (arg,)])]
  540. named_args.append((param_name, param_val))
  541. raise primitive_functions.PrimitiveFinished(named_args)
  542. def analyze_indirect_call(self, target, argument_list):
  543. """Analyzes a call to an unknown function."""
  544. # First off, let's analyze the callee and the argument list.
  545. func_val, = yield [("CALL_ARGS", [self.analyze, (target,)])]
  546. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  547. func_val = tree_ir.StoreLocalInstruction(None, func_val)
  548. raise primitive_functions.PrimitiveFinished(
  549. tree_ir.create_block(
  550. func_val,
  551. create_indirect_call(func_val.create_load(), named_args)))
  552. def try_analyze_direct_call(self, target, argument_list):
  553. """Tries to analyze the given 'call' instruction as a direct call."""
  554. if not self.jit.direct_calls_allowed:
  555. raise jit_runtime.JitCompilationFailedException(
  556. 'Direct calls are not allowed by the JIT.')
  557. # Figure out what the 'func' instruction's type is.
  558. if isinstance(target, bytecode_ir.AccessInstruction):
  559. # 'access(resolve(var))' instructions are translated to direct calls.
  560. if isinstance(target.pointer, bytecode_ir.ResolveInstruction):
  561. self.register_function_var(target.pointer.variable.node_id)
  562. resolved_var_name = target.pointer.variable.name
  563. if self.jit.thunks_enabled:
  564. # Analyze the argument dictionary.
  565. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  566. # Try to resolve the callee as an intrinsic.
  567. intrinsic = self.jit.get_intrinsic(resolved_var_name)
  568. if intrinsic is not None:
  569. raise primitive_functions.PrimitiveFinished(
  570. apply_intrinsic(intrinsic, named_args))
  571. # Otherwise, build a thunk.
  572. thunk_name = self.jit.jit_thunk_global(target.pointer.variable.name)
  573. raise primitive_functions.PrimitiveFinished(
  574. tree_ir.create_jit_call(
  575. tree_ir.LoadGlobalInstruction(thunk_name),
  576. named_args,
  577. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  578. else:
  579. # Try to look up the name as a global.
  580. _globals, = yield [("RD", [self.task_root, "globals"])]
  581. global_var, = yield [("RD", [_globals, resolved_var_name])]
  582. global_val, = yield [("RD", [global_var, "value"])]
  583. if global_val is not None:
  584. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  585. global_val, resolved_var_name, argument_list)])]
  586. raise primitive_functions.PrimitiveFinished(result)
  587. elif isinstance(target, bytecode_ir.ConstantInstruction):
  588. # 'const(func_id)' instructions are also translated to direct calls.
  589. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  590. target.constant_id, None, argument_list)])]
  591. raise primitive_functions.PrimitiveFinished(result)
  592. raise jit_runtime.JitCompilationFailedException(
  593. "Cannot JIT function calls that target an unknown value as direct calls.")
  594. def analyze_call(self, instruction):
  595. """Tries to analyze the given 'call' instruction."""
  596. def handle_exception(_):
  597. # Looks like we'll have to compile it as an indirect call.
  598. gen = self.analyze_indirect_call(instruction.target, instruction.argument_list)
  599. result, = yield [("CALL", [gen])]
  600. raise primitive_functions.PrimitiveFinished(result)
  601. # Try to analyze the call as a direct call.
  602. yield [("TRY", [])]
  603. yield [("CATCH", [jit_runtime.JitCompilationFailedException, handle_exception])]
  604. result, = yield [
  605. ("CALL_ARGS",
  606. [self.try_analyze_direct_call, (instruction.target, instruction.argument_list)])]
  607. yield [("END_TRY", [])]
  608. raise primitive_functions.PrimitiveFinished(result)
  609. def analyze_break(self, instruction):
  610. """Tries to analyze the given 'break' instruction."""
  611. if instruction.loop == self.enclosing_loop_instruction:
  612. raise primitive_functions.PrimitiveFinished(tree_ir.BreakInstruction())
  613. else:
  614. raise jit_runtime.JitCompilationFailedException(
  615. "Multilevel 'break' is not supported by the baseline JIT.")
  616. def analyze_continue(self, instruction):
  617. """Tries to analyze the given 'continue' instruction."""
  618. if instruction.loop == self.enclosing_loop_instruction:
  619. raise primitive_functions.PrimitiveFinished(tree_ir.ContinueInstruction())
  620. else:
  621. raise jit_runtime.JitCompilationFailedException(
  622. "Multilevel 'continue' is not supported by the baseline JIT.")
  623. instruction_analyzers = {
  624. bytecode_ir.SelectInstruction : analyze_if,
  625. bytecode_ir.WhileInstruction : analyze_while,
  626. bytecode_ir.ReturnInstruction : analyze_return,
  627. bytecode_ir.ConstantInstruction : analyze_constant,
  628. bytecode_ir.ResolveInstruction : analyze_resolve,
  629. bytecode_ir.DeclareInstruction : analyze_declare,
  630. bytecode_ir.GlobalInstruction : analyze_global,
  631. bytecode_ir.AssignInstruction : analyze_assign,
  632. bytecode_ir.AccessInstruction : analyze_access,
  633. bytecode_ir.OutputInstruction : analyze_output,
  634. bytecode_ir.InputInstruction : analyze_input,
  635. bytecode_ir.CallInstruction : analyze_call,
  636. bytecode_ir.BreakInstruction : analyze_break,
  637. bytecode_ir.ContinueInstruction : analyze_continue
  638. }