1 /*
2 * Copyright 2017 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 #ifndef wasm_ir_global_h
18 #define wasm_ir_global_h
19
20 #include <algorithm>
21 #include <vector>
22
23 #include "ir/module-utils.h"
24 #include "literal.h"
25 #include "wasm.h"
26
27 namespace wasm {
28
29 namespace GlobalUtils {
30 // find a global initialized to the value of an import, or null if no such
31 // global
32 inline Global*
getGlobalInitializedToImport(Module & wasm,Name module,Name base)33 getGlobalInitializedToImport(Module& wasm, Name module, Name base) {
34 // find the import
35 Name imported;
36 ModuleUtils::iterImportedGlobals(wasm, [&](Global* import) {
37 if (import->module == module && import->base == base) {
38 imported = import->name;
39 }
40 });
41 if (imported.isNull()) {
42 return nullptr;
43 }
44 // find a global inited to it
45 Global* ret = nullptr;
46 ModuleUtils::iterDefinedGlobals(wasm, [&](Global* defined) {
47 if (auto* init = defined->init->dynCast<GlobalGet>()) {
48 if (init->name == imported) {
49 ret = defined;
50 }
51 }
52 });
53 return ret;
54 }
55
canInitializeGlobal(const Expression * curr)56 inline bool canInitializeGlobal(const Expression* curr) {
57 if (auto* tuple = curr->dynCast<TupleMake>()) {
58 for (auto* op : tuple->operands) {
59 if (!Properties::isSingleConstantExpression(op) && !op->is<GlobalGet>()) {
60 return false;
61 }
62 }
63 return true;
64 }
65 return Properties::isSingleConstantExpression(curr) || curr->is<GlobalGet>();
66 }
67
68 } // namespace GlobalUtils
69
70 } // namespace wasm
71
72 #endif // wasm_ir_global_h
73