cfg_ir.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 ref_str(self):
  84. """Gets a string that represents a reference to this definition."""
  85. return '$%d' % self.index
  86. def __str__(self):
  87. return '$%d = %s' % (self.index, str(self.value))
  88. class Instruction(object):
  89. """Represents an instruction."""
  90. def get_dependencies(self):
  91. """Gets all definitions and instructions on which this instruction depends."""
  92. raise NotImplementedError()
  93. def get_all_dependencies(self):
  94. """Gets all definitions and instructions on which this instruction depends,
  95. along with any dependencies of dependencies."""
  96. results = list(self.get_dependencies())
  97. for item in results:
  98. results.extend(item.get_all_dependencies())
  99. return results
  100. class Branch(Instruction):
  101. """Represents a branch from one basic block to another."""
  102. def __init__(self, block, arguments=None):
  103. self.block = block
  104. assert isinstance(block, BasicBlock)
  105. if arguments is None:
  106. arguments = []
  107. self.arguments = arguments
  108. assert all([isinstance(arg, Definition) for arg in arguments])
  109. def get_dependencies(self):
  110. """Gets all definitions and instructions on which this instruction depends."""
  111. return self.arguments
  112. def __str__(self):
  113. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  114. class FlowInstruction(Instruction):
  115. """Represents a control flow instruction which terminates a basic block."""
  116. def branches(self):
  117. """Gets a list of basic blocks targeted by this flow instruction."""
  118. raise NotImplementedError()
  119. class JumpFlow(FlowInstruction):
  120. """Represents a control flow instruction which jumps directly to a basic block."""
  121. def __init__(self, branch):
  122. FlowInstruction.__init__(self)
  123. self.branch = branch
  124. assert isinstance(branch, Branch)
  125. def get_dependencies(self):
  126. """Gets all definitions and instructions on which this instruction depends."""
  127. return self.branches()
  128. def branches(self):
  129. """Gets a list of basic blocks targeted by this flow instruction."""
  130. return [self.branch]
  131. def __str__(self):
  132. return 'jump %s' % self.branch
  133. class SelectFlow(FlowInstruction):
  134. """Represents a control flow instruction which jumps to one of two basic blocks depending
  135. on whether a condition is truthy or not."""
  136. def __init__(self, condition, if_branch, else_branch):
  137. FlowInstruction.__init__(self)
  138. self.condition = condition
  139. assert isinstance(condition, Definition)
  140. self.if_branch = if_branch
  141. assert isinstance(if_branch, Branch)
  142. self.else_branch = else_branch
  143. assert isinstance(else_branch, Branch)
  144. def get_dependencies(self):
  145. """Gets all definitions and instructions on which this instruction depends."""
  146. return [self.condition] + self.branches()
  147. def branches(self):
  148. """Gets a list of basic blocks targeted by this flow instruction."""
  149. return [self.if_branch, self.else_branch]
  150. def __str__(self):
  151. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  152. class ReturnFlow(FlowInstruction):
  153. """Represents a control flow instruction which terminates the execution of the current
  154. function and returns a value."""
  155. def __init__(self, value):
  156. FlowInstruction.__init__(self)
  157. self.value = value
  158. assert isinstance(value, Definition)
  159. def get_dependencies(self):
  160. """Gets all definitions and instructions on which this instruction depends."""
  161. return [self.value]
  162. def branches(self):
  163. """Gets a list of basic blocks targeted by this flow instruction."""
  164. return []
  165. def __str__(self):
  166. return 'return %s' % self.value.ref_str()
  167. class ThrowFlow(FlowInstruction):
  168. """Represents a control flow instruction which throws an exception."""
  169. def __init__(self, exception):
  170. FlowInstruction.__init__(self)
  171. self.exception = exception
  172. assert isinstance(exception, Definition)
  173. def get_dependencies(self):
  174. """Gets all definitions and instructions on which this instruction depends."""
  175. return [self.exception]
  176. def branches(self):
  177. """Gets a list of basic blocks targeted by this flow instruction."""
  178. return []
  179. def __str__(self):
  180. return 'throw %s' % self.exception.ref_str()
  181. class UnreachableFlow(FlowInstruction):
  182. """Represents a control flow instruction which is unreachable."""
  183. def get_dependencies(self):
  184. """Gets all definitions and instructions on which this instruction depends."""
  185. return []
  186. def branches(self):
  187. """Gets a list of basic blocks targeted by this flow instruction."""
  188. return []
  189. def __str__(self):
  190. return 'unreachable'
  191. class Value(Instruction):
  192. """A value: an instruction that produces some result."""
  193. def get_dependencies(self):
  194. """Gets all definitions and instructions on which this instruction depends."""
  195. raise NotImplementedError()
  196. def has_value(self):
  197. """Tells if this value produces a result that is not None."""
  198. return True
  199. def has_side_effects(self):
  200. """Tells if this instruction has side-effects."""
  201. return False
  202. class BlockParameter(Value):
  203. """A basic block parameter."""
  204. def get_dependencies(self):
  205. """Gets all definitions and instructions on which this instruction depends."""
  206. return []
  207. def __str__(self):
  208. return 'block-parameter'
  209. class FunctionParameter(Value):
  210. """A function parameter."""
  211. def __init__(self, name):
  212. Value.__init__(self)
  213. self.name = name
  214. def get_dependencies(self):
  215. """Gets all definitions and instructions on which this instruction depends."""
  216. return []
  217. def __str__(self):
  218. return 'func-parameter %s' % self.name
  219. class Literal(Value):
  220. """A literal value."""
  221. def __init__(self, literal):
  222. Value.__init__(self)
  223. self.literal = literal
  224. def get_dependencies(self):
  225. """Gets all definitions and instructions on which this instruction depends."""
  226. return []
  227. def has_value(self):
  228. """Tells if this value produces a result that is not None."""
  229. return self.literal is not None
  230. def __str__(self):
  231. return 'literal %r' % self.literal
  232. class IndirectFunctionCall(Value):
  233. """A value that is the result of an indirect function call."""
  234. def __init__(self, target, argument_list):
  235. Value.__init__(self)
  236. assert isinstance(target, Definition)
  237. self.target = target
  238. assert all([isinstance(val, Definition) for _, val in argument_list])
  239. self.argument_list = argument_list
  240. def has_side_effects(self):
  241. """Tells if this instruction has side-effects."""
  242. return True
  243. def get_dependencies(self):
  244. """Gets all definitions and instructions on which this instruction depends."""
  245. return [self.target] + [val for _, val in self.argument_list]
  246. def __str__(self):
  247. return 'indirect-call %s(%s)' % (
  248. self.target.ref_str(),
  249. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  250. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  251. """The calling convention for functions that use 'return' statements to return.
  252. Arguments are matched to parameters based on position."""
  253. JIT_CALLING_CONVENTION = 'jit'
  254. """The calling convention for jitted functions."""
  255. class DirectFunctionCall(Value):
  256. """A value that is the result of a direct function call."""
  257. def __init__(self, target_name, argument_list, calling_convention=JIT_CALLING_CONVENTION):
  258. Value.__init__(self)
  259. self.target_name = target_name
  260. assert all([isinstance(val, Definition) for _, val in argument_list])
  261. self.argument_list = argument_list
  262. self.calling_convention = calling_convention
  263. def has_side_effects(self):
  264. """Tells if this instruction has side-effects."""
  265. return True
  266. def get_dependencies(self):
  267. """Gets all definitions and instructions on which this instruction depends."""
  268. return [val for _, val in self.argument_list]
  269. def __str__(self):
  270. return 'direct-call %r %s(%s)' % (
  271. self.calling_convention,
  272. self.target_name,
  273. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  274. class AllocateRootNode(Value):
  275. """A value that produces a new root node. Typically used in function prologs."""
  276. def __init__(self):
  277. Value.__init__(self)
  278. def get_dependencies(self):
  279. """Gets all definitions and instructions on which this instruction depends."""
  280. return []
  281. def __str__(self):
  282. return 'alloc-root-node'
  283. class DeallocateRootNode(Value):
  284. """A value that deallocates a root node. Typically used in function epilogs."""
  285. def __init__(self, root_node):
  286. Value.__init__(self)
  287. assert isinstance(root_node, Definition)
  288. self.root_node = root_node
  289. def get_dependencies(self):
  290. """Gets all definitions and instructions on which this instruction depends."""
  291. return []
  292. def __str__(self):
  293. return 'free-root-node %s' % self.root_node.ref_str()
  294. class DeclareLocal(Value):
  295. """A value that declares a local variable."""
  296. def __init__(self, variable, root_node):
  297. Value.__init__(self)
  298. self.variable = variable
  299. self.root_node = root_node
  300. def get_dependencies(self):
  301. """Gets all definitions and instructions on which this instruction depends."""
  302. return []
  303. def has_value(self):
  304. """Tells if this value produces a result that is not None."""
  305. return False
  306. def has_side_effects(self):
  307. """Tells if this instruction has side-effects."""
  308. return True
  309. def __str__(self):
  310. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  311. class DeclareGlobal(Value):
  312. """A value that declares a global variable."""
  313. def __init__(self, variable):
  314. Value.__init__(self)
  315. self.variable = variable
  316. def get_dependencies(self):
  317. """Gets all definitions and instructions on which this instruction depends."""
  318. return []
  319. def has_value(self):
  320. """Tells if this value produces a result that is not None."""
  321. return False
  322. def has_side_effects(self):
  323. """Tells if this instruction has side-effects."""
  324. return True
  325. def __str__(self):
  326. return 'declare-global %s' % self.variable.name
  327. class CheckLocalExists(Value):
  328. """A value that checks if a local value has been defined (yet)."""
  329. def __init__(self, variable):
  330. Value.__init__(self)
  331. self.variable = variable
  332. def get_dependencies(self):
  333. """Gets all definitions and instructions on which this instruction depends."""
  334. return []
  335. def __str__(self):
  336. return 'check-local-exists %s' % self.variable
  337. class ResolveLocal(Value):
  338. """A value that resolves a local as a pointer."""
  339. def __init__(self, variable):
  340. Value.__init__(self)
  341. self.variable = variable
  342. def get_dependencies(self):
  343. """Gets all definitions and instructions on which this instruction depends."""
  344. return []
  345. def __str__(self):
  346. return 'resolve-local %s' % self.variable
  347. class ResolveGlobal(Value):
  348. """A value that resolves a global as a pointer."""
  349. def __init__(self, variable):
  350. Value.__init__(self)
  351. self.variable = variable
  352. def get_dependencies(self):
  353. """Gets all definitions and instructions on which this instruction depends."""
  354. return []
  355. def __str__(self):
  356. return 'resolve-global %s' % self.variable.name
  357. class LoadPointer(Value):
  358. """A value that loads the value assigned to a pointer."""
  359. def __init__(self, pointer):
  360. Value.__init__(self)
  361. self.pointer = pointer
  362. assert isinstance(pointer, Definition)
  363. def get_dependencies(self):
  364. """Gets all definitions and instructions on which this instruction depends."""
  365. return [self.pointer]
  366. def __str__(self):
  367. return 'load %s' % self.pointer.ref_str()
  368. class StoreAtPointer(Value):
  369. """A value that assigns a value to a pointer."""
  370. def __init__(self, pointer, value):
  371. Value.__init__(self)
  372. self.pointer = pointer
  373. assert isinstance(pointer, Definition)
  374. self.value = value
  375. assert isinstance(value, Definition)
  376. def get_dependencies(self):
  377. """Gets all definitions and instructions on which this instruction depends."""
  378. return [self.pointer, self.value]
  379. def has_value(self):
  380. """Tells if this value produces a result that is not None."""
  381. return False
  382. def has_side_effects(self):
  383. """Tells if this instruction has side-effects."""
  384. return True
  385. def __str__(self):
  386. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  387. class Read(Value):
  388. """A value that reads the value stored in a node."""
  389. def __init__(self, node):
  390. Value.__init__(self)
  391. self.node = node
  392. assert isinstance(node, Definition)
  393. def get_dependencies(self):
  394. """Gets all definitions and instructions on which this instruction depends."""
  395. return [self.node]
  396. def __str__(self):
  397. return 'read %s' % (self.node.ref_str())
  398. class Input(Value):
  399. """A value that pops a node from the input queue."""
  400. def get_dependencies(self):
  401. """Gets all definitions and instructions on which this instruction depends."""
  402. return []
  403. def has_side_effects(self):
  404. """Tells if this instruction has side-effects."""
  405. return True
  406. def __str__(self):
  407. return 'input'
  408. class Output(Value):
  409. """A value that pushes a node onto the output queue."""
  410. def __init__(self, value):
  411. Value.__init__(self)
  412. self.value = value
  413. assert isinstance(value, Definition)
  414. def get_dependencies(self):
  415. """Gets all definitions and instructions on which this instruction depends."""
  416. return [self.value]
  417. def has_value(self):
  418. """Tells if this value produces a result that is not None."""
  419. return False
  420. def has_side_effects(self):
  421. """Tells if this instruction has side-effects."""
  422. return True
  423. def __str__(self):
  424. return 'output %s' % self.value.ref_str()
  425. class Binary(Value):
  426. """A value that applies a binary operator to two other values."""
  427. def __init__(self, lhs, operator, rhs):
  428. Value.__init__(self)
  429. self.lhs = lhs
  430. assert isinstance(lhs, Definition)
  431. self.operator = operator
  432. self.rhs = rhs
  433. assert isinstance(rhs, Definition)
  434. def get_dependencies(self):
  435. """Gets all definitions and instructions on which this instruction depends."""
  436. return [self.lhs, self.rhs]
  437. def __str__(self):
  438. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  439. def create_jump(block, arguments=None):
  440. """Creates a jump to the given block with the given argument list."""
  441. return JumpFlow(Branch(block, arguments))
  442. def apply_to_value(function, def_or_value):
  443. """Applies the given function to the specified value, or the underlying value of the
  444. given definition."""
  445. if isinstance(def_or_value, Definition):
  446. return apply_to_value(function, def_or_value.value)
  447. else:
  448. return function(def_or_value)
  449. def is_literal(value):
  450. """Tests if the given value is a literal."""
  451. return isinstance(value, Literal)
  452. def is_literal_def(def_or_value):
  453. """Tests if the given value is a literal or a definition with an underlying literal."""
  454. return apply_to_value(is_literal, def_or_value)
  455. def get_literal_value(value):
  456. """Gets the value of the given literal value."""
  457. return value.literal
  458. def get_literal_def_value(def_or_value):
  459. """Gets the value of the given literal value or definition with an underlying literal."""
  460. return apply_to_value(get_literal_value, def_or_value)