[hir] Validate globals are equal before propagating
Make sure the value of the globals in phi operands are the same before constant propagating them.
Sathya Gunasekaran committed
Aug 16, 2023 at 15:39 UTC
b968d4da48fd3b9ae703698bfe31ecdc731630fa
3 files changed
+52
compiler/forget/packages/babel-plugin-react-forget/src/Optimization/ConstantPropagation.ts
+13
@@ -206,6 +206,19 @@ function evaluatePhi(phi: Phi, constants: Constants): Constant | null {
206
}
207
break;
208
}
209
+ case "LoadGlobal": {
210
+ CompilerError.invariant(value.kind === "LoadGlobal", {
211
+ reason: "value kind expected to be LoadGlobal",
212
+ loc: null,
213
+ suggestions: null,
214
+ });
215
+
216
+ // different global values, can't constant propogate
217
+ if (operandValue.name !== value.name) {
218
+ return null;
219
+ }
220
+ break;
221
+ }
222
default:
223
return null;
224
}
compiler/forget/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/constant-propagate-global-phis-constant.expect.md
new
+33
@@ -0,0 +1,33 @@
1
+
2
+## Input
3
+
4
+```javascript
5
+function Test() {
6
+ const { tab } = useFoo();
7
+ const currentTab = tab === WAT ? WAT : WAT;
8
+
9
+ return <Foo value={currentTab} />;
10
+}
11
+
12
+```
13
+
14
+## Code
15
+
16
+```javascript
17
+import { unstable_useMemoCache as useMemoCache } from "react";
18
+function Test() {
19
+ const $ = useMemoCache(1);
20
+ const { tab } = useFoo();
21
+ tab === WAT ? WAT : WAT;
22
+ let t0;
23
+ if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
24
+ t0 = <Foo value={WAT} />;
25
+ $[0] = t0;
26
+ } else {
27
+ t0 = $[0];
28
+ }
29
+ return t0;
30
+}
31
+
32
+```
33
+
\ No newline at end of file
compiler/forget/packages/babel-plugin-react-forget/src/__tests__/fixtures/compiler/constant-propagate-global-phis-constant.js
new
+6
@@ -0,0 +1,6 @@
1
+function Test() {
2
+ const { tab } = useFoo();
3
+ const currentTab = tab === WAT ? WAT : WAT;
4
+
5
+ return <Foo value={currentTab} />;
6
+}