-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathKernel.java
More file actions
3882 lines (3523 loc) · 171 KB
/
Copy pathKernel.java
File metadata and controls
3882 lines (3523 loc) · 171 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2016 - 2018 Syncleus, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Copyright (c) 2010-2011, Advanced Micro Devices, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export
laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through
774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR,
you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of
Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration
Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1,
E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups
D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject
to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774
of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations
under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/.
*/
package com.aparapi;
import com.aparapi.annotation.Experimental;
import com.aparapi.exception.QueryFailedException;
import com.aparapi.internal.model.CacheEnabler;
import com.aparapi.internal.model.ClassModel.ConstantPool.MethodReferenceEntry;
import com.aparapi.internal.model.ClassModel.ConstantPool.NameAndTypeEntry;
import com.aparapi.internal.model.ValueCache;
import com.aparapi.internal.model.ValueCache.ThrowingValueComputer;
import com.aparapi.internal.model.ValueCache.ValueComputer;
import com.aparapi.internal.opencl.OpenCLLoader;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinPool.ManagedBlocker;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntBinaryOperator;
import java.util.logging.Logger;
import com.aparapi.device.Device;
import com.aparapi.device.JavaDevice;
import com.aparapi.device.OpenCLDevice;
import com.aparapi.exception.CompileFailedException;
import com.aparapi.internal.kernel.IKernelBarrier;
import com.aparapi.internal.kernel.KernelArg;
import com.aparapi.internal.kernel.KernelDeviceProfile;
import com.aparapi.internal.kernel.KernelManager;
import com.aparapi.internal.kernel.KernelProfile;
import com.aparapi.internal.kernel.KernelRunner;
import com.aparapi.internal.util.Reflection;
import com.aparapi.internal.util.UnsafeWrapper;
/**
* A <i>kernel</i> encapsulates a data parallel algorithm that will execute either on a GPU
* (through conversion to OpenCL) or on a CPU via a Java Thread Pool.
* <p>
* To write a new kernel, a developer extends the <code>Kernel</code> class and overrides the <code>Kernel.run()</code> method.
* To execute this kernel, the developer creates a new instance of it and calls <code>Kernel.execute(int globalSize)</code> with a suitable 'global size'. At runtime
* Aparapi will attempt to convert the <code>Kernel.run()</code> method (and any method called directly or indirectly
* by <code>Kernel.run()</code>) into OpenCL for execution on GPU devices made available via the OpenCL platform.
* <p>
* Note that <code>Kernel.run()</code> is not called directly. Instead,
* the <code>Kernel.execute(int globalSize)</code> method will cause the overridden <code>Kernel.run()</code>
* method to be invoked once for each value in the range <code>0...globalSize</code>.
* <p>
* On the first call to <code>Kernel.execute(int _globalSize)</code>, Aparapi will determine the EXECUTION_MODE of the kernel.
* This decision is made dynamically based on two factors:
* <ol>
* <li>Whether OpenCL is available (appropriate drivers are installed and the OpenCL and Aparapi dynamic libraries are included on the system path).</li>
* <li>Whether the bytecode of the <code>run()</code> method (and every method that can be called directly or indirectly from the <code>run()</code> method)
* can be converted into OpenCL.</li>
* </ol>
* <p>
* Below is an example Kernel that calculates the square of a set of input values.
* <p>
* <blockquote><pre>
* class SquareKernel extends Kernel{
* private int values[];
* private int squares[];
* public SquareKernel(int values[]){
* this.values = values;
* squares = new int[values.length];
* }
* public void run() {
* int gid = getGlobalID();
* squares[gid] = values[gid]*values[gid];
* }
* public int[] getSquares(){
* return(squares);
* }
* }
* </pre></blockquote>
* <p>
* To execute this kernel, first create a new instance of it and then call <code>execute(Range _range)</code>.
* <p>
* <blockquote><pre>
* int[] values = new int[1024];
* // fill values array
* Range range = Range.create(values.length); // create a range 0..1024
* SquareKernel kernel = new SquareKernel(values);
* kernel.execute(range);
* </pre></blockquote>
* <p>
* When <code>execute(Range)</code> returns, all the executions of <code>Kernel.run()</code> have completed and the results are available in the <code>squares</code> array.
* <p>
* <blockquote><pre>
* int[] squares = kernel.getSquares();
* for (int i=0; i< values.length; i++){
* System.out.printf("%4d %4d %8d\n", i, values[i], squares[i]);
* }
* </pre></blockquote>
* <p>
* A different approach to creating kernels that avoids extending Kernel is to write an anonymous inner class:
* <p>
* <blockquote><pre>
*
* final int[] values = new int[1024];
* // fill the values array
* final int[] squares = new int[values.length];
* final Range range = Range.create(values.length);
*
* Kernel kernel = new Kernel(){
* public void run() {
* int gid = getGlobalID();
* squares[gid] = values[gid]*values[gid];
* }
* };
* kernel.execute(range);
* for (int i=0; i< values.length; i++){
* System.out.printf("%4d %4d %8d\n", i, values[i], squares[i]);
* }
*
* </pre></blockquote>
* <p>
*
* @author gfrost AMD Javalabs
* @version Alpha, 21/09/2010
*/
public abstract class Kernel implements Cloneable {
private static Logger logger = Logger.getLogger(Config.getLoggerName());
/**
* We can use this Annotation to 'tag' intended local buffers.
*
* So we can either annotate the buffer
* <pre><code>
* @Local int[] buffer = new int[1024];
* </code></pre>
* Or use a special suffix
* <pre><code>
* int[] buffer_$local$ = new int[1024];
* </code></pre>
*
* @see #LOCAL_SUFFIX
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Local {
}
/**
* We can use this Annotation to 'tag' intended constant buffers.
*
* So we can either annotate the buffer
* <pre><code>
* @Constant int[] buffer = new int[1024];
* </code></pre>
* Or use a special suffix
* <pre><code>
* int[] buffer_$constant$ = new int[1024];
* </code></pre>
*
* @see #LOCAL_SUFFIX
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Constant {
}
/**
*
* We can use this Annotation to 'tag' __private (unshared) array fields. Data in the __private address space in OpenCL is accessible only from
* the current kernel instance.
*
* To so mark a field with a buffer size of 99, we can either annotate the buffer
* <pre><code>
* @PrivateMemorySpace(99) int[] buffer = new int[99];
* </code></pre>
* Or use a special suffix
* <pre><code>
* int[] buffer_$private$99 = new int[99];
* </code></pre>
*
* <p>Note that any code which must be runnable in {@link EXECUTION_MODE#JTP} will fail to work correctly if it uses such an
* array, as the array will be shared by all threads. The solution is to create a {@link NoCL} method called at the start of {@link #run()} which sets
* the field to an array returned from a static <code>ThreadLocal<foo[]></code></p>. Please see <code>MedianKernel7x7</code> in the samples for an example.
*
* @see #PRIVATE_SUFFIX
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface PrivateMemorySpace {
/** Size of the array used as __private buffer. */
int value();
}
/**
* Annotation which can be applied to either a getter (with usual java bean naming convention relative to an instance field), or to any method
* with void return type, which prevents both the method body and any calls to the method being emitted in the generated OpenCL. (In the case of a getter, the
* underlying field is used in place of the NoCL getter method.) This allows for code specialization within a java/JTP execution path, for example to
* allow logging/breakpointing when debugging, or to apply ThreadLocal processing (see {@link PrivateMemorySpace}) in java to simulate OpenCL __private
* memory.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface NoCL {
// empty
}
/**
* We can use this suffix to 'tag' intended local buffers.
*
*
* So either name the buffer
* <pre><code>
* int[] buffer_$local$ = new int[1024];
* </code></pre>
* Or use the Annotation form
* <pre><code>
* @Local int[] buffer = new int[1024];
* </code></pre>
*/
public final static String LOCAL_SUFFIX = "_$local$";
/**
* We can use this suffix to 'tag' intended constant buffers.
*
*
* So either name the buffer
* <pre><code>
* int[] buffer_$constant$ = new int[1024];
* </code></pre>
* Or use the Annotation form
* <pre><code>
* @Constant int[] buffer = new int[1024];
* </code></pre>
*/
public final static String CONSTANT_SUFFIX = "_$constant$";
/**
* We can use this suffix to 'tag' __private buffers.
*
* <p>So either name the buffer
* <pre><code>
* int[] buffer_$private$32 = new int[32];
* </code></pre>
* Or use the Annotation form
* <pre><code>
* @PrivateMemorySpace(32) int[] buffer = new int[32];
* </code></pre>
*
* @see PrivateMemorySpace for a more detailed usage summary
*/
public final static String PRIVATE_SUFFIX = "_$private$";
/**
* This annotation is for internal use only
*/
@Retention(RetentionPolicy.RUNTIME)
protected @interface OpenCLDelegate {
}
/**
* This annotation is for internal use only
*/
@Retention(RetentionPolicy.RUNTIME)
protected @interface OpenCLMapping {
String mapTo() default "";
boolean atomic32() default false;
boolean atomic64() default false;
}
public abstract class Entry {
public abstract void run();
public Kernel execute(Range _range) {
return (Kernel.this.execute("foo", _range, 1));
}
}
/**
* @deprecated It is no longer recommended that {@code EXECUTION_MODE}s are used, as a more sophisticated {@link com.aparapi.device.Device}
* preference mechanism is in place, see {@link com.aparapi.internal.kernel.KernelManager}. Though {@link #setExecutionMode(EXECUTION_MODE)}
* is still honored, the default EXECUTION_MODE is now {@link EXECUTION_MODE#AUTO}, which indicates that the KernelManager
* will determine execution behaviours.
*
* <p>
* The <i>execution mode</i> ENUM enumerates the possible modes of executing a kernel.
* One can request a mode of execution using the values below, and query a kernel after it first executes to
* determine how it executed.
*
* <p>
* Aparapi supports 5 execution modes. Default is GPU.
* <ul>
* <table>
* <tr><th align="left">Enum value</th><th align="left">Execution</th></tr>
* <tr><td><code><b>GPU</b></code></td><td>Execute using OpenCL on first available GPU device</td></tr>
* <tr><td><code><b>ACC</b></code></td><td>Execute using OpenCL on first available Accelerator device</td></tr>
* <tr><td><code><b>CPU</b></code></td><td>Execute using OpenCL on first available CPU device</td></tr>
* <tr><td><code><b>JTP</b></code></td><td>Execute using a Java Thread Pool (one thread spawned per available core)</td></tr>
* <tr><td><code><b>SEQ</b></code></td><td>Execute using a single loop. This is useful for debugging but will be less
* performant than the other modes</td></tr>
* </table>
* </ul>
* <p>
* To request that a kernel is executed in a specific mode, call <code>Kernel.setExecutionMode(EXECUTION_MODE)</code> before the
* kernel first executes.
* <p>
* <blockquote><pre>
* int[] values = new int[1024];
* // fill values array
* SquareKernel kernel = new SquareKernel(values);
* kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP);
* kernel.execute(values.length);
* </pre></blockquote>
* <p>
* Alternatively, the property <code>com.codegen.executionMode</code> can be set to one of <code>JTP,GPU,ACC,CPU,SEQ</code>
* when an application is launched.
* <p><blockquote><pre>
* java -classpath ....;codegen.jar -Dcom.codegen.executionMode=GPU MyApplication
* </pre></blockquote><p>
* Generally setting the execution mode is not recommended (it is best to let Aparapi decide automatically) but the option
* provides a way to compare a kernel's performance under multiple execution modes.
*
* @author gfrost AMD Javalabs
* @version Alpha, 21/09/2010
*/
@Deprecated
public static enum EXECUTION_MODE {
/**
*
*/
AUTO,
/**
* A dummy value to indicate an unknown state.
*/
NONE,
/**
* The value representing execution on a GPU device via OpenCL.
*/
GPU,
/**
* The value representing execution on a CPU device via OpenCL.
* <p>
* <b>Note</b> not all OpenCL implementations support OpenCL compute on the CPU.
*/
CPU,
/**
* The value representing execution on a Java Thread Pool.
* <p>
* By default one Java thread is started for each available core and each core will execute <code>globalSize/cores</code> work items.
* This creates a total of <code>globalSize%cores</code> threads to complete the work.
* Choose suitable values for <code>globalSize</code> to minimize the number of threads that are spawned.
*/
JTP,
/**
* The value representing execution sequentially in a single loop.
* <p>
* This is meant to be used for debugging a kernel.
*/
SEQ,
/**
* The value representing execution on an accelerator device (Xeon Phi) via OpenCL.
*/
ACC;
/**
* @deprecated See {@link EXECUTION_MODE}.
*/
@Deprecated
static LinkedHashSet<EXECUTION_MODE> getDefaultExecutionModes() {
LinkedHashSet<EXECUTION_MODE> defaultExecutionModes = new LinkedHashSet<EXECUTION_MODE>();
if (OpenCLLoader.isOpenCLAvailable()) {
defaultExecutionModes.add(GPU);
defaultExecutionModes.add(JTP);
} else {
defaultExecutionModes.add(JTP);
}
final String executionMode = Config.executionMode;
if (executionMode != null) {
LinkedHashSet<EXECUTION_MODE> requestedExecutionModes;
requestedExecutionModes = EXECUTION_MODE.getExecutionModeFromString(executionMode);
logger.fine("requested execution mode =");
for (final EXECUTION_MODE mode : requestedExecutionModes) {
logger.fine(" " + mode);
}
if ((OpenCLLoader.isOpenCLAvailable() && EXECUTION_MODE.anyOpenCL(requestedExecutionModes))
|| !EXECUTION_MODE.anyOpenCL(requestedExecutionModes)) {
defaultExecutionModes = requestedExecutionModes;
}
}
logger.info("default execution modes = " + defaultExecutionModes);
for (final EXECUTION_MODE e : defaultExecutionModes) {
logger.info("SETTING DEFAULT MODE: " + e.toString());
}
return (defaultExecutionModes);
}
static LinkedHashSet<EXECUTION_MODE> getExecutionModeFromString(String executionMode) {
final LinkedHashSet<EXECUTION_MODE> executionModes = new LinkedHashSet<EXECUTION_MODE>();
for (final String mode : executionMode.split(",")) {
executionModes.add(valueOf(mode.toUpperCase()));
}
return executionModes;
}
static EXECUTION_MODE getFallbackExecutionMode() {
final EXECUTION_MODE defaultFallbackExecutionMode = JTP;
logger.info("fallback execution mode = " + defaultFallbackExecutionMode);
return (defaultFallbackExecutionMode);
}
static boolean anyOpenCL(LinkedHashSet<EXECUTION_MODE> _executionModes) {
for (final EXECUTION_MODE mode : _executionModes) {
if ((mode == GPU) || (mode == ACC) || (mode == CPU)) {
return true;
}
}
return false;
}
public boolean isOpenCL() {
return (this == GPU) || (this == ACC) || (this == CPU);
}
};
private KernelRunner kernelRunner = null;
private boolean autoCleanUpArrays = false;
private KernelState kernelState = new KernelState();
/**
* This class is for internal Kernel state management<p>
* NOT INTENDED FOR USE BY USERS
*/
public final class KernelState {
private int[] globalIds = new int[] {0, 0, 0};
private int[] localIds = new int[] {0, 0, 0};
private int[] groupIds = new int[] {0, 0, 0};
private Range range;
private int passId;
private final AtomicReference<IKernelBarrier> localBarrier = new AtomicReference<IKernelBarrier>();
/**
* Default constructor
*/
protected KernelState() {
}
/**
* Copy constructor
*/
protected KernelState(KernelState kernelState) {
globalIds = kernelState.getGlobalIds();
localIds = kernelState.getLocalIds();
groupIds = kernelState.getGroupIds();
range = kernelState.getRange();
passId = kernelState.getPassId();
localBarrier.set(kernelState.getLocalBarrier());
}
/**
* @return the globalIds
*/
public int[] getGlobalIds() {
return globalIds;
}
/**
* @param globalIds the globalIds to set
*/
public void setGlobalIds(int[] globalIds) {
this.globalIds = globalIds;
}
/**
* Set a specific index value
*
* @param _index
* @param value
*/
public void setGlobalId(int _index, int value) {
globalIds[_index] = value;
}
/**
* @return the localIds
*/
public int[] getLocalIds() {
return localIds;
}
/**
* @param localIds the localIds to set
*/
public void setLocalIds(int[] localIds) {
this.localIds = localIds;
}
/**
* Set a specific index value
*
* @param _index
* @param value
*/
public void setLocalId(int _index, int value) {
localIds[_index] = value;
}
/**
* @return the groupIds
*/
public int[] getGroupIds() {
return groupIds;
}
/**
* @param groupIds the groupIds to set
*/
public void setGroupIds(int[] groupIds) {
this.groupIds = groupIds;
}
/**
* Set a specific index value
*
* @param _index
* @param value
*/
public void setGroupId(int _index, int value) {
groupIds[_index] = value;
}
/**
* @return the range
*/
public Range getRange() {
return range;
}
/**
* @param range the range to set
*/
public void setRange(Range range) {
this.range = range;
}
/**
* @return the passId
*/
public int getPassId() {
return passId;
}
/**
* @param passId the passId to set
*/
public void setPassId(int passId) {
this.passId = passId;
}
/**
* @return the localBarrier
*/
public IKernelBarrier getLocalBarrier() {
return localBarrier.get();
}
/**
* @param localBarrier the localBarrier to set
*/
public void setLocalBarrier(IKernelBarrier localBarrier) {
this.localBarrier.set(localBarrier);
}
public void awaitOnLocalBarrier() {
boolean completed = false;
final IKernelBarrier barrier = localBarrier.get();
while (!completed && barrier != null) {
try {
ForkJoinPool.managedBlock(barrier); //ManagedBlocker already has to be reentrant
completed = true;
} catch (InterruptedException ex) {
//Empty on purpose, either barrier is disabled on InterruptedException or lock will have to complete
}
}
}
public void disableLocalBarrier() {
final IKernelBarrier barrier = localBarrier.getAndSet(null);
if (barrier != null) {
barrier.cancelBarrier();
}
}
public String describe() {
final StringBuilder sb = new StringBuilder(100);
sb.append("Pass Id: ");
sb.append(passId);
sb.append(" - Group IDs: [");
boolean first = true;
for (int groupId : groupIds) {
if (!first) {
sb.append(", ");
}
sb.append(groupId);
first = false;
}
sb.append("] - Global IDs: [");
first = true;
for (int globalId : globalIds) {
if (!first) {
sb.append(", ");
}
sb.append(globalId);
first = false;
}
sb.append("], Local IDs: [");
first = true;
for (int localId : localIds) {
if (!first) {
sb.append(", ");
}
sb.append(localId);
first = false;
}
sb.append("]");
return sb.toString();
}
}
/**
* Determine the globalId of an executing kernel.
* <p>
* The kernel implementation uses the globalId to determine which of the executing kernels (in the global domain space) this invocation is expected to deal with.
* <p>
* For example in a <code>SquareKernel</code> implementation:
* <p>
* <blockquote><pre>
* class SquareKernel extends Kernel{
* private int values[];
* private int squares[];
* public SquareKernel(int values[]){
* this.values = values;
* squares = new int[values.length];
* }
* public void run() {
* int gid = getGlobalID();
* squares[gid] = values[gid]*values[gid];
* }
* public int[] getSquares(){
* return(squares);
* }
* }
* </pre></blockquote>
* <p>
* Each invocation of <code>SquareKernel.run()</code> retrieves it's globalId by calling <code>getGlobalId()</code>, and then computes the value of <code>square[gid]</code> for a given value of <code>value[gid]</code>.
* <p>
* @return The globalId for the Kernel being executed
*
* @see #getLocalId()
* @see #getGroupId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*/
@OpenCLDelegate
protected final int getGlobalId() {
return getGlobalId(0);
}
@OpenCLDelegate
protected final int getGlobalId(int _dim) {
return kernelState.getGlobalIds()[_dim];
}
/*
@OpenCLDelegate protected final int getGlobalX() {
return (getGlobalId(0));
}
@OpenCLDelegate protected final int getGlobalY() {
return (getGlobalId(1));
}
@OpenCLDelegate protected final int getGlobalZ() {
return (getGlobalId(2));
}
*/
/**
* Determine the groupId of an executing kernel.
* <p>
* When a <code>Kernel.execute(int globalSize)</code> is invoked for a particular kernel, the runtime will break the work into various 'groups'.
* <p>
* A kernel can use <code>getGroupId()</code> to determine which group a kernel is currently
* dispatched to
* <p>
* The following code would capture the groupId for each kernel and map it against globalId.
* <blockquote><pre>
* final int[] groupIds = new int[1024];
* Kernel kernel = new Kernel(){
* public void run() {
* int gid = getGlobalId();
* groupIds[gid] = getGroupId();
* }
* };
* kernel.execute(groupIds.length);
* for (int i=0; i< values.length; i++){
* System.out.printf("%4d %4d\n", i, groupIds[i]);
* }
* </pre></blockquote>
*
* @see #getLocalId()
* @see #getGlobalId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The groupId for this Kernel being executed
*/
@OpenCLDelegate
protected final int getGroupId() {
return getGroupId(0);
}
@OpenCLDelegate
protected final int getGroupId(int _dim) {
return kernelState.getGroupIds()[_dim];
}
/*
@OpenCLDelegate protected final int getGroupX() {
return (getGroupId(0));
}
@OpenCLDelegate protected final int getGroupY() {
return (getGroupId(1));
}
@OpenCLDelegate protected final int getGroupZ() {
return (getGroupId(2));
}
*/
/**
* Determine the passId of an executing kernel.
* <p>
* When a <code>Kernel.execute(int globalSize, int passes)</code> is invoked for a particular kernel, the runtime will break the work into various 'groups'.
* <p>
* A kernel can use <code>getPassId()</code> to determine which pass we are in. This is ideal for 'reduce' type phases
*
* @see #getLocalId()
* @see #getGlobalId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The groupId for this Kernel being executed
*/
@OpenCLDelegate
protected final int getPassId() {
return kernelState.getPassId();
}
/**
* Determine the local id of an executing kernel.
* <p>
* When a <code>Kernel.execute(int globalSize)</code> is invoked for a particular kernel, the runtime will break the work into
* various 'groups'.
* <code>getLocalId()</code> can be used to determine the relative id of the current kernel within a specific group.
* <p>
* The following code would capture the groupId for each kernel and map it against globalId.
* <blockquote><pre>
* final int[] localIds = new int[1024];
* Kernel kernel = new Kernel(){
* public void run() {
* int gid = getGlobalId();
* localIds[gid] = getLocalId();
* }
* };
* kernel.execute(localIds.length);
* for (int i=0; i< values.length; i++){
* System.out.printf("%4d %4d\n", i, localIds[i]);
* }
* </pre></blockquote>
*
* @see #getGroupId()
* @see #getGlobalId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The local id for this Kernel being executed
*/
@OpenCLDelegate
protected final int getLocalId() {
return getLocalId(0);
}
@OpenCLDelegate
protected final int getLocalId(int _dim) {
return kernelState.getLocalIds()[_dim];
}
/*
@OpenCLDelegate protected final int getLocalX() {
return (getLocalId(0));
}
@OpenCLDelegate protected final int getLocalY() {
return (getLocalId(1));
}
@OpenCLDelegate protected final int getLocalZ() {
return (getLocalId(2));
}
*/
/**
* Determine the size of the group that an executing kernel is a member of.
* <p>
* When a <code>Kernel.execute(int globalSize)</code> is invoked for a particular kernel, the runtime will break the work into
* various 'groups'. <code>getLocalSize()</code> allows a kernel to determine the size of the current group.
* <p>
* Note groups may not all be the same size. In particular, if <code>(global size)%(# of compute devices)!=0</code>, the runtime can choose to dispatch kernels to
* groups with differing sizes.
*
* @see #getGroupId()
* @see #getGlobalId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The size of the currently executing group.
*/
@OpenCLDelegate
protected final int getLocalSize() {
return kernelState.getRange().getLocalSize(0);
}
@OpenCLDelegate
protected final int getLocalSize(int _dim) {
return kernelState.getRange().getLocalSize(_dim);
}
/*
@OpenCLDelegate protected final int getLocalWidth() {
return (range.getLocalSize(0));
}
@OpenCLDelegate protected final int getLocalHeight() {
return (range.getLocalSize(1));
}
@OpenCLDelegate protected final int getLocalDepth() {
return (range.getLocalSize(2));
}
*/
/**
* Determine the value that was passed to <code>Kernel.execute(int globalSize)</code> method.
*
* @see #getGroupId()
* @see #getGlobalId()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The value passed to <code>Kernel.execute(int globalSize)</code> causing the current execution.
*/
@OpenCLDelegate
protected final int getGlobalSize() {
return kernelState.getRange().getGlobalSize(0);
}
@OpenCLDelegate
protected final int getGlobalSize(int _dim) {
return kernelState.getRange().getGlobalSize(_dim);
}
/*
@OpenCLDelegate protected final int getGlobalWidth() {
return (range.getGlobalSize(0));
}
@OpenCLDelegate protected final int getGlobalHeight() {
return (range.getGlobalSize(1));
}
@OpenCLDelegate protected final int getGlobalDepth() {
return (range.getGlobalSize(2));
}
*/
/**
* Determine the number of groups that will be used to execute a kernel
* <p>
* When <code>Kernel.execute(int globalSize)</code> is invoked, the runtime will split the work into
* multiple 'groups'. <code>getNumGroups()</code> returns the total number of groups that will be used.
*
* @see #getGroupId()
* @see #getGlobalId()
* @see #getGlobalSize()
* @see #getNumGroups()
* @see #getLocalSize()
*
* @return The number of groups that kernels will be dispatched into.
*/
@OpenCLDelegate
protected final int getNumGroups() {
return kernelState.getRange().getNumGroups(0);
}
@OpenCLDelegate
protected final int getNumGroups(int _dim) {
return kernelState.getRange().getNumGroups(_dim);
}
/*
@OpenCLDelegate protected final int getNumGroupsWidth() {
return (range.getGroups(0));