cfg_ir.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """Defines control flow graph IR data structures."""
  2. # Let's just agree to disagree on map vs list comprehensions, pylint.
  3. # pylint: disable=I0011,W0141
  4. class SharedCounter(object):
  5. """Defines a shared counter."""
  6. def __init__(self):
  7. self.index = 0
  8. def next_value(self):
  9. """Gets the next value for this counter."""
  10. result = self.index
  11. self.index += 1
  12. return result
  13. class BasicBlock(object):
  14. """Represents a basic block."""
  15. def __init__(self, counter):
  16. self.parameters = []
  17. self.definitions = []
  18. self.counter = counter
  19. self.index = counter.next_value()
  20. self.definition_counter = SharedCounter()
  21. self.flow = UnreachableFlow()
  22. def append_parameter(self, parameter):
  23. """Appends a parameter to this basic block."""
  24. result = self.create_definition(parameter)
  25. self.parameters.append(result)
  26. if len(self.definitions) > 0:
  27. self.renumber_definitions()
  28. return result
  29. def prepend_definition(self, value):
  30. """Defines the given value in this basic block."""
  31. result = self.create_definition(value)
  32. self.definitions.insert(0, result)
  33. self.renumber_definitions()
  34. return result
  35. def append_definition(self, value):
  36. """Defines the given value in this basic block."""
  37. result = self.create_definition(value)
  38. self.definitions.append(result)
  39. return result
  40. def create_definition(self, value=None):
  41. """Creates a definition, but does not assign it to this block yet."""
  42. if isinstance(value, Definition):
  43. return value
  44. else:
  45. assert isinstance(value, Value) or value is None
  46. return Definition(
  47. self.counter.next_value(),
  48. self,
  49. self.definition_counter.next_value(),
  50. value)
  51. def remove_definition(self, definition):
  52. """Removes the given definition from this basic block."""
  53. return self.definitions.remove(definition)
  54. def renumber_definitions(self):
  55. """Re-numbers all definitions in this basic block."""
  56. self.definition_counter = SharedCounter()
  57. for definition in self.parameters:
  58. definition.renumber(self.definition_counter.next_value())
  59. for definition in self.definitions:
  60. definition.renumber(self.definition_counter.next_value())
  61. def __str__(self):
  62. prefix = '!%d(%s):' % (self.index, ', '.join(map(str, self.parameters)))
  63. return '\n'.join(
  64. [prefix] +
  65. [' ' * 4 + str(item) for item in self.definitions + [self.flow]])
  66. class Definition(object):
  67. """Maps a value to a variable."""
  68. def __init__(self, index, block, definition_index, value):
  69. self.index = index
  70. self.block = block
  71. self.definition_index = definition_index
  72. self.value = value
  73. if value is not None:
  74. assert isinstance(value, Value)
  75. def redefine(self, new_value):
  76. """Tweaks this definition to take on the given new value."""
  77. self.value = new_value
  78. if new_value is not None:
  79. assert isinstance(new_value, Value)
  80. def renumber(self, new_definition_index):
  81. """Updates this definition's index in the block that defines it."""
  82. self.definition_index = new_definition_index
  83. def get_all_dependencies(self):
  84. """Gets all definitions and instructions on which this definition depends,
  85. along with any dependencies of instruction dependencies."""
  86. return self.value.get_all_dependencies()
  87. def has_side_effects(self):
  88. """Tests if this definition produces any side-effects."""
  89. return self.value.has_side_effects()
  90. def ref_str(self):
  91. """Gets a string that represents a reference to this definition."""
  92. return '$%d' % self.index
  93. def __str__(self):
  94. return '$%d = %s' % (self.index, str(self.value))
  95. class Instruction(object):
  96. """Represents an instruction."""
  97. def get_dependencies(self):
  98. """Gets all definitions and instructions on which this instruction depends."""
  99. raise NotImplementedError()
  100. def get_all_dependencies(self):
  101. """Gets all definitions and instructions on which this instruction depends,
  102. along with any dependencies of instruction dependencies."""
  103. results = list(self.get_dependencies())
  104. for item in results:
  105. results.extend(item.get_all_dependencies())
  106. return results
  107. class Branch(Instruction):
  108. """Represents a branch from one basic block to another."""
  109. def __init__(self, block, arguments=None):
  110. self.block = block
  111. assert isinstance(block, BasicBlock)
  112. if arguments is None:
  113. arguments = []
  114. self.arguments = arguments
  115. assert all([isinstance(arg, Definition) for arg in arguments])
  116. def get_dependencies(self):
  117. """Gets all definitions and instructions on which this instruction depends."""
  118. return self.arguments
  119. def __str__(self):
  120. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  121. class FlowInstruction(Instruction):
  122. """Represents a control flow instruction which terminates a basic block."""
  123. def branches(self):
  124. """Gets a list of basic blocks targeted by this flow instruction."""
  125. raise NotImplementedError()
  126. class JumpFlow(FlowInstruction):
  127. """Represents a control flow instruction which jumps directly to a basic block."""
  128. def __init__(self, branch):
  129. FlowInstruction.__init__(self)
  130. self.branch = branch
  131. assert isinstance(branch, Branch)
  132. def get_dependencies(self):
  133. """Gets all definitions and instructions on which this instruction depends."""
  134. return self.branches()
  135. def branches(self):
  136. """Gets a list of basic blocks targeted by this flow instruction."""
  137. return [self.branch]
  138. def __str__(self):
  139. return 'jump %s' % self.branch
  140. class SelectFlow(FlowInstruction):
  141. """Represents a control flow instruction which jumps to one of two basic blocks depending
  142. on whether a condition is truthy or not."""
  143. def __init__(self, condition, if_branch, else_branch):
  144. FlowInstruction.__init__(self)
  145. self.condition = condition
  146. assert isinstance(condition, Definition)
  147. self.if_branch = if_branch
  148. assert isinstance(if_branch, Branch)
  149. self.else_branch = else_branch
  150. assert isinstance(else_branch, Branch)
  151. def get_dependencies(self):
  152. """Gets all definitions and instructions on which this instruction depends."""
  153. return [self.condition] + self.branches()
  154. def branches(self):
  155. """Gets a list of basic blocks targeted by this flow instruction."""
  156. return [self.if_branch, self.else_branch]
  157. def __str__(self):
  158. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  159. class ReturnFlow(FlowInstruction):
  160. """Represents a control flow instruction which terminates the execution of the current
  161. function and returns a value."""
  162. def __init__(self, value):
  163. FlowInstruction.__init__(self)
  164. self.value = value
  165. assert isinstance(value, Definition)
  166. def get_dependencies(self):
  167. """Gets all definitions and instructions on which this instruction depends."""
  168. return [self.value]
  169. def branches(self):
  170. """Gets a list of basic blocks targeted by this flow instruction."""
  171. return []
  172. def __str__(self):
  173. return 'return %s' % self.value.ref_str()
  174. class ThrowFlow(FlowInstruction):
  175. """Represents a control flow instruction which throws an exception."""
  176. def __init__(self, exception):
  177. FlowInstruction.__init__(self)
  178. self.exception = exception
  179. assert isinstance(exception, Definition)
  180. def get_dependencies(self):
  181. """Gets all definitions and instructions on which this instruction depends."""
  182. return [self.exception]
  183. def branches(self):
  184. """Gets a list of basic blocks targeted by this flow instruction."""
  185. return []
  186. def __str__(self):
  187. return 'throw %s' % self.exception.ref_str()
  188. class UnreachableFlow(FlowInstruction):
  189. """Represents a control flow instruction which is unreachable."""
  190. def get_dependencies(self):
  191. """Gets all definitions and instructions on which this instruction depends."""
  192. return []
  193. def branches(self):
  194. """Gets a list of basic blocks targeted by this flow instruction."""
  195. return []
  196. def __str__(self):
  197. return 'unreachable'
  198. class Value(Instruction):
  199. """A value: an instruction that produces some result."""
  200. def get_dependencies(self):
  201. """Gets all definitions and instructions on which this instruction depends."""
  202. raise NotImplementedError()
  203. def has_value(self):
  204. """Tells if this value produces a result that is not None."""
  205. return True
  206. def has_side_effects(self):
  207. """Tells if this instruction has side-effects."""
  208. return False
  209. class BlockParameter(Value):
  210. """A basic block parameter."""
  211. def get_dependencies(self):
  212. """Gets all definitions and instructions on which this instruction depends."""
  213. return []
  214. def __str__(self):
  215. return 'block-parameter'
  216. class FunctionParameter(Value):
  217. """A function parameter."""
  218. def __init__(self, name):
  219. Value.__init__(self)
  220. self.name = name
  221. def get_dependencies(self):
  222. """Gets all definitions and instructions on which this instruction depends."""
  223. return []
  224. def __str__(self):
  225. return 'func-parameter %s' % self.name
  226. class Literal(Value):
  227. """A literal value."""
  228. def __init__(self, literal):
  229. Value.__init__(self)
  230. self.literal = literal
  231. def get_dependencies(self):
  232. """Gets all definitions and instructions on which this instruction depends."""
  233. return []
  234. def has_value(self):
  235. """Tells if this value produces a result that is not None."""
  236. return self.literal is not None
  237. def __str__(self):
  238. return 'literal %r' % self.literal
  239. class IndirectFunctionCall(Value):
  240. """A value that is the result of an indirect function call."""
  241. def __init__(self, target, argument_list):
  242. Value.__init__(self)
  243. assert isinstance(target, Definition)
  244. self.target = target
  245. assert all([isinstance(val, Definition) for _, val in argument_list])
  246. self.argument_list = argument_list
  247. def has_side_effects(self):
  248. """Tells if this instruction has side-effects."""
  249. return True
  250. def get_dependencies(self):
  251. """Gets all definitions and instructions on which this instruction depends."""
  252. return [self.target] + [val for _, val in self.argument_list]
  253. def __str__(self):
  254. return 'indirect-call %s(%s)' % (
  255. self.target.ref_str(),
  256. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  257. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  258. """The calling convention for functions that use 'return' statements to return.
  259. Arguments are matched to parameters based on position."""
  260. JIT_CALLING_CONVENTION = 'jit'
  261. """The calling convention for jitted functions."""
  262. class DirectFunctionCall(Value):
  263. """A value that is the result of a direct function call."""
  264. def __init__(self, target_name, argument_list, calling_convention=JIT_CALLING_CONVENTION):
  265. Value.__init__(self)
  266. self.target_name = target_name
  267. assert all([isinstance(val, Definition) for _, val in argument_list])
  268. self.argument_list = argument_list
  269. self.calling_convention = calling_convention
  270. def has_side_effects(self):
  271. """Tells if this instruction has side-effects."""
  272. return True
  273. def get_dependencies(self):
  274. """Gets all definitions and instructions on which this instruction depends."""
  275. return [val for _, val in self.argument_list]
  276. def __str__(self):
  277. return 'direct-call %r %s(%s)' % (
  278. self.calling_convention,
  279. self.target_name,
  280. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  281. class AllocateRootNode(Value):
  282. """A value that produces a new root node. Typically used in function prologs."""
  283. def __init__(self):
  284. Value.__init__(self)
  285. def get_dependencies(self):
  286. """Gets all definitions and instructions on which this instruction depends."""
  287. return []
  288. def __str__(self):
  289. return 'alloc-root-node'
  290. class DeallocateRootNode(Value):
  291. """A value that deallocates a root node. Typically used in function epilogs."""
  292. def __init__(self, root_node):
  293. Value.__init__(self)
  294. assert isinstance(root_node, Definition)
  295. self.root_node = root_node
  296. def get_dependencies(self):
  297. """Gets all definitions and instructions on which this instruction depends."""
  298. return []
  299. def __str__(self):
  300. return 'free-root-node %s' % self.root_node.ref_str()
  301. class DeclareLocal(Value):
  302. """A value that declares a local variable."""
  303. def __init__(self, variable, root_node):
  304. Value.__init__(self)
  305. self.variable = variable
  306. self.root_node = root_node
  307. def get_dependencies(self):
  308. """Gets all definitions and instructions on which this instruction depends."""
  309. return []
  310. def has_value(self):
  311. """Tells if this value produces a result that is not None."""
  312. return False
  313. def has_side_effects(self):
  314. """Tells if this instruction has side-effects."""
  315. return True
  316. def __str__(self):
  317. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  318. class DeclareGlobal(Value):
  319. """A value that declares a global variable."""
  320. def __init__(self, variable):
  321. Value.__init__(self)
  322. self.variable = variable
  323. def get_dependencies(self):
  324. """Gets all definitions and instructions on which this instruction depends."""
  325. return []
  326. def has_value(self):
  327. """Tells if this value produces a result that is not None."""
  328. return False
  329. def has_side_effects(self):
  330. """Tells if this instruction has side-effects."""
  331. return True
  332. def __str__(self):
  333. return 'declare-global %s' % self.variable.name
  334. class CheckLocalExists(Value):
  335. """A value that checks if a local value has been defined (yet)."""
  336. def __init__(self, variable):
  337. Value.__init__(self)
  338. self.variable = variable
  339. def get_dependencies(self):
  340. """Gets all definitions and instructions on which this instruction depends."""
  341. return []
  342. def __str__(self):
  343. return 'check-local-exists %s' % self.variable
  344. class ResolveLocal(Value):
  345. """A value that resolves a local as a pointer."""
  346. def __init__(self, variable):
  347. Value.__init__(self)
  348. self.variable = variable
  349. def get_dependencies(self):
  350. """Gets all definitions and instructions on which this instruction depends."""
  351. return []
  352. def __str__(self):
  353. return 'resolve-local %s' % self.variable
  354. class ResolveGlobal(Value):
  355. """A value that resolves a global as a pointer."""
  356. def __init__(self, variable):
  357. Value.__init__(self)
  358. self.variable = variable
  359. def get_dependencies(self):
  360. """Gets all definitions and instructions on which this instruction depends."""
  361. return []
  362. def __str__(self):
  363. return 'resolve-global %s' % self.variable.name
  364. class LoadPointer(Value):
  365. """A value that loads the value assigned to a pointer."""
  366. def __init__(self, pointer):
  367. Value.__init__(self)
  368. self.pointer = pointer
  369. assert isinstance(pointer, Definition)
  370. def get_dependencies(self):
  371. """Gets all definitions and instructions on which this instruction depends."""
  372. return [self.pointer]
  373. def __str__(self):
  374. return 'load %s' % self.pointer.ref_str()
  375. class StoreAtPointer(Value):
  376. """A value that assigns a value to a pointer."""
  377. def __init__(self, pointer, value):
  378. Value.__init__(self)
  379. self.pointer = pointer
  380. assert isinstance(pointer, Definition)
  381. self.value = value
  382. assert isinstance(value, Definition)
  383. def get_dependencies(self):
  384. """Gets all definitions and instructions on which this instruction depends."""
  385. return [self.pointer, self.value]
  386. def has_value(self):
  387. """Tells if this value produces a result that is not None."""
  388. return False
  389. def has_side_effects(self):
  390. """Tells if this instruction has side-effects."""
  391. return True
  392. def __str__(self):
  393. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  394. class Read(Value):
  395. """A value that reads the value stored in a node."""
  396. def __init__(self, node):
  397. Value.__init__(self)
  398. self.node = node
  399. assert isinstance(node, Definition)
  400. def get_dependencies(self):
  401. """Gets all definitions and instructions on which this instruction depends."""
  402. return [self.node]
  403. def __str__(self):
  404. return 'read %s' % (self.node.ref_str())
  405. class Input(Value):
  406. """A value that pops a node from the input queue."""
  407. def get_dependencies(self):
  408. """Gets all definitions and instructions on which this instruction depends."""
  409. return []
  410. def has_side_effects(self):
  411. """Tells if this instruction has side-effects."""
  412. return True
  413. def __str__(self):
  414. return 'input'
  415. class Output(Value):
  416. """A value that pushes a node onto the output queue."""
  417. def __init__(self, value):
  418. Value.__init__(self)
  419. self.value = value
  420. assert isinstance(value, Definition)
  421. def get_dependencies(self):
  422. """Gets all definitions and instructions on which this instruction depends."""
  423. return [self.value]
  424. def has_value(self):
  425. """Tells if this value produces a result that is not None."""
  426. return False
  427. def has_side_effects(self):
  428. """Tells if this instruction has side-effects."""
  429. return True
  430. def __str__(self):
  431. return 'output %s' % self.value.ref_str()
  432. class Binary(Value):
  433. """A value that applies a binary operator to two other values."""
  434. def __init__(self, lhs, operator, rhs):
  435. Value.__init__(self)
  436. self.lhs = lhs
  437. assert isinstance(lhs, Definition)
  438. self.operator = operator
  439. self.rhs = rhs
  440. assert isinstance(rhs, Definition)
  441. def get_dependencies(self):
  442. """Gets all definitions and instructions on which this instruction depends."""
  443. return [self.lhs, self.rhs]
  444. def __str__(self):
  445. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  446. def create_jump(block, arguments=None):
  447. """Creates a jump to the given block with the given argument list."""
  448. return JumpFlow(Branch(block, arguments))
  449. def apply_to_value(function, def_or_value):
  450. """Applies the given function to the specified value, or the underlying value of the
  451. given definition."""
  452. if isinstance(def_or_value, Definition):
  453. return apply_to_value(function, def_or_value.value)
  454. else:
  455. return function(def_or_value)
  456. def is_literal(value):
  457. """Tests if the given value is a literal."""
  458. return isinstance(value, Literal)
  459. def is_literal_def(def_or_value):
  460. """Tests if the given value is a literal or a definition with an underlying literal."""
  461. return apply_to_value(is_literal, def_or_value)
  462. def is_value_def(def_or_value, class_or_type_or_tuple=Value):
  463. """Tests if the given definition or value is a value of the given type."""
  464. if isinstance(def_or_value, Definition):
  465. return is_value_def(def_or_value.value, class_or_type_or_tuple)
  466. else:
  467. return isinstance(def_or_value, class_or_type_or_tuple)
  468. def get_def_variable(def_or_value):
  469. """Gets the 'variable' attribute of the given value, or the underlying value of the given
  470. definition, whichever is appropriate."""
  471. if isinstance(def_or_value, Definition):
  472. return get_def_variable(def_or_value.value)
  473. else:
  474. return def_or_value.variable
  475. def get_literal_value(value):
  476. """Gets the value of the given literal value."""
  477. return value.literal
  478. def get_literal_def_value(def_or_value):
  479. """Gets the value of the given literal value or definition with an underlying literal."""
  480. return apply_to_value(get_literal_value, def_or_value)