cfg_ir.py 22 KB

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