|
| 1 | +/* |
| 2 | + * Copyright 2019 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 | +// Removes duplicate imports. |
| 19 | +// |
| 20 | +// TODO: non-function imports too |
| 21 | +// |
| 22 | + |
| 23 | +#include "asm_v_wasm.h" |
| 24 | +#include "ir/import-utils.h" |
| 25 | +#include "opt-utils.h" |
| 26 | +#include "pass.h" |
| 27 | +#include "wasm.h" |
| 28 | + |
| 29 | +namespace wasm { |
| 30 | + |
| 31 | +struct DuplicateImportElimination : public Pass { |
| 32 | + void run(PassRunner* runner, Module* module) override { |
| 33 | + ImportInfo imports(*module); |
| 34 | + std::map<Name, Name> replacements; |
| 35 | + std::map<std::pair<Name, Name>, Name> seen; |
| 36 | + std::vector<Name> toRemove; |
| 37 | + for (auto* func : imports.importedFunctions) { |
| 38 | + auto pair = std::make_pair(func->module, func->base); |
| 39 | + auto iter = seen.find(pair); |
| 40 | + if (iter != seen.end()) { |
| 41 | + auto previousName = iter->second; |
| 42 | + auto previousFunc = module->getFunction(previousName); |
| 43 | + // It is ok to import the same thing with multiple types; we can only |
| 44 | + // merge if the types match, of course. |
| 45 | + if (getSig(previousFunc) == getSig(func)) { |
| 46 | + replacements[func->name] = previousName; |
| 47 | + toRemove.push_back(func->name); |
| 48 | + continue; |
| 49 | + } |
| 50 | + } |
| 51 | + seen[pair] = func->name; |
| 52 | + } |
| 53 | + if (!replacements.empty()) { |
| 54 | + module->updateMaps(); |
| 55 | + OptUtils::replaceFunctions(runner, *module, replacements); |
| 56 | + for (auto name : toRemove) { |
| 57 | + module->removeFunction(name); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +}; |
| 62 | + |
| 63 | +Pass* createDuplicateImportEliminationPass() { |
| 64 | + return new DuplicateImportElimination(); |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace wasm |
0 commit comments