3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
9 // Test for correct heap-moving of escaped variables.
10 // It is hard to check for the allocations, but it is easy
11 // to check that if you call the function twice at the
12 // same stack level, the pointers returned should be
17 var allptr = make([]*int, 0, 100)
19 func noalias(p, q *int, s string) {
23 allptr = allptr[0 : n+2]
27 for i := 0; i < n; i++ {
28 if allptr[i] != nil && *allptr[i] != -(i+1) {
29 println("aliased pointers", -(i + 1), *allptr[i], "after", s)
36 func val(p, q *int, v int, s string) {
38 println("wrong value want", v, "got", *p, "after", s)
42 println("wrong value want", v+1, "got", *q, "after", s)
47 func chk(p, q *int, v int, s string) {
52 func chkalias(p, q *int, v int, s string) {
54 println("want aliased pointers but got different after", s)
58 println("wrong value want", v+1, "got", *q, "after", s)
63 func i_escapes(x int) *int {
69 func j_escapes(x int) *int {
75 func k_escapes(x int) *int {
80 func in_escapes(x int) *int {
84 func send(c chan int, x int) {
88 func select_escapes(x int) *int {
98 func select_escapes1(x int, y int) (*int, *int) {
104 for i := 0; i < 2; i++ {
114 func range_escapes(x int) *int {
117 for _, v := range a {
124 func range_escapes2(x, y int) (*int, *int) {
129 for k, v := range a {
136 func for_escapes2(x int, y int) (*int, *int) {
139 for i := x; n < 2; i = y {
146 func for_escapes3(x int, y int) (*int, *int) {
149 for i := x; n < 2; i = y {
152 f[n] = func() *int { return p }
155 return f[0](), f[1]()
158 func out_escapes(i int) (x int, p *int) {
160 p = &x // ERROR "address of out parameter"
164 func out_escapes_2(i int) (x int, p *int) {
166 return x, &x // ERROR "address of out parameter"
169 func defer1(i int) (x int) {
171 go func() { x = i; c <- 1 }()
177 p, q := i_escapes(1), i_escapes(2)
178 chk(p, q, 1, "i_escapes")
180 p, q = j_escapes(3), j_escapes(4)
181 chk(p, q, 3, "j_escapes")
183 p, q = k_escapes(5), k_escapes(6)
184 chk(p, q, 5, "k_escapes")
186 p, q = in_escapes(7), in_escapes(8)
187 chk(p, q, 7, "in_escapes")
189 p, q = select_escapes(9), select_escapes(10)
190 chk(p, q, 9, "select_escapes")
192 p, q = select_escapes1(11, 12)
193 chk(p, q, 11, "select_escapes1")
195 p, q = range_escapes(13), range_escapes(14)
196 chk(p, q, 13, "range_escapes")
198 p, q = range_escapes2(101, 102)
199 chkalias(p, q, 101, "range_escapes2")
201 p, q = for_escapes2(103, 104)
202 chkalias(p, q, 103, "for_escapes2")
204 p, q = for_escapes3(105, 106)
205 chk(p, q, 105, "for_escapes3")
207 _, p = out_escapes(15)
208 _, q = out_escapes(16)
209 chk(p, q, 15, "out_escapes")
211 _, p = out_escapes_2(17)
212 _, q = out_escapes_2(18)
213 chk(p, q, 17, "out_escapes_2")
217 println("defer failed", x)
222 panic("BUG: no escape")