Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/tools/js_optimizer.py
6162 views
1
#!/usr/bin/env python3
2
# Copyright 2012 The Emscripten Authors. All rights reserved.
3
# Emscripten is available under two separate licenses, the MIT license and the
4
# University of Illinois/NCSA Open Source License. Both these licenses can be
5
# found in the LICENSE file.
6
7
import json
8
import os
9
import re
10
import shutil
11
import subprocess
12
import sys
13
14
__scriptdir__ = os.path.dirname(os.path.abspath(__file__))
15
__rootdir__ = os.path.dirname(__scriptdir__)
16
sys.path.insert(0, __rootdir__)
17
18
from tools import building, config, shared, utils
19
from tools.toolchain_profiler import ToolchainProfiler
20
from tools.utils import path_from_root
21
22
temp_files = shared.get_temp_files()
23
24
25
ACORN_OPTIMIZER = path_from_root('tools/acorn-optimizer.mjs')
26
27
NUM_CHUNKS_PER_CORE = 3
28
MIN_CHUNK_SIZE = int(os.environ.get('EMCC_JSOPT_MIN_CHUNK_SIZE') or 512 * 1024) # configuring this is just for debugging purposes
29
MAX_CHUNK_SIZE = int(os.environ.get('EMCC_JSOPT_MAX_CHUNK_SIZE') or 5 * 1024 * 1024)
30
31
WINDOWS = sys.platform.startswith('win')
32
33
DEBUG = os.environ.get('EMCC_DEBUG')
34
35
func_sig = re.compile(r'function ([_\w$]+)\(')
36
func_sig_json = re.compile(r'\["defun", ?"([_\w$]+)",')
37
38
39
def get_acorn_cmd():
40
node = config.NODE_JS
41
if not any('--stack-size' in arg for arg in node):
42
# Use an 8Mb stack (rather than the ~1Mb default) when running the
43
# js optimizer since larger inputs can cause terser to use a lot of stack.
44
node.append('--stack-size=8192')
45
return node + [ACORN_OPTIMIZER]
46
47
48
def split_funcs(js):
49
# split properly even if there are no newlines,
50
# which is important for deterministic builds (as which functions
51
# are in each chunk may differ, so we need to split them up and combine
52
# them all together later and sort them deterministically)
53
parts = ['function ' + part for part in js.split('function ')[1:]]
54
funcs = []
55
for func in parts:
56
m = func_sig.search(func)
57
if not m:
58
continue
59
ident = m.group(1)
60
assert ident
61
funcs.append((ident, func))
62
return funcs
63
64
65
class Minifier:
66
"""minification support. We calculate minification of
67
globals here, then pass that into the parallel acorn-optimizer.mjs runners which
68
perform minification of locals.
69
"""
70
71
def __init__(self, js):
72
self.js = js
73
self.symbols_file = None
74
self.profiling_funcs = False
75
76
def minify_shell(self, shell, minify_whitespace):
77
# Run through acorn-optimizer.mjs to find and minify the global symbols
78
# We send it the globals, which it parses at the proper time. JS decides how
79
# to minify all global names, we receive a dictionary back, which is then
80
# used by the function processors
81
82
shell = shell.replace('0.0', '13371337') # avoid optimizer doing 0.0 => 0
83
84
# Find all globals in the JS functions code
85
86
if not self.profiling_funcs:
87
self.globs = [m.group(1) for m in func_sig.finditer(self.js)]
88
if len(self.globs) == 0:
89
self.globs = [m.group(1) for m in func_sig_json.finditer(self.js)]
90
else:
91
self.globs = []
92
93
with temp_files.get_file('.minifyglobals.js') as temp_file:
94
with open(temp_file, 'w') as f:
95
f.write(shell)
96
f.write('\n')
97
f.write('// EXTRA_INFO:' + json.dumps(self.serialize()))
98
99
cmd = get_acorn_cmd() + [temp_file, 'minifyGlobals']
100
if minify_whitespace:
101
cmd.append('--minify-whitespace')
102
output = utils.run_process(cmd, stdout=subprocess.PIPE).stdout
103
104
assert len(output) and not output.startswith('Assertion failed'), 'Error in js optimizer: ' + output
105
code, metadata = output.split('// EXTRA_INFO:')
106
self.globs = json.loads(metadata)
107
108
if self.symbols_file:
109
mapping = '\n'.join(f'{value}:{key}' for key, value in self.globs.items())
110
utils.write_file(self.symbols_file, mapping + '\n')
111
print('wrote symbol map file to', self.symbols_file, file=sys.stderr)
112
113
return code.replace('13371337', '0.0')
114
115
def serialize(self):
116
return {
117
'globals': self.globs,
118
}
119
120
121
start_funcs_marker = '// EMSCRIPTEN_START_FUNCS\n'
122
end_funcs_marker = '// EMSCRIPTEN_END_FUNCS\n'
123
start_asm_marker = '// EMSCRIPTEN_START_ASM\n'
124
end_asm_marker = '// EMSCRIPTEN_END_ASM\n'
125
126
127
# Given a set of functions of form (ident, text), and a preferred chunk size,
128
# generates a set of chunks for parallel processing and caching.
129
@ToolchainProfiler.profile()
130
def chunkify(funcs, chunk_size):
131
chunks = []
132
# initialize reasonably, the rest of the funcs we need to split out
133
curr = []
134
total_size = 0
135
for func in funcs:
136
curr_size = len(func[1])
137
if total_size + curr_size < chunk_size:
138
curr.append(func)
139
total_size += curr_size
140
else:
141
chunks.append(curr)
142
curr = [func]
143
total_size = curr_size
144
if curr:
145
chunks.append(curr)
146
curr = None
147
return [''.join(func[1] for func in chunk) for chunk in chunks] # remove function names
148
149
150
@ToolchainProfiler.profile_block('js_optimizer.run_on_file')
151
def run_on_file(filename, passes, extra_info=None):
152
with ToolchainProfiler.profile_block('js_optimizer.split_markers'):
153
if not isinstance(passes, list):
154
passes = [passes]
155
156
js = utils.read_file(filename)
157
if os.linesep != '\n':
158
js = js.replace(os.linesep, '\n') # we assume \n in the splitting code
159
160
# Find markers
161
start_funcs = js.find(start_funcs_marker)
162
end_funcs = js.rfind(end_funcs_marker)
163
164
if start_funcs < 0 or end_funcs < start_funcs:
165
utils.exit_with_error('invalid input file. Did not contain appropriate markers. (start_funcs: %s, end_funcs: %s' % (start_funcs, end_funcs))
166
167
minify_globals = 'minifyNames' in passes
168
if minify_globals:
169
passes = [p if p != 'minifyNames' else 'minifyLocals' for p in passes]
170
start_asm = js.find(start_asm_marker)
171
end_asm = js.rfind(end_asm_marker)
172
assert (start_asm >= 0) == (end_asm >= 0)
173
174
closure = 'closure' in passes
175
if closure:
176
passes = [p for p in passes if p != 'closure'] # we will do it manually
177
178
cleanup = 'cleanup' in passes
179
if cleanup:
180
passes = [p for p in passes if p != 'cleanup'] # we will do it manually
181
182
if not minify_globals:
183
with ToolchainProfiler.profile_block('js_optimizer.no_minify_globals'):
184
pre = js[:start_funcs + len(start_funcs_marker)]
185
post = js[end_funcs + len(end_funcs_marker):]
186
js = js[start_funcs + len(start_funcs_marker):end_funcs]
187
# can have Module[..] and inlining prevention code, push those to post
188
finals = []
189
190
def process(line):
191
if line and (line.startswith(('Module[', 'if (globalScope)')) or line.endswith('["X"]=1;')):
192
finals.append(line)
193
return False
194
return True
195
196
js = '\n'.join(line for line in js.split('\n') if process(line))
197
post = '\n'.join(finals) + '\n' + post
198
post = end_funcs_marker + post
199
else:
200
with ToolchainProfiler.profile_block('js_optimizer.minify_globals'):
201
# We need to split out the asm shell as well, for minification
202
pre = js[:start_asm + len(start_asm_marker)]
203
post = js[end_asm:]
204
asm_shell = js[start_asm + len(start_asm_marker):start_funcs + len(start_funcs_marker)] + '''
205
EMSCRIPTEN_FUNCS();
206
''' + js[end_funcs + len(end_funcs_marker):end_asm + len(end_asm_marker)]
207
js = js[start_funcs + len(start_funcs_marker):end_funcs]
208
209
# we assume there is a maximum of one new name per line
210
minifier = Minifier(js)
211
212
def check_symbol_mapping(p):
213
if p.startswith('symbolMap='):
214
minifier.symbols_file = p.split('=', 1)[1]
215
return False
216
if p == 'profilingFuncs':
217
minifier.profiling_funcs = True
218
return False
219
return True
220
221
passes = [p for p in passes if check_symbol_mapping(p)]
222
asm_shell_pre, asm_shell_post = minifier.minify_shell(asm_shell, '--minify-whitespace' in passes).split('EMSCRIPTEN_FUNCS();')
223
asm_shell_post = asm_shell_post.replace('});', '})')
224
pre += asm_shell_pre + '\n' + start_funcs_marker
225
post = end_funcs_marker + asm_shell_post + post
226
227
minify_info = minifier.serialize()
228
229
if extra_info:
230
for key, value in extra_info.items():
231
assert key not in minify_info or value == minify_info[key], [key, value, minify_info[key]]
232
minify_info[key] = value
233
234
# if DEBUG:
235
# print >> sys.stderr, 'minify info:', minify_info
236
237
with ToolchainProfiler.profile_block('js_optimizer.split'):
238
total_size = len(js)
239
funcs = split_funcs(js)
240
js = None
241
242
with ToolchainProfiler.profile_block('js_optimizer.split_to_chunks'):
243
# if we are making source maps, we want our debug numbering to start from the
244
# top of the file, so avoid breaking the JS into chunks
245
246
intended_num_chunks = round(utils.get_num_cores() * NUM_CHUNKS_PER_CORE)
247
chunk_size = min(MAX_CHUNK_SIZE, max(MIN_CHUNK_SIZE, total_size / intended_num_chunks))
248
chunks = chunkify(funcs, chunk_size)
249
250
chunks = [chunk for chunk in chunks if chunk]
251
if DEBUG:
252
lengths = [len(c) for c in chunks]
253
if not lengths:
254
lengths = [0]
255
print('chunkification: num funcs:', len(funcs), 'actual num chunks:', len(chunks), 'chunk size range:', max(lengths), '-', min(lengths), file=sys.stderr)
256
funcs = None
257
258
serialized_extra_info = ''
259
if minify_globals:
260
assert not extra_info
261
serialized_extra_info += '// EXTRA_INFO:' + json.dumps(minify_info)
262
elif extra_info:
263
serialized_extra_info += '// EXTRA_INFO:' + json.dumps(extra_info)
264
with ToolchainProfiler.profile_block('js_optimizer.write_chunks'):
265
def write_chunk(chunk, i):
266
temp_file = temp_files.get('.jsfunc_%d.js' % i).name
267
utils.write_file(temp_file, chunk + serialized_extra_info)
268
return temp_file
269
filenames = [write_chunk(chunk, i) for i, chunk in enumerate(chunks)]
270
271
with ToolchainProfiler.profile_block('run_optimizer'):
272
commands = [get_acorn_cmd() + [f] + passes for f in filenames]
273
filenames = shared.run_multiple_processes(commands, route_stdout_to_temp_files_suffix='js_opt.jo.js')
274
275
with ToolchainProfiler.profile_block('split_closure_cleanup'):
276
if closure or cleanup:
277
# run on the shell code, everything but what we acorn-optimize
278
start_asm = '// EMSCRIPTEN_START_ASM\n'
279
end_asm = '// EMSCRIPTEN_END_ASM\n'
280
cl_sep = 'wakaUnknownBefore(); var asm=wakaUnknownAfter(wakaGlobal,wakaEnv,wakaBuffer)\n'
281
282
with temp_files.get_file('.cl.js') as cle:
283
pre_1, pre_2 = pre.split(start_asm)
284
post_1, post_2 = post.split(end_asm)
285
with open(cle, 'w') as f:
286
f.write(pre_1)
287
f.write(cl_sep)
288
f.write(post_2)
289
cld = cle
290
if closure:
291
if DEBUG:
292
print('running closure on shell code', file=sys.stderr)
293
cld = building.closure_compiler(cld, pretty='--minify-whitespace' not in passes)
294
temp_files.note(cld)
295
elif cleanup:
296
if DEBUG:
297
print('running cleanup on shell code', file=sys.stderr)
298
acorn_passes = ['JSDCE']
299
if '--minify-whitespace' in passes:
300
acorn_passes.append('--minify-whitespace')
301
cld = building.acorn_optimizer(cld, acorn_passes)
302
temp_files.note(cld)
303
coutput = utils.read_file(cld)
304
305
coutput = coutput.replace('wakaUnknownBefore();', start_asm)
306
after = 'wakaUnknownAfter'
307
start = coutput.find(after)
308
end = coutput.find(')', start)
309
# If the closure comment to suppress useless code is present, we need to look one
310
# brace past it, as the first is in there. Otherwise, the first brace is the
311
# start of the function body (what we want).
312
USELESS_CODE_COMMENT = '/** @suppress {uselessCode} */ '
313
USELESS_CODE_COMMENT_BODY = 'uselessCode'
314
brace = pre_2.find('{') + 1
315
has_useless_code_comment = False
316
if pre_2[brace:brace + len(USELESS_CODE_COMMENT_BODY)] == USELESS_CODE_COMMENT_BODY:
317
brace = pre_2.find('{', brace) + 1
318
has_useless_code_comment = True
319
pre = coutput[:start] + '(' + (USELESS_CODE_COMMENT if has_useless_code_comment else '') + 'function(global,env,buffer) {\n' + pre_2[brace:]
320
post = post_1 + end_asm + coutput[end + 1:]
321
322
filename += '.jo.js'
323
temp_files.note(filename)
324
325
with open(filename, 'w') as f:
326
with ToolchainProfiler.profile_block('write_pre'):
327
f.write(pre)
328
pre = None
329
330
with ToolchainProfiler.profile_block('sort_or_concat'):
331
# sort functions by size, to make diffing easier and to improve aot times
332
funcses = [split_funcs(utils.read_file(out_file)) for out_file in filenames]
333
funcs = [item for sublist in funcses for item in sublist]
334
funcses = None
335
if not os.environ.get('EMCC_NO_OPT_SORT'):
336
funcs.sort(key=lambda x: (len(x[1]), x[0]), reverse=True)
337
338
for func in funcs:
339
f.write(func[1])
340
funcs = None
341
342
with ToolchainProfiler.profile_block('write_post'):
343
f.write('\n')
344
f.write(post)
345
f.write('\n')
346
347
return filename
348
349
350
def main():
351
last = sys.argv[-1]
352
if '{' in last:
353
extra_info = json.loads(last)
354
sys.argv = sys.argv[:-1]
355
else:
356
extra_info = None
357
out = run_on_file(sys.argv[1], sys.argv[2:], extra_info=extra_info)
358
shutil.copyfile(out, sys.argv[1] + '.jsopt.js')
359
return 0
360
361
362
if __name__ == '__main__':
363
sys.exit(main())
364
365