cfg_ir.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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.flow = UnreachableFlow()
  21. def append_parameter(self, parameter):
  22. """Appends a parameter to this basic block."""
  23. assert isinstance(parameter, BlockParameter)
  24. result = Definition(self.counter.next_value(), parameter)
  25. self.parameters.append(result)
  26. return result
  27. def prepend_definition(self, value):
  28. """Defines the given value in this basic block."""
  29. result = self.create_definition(value)
  30. self.definitions.insert(0, result)
  31. return result
  32. def append_definition(self, value):
  33. """Defines the given value in this basic block."""
  34. result = self.create_definition(value)
  35. self.definitions.append(result)
  36. return result
  37. def create_definition(self, value=None):
  38. """Creates a definition, but does not assign it to this block yet."""
  39. if isinstance(value, Definition):
  40. return value
  41. else:
  42. assert isinstance(value, Value) or value is None
  43. return Definition(self.counter.next_value(), value)
  44. def remove_definition(self, definition):
  45. """Removes the given definition from this basic block."""
  46. return self.definitions.remove(definition)
  47. def __str__(self):
  48. prefix = '!%d(%s):' % (self.index, ', '.join(map(str, self.parameters)))
  49. return '\n'.join(
  50. [prefix] +
  51. [' ' * 4 + str(item) for item in self.definitions + [self.flow]])
  52. class Definition(object):
  53. """Maps a value to a variable."""
  54. def __init__(self, index, value):
  55. self.index = index
  56. self.value = value
  57. if value is not None:
  58. assert isinstance(value, Value)
  59. def redefine(self, new_value):
  60. """Tweaks this definition to take on the given new value."""
  61. self.value = new_value
  62. if new_value is not None:
  63. assert isinstance(new_value, Value)
  64. def ref_str(self):
  65. """Gets a string that represents a reference to this definition."""
  66. return '$%d' % self.index
  67. def __str__(self):
  68. return '$%d = %s' % (self.index, str(self.value))
  69. class Instruction(object):
  70. """Represents an instruction."""
  71. def get_dependencies(self):
  72. """Gets all definitions and instructions on which this instruction depends."""
  73. raise NotImplementedError()
  74. def get_all_dependencies(self):
  75. """Gets all definitions and instructions on which this instruction depends,
  76. along with any dependencies of dependencies."""
  77. results = list(self.get_dependencies())
  78. for item in results:
  79. results.extend(item.get_all_dependencies())
  80. return results
  81. class Branch(Instruction):
  82. """Represents a branch from one basic block to another."""
  83. def __init__(self, block, arguments=None):
  84. self.block = block
  85. assert isinstance(block, BasicBlock)
  86. if arguments is None:
  87. arguments = []
  88. self.arguments = arguments
  89. assert all([isinstance(arg, Definition) for arg in arguments])
  90. def get_dependencies(self):
  91. """Gets all definitions and instructions on which this instruction depends."""
  92. return self.arguments
  93. def __str__(self):
  94. return '!%d(%s)' % (self.block.index, ', '.join(map(str, self.arguments)))
  95. class FlowInstruction(Instruction):
  96. """Represents a control flow instruction which terminates a basic block."""
  97. def branches(self):
  98. """Gets a list of basic blocks targeted by this flow instruction."""
  99. raise NotImplementedError()
  100. class JumpFlow(FlowInstruction):
  101. """Represents a control flow instruction which jumps directly to a basic block."""
  102. def __init__(self, branch):
  103. FlowInstruction.__init__(self)
  104. self.branch = branch
  105. assert isinstance(branch, Branch)
  106. def get_dependencies(self):
  107. """Gets all definitions and instructions on which this instruction depends."""
  108. return self.branches()
  109. def branches(self):
  110. """Gets a list of basic blocks targeted by this flow instruction."""
  111. return [self.branch]
  112. def __str__(self):
  113. return 'jump %s' % self.branch
  114. class SelectFlow(FlowInstruction):
  115. """Represents a control flow instruction which jumps to one of two basic blocks depending
  116. on whether a condition is truthy or not."""
  117. def __init__(self, condition, if_branch, else_branch):
  118. FlowInstruction.__init__(self)
  119. self.condition = condition
  120. assert isinstance(condition, Definition)
  121. self.if_branch = if_branch
  122. assert isinstance(if_branch, Branch)
  123. self.else_branch = else_branch
  124. assert isinstance(else_branch, Branch)
  125. def get_dependencies(self):
  126. """Gets all definitions and instructions on which this instruction depends."""
  127. return [self.condition] + self.branches()
  128. def branches(self):
  129. """Gets a list of basic blocks targeted by this flow instruction."""
  130. return [self.if_branch, self.else_branch]
  131. def __str__(self):
  132. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  133. class ReturnFlow(FlowInstruction):
  134. """Represents a control flow instruction which terminates the execution of the current
  135. function and returns a value."""
  136. def __init__(self, value):
  137. FlowInstruction.__init__(self)
  138. self.value = value
  139. assert isinstance(value, Value)
  140. def get_dependencies(self):
  141. """Gets all definitions and instructions on which this instruction depends."""
  142. return [self.value]
  143. def branches(self):
  144. """Gets a list of basic blocks targeted by this flow instruction."""
  145. return []
  146. def __str__(self):
  147. return 'return %s' % self.value.ref_str()
  148. class UnreachableFlow(FlowInstruction):
  149. """Represents a control flow instruction which is unreachable."""
  150. def get_dependencies(self):
  151. """Gets all definitions and instructions on which this instruction depends."""
  152. return []
  153. def branches(self):
  154. """Gets a list of basic blocks targeted by this flow instruction."""
  155. return []
  156. def __str__(self):
  157. return 'unreachable'
  158. class Value(Instruction):
  159. """A value: an instruction that produces some result."""
  160. def get_dependencies(self):
  161. """Gets all definitions and instructions on which this instruction depends."""
  162. raise NotImplementedError()
  163. def has_value(self):
  164. """Tells if this value produces a result that is not None."""
  165. return True
  166. def has_side_effects(self):
  167. """Tells if this instruction has side-effects."""
  168. return False
  169. class BlockParameter(Value):
  170. """A basic block parameter."""
  171. def get_dependencies(self):
  172. """Gets all definitions and instructions on which this instruction depends."""
  173. return []
  174. def __str__(self):
  175. return 'block-parameter'
  176. class FunctionParameter(Value):
  177. """A function parameter."""
  178. def __init__(self, name):
  179. Value.__init__(self)
  180. self.name = name
  181. def get_dependencies(self):
  182. """Gets all definitions and instructions on which this instruction depends."""
  183. return []
  184. def __str__(self):
  185. return 'func-parameter %s' % self.name
  186. class Literal(Value):
  187. """A literal value."""
  188. def __init__(self, literal):
  189. Value.__init__(self)
  190. self.literal = literal
  191. def get_dependencies(self):
  192. """Gets all definitions and instructions on which this instruction depends."""
  193. return []
  194. def has_value(self):
  195. """Tells if this value produces a result that is not None."""
  196. return self.literal is not None
  197. def __str__(self):
  198. return 'literal %r' % self.literal
  199. class JitFunctionCall(Value):
  200. """A value that is the result of a function call."""
  201. def __init__(self, target, argument_list):
  202. Value.__init__(self)
  203. assert isinstance(target, Definition)
  204. self.target = target
  205. assert all([isinstance(val, Definition) for val in argument_list])
  206. self.argument_list = argument_list
  207. def has_side_effects(self):
  208. """Tells if this instruction has side-effects."""
  209. return True
  210. def get_dependencies(self):
  211. """Gets all definitions and instructions on which this instruction depends."""
  212. return [self.target] + [val for _, val in self.argument_list]
  213. def __str__(self):
  214. return 'call %s(%s)' % (
  215. self.target.ref_str(),
  216. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  217. class DeclareLocal(Value):
  218. """A value that declares a local variable."""
  219. def __init__(self, variable):
  220. Value.__init__(self)
  221. self.variable = variable
  222. def get_dependencies(self):
  223. """Gets all definitions and instructions on which this instruction depends."""
  224. return []
  225. def has_value(self):
  226. """Tells if this value produces a result that is not None."""
  227. return False
  228. def has_side_effects(self):
  229. """Tells if this instruction has side-effects."""
  230. return True
  231. def __str__(self):
  232. return 'declare-local %d' % self.variable.node_id
  233. class DeclareGlobal(Value):
  234. """A value that declares a global variable."""
  235. def __init__(self, variable):
  236. Value.__init__(self)
  237. self.variable = variable
  238. def get_dependencies(self):
  239. """Gets all definitions and instructions on which this instruction depends."""
  240. return []
  241. def has_value(self):
  242. """Tells if this value produces a result that is not None."""
  243. return False
  244. def has_side_effects(self):
  245. """Tells if this instruction has side-effects."""
  246. return True
  247. def __str__(self):
  248. return 'declare-global %s' % self.variable.name
  249. class CheckLocalExists(Value):
  250. """A value that checks if a local value has been defined (yet)."""
  251. def __init__(self, variable):
  252. Value.__init__(self)
  253. self.variable = variable
  254. def get_dependencies(self):
  255. """Gets all definitions and instructions on which this instruction depends."""
  256. return []
  257. def __str__(self):
  258. return 'check-local-exists %d' % self.variable.node_id
  259. class ResolveLocal(Value):
  260. """A value that resolves a local as a pointer."""
  261. def __init__(self, variable):
  262. Value.__init__(self)
  263. self.variable = variable
  264. def get_dependencies(self):
  265. """Gets all definitions and instructions on which this instruction depends."""
  266. return []
  267. def __str__(self):
  268. return 'resolve-local %d' % self.variable.node_id
  269. class ResolveGlobal(Value):
  270. """A value that resolves a global as a pointer."""
  271. def __init__(self, variable):
  272. Value.__init__(self)
  273. self.variable = variable
  274. def get_dependencies(self):
  275. """Gets all definitions and instructions on which this instruction depends."""
  276. return []
  277. def __str__(self):
  278. return 'resolve-global %s' % self.variable.name
  279. class LoadPointer(Value):
  280. """A value that loads the value assigned to a pointer."""
  281. def __init__(self, pointer):
  282. Value.__init__(self)
  283. self.pointer = pointer
  284. assert isinstance(pointer, Definition)
  285. def get_dependencies(self):
  286. """Gets all definitions and instructions on which this instruction depends."""
  287. return [self.pointer]
  288. def __str__(self):
  289. return 'load %s' % self.pointer.ref_str()
  290. class StoreAtPointer(Value):
  291. """A value that assigns a value to a pointer."""
  292. def __init__(self, pointer, value):
  293. Value.__init__(self)
  294. self.pointer = pointer
  295. assert isinstance(pointer, Definition)
  296. self.value = value
  297. assert isinstance(value, Definition)
  298. def get_dependencies(self):
  299. """Gets all definitions and instructions on which this instruction depends."""
  300. return [self.pointer, self.value]
  301. def has_value(self):
  302. """Tells if this value produces a result that is not None."""
  303. return False
  304. def has_side_effects(self):
  305. """Tells if this instruction has side-effects."""
  306. return True
  307. def __str__(self):
  308. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  309. class Input(Value):
  310. """A value that pops a node from the input queue."""
  311. def get_dependencies(self):
  312. """Gets all definitions and instructions on which this instruction depends."""
  313. return []
  314. def has_side_effects(self):
  315. """Tells if this instruction has side-effects."""
  316. return True
  317. def __str__(self):
  318. return 'input'
  319. class Output(Value):
  320. """A value that pushes a node onto the output queue."""
  321. def __init__(self, value):
  322. Value.__init__(self)
  323. self.value = value
  324. assert isinstance(value, Definition)
  325. def get_dependencies(self):
  326. """Gets all definitions and instructions on which this instruction depends."""
  327. return [self.value]
  328. def has_value(self):
  329. """Tells if this value produces a result that is not None."""
  330. return False
  331. def has_side_effects(self):
  332. """Tells if this instruction has side-effects."""
  333. return True
  334. def __str__(self):
  335. return 'output %s' % self.value.ref_str()
  336. def create_jump(block, arguments=None):
  337. """Creates a jump to the given block with the given argument list."""
  338. return JumpFlow(Branch(block, arguments))