fft_kernelstring.cpp 67.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/***************************************************************************
 *   Copyright (C) 2012 by Oliver Bock,Heinz-Bernd Eggenstein              *
 *   oliver.bock[AT]aei.mpg.de                                             *
 *   heinz-bernd.eggenstein[AT]aei.mpg.de                                  *
 *                                                                         *
 *   This file is part of libclfft (originally for Einstein@Home)          *
 *   Derived from clFFT,  (C) Apple, see notice below.                     *
 *                                                                         *
 *                                                                         *
 *   libclfft  is distributed in the hope that it will be useful,          *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See              *
 *   notice below for more details.                                        *
 *                                                                         *
 ***************************************************************************/
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
//
// File:       fft_kernelstring.cpp
//
// Version:    <1.0>
//
// Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ("Apple")
//             in consideration of your agreement to the following terms, and your use,
//             installation, modification or redistribution of this Apple software
//             constitutes acceptance of these terms.  If you do not agree with these
//             terms, please do not use, install, modify or redistribute this Apple
//             software.
//
//             In consideration of your agreement to abide by the following terms, and
//             subject to these terms, Apple grants you a personal, non - exclusive
//             license, under Apple's copyrights in this original Apple software ( the
//             "Apple Software" ), to use, reproduce, modify and redistribute the Apple
//             Software, with or without modifications, in source and / or binary forms;
//             provided that if you redistribute the Apple Software in its entirety and
//             without modifications, you must retain this notice and the following text
//             and disclaimers in all such redistributions of the Apple Software. Neither
//             the name, trademarks, service marks or logos of Apple Inc. may be used to
//             endorse or promote products derived from the Apple Software without specific
//             prior written permission from Apple.  Except as expressly stated in this
//             notice, no other rights or licenses, express or implied, are granted by
//             Apple herein, including but not limited to any patent rights that may be
//             infringed by your derivative works or by other works in which the Apple
//             Software may be incorporated.
//
//             The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
//             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
//             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
//             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION
//             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
//
//             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
//             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
//             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER
//             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR
//             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright ( C ) 2008 Apple Inc. All Rights Reserved.
//
////////////////////////////////////////////////////////////////////////////////////////////////////


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <string>
69
#include <string.h>
70
71
72
73
74
75
76
77
78
#include <assert.h>
#include "fft_internal.h"
#include "clFFT.h"

using namespace std;

#define max(A,B) ((A) > (B) ? (A) : (B))
#define min(A,B) ((A) < (B) ? (A) : (B))

Oliver Bock's avatar
Oliver Bock committed
79
static string
80
81
num2str(int num)
{
Oliver Bock's avatar
Oliver Bock committed
82
83
84
    char temp[200];
    sprintf(temp, "%d", num);
    return string(temp);
85
86
}

Oliver Bock's avatar
Oliver Bock committed
87
// For any n, this function decomposes n into factors for loacal memory tranpose
88
89
90
91
// based fft. Factors (radices) are sorted such that the first one (radixArray[0])
// is the largest. This base radix determines the number of registers used by each
// work item and product of remaining radices determine the size of work group needed.
// To make things concrete with and example, suppose n = 1024. It is decomposed into
Oliver Bock's avatar
Oliver Bock committed
92
// 1024 = 16 x 16 x 4. Hence kernel uses float2 a[16], for local in-register fft and
93
// needs 16 x 4 = 64 work items per work group. So kernel first performance 64 length
Oliver Bock's avatar
Oliver Bock committed
94
// 16 ffts (64 work items working in parallel) following by transpose using local
95
// memory followed by again 64 length 16 ffts followed by transpose using local memory
Oliver Bock's avatar
Oliver Bock committed
96
// followed by 256 length 4 ffts. For the last step since with size of work group is
97
// 64 and each work item can array for 16 values, 64 work items can compute 256 length
Oliver Bock's avatar
Oliver Bock committed
98
// 4 ffts by each work item computing 4 length 4 ffts.
99
100
101
102
103
104
// Similarly for n = 2048 = 8 x 8 x 8 x 4, each work group has 8 x 8 x 4 = 256 work
// iterms which each computes 256 (in-parallel) length 8 ffts in-register, followed
// by transpose using local memory, followed by 256 length 8 in-register ffts, followed
// by transpose using local memory, followed by 256 length 8 in-register ffts, followed
// by transpose using local memory, followed by 512 length 4 in-register ffts. Again,
// for the last step, each work item computes two length 4 in-register ffts and thus
Oliver Bock's avatar
Oliver Bock committed
105
106
// 256 work items are needed to compute all 512 ffts.
// For n = 32 = 8 x 4, 4 work items first compute 4 in-register
107
108
// lenth 8 ffts, followed by transpose using local memory followed by 8 in-register
// length 4 ffts, where each work item computes two length 4 ffts thus 4 work items
Oliver Bock's avatar
Oliver Bock committed
109
110
// can compute 8 length 4 ffts. However if work group size of say 64 is choosen,
// each work group can compute 64/ 4 = 16 size 32 ffts (batched transform).
111
112
// Users can play with these parameters to figure what gives best performance on
// their particular device i.e. some device have less register space thus using
Oliver Bock's avatar
Oliver Bock committed
113
// smaller base radix can avoid spilling ... some has small local memory thus
114
115
// using smaller work group size may be required etc

Oliver Bock's avatar
Oliver Bock committed
116
static void
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
getRadixArray(unsigned int n, unsigned int *radixArray, unsigned int *numRadices, unsigned int maxRadix)
{
    if(maxRadix > 1)
    {
        maxRadix = min(n, maxRadix);
        unsigned int cnt = 0;
        while(n > maxRadix)
        {
            radixArray[cnt++] = maxRadix;
            n /= maxRadix;
        }
        radixArray[cnt++] = n;
        *numRadices = cnt;
        return;
    }

Oliver Bock's avatar
Oliver Bock committed
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
    switch(n)
    {
        case 2:
            *numRadices = 1;
            radixArray[0] = 2;
            break;

        case 4:
            *numRadices = 1;
            radixArray[0] = 4;
            break;

        case 8:
            *numRadices = 1;
            radixArray[0] = 8;
            break;

        case 16:
            *numRadices = 2;
            radixArray[0] = 8; radixArray[1] = 2;
            break;

        case 32:
            *numRadices = 2;
            radixArray[0] = 8; radixArray[1] = 4;
            break;

        case 64:
            *numRadices = 2;
            radixArray[0] = 8; radixArray[1] = 8;
            break;

        case 128:
            *numRadices = 3;
            radixArray[0] = 8; radixArray[1] = 4; radixArray[2] = 4;
            break;

        case 256:
            *numRadices = 4;
            radixArray[0] = 4; radixArray[1] = 4; radixArray[2] = 4; radixArray[3] = 4;
            break;

        case 512:
            *numRadices = 3;
            radixArray[0] = 8; radixArray[1] = 8; radixArray[2] = 8;
            break;

        case 1024:
            *numRadices = 3;
            radixArray[0] = 16; radixArray[1] = 16; radixArray[2] = 4;
            break;
        case 2048:
            *numRadices = 4;
            radixArray[0] = 8; radixArray[1] = 8; radixArray[2] = 8; radixArray[3] = 4;
            break;
        default:
            *numRadices = 0;
            return;
    }
192
193
194
195
196
}

static void
insertHeader(string &kernelString, string &kernelName, clFFT_DataFormat dataFormat)
{
Oliver Bock's avatar
Oliver Bock committed
197
    if(dataFormat == clFFT_SplitComplexFormat)
198
199
        kernelString += string("__kernel void ") + kernelName + string("(__global float *in_real, __global float *in_imag, __global float *out_real, __global float *out_imag, int dir, int S,"
                                                                          
200
                                                                           "__global float2 * cossinLUT1, __global float2 * cossinLUT2 )\n");
201
202
203
204
    
//     "__constant float * sinLUT1, __constant float * cosLUT1, __constant float * sinLUT2, __constant float * cosLUT2)\n");
        else
//        kernelString += string("__kernel void ") + kernelName + string("(__global float2 *in, __global float2 *out, int dir, int S, __constant float * sinLUT1, __constant float * cosLUT1, __constant float * sinLUT2, __constant float * cosLUT2)\n");
205
    kernelString += string("__kernel void ") + kernelName + string("(__global float2 *in, __global float2 *out, int dir, int S, __global float2 * cossinLUT1, __global float2 * cossinLUT2 )\n");
206

207
208
}

Oliver Bock's avatar
Oliver Bock committed
209
static void
210
211
insertVariables(string &kStream, int maxRadix)
{
Oliver Bock's avatar
Oliver Bock committed
212
    kStream += string("    int i, j, r, indexIn, indexOut, index, tid, bNum, xNum, k, l;\n");
213
    kStream += string("    int s, ii, jj, offset;\n");
Oliver Bock's avatar
Oliver Bock committed
214
215
    kStream += string("    float2 w;\n");
    kStream += string("    float ang, angf, ang1;\n");
216
217
218
219
220
221
222
223
224
    kStream += string("    __local float *lMemStore, *lMemLoad;\n");
    kStream += string("    float2 a[") +  num2str(maxRadix) + string("];\n");
    kStream += string("    int lId = get_local_id( 0 );\n");
    kStream += string("    int groupId = get_group_id( 0 );\n");
}

static void
formattedLoad(string &kernelString, int aIndex, int gIndex, clFFT_DataFormat dataFormat)
{
Oliver Bock's avatar
Oliver Bock committed
225
226
227
228
229
230
231
    if(dataFormat == clFFT_InterleavedComplexFormat)
        kernelString += string("        a[") + num2str(aIndex) + string("] = in[") + num2str(gIndex) + string("];\n");
    else
    {
        kernelString += string("        a[") + num2str(aIndex) + string("].x = in_real[") + num2str(gIndex) + string("];\n");
        kernelString += string("        a[") + num2str(aIndex) + string("].y = in_imag[") + num2str(gIndex) + string("];\n");
    }
232
233
234
235
236
}

static void
formattedStore(string &kernelString, int aIndex, int gIndex, clFFT_DataFormat dataFormat)
{
Oliver Bock's avatar
Oliver Bock committed
237
238
239
240
241
242
243
    if(dataFormat == clFFT_InterleavedComplexFormat)
        kernelString += string("        out[") + num2str(gIndex) + string("] = a[") + num2str(aIndex) + string("];\n");
    else
    {
        kernelString += string("        out_real[") + num2str(gIndex) + string("] = a[") + num2str(aIndex) + string("].x;\n");
        kernelString += string("        out_imag[") + num2str(gIndex) + string("] = a[") + num2str(aIndex) + string("].y;\n");
    }
244
245
246
247
248
}

static int
insertGlobalLoadsAndTranspose(string &kernelString, int N, int numWorkItemsPerXForm, int numXFormsPerWG, int R0, int mem_coalesce_width, clFFT_DataFormat dataFormat)
{
Oliver Bock's avatar
Oliver Bock committed
249
250
251
252
    int log2NumWorkItemsPerXForm = (int) log2(numWorkItemsPerXForm);
    int groupSize = numWorkItemsPerXForm * numXFormsPerWG;
    int i, j;
    int lMemSize = 0;
Oliver Bock's avatar
Oliver Bock committed
253

Oliver Bock's avatar
Oliver Bock committed
254
255
    if(numXFormsPerWG > 1)
        kernelString += string("        s = S & ") + num2str(numXFormsPerWG - 1) + string(";\n");
Oliver Bock's avatar
Oliver Bock committed
256

257
    if(numWorkItemsPerXForm >= mem_coalesce_width)
Oliver Bock's avatar
Oliver Bock committed
258
    {
Oliver Bock's avatar
Oliver Bock committed
259
260
        if(numXFormsPerWG > 1)
        {
261
262
263
            kernelString += string("    ii = lId & ") + num2str(numWorkItemsPerXForm-1) + string(";\n");
            kernelString += string("    jj = lId >> ") + num2str(log2NumWorkItemsPerXForm) + string(";\n");
            kernelString += string("    if( !s || (groupId < get_num_groups(0)-1) || (jj < s) ) {\n");
Oliver Bock's avatar
Oliver Bock committed
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
            kernelString += string("        offset = mad24( mad24(groupId, ") + num2str(numXFormsPerWG) + string(", jj), ") + num2str(N) + string(", ii );\n");
            if(dataFormat == clFFT_InterleavedComplexFormat)
            {
                kernelString += string("        in += offset;\n");
                kernelString += string("        out += offset;\n");
            }
            else
            {
                kernelString += string("        in_real += offset;\n");
                kernelString += string("        in_imag += offset;\n");
                kernelString += string("        out_real += offset;\n");
                kernelString += string("        out_imag += offset;\n");
            }
            for(i = 0; i < R0; i++)
                formattedLoad(kernelString, i, i*numWorkItemsPerXForm, dataFormat);
            kernelString += string("    }\n");
        }
        else
        {
            kernelString += string("    ii = lId;\n");
            kernelString += string("    jj = 0;\n");
            kernelString += string("    offset =  mad24(groupId, ") + num2str(N) + string(", ii);\n");
            if(dataFormat == clFFT_InterleavedComplexFormat)
            {
                kernelString += string("        in += offset;\n");
                kernelString += string("        out += offset;\n");
            }
            else
            {
                kernelString += string("        in_real += offset;\n");
                kernelString += string("        in_imag += offset;\n");
                kernelString += string("        out_real += offset;\n");
                kernelString += string("        out_imag += offset;\n");
            }
            for(i = 0; i < R0; i++)
                formattedLoad(kernelString, i, i*numWorkItemsPerXForm, dataFormat);
        }
301
302
303
304
305
    }
    else if( N >= mem_coalesce_width )
    {
        int numInnerIter = N / mem_coalesce_width;
        int numOuterIter = numXFormsPerWG / ( groupSize / mem_coalesce_width );
Oliver Bock's avatar
Oliver Bock committed
306

307
308
309
310
311
        kernelString += string("    ii = lId & ") + num2str(mem_coalesce_width - 1) + string(";\n");
        kernelString += string("    jj = lId >> ") + num2str((int)log2(mem_coalesce_width)) + string(";\n");
        kernelString += string("    lMemStore = sMem + mad24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
        kernelString += string("    offset = mad24( groupId, ") + num2str(numXFormsPerWG) + string(", jj);\n");
        kernelString += string("    offset = mad24( offset, ") + num2str(N) + string(", ii );\n");
Oliver Bock's avatar
Oliver Bock committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        if(dataFormat == clFFT_InterleavedComplexFormat)
        {
            kernelString += string("        in += offset;\n");
            kernelString += string("        out += offset;\n");
        }
        else
        {
            kernelString += string("        in_real += offset;\n");
            kernelString += string("        in_imag += offset;\n");
            kernelString += string("        out_real += offset;\n");
            kernelString += string("        out_imag += offset;\n");
        }

        kernelString += string("if((groupId == get_num_groups(0)-1) && s) {\n");
326
327
328
        for(i = 0; i < numOuterIter; i++ )
        {
            kernelString += string("    if( jj < s ) {\n");
Oliver Bock's avatar
Oliver Bock committed
329
330
331
332
333
            for(j = 0; j < numInnerIter; j++ )
                formattedLoad(kernelString, i * numInnerIter + j, j * mem_coalesce_width + i * ( groupSize / mem_coalesce_width ) * N, dataFormat);
            kernelString += string("    }\n");
            if(i != numOuterIter - 1)
                kernelString += string("    jj += ") + num2str(groupSize / mem_coalesce_width) + string(";\n");
334
        }
Oliver Bock's avatar
Oliver Bock committed
335
336
        kernelString += string("}\n ");
        kernelString += string("else {\n");
337
338
        for(i = 0; i < numOuterIter; i++ )
        {
Oliver Bock's avatar
Oliver Bock committed
339
340
            for(j = 0; j < numInnerIter; j++ )
                formattedLoad(kernelString, i * numInnerIter + j, j * mem_coalesce_width + i * ( groupSize / mem_coalesce_width ) * N, dataFormat);
Oliver Bock's avatar
Oliver Bock committed
341
        }
Oliver Bock's avatar
Oliver Bock committed
342
        kernelString += string("}\n");
Oliver Bock's avatar
Oliver Bock committed
343

Oliver Bock's avatar
Oliver Bock committed
344
345
        kernelString += string("    ii = lId & ") + num2str(numWorkItemsPerXForm - 1) + string(";\n");
        kernelString += string("    jj = lId >> ") + num2str(log2NumWorkItemsPerXForm) + string(";\n");
Oliver Bock's avatar
Oliver Bock committed
346
347
        kernelString += string("    lMemLoad  = sMem + mad24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(", ii);\n");

348
        for( i = 0; i < numOuterIter; i++ )
Oliver Bock's avatar
Oliver Bock committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        {
            for( j = 0; j < numInnerIter; j++ )
            {
                kernelString += string("    lMemStore[") + num2str(j * mem_coalesce_width + i * ( groupSize / mem_coalesce_width ) * (N + numWorkItemsPerXForm )) + string("] = a[") +
                                num2str(i * numInnerIter + j) + string("].x;\n");
            }
        }
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

        for( i = 0; i < R0; i++ )
            kernelString += string("    a[") + num2str(i) + string("].x = lMemLoad[") + num2str(i * numWorkItemsPerXForm) + string("];\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

        for( i = 0; i < numOuterIter; i++ )
        {
            for( j = 0; j < numInnerIter; j++ )
            {
                kernelString += string("    lMemStore[") + num2str(j * mem_coalesce_width + i * ( groupSize / mem_coalesce_width ) * (N + numWorkItemsPerXForm )) + string("] = a[") +
                                num2str(i * numInnerIter + j) + string("].y;\n");
            }
        }
370
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
371

372
        for( i = 0; i < R0; i++ )
Oliver Bock's avatar
Oliver Bock committed
373
374
375
376
            kernelString += string("    a[") + num2str(i) + string("].y = lMemLoad[") + num2str(i * numWorkItemsPerXForm) + string("];\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

        lMemSize = (N + numWorkItemsPerXForm) * numXFormsPerWG;
Oliver Bock's avatar
Oliver Bock committed
377
    }
378
379
380
    else
    {
        kernelString += string("    offset = mad24( groupId,  ") + num2str(N * numXFormsPerWG) + string(", lId );\n");
Oliver Bock's avatar
Oliver Bock committed
381
382
383
384
385
386
387
388
389
390
391
392
        if(dataFormat == clFFT_InterleavedComplexFormat)
        {
            kernelString += string("        in += offset;\n");
            kernelString += string("        out += offset;\n");
        }
        else
        {
            kernelString += string("        in_real += offset;\n");
            kernelString += string("        in_imag += offset;\n");
            kernelString += string("        out_real += offset;\n");
            kernelString += string("        out_imag += offset;\n");
        }
Oliver Bock's avatar
Oliver Bock committed
393

394
395
396
        kernelString += string("    ii = lId & ") + num2str(N-1) + string(";\n");
        kernelString += string("    jj = lId >> ") + num2str((int)log2(N)) + string(";\n");
        kernelString += string("    lMemStore = sMem + mad24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
Oliver Bock's avatar
Oliver Bock committed
397

Oliver Bock's avatar
Oliver Bock committed
398
        kernelString += string("if((groupId == get_num_groups(0)-1) && s) {\n");
399
400
401
        for( i = 0; i < R0; i++ )
        {
            kernelString += string("    if(jj < s )\n");
Oliver Bock's avatar
Oliver Bock committed
402
403
404
            formattedLoad(kernelString, i, i*groupSize, dataFormat);
            if(i != R0 - 1)
                kernelString += string("    jj += ") + num2str(groupSize / N) + string(";\n");
405
        }
Oliver Bock's avatar
Oliver Bock committed
406
407
        kernelString += string("}\n");
        kernelString += string("else {\n");
408
409
        for( i = 0; i < R0; i++ )
        {
Oliver Bock's avatar
Oliver Bock committed
410
            formattedLoad(kernelString, i, i*groupSize, dataFormat);
Oliver Bock's avatar
Oliver Bock committed
411
        }
Oliver Bock's avatar
Oliver Bock committed
412
        kernelString += string("}\n");
Oliver Bock's avatar
Oliver Bock committed
413

Oliver Bock's avatar
Oliver Bock committed
414
415
        if(numWorkItemsPerXForm > 1)
        {
416
417
            kernelString += string("    ii = lId & ") + num2str(numWorkItemsPerXForm - 1) + string(";\n");
            kernelString += string("    jj = lId >> ") + num2str(log2NumWorkItemsPerXForm) + string(";\n");
Oliver Bock's avatar
Oliver Bock committed
418
            kernelString += string("    lMemLoad = sMem + mad24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
Oliver Bock's avatar
Oliver Bock committed
419
420
421
        }
        else
        {
422
423
            kernelString += string("    ii = 0;\n");
            kernelString += string("    jj = lId;\n");
Oliver Bock's avatar
Oliver Bock committed
424
            kernelString += string("    lMemLoad = sMem + mul24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(");\n");
Oliver Bock's avatar
Oliver Bock committed
425
        }
426

Oliver Bock's avatar
Oliver Bock committed
427

428
        for( i = 0; i < R0; i++ )
Oliver Bock's avatar
Oliver Bock committed
429
430
431
            kernelString += string("    lMemStore[") + num2str(i * ( groupSize / N ) * ( N + numWorkItemsPerXForm )) + string("] = a[") + num2str(i) + string("].x;\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

432
433
        for( i = 0; i < R0; i++ )
            kernelString += string("    a[") + num2str(i) + string("].x = lMemLoad[") + num2str(i * numWorkItemsPerXForm) + string("];\n");
Oliver Bock's avatar
Oliver Bock committed
434
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
435

436
        for( i = 0; i < R0; i++ )
Oliver Bock's avatar
Oliver Bock committed
437
438
439
            kernelString += string("    lMemStore[") + num2str(i * ( groupSize / N ) * ( N + numWorkItemsPerXForm )) + string("] = a[") + num2str(i) + string("].y;\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

440
441
        for( i = 0; i < R0; i++ )
            kernelString += string("    a[") + num2str(i) + string("].y = lMemLoad[") + num2str(i * numWorkItemsPerXForm) + string("];\n");
Oliver Bock's avatar
Oliver Bock committed
442
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
443

Oliver Bock's avatar
Oliver Bock committed
444
        lMemSize = (N + numWorkItemsPerXForm) * numXFormsPerWG;
445
    }
Oliver Bock's avatar
Oliver Bock committed
446

Oliver Bock's avatar
Oliver Bock committed
447
    return lMemSize;
448
449
450
451
452
}

static int
insertGlobalStoresAndTranspose(string &kernelString, int N, int maxRadix, int Nr, int numWorkItemsPerXForm, int numXFormsPerWG, int mem_coalesce_width, clFFT_DataFormat dataFormat)
{
Oliver Bock's avatar
Oliver Bock committed
453
454
455
456
457
    int groupSize = numWorkItemsPerXForm * numXFormsPerWG;
    int i, j, k, ind;
    int lMemSize = 0;
    int numIter = maxRadix / Nr;
    string indent = string("");
Oliver Bock's avatar
Oliver Bock committed
458

459
    if( numWorkItemsPerXForm >= mem_coalesce_width )
Oliver Bock's avatar
Oliver Bock committed
460
    {
Oliver Bock's avatar
Oliver Bock committed
461
462
        if(numXFormsPerWG > 1)
        {
463
            kernelString += string("    if( !s || (groupId < get_num_groups(0)-1) || (jj < s) ) {\n");
Oliver Bock's avatar
Oliver Bock committed
464
465
466
467
468
469
470
471
472
473
474
            indent = string("    ");
        }
        for(i = 0; i < maxRadix; i++)
        {
            j = i % numIter;
            k = i / numIter;
            ind = j * Nr + k;
            formattedStore(kernelString, ind, i*numWorkItemsPerXForm, dataFormat);
        }
        if(numXFormsPerWG > 1)
            kernelString += string("    }\n");
475
476
477
478
479
    }
    else if( N >= mem_coalesce_width )
    {
        int numInnerIter = N / mem_coalesce_width;
        int numOuterIter = numXFormsPerWG / ( groupSize / mem_coalesce_width );
Oliver Bock's avatar
Oliver Bock committed
480
481

        kernelString += string("    lMemLoad  = sMem + mad24( jj, ") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
482
483
484
        kernelString += string("    ii = lId & ") + num2str(mem_coalesce_width - 1) + string(";\n");
        kernelString += string("    jj = lId >> ") + num2str((int)log2(mem_coalesce_width)) + string(";\n");
        kernelString += string("    lMemStore = sMem + mad24( jj,") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
Oliver Bock's avatar
Oliver Bock committed
485

486
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
487
488
489
490
        {
            j = i % numIter;
            k = i / numIter;
            ind = j * Nr + k;
Oliver Bock's avatar
Oliver Bock committed
491
            kernelString += string("    lMemLoad[") + num2str(i*numWorkItemsPerXForm) + string("] = a[") + num2str(ind) + string("].x;\n");
Oliver Bock's avatar
Oliver Bock committed
492
        }
Oliver Bock's avatar
Oliver Bock committed
493
494
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

495
        for( i = 0; i < numOuterIter; i++ )
Oliver Bock's avatar
Oliver Bock committed
496
497
            for( j = 0; j < numInnerIter; j++ )
                kernelString += string("    a[") + num2str(i*numInnerIter + j) + string("].x = lMemStore[") + num2str(j*mem_coalesce_width + i*( groupSize / mem_coalesce_width )*(N + numWorkItemsPerXForm)) + string("];\n");
498
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
499

500
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
501
502
503
504
        {
            j = i % numIter;
            k = i / numIter;
            ind = j * Nr + k;
Oliver Bock's avatar
Oliver Bock committed
505
            kernelString += string("    lMemLoad[") + num2str(i*numWorkItemsPerXForm) + string("] = a[") + num2str(ind) + string("].y;\n");
Oliver Bock's avatar
Oliver Bock committed
506
        }
Oliver Bock's avatar
Oliver Bock committed
507
508
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

509
        for( i = 0; i < numOuterIter; i++ )
Oliver Bock's avatar
Oliver Bock committed
510
511
            for( j = 0; j < numInnerIter; j++ )
                kernelString += string("    a[") + num2str(i*numInnerIter + j) + string("].y = lMemStore[") + num2str(j*mem_coalesce_width + i*( groupSize / mem_coalesce_width )*(N + numWorkItemsPerXForm)) + string("];\n");
Oliver Bock's avatar
Oliver Bock committed
512
513
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

Oliver Bock's avatar
Oliver Bock committed
514
515
        kernelString += string("if((groupId == get_num_groups(0)-1) && s) {\n");
        for(i = 0; i < numOuterIter; i++ )
516
517
        {
            kernelString += string("    if( jj < s ) {\n");
Oliver Bock's avatar
Oliver Bock committed
518
519
520
521
522
            for(j = 0; j < numInnerIter; j++ )
                formattedStore(kernelString, i*numInnerIter + j, j*mem_coalesce_width + i*(groupSize/mem_coalesce_width)*N, dataFormat);
            kernelString += string("    }\n");
            if(i != numOuterIter - 1)
                kernelString += string("    jj += ") + num2str(groupSize / mem_coalesce_width) + string(";\n");
523
        }
Oliver Bock's avatar
Oliver Bock committed
524
525
526
        kernelString += string("}\n");
        kernelString += string("else {\n");
        for(i = 0; i < numOuterIter; i++ )
527
        {
Oliver Bock's avatar
Oliver Bock committed
528
529
            for(j = 0; j < numInnerIter; j++ )
                formattedStore(kernelString, i*numInnerIter + j, j*mem_coalesce_width + i*(groupSize/mem_coalesce_width)*N, dataFormat);
Oliver Bock's avatar
Oliver Bock committed
530
        }
Oliver Bock's avatar
Oliver Bock committed
531
        kernelString += string("}\n");
Oliver Bock's avatar
Oliver Bock committed
532

Oliver Bock's avatar
Oliver Bock committed
533
534
        lMemSize = (N + numWorkItemsPerXForm) * numXFormsPerWG;
    }
535
    else
Oliver Bock's avatar
Oliver Bock committed
536
537
538
    {
        kernelString += string("    lMemLoad  = sMem + mad24( jj,") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");

Oliver Bock's avatar
Oliver Bock committed
539
        kernelString += string("    ii = lId & ") + num2str(N - 1) + string(";\n");
540
541
        kernelString += string("    jj = lId >> ") + num2str((int) log2(N)) + string(";\n");
        kernelString += string("    lMemStore = sMem + mad24( jj,") + num2str(N + numWorkItemsPerXForm) + string(", ii );\n");
Oliver Bock's avatar
Oliver Bock committed
542

543
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
544
545
546
547
        {
            j = i % numIter;
            k = i / numIter;
            ind = j * Nr + k;
548
            kernelString += string("    lMemLoad[") + num2str(i*numWorkItemsPerXForm) + string("] = a[") + num2str(ind) + string("].x;\n");
Oliver Bock's avatar
Oliver Bock committed
549
        }
550
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
551

552
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
553
554
555
            kernelString += string("    a[") + num2str(i) + string("].x = lMemStore[") + num2str(i*( groupSize / N )*( N + numWorkItemsPerXForm )) + string("];\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

556
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
557
558
559
560
        {
            j = i % numIter;
            k = i / numIter;
            ind = j * Nr + k;
561
            kernelString += string("    lMemLoad[") + num2str(i*numWorkItemsPerXForm) + string("] = a[") + num2str(ind) + string("].y;\n");
Oliver Bock's avatar
Oliver Bock committed
562
        }
563
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");
Oliver Bock's avatar
Oliver Bock committed
564

565
        for( i = 0; i < maxRadix; i++ )
Oliver Bock's avatar
Oliver Bock committed
566
567
568
            kernelString += string("    a[") + num2str(i) + string("].y = lMemStore[") + num2str(i*( groupSize / N )*( N + numWorkItemsPerXForm )) + string("];\n");
        kernelString += string("    barrier( CLK_LOCAL_MEM_FENCE );\n");

Oliver Bock's avatar
Oliver Bock committed
569
570
        kernelString += string("if((groupId == get_num_groups(0)-1) && s) {\n");
        for( i = 0; i < maxRadix; i++ )
571
572
        {
            kernelString += string("    if(jj < s ) {\n");
Oliver Bock's avatar
Oliver Bock committed
573
574
575
576
            formattedStore(kernelString, i, i*groupSize, dataFormat);
            kernelString += string("    }\n");
            if( i != maxRadix - 1)
                kernelString += string("    jj +=") + num2str(groupSize / N) + string(";\n");
Oliver Bock's avatar
Oliver Bock committed
577
        }
Oliver Bock's avatar
Oliver Bock committed
578
579
580
        kernelString += string("}\n");
        kernelString += string("else {\n");
        for( i = 0; i < maxRadix; i++ )
581
        {
Oliver Bock's avatar
Oliver Bock committed
582
            formattedStore(kernelString, i, i*groupSize, dataFormat);
Oliver Bock's avatar
Oliver Bock committed
583
        }
Oliver Bock's avatar
Oliver Bock committed
584
        kernelString += string("}\n");
Oliver Bock's avatar
Oliver Bock committed
585

Oliver Bock's avatar
Oliver Bock committed
586
        lMemSize = (N + numWorkItemsPerXForm) * numXFormsPerWG;
587
    }
Oliver Bock's avatar
Oliver Bock committed
588

Oliver Bock's avatar
Oliver Bock committed
589
    return lMemSize;
590
591
}

Oliver Bock's avatar
Oliver Bock committed
592
static void
593
594
insertfftKernel(string &kernelString, int Nr, int numIter)
{
Oliver Bock's avatar
Oliver Bock committed
595
596
597
598
599
    int i;
    for(i = 0; i < numIter; i++)
    {
        kernelString += string("    fftKernel") + num2str(Nr) + string("(a+") + num2str(i*Nr) + string(", dir);\n");
    }
600
601
}

602
603


604
605
606
static void
insertTwiddleKernel(string &kernelString, int Nr, int numIter, int Nprev, int len, int numWorkItemsPerXForm)
{
Oliver Bock's avatar
Oliver Bock committed
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
    int z, k;
    int logNPrev = log2(Nprev);

    for(z = 0; z < numIter; z++)
    {
        if(z == 0)
        {
            if(Nprev > 1)
                kernelString += string("    angf = (float) (ii >> ") + num2str(logNPrev) + string(");\n");
            else
                kernelString += string("    angf = (float) ii;\n");
        }
        else
        {
            if(Nprev > 1)
                kernelString += string("    angf = (float) ((") + num2str(z*numWorkItemsPerXForm) + string(" + ii) >>") + num2str(logNPrev) + string(");\n");
            else
                kernelString += string("    angf = (float) (") + num2str(z*numWorkItemsPerXForm) + string(" + ii);\n");
        }

        for(k = 1; k < Nr; k++) {
            int ind = z*Nr + k;
            //float fac =  (float) (2.0 * M_PI * (double) k / (double) len);
            kernelString += string("    ang = dir * ( 2.0f * M_PI * ") + num2str(k) + string(".0f / ") + num2str(len) + string(".0f )") + string(" * angf;\n");
            kernelString += string("    w = (float2)(native_cos(ang), native_sin(ang));\n");
            kernelString += string("    a[") + num2str(ind) + string("] = complexMul(a[") + num2str(ind) + string("], w);\n");
        }
    }
635
636
}

637
638
639
640




641
642
643
static int
getPadding(int numWorkItemsPerXForm, int Nprev, int numWorkItemsReq, int numXFormsPerWG, int Nr, int numBanks, int *offset, int *midPad)
{
Oliver Bock's avatar
Oliver Bock committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    if((numWorkItemsPerXForm <= Nprev) || (Nprev >= numBanks))
        *offset = 0;
    else {
        int numRowsReq = ((numWorkItemsPerXForm < numBanks) ? numWorkItemsPerXForm : numBanks) / Nprev;
        int numColsReq = 1;
        if(numRowsReq > Nr)
            numColsReq = numRowsReq / Nr;
        numColsReq = Nprev * numColsReq;
        *offset = numColsReq;
    }

    if(numWorkItemsPerXForm >= numBanks || numXFormsPerWG == 1)
        *midPad = 0;
    else {
        int bankNum = ( (numWorkItemsReq + *offset) * Nr ) & (numBanks - 1);
        if( bankNum >= numWorkItemsPerXForm )
            *midPad = 0;
        else
            *midPad = numWorkItemsPerXForm - bankNum;
    }

    int lMemSize = ( numWorkItemsReq + *offset) * Nr * numXFormsPerWG + *midPad * (numXFormsPerWG - 1);
    return lMemSize;
667
668
669
}


Oliver Bock's avatar
Oliver Bock committed
670
static void
671
672
insertLocalStores(string &kernelString, int numIter, int Nr, int numWorkItemsPerXForm, int numWorkItemsReq, int offset, string &comp)
{
Oliver Bock's avatar
Oliver Bock committed
673
674
675
676
677
678
679
680
681
    int z, k;

    for(z = 0; z < numIter; z++) {
        for(k = 0; k < Nr; k++) {
            int index = k*(numWorkItemsReq + offset) + z*numWorkItemsPerXForm;
            kernelString += string("    lMemStore[") + num2str(index) + string("] = a[") + num2str(z*Nr + k) + string("].") + comp + string(";\n");
        }
    }
    kernelString += string("    barrier(CLK_LOCAL_MEM_FENCE);\n");
682
683
}

Oliver Bock's avatar
Oliver Bock committed
684
static void
685
686
insertLocalLoads(string &kernelString, int n, int Nr, int Nrn, int Nprev, int Ncurr, int numWorkItemsPerXForm, int numWorkItemsReq, int offset, string &comp)
{
Oliver Bock's avatar
Oliver Bock committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
    int numWorkItemsReqN = n / Nrn;
    int interBlockHNum = max( Nprev / numWorkItemsPerXForm, 1 );
    int interBlockHStride = numWorkItemsPerXForm;
    int vertWidth = max(numWorkItemsPerXForm / Nprev, 1);
    vertWidth = min( vertWidth, Nr);
    int vertNum = Nr / vertWidth;
    int vertStride = ( n / Nr + offset ) * vertWidth;
    int iter = max( numWorkItemsReqN / numWorkItemsPerXForm, 1);
    int intraBlockHStride = (numWorkItemsPerXForm / (Nprev*Nr)) > 1 ? (numWorkItemsPerXForm / (Nprev*Nr)) : 1;
    intraBlockHStride *= Nprev;

    int stride = numWorkItemsReq / Nrn;
    int i;
    for(i = 0; i < iter; i++) {
        int ii = i / (interBlockHNum * vertNum);
        int zz = i % (interBlockHNum * vertNum);
        int jj = zz % interBlockHNum;
        int kk = zz / interBlockHNum;
        int z;
        for(z = 0; z < Nrn; z++) {
            int st = kk * vertStride + jj * interBlockHStride + ii * intraBlockHStride + z * stride;
            kernelString += string("    a[") + num2str(i*Nrn + z) + string("].") + comp + string(" = lMemLoad[") + num2str(st) + string("];\n");
        }
    }
711
    
Oliver Bock's avatar
Oliver Bock committed
712
    kernelString += string("    barrier(CLK_LOCAL_MEM_FENCE);\n");
713
714
715
716
}

static void
insertLocalLoadIndexArithmatic(string &kernelString, int Nprev, int Nr, int numWorkItemsReq, int numWorkItemsPerXForm, int numXFormsPerWG, int offset, int midPad)
Oliver Bock's avatar
Oliver Bock committed
717
{
Oliver Bock's avatar
Oliver Bock committed
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
    int Ncurr = Nprev * Nr;
    int logNcurr = log2(Ncurr);
    int logNprev = log2(Nprev);
    int incr = (numWorkItemsReq + offset) * Nr + midPad;

    if(Ncurr < numWorkItemsPerXForm)
    {
        if(Nprev == 1)
            kernelString += string("    j = ii & ") + num2str(Ncurr - 1) + string(";\n");
        else
            kernelString += string("    j = (ii & ") + num2str(Ncurr - 1) + string(") >> ") + num2str(logNprev) + string(";\n");

        if(Nprev == 1)
            kernelString += string("    i = ii >> ") + num2str(logNcurr) + string(";\n");
        else
            kernelString += string("    i = mad24(ii >> ") + num2str(logNcurr) + string(", ") + num2str(Nprev) + string(", ii & ") + num2str(Nprev - 1) + string(");\n");
    }
    else
    {
        if(Nprev == 1)
            kernelString += string("    j = ii;\n");
        else
            kernelString += string("    j = ii >> ") + num2str(logNprev) + string(";\n");
        if(Nprev == 1)
            kernelString += string("    i = 0;\n");
        else
            kernelString += string("    i = ii & ") + num2str(Nprev - 1) + string(";\n");
    }
746
747

    if(numXFormsPerWG > 1)
Oliver Bock's avatar
Oliver Bock committed
748
        kernelString += string("    i = mad24(jj, ") + num2str(incr) + string(", i);\n");
749

Oliver Bock's avatar
Oliver Bock committed
750
    kernelString += string("    lMemLoad = sMem + mad24(j, ") + num2str(numWorkItemsReq + offset) + string(", i);\n");
751
752
753
754
755
}

static void
insertLocalStoreIndexArithmatic(string &kernelString, int numWorkItemsReq, int numXFormsPerWG, int Nr, int offset, int midPad)
{
Oliver Bock's avatar
Oliver Bock committed
756
757
758
759
760
761
    if(numXFormsPerWG == 1) {
        kernelString += string("    lMemStore = sMem + ii;\n");
    }
    else {
        kernelString += string("    lMemStore = sMem + mad24(jj, ") + num2str((numWorkItemsReq + offset)*Nr + midPad) + string(", ii);\n");
    }
762
763
764
}


765
766
767
768
769
770
771
772
773
static void
insertLocalSinCosLUT(string & kernel_string, cl_fft_plan *plan, int workgroupsize) {
    
    // conditionally copy to local (shared) memory 
    
    if(plan->twiddleMethod == clFFT_TaylorLUT) {
        // LUT holds grid values for Taylor seres approx
        kernel_string += string(" __local  float2  cossin_T_LUT[256];\n");
        
774
775
776
        int sizeLUT= plan->N2;
        
        int m = (int) ceilf((float) sizeLUT / (float) workgroupsize);
777
778
779
780
        
        
        kernel_string += string(" int lLUTind= lId;       \n");     
        
781
        if (sizeLUT % workgroupsize != 0) kernel_string += string(" if(lLUTind < ") + num2str(sizeLUT) + string("){ \n");
782
        kernel_string += string("     cossin_T_LUT[lLUTind]=cossinLUT2[lLUTind]; \n");
783
        if (sizeLUT % workgroupsize  != 0)  kernel_string += string(" }\n");
784
785
786
        
        for(int k= 1 ; k < m ; k++) {
            kernel_string += string(" lLUTind+=") + num2str(workgroupsize) + string(";\n");
787
            if (sizeLUT % workgroupsize != 0) kernel_string += string(" if(lLUTind < ") + num2str(sizeLUT) + string("){ \n");
788
            kernel_string += string("     cossin_T_LUT[lLUTind]=cossinLUT2[lLUTind]; \n");
789
            if (sizeLUT % workgroupsize != 0) kernel_string += string(" }\n");
790
791
792
793
794
795
796
        }
        
        kernel_string += string(" barrier(CLK_LOCAL_MEM_FENCE);\n");
    }
}


797
798
799
static void
createLocalMemfftKernelString(cl_fft_plan *plan)
{
Oliver Bock's avatar
Oliver Bock committed
800
801
802
803
    unsigned int radixArray[10];
    unsigned int numRadix;

    unsigned int n = plan->n.x;
Oliver Bock's avatar
Oliver Bock committed
804

Oliver Bock's avatar
Oliver Bock committed
805
    assert(n <= plan->max_work_item_per_workgroup * plan->max_radix && "signal lenght too big for local mem fft\n");
Oliver Bock's avatar
Oliver Bock committed
806

Oliver Bock's avatar
Oliver Bock committed
807
808
    getRadixArray(n, radixArray, &numRadix, 0);
    assert(numRadix > 0 && "no radix array supplied\n");
Oliver Bock's avatar
Oliver Bock committed
809

Oliver Bock's avatar
Oliver Bock committed
810
811
    if(n/radixArray[0] > plan->max_work_item_per_workgroup)
        getRadixArray(n, radixArray, &numRadix, plan->max_radix);
Oliver Bock's avatar
Oliver Bock committed
812

Oliver Bock's avatar
Oliver Bock committed
813
814
    assert(radixArray[0] <= plan->max_radix && "max radix choosen is greater than allowed\n");
    assert(n/radixArray[0] <= plan->max_work_item_per_workgroup && "required work items per xform greater than maximum work items allowed per work group for local mem fft\n");
815

Oliver Bock's avatar
Oliver Bock committed
816
817
818
819
820
821
822
823
    unsigned int tmpLen = 1;
    unsigned int i;
    for(i = 0; i < numRadix; i++)
    {
        assert( radixArray[i] && !( (radixArray[i] - 1) & radixArray[i] ) );
        tmpLen *= radixArray[i];
    }
    assert(tmpLen == n && "product of radices choosen doesnt match the length of signal\n");
Oliver Bock's avatar
Oliver Bock committed
824

Oliver Bock's avatar
Oliver Bock committed
825
826
    int offset, midPad;
    string localString(""), kernelName("");
Oliver Bock's avatar
Oliver Bock committed
827

Oliver Bock's avatar
Oliver Bock committed
828
829
    clFFT_DataFormat dataFormat = plan->format;
    string *kernelString = plan->kernel_string;
Oliver Bock's avatar
Oliver Bock committed
830
831


Oliver Bock's avatar
Oliver Bock committed
832
833
    cl_fft_kernel_info **kInfo = &plan->kernel_info;
    int kCount = 0;
Oliver Bock's avatar
Oliver Bock committed
834

Oliver Bock's avatar
Oliver Bock committed
835
836
837
838
839
    while(*kInfo)
    {
        kInfo = &(*kInfo)->next;
        kCount++;
    }
Oliver Bock's avatar
Oliver Bock committed
840

Oliver Bock's avatar
Oliver Bock committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
    kernelName = string("fft") + num2str(kCount);

    *kInfo = (cl_fft_kernel_info *) malloc(sizeof(cl_fft_kernel_info));
    (*kInfo)->kernel = 0;
    (*kInfo)->lmem_size = 0;
    (*kInfo)->num_workgroups = 0;
    (*kInfo)->num_workitems_per_workgroup = 0;
    (*kInfo)->dir = cl_fft_kernel_x;
    (*kInfo)->in_place_possible = 1;
    (*kInfo)->next = NULL;
    (*kInfo)->kernel_name = (char *) malloc(sizeof(char)*(kernelName.size()+1));
    strcpy((*kInfo)->kernel_name, kernelName.c_str());

    unsigned int numWorkItemsPerXForm = n / radixArray[0];
    unsigned int numWorkItemsPerWG = numWorkItemsPerXForm <= 64 ? 64 : numWorkItemsPerXForm;
    assert(numWorkItemsPerWG <= plan->max_work_item_per_workgroup);
    int numXFormsPerWG = numWorkItemsPerWG / numWorkItemsPerXForm;
    (*kInfo)->num_workgroups = 1;
    (*kInfo)->num_xforms_per_workgroup = numXFormsPerWG;
    (*kInfo)->num_workitems_per_workgroup = numWorkItemsPerWG;
Oliver Bock's avatar
Oliver Bock committed
861

Oliver Bock's avatar
Oliver Bock committed
862
863
864
    unsigned int *N = radixArray;
    unsigned int maxRadix = N[0];
    unsigned int lMemSize = 0;
Oliver Bock's avatar
Oliver Bock committed
865

Oliver Bock's avatar
Oliver Bock committed
866
    insertVariables(localString, maxRadix);
867
    insertLocalSinCosLUT(localString, plan, numWorkItemsPerWG);
Oliver Bock's avatar
Oliver Bock committed
868

Oliver Bock's avatar
Oliver Bock committed
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
    lMemSize = insertGlobalLoadsAndTranspose(localString, n, numWorkItemsPerXForm, numXFormsPerWG, maxRadix, plan->min_mem_coalesce_width, dataFormat);
    (*kInfo)->lmem_size = (lMemSize > (*kInfo)->lmem_size) ? lMemSize : (*kInfo)->lmem_size;

    string xcomp = string("x");
    string ycomp = string("y");

    unsigned int Nprev = 1;
    unsigned int len = n;
    unsigned int r;
    for(r = 0; r < numRadix; r++)
    {
        int numIter = N[0] / N[r];
        int numWorkItemsReq = n / N[r];
        int Ncurr = Nprev * N[r];
        insertfftKernel(localString, N[r], numIter);

        if(r < (numRadix - 1)) {
            insertTwiddleKernel(localString, N[r], numIter, Nprev, len, numWorkItemsPerXForm);
            lMemSize = getPadding(numWorkItemsPerXForm, Nprev, numWorkItemsReq, numXFormsPerWG, N[r], plan->num_local_mem_banks, &offset, &midPad);
            (*kInfo)->lmem_size = (lMemSize > (*kInfo)->lmem_size) ? lMemSize : (*kInfo)->lmem_size;
            insertLocalStoreIndexArithmatic(localString, numWorkItemsReq, numXFormsPerWG, N[r], offset, midPad);
            insertLocalLoadIndexArithmatic(localString, Nprev, N[r], numWorkItemsReq, numWorkItemsPerXForm, numXFormsPerWG, offset, midPad);
            insertLocalStores(localString, numIter, N[r], numWorkItemsPerXForm, numWorkItemsReq, offset, xcomp);
            insertLocalLoads(localString, n, N[r], N[r+1], Nprev, Ncurr, numWorkItemsPerXForm, numWorkItemsReq, offset, xcomp);
            insertLocalStores(localString, numIter, N[r], numWorkItemsPerXForm, numWorkItemsReq, offset, ycomp);
            insertLocalLoads(localString, n, N[r], N[r+1], Nprev, Ncurr, numWorkItemsPerXForm, numWorkItemsReq, offset, ycomp);
            Nprev = Ncurr;
            len = len / N[r];
        }
    }

    lMemSize = insertGlobalStoresAndTranspose(localString, n, maxRadix, N[numRadix - 1], numWorkItemsPerXForm, numXFormsPerWG, plan->min_mem_coalesce_width, dataFormat);
    (*kInfo)->lmem_size = (lMemSize > (*kInfo)->lmem_size) ? lMemSize : (*kInfo)->lmem_size;

    insertHeader(*kernelString, kernelName, dataFormat);
    *kernelString += string("{\n");
    if((*kInfo)->lmem_size)
906
        *kernelString += string("    __local float sMem[") + num2str((*kInfo)->lmem_size) + string("];\n");
Oliver Bock's avatar
Oliver Bock committed
907
908
    *kernelString += localString;
    *kernelString += string("}\n");
909
910
911
912
913
914
}

// For n larger than what can be computed using local memory fft, global transposes
// multiple kernel launces is needed. For these sizes, n can be decomposed using
// much larger base radices i.e. say n = 262144 = 128 x 64 x 32. Thus three kernel
// launches will be needed, first computing 64 x 32, length 128 ffts, second computing
Oliver Bock's avatar
Oliver Bock committed
915
916
917
918
919
920
921
// 128 x 32 length 64 ffts, and finally a kernel computing 128 x 64 length 32 ffts.
// Each of these base radices can futher be divided into factors so that each of these
// base ffts can be computed within one kernel launch using in-register ffts and local
// memory transposes i.e for the first kernel above which computes 64 x 32 ffts on length
// 128, 128 can be decomposed into 128 = 16 x 8 i.e. 8 work items can compute 8 length
// 16 ffts followed by transpose using local memory followed by each of these eight
// work items computing 2 length 8 ffts thus computing 16 length 8 ffts in total. This
922
923
// means only 8 work items are needed for computing one length 128 fft. If we choose
// work group size of say 64, we can compute 64/8 = 8 length 128 ffts within one
Oliver Bock's avatar
Oliver Bock committed
924
925
// work group. Since we need to compute 64 x 32 length 128 ffts in first kernel, this
// means we need to launch 64 x 32 / 8 = 256 work groups with 64 work items in each
926
927
// work group where each work group is computing 8 length 128 ffts where each length
// 128 fft is computed by 8 work items. Same logic can be applied to other two kernels
Oliver Bock's avatar
Oliver Bock committed
928
// in this example. Users can play with difference base radices and difference
929
930
931
932
933
934
// decompositions of base radices to generates different kernels and see which gives
// best performance. Following function is just fixed to use 128 as base radix

void
getGlobalRadixInfo(int n, int *radix, int *R1, int *R2, int *numRadices)
{
Oliver Bock's avatar
Oliver Bock committed
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
    int baseRadix = min(n, 128);

    int numR = 0;
    int N = n;
    while(N > baseRadix)
    {
        N /= baseRadix;
        numR++;
    }

    for(int i = 0; i < numR; i++)
        radix[i] = baseRadix;

    radix[numR] = N;
    numR++;
    *numRadices = numR;

    for(int i = 0; i < numR; i++)
    {
        int B = radix[i];
        if(B <= 8)
        {
            R1[i] = B;
            R2[i] = 1;
            continue;
        }

        int r1 = 2;
        int r2 = B / r1;
        while(r2 > r1)
        {
           r1 *=2;
           r2 = B / r1;
        }
        R1[i] = r1;
        R2[i] = r2;
    }
972
973
}

974
975
976
977
978
979
980
981
// generate code to calculate cos(w),sin(w) and assign to a variable varRes 
// where w= dir * 2.0 * PI * num/denom * {expr}
// and    dir is a variable in the generated code
//        PI can be assumed to be defined by the macro M_PI
//        num and denom are integers passed to the function
//        expr is C++ code for an expression evaluating to an integer, 
//             such that num * value(expr)< denom

982
983


984
static void 
985
insertSinCosCalcDirectNative(string & kernel_string, cl_fft_plan *plan, int num, int denom , string & expr, string & varRes) 
986
{
987
988
989
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    const char format[] = "%a"; 
#else
990
    const char format[] = "%.10e";
991
992
#endif

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
    if(denom & (denom-1)) {
        kernel_string += string("ang = dir*(2.0f*M_PI*") + num2str(num) + string("/") + num2str(denom) + string(")*("+expr+");\n");        
    } else {
        // denom is a power of two  
        int logDenom =0;
        int d= denom;
        while (d != 1) {
            logDenom++;
            d >>= 1;
        }
        int pi_exp=1+1-logDenom;
        string pi_mult_hex = string("0x1.921fb54442d18p") + (pi_exp>0 ? string("+") : string("")) + num2str(pi_exp);
        switch (num) { 
            case 0 : 
                kernel_string += string("ang = 0.0f;\n");  
                break;
            case 1 : 
                kernel_string += string("ang = dir*(" + pi_mult_hex + string(") * (")+expr+");\n");   
                break;
            default:     
                float pi2=0x1.921fb54442d18p+2;
                char tw[200];
1015
                sprintf(tw,format,pi2*num / (float) denom);
1016
1017
1018
1019
1020
1021
1022
                kernel_string += string("ang = dir*(" + string(tw) + string(") * (")+expr+");\n"); 
                break;
        }
    }
    kernel_string += varRes+string(" = (float2)(native_cos(ang), native_sin(ang));\n");
}

1023
1024
1025
static void
insertSinCosCalcDirect(string & kernel_string, cl_fft_plan *plan, int num, int denom , string & expr, string & varRes)
{
1026
1027
1028
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    const char format[] = "%a";
#else
1029
    const char format[] = "%.10e";
1030
1031
#endif

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
  if(denom & (denom-1)) {
    kernel_string += string("ang = dir*(2.0f*M_PI*") + num2str(num) + string("/") + num2str(denom) + string(")*("+expr+");\n");
  } else {
    // denom is a power of two                                                                                                                                                                                          
    int logDenom =0;
    int d= denom;
    while (d != 1) {
      logDenom++;
      d >>= 1;
    }
    int pi_exp=1+1-logDenom;
    string pi_mult_hex = string("0x1.921fb54442d18p") + (pi_exp>0 ? string("+") : string("")) + num2str(pi_exp);
    switch (num) {
    case 0 :
      kernel_string += string("ang = 0.0f;\n");
      break;
    case 1 :
      kernel_string += string("ang = dir*(" + pi_mult_hex + string(") * (")+expr+");\n");
      break;
    default:
      float pi2=0x1.921fb54442d18p+2;
      char tw[200];
1054
      sprintf(tw,format,pi2*num / (float) denom);
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
      kernel_string += string("ang = dir*(" + string(tw) + string(") * (")+expr+");\n");
      break;
    }
  }
   
  kernel_string += string("{\n");
  kernel_string += string(" float _tmpcos,_tmpsin;\n");
  kernel_string += string(" _tmpsin=sincos(ang,&_tmpcos);\n");
  kernel_string += varRes+string(" = (float2)(_tmpcos, _tmpsin);\n");
  kernel_string += string("}\n");
 
}


1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
static void 
insertSinCosCalc(string & kernel_string, cl_fft_plan *plan, int num, int denom , string & expr, string & varRes) 
{
    if(denom & (denom-1)) {
        kernel_string += string("ang = dir*(2.0f*M_PI*") + num2str(num) + string("/") + num2str(denom) + string(")*("+expr+");\n");        
        kernel_string += varRes+string(" = (float2)(native_cos(ang), native_sin(ang));\n");
    } else {

        switch (num) { 
            case 0 : 
                kernel_string += string("ang = 0.0f;\n");  
                kernel_string += varRes+string(" = (float2)(1.0f, 0.0f);\n");
                break;
            default:     
                int num_norm = num*(plan->N1 * plan->N2)/denom;
                
                if(num_norm % plan->N1 == 0) {
                    
                    kernel_string += string("{ int ang_index = ") + num2str(num_norm) + string(" * ( ") + expr + string(") ; \n");  
                    kernel_string += string("  int ang_index_k = (ang_index >> " ) + num2str(plan->logN1)+ string(") & "+num2str(plan->N2-1)+ ";\n");
1089
                    kernel_string += string("  cos_sinLUT1("+varRes+",dir,ang_index_k,cossinLUT2);\n");
1090
1091
1092
1093
1094
                    kernel_string += string("}\n");
                } else {
                    kernel_string += string("{ int ang_index = ") + num2str(num_norm) + string(" * ( ") + expr + string(") ; \n");  
                    kernel_string += string("  int ang_index_k = ((ang_index >> " ) + num2str(plan->logN1)+ string(") & "+num2str(plan->N2-1)+ ");\n");
                    kernel_string += string("  int ang_index_i = (ang_index & " ) + num2str(plan->N1-1)+ string(");\n");
1095
                    kernel_string += string("  cos_sinLUT2("+varRes+",dir,ang_index_i,ang_index_k,cossinLUT1,cossinLUT2);\n");
1096
1097
1098
1099
1100
1101
1102
1103
                    kernel_string += string("}\n");

                }    
                break;
        }
    }
}

1104
1105
1106
1107
1108
// pedantic : use Taylor series approx to degree 3, on 64 grid points between [0,2pi[

static void
insertSinCosCalcTaylor3(string & kernel_string, cl_fft_plan *plan, int num, int denom , string & expr, string & varRes)
{
1109
1110
1111
1112

#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    const char format[] = "%a";
#else
1113
    const char format[] = "%.10e";
1114
1115
1116
#endif


1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
  if(denom & (denom-1)) {
    kernel_string += string("ang = dir*(2.0f*M_PI*") + num2str(num) + string("/") + num2str(denom) + string(")*("+expr+");\n");
    kernel_string += varRes+string(" = (float2)(native_cos(ang), native_sin(ang));\n");
  } else {

    switch (num) {
    case 0 :
      kernel_string += string("ang = 0.0f;\n");
      kernel_string += varRes+string(" = (float2)(1.0f, 0.0f);\n");
      break;
    default:
            
      // normalize num,denom while num is even
      while((num % 2 ==0 ) && (denom %2 == 0) ){
        denom >>=1;
        num >>=1;
      }
      // if normalized denom < grid size, pick directly from LUT. 
1135
      if((size_t) denom <= plan->N2) {
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
          kernel_string += string("{ int ang_index = (") + num2str(num) + string(" * ( ") + expr + string(")) & ") + num2str(denom -1)   + string("; \n");
          kernel_string += string("  int k = ang_index * ") + num2str(plan->N2 / denom ) + string(";\n");
          kernel_string += string("  float2 cs =cossin_T_LUT[k];\n");                     
          kernel_string += string("  cs.y *=dir;\n");
          
          kernel_string += varRes + string(" = cs;\n");
          kernel_string += string("}\n");
          
                
      } else {
          kernel_string += string("{ int ang_index = (") + num2str(num) + string(" * ( ") + expr + string(")) & ") + num2str(denom -1)   + string("; \n");
      
          // find nearest bin in grid
      
          int logDenom=0;
          int d = denom;
          while (d > 1) {
              d>>=1;
              logDenom++;
          }
          
1157
          kernel_string += string(" int k = (ang_index +  ") + num2str( 1 <<(logDenom - plan->logN2 -1) ) + string(") >> ") + num2str(logDenom - plan->logN2) +string( ";\n");    
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
          
	      // get cos/sin of grid point from LUT                                                                                                                                                                            

          kernel_string += string(" float2 csx0 =cossin_T_LUT[k];\n");                     
          kernel_string += string(" float2 csx0Transp= (float2)(csx0.y,-csx0.x);\n");
          kernel_string += string(" int    r=ang_index - k * ( ")+ num2str(denom >> plan->logN2) + string(" );\n") ; 

        
	      // calculate distance (with sign) from this grid point
          // DO NOT calculate teh angles here directly and subtract as this will deteriorate precision.
          // precompute h0=2*pi/denom;
          float pi2=0x1.921fb54442d18p+2;
          char tw[200];
1171
          sprintf(tw,format,-pi2/(float) denom);
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
          kernel_string += string("  float mh=") +string(tw)+string("*(float)r;\n"); 

          // compute taylor series terms to order 3 and add them up, in "reverse" order (highest order first)

          kernel_string += string("  float mhsqr2= mh*mh*(-0.5f);\n"); 
          kernel_string += string("  float hqub6= mhsqr2*mh*(1.0f/3.0f);\n"); 
          kernel_string += string("  float2 cs;\n"); // we could use varRes in the first place here..
          kernel_string += string("   cs= hqub6 * csx0Transp;\n");

          kernel_string += string("   cs += mhsqr2*csx0;\n");

          kernel_string += string("   cs += mh*csx0Transp;\n");

          kernel_string += string("   cs += csx0;\n");

          kernel_string += string("   cs.y *=dir;\n");

          kernel_string += varRes + string(" = cs;\n");
          kernel_string += string("}\n");

      }
      break;
    }
  }    
}

static void 
insertSinCos(string & kernel_string, cl_fft_plan *plan, int num, int denom , string & expr, string & varRes) 
{
    switch (plan->twiddleMethod) {    
        case clFFT_sincosfunc : insertSinCosCalcDirect(kernel_string,plan,num,denom,expr,varRes); break;
        case clFFT_BigLUT     : insertSinCosCalc(kernel_string,plan,num,denom,expr,varRes); break;
        case clFFT_TaylorLUT  : insertSinCosCalcTaylor3(kernel_string,plan,num,denom,expr,varRes); break;
        default               : insertSinCosCalcDirectNative(kernel_string,plan,num,denom,expr,varRes); break;    
    }    
}

1209

1210

1211

1212
1213
static void
createGlobalFFTKernelString(cl_fft_plan *plan, int n, int BS, cl_fft_kernel_dir dir, int vertBS)
Oliver Bock's avatar
Oliver Bock committed
1214
{
Oliver Bock's avatar
Oliver Bock committed
1215
1216
    int i, j, k, t;
    int radixArr[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1217
1218
    int R1Arr[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    int R2Arr[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Oliver Bock's avatar
Oliver Bock committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
    int radix, R1, R2;
    int numRadices;

    int maxThreadsPerBlock = plan->max_work_item_per_workgroup;
    int maxArrayLen = plan->max_radix;
    int batchSize = plan->min_mem_coalesce_width;
    clFFT_DataFormat dataFormat = plan->format;
    int vertical = (dir == cl_fft_kernel_x) ? 0 : 1;

    getGlobalRadixInfo(n, radixArr, R1Arr, R2Arr, &numRadices);

    int numPasses = numRadices;

    string localString(""), kernelName("");
    string *kernelString = plan->kernel_string;
    cl_fft_kernel_info **kInfo = &plan->kernel_info;
    int kCount = 0;

    while(*kInfo)
    {
        kInfo = &(*kInfo)->next;
        kCount++;
    }

    int N = n;
    int m = (int)log2(n);
    int Rinit = vertical ? BS : 1;
    batchSize = vertical ? min(BS, batchSize) : batchSize;
    int passNum;
1248
    
Oliver Bock's avatar
Oliver Bock committed
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
    for(passNum = 0; passNum < numPasses; passNum++)
    {

        localString.clear();
        kernelName.clear();

        radix = radixArr[passNum];
        R1 =