Debian Codegraph @

loki/transformations/temporaries/tests/test_pool_allocator.py

raw
1 # (C) Copyright 2018- ECMWF.
2 # This software is licensed under the terms of the Apache Licence Version 2.0
3 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
4 # In applying this licence, ECMWF does not waive the privileges and immunities
5 # granted to it by virtue of its status as an intergovernmental organisation
6 # nor does it submit to any jurisdiction.
7
8 import pytest
9
10 from loki.expression.parser import parse_expr
11 from loki import Dimension, Subroutine
12 from loki.batch import Scheduler, SchedulerConfig
13 from loki.expression import (
14 InlineCall, RangeIndex, simplify, Sum,
15 Product
16 )
17 from loki.frontend import available_frontends, OMNI, FP
18 from loki.ir import (
19 nodes as ir, FindNodes, FindVariables, FindInlineCalls,
20 get_pragma_parameters
21 )
22
23 from loki.transformations.pragma_model import PragmaModelTransformation
24 from loki.transformations.temporaries.pool_allocator import (
25 TemporariesPoolAllocatorTransformation, EcstackPoolAllocatorTransformation
26 )
27
28
29 @pytest.fixture(scope='module', name='block_dim')
30 def fixture_block_dim():
31 return Dimension(name='block_dim', size='nb', index='b')
32
33 @pytest.fixture(scope='module', name='horizontal')
34 def fixture_horizontal():
35 return Dimension(name='horizontal', size='nlon', index='jl', bounds=('start', 'end'), aliases=('klon', 'columns'))
36
37 @pytest.fixture(scope='module', name='block_dim_alt')
38 def fixture_block_dim_alt():
39 return Dimension(name='block_dim_alt', size='geom%blk_dim%nb', index='b')
40
41 def check_c_sizeof_import(routine):
42 assert any(import_.module.lower() == 'iso_c_binding' for import_ in routine.imports)
43 assert 'c_sizeof' in routine.imported_symbols
44
45 def check_real64_import(routine):
46 assert any(import_.module.lower() == 'iso_fortran_env' for import_ in routine.imports)
47 assert 'real64' in routine.imported_symbols
48
49
50 def check_stack_created_in_driver(
51 driver, stack_size, first_kernel_call, num_block_loops,
52 check_bounds=True, cray_ptr_loc_rhs=False
53 ):
54 # Are stack size, storage and stack derived type declared?
55 assert 'istsz' in driver.variables
56 assert 'zstack(:,:)' in driver.variables
57 assert 'ylstack_l' in driver.variables
58
59 # Is there an allocation and deallocation for the stack storage?
60 allocations = FindNodes(ir.Allocation).visit(driver.body)
61 assert len(allocations) == 1 and 'zstack(istsz,nb)' in allocations[0].variables
62 deallocations = FindNodes(ir.Deallocation).visit(driver.body)
63 assert len(deallocations) == 1 and 'zstack' in deallocations[0].variables
64
65 # # Check the stack size
66 assignments = FindNodes(ir.Assignment).visit(driver.body)
67 for assignment in assignments:
68 if assignment.lhs == 'istsz':
69 assert simplify(assignment.rhs) == simplify(stack_size)
70
71 # # Check for stack assignment inside loop
72 loops = FindNodes(ir.Loop).visit(driver.body)
73 assert len(loops) == num_block_loops
74 assignments = FindNodes(ir.Assignment).visit(loops[0].body)
75 assert assignments[0].lhs == 'ylstack_l'
76 if cray_ptr_loc_rhs:
77 assert assignments[0].rhs == '1'
78 else:
79 assert isinstance(assignments[0].rhs, InlineCall) and assignments[0].rhs.function == 'loc'
80 assert 'zstack(1, b)' in assignments[0].rhs.parameters
81 if check_bounds:
82 if cray_ptr_loc_rhs:
83 assert assignments[1].lhs == 'ylstack_u' and (
84 assignments[1].rhs == 'ylstack_l + istsz')
85 else:
86 assert assignments[1].lhs == 'ylstack_u' and (
87 assignments[1].rhs == 'ylstack_l + istsz * c_sizeof(real(1, kind=real64))')
88 # Check that stack assignment happens before kernel call
89 assert all(loops[0].body.index(a) < loops[0].body.index(first_kernel_call) for a in assignments)
90
91
92 @pytest.mark.parametrize('frontend', available_frontends())
93 @pytest.mark.parametrize('loop_pragma, loop_end_pragma, increment', [
94 ('!$omp parallel do private(b)', '!$omp end parallel do', '1.0'),
95 (
96 '!$omp parallel default(shared) private(b)\n marker = marker + 1\n'
97 ' !$omp do',
98 '!$omp end do\n !$omp end parallel',
99 'marker'
100 ),
101 ('!$acc parallel loop gang', '!$acc end parallel loop', '1.0'),
102 ('!$omp target teams distribute', '!$omp end target teams distribute', '1.0'),
103 ])
104 def test_pool_allocator_annotated_driver_loops_without_targets(
105 frontend, block_dim, loop_pragma, loop_end_pragma, increment
106 ):
107 """
108 Parallel loops may already be present without Loki driver-loop annotations.
109 Treat OpenMP CPU, OpenACC gang, and OpenMP target teams loops as annotated
110 driver loops.
111 """
112 fcode = f"""
113 subroutine driver(NLON, NB, FIELD, nouter_loop)
114 implicit none
115 integer, intent(in) :: nlon, nb, nouter_loop
116 real, intent(inout) :: field(nlon, nb)
117 integer :: b, marker, it
118
119 marker = 0
120
121 do it=1,nouter_loop
122 {loop_pragma}
123 do b=1,nb
124 field(1,b) = field(1,b) + {increment}
125 end do
126 {loop_end_pragma}
127 enddo
128 end subroutine driver
129 """.strip()
130
131 driver = Subroutine.from_source(fcode, frontend=frontend)
132 transformation = TemporariesPoolAllocatorTransformation(block_dim=block_dim)
133 transformation.transform_subroutine(driver, role='driver', targets=())
134
135 loops = FindNodes(ir.Loop).visit(driver.body)
136 assert len(loops) == 2
137
138 assignments = tuple(stmt for stmt in loops[1].body if isinstance(stmt, ir.Assignment))
139 assert assignments[0].lhs == 'ylstack_l'
140 assert assignments[1].lhs == 'ylstack_u'
141
142
143 @pytest.mark.parametrize('generate_driver_stack', [True, False])
144 @pytest.mark.parametrize('frontend', available_frontends())
145 @pytest.mark.parametrize('check_bounds', [True, False])
146 @pytest.mark.parametrize('nclv_param', [False, True])
147 @pytest.mark.parametrize('cray_ptr_loc_rhs', [False, True])
148 @pytest.mark.parametrize('trafo', [EcstackPoolAllocatorTransformation, TemporariesPoolAllocatorTransformation])
149 def test_pool_allocator_temporaries(tmp_path, frontend, generate_driver_stack, block_dim, check_bounds,
150 nclv_param, cray_ptr_loc_rhs, trafo, horizontal):
151 fcode_iso_c_binding = "use, intrinsic :: iso_c_binding, only: c_sizeof"
152 fcode_iso_env = "use iso_fortran_env, only: real64"
153 fcode_nclv_param = 'integer, parameter :: nclv = 2'
154 # set kind comaprison string
155 nclv_var = '2' if frontend == OMNI else 'nclv'
156 if frontend == OMNI:
157 kind_real = 'selected_real_kind(13, 300)'
158 else:
159 kind_real = 'jprb'
160 kind_stack = 'real64'
161 if nclv_param:
162 nclv_var = '2' if frontend == OMNI else 'nclv'
163 stack_size_str = (
164 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3)'
165 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
166 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon*{nclv_var}, -3)'
167 )
168 else:
169 stack_size_str = (
170 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3) &\n'
171 f' & + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3) &\n'
172 f' & + ishft(7 + c_sizeof(real(1, kind={kind_real}))*2, -3)'
173 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon*2, -3)'
174 )
175
176 fcode_stack_decl = f"""
177 integer :: istsz
178 REAL(KIND=REAL64), ALLOCATABLE :: ZSTACK(:, :)
179 integer(kind=8) :: ylstack_l
180 integer(kind=8) :: ylstack_u
181
182 istsz = {stack_size_str}
183
184 {'ALLOCATE(ZSTACK(ISTSZ, nb))' if trafo == TemporariesPoolAllocatorTransformation else 'CALL ECSTACK%GET_STACK_PTR(ZSTACK, ISTSZ, nb)'}
185 """
186 if cray_ptr_loc_rhs:
187 fcode_stack_assign = """
188 ylstack_l = 1
189 ylstack_u = ylstack_l + istsz
190 """
191 else:
192 fcode_stack_assign = f"""
193 ylstack_l = loc(zstack(1, b))
194 ylstack_u = ylstack_l + istsz * c_sizeof(real(1, kind={kind_stack}))
195 """
196 fcode_stack_dealloc = "DEALLOCATE(ZSTACK)" if trafo == TemporariesPoolAllocatorTransformation else ''
197
198 fcode_ecstack = """
199 module ecstack_mod
200 implicit none
201 type tecstack
202 integer :: size
203 contains
204 PROCEDURE :: GET_STACK_PTR
205 end type tecstack
206
207 type(tecstack) :: ecstack
208
209 contains
210 SUBROUTINE GET_STACK_PTR(SELF, PTR, KSIZE, NGPBLKS)
211 CLASS(TECSTACK) :: SELF
212 REAL, POINTER, CONTIGUOUS, INTENT(INOUT) :: PTR(:, :)
213 INTEGER, INTENT(IN) :: KSIZE
214 INTEGER, INTENT(IN) :: NGPBLKS
215
216 END SUBROUTINE GET_STACK_PTR
217 end module ecstack_mod
218 """
219 fcode_driver = f"""
220 subroutine driver(NLON, NZ, NB, FIELD1, FIELD2)
221 {fcode_iso_c_binding if not generate_driver_stack else ''}
222 {fcode_iso_env if not generate_driver_stack else ''}
223 {'use ecstack_mod, only: ecstack' if (trafo == EcstackPoolAllocatorTransformation and not generate_driver_stack) else ''}
224 use kernel_mod, only: kernel
225 implicit none
226 INTEGER, PARAMETER :: JPRB = SELECTED_REAL_KIND(13,300)
227 INTEGER, INTENT(IN) :: NLON, NZ, NB
228 real(kind=jprb), intent(inout) :: field1(nlon, nb)
229 real(kind=jprb), intent(inout) :: field2(nlon, nz, nb)
230 integer :: b
231 {fcode_stack_decl if not generate_driver_stack else ''}
232 do b=1,nb
233 {fcode_stack_assign if not generate_driver_stack else ''}
234 call KERNEL(1, nlon, nlon, nz, {'2, ' if not nclv_param else ''} field1(:,b), field2(:,:,b))
235 end do
236 {fcode_stack_dealloc if not generate_driver_stack else ''}
237 end subroutine driver
238 """.strip()
239 fcode_kernel = f"""
240 module kernel_mod
241 implicit none
242 contains
243 subroutine kernel(start, end, klon, klev, {'nclv, ' if not nclv_param else ''} field1, field2)
244 ! use, intrinsic :: iso_c_binding, only : c_size_t
245 implicit none
246 integer, parameter :: jprb = selected_real_kind(13,300)
247 {fcode_nclv_param if nclv_param else 'integer, intent(in) :: nclv'}
248 integer, intent(in) :: start, end, klon, klev
249 real(kind=jprb), intent(inout), target :: field1(klon)
250 real(kind=jprb), intent(inout) :: field2(klon,klev)
251 real(kind=jprb) :: tmp1(klon)
252 real(kind=jprb) :: tmp2(klon, klev)
253 real(kind=jprb) :: tmp3(nclv), tmp4(2), tmp5(klon, nclv)
254 real(kind=jprb), pointer :: tmp3_ptr(:)
255 integer :: jk, jl, jm
256
257 tmp3_ptr => field1
258
259 do jk=1,klev
260 tmp1(jl) = 0.0_jprb
261 do jl=start,end
262 tmp2(jl, jk) = field2(jl, jk)
263 tmp1(jl) = field2(jl, jk)
264 end do
265 field1(jl) = tmp1(jl)
266 end do
267
268 do jm=1,nclv
269 tmp3(jm) = 0._jprb
270 do jl=start,end
271 tmp5(jl, jm) = field1(jl)
272 enddo
273 enddo
274 end subroutine kernel
275 end module kernel_mod
276 """.strip()
277
278
279 (tmp_path/'driver.F90').write_text(fcode_driver)
280 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
281 (tmp_path/'ecstack_mod.F90').write_text(fcode_ecstack)
282
283 config = {
284 'default': {
285 'mode': 'idem',
286 'role': 'kernel',
287 'expand': True,
288 'strict': True,
289 'enable_imports': True,
290 'ignore': ['iso_fortran_env']
291 },
292 'routines': {
293 'driver': {'role': 'driver'}
294 }
295 }
296
297 if frontend == FP and not generate_driver_stack:
298 # Patch "LOC" intrinsic into fparser. This is not strictly needed (it will just represent it
299 # as Array instead of an InlineCall) but makes for a more coherent check further down
300 try:
301 from fparser.two.Fortran2008 import Intrinsic_Name # pylint: disable=import-outside-toplevel
302 except ImportError:
303 from fparser.two.Fortran2003 import Intrinsic_Name # pylint: disable=import-outside-toplevel
304
305 Intrinsic_Name.other_inquiry_names.update({"LOC": {'min': 1, 'max': 1}})
306 Intrinsic_Name.generic_function_names.update({"LOC": {'min': 1, 'max': 1}})
307 Intrinsic_Name.function_names += ["LOC"]
308
309 scheduler = Scheduler(
310 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
311 frontend=frontend, xmods=[tmp_path]
312 )
313
314 transformation = trafo(
315 block_dim=block_dim, horizontal=horizontal, check_bounds=check_bounds,
316 cray_ptr_loc_rhs=cray_ptr_loc_rhs
317 )
318 scheduler.process(transformation=transformation)
319 pragma_model_trafo = PragmaModelTransformation()
320 scheduler.process(transformation=pragma_model_trafo)
321 kernel_item = scheduler['kernel_mod#kernel']
322
323 assert transformation._key in kernel_item.trafo_data
324
325 # a few driver checks
326 driver = scheduler['#driver'].ir
327 check_c_sizeof_import(driver)
328 check_real64_import(driver)
329 calls = FindNodes(ir.CallStatement).visit(driver.body)
330 assert len(calls) == 1 if trafo == TemporariesPoolAllocatorTransformation else 2
331 if nclv_param:
332 expected_args = ('1', 'nlon', 'nlon', 'nz', 'field1(:,b)', 'field2(:,:,b)')
333 else:
334 expected_args = ('1', 'nlon', 'nlon', 'nz', '2', 'field1(:,b)', 'field2(:,:,b)')
335 if check_bounds:
336 expected_kwargs = (('YDSTACK_L', 'ylstack_l'), ('YDSTACK_U', 'ylstack_u'))
337 else:
338 expected_kwargs = (('YDSTACK_L', 'ylstack_l'),)
339 if cray_ptr_loc_rhs:
340 if frontend == OMNI and not generate_driver_stack:
341 # If the stack exists already in the driver, that variable is used. And because
342 # OMNI lower-cases everything, this will result in a lower-case name for the
343 # argument for that particular case...
344 expected_kwargs += (('zstack', 'zstack(:,b)'),)
345 else:
346 expected_kwargs += (('ZSTACK', 'zstack(:,b)'),)
347 relevant_call = calls[0] if trafo == TemporariesPoolAllocatorTransformation else calls[1]
348 assert relevant_call.arguments == expected_args
349 assert relevant_call.kwarguments == expected_kwargs
350 if trafo == EcstackPoolAllocatorTransformation:
351 assert calls[0].arguments == ('ZSTACK', 'ISTSZ', 'nb')
352
353 if nclv_param:
354 nclv_var = '2' if frontend == OMNI else 'nclv'
355 stack_size_str = (
356 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3)'
357 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
358 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon*{nclv_var}, -3)'
359 )
360 else:
361 stack_size_str = (
362 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3)'
363 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
364 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*2, -3)'
365 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon*2, -3)'
366 )
367
368 stack_size = parse_expr(stack_size_str)
369 if trafo == TemporariesPoolAllocatorTransformation:
370 check_stack_created_in_driver(driver, stack_size, calls[0], 1, check_bounds=check_bounds,
371 cray_ptr_loc_rhs=cray_ptr_loc_rhs)
372
373 # a few kernel checks
374 kernel = kernel_item.ir
375 check_c_sizeof_import(kernel)
376 check_real64_import(kernel)
377 # # Has the stack been added to the arguments?
378 assert 'ydstack_l' in kernel.arguments
379 if check_bounds:
380 assert 'ydstack_u' in kernel.arguments
381
382 # Is it being assigned to a local variable?
383 assert 'ylstack_l' in kernel.variables
384 if check_bounds:
385 assert 'ylstack_u' in kernel.variables
386
387 # Let's check for the relevant "allocations" happening in the right order
388 if nclv_param:
389 tmp_indices = (1, 2, 5)
390 else:
391 tmp_indices = (1, 2, 3, 5)
392 assign_idx = {}
393 for idx, assign in enumerate(FindNodes(ir.Assignment).visit(kernel.body)):
394 if assign.lhs == 'ylstack_l' and assign.rhs == 'ydstack_l':
395 # Local copy of stack status
396 assign_idx['stack_assign'] = idx
397 elif str(assign.lhs).lower().startswith('ip_tmp'):
398 # Assign Cray pointer for tmp1, tmp2, tmp5 (and tmp3, tmp4 if no alloc_dims provided)
399 for tmp_index in tmp_indices:
400 if f'ip_tmp{tmp_index}' == assign.lhs:
401 assign_idx[f'tmp{tmp_index}_ptr_assign'] = idx
402 elif assign.lhs == 'ylstack_l' and 'ylstack_l' in assign.rhs: #  and 'c_sizeof' in assign.rhs:
403
404 # Stack increment for tmp1, tmp2, tmp5 (and tmp3, tmp4 if no alloc_dims provided)
405 for tmp_index in tmp_indices:
406
407 dim = f"{kernel.variable_map[f'tmp{tmp_index}'].shape[0]}"
408 for v in kernel.variable_map[f'tmp{tmp_index}'].shape[1:]:
409 dim += f'*{v}'
410 if cray_ptr_loc_rhs:
411 exp_rhs_str = f'ylstack_l + ishft({dim}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3)'
412 else:
413 exp_rhs_str = f'ylstack_l + ishft(ishft({dim}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3), 3)'
414 expected_rhs = parse_expr(exp_rhs_str)
415 if expected_rhs == assign.rhs:
416 assign_idx[f'tmp{tmp_index}_stack_incr'] = idx
417
418 expected_assign_in_order = ['stack_assign']
419 for tmp_index in tmp_indices:
420 expected_assign_in_order += [f'tmp{tmp_index}_ptr_assign', f'tmp{tmp_index}_stack_incr']
421 assert set(expected_assign_in_order) == set(assign_idx.keys())
422
423 for assign1, assign2 in zip(expected_assign_in_order, expected_assign_in_order[1:]):
424 assert assign_idx[assign2] > assign_idx[assign1]
425
426 # Check for pointer declarations in generated code
427 fcode = kernel.to_fortran()
428 for tmp_index in tmp_indices:
429 assert f'pointer(ip_tmp{tmp_index}, tmp{tmp_index})' in fcode.lower()
430
431 # Check for stack size safeguards in generated code
432 if check_bounds:
433 assert fcode.lower().count('if (ylstack_l > ylstack_u)') == len(tmp_indices)
434 assert fcode.lower().count('stop') == len(tmp_indices)
435 else:
436 assert 'if (ylstack_l > ylstack_u)' not in fcode.lower()
437 assert 'stop' not in fcode.lower()
438
439
440 @pytest.mark.parametrize('frontend', available_frontends())
441 def test_pool_allocator_unused_temporaries(tmp_path, frontend, horizontal, block_dim):
442 fcode_driver = """
443 subroutine driver(NLON, NZ, NB, FIELD1, FIELD2)
444 use kernel_mod, only: kernel
445 implicit none
446 INTEGER, PARAMETER :: JPRB = SELECTED_REAL_KIND(13,300)
447 INTEGER, INTENT(IN) :: NLON, NZ, NB
448 real(kind=jprb), intent(inout) :: field1(nlon, nb)
449 real(kind=jprb), intent(inout) :: field2(nlon, nz, nb)
450 integer :: b
451 do b=1,nb
452 call KERNEL(1, nlon, nlon, nz, field1(:,b), field2(:,:,b))
453 end do
454 end subroutine driver
455 """.strip()
456 fcode_kernel = """
457 module kernel_mod
458 implicit none
459 contains
460 subroutine kernel(start, end, klon, klev, field1, field2)
461 implicit none
462 integer, parameter :: jprb = selected_real_kind(13,300)
463 integer, parameter :: nclv = 2
464 integer, intent(in) :: start, end, klon, klev
465 real(kind=jprb), intent(inout) :: field1(klon)
466 real(kind=jprb), intent(inout) :: field2(klon,klev)
467 real(kind=jprb) :: tmp1(klon)
468 real(kind=jprb) :: tmp2(klon, klev)
469 ! shouldn't end up on stack since not used at all
470 real(kind=jprb) :: tmp3(klon, klev)
471 ! shouldn't end up on stack since all dimension are constant
472 real(kind=jprb) :: tmp4(nclv)
473 ! shouldn't end up on stack since all dimension are constant
474 real(kind=jprb) :: tmp5(2)
475 ! should be on the stack although only read and not written to
476 real(kind=jprb) :: tmp6(klon, nclv)
477 ! should be on the stack although only used as an argument in a call
478 real(kind=jprb) :: tmp7(klon, nclv)
479 integer :: jk, jl, jm
480
481 tmp5(1) = 0.0_jprb
482 do jk=1,klev
483 tmp1(jl) = 0.0_jprb
484 do jl=start,end
485 tmp2(jl, jk) = field2(jl, jk)
486 tmp1(jl) = field2(jl, jk)
487 end do
488 field1(jl) = tmp1(jl)
489 end do
490
491 do jm=1,nclv
492 tmp4(jm) = 0._jprb
493 do jl=start,end
494 field1(jl) = tmp6(jl, jm)
495 enddo
496 enddo
497
498 call foo(tmp7)
499
500 end subroutine kernel
501 end module kernel_mod
502 """.strip()
503
504 config = {
505 'default': {
506 'mode': 'idem',
507 'role': 'kernel',
508 'expand': True,
509 'strict': False,
510 'enable_imports': True,
511 },
512 'routines': {
513 'driver': {'role': 'driver'}
514 }
515 }
516
517 (tmp_path/'driver.F90').write_text(fcode_driver)
518 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
519 scheduler = Scheduler(
520 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
521 frontend=frontend, xmods=[tmp_path]
522 )
523
524 transformation = TemporariesPoolAllocatorTransformation(
525 block_dim=block_dim, horizontal=horizontal, check_bounds=False,
526 cray_ptr_loc_rhs=False
527 )
528 scheduler.process(transformation=transformation)
529 kernel_item = scheduler['kernel_mod#kernel']
530
531 assert transformation._key in kernel_item.trafo_data
532
533 # check that the correct variables end up on the stack
534 #  look for 'POINTER(IP_tmp<...>, tmp<...>)' Intrinsics
535 pointers = [
536 intrinsic.text.split(',')[1].replace(')', '').replace(' ', '')
537 for intrinsic in FindNodes(ir.GenericStmt).visit(kernel_item.ir.spec)
538 if 'pointer' in intrinsic.text.lower()
539 ]
540 assert 'tmp1' in pointers
541 assert 'tmp2' in pointers
542 assert 'tmp6' in pointers
543 assert 'tmp7' in pointers
544 assert 'tmp3' not in pointers
545 assert 'tmp4' not in pointers
546 assert 'tmp5' not in pointers
547
548 @pytest.mark.parametrize('frontend', available_frontends())
549 @pytest.mark.parametrize('directive', [False, 'openmp', 'openacc', 'openmp-manual'])
550 @pytest.mark.parametrize('stack_insert_pragma', [False, True])
551 @pytest.mark.parametrize('cray_ptr_loc_rhs', [False, True])
552 def test_pool_allocator_temporaries_kernel_sequence(tmp_path, frontend, block_dim, directive,
553 stack_insert_pragma, cray_ptr_loc_rhs, horizontal):
554
555 if directive == 'openmp-manual':
556 driver_loop_pragma1 = '!$omp parallel default(shared) private(b) firstprivate(a)\n !$omp do'
557 driver_end_loop_pragma1 = '!$omp end do\n !$omp end parallel'
558 driver_loop_pragma2 = '!$omp parallel do firstprivate(a)'
559 driver_end_loop_pragma2 = '!$omp end parallel do'
560 kernel_pragma = ''
561 # from here on continue as directive is 'openmp'
562 directive = 'openmp'
563 else:
564 driver_loop_pragma1 = '!$loki loop gang default(shared) private(b) firstprivate(a)'
565 driver_end_loop_pragma1 = '!$loki end loop gang'
566 driver_loop_pragma2 = '!$loki loop gang firstprivate(a)'
567 driver_end_loop_pragma2 = '!$loki end loop gang'
568 kernel_pragma = '!$loki routine vector'
569
570 if stack_insert_pragma:
571 stack_size_location_pragma = '!$loki stack-insert'
572 else:
573 stack_size_location_pragma = ''
574
575
576 fcode_parkind_mod = """
577 module parkind1
578 implicit none
579 integer, parameter :: jprb = selected_real_kind(13,300)
580 integer, parameter :: jpim = selected_int_kind(9)
581 integer, parameter :: jplm = jpim
582 end module parkind1
583 """.strip()
584
585 fcode_driver = f"""
586 subroutine driver(NLON, NZ, NB, FIELD1, FIELD2)
587 use kernel_mod, only: kernel, kernel2
588 implicit none
589 INTEGER, PARAMETER :: JPRB = SELECTED_REAL_KIND(13,300)
590 INTEGER, INTENT(IN) :: NLON, NZ, NB
591 real(kind=jprb), intent(inout) :: field1(nlon, nb)
592 real(kind=jprb), intent(inout) :: field2(nlon, nz, nb)
593 integer :: a,b
594
595 ! a = 1, necessary to check loki stack-insert pragma
596 a = 1
597 {stack_size_location_pragma}
598
599 {driver_loop_pragma1}
600 do b=1,nb
601 call KERNEL(1, nlon, nlon, nz, field1(:,b), field2(:,:,b))
602 end do
603 {driver_end_loop_pragma1}
604
605 {driver_loop_pragma2}
606 do b=1,nb
607 call KERNEL2(1, nlon, nlon, nz, field2(:,:,b))
608 end do
609 {driver_end_loop_pragma2}
610 end subroutine driver
611 """.strip()
612
613 fcode_kernel = f"""
614 module kernel_mod
615 implicit none
616 contains
617 subroutine kernel(start, end, klon, klev, field1, field2)
618 use parkind1, only: jprb, jpim, jplm
619 implicit none
620 integer, intent(in) :: start, end, klon, klev
621 real(kind=jprb), intent(inout) :: field1(klon)
622 real(kind=jprb), intent(inout) :: field2(klon,klev)
623 real(kind=jprb) :: tmp1(klon)
624 real(kind=jprb) :: tmp2(klon, klev)
625 integer(kind=jpim) :: tmp3(klon*2)
626 logical(kind=jplm) :: tmp4(klev)
627 integer :: jk, jl
628 {kernel_pragma}
629
630 do jk=1,klev
631 tmp1(jl) = 0.0_jprb
632 do jl=start,end
633 tmp2(jl, jk) = field2(jl, jk)
634 tmp1(jl) = field2(jl, jk)
635 end do
636 field1(jl) = tmp1(jl)
637 tmp4(jk) = .true.
638 end do
639
640 do jl=start,end
641 tmp3(jl) = 1_jpim
642 tmp3(jl+klon) = 1_jpim
643 enddo
644 end subroutine kernel
645
646 subroutine kernel2(start, end, klon, klev, field2)
647 implicit none
648 integer, parameter :: jprb = selected_real_kind(13,300)
649 integer, intent(in) :: start, end, klon, klev
650 real(kind=jprb), intent(inout) :: field2(klon,klev)
651 real(kind=jprb) :: tmp1(2*klon, klev), tmp2(0:klon, 0:klev)
652 integer :: jk, jl
653
654 do jk=1,klev
655 do jl=start,end
656 tmp1(jl, jk) = field2(jl, jk)
657 tmp1(jl+klon, jk) = field2(jl, jk)*2._jprb
658 tmp2(jl, jk) = tmp1(jl, jk) + 1._jprb
659 field2(jl, jk) = tmp2(jl, jk)
660 end do
661 end do
662 end subroutine kernel2
663
664 end module kernel_mod
665 """.strip()
666
667 (tmp_path/'driver.F90').write_text(fcode_driver)
668 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
669 (tmp_path/'parkind_mod.F90').write_text(fcode_parkind_mod)
670
671 config = {
672 'default': {
673 'mode': 'idem',
674 'role': 'kernel',
675 'expand': True,
676 'strict': True,
677 'enable_imports': True,
678 },
679 'routines': {
680 'driver': {'role': 'driver'}
681 }
682 }
683 scheduler = Scheduler(
684 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
685 frontend=frontend, xmods=[tmp_path]
686 )
687
688 transformation = TemporariesPoolAllocatorTransformation(
689 block_dim=block_dim, horizontal=horizontal, directive=directive, cray_ptr_loc_rhs=cray_ptr_loc_rhs
690 )
691 scheduler.process(transformation=transformation)
692 pragma_model_trafo = PragmaModelTransformation(directive=directive)
693 scheduler.process(transformation=pragma_model_trafo)
694
695 kernel_item = scheduler['kernel_mod#kernel']
696 kernel2_item = scheduler['kernel_mod#kernel2']
697
698 # set kind comaprison string
699 if frontend == OMNI:
700 kind_real = 'selected_real_kind(13, 300)'
701 kind_int = '4'
702 kind_log = '4'
703 else:
704 kind_real = 'jprb'
705 kind_int = 'jpim'
706 kind_log = 'jplm'
707
708 assert transformation._key in kernel_item.trafo_data
709 exp_stack_size_str = (
710 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*klon, -3)'
711 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*klev*klon, -3)'
712 f' + ishft(7 + 2*c_sizeof(int(1, kind={kind_int}))*klon, -3)'
713 f' + ishft(7 + c_sizeof(logical(true, kind={kind_log}))*klev, -3)'
714 )
715 exp_stack_size = parse_expr(exp_stack_size_str )
716 assert kernel_item.trafo_data[transformation._key]['stack_size'] == exp_stack_size
717 exp_stack_size_str = (
718 f'ishft(7 + 2*c_sizeof(real(1, kind={kind_real}))*klev*klon, -3)'
719 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))'
720 f' + c_sizeof(real(1, kind={kind_real}))*klon'
721 f' + c_sizeof(real(1, kind={kind_real}))*klev'
722 f' + c_sizeof(real(1, kind={kind_real}))*klev*klon, -3)'
723 )
724
725 exp_stack_size = parse_expr(exp_stack_size_str)
726 assert kernel2_item.trafo_data[transformation._key]['stack_size'] == exp_stack_size
727 assert all(
728 v.scope is None
729 for v in FindVariables().visit(kernel_item.trafo_data[transformation._key]['stack_size'])
730 )
731 assert all(
732 v.scope is None
733 for v in FindVariables().visit(kernel2_item.trafo_data[transformation._key]['stack_size'])
734 )
735
736 #
737 # A few checks on the driver
738 #
739 driver = scheduler['#driver'].ir
740
741 stack_order = FindNodes(ir.Assignment).visit(driver.body)
742 if stack_insert_pragma:
743 assert stack_order[0].lhs == "a"
744 else:
745 assert stack_order[0].lhs == "ISTSZ"
746
747 # Check if allocation type symbols have been imported
748 if frontend != OMNI:
749 assert 'jpim' in driver.imported_symbols
750 assert 'jplm' in driver.imported_symbols
751 assert driver.import_map['jpim'] == driver.import_map['jplm']
752 assert 'jprb' not in driver.import_map['jpim'].symbols
753
754 # Has the stack been added to the call statements?
755 calls = FindNodes(ir.CallStatement).visit(driver.body)
756 expected_kwarguments = (('YDSTACK_L', 'ylstack_l'), ('YDSTACK_U', 'ylstack_U'))
757 if cray_ptr_loc_rhs:
758 expected_kwarguments += (('ZSTACK', 'zstack(:,b)'),)
759 assert len(calls) == 2
760 assert calls[0].arguments == ('1', 'nlon', 'nlon', 'nz', 'field1(:,b)', 'field2(:,:,b)')
761 assert calls[0].kwarguments == expected_kwarguments
762 assert calls[1].arguments == ('1', 'nlon', 'nlon', 'nz', 'field2(:,:,b)')
763 assert calls[1].kwarguments == expected_kwarguments
764
765 stack_size_str = (
766 f'max(ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3)'
767 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
768 f' + ishft(7 + 2*c_sizeof(int(1, kind={kind_int}))*nlon, -3)'
769 f' + ishft(7 + c_sizeof(logical(true, kind={kind_log}))*nz, -3),'
770 f' ishft(7 + 2*c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
771 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))'
772 f' + c_sizeof(real(1, kind={kind_real}))*nlon'
773 f' + c_sizeof(real(1, kind={kind_real}))*nz'
774 f' + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3))'
775 )
776 stack_size = parse_expr(stack_size_str)
777
778 check_stack_created_in_driver(driver, stack_size, calls[0], 2, cray_ptr_loc_rhs=cray_ptr_loc_rhs)
779
780 # Has the data sharing been updated?
781 if directive in ['openmp', 'openacc']:
782 keyword = {'openmp': 'omp', 'openacc': 'acc'}[directive]
783 pragmas = [
784 p for p in FindNodes(ir.Pragma).visit(driver.body)
785 if p.keyword.lower() == keyword and p.content.startswith('parallel')
786 ]
787 assert len(pragmas) == 2
788 for pragma in pragmas:
789 parameters = get_pragma_parameters(pragma, starts_with='parallel', only_loki_pragmas=False)
790 assert 'private' in parameters and 'ylstack' in parameters['private'].lower()
791 assert not 'ylstack' in parameters['firstprivate'].lower()
792
793 # Are there data regions for the stack?
794 if directive == ['openacc']:
795 pragmas = [
796 p for p in FindNodes(ir.Pragma).visit(driver.body)
797 if p.keyword.lower() == 'acc' and 'data' in p.content
798 ]
799 assert len(pragmas) == 2
800 parameters = get_pragma_parameters(pragmas[0], starts_with='data', only_loki_pragmas=False)
801 assert parameters['create'] == 'zstack'
802
803 #
804 # A few checks on the kernel
805 #
806 for count, item in enumerate([kernel_item, kernel2_item]):
807 kernel = item.ir
808
809 # Has the stack been added to the arguments?
810 assert 'ydstack_l' in kernel.arguments
811 assert 'ydstack_u' in kernel.arguments
812
813 # Is it being assigned to a local variable?
814 assert 'ylstack_l' in kernel.variables
815 assert 'ylstack_u' in kernel.variables
816
817 dim1 = f"{kernel.variable_map['tmp1'].shape[0]}"
818 for v in kernel.variable_map['tmp1'].shape[1:]:
819 dim1 += f'*{v}'
820 # tmp2 has the shape "0:klon, 0:klev"
821 dim2 = kernel.variable_map['tmp2'].shape[0]
822 if isinstance(dim2, RangeIndex):
823 dim2 = Sum((dim2.upper, Product((-1, dim2.lower)), 1))
824 for v in kernel.variable_map['tmp2'].shape[1:]:
825 _dim = v
826 if isinstance(_dim, RangeIndex):
827 _dim = Sum((_dim.upper, Product((-1, _dim.lower)), 1))
828 dim2 = Product((dim2, _dim))
829
830 if cray_ptr_loc_rhs:
831 exp_rhs_1 = parse_expr(f'ylstack_l + ishft({dim1}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3)')
832 exp_rhs_2 = parse_expr(f'ylstack_l + ishft({dim2}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3)')
833 else:
834 exp_rhs_1 = parse_expr(f'ylstack_l + ishft(ishft({dim1}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3), 3)')
835 exp_rhs_2 = parse_expr(f'ylstack_l + ishft(ishft({dim2}*C_SIZEOF(REAL(1, kind={kind_real})) + 7, -3), 3)')
836
837 # Let's check for the relevant "allocations" happening in the right order
838 assign_idx = {}
839 for idx, ass in enumerate(FindNodes(ir.Assignment).visit(kernel.body)):
840
841 if ass.lhs == 'ylstack_l' and ass.rhs == 'ydstack_l':
842 # Local copy of stack status
843 assign_idx['stack_assign'] = idx
844 elif ass.lhs == 'ylstack_u' and ass.rhs == 'ydstack_u':
845 # Local copy of stack status
846 assign_idx['stack_assign_end'] = idx
847 elif ass.lhs == 'ip_tmp1':
848 # ass Cray pointer for tmp1
849 assign_idx['tmp1_ptr_assign'] = idx
850 elif ass.lhs == 'ip_tmp2':
851 # ass Cray pointer for tmp2
852 assign_idx['tmp2_ptr_assign'] = idx
853 elif ass.lhs == 'ylstack_l' and 'ylstack_l' in ass.rhs and ass.rhs == exp_rhs_1:
854 # Stack increment for tmp1
855 assign_idx['tmp1_stack_incr'] = idx
856 elif ass.lhs == 'ylstack_l' and 'ylstack_l' in ass.rhs and ass.rhs == exp_rhs_2:
857 # Stack increment for tmp2
858 assign_idx['tmp2_stack_incr'] = idx
859
860 expected_assign_in_order = [
861 'stack_assign', 'stack_assign_end', 'tmp1_ptr_assign', 'tmp1_stack_incr', 'tmp2_ptr_assign',
862 'tmp2_stack_incr'
863 ]
864 assert set(expected_assign_in_order) == set(assign_idx.keys())
865
866 for assign1, assign2 in zip(expected_assign_in_order, expected_assign_in_order[1:]):
867 assert assign_idx[assign2] > assign_idx[assign1]
868
869 # Check for pointer declarations in generated code
870 fcode = kernel.to_fortran()
871 assert 'pointer(ip_tmp1, tmp1)' in fcode.lower()
872 assert 'pointer(ip_tmp2, tmp2)' in fcode.lower()
873
874 # Check for stack size safegurads in generated code
875 if count == 0:
876 assert fcode.lower().count('if (ylstack_l > ylstack_u)') == 4
877 assert fcode.lower().count('stop') == 4
878 else:
879 assert fcode.lower().count('if (ylstack_l > ylstack_u)') == 2
880 assert fcode.lower().count('stop') == 2
881
882
883 @pytest.mark.parametrize('frontend', available_frontends())
884 @pytest.mark.parametrize('directive', [False, 'openmp', 'openacc'])
885 @pytest.mark.parametrize('cray_ptr_loc_rhs', [False, True])
886 def test_pool_allocator_temporaries_kernel_nested(tmp_path, frontend, block_dim, directive, cray_ptr_loc_rhs):
887 driver_pragma = f'!$loki loop gang{" private(b)" if directive == "openmp" else ""}'
888 driver_end_pragma = '!$loki end loop gang'
889 kernel_pragma = '!$loki routine vector'
890
891 fcode_parkind_mod = """
892 module parkind1
893 implicit none
894 integer, parameter :: jwrb = selected_real_kind(13,300)
895 integer, parameter :: jpim = selected_int_kind(9)
896 integer, parameter :: jplm = jpim
897 end module parkind1
898 """.strip()
899
900 fcode_driver = f"""
901 subroutine driver(NLON, NZ, NB, FIELD1, FIELD2)
902 use kernel_mod, only: kernel
903 use parkind1, only : jpim
904 implicit none
905 INTEGER, PARAMETER :: JWRB = SELECTED_REAL_KIND(13,300)
906 INTEGER, INTENT(IN) :: NLON, NZ, NB
907 real(kind=jwrb), intent(inout) :: field1(nlon, nb)
908 real(kind=jwrb), intent(inout) :: field2(nlon, nz, nb)
909 integer :: b
910 {driver_pragma}
911 do b=1,nb
912 call KERNEL(1, nlon, nlon, nz, field1(:,b), field2(:,:,b))
913 end do
914 {driver_end_pragma}
915 end subroutine driver
916 """.strip()
917 fcode_kernel = f"""
918 module kernel_mod
919 implicit none
920 contains
921 subroutine kernel(start, end, klon, klev, field1, field2)
922 use parkind1, only : jpim, jplm
923 implicit none
924 integer, parameter :: jwrb = selected_real_kind(13,300)
925 integer, intent(in) :: start, end, klon, klev
926 real(kind=jwrb), intent(inout) :: field1(klon)
927 real(kind=jwrb), intent(inout) :: field2(klon,klev)
928 real(kind=jwrb) :: tmp1(klon)
929 real(kind=jwrb) :: tmp2(klon, klev)
930 integer(kind=jpim) :: tmp3(klon*2)
931 logical(kind=jplm) :: tmp4(klev)
932 integer :: jk, jl
933 {kernel_pragma}
934
935 do jk=1,klev
936 tmp1(jl) = 0.0_jwrb
937 do jl=start,end
938 tmp2(jl, jk) = field2(jl, jk)
939 tmp1(jl) = field2(jl, jk)
940 end do
941 field1(jl) = tmp1(jl)
942 tmp4(jk) = .true.
943 end do
944
945 do jl=start,end
946 tmp3(jl) = 1_jpim
947 tmp3(jl+klon) = 1_jpim
948 enddo
949
950 call kernel2(start, end, klon, klev, field2)
951 end subroutine kernel
952
953 subroutine kernel2(start, end, columns, levels, field2)
954 implicit none
955 integer, parameter :: jwrb = selected_real_kind(13,300)
956 integer, intent(in) :: start, end, columns, levels
957 real(kind=jwrb), intent(inout) :: field2(columns,levels)
958 real(kind=jwrb) :: tmp1(2*columns, levels), tmp2(columns, levels)
959 integer :: jk, jl
960 {kernel_pragma}
961
962 do jk=1,levels
963 do jl=start,end
964 tmp1(jl, jk) = field2(jl, jk)
965 tmp1(jl+columns, jk) = field2(jl, jk)*2._jwrb
966 tmp2(jl, jk) = tmp1(jl, jk) + 1._jwrb
967 field2(jl, jk) = tmp2(jl, jk)
968 end do
969 end do
970 end subroutine kernel2
971
972 end module kernel_mod
973 """.strip()
974
975 (tmp_path/'driver.F90').write_text(fcode_driver)
976 (tmp_path/'kernel_mod.F90').write_text(fcode_kernel)
977 (tmp_path/'parkind_mod.F90').write_text(fcode_parkind_mod)
978
979 config = {
980 'default': {
981 'mode': 'idem',
982 'role': 'kernel',
983 'expand': True,
984 'strict': True,
985 'enable_imports': True,
986 },
987 'routines': {
988 # real_kind = jwrb has no (and should have no) effect anymore as
989 # 'real64' as kind of the stack is baked into the recipe
990 'driver': {'role': 'driver', 'real_kind': 'jwrb'}
991 }
992 }
993
994 scheduler = Scheduler(
995 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
996 frontend=frontend, xmods=[tmp_path]
997 )
998
999 transformation = TemporariesPoolAllocatorTransformation(block_dim=block_dim,
1000 directive=directive, cray_ptr_loc_rhs=cray_ptr_loc_rhs)
1001 scheduler.process(transformation=transformation)
1002 pragma_model_trafo = PragmaModelTransformation(directive=directive)
1003 scheduler.process(transformation=pragma_model_trafo)
1004
1005 kernel_item = scheduler['kernel_mod#kernel']
1006 kernel2_item = scheduler['kernel_mod#kernel2']
1007
1008 # set kind comaprison string
1009 if frontend == OMNI:
1010 kind_real = 'selected_real_kind(13, 300)'
1011 kind_int = '4'
1012 kind_log = '4'
1013 else:
1014 kind_real = 'jwrb'
1015 kind_int = 'jpim'
1016 kind_log = 'jplm'
1017
1018 assert transformation._key in kernel_item.trafo_data
1019 exp_stack_size_str = (
1020 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*klon, -3)'
1021 f' + 2*ishft(7 + c_sizeof(real(1, kind={kind_real}))*klev*klon, -3)'
1022 f' + ishft(7 + 2*c_sizeof(int(1, kind={kind_int}))*klon, -3)'
1023 f' + ishft(7 + c_sizeof(logical(true, kind={kind_log}))*klev, -3)'
1024 f' + ishft(7 + 2*c_sizeof(real(1, kind={kind_real}))*klev*klon, -3)'
1025 )
1026 exp_stack_size = parse_expr(exp_stack_size_str)
1027 assert kernel_item.trafo_data[transformation._key]['stack_size'] == exp_stack_size
1028 exp_stack_size_str = (
1029 f'ishft(7 + 2*c_sizeof(real(1, kind={kind_real}))*columns*levels, -3)'
1030 f' + ishft(7 + c_sizeof(real(1, kind={kind_real}))*columns*levels, -3)'
1031 )
1032 exp_stack_size = parse_expr(exp_stack_size_str)
1033 assert kernel2_item.trafo_data[transformation._key]['stack_size'] == exp_stack_size
1034 assert all(
1035 v.scope is None
1036 for v in FindVariables().visit(kernel_item.trafo_data[transformation._key]['stack_size'])
1037 )
1038 assert all(
1039 v.scope is None
1040 for v in FindVariables().visit(kernel2_item.trafo_data[transformation._key]['stack_size'])
1041 )
1042
1043 #
1044 # A few checks on the driver
1045 #
1046 driver = scheduler['#driver'].ir
1047
1048 # Check if allocation type symbols have been imported
1049 if frontend != OMNI:
1050 assert 'jpim' in driver.imported_symbols
1051 assert 'jplm' in driver.imported_symbols
1052 assert driver.import_map['jpim'] == driver.import_map['jplm']
1053
1054 # Has the stack been added to the call statements?
1055 calls = FindNodes(ir.CallStatement).visit(driver.body)
1056 expected_kwarguments = (('YDSTACK_L', 'ylstack_l'), ('YDSTACK_U', 'ylstack_u'))
1057 if cray_ptr_loc_rhs:
1058 expected_kwarguments += (('ZSTACK', 'zstack(:,b)'),)
1059 assert len(calls) == 1
1060 assert calls[0].arguments == ('1', 'nlon', 'nlon', 'nz', 'field1(:,b)', 'field2(:,:,b)')
1061 assert calls[0].kwarguments == expected_kwarguments
1062
1063 stack_size_str = (
1064 f'ishft(7 + c_sizeof(real(1, kind={kind_real}))*nlon, -3)'
1065 f' + 2*ishft(7 + c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
1066 f' + ishft(7 + 2*c_sizeof(int(1, kind={kind_int}))*nlon, -3)'
1067 f' + ishft(7 + c_sizeof(logical(true, kind={kind_log}))*nz, -3)'
1068 f' + ishft(7 + 2*c_sizeof(real(1, kind={kind_real}))*nz*nlon, -3)'
1069 )
1070 stack_size = parse_expr(stack_size_str)
1071 check_stack_created_in_driver(
1072 driver, stack_size, calls[0], 1,
1073 cray_ptr_loc_rhs=cray_ptr_loc_rhs
1074 )
1075
1076 # check if stack allocatable in the driver has the correct kind parameter
1077 if not frontend == OMNI:
1078 assert driver.symbol_map['zstack'].type.kind == 'real64'
1079
1080 # Has the data sharing been updated?
1081 if directive in ['openmp', 'openacc']:
1082 keyword = {'openmp': 'omp', 'openacc': 'acc'}[directive]
1083 pragmas = [
1084 p for p in FindNodes(ir.Pragma).visit(driver.body)
1085 if p.keyword.lower() == keyword and p.content.startswith('parallel')
1086 ]
1087 assert len(pragmas) == 1
1088 for pragma in pragmas:
1089 parameters = get_pragma_parameters(pragma, starts_with='parallel', only_loki_pragmas=False)
1090 assert 'private' in parameters and 'ylstack' in parameters['private'].lower()
1091 if directive == 'openmp':
1092 assert 'b' in parameters['private']
1093
1094 # Are there data regions for the stack?
1095 if directive == ['openacc']:
1096 pragmas = [
1097 p for p in FindNodes(ir.Pragma).visit(driver.body)
1098 if p.keyword.lower() == 'acc' and 'data' in p.content
1099 ]
1100 assert len(pragmas) == 2
1101 parameters = get_pragma_parameters(pragmas[0], starts_with='data', only_loki_pragmas=False)
1102 assert parameters['create'] == 'zstack'
1103
1104 #
1105 # A few checks on the kernels
1106 #
1107 calls = FindNodes(ir.CallStatement).visit(kernel_item.ir.body)
1108 expected_kwarguments = (('YDSTACK_L', 'ylstack_l'), ('YDSTACK_U', 'ylstack_u'))
1109 if cray_ptr_loc_rhs:
1110 expected_kwarguments += (('ZSTACK', 'zstack'),)
1111 assert len(calls) == 1
1112 assert calls[0].arguments == ('start', 'end', 'klon', 'klev', 'field2')
1113 assert calls[0].kwarguments == expected_kwarguments
1114
1115 for count, item in enumerate([kernel_item, kernel2_item]):
1116 kernel = item.ir
1117
1118 # Has the stack been added to the arguments?
1119 assert 'ydstack_l' in kernel.arguments
1120 assert 'ydstack_u' in kernel.arguments
1121
1122 # Is it being assigned to a local variable?
1123 assert 'ylstack_l' in kernel.variables
1124 assert 'ylstack_u' in kernel.variables
1125
1126 dim1 = f"{kernel.variable_map['tmp1'].shape[0]}"
1127 for v in kernel.variable_map['tmp1'].shape[1:]:
1128 dim1 += f'*{v}'
1129 dim2 = f"{kernel.variable_map['tmp2'].shape[0]}"
1130 for v in kernel.variable_map['tmp2'].shape[1:]:
1131 dim2 += f'*{v}'
1132
1133 if cray_ptr_loc_rhs:
1134 exp_rhs_1 = parse_expr(f'ylstack_l + ishft({dim1}*c_sizeof(real(1, kind={kind_real})) + 7, -3)')
1135 else:
1136 exp_rhs_1 = parse_expr(f'ylstack_l + ishft(ishft({dim1}*c_sizeof(real(1, kind={kind_real})) + 7, -3), 3)')
1137 if cray_ptr_loc_rhs:
1138 exp_rhs_2 = parse_expr(f'ylstack_l + ishft({dim2}*c_sizeof(real(1, kind={kind_real})) + 7, -3)')
1139 else:
1140 exp_rhs_2 = parse_expr(f'ylstack_l + ishft(ishft({dim2}*c_sizeof(real(1, kind={kind_real})) + 7, -3), 3)')
1141
1142 # Let's check for the relevant "allocations" happening in the right order
1143 assign_idx = {}
1144 for idx, ass in enumerate(FindNodes(ir.Assignment).visit(kernel.body)):
1145
1146 if ass.lhs == 'ylstack_l' and ass.rhs == 'ydstack_l':
1147 # Local copy of stack status
1148 assign_idx['stack_assign'] = idx
1149 if ass.lhs == 'ylstack_u' and ass.rhs == 'ydstack_u':
1150 # Local copy of stack status
1151 assign_idx['stack_assign_end'] = idx
1152 elif ass.lhs == 'ip_tmp1': # and ass.rhs == 'ylstack_l':
1153 # ass Cray pointer for tmp1
1154 assign_idx['tmp1_ptr_assign'] = idx
1155 elif ass.lhs == 'ip_tmp2': # and ass.rhs == 'ylstack_l':
1156 # ass Cray pointer for tmp2
1157 assign_idx['tmp2_ptr_assign'] = idx
1158 elif ass.lhs == 'ylstack_l' and 'ylstack_l' in ass.rhs and simplify(ass.rhs) == simplify(exp_rhs_1):
1159 # Stack increment for tmp1
1160 assign_idx['tmp1_stack_incr'] = idx
1161 elif ass.lhs == 'ylstack_l' and 'ylstack_l' in ass.rhs and simplify(ass.rhs) == simplify(exp_rhs_2):
1162 # Stack increment for tmp2
1163 assign_idx['tmp2_stack_incr'] = idx
1164
1165 expected_assign_in_order = [
1166 'stack_assign', 'stack_assign_end', 'tmp1_ptr_assign', 'tmp1_stack_incr', 'tmp2_ptr_assign',
1167 'tmp2_stack_incr'
1168 ]
1169 assert set(expected_assign_in_order) == set(assign_idx.keys())
1170
1171 for assign1, assign2 in zip(expected_assign_in_order, expected_assign_in_order[1:]):
1172 assert assign_idx[assign2] > assign_idx[assign1]
1173
1174 # Check for pointer declarations in generated code
1175 fcode = kernel.to_fortran()
1176 assert 'pointer(ip_tmp1, tmp1)' in fcode.lower()
1177 assert 'pointer(ip_tmp2, tmp2)' in fcode.lower()
1178
1179 # Check for stack size safegurads in generated code
1180 if count == 0:
1181 assert fcode.lower().count('if (ylstack_l > ylstack_u)') == 4
1182 assert fcode.lower().count('stop') == 4
1183 else:
1184 assert fcode.lower().count('if (ylstack_l > ylstack_u)') == 2
1185 assert fcode.lower().count('stop') == 2
1186
1187
1188 @pytest.mark.parametrize('frontend', available_frontends())
1189 @pytest.mark.parametrize('cray_ptr_loc_rhs', [False, True])
1190 def test_pool_allocator_more_call_checks(tmp_path, frontend, block_dim, caplog, cray_ptr_loc_rhs, horizontal):
1191 fcode = """
1192 module kernel_mod
1193 type point
1194 real :: x
1195 real :: y
1196 real :: z
1197 end type point
1198 contains
1199 real function inline_kernel(jl)
1200 integer, intent(in) :: jl
1201 end function inline_kernel
1202 subroutine optional_arg(klon, temp1, temp2)
1203 integer, intent(in) :: klon
1204 real, intent(inout) :: temp1
1205 real, intent(out), optional :: temp2
1206 end subroutine optional_arg
1207 subroutine kernel(start, end, klon, field1)
1208 implicit none
1209
1210 interface
1211 real function inline_kernel(jl)
1212 integer, intent(in) :: jl
1213 end function inline_kernel
1214 end interface
1215
1216 integer, intent(in) :: start, end, klon
1217 real, intent(inout) :: field1(klon)
1218 real :: temp1(klon)
1219 real :: temp2(klon)
1220 type(point) :: p(klon)
1221
1222 integer :: jl
1223
1224 do jl=start,end
1225 field1(jl) = inline_kernel(jl)
1226 p(jl)%x = 0.
1227 p(jl)%y = 0.
1228 p(jl)%z = 0.
1229 end do
1230
1231 call optional_arg(klon, temp1, temp2)
1232 end subroutine kernel
1233 end module kernel_mod
1234 """.strip()
1235
1236 (tmp_path/'kernel.F90').write_text(fcode)
1237
1238 config = {
1239 'default': {
1240 'mode': 'idem',
1241 'role': 'kernel',
1242 'expand': True,
1243 'strict': True,
1244 'enable_imports': True,
1245 },
1246 'routines': {
1247 'kernel': {}
1248 }
1249 }
1250 scheduler = Scheduler(
1251 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
1252 seed_routines=['kernel'],
1253 frontend=frontend, xmods=[tmp_path]
1254 )
1255
1256 transformation = TemporariesPoolAllocatorTransformation(block_dim=block_dim, horizontal=horizontal,
1257 cray_ptr_loc_rhs=cray_ptr_loc_rhs)
1258 scheduler.process(transformation=transformation)
1259 pragma_model_trafo = PragmaModelTransformation()
1260 scheduler.process(transformation=pragma_model_trafo)
1261
1262 item = scheduler['kernel_mod#kernel']
1263 kernel = item.ir
1264
1265 # Has the stack been added to the arguments?
1266 assert 'ydstack_l' in kernel.arguments
1267 assert 'ydstack_u' in kernel.arguments
1268
1269 # Is it being assigned to a local variable?
1270 assert 'ylstack_l' in kernel.variables
1271 assert 'ylstack_u' in kernel.variables
1272
1273 # Has the stack been added to the call statement at the correct location?
1274 calls = FindNodes(ir.CallStatement).visit(kernel.body)
1275 expected_kwarguments = (('YDSTACK_L', 'ylstack_l'), ('YDSTACK_U', 'ylstack_u'))
1276 if cray_ptr_loc_rhs:
1277 expected_kwarguments += (('ZSTACK', 'zstack'),)
1278 assert len(calls) == 1
1279 assert calls[0].arguments == ('klon', 'temp1', 'temp2')
1280 assert calls[0].kwarguments == expected_kwarguments
1281
1282 # Now repeat the checks for the inline call
1283 calls = [i for i in FindInlineCalls().visit(kernel.body) if not i.name.lower() in ('max', 'c_sizeof', 'real')]
1284 # filter out ishft inline calls being part of the stack size calculation
1285 calls = [call for call in calls if str(call.name).lower() != 'ishft']
1286 if cray_ptr_loc_rhs:
1287 assert len(calls) == 2
1288 if calls[0].name == 'inline_kernel':
1289 relevant_call = calls[0]
1290 else:
1291 relevant_call = calls[1]
1292 else:
1293 assert len(calls) == 1
1294 relevant_call = calls[0]
1295 assert relevant_call.arguments == ('jl',)
1296 assert relevant_call.kwarguments == expected_kwarguments
1297
1298 assert 'Derived-type vars in Subroutine:: kernel not supported in pool allocator' in caplog.text
1299
1300
1301 @pytest.mark.parametrize('frontend', available_frontends())
1302 @pytest.mark.parametrize('cray_ptr_loc_rhs', [False, True])
1303 def test_pool_allocator_args_vs_kwargs(tmp_path, frontend, block_dim_alt, cray_ptr_loc_rhs, horizontal):
1304 fcode_parkind_mod = """
1305 module parkind1
1306 implicit none
1307 integer, parameter :: jwrb = selected_real_kind(13,300)
1308 integer, parameter :: jpim = selected_int_kind(9)
1309 integer, parameter :: jplm = jpim
1310 end module parkind1
1311 """.strip()
1312
1313 fcode_module = """
1314 module geom_mod
1315 implicit none
1316 type dim_type
1317 integer :: nb
1318 end type dim_type
1319
1320 type geom_type
1321 type(dim_type) :: blk_dim
1322 end type geom_type
1323
1324 integer :: n
1325 end module geom_mod
1326 """
1327
1328 fcode_driver = """
1329 subroutine driver(NLON, NZ, GEOM, FIELD1, FIELD2)
1330 use kernel_mod, only: kernel, kernel2
1331 use parkind1, only : jpim
1332 use geom_mod, only : geom_type
1333 implicit none
1334 INTEGER, PARAMETER :: JWRB = SELECTED_REAL_KIND(13,300)
1335 INTEGER, INTENT(IN) :: NLON, NZ
1336 type(geom_type), intent(in) :: geom
1337 real(kind=jwrb), intent(inout) :: field1(nlon, geom%blk_dim%nb)
1338 real(kind=jwrb), intent(inout) :: field2(nlon, nz, geom%blk_dim%nb)
1339 integer :: b
1340 real(kind=jwrb) :: opt
1341 do b=1,geom%blk_dim%nb
1342 call KERNEL(start=1, end=nlon, klon=nlon, klev=nz, field1=field1(:,b), field2=field2(:,:,b))
1343 call KERNEL2(1, nlon, nlon, nz, field2=field2(:,:,b))
1344 call KERNEL2(1, nlon, nlon, nz, field2(:,:,b))
1345 call KERNEL2(1, nlon, nlon, nz, field2=field2(:,:,b), opt_arg=opt)
1346 call KERNEL2(1, nlon, nlon, nz, field2(:,:,b), opt)
1347 end do
1348 end subroutine driver
1349 """.strip()
1350
1351 fcode_kernel = """
1352 module kernel_mod
1353 implicit none
1354 contains
1355 subroutine kernel(start, end, klon, klev, field1, field2)
1356 use parkind1, only : jpim, jplm
1357 use geom_mod, only : n
1358 implicit none
1359 integer, parameter :: jwrb = selected_real_kind(13,300)
1360 integer, intent(in) :: start, end, klon, klev
1361 real(kind=jwrb), intent(inout) :: field1(klon)
1362 real(kind=jwrb), intent(inout) :: field2(klon,klev)
1363 real(kind=jwrb) :: tmp1(klon)
1364 real(kind=jwrb) :: tmp2(klon, klev)
1365 integer(kind=jpim) :: tmp3(klon*2)
1366 logical(kind=jplm) :: tmp4(klev)
1367 logical(kind=jplm) :: tmp5(klev,n)
1368 integer :: jk, jl
1369
1370 do jk=1,klev
1371 tmp1(jl) = 0.0_jwrb
1372 do jl=start,end
1373 tmp2(jl, jk) = field2(jl, jk)
1374 tmp1(jl) = field2(jl, jk)
1375 end do
1376 field1(jl) = tmp1(jl)
1377 tmp4(jk) = .true.
1378 tmp5(jk,1:n) = .true.
1379 end do
1380
1381 do jl=start,end
1382 tmp3(jl) = 1_jpim
1383 tmp3(jl+klon) = 1_jpim
1384 enddo
1385
1386 call kernel2(start, end, klon, klev, field2)
1387 end subroutine kernel
1388 subroutine kernel2(start, end, columns, levels, field2, opt_arg)
1389 implicit none
1390 integer, parameter :: jwrb = selected_real_kind(13,300)
1391 integer, intent(in) :: start, end, columns, levels
1392 real(kind=jwrb), intent(inout) :: field2(columns,levels)
1393 real(kind=jwrb) :: tmp1(2*columns, levels), tmp2(columns, levels)
1394 real(kind=jwrb), optional :: opt_arg
1395 integer :: jk, jl
1396
1397 do jk=1,levels
1398 do jl=start,end
1399 tmp1(jl, jk) = field2(jl, jk)
1400 tmp1(jl+columns, jk) = field2(jl, jk)*2._jwrb
1401 tmp2(jl, jk) = tmp1(jl, jk) + 1._jwrb
1402 field2(jl, jk) = tmp2(jl, jk)
1403 end do
1404 end do
1405 end subroutine kernel2
1406
1407 end module kernel_mod
1408 """.strip()
1409
1410 (tmp_path / 'parkind1.F90').write_text(fcode_parkind_mod)
1411 (tmp_path / 'driver.F90').write_text(fcode_driver)
1412 (tmp_path / 'kernel.F90').write_text(fcode_kernel)
1413 (tmp_path / 'module.F90').write_text(fcode_module)
1414
1415 config = {
1416 'default': {
1417 'mode': 'idem',
1418 'role': 'kernel',
1419 'expand': True,
1420 'strict': True,
1421 'ignore': ['parkind1'],
1422 'enable_imports': True,
1423 },
1424 'routines': {
1425 'driver': {'role': 'driver'}
1426 }
1427 }
1428 scheduler = Scheduler(
1429 paths=[tmp_path], config=SchedulerConfig.from_dict(config),
1430 frontend=frontend, xmods=[tmp_path]
1431 )
1432
1433 transformation = TemporariesPoolAllocatorTransformation(block_dim=block_dim_alt, horizontal=horizontal,
1434 cray_ptr_loc_rhs=cray_ptr_loc_rhs)
1435 scheduler.process(transformation=transformation)
1436 pragma_model_trafo = PragmaModelTransformation()
1437 scheduler.process(transformation=pragma_model_trafo)
1438
1439 kernel = scheduler['kernel_mod#kernel'].ir
1440 kernel2 = scheduler['kernel_mod#kernel2'].ir
1441 driver = scheduler['#driver'].ir
1442
1443 assert 'ydstack_l' in kernel.arguments
1444 assert 'ydstack_u' in kernel.arguments
1445 assert 'ydstack_l' in kernel2.arguments
1446 assert 'ydstack_u' in kernel2.arguments
1447
1448 calls = FindNodes(ir.CallStatement).visit(driver.body)
1449 additional_kwargs = (('ZSTACK', 'zstack(:,b)'),) if cray_ptr_loc_rhs else ()
1450 assert calls[0].arguments == ()
1451 assert calls[0].kwarguments == (
1452 ('start', 1), ('end', 'nlon'), ('klon', 'nlon'), ('klev', 'nz'),
1453 ('field1', 'field1(:, b)'), ('field2', 'field2(:, :, b)'),
1454 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1455 ) + additional_kwargs
1456 assert calls[1].arguments == ('1', 'nlon', 'nlon', 'nz')
1457 assert calls[1].kwarguments == (
1458 ('field2', 'field2(:, :, b)'), ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1459 ) + additional_kwargs
1460 assert calls[2].arguments == ('1', 'nlon', 'nlon', 'nz', 'field2(:, :, b)')
1461 assert calls[2].kwarguments == (
1462 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1463 ) + additional_kwargs
1464 assert calls[3].arguments == ('1', 'nlon', 'nlon', 'nz')
1465 assert calls[3].kwarguments == (
1466 ('field2', 'field2(:, :, b)'), ('opt_arg', 'opt'),
1467 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1468 ) + additional_kwargs
1469 assert calls[4].arguments == ('1', 'nlon', 'nlon', 'nz', 'field2(:, :, b)', 'opt')
1470 assert calls[2].arguments == ('1', 'nlon', 'nlon', 'nz', 'field2(:, :, b)')
1471 assert calls[2].kwarguments == (
1472 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1473 ) + additional_kwargs
1474 assert calls[3].arguments == ('1', 'nlon', 'nlon', 'nz')
1475 assert calls[3].kwarguments == (
1476 ('field2', 'field2(:, :, b)'), ('opt_arg', 'opt'),
1477 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1478 ) + additional_kwargs
1479 assert calls[4].arguments == ('1', 'nlon', 'nlon', 'nz', 'field2(:, :, b)', 'opt')
1480 assert calls[4].kwarguments == (
1481 ('YDSTACK_L', 'YLSTACK_L'), ('YDSTACK_U', 'YLSTACK_U')
1482 ) + additional_kwargs
1483
1484 # check stack size allocation
1485 allocations = FindNodes(ir.Allocation).visit(driver.body)
1486 assert len(allocations) == 1 and 'zstack(istsz,geom%blk_dim%nb)' in allocations[0].variables
1487
1488 # check that array size was imported to the driver
1489 assert 'n' in driver.imported_symbols