Skip to content

Commit 6e92c82

Browse files
committed
Add memory allocation
1 parent 3a1069e commit 6e92c82

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

src/memory_allocation.wat

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
(module
2+
(import "env" "_Znwj" (func $_Znwj (param i32) (result i32))) ;; new
3+
(import "env" "_Znaj" (func $_Znaj (param i32) (result i32))) ;; new[]
4+
(import "env" "_ZdlPv" (func $_ZdlPv (param i32))) ;; delete
5+
(import "env" "_ZdaPv" (func $_ZdaPv (param i32))) ;; delete[]
6+
7+
(memory $memory 1)
8+
9+
;; int load(int* a) {
10+
;; return *a;
11+
;; }
12+
(func $load (param $a i32) (result i32)
13+
(i32.load
14+
(get_local $a)))
15+
16+
;; void store(int* a, int b) {
17+
;; *a = b;
18+
;; }
19+
(func $store (param $a i32) (param $b i32)
20+
(i32.store
21+
(get_local $a)
22+
(get_local $b)))
23+
24+
;; int* func1() {
25+
;; int* ptr = new int;
26+
;; return ptr;
27+
;; }
28+
(func $func1 (result i32)
29+
(call $_Znwj
30+
(i32.const 4)))
31+
32+
;; void func2(int* ptr) {
33+
;; delete ptr;
34+
;; }
35+
(func $func2 (param $ptr i32)
36+
(block $B0
37+
(br_if $B0
38+
(i32.eqz
39+
(get_local $ptr)))
40+
(call $_ZdlPv
41+
(get_local $ptr))))
42+
43+
;; int* func3() {
44+
;; int* ptr = new int[10];
45+
;; return ptr;
46+
;; }
47+
(func $func3 (result i32)
48+
(call $_Znaj
49+
(i32.const 40)))
50+
51+
;; void func4(int* ptr) {
52+
;; delete[] ptr;
53+
;; }
54+
(func $func4 (param $ptr i32)
55+
(block $B0
56+
(br_if $B0
57+
(i32.eqz
58+
(get_local $ptr)))
59+
(call $_ZdaPv
60+
(get_local $ptr))))
61+
62+
;; int* func5(int size) {
63+
;; int* ptr = new int[size];
64+
;; return ptr;
65+
;; }
66+
(func $func5 (param $size i32) (result i32)
67+
(local $l0 i64)
68+
(call $_Znaj
69+
(select
70+
(i32.const -1)
71+
(i32.wrap/i64
72+
(tee_local $l0
73+
(i64.shl
74+
(i64.extend_u/i32
75+
(get_local $size))
76+
(i64.const 2))))
77+
(i32.wrap/i64
78+
(i64.shr_u
79+
(get_local $l0)
80+
(i64.const 32))))))
81+
)

0 commit comments

Comments
 (0)