Hack to try deleting file from build bots

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@229409 91177308-0d34-0410-b5e6-96231b3b80d8

// RUN: rm %S/cl-strict-aliasing.ll
// RUN: %clang_cc1 -x cl -emit-llvm -cl-strict-aliasing < %s


typo fix

typo fix

#ifndef VSMC_HELPER_PARALLEL_CL_COMMON_CL
#define VSMC_HELPER_PARALLEL_CL_COMMON_CL

#if defined(cl_khr_fp64)
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#elif defined(cl_amd_fp64)
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#else
#define R123_USE_U01_DOUBLE 0
#endif

#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/u01.h>

__kernel
void copy (__global state_struct *state, __global uint *source)
{
    size_type to = get_global_id(0);

    if (to >= Size)
        return;

    size_t from = source[to];
    if (to != from)
        state[to] = state[from];
}

#endif // VSMC_HELPER_PARALLEL_CL_COMMON_CL

#ifndef VSMC_HELPER_PARALLEL_CL_COMMON_CL
#define VSMC_HELPER_PARALLEL_CL_COMMON_CL

#if defined(cl_khr_fp64)
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#elif defined(cl_amd_fp64)
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#else
#define R123_USE_U01_DOUBLE 0
#endif

#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/u01.h>

__kernel
void copy (__global state_struct *state, __global uint *source)
{
    size_type to = get_global_id(0);

    if (to >= Size)
        return;

    size_t from = source[to];
    if (to != form)
        state[to] = state[from];
}

#endif // VSMC_HELPER_PARALLEL_CL_COMMON_CL


fmax float

fmax float

__kernel void harris_corner_response(
        __global hh_float* xx,
        __global hh_float* xy,
        __global hh_float* yy,
        __global hh_float* output,
        param_float sigmaD )
{
    int i = get_global_id(0);
    hh_float A = LOAD_HHF(xx,i) * pow(sigmaD, 2);
    hh_float B = LOAD_HHF(yy,i) * pow(sigmaD, 2);
    hh_float C = LOAD_HHF(xy,i) * pow(sigmaD, 2);

    STORE_HHF(output, i, A*B-C*C-CORNER_RESPONSE_ALPHA*pow(A+B,2));
}

__kernel void harris_corner_suppression(
        __global hh_float* in,
        __global hh_float* out,
        int width,
        int height )
{
    int2 c = (int2)(get_global_id(0),get_global_id(1));

    hh_float m = -HUGE_VALF;

    for( int y = -SUP_HALFWIDTH; y <= SUP_HALFWIDTH; y++ )
    {
        for( int x = -SUP_HALFWIDTH; x <= SUP_HALFWIDTH; x++ )
        {
            int2 lc = (int2)(il(x+c.x,0,width),il(y+c.y,0,height));
            m = fmax(m,(hh_float)LOAD_HHF(in,lc.x+lc.y*width));
        }
    }

    hh_float in_value = LOAD_HHF(in,c.x+c.y*width);
    if( m > in_value )
        STORE_HHF(out, c.x+c.y*width, 0.0f);
    else
        STORE_HHF(out, c.x+c.y*width, in_value);
}

__kernel void harris_count( __global hh_float* in, volatile __global uint* strong, volatile __global int* count )
{
    int i = get_global_id(0);

    hh_float value = LOAD_HHF(in, i);

    if( value > 0.0f )
    {
        atomic_inc( count );
        if( value > HARRIS_THRESHOLD )
        {
           strong[i] += 1;
        }
    }
}

__kernel void harris_corner_response(
        __global hh_float* xx,
        __global hh_float* xy,
        __global hh_float* yy,
        __global hh_float* output,
        param_float sigmaD )
{
    int i = get_global_id(0);
    hh_float A = LOAD_HHF(xx,i) * pow(sigmaD, 2);
    hh_float B = LOAD_HHF(yy,i) * pow(sigmaD, 2);
    hh_float C = LOAD_HHF(xy,i) * pow(sigmaD, 2);

    STORE_HHF(output, i, A*B-C*C-CORNER_RESPONSE_ALPHA*pow(A+B,2));
}

__kernel void harris_corner_suppression(
        __global hh_float* in,
        __global hh_float* out,
        int width,
        int height )
{
    int2 c = (int2)(get_global_id(0),get_global_id(1));

    hh_float m = -HUGE_VALF;

    for( int y = -SUP_HALFWIDTH; y <= SUP_HALFWIDTH; y++ )
    {
        for( int x = -SUP_HALFWIDTH; x <= SUP_HALFWIDTH; x++ )
        {
            int2 lc = (int2)(il(x+c.x,0,width),il(y+c.y,0,height));
            m = fmax(m,LOAD_HHF(in,lc.x+lc.y*width));
        }
    }

    hh_float in_value = LOAD_HHF(in,c.x+c.y*width);
    if( m > in_value )
        STORE_HHF(out, c.x+c.y*width, 0.0f);
    else
        STORE_HHF(out, c.x+c.y*width, in_value);
}

__kernel void harris_count( __global hh_float* in, volatile __global uint* strong, volatile __global int* count )
{
    int i = get_global_id(0);

    hh_float value = LOAD_HHF(in, i);

    if( value > 0.0f )
    {
        atomic_inc( count );
        if( value > HARRIS_THRESHOLD )
        {
           strong[i] += 1;
        }
    }
}


normalization vectorized. gemm vectorization missing

// -*- c++ -*-
// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This is a c-implementation of the PCA->MLP response map calculation

typedef struct {
    int rows;
    int cols;
    int step;
    int start;
} clMat; // struct clMatFloat

typedef struct {
    int size;
    int step;
    int start;
} clVector; // struct clVector

typedef struct {
    int m_patchSize;
    clMat /* uint8_t */ alignedImage;
    clMat /* int32_t */ shape;
    clMat /* float */ m_wOut;
    clMat /* float */ wIn;
    clMat /* float */ bIn;
} calcinput; // struct

typedef struct {
    int x;
    int y;
} Point2i; // struct Point2i

typedef struct {
    // results
    clMat /*float*/ responseMap;
} calcoutput;

typedef struct {
    calcinput  input;
    calcoutput output;
} calcpackage;

typedef struct {
    float shift;
    float stride;
} normalization;

__constant const int MAX_INT = ~(1 << (8*sizeof(int) - 1));
// __constant const int false = (1!=1);
__constant const bool precise = false;

clMat /*uint8_t*/
GetBlockChar( __local void * self, clMat /*uint8_t*/  smat, int row_from, int row_to, int col_from, int col_to )
{
    // assert(row_from>=0);
    // assert(col_from>=0);
    // assert(row_from<row_to);
    // assert(col_from<col_to);
    // assert(row_to<=smat.rows);
    // assert(col_to<=smat.cols);

    clMat /*uchar*/  result;
    result.rows  = row_to - row_from;
    result.cols  = col_to - col_from;
    result.step  = smat.step;
    result.start = smat.start + row_from * smat.step + col_from;

    return result;
}

clMat
GetBlockFloat( __local void * self, clMat /*float*/smat, int row_from, int row_to, int col_from, int col_to )
{
    // assert(row_from>=0);
    // assert(col_from>=0);
    // assert(row_from<row_to);
    // assert(col_from<col_to);
    // assert(row_to<=smat.rows);
    // assert(col_to<=smat.cols);

    clMat /*float*/result;
    result.rows  = row_to - row_from;
    result.cols  = col_to - col_from;
    result.step  = smat.step;
    result.start = smat.start + row_from * smat.step + col_from;

    return result;
}

// returns alpha*A*B + beta * C
float
gemmFloatDirDirDir(
    __local void * self,
    clMat /*float*/A,
    clMat /*uint8_t*/B,
    float alpha,
    clMat /*float*/C,
    float beta,
    normalization norm,
    clMat /* float */ dotmatrix//,
//    clMat /*float*/ result
    )
{
    // assert(A.rows == C.rows);
    // assert(A.cols == B.rows);
    // assert(B.cols == C.cols);
    // assert(C.rows == result.rows);
    // assert(C.cols == result.cols);
    // assert(C.cols == 1 );

    float sum=0.0f;
    float c=0.0f;
    float dot = 0.0f;

    for ( int q=0; q<C.rows; q++ ) {
        sum = 0;
        for ( int e=0; e<A.cols; e++ )
        {
            float a = ((__local float*)self)[ q * A.step + e + A.start ];
            int b_row = e / B.rows;
            int b_col = e % B.cols;
            float b = ((__local uchar*)self)[ b_row * B.step + b_col + B.start ];
            sum += a * (norm.shift + norm.stride * b);
        }

        float val    = alpha * sum  + beta * ((__local float*)self)[ q * C.step /* + w==0*/ + C.start ];
        float resval = 2.0f/(exp(val) + 1) - 1;

        dot += resval * ((__local float*)self)[ q + dotmatrix.start ];
    } // for q

    return dot;
} // gemmFloatDirDirDir

float
GetValueFloat( __local void * self, clMat /*float*/smat, int row, int col )
{
    // assert(self);
    // assert(row >= 0);
    // assert(col >= 0);
    // assert(row < smat.rows);
    // assert(col < smat.cols);
    // assert(smat.step >= smat.cols);
    // assert(smat.step % smat.cols == 0);

    return ((__local float*)self)[ row * smat.step + col + smat.start ];
    // return -1231.;
}

void
SetValueFloat( __local void * self, clMat /*float*/ smat, int row, int col, float value )
{
    // assert(self);
    // assert(row >= 0);
    // assert(col >= 0);
    // assert(row < smat.rows);
    // assert(col < smat.cols);
    // assert(smat.step >= smat.cols);
    // assert(smat.step % smat.cols == 0);

    ((__local float*)self)[ row * smat.step + col + smat.start ] = value;
    return;
}

normalization
normalizeSample( __local void * self, clMat /*uint8_t*/  image ) // , clMat /*float*/ * result )
{
  // assert(result->cols == image.cols);
  // assert(result->rows == image.rows);

    float8 sum8      = (float8)(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
    uchar8 minvalue8 = (uchar8)(255, 255, 255, 255, 255, 255, 255, 255);
    uchar8 maxvalue8 = (uchar8)(0, 0, 0, 0, 0, 0, 0, 0);
    float sum      = 0.0f;
    uchar minvalue = 255;
    uchar maxvalue = 0;

    for ( int q=0; q<image.rows; q++ ) {
        int start_index = image.start + q * image.step;
        int end_index = image.start + q * image.step + image.cols;

        int start_aligned = start_index - start_index % 8 + 8;
        int end_aligned = end_index - end_index % 8;

        for ( int index = start_index; index < start_aligned; index++ )
        {
            uchar pixel = ((__local uchar*)self)[index];
            minvalue = min( minvalue, pixel );
            maxvalue = max( maxvalue, pixel );
            sum += pixel;
        }

        for ( int index = start_aligned / 8; index < end_aligned / 8; index ++ )
        {
            uchar8 pixel8 = ((__local uchar8*)self)[index];
            minvalue8 = min( minvalue8, pixel8 );
            maxvalue8 = max( maxvalue8, pixel8 );
            sum8 += convert_float8(pixel8);
        }

        for ( int index = end_aligned; index < end_index; index++ )
        {
            uchar pixel = ((__local uchar*)self)[index];
            minvalue = min( minvalue, pixel );
            maxvalue = max( maxvalue, pixel );
            sum += pixel;
        }
    } // for q

    sum += sum8.s0 + sum8.s1 + sum8.s2 + sum8.s3 + sum8.s4 + sum8.s5 + sum8.s6 + sum8.s7;

    uchar4 min_a = min( minvalue8.s0123, minvalue8.s4567 );
    uchar2 min_b = min( min_a.s01, min_a.s23 );
    uchar  min_c = min( min_b.s0, min_b.s1 );
    minvalue = min( min_c, minvalue );

    uchar4 max_a = max( maxvalue8.s0123, maxvalue8.s4567 );
    uchar2 max_b = max( max_a.s01, max_a.s23 );
    uchar  max_c = max( max_b.s0, max_b.s1 );
    maxvalue = max( max_c, maxvalue );

    normalization nresult;

    float sampleMean = sum / (image.rows * image.cols);
    float sampleMin  = minvalue;
    float sampleMax  = maxvalue;

    sampleMax -= sampleMean;
    sampleMin -= sampleMean;

    sampleMax = fmax( fabs(sampleMin), fabs(sampleMax));

    if (sampleMax == 0.0) sampleMax = 1.0;

    nresult.shift  = -(1.0/sampleMax)*sampleMean;
    nresult.stride = 1.0/sampleMax;

    return nresult;
} // normalizeSample

void
generateResponseMap(
    __local void * self,
    const clMat /*uint8_t*/  image,
    const Point2i center,
    int mapSize,
    int m_patchSize,
    // clMat /*float*/m_wIn,
    clMat /*float*/m_wOut,
    // clMat /*float*/m_U,
    clMat wIn,
    clMat bIn,

    // result
    clMat /*float*/ result
    )
{

    int gangsize = get_local_size(0);
  // assert( result.rows == 2 * mapSize + 1 );
  // assert( result.cols == 2 * mapSize + 1 );

  //  assert(wIn.rows == wIn_A.rows);
  //  assert(wIn.cols == m_U.rows);

    clMat /*float*/wOut_tmp = GetBlockFloat( self, m_wOut, 0, m_wOut.rows, 0, m_wOut.cols - 1 );

    {
        int localid = get_local_id(0);
//        for ( localid=0; localid<gangsize; localid++ ) {

            int worksize = (2 * mapSize + 1) * (2 * mapSize + 1);

            float bOut = GetValueFloat( self, m_wOut, 0, m_wOut.cols - 1 );

            for ( int work=0; work < (worksize / gangsize) + 1; work++ )
            {
              int index = work * gangsize + localid;
              if (index>=worksize) continue;
              int ncy = index / (2 * mapSize + 1);
              int cy  = center.y - mapSize + ncy;
              int ncx = index % (2 * mapSize + 1);
              int cx  = center.x - mapSize + ncx;

              clMat /*uint8_t*/   imagePatch = GetBlockChar( self, image, cy - m_patchSize, cy + m_patchSize + 1, cx - m_patchSize, cx + m_patchSize + 1 );

              normalization norm = normalizeSample( self, imagePatch );

              float dot = gemmFloatDirDirDir( self, wIn, imagePatch, -1.0f, bIn, -1.0f, norm, wOut_tmp /*, xOut */);

              SetValueFloat( self, result, ncy, ncx, 1.0f/( 1.0f + exp( - dot - bOut ) ) );

            } // for gangsize
            //       } // for localid
    } // localid block

    return;
} // generateResponseMap

int
cvRound( float value )
{
    return (int)(value + (value >= 0 ? 0.5f : -0.5f));
} // cvRound

__kernel void
calculateMaps(
    // global variables
    __global void * self,
    __constant int memory_segments[], // representing the start of the gang's memory segment
    int m_visibleLandmarks_size,
    int m_mapSize,

    __constant calcpackage packages[],

    // local buffer
    int buffersize,
    __local void * buffer
    )
{

    int idx = get_group_id(0);
    int gangsize = get_local_size(0);
    int localid = get_local_id(0);

    // Copying the calculation into the local memory
    {
        __global int * glob = ((__global int*)(self + memory_segments[idx]));
        __local  int * loc  = ((__local  int*) buffer);

        for ( int iter = 0; iter < (buffersize/4) / gangsize + 1; iter++ ) {
            int index = gangsize * iter + localid;
            if (index >= buffersize/4) continue;
            loc[index]=glob[index];
        }
    }
    barrier(CLK_LOCAL_MEM_FENCE);

    calcpackage package = packages[idx];

    // Calculating
    Point2i center;

    float shape_x;
    float shape_y;

    shape_x = GetValueFloat( buffer, package.input.shape, 2*idx, 0 );
    shape_y = GetValueFloat( buffer, package.input.shape, 2*idx+1, 0 );

    center.x = cvRound(shape_x);
    center.y = cvRound(shape_y);

    generateResponseMap(
        buffer,
        package.input.alignedImage,
        center,
        m_mapSize,
        package.input.m_patchSize,
        package.input.m_wOut,
        package.input.wIn,
        package.input.bIn,

        // result
        package.output.responseMap );

    barrier(CLK_LOCAL_MEM_FENCE);
    // Copying back the result into the global memory
    {
        int start = package.output.responseMap.start;
        int size  = package.output.responseMap.step * package.output.responseMap.rows;

        __global float * glob = ((__global float*)(self + memory_segments[idx]));
        __local  float * loc  = ((__local  float*) buffer);

        for ( int iter = 0; iter < size / gangsize + 1; iter++ ) {
            int index = start + gangsize * iter + localid;
            if (index >= start + size) continue;
            glob[index]=loc[index];
        }
    }

    return;
} // calculateMaps

// LuM end of file

// -*- c++ -*-
// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This is a c-implementation of the PCA->MLP response map calculation

typedef struct {
    int rows;
    int cols;
    int step;
    int start;
} clMat; // struct clMatFloat

typedef struct {
    int size;
    int step;
    int start;
} clVector; // struct clVector

typedef struct {
    int m_patchSize;
    clMat /* uint8_t */ alignedImage;
    clMat /* int32_t */ shape;
    clMat /* float */ m_wOut;
    clMat /* float */ wIn;
    clMat /* float */ bIn;
} calcinput; // struct

typedef struct {
    int x;
    int y;
} Point2i; // struct Point2i

typedef struct {
    // results
    clMat /*float*/ responseMap;
} calcoutput;

typedef struct {
    calcinput  input;
    calcoutput output;
} calcpackage;

typedef struct {
    float shift;
    float stride;
} normalization;

__constant const int MAX_INT = ~(1 << (8*sizeof(int) - 1));
// __constant const int false = (1!=1);
__constant const bool precise = false;

clMat /*uint8_t*/
GetBlockChar( __local void * self, clMat /*uint8_t*/  smat, int row_from, int row_to, int col_from, int col_to )
{
    // assert(row_from>=0);
    // assert(col_from>=0);
    // assert(row_from<row_to);
    // assert(col_from<col_to);
    // assert(row_to<=smat.rows);
    // assert(col_to<=smat.cols);

    clMat /*uchar*/  result;
    result.rows  = row_to - row_from;
    result.cols  = col_to - col_from;
    result.step  = smat.step;
    result.start = smat.start + row_from * smat.step + col_from;

    return result;
}

clMat
GetBlockFloat( __local void * self, clMat /*float*/smat, int row_from, int row_to, int col_from, int col_to )
{
    // assert(row_from>=0);
    // assert(col_from>=0);
    // assert(row_from<row_to);
    // assert(col_from<col_to);
    // assert(row_to<=smat.rows);
    // assert(col_to<=smat.cols);

    clMat /*float*/result;
    result.rows  = row_to - row_from;
    result.cols  = col_to - col_from;
    result.step  = smat.step;
    result.start = smat.start + row_from * smat.step + col_from;

    return result;
}

// returns alpha*A*B + beta * C
float
gemmFloatDirDirDir(
    __local void * self,
    clMat /*float*/A,
    clMat /*uint8_t*/B,
    float alpha,
    clMat /*float*/C,
    float beta,
    normalization norm,
    clMat /* float */ dotmatrix//,
//    clMat /*float*/ result
    )
{
    // assert(A.rows == C.rows);
    // assert(A.cols == B.rows);
    // assert(B.cols == C.cols);
    // assert(C.rows == result.rows);
    // assert(C.cols == result.cols);
    // assert(C.cols == 1 );

    float sum=0.0f;
    float c=0.0f;
    float dot = 0.0f;

    for ( int q=0; q<C.rows; q++ ) {
        sum = 0;
        for ( int e=0; e<A.cols; e++ )
        {
            float a = ((__local float*)self)[ q * A.step + e + A.start ];
            int b_row = e / B.rows;
            int b_col = e % B.cols;
            float b = ((__local uchar*)self)[ b_row * B.step + b_col + B.start ];
            sum += a * (norm.shift + norm.stride * b);
        }

        float val    = alpha * sum  + beta * ((__local float*)self)[ q * C.step /* + w==0*/ + C.start ];
        float resval = 2.0f/(exp(val) + 1) - 1;

        dot += resval * ((__local float*)self)[ q + dotmatrix.start ];
    } // for q

    return dot;
} // gemmFloatDirDirDir

float
GetValueFloat( __local void * self, clMat /*float*/smat, int row, int col )
{
    // assert(self);
    // assert(row >= 0);
    // assert(col >= 0);
    // assert(row < smat.rows);
    // assert(col < smat.cols);
    // assert(smat.step >= smat.cols);
    // assert(smat.step % smat.cols == 0);

    return ((__local float*)self)[ row * smat.step + col + smat.start ];
    // return -1231.;
}

void
SetValueFloat( __local void * self, clMat /*float*/ smat, int row, int col, float value )
{
    // assert(self);
    // assert(row >= 0);
    // assert(col >= 0);
    // assert(row < smat.rows);
    // assert(col < smat.cols);
    // assert(smat.step >= smat.cols);
    // assert(smat.step % smat.cols == 0);

    ((__local float*)self)[ row * smat.step + col + smat.start ] = value;
    return;
}

normalization
normalizeSample( __local void * self, clMat /*uint8_t*/  image ) // , clMat /*float*/ * result )
{
  // assert(result->cols == image.cols);
  // assert(result->rows == image.rows);

    float4 sum4      = (float4)(0.0f, 0.0f, 0.0f, 0.0f);
    uchar4 minvalue4 = (uchar4)(255, 255, 255, 255);
    uchar4 maxvalue4 = (uchar4)(0, 0, 0, 0);
    float sum      = 0.0f;
    uchar minvalue = 255;
    uchar maxvalue = 0;

    for ( int q=0; q<image.rows; q++ ) {
        int start_index = image.start + q * image.step;
        int end_index = image.start + q * image.step + image.cols;

        int start_aligned = start_index - start_index % 4 + 4;
        int end_aligned = end_index - end_index % 4;

        for ( int index = start_index; index < start_aligned; index++ )
        {
            uchar pixel = ((__local uchar*)self)[index];
            minvalue = min( minvalue, pixel );
            maxvalue = max( maxvalue, pixel );
            sum += pixel;
        }

        for ( int index = start_aligned / 4; index < end_aligned / 4; index ++ )
        {
            uchar4 pixel4 = ((__local uchar4*)self)[index];
            minvalue4 = min( minvalue4, pixel4 );
            maxvalue4 = max( maxvalue4, pixel4 );
            sum4 += convert_float4(pixel4);
        }

        for ( int index = end_aligned; index < end_index; index++ )
        {
            uchar pixel = ((__local uchar*)self)[index];
            minvalue = min( minvalue, pixel );
            maxvalue = max( maxvalue, pixel );
            sum += pixel;
        }
    } // for q

    sum += sum4.x + sum4.y + sum4.z + sum4.w;

    minvalue = min( minvalue4.x, minvalue );
    minvalue = min( minvalue4.y, minvalue );
    minvalue = min( minvalue4.z, minvalue );
    minvalue = min( minvalue4.w, minvalue );

    maxvalue = max( maxvalue4.x, maxvalue );
    maxvalue = max( maxvalue4.y, maxvalue );
    maxvalue = max( maxvalue4.z, maxvalue );
    maxvalue = max( maxvalue4.w, maxvalue );

    normalization nresult;

    float sampleMean = sum / (image.rows * image.cols);
    float sampleMin  = minvalue;
    float sampleMax  = maxvalue;

    sampleMax -= sampleMean;
    sampleMin -= sampleMean;

    sampleMax = fmax( fabs(sampleMin), fabs(sampleMax));

    if (sampleMax == 0.0) sampleMax = 1.0;

    nresult.shift  = -(1.0/sampleMax)*sampleMean;
    nresult.stride = 1.0/sampleMax;

    return nresult;
} // normalizeSample

void
generateResponseMap(
    __local void * self,
    const clMat /*uint8_t*/  image,
    const Point2i center,
    int mapSize,
    int m_patchSize,
    // clMat /*float*/m_wIn,
    clMat /*float*/m_wOut,
    // clMat /*float*/m_U,
    clMat wIn,
    clMat bIn,

    // result
    clMat /*float*/ result
    )
{

    int gangsize = get_local_size(0);
  // assert( result.rows == 2 * mapSize + 1 );
  // assert( result.cols == 2 * mapSize + 1 );

  //  assert(wIn.rows == wIn_A.rows);
  //  assert(wIn.cols == m_U.rows);

    clMat /*float*/wOut_tmp = GetBlockFloat( self, m_wOut, 0, m_wOut.rows, 0, m_wOut.cols - 1 );

    {
        int localid = get_local_id(0);
//        for ( localid=0; localid<gangsize; localid++ ) {

            int worksize = (2 * mapSize + 1) * (2 * mapSize + 1);

            float bOut = GetValueFloat( self, m_wOut, 0, m_wOut.cols - 1 );

            for ( int work=0; work < (worksize / gangsize) + 1; work++ )
            {
              int index = work * gangsize + localid;
              if (index>=worksize) continue;
              int ncy = index / (2 * mapSize + 1);
              int cy  = center.y - mapSize + ncy;
              int ncx = index % (2 * mapSize + 1);
              int cx  = center.x - mapSize + ncx;

              clMat /*uint8_t*/   imagePatch = GetBlockChar( self, image, cy - m_patchSize, cy + m_patchSize + 1, cx - m_patchSize, cx + m_patchSize + 1 );

              normalization norm = normalizeSample( self, imagePatch );

              float dot = gemmFloatDirDirDir( self, wIn, imagePatch, -1.0f, bIn, -1.0f, norm, wOut_tmp /*, xOut */);

              SetValueFloat( self, result, ncy, ncx, 1.0f/( 1.0f + exp( - dot - bOut ) ) );

            } // for gangsize
            //       } // for localid
    } // localid block

    return;
} // generateResponseMap

int
cvRound( float value )
{
    return (int)(value + (value >= 0 ? 0.5f : -0.5f));
} // cvRound

__kernel void
calculateMaps(
    // global variables
    __global void * self,
    __constant int memory_segments[], // representing the start of the gang's memory segment
    int m_visibleLandmarks_size,
    int m_mapSize,

    __constant calcpackage packages[],

    // local buffer
    int buffersize,
    __local void * buffer
    )
{

    int idx = get_group_id(0);
    int gangsize = get_local_size(0);
    int localid = get_local_id(0);

    // Copying the calculation into the local memory
    {
        __global int * glob = ((__global int*)(self + memory_segments[idx]));
        __local  int * loc  = ((__local  int*) buffer);

        for ( int iter = 0; iter < (buffersize/4) / gangsize + 1; iter++ ) {
            int index = gangsize * iter + localid;
            if (index >= buffersize/4) continue;
            loc[index]=glob[index];
        }
    }
    barrier(CLK_LOCAL_MEM_FENCE);

    calcpackage package = packages[idx];

    // Calculating
    Point2i center;

    float shape_x;
    float shape_y;

    shape_x = GetValueFloat( buffer, package.input.shape, 2*idx, 0 );
    shape_y = GetValueFloat( buffer, package.input.shape, 2*idx+1, 0 );

    center.x = cvRound(shape_x);
    center.y = cvRound(shape_y);

    generateResponseMap(
        buffer,
        package.input.alignedImage,
        center,
        m_mapSize,
        package.input.m_patchSize,
        package.input.m_wOut,
        package.input.wIn,
        package.input.bIn,

        // result
        package.output.responseMap );

    barrier(CLK_LOCAL_MEM_FENCE);
    // Copying back the result into the global memory
    {
        int start = package.output.responseMap.start;
        int size  = package.output.responseMap.step * package.output.responseMap.rows;

        __global float * glob = ((__global float*)(self + memory_segments[idx]));
        __local  float * loc  = ((__local  float*) buffer);

        for ( int iter = 0; iter < size / gangsize + 1; iter++ ) {
            int index = start + gangsize * iter + localid;
            if (index >= start + size) continue;
            glob[index]=loc[index];
        }
    }

    return;
} // calculateMaps

// LuM end of file


r2038: Debian build

r2038: Debian build

;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name:          clsql-uffi-loader.sql
;;;; Purpose:       library loader using CLSQL UFFI helper library
;;;; Programmers:   Kevin M. Rosenberg
;;;; Date Started:  Mar 2002
;;;;
;;;; $Id: clsql-uffi-loader.cl,v 1.5 2002/05/14 16:03:52 kevin Exp $
;;;;
;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
;;;;
;;;; CLSQL users are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser GNU Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
;;;; *************************************************************************

(declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
(in-package :clsql-uffi)

(defvar *clsql-uffi-library-filename*
  (uffi:find-foreign-library
   :names "clsql-uffi"
   :directories
   (translate-logical-pathname
    "CL-LIBRARY:clsql;interfaces;clsql-uffi;clsql-uffi.so")
   "/usr/share/common-lisp/source/clsql/interfaces/clsql-uffi/"))

(defvar *clsql-uffi-supporting-libraries* '("c")
  "Used only by CMU. List of library flags needed to be passed to ld to
load the MySQL client library succesfully.  If this differs at your site,
set to the right path before compiling or loading the system.")

(defvar *uffi-library-loaded* nil
  "T if foreign library was able to be loaded successfully")

(defun load-uffi-foreign-library ()
  (if (uffi:load-foreign-library *clsql-uffi-library-filename*
				 :module "clsql-uffi"
				 :supporting-libraries
				 *clsql-uffi-supporting-libraries*)
      (setq *uffi-library-loaded* t)
    (warn "Unable to load helper library ~A (~S)" *clsql-uffi-library-filename*
	  (logical-pathname-translations "CL-LIBRARY"))))

(load-uffi-foreign-library)

;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name:          clsql-uffi-loader.sql
;;;; Purpose:       library loader using CLSQL UFFI helper library
;;;; Programmers:   Kevin M. Rosenberg
;;;; Date Started:  Mar 2002
;;;;
;;;; $Id: clsql-uffi-loader.cl,v 1.4 2002/05/14 15:58:45 kevin Exp $
;;;;
;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
;;;;
;;;; CLSQL users are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser GNU Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
;;;; *************************************************************************

(declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
(in-package :clsql-uffi)

(defvar *clsql-uffi-library-filename*
    (translate-logical-pathname
     #+(or linux unix) "CL-LIBRARY:clsql;interfaces;clsql-uffi;clsql-uffi.so"
     #+(or mswindows win32) "CL-LIBRARY:clsql;interfaces;clsql-uffi;clsql-uffi.dll"
     ))

(defvar *clsql-uffi-supporting-libraries* '("c")
  "Used only by CMU. List of library flags needed to be passed to ld to
load the MySQL client library succesfully.  If this differs at your site,
set to the right path before compiling or loading the system.")

(defvar *uffi-library-loaded* nil
  "T if foreign library was able to be loaded successfully")

(defun load-uffi-foreign-library ()
  (if (uffi:load-foreign-library *clsql-uffi-library-filename*
				 :module "clsql-uffi"
				 :supporting-libraries
				 *clsql-uffi-supporting-libraries*)
      (setq *uffi-library-loaded* t)
    (warn "Unable to load helper library ~A (~S)" *clsql-uffi-library-filename*
	  (logical-pathname-translations "CL-LIBRARY"))))

(load-uffi-foreign-library)


fixed bug in the previous reverted commit

#pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
#pragma OPENCL EXTENSION cl_amd_printf : enable

__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;

__kernel void GVFInit(__read_only image3d_t volume, __write_only image3d_t vector_field ) {
    // Calculate gradient using a 1D central difference for each dimension, with spacing 1
    int4 pos = {get_global_id(0), get_global_id(1), get_global_id(2), 0};

    float f100 = read_imagef(volume, sampler, pos + (int4)(1,0,0,0)).x;
    float f_100 = read_imagef(volume, sampler, pos - (int4)(1,0,0,0)).x;
    float f010 = read_imagef(volume, sampler, pos + (int4)(0,1,0,0)).x;
    float f0_10 = read_imagef(volume, sampler, pos - (int4)(0,1,0,0)).x;
    float f001 = read_imagef(volume, sampler, pos + (int4)(0,0,1,0)).x;
    float f00_1 = read_imagef(volume, sampler, pos - (int4)(0,0,1,0)).x;

    float4 gradient = {
        0.5f*(f100-f_100),
        0.5f*(f010-f0_10),
        0.5f*(f001-f00_1),
        0};

    gradient.w = gradient.x*gradient.x + gradient.y*gradient.y + gradient.z*gradient.z;

    write_imagef(vector_field, pos, gradient);
}

__kernel void GVFIteration(__read_only image3d_t init_vector_field, __read_only image3d_t read_vector_field, __write_only image3d_t write_vector_field, __private float mu) {

    int4 writePos = {
        get_global_id(0)-(get_group_id(0)*2+1),
        get_global_id(1)-(get_group_id(1)*2+1),
        get_global_id(2)-(get_group_id(2)*2+1),
        0
    };
    int3 localPos = {get_local_id(0), get_local_id(1), get_local_id(2)};

    // Enforce mirror boundary conditions
    //int4 size = {get_global_size(0), get_global_size(1), get_global_size(2), 0};
    //int4 pos = writePos;
    //pos = select(pos, (int4)(2,2,2,0), pos == (int4)(0,0,0,0));
    //pos = select(pos, size-3, pos == size-1);

    // Allocate shared memory
    __local float4 sharedMemory[6][6][6];

    // Read into shared memory
    sharedMemory[localPos.x][localPos.y][localPos.z] = read_imagef(read_vector_field, sampler, writePos);

    int3 comp = (localPos == (int3)(0,0,0)) +
        (localPos == (int3)(get_local_size(0)-1,get_local_size(1)-1,get_local_size(2)-1));

    // Synchronize the threads in the group
    barrier(CLK_LOCAL_MEM_FENCE);

    if(comp.x+comp.y+comp.z == 0) {
    // Load data from shared memory and do calculations
    float3 vector = sharedMemory[localPos.x][localPos.y][localPos.z].xyz;
    float3 fx1 = sharedMemory[localPos.x+1][localPos.y][localPos.z].xyz;
    float3 fx_1 = sharedMemory[localPos.x-1][localPos.y][localPos.z].xyz;
    float3 fy1 = sharedMemory[localPos.x][localPos.y+1][localPos.z].xyz;
    float3 fy_1 = sharedMemory[localPos.x][localPos.y-1][localPos.z].xyz;
    float3 fz1 = sharedMemory[localPos.x][localPos.y][localPos.z+1].xyz;
    float3 fz_1 = sharedMemory[localPos.x][localPos.y][localPos.z-1].xyz;
    float4 init_vector = read_imagef(init_vector_field, sampler, writePos); // should read from pos

    // Update the vector field: Calculate Laplacian using a 3D central difference scheme
    float3 laplacian = -6*vector + fx1 + fx_1 + fy1 + fy_1 + fz1 + fz_1;

    vector += mu * laplacian - (vector - init_vector.xyz)*init_vector.w;

    write_imagef(write_vector_field, writePos, (float4)(vector.x,vector.y,vector.z,0));
    }
}

__kernel void GVFResult(__write_only image3d_t result, __read_only image3d_t vectorField) {

    int4 pos = {get_global_id(0), get_global_id(1), get_global_id(2), 0};
    float4 vector = read_imagef(vectorField, sampler, pos);
    vector.w = 0;
    //if(1 < length(vector))
    //    printf("%f %f %f\n", vector.x, vector.y, vector.z);
    write_imagef(result, pos, length(vector));
}

#pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
#pragma OPENCL EXTENSION cl_amd_printf : enable

__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;

__kernel void GVFInit(__read_only image3d_t volume, __write_only image3d_t vector_field ) {
    // Calculate gradient using a 1D central difference for each dimension, with spacing 1
    int4 pos = {get_global_id(0), get_global_id(1), get_global_id(2), 0};

    float f100 = read_imagef(volume, sampler, pos + (int4)(1,0,0,0)).x;
    float f_100 = read_imagef(volume, sampler, pos - (int4)(1,0,0,0)).x;
    float f010 = read_imagef(volume, sampler, pos + (int4)(0,1,0,0)).x;
    float f0_10 = read_imagef(volume, sampler, pos - (int4)(0,1,0,0)).x;
    float f001 = read_imagef(volume, sampler, pos + (int4)(0,0,1,0)).x;
    float f00_1 = read_imagef(volume, sampler, pos - (int4)(0,0,1,0)).x;

    float4 gradient = {
        0.5f*(f100-f_100),
        0.5f*(f010-f0_10),
        0.5f*(f001-f00_1),
        0};

    gradient.w = gradient.x*gradient.x + gradient.y*gradient.y + gradient.z*gradient.z;

    write_imagef(vector_field, pos, gradient);
}

__kernel void GVFIteration(__read_only image3d_t init_vector_field, __read_only image3d_t read_vector_field, __write_only image3d_t write_vector_field, __private float mu) {

    int4 writePos = {
        get_global_id(0)-(get_group_id(0)*2+1),
        get_global_id(1)-(get_group_id(1)*2+1),
        get_global_id(2)-(get_group_id(2)*2+1),
        0
    };
    int3 localPos = {get_local_id(0), get_local_id(1), get_local_id(2)};

    // Enforce mirror boundary conditions
    //int4 size = {get_global_size(0), get_global_size(1), get_global_size(2), 0};
    //int4 pos = writePos;
    //pos = select(pos, (int4)(2,2,2,0), pos == (int4)(0,0,0,0));
    //pos = select(pos, size-3, pos == size-1);

    // Allocate shared memory
    __local float4 sharedMemory[6][6][6];

    // Read into shared memory
    sharedMemory[localPos.x][localPos.y][localPos.z] = read_imagef(read_vector_field, sampler, writePos);

    // Synchronize the threads in the group
    barrier(CLK_LOCAL_MEM_FENCE);

    int3 comp = (localPos == (int3)(0,0,0)) +
        (localPos == (int3)(get_local_size(0)-1,get_local_size(1)-1,get_local_size(2)-1));

    if(comp.x+comp.y+comp.z == 0) {
    // Load data from shared memory and do calculations
    float4 vector = sharedMemory[localPos.x][localPos.y][localPos.z];
    float4 fx1 = sharedMemory[localPos.x+1][localPos.y][localPos.z];
    float4 fx_1 = sharedMemory[localPos.x-1][localPos.y][localPos.z];
    float4 fy1 = sharedMemory[localPos.x][localPos.y+1][localPos.z];
    float4 fy_1 = sharedMemory[localPos.x][localPos.y-1][localPos.z];
    float4 fz1 = sharedMemory[localPos.x][localPos.y][localPos.z+1];
    float4 fz_1 = sharedMemory[localPos.x][localPos.y][localPos.z-1];
    float4 init_vector = read_imagef(init_vector_field, sampler, writePos); // should read from pos

    // Update the vector field: Calculate Laplacian using a 3D central difference scheme
    float4 laplacian = -6*vector + fx1 + fx_1 + fy1 + fy_1 + fz1 + fz_1;

    vector += mu * laplacian - (vector - init_vector)*init_vector.w;

    write_imagef(write_vector_field, writePos, vector);
    }
}

__kernel void GVFResult(__write_only image3d_t result, __read_only image3d_t vectorField) {

    int4 pos = {get_global_id(0), get_global_id(1), get_global_id(2), 0};
    float4 vector = read_imagef(vectorField, sampler, pos);
    vector.w = 0;
    //if(1 < length(vector))
    //    printf("%f %f %f\n", vector.x, vector.y, vector.z);
    write_imagef(result, pos, length(vector));
}


trying stuff

trying stuff

// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

// expected defines:
// one of: [ TANH | RELU | LINEAR ]
// BIASED (or not)

#ifdef TANH
    #define ACTIVATION_FUNCTION(output) (tanh(output))
#elif defined SCALEDTANH
    #define ACTIVATION_FUNCTION(output) ( 1.7159f * tanh( 0.66667f * output))
#elif SIGMOID
    #define ACTIVATION_FUNCTION(output) (1.0f / (1 + exp(-output)))
#elif defined RELU
    #define ACTIVATION_FUNCTION(output) (output> 0 ? output : 0)
#elif defined LINEAR
    #define ACTIVATION_FUNCTION(output) (output)
#endif

#ifdef gOutputBoardSize // for previous tests that dont define it
#ifdef ACTIVATION_FUNCTION // protect against not defined
// workgroup id organized like: [imageid][outplane]
// local id organized like: [outrow][outcol]
// each thread iterates over: [upstreamplane][filterrow][filtercol]
// number workgroups = 32
// one filter plane takes up 5 * 5 * 4 = 100 bytes
// one filter cube (corresponding to one outplane) = 5*5 * 32 * 4 = 3.2KB (ok)
// all filter cubes = 3.2KB * 32 = 102KB (too big)
// results are organized like [imageid][filterid][row][col]
void kernel propagate_4_by_n_outplane_smallercache( const int batchSize,
    const int pixelsPerThread,
      global const float *images, global const float *filters,
        #ifdef BIASED
            global const float*biases,
        #endif
    global float *results,
    local float *_upstreamBoard, local float *_filterCube, local float *_pixelSums ) {
    const int globalId = get_global_id(0);

    const int evenPadding = gFilterSize % 2 == 0 ? 1 : 0;

    const int localId = get_local_id(0);
    const int workgroupId = get_group_id(0);
    const int workgroupSize = get_local_size(0);
    const int n = workgroupId / gNumFilters;
    const int outPlane = workgroupId % gNumFilters;

    const int numUpstreamsPerThread = ( gInputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;
    const int numFilterPixelsPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;

    //local float *_myPixelSums = _pixelSums + pixelsPerThread * localId;
    local float *_myPixelSums = _pixelSums;

    for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
        _myPixelSums[pixel] = 0.0f;
    }

    const int outputRow = localId / gOutputBoardSize;
    const int outputCol = localId % gOutputBoardSize;

    const int minu = gPadZeros ? max( -gHalfFilterSize, -outputRow ) : -gHalfFilterSize;
    const int maxu = gPadZeros ? min( gHalfFilterSize - evenPadding, gOutputBoardSize - 1 - outputRow  - evenPadding) : gHalfFilterSize - evenPadding;
    const int minv = gPadZeros ? max( -gHalfFilterSize, -outputCol ) : - gHalfFilterSize;
    const int maxv = gPadZeros ? min( gHalfFilterSize - evenPadding, gOutputBoardSize - 1 - outputCol - evenPadding) : gHalfFilterSize - evenPadding;

    for( int upstreamPlane = 0; upstreamPlane < gInputPlanes; upstreamPlane++ ) {
        int thisUpstreamBoardOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;
        barrier(CLK_LOCAL_MEM_FENCE);
        for( int i = 0; i < numUpstreamsPerThread; i++ ) {
            int thisOffset = workgroupSize * i + localId;
            if( thisOffset < gInputBoardSizeSquared ) {
                _upstreamBoard[ thisOffset ] = images[ thisUpstreamBoardOffset + thisOffset ];
            }
        }
        const int filterGlobalOffset = ( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;
        for( int i = 0; i < numFilterPixelsPerThread; i++ ) {
            int thisOffset = workgroupSize * i + localId;
            if( thisOffset < gFilterSizeSquared ) {
                _filterCube[thisOffset] = filters[filterGlobalOffset + thisOffset];
            }
        }
        barrier(CLK_LOCAL_MEM_FENCE);

        for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
            const int virtualLocalId = localId + pixel * workgroupSize;

            float thissum = 0;
            if( virtualLocalId < gOutputBoardSizeSquared ) {
                for( int u = minu; u <= maxu; u++ ) {
                    int inputRow = outputRow + u + ( gPadZeros ? 0 : gHalfFilterSize );
                    int inputboardrowoffset = inputRow * gInputBoardSize;
                    int filterrowoffset = (u+gHalfFilterSize) * gFilterSize + gHalfFilterSize;
                    for( int v = minv; v <= maxv; v++ ) {
                        int inputCol = outputCol + v + ( gPadZeros ? 0 : gHalfFilterSize );
                        thissum += _upstreamBoard[ inputboardrowoffset + inputCol] * _filterCube[ filterrowoffset + v ];
                    }
                }
            }
            _myPixelSums[pixel] += thissum;
//            if( globalId == 0 ) results[0] = _upstreamBoard[pixel];
        }
    }
    for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
        const int virtualLocalId = localId + pixel * workgroupSize;
        if( virtualLocalId < gOutputBoardSizeSquared ) {
            float sum = _myPixelSums[pixel];
            #ifdef BIASED
                sum += biases[outPlane];
            #endif
            // results are organized like [imageid][filterid][row][col]
            int resultIndex = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared + virtualLocalId;
            results[resultIndex ] = ACTIVATION_FUNCTION(sum);
            // results[resultIndex ] = 123;
            //if( globalId == 0 ) results[0] += 0.000001f + _perPixelSums[0];
        }
    }
}
#endif
#endif

// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

// expected defines:
// one of: [ TANH | RELU | LINEAR ]
// BIASED (or not)

#ifdef TANH
    #define ACTIVATION_FUNCTION(output) (tanh(output))
#elif defined SCALEDTANH
    #define ACTIVATION_FUNCTION(output) ( 1.7159f * tanh( 0.66667f * output))
#elif SIGMOID
    #define ACTIVATION_FUNCTION(output) (1.0f / (1 + exp(-output)))
#elif defined RELU
    #define ACTIVATION_FUNCTION(output) (output> 0 ? output : 0)
#elif defined LINEAR
    #define ACTIVATION_FUNCTION(output) (output)
#endif

#ifdef gOutputBoardSize // for previous tests that dont define it
#ifdef ACTIVATION_FUNCTION // protect against not defined
// workgroup id organized like: [imageid][outplane]
// local id organized like: [outrow][outcol]
// each thread iterates over: [upstreamplane][filterrow][filtercol]
// number workgroups = 32
// one filter plane takes up 5 * 5 * 4 = 100 bytes
// one filter cube (corresponding to one outplane) = 5*5 * 32 * 4 = 3.2KB (ok)
// all filter cubes = 3.2KB * 32 = 102KB (too big)
// results are organized like [imageid][filterid][row][col]
void kernel propagate_4_by_n_outplane_smallercache( const int batchSize,
    const int pixelsPerThread,
      global const float *images, global const float *filters,
        #ifdef BIASED
            global const float*biases,
        #endif
    global float *results,
    local float *_upstreamBoard, local float *_filterCube, local float *_pixelSums ) {
    const int globalId = get_global_id(0);

    const int evenPadding = gFilterSize % 2 == 0 ? 1 : 0;

    const int localId = get_local_id(0);
    const int workgroupId = get_group_id(0);
    const int workgroupSize = get_local_size(0);
    const int n = workgroupId / gNumFilters;
    const int outPlane = workgroupId % gNumFilters;

    const int numUpstreamsPerThread = ( gInputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;
    const int numFilterPixelsPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;

    local float *_myPixelSums = _pixelSums + pixelsPerThread * localId;

    for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
        _myPixelSums[pixel] = 0.0f;
    }

    const int outputRow = localId / gOutputBoardSize;
    const int outputCol = localId % gOutputBoardSize;

    const int minu = gPadZeros ? max( -gHalfFilterSize, -outputRow ) : -gHalfFilterSize;
    const int maxu = gPadZeros ? min( gHalfFilterSize - evenPadding, gOutputBoardSize - 1 - outputRow  - evenPadding) : gHalfFilterSize - evenPadding;
    const int minv = gPadZeros ? max( -gHalfFilterSize, -outputCol ) : - gHalfFilterSize;
    const int maxv = gPadZeros ? min( gHalfFilterSize - evenPadding, gOutputBoardSize - 1 - outputCol - evenPadding) : gHalfFilterSize - evenPadding;

    for( int upstreamPlane = 0; upstreamPlane < gInputPlanes; upstreamPlane++ ) {
        int thisUpstreamBoardOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;
        barrier(CLK_LOCAL_MEM_FENCE);
        for( int i = 0; i < numUpstreamsPerThread; i++ ) {
            int thisOffset = workgroupSize * i + localId;
            if( thisOffset < gInputBoardSizeSquared ) {
                _upstreamBoard[ thisOffset ] = images[ thisUpstreamBoardOffset + thisOffset ];
            }
        }
        const int filterGlobalOffset = ( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;
        for( int i = 0; i < numFilterPixelsPerThread; i++ ) {
            int thisOffset = workgroupSize * i + localId;
            if( thisOffset < gFilterSizeSquared ) {
                _filterCube[thisOffset] = filters[filterGlobalOffset + thisOffset];
            }
        }
        barrier(CLK_LOCAL_MEM_FENCE);

        for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
            const int virtualLocalId = localId + pixel * workgroupSize;

            float thissum = 0;
            if( virtualLocalId < gOutputBoardSizeSquared ) {
                for( int u = minu; u <= maxu; u++ ) {
                    int inputRow = outputRow + u + ( gPadZeros ? 0 : gHalfFilterSize );
                    int inputboardrowoffset = inputRow * gInputBoardSize;
                    int filterrowoffset = (u+gHalfFilterSize) * gFilterSize + gHalfFilterSize;
                    for( int v = minv; v <= maxv; v++ ) {
                        int inputCol = outputCol + v + ( gPadZeros ? 0 : gHalfFilterSize );
                        thissum += _upstreamBoard[ inputboardrowoffset + inputCol] * _filterCube[ filterrowoffset + v ];
                    }
                }
            }
            _myPixelSums[pixel] += thissum;
//            if( globalId == 0 ) results[0] = _upstreamBoard[pixel];
        }
    }
    for( int pixel = 0; pixel < pixelsPerThread; pixel++ ) {
        const int virtualLocalId = localId + pixel * workgroupSize;
        if( virtualLocalId < gOutputBoardSizeSquared ) {
            float sum = _myPixelSums[pixel];
            #ifdef BIASED
                sum += biases[outPlane];
            #endif
            // results are organized like [imageid][filterid][row][col]
            int resultIndex = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared + virtualLocalId;
            results[resultIndex ] = ACTIVATION_FUNCTION(sum);
            // results[resultIndex ] = 123;
            //if( globalId == 0 ) results[0] += 0.000001f + _perPixelSums[0];
        }
    }
}
#endif
#endif


little changes in ocl code

little changes in ocl code

/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2011, 2017 OpenWorm.
 * http://openworm.org
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the MIT License
 * which accompanies this distribution, and is available at
 * http://opensource.org/licenses/MIT
 *
 * Contributors:
 *     	OpenWorm - http://openworm.org/people.html
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *******************************************************************************/

#ifdef cl_amd_printf
	#pragma OPENCL EXTENSION cl_amd_printf : enable
	#define PRINTF_ON // this comment because using printf leads to very slow work on Radeon r9 290x on my machine
    	              // don't know why
#elif defined(cl_intel_printf)
	#pragma OPENCL EXTENSION cl_intel_printf : enable
	#define PRINTF_ON
#endif

#ifdef _DOUBLE_PRECISION
	#ifdef cl_khr_fp64
		#pragma OPENCL EXTENSION cl_khr_fp64 : enable

	#elif defined(cl_amd_fp64)
		#pragma OPENCL EXTENSION cl_amd_fp64 : enable
		#define _DOUBLE_PRECISION
	#else
		#error "Double precision floating point not supported by OpenCL implementation."
	#endif
#endif

#include "inc/ocl_struct.h"

typedef struct particle_f{
	float4 pos;
	float4 vel;
	size_t cell_id;
	size_t type_;
	float density;
	float pressure;
} particle_f;
#ifdef _DOUBLE_PRECISION
typedef struct particle_d{
	double4 pos;
	double4 vel;
	size_t cell_id;
	size_t type_;
	double density;
	double pressure;
} particle_d;
#endif

/** Just for test
*/
__kernel void work_with_struct(__global struct extendet_particle * ext_particles,
							   __global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){
	int id = get_global_id(0);
#ifdef PRINTF_ON
	if(id == 0){
		printf("sizeof() of particles_f is %d\n", sizeof(particle_f) );
		#ifdef _DOUBLE_PRECISION
		printf("sizeof() of particles_d is %d\n", sizeof(particle_d) );
		#endif
	}
#endif
#ifdef _DOUBLE_PRECISION

	particles[id].pos = (double4)(id, id, id, id);
	particles[id].vel = (double4)(id, id, id, id);
#else
	particles[id].pos = (float4)(id, id, id, id);
	particles[id].vel = (float4)(id, id, id, id);
#endif
	particles[id].type_ = id + 1;
}

/**Initialization of neighbour list by -1
* what means that it's no neighbours.
*/
__kernel void _ker_init_ext_particles(__global struct extendet_particle * ext_particles){
	int id = get_global_id(0);
	ext_particles[id].p_id = id;
	for(int i=0;i<NEIGHBOUR_COUNT;++i){
		ext_particles[id].neigbour_list[i] = -1;
	}
}

/** Calc current cell id for each particles
*/
__kernel void _ker_calc_cell_id(__global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){

}

/** Searchin for neigbours foe each particles
*/
__kernel void _ker_neighbour_search(__global struct extendet_particle * ext_particles,
							   __global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){

}

int cellId(
		   int4 cellFactors_,
		   uint gridCellsX,
		   uint gridCellsY,
		   uint gridCellsZ//don't use
		   )
{
	int cellId_ = cellFactors_.x + cellFactors_.y * gridCellsX
		+ cellFactors_.z * gridCellsX * gridCellsY;
	return cellId_;
}
/** Caculation spatial hash cellId for every particle
 *  Kernel fill up particleIndex buffer.
 */
 int4 cell_factors(
				 __global struct
				#ifdef _DOUBLE_PRECISION
					particle_d
				#else
					particle_f
				#endif
					* particle,
				 float xmin,
				 float ymin,
				 float zmin,
				 float hash_grid_cell_size_inv
				 )
{
	//xmin, ymin, zmin
	int4 result;
	result.x = (int)( particle->pos.x *  hash_grid_cell_size_inv );
	result.y = (int)( particle->pos.y *  hash_grid_cell_size_inv );
	result.z = (int)( particle->pos.z *  hash_grid_cell_size_inv );
	return result;
}
__kernel void _ker_hash_particles(
							__global struct
							#ifdef _DOUBLE_PRECISION
								particle_d
							#else
								particle_f
							#endif
								* particles,
							uint grid_cells_x,
							uint grid_cells_y,
							uint grid_cells_Z,
							float hash_grid_cell_size_inv,
							float xmin,
							float ymin,
							float zmin,
							__global uint2 * particleIndex,
							uint PARTICLE_COUNT
							)
{
	int id = get_global_id( 0 );
	if( id >= PARTICLE_COUNT ) return;
#ifdef _DOUBLE_PRECISION
	particle_d
#else
	particle_f
#endif
	* particle = particles[id];
	/*float4 _position = position[ id ];
	/*int4 cellFactors_ = cellFactors( _position, xmin, ymin, zmin, hashGridCellSizeInv );
	int cellId_ = cellId( cellFactors_, gridCellsX, gridCellsY, gridCellsZ ) & 0xffffff; // truncate to low 16 bits
	uint2 result;
	PI_CELL_ID( result ) = cellId_;
	PI_SERIAL_ID( result ) = id;
	particleIndex[ id ] = result;*/
}

/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2011, 2017 OpenWorm.
 * http://openworm.org
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the MIT License
 * which accompanies this distribution, and is available at
 * http://opensource.org/licenses/MIT
 *
 * Contributors:
 *     	OpenWorm - http://openworm.org/people.html
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *******************************************************************************/

#ifdef cl_amd_printf
	#pragma OPENCL EXTENSION cl_amd_printf : enable
	#define PRINTF_ON // this comment because using printf leads to very slow work on Radeon r9 290x on my machine
    	              // don't know why
#elif defined(cl_intel_printf)
	#pragma OPENCL EXTENSION cl_intel_printf : enable
	#define PRINTF_ON
#endif

#ifdef _DOUBLE_PRECISION
	#ifdef cl_khr_fp64
		#pragma OPENCL EXTENSION cl_khr_fp64 : enable

	#elif defined(cl_amd_fp64)
		#pragma OPENCL EXTENSION cl_amd_fp64 : enable
		#define _DOUBLE_PRECISION
	#else
		#error "Double precision floating point not supported by OpenCL implementation."
	#endif
#endif

#include "inc/ocl_struct.h"

typedef struct particle_f{
	float4 pos;
	float4 vel;
	size_t cell_id;
	size_t type_;
	float density;
	float pressure;
} particle_f;
#ifdef _DOUBLE_PRECISION
typedef struct particle_d{
	double4 pos;
	double4 vel;
	size_t cell_id;
	size_t type_;
	double density;
	double pressure;
} particle_d;
#endif

/** Just for test
*/
__kernel void work_with_struct(__global struct extendet_particle * ext_particles,
							   __global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){
	int id = get_global_id(0);
#ifdef PRINTF_ON
	if(id == 0){
		printf("sizeof() of particles_f is %d\n", sizeof(particle_f) );
		#ifdef _DOUBLE_PRECISION
		printf("sizeof() of particles_d is %d\n", sizeof(particle_d) );
		#endif
	}
#endif
#ifdef _DOUBLE_PRECISION

	particles[id].pos = (double4)(id, id, id, id);
	particles[id].vel = (double4)(id, id, id, id);
#else
	particles[id].pos = (float4)(id, id, id, id);
	particles[id].vel = (float4)(id, id, id, id);
#endif
	particles[id].type_ = id + 1;
}

/**Initialization of neighbour list by -1
* what means that it's no neighbours.
*/
__kernel void _ker_init_ext_particles(__global struct extendet_particle * ext_particles){
	int id = get_global_id(0);
	ext_particles[id].p_id = id;
	for(int i=0;i<NEIGHBOUR_COUNT;++i){
		ext_particles[id].neigbour_list[i] = -1;
	}
}

/** Calc current cell id for each particles
*/
__kernel void _ker_calc_cell_id(__global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){

}

/** Searchin for neigbours foe each particles
*/
__kernel void _ker_neighbour_search(__global struct extendet_particle * ext_particles,
							   __global struct
							   #ifdef _DOUBLE_PRECISION
									particle_d
							   #else
									particle_f
							   #endif
									* particles){

}

int cellId(
		   int4 cellFactors_,
		   uint gridCellsX,
		   uint gridCellsY,
		   uint gridCellsZ//don't use
		   )
{
	int cellId_ = cellFactors_.x + cellFactors_.y * gridCellsX
		+ cellFactors_.z * gridCellsX * gridCellsY;
	return cellId_;
}
/** Caculation spatial hash cellId for every particle
 *  Kernel fill up particleIndex buffer.
 */
 int4 cellFactors(
				 __global struct
				#ifdef _DOUBLE_PRECISION
					particle_d
				#else
					particle_f
				#endif
					* particle,
				 float xmin,
				 float ymin,
				 float zmin,
				 float hashGridCellSizeInv
				 )
{
	//xmin, ymin, zmin
	int4 result;
	result.x = (int)( particle->pos.x *  hashGridCellSizeInv );
	result.y = (int)( particle->pos.y *  hashGridCellSizeInv );
	result.z = (int)( particle->pos.z *  hashGridCellSizeInv );
	return result;
}
__kernel void hashParticles(
							__global struct
							#ifdef _DOUBLE_PRECISION
								particle_d
							#else
								particle_f
							#endif
								* particles,
							uint gridCellsX,
							uint gridCellsY,
							uint gridCellsZ,
							float hashGridCellSizeInv,
							float xmin,
							float ymin,
							float zmin,
							__global uint2 * particleIndex,
							uint   PARTICLE_COUNT
							)
{
	/*int id = get_global_id( 0 );
	if( id >= PARTICLE_COUNT ) return;
	float4 _position = position[ id ];
	int4 cellFactors_ = cellFactors( _position, xmin, ymin, zmin, hashGridCellSizeInv );
	int cellId_ = cellId( cellFactors_, gridCellsX, gridCellsY, gridCellsZ ) & 0xffffff; // truncate to low 16 bits
	uint2 result;
	PI_CELL_ID( result ) = cellId_;
	PI_SERIAL_ID( result ) = id;
	particleIndex[ id ] = result;*/
}