__init__.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. from src.dataflow import find_basic_blocks
  2. from standard import redundant_move_1, redundant_move_2, \
  3. redundant_move_3, redundant_move_4, redundant_load, \
  4. redundant_shift, redundant_add
  5. from advanced import eliminate_common_subexpressions, fold_constants
  6. def optimize_global(statements):
  7. """Optimize statement sequences on a global level."""
  8. old_len = -1
  9. while old_len != len(statements):
  10. old_len = len(statements)
  11. while not statements.end():
  12. s = statements.read()
  13. # beq/bne ..., $Lx -> bne/beq ..., $Ly
  14. # j $Ly $Lx:
  15. # $Lx:
  16. if s.is_command('beq', 'bne'):
  17. following = statements.peek(2)
  18. if len(following) == 2:
  19. j, label = following
  20. if j.is_command('j') and label.is_label(s[2]):
  21. s.name = 'bne' if s.is_command('beq') else 'beq'
  22. s[2] = j[0]
  23. statements.replace(3, [s, label])
  24. def optimize_block(block):
  25. """Optimize a basic block."""
  26. standard = [redundant_move_1, redundant_move_2, redundant_move_3, \
  27. redundant_move_4, redundant_load, redundant_shift, \
  28. redundant_add]
  29. old_len = -1
  30. # Standard optimizations
  31. while old_len != len(block):
  32. old_len = len(block)
  33. while not block.end():
  34. s = block.read()
  35. for callback in standard:
  36. if callback(s, block):
  37. break
  38. # Advanced optimizations
  39. #changed = True
  40. #while changed:
  41. # changed = eliminate_common_subexpressions(block) \
  42. # or fold_constants(block)
  43. while eliminate_common_subexpressions(block) \
  44. | fold_constants(block):
  45. pass
  46. def optimize(statements, verbose=0):
  47. """optimization wrapper function, calls global and basic-block level
  48. optimization functions."""
  49. # Optimize on a global level
  50. o = len(statements)
  51. optimize_global(statements)
  52. g = len(statements)
  53. # Optimize basic blocks
  54. blocks = find_basic_blocks(statements)
  55. map(optimize_block, blocks)
  56. block_statements = map(lambda b: b.statements, blocks)
  57. opt_blocks = reduce(lambda a, b: a + b, block_statements)
  58. b = len(opt_blocks)
  59. # - Common subexpression elimination
  60. # - Constant folding
  61. # - Copy propagation
  62. # - Dead-code elimination
  63. # - Temporary variable renaming
  64. # - Interchange of independent statements
  65. if verbose:
  66. print 'Original statements: %d' % o
  67. print 'After global optimization: %d' % g
  68. print 'After basic blocks optimization: %d' % b
  69. print 'Optimization: %d (%d%%)' \
  70. % (b - o, int((b - o) / float(o) * 100))
  71. return opt_blocks