]> git.proxmox.com Git - rustc.git/blob - src/binaryen/src/passes/ReorderFunctions.cpp
New upstream version 1.23.0+dfsg1
[rustc.git] / src / binaryen / src / passes / ReorderFunctions.cpp
1 /*
2 * Copyright 2016 WebAssembly Community Group participants
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //
18 // Sorts functions by their static use count. This helps reduce the size of wasm
19 // binaries because fewer bytes are needed to encode references to frequently
20 // used functions.
21 //
22
23
24 #include <memory>
25
26 #include <wasm.h>
27 #include <pass.h>
28
29 namespace wasm {
30
31 struct ReorderFunctions : public WalkerPass<PostWalker<ReorderFunctions>> {
32 std::map<Name, uint32_t> counts;
33
34 void visitModule(Module *module) {
35 if (module->start.is()) {
36 counts[module->start]++;
37 }
38 for (auto& curr : module->exports) {
39 counts[curr->value]++;
40 }
41 for (auto& segment : module->table.segments) {
42 for (auto& curr : segment.data) {
43 counts[curr]++;
44 }
45 }
46 std::sort(module->functions.begin(), module->functions.end(), [this](
47 const std::unique_ptr<Function>& a,
48 const std::unique_ptr<Function>& b) -> bool {
49 if (this->counts[a->name] == this->counts[b->name]) {
50 return strcmp(a->name.str, b->name.str) > 0;
51 }
52 return this->counts[a->name] > this->counts[b->name];
53 });
54 counts.clear();
55 }
56
57 void visitCall(Call *curr) {
58 counts[curr->target]++;
59 }
60 };
61
62 Pass *createReorderFunctionsPass() {
63 return new ReorderFunctions();
64 }
65
66 } // namespace wasm