forked from tkoptimizer/Assembly-code-optimizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimize.py
213 lines (163 loc) · 5.43 KB
/
optimize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
File: optimize.py
Authors: Tim van Deurzen, Koos van Strien
Date: 26-02-2010
"""
import getopt
import sys
import os
from blockBuilder import *
from basicblock import *
from redundantLoadStore import *
from redundantLabels import *
from copyPropagation import *
from subExpressionElimination import *
from globalBranchOptimization import *
#
# A simple script that runs a set of optimization classes on a set of assembly
# files.
#
PARSE_FILE = True
PARSE_FOLDER = False
BE_VERBOSE = False
DEBUG = False
input_file = "foo.s"
input_folder = "./"
output_folder = "optimized/"
optimizations = []
optimizers = ({
'copy_propagation': copyPropagation(None),
'redundant_labels': redundantLabels(None),
'redundant_load_store': redundantLoadStore(None),
'common_subexpression': subExpressionElimination(None),
'global_branch_opt': globalBranchOptimization(None)
})
def main():
"""
Commandline parser using GNU getopt.
"""
global PARSE_FOLDER, PARSE_FILE, BE_VERBOSE, DEBUG, input_folder, \
input_file, output_folder, optimizations
try:
options, arguments = getopt.getopt(
sys.argv[1:], "f:i:o:vdx:",
[
"file=",
"input-folder=",
"output-folder=",
"--verbose",
"--debug",
"--execute-optimizations="
]
)
except getopt.GetoptError, error:
print str(error) + "\n"
usage()
sys.exit(2)
if len(sys.argv) < 2:
usage()
sys.exit(2)
for option, argument in options:
if option in ("-f", "--file"):
if PARSE_FOLDER:
raise Exception, "Can either parse a file or a folder not both!"
input_file = argument
elif option in ("-i", "--input-folder"):
PARSE_FILE = False
PARSE_FOLDER = True
input_folder = argument
elif option in ("-o", "--output-folder"):
output_folder = argument
elif option in ("-v", "--verbose"):
BE_VERBOSE = True
elif option in ("-d", "--debug"):
DEBUG = True
elif option in ("-x", "--execute-optimizations"):
optimizations = argument.split(",")
else:
assert False, "Unhandled option!"
optimize()
def optimize():
"""
Load the necessary files, instantiate each optimization class.
"""
global PARSE_FOLDER, input_folder, input_file
if PARSE_FOLDER:
for subdirectories, directories, files in os.walk(input_folder):
for file in files:
if BE_VERBOSE:
print "Optimizing: ", file
print "----------"
parseAndStore(blockBuilder(input_folder + "/" + file))
else:
if BE_VERBOSE:
print "Optimizing: ", input_file
print "----------"
parseAndStore(blockBuilder(input_folder + "/" + input_file))
def parseAndStore(blockHolder):
"""
Apply each optimizer and store the result in a file.
"""
global BE_VERBOSE, DEBUG, output_folder, optimizations, optimizers
blockHolder.analyze()
blockHolder.findBlockTargets()
blocks = blockHolder.basicBlocks
buffer = ""
output = []
# Execute each optimizer in the given order.
for optimization in optimizations:
optimizer = optimizers[optimization]
optimizer.setBlocks(blocks)
if BE_VERBOSE:
print "\tRunning optimization: ", optimizer.name
optimizer.analyseBlocks()
blocks = optimizer.getBlocks()
output.append(optimizer.getOutput())
for block in blocks:
if DEBUG:
buffer += "## basic block (" + block.interval() + ") ##\n"
for operation in block.operations:
if operation.included:
buffer += operation.code + "\n"
else:
if DEBUG:
buffer += "# " + operation.code + "\n"
filename = blockHolder.filename.split("/")
if len(filename) > 1:
filename = filename[-1]
else:
filename = filename[0]
if BE_VERBOSE:
print "----------\n"
print "Storing file: ", output_folder + "/" + filename
print "\n"
if DEBUG:
print "Debug: \n"
for lines in output:
for line in lines:
print line
FILE = open(output_folder + "/" + filename, 'w')
FILE.write(buffer)
def usage():
"""
Explains to the user how this script should be used.
"""
print "Usage:"
print "\t python " + sys.argv[0] + " [options]"
print "----------"
print "Options: \n"
print "\t-f (--file=) \t\t - Parse a single file."
print "\t-i (--input-folder=) \t - Parse an entire folder."
print "\t-o (--output-folder=) \t - Set a specific output folder."
print "\t-v (--verbose) \t\t - Be verbose while optimizing."
print "\t-d (--debug) \t\t - Add debug messages to the output assembly.\n"
print "\t-x (--execute-optimizations=): \n"
print "\t\t Select the optimizations that should be executed (in order),"
print "\t\t separated by ','."
print "\t\t possible optimizations:\n"
print "\t\t\tcopy_propagation"
print "\t\t\tredundant_labels"
print "\t\t\tredundant_load_store"
print "\t\t\tcommon_subexpression"
if __name__ == "__main__":
main()