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) {
137 func for_escapes2(x int, y int) (*int, *int) {
148 func for_escapes3(x int, y int) (*int, *int) {
151 for i := x; n < 2; i = y {
154 f[n] = func() *int { return p }
157 return f[0](), f[1]()
160 func out_escapes(i int) (x int, p *int) {
162 p = &x // ERROR "address of out parameter"
166 func out_escapes_2(i int) (x int, p *int) {
168 return x, &x // ERROR "address of out parameter"
171 func defer1(i int) (x int) {
173 go func() { x = i; c <- 1 }()
179 p, q := i_escapes(1), i_escapes(2)
180 chk(p, q, 1, "i_escapes")
182 p, q = j_escapes(3), j_escapes(4)
183 chk(p, q, 3, "j_escapes")
185 p, q = k_escapes(5), k_escapes(6)
186 chk(p, q, 5, "k_escapes")
188 p, q = in_escapes(7), in_escapes(8)
189 chk(p, q, 7, "in_escapes")
191 p, q = select_escapes(9), select_escapes(10)
192 chk(p, q, 9, "select_escapes")
194 p, q = select_escapes1(11, 12)
195 chk(p, q, 11, "select_escapes1")
197 p, q = range_escapes(13), range_escapes(14)
198 chk(p, q, 13, "range_escapes")
200 p, q = range_escapes2(101, 102)
201 chkalias(p, q, 101, "range_escapes2")
203 p, q = for_escapes2(103, 104)
204 chkalias(p, q, 103, "for_escapes2")
206 p, q = for_escapes3(105, 106)
207 chk(p, q, 105, "for_escapes3")
209 _, p = out_escapes(15)
210 _, q = out_escapes(16)
211 chk(p, q, 15, "out_escapes")
213 _, p = out_escapes_2(17)
214 _, q = out_escapes_2(18)
215 chk(p, q, 17, "out_escapes_2")
219 println("defer failed", x)
224 panic("BUG: no escape")