aboutsummaryrefslogtreecommitdiff
path: root/test_conformance/spir/run_build_test.cpp
blob: 9264d3a48addd90083de8c3e5c7b74adef37c7f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//
// Copyright (c) 2017 The Khronos Group Inc.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "harness/compat.h"

#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif

#include <sstream>
#include <fstream>
#include <assert.h>
#include <functional>
#include <memory>

#include "harness/errorHelpers.h"
#include "harness/kernelHelpers.h"
#include "harness/typeWrappers.h"
#include "harness/clImageHelper.h"
#include "harness/os_helpers.h"

#include "../math_brute_force/function_list.h"
#include "datagen.h"
#include "exceptions.h"
#include "kernelargs.h"
#include "run_build_test.h"
#include "run_services.h"
#include <CL/cl.h>
//
// Task
//
Task::Task(cl_device_id device, const char* options):
m_devid(device) {
  if (options)
    m_options = options;
}

Task::~Task() {}

const char* Task::getErrorLog() const {
  return m_log.c_str();
}

void Task::setErrorLog(cl_program prog) {
    size_t len = 0;
    std::vector<char> log;

    cl_int err_code = clGetProgramBuildInfo(prog, m_devid, CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
    if(err_code != CL_SUCCESS)
    {
        m_log = "Error: clGetProgramBuildInfo(CL_PROGRAM_BUILD_LOG, &len) failed.\n";
        return;
    }

    log.resize(len, 0);

    err_code = clGetProgramBuildInfo(prog, m_devid, CL_PROGRAM_BUILD_LOG, len, &log[0], NULL);
    if(err_code != CL_SUCCESS)
    {
        m_log = "Error: clGetProgramBuildInfo(CL_PROGRAM_BUILD_LOG, &log) failed.\n";
        return;
    }
    m_log.append(&log[0]);
}

//
// BuildTask
//
BuildTask::BuildTask(cl_program prog, cl_device_id dev, const char* options) :
    m_program(prog), Task(dev, options) {}

bool BuildTask::execute() {
    cl_int err_code = clBuildProgram(m_program, 0, NULL, m_options.c_str(), NULL, NULL);
    if(CL_SUCCESS == err_code)
        return true;

    setErrorLog(m_program);
    return false;
}

//
// SpirBuildTask
//
SpirBuildTask::SpirBuildTask(cl_program prog, cl_device_id dev, const char* options) :
    BuildTask(prog, dev, options) {}

//
// CompileTask
//

CompileTask::CompileTask(cl_program prog, cl_device_id dev, const char* options) :
    m_program(prog), Task(dev, options) {}

void CompileTask::addHeader(const char* hname, cl_program hprog) {
    m_headers.push_back(std::make_pair(hname, hprog));
}

const char* first(std::pair<const char*,cl_program>& p) {
    return p.first;
}

cl_program second(const std::pair<const char*, cl_program>& p) {
    return p.second;
}

bool CompileTask::execute() {
    // Generating the header names vector.
    std::vector<const char*> names;
    std::transform(m_headers.begin(), m_headers.end(), names.begin(), first);

    // Generating the header programs vector.
    std::vector<cl_program> programs;
    std::transform(m_headers.begin(), m_headers.end(), programs.begin(), second);

    const char** h_names = NULL;
    const cl_program* h_programs = NULL;
    if (!m_headers.empty())
    {
        h_programs = &programs[0];
        h_names    = &names[0];
    }

    // Compiling with the headers.
    cl_int err_code = clCompileProgram(
        m_program,
        1U,
        &m_devid,
        m_options.c_str(),
        m_headers.size(), // # of headers
        h_programs,
        h_names,
        NULL, NULL);
    if (CL_SUCCESS == err_code)
        return true;

    setErrorLog(m_program);
    return false;
}

//
// SpirCompileTask
//
SpirCompileTask::SpirCompileTask(cl_program prog, cl_device_id dev, const char* options) :
    CompileTask(prog, dev, options) {}


//
// LinkTask
//
LinkTask::LinkTask(cl_program* programs, int num_programs, cl_context ctxt,
                   cl_device_id dev, const char* options) :
    m_programs(programs), m_numPrograms(num_programs), m_context(ctxt), m_executable(NULL),
    Task(dev, options) {}

bool LinkTask::execute() {
    cl_int err_code;
    int i;

    for(i = 0; i < m_numPrograms; ++i)
    {
        err_code = clCompileProgram(m_programs[i], 1, &m_devid, "-x spir -spir-std=1.2 -cl-kernel-arg-info", 0, NULL, NULL, NULL, NULL);
        if (CL_SUCCESS != err_code)
        {
            setErrorLog(m_programs[i]);
            return false;
        }
    }

    m_executable = clLinkProgram(m_context, 1, &m_devid, m_options.c_str(), m_numPrograms, m_programs, NULL, NULL, &err_code);
    if (CL_SUCCESS == err_code)
      return true;

    if(m_executable) setErrorLog(m_executable);
    return false;
}

cl_program LinkTask::getExecutable() const {
    return m_executable;
}

LinkTask::~LinkTask() {
    if(m_executable) clReleaseProgram(m_executable);
}

//
// KernelEnumerator
//
void KernelEnumerator::process(cl_program prog) {
    const size_t MAX_KERNEL_NAME = 64;
    size_t num_kernels;

    cl_int err_code = clGetProgramInfo(
        prog,
        CL_PROGRAM_NUM_KERNELS,
        sizeof(size_t),
        &num_kernels,
        NULL
    );
    if (CL_SUCCESS != err_code)
        return;

    // Querying for the number of kernels.
    size_t buffer_len = sizeof(char)*num_kernels*MAX_KERNEL_NAME;
    char* kernel_names = new char[buffer_len];
    memset(kernel_names, '\0', buffer_len);
    size_t str_len = 0;
    err_code = clGetProgramInfo(
        prog,
        CL_PROGRAM_KERNEL_NAMES,
        buffer_len,
        (void *)kernel_names,
        &str_len
    );
    if (CL_SUCCESS != err_code)
        return;

    //parsing the names and inserting them to the list
    std::string names(kernel_names);
    assert (str_len == 1+names.size() && "incompatible string lengths");
    size_t offset = 0;
    for(size_t i=0 ; i<names.size() ; ++i){
        //kernel names are separated by semi colons
        if (names[i] == ';'){
            m_kernels.push_back(names.substr(offset, i-offset));
            offset = i+1;
        }
    }
    m_kernels.push_back(names.substr(offset, names.size()-offset));
    delete[] kernel_names;
}

KernelEnumerator::KernelEnumerator(cl_program prog) {
    process(prog);
}

KernelEnumerator::iterator KernelEnumerator::begin(){
    return m_kernels.begin();
}

KernelEnumerator::iterator KernelEnumerator::end(){
    return m_kernels.end();
}

size_t KernelEnumerator::size() const {
    return m_kernels.size();
}

/**
 Run the single test - run the test for both CL and SPIR versions of the kernel
 */
static bool run_test(cl_context context, cl_command_queue queue, cl_program clprog,
    cl_program bcprog, const std::string& kernel_name, std::string& err, const cl_device_id device,
    float ulps)
{
    WorkSizeInfo ws;
    TestResult cl_result;
    std::unique_ptr<TestResult> bc_result;
    // first, run the single CL test
    {
        // make sure that the kernel will be released before the program
        clKernelWrapper kernel = create_kernel_helper(clprog, kernel_name);
        // based on the kernel characteristics, we are generating and initializing the arguments for both phases (cl and bc executions)
        generate_kernel_data(context, kernel, ws, cl_result);
        bc_result.reset(cl_result.clone(context, ws, kernel, device));
        assert (compare_results(cl_result, *bc_result, ulps) && "not equal?");
        run_kernel( kernel, queue, ws, cl_result );
    }
    // now, run the single BC test
    {
        // make sure that the kernel will be released before the program
        clKernelWrapper kernel = create_kernel_helper(bcprog, kernel_name);
        run_kernel( kernel, queue, ws, *bc_result );
    }

    int error = clFinish(queue);
    if( CL_SUCCESS != error)
    {
        err = "clFinish failed\n";
        return false;
    }

    // compare the results
    if( !compare_results(cl_result, *bc_result, ulps) )
    {
        err = " (result diff in kernel '" + kernel_name + "').";
        return false;
    }
    return true;
}

/**
 Get the maximum relative error defined as ULP of floating-point math functions
 */
static float get_max_ulps(const char *test_name)
{
    float ulps = 0.f;
    // Get ULP values from math_brute_force functionList
    if (strstr(test_name, "math_kernel"))
    {
        for( size_t i = 0; i < functionListCount; i++ )
        {
            char name[64];
            const Func *func = &functionList[ i ];
            sprintf(name, ".%s_float", func->name);
            if (strstr(test_name, name))
            {
                ulps = func->float_ulps;
            }
            else
            {
                sprintf(name, ".%s_double", func->name);
                if (strstr(test_name, name))
                {
                    ulps = func->double_ulps;
                }
            }
        }
    }
    return ulps;
}

TestRunner::TestRunner(EventHandler *success, EventHandler *failure,
                       const OclExtensions& devExt):
    m_successHandler(success), m_failureHandler(failure), m_devExt(&devExt) {}

/**
 Based on the test name build the cl file name, the bc file name and execute
 the kernel for both modes (cl and bc).
 */
bool TestRunner::runBuildTest(cl_device_id device, const char *folder,
                              const char *test_name, cl_uint size_t_width)
{
    int failures = 0;
    // Composing the name of the CSV file.
    char* dir = get_exe_dir();
    std::string csvName(dir);
    csvName.append(dir_sep());
    csvName.append("khr.csv");
    free(dir);

    log_info("%s...\n", test_name);

    float ulps = get_max_ulps(test_name);

    // Figure out whether the test can run on the device. If not, we skip it.
    const KhrSupport& khrDb = *KhrSupport::get(csvName);
    cl_bool images = khrDb.isImagesRequired(folder, test_name);
    cl_bool images3D = khrDb.isImages3DRequired(folder, test_name);

    char deviceProfile[64];
    clGetDeviceInfo(device, CL_DEVICE_PROFILE, sizeof(deviceProfile), &deviceProfile, NULL);
    std::string device_profile(deviceProfile, 64);

    if(images == CL_TRUE && checkForImageSupport(device) != 0)
    {
        (*m_successHandler)(test_name, "");
        std::cout << "Skipped. (Cannot run on device due to Images is not supported)." << std::endl;
        return true;
    }

    if(images3D == CL_TRUE && checkFor3DImageSupport(device) != 0)
    {
        (*m_successHandler)(test_name, "");
        std::cout << "Skipped. (Cannot run on device as 3D images are not supported)." << std::endl;
        return true;
    }

    OclExtensions requiredExt = khrDb.getRequiredExtensions(folder, test_name);
    if(!m_devExt->supports(requiredExt))
    {
        (*m_successHandler)(test_name, "");
        std::cout << "Skipped. (Cannot run on device due to missing extensions: " << m_devExt->get_missing(requiredExt) << " )." << std::endl;
        return true;
    }

    std::string cl_file_path, bc_file;
    // Build cl file name based on the test name
    get_cl_file_path(folder, test_name, cl_file_path);
    // Build bc file name based on the test name
    get_bc_file_path(folder, test_name, bc_file, size_t_width);
    gRG.init(1);
    //
    // Processing each kernel in the program separately
    //
    clContextWrapper context;
    clCommandQueueWrapper queue;
    create_context_and_queue(device, &context, &queue);
    clProgramWrapper clprog = create_program_from_cl(context, cl_file_path);
    clProgramWrapper bcprog = create_program_from_bc(context, bc_file);
    std::string bcoptions = "-x spir -spir-std=1.2 -cl-kernel-arg-info";
    std::string cloptions = "-cl-kernel-arg-info";

    cl_device_fp_config gFloatCapabilities = 0;
    cl_int err;
    if ((err = clGetDeviceInfo(device, CL_DEVICE_SINGLE_FP_CONFIG, sizeof(gFloatCapabilities), &gFloatCapabilities, NULL)))
    {
        log_info("Unable to get device CL_DEVICE_SINGLE_FP_CONFIG. (%d)\n", err);
    }

    if (strstr(test_name, "div_cr") || strstr(test_name, "sqrt_cr")) {
        if ((gFloatCapabilities & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT) == 0) {
            (*m_successHandler)(test_name, "");
            std::cout << "Skipped. (Cannot run on device due to missing CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT property.)" << std::endl;
            return true;
        } else {
            bcoptions += " -cl-fp32-correctly-rounded-divide-sqrt";
            cloptions += " -cl-fp32-correctly-rounded-divide-sqrt";
        }
    }

    // Building the programs.
    BuildTask clBuild(clprog, device, cloptions.c_str());
    if (!clBuild.execute()) {
        std::cerr << clBuild.getErrorLog() << std::endl;
        return false;
    }

    SpirBuildTask bcBuild(bcprog, device, bcoptions.c_str());
    if (!bcBuild.execute()) {
        std::cerr << bcBuild.getErrorLog() << std::endl;
        return false;
    }

    KernelEnumerator clkernel_enumerator(clprog),
                     bckernel_enumerator(bcprog);
    if (clkernel_enumerator.size() != bckernel_enumerator.size()) {
        std::cerr << "number of kernels in test" << test_name
                  << " doesn't match in bc and cl files" << std::endl;
        return false;
    }
    KernelEnumerator::iterator it = clkernel_enumerator.begin(),
        e = clkernel_enumerator.end();
    while (it != e)
    {
        std::string kernel_name = *it++;
        std::string err;
        try
        {
            bool success = run_test(context, queue, clprog, bcprog, kernel_name, err, device, ulps);
            if (success)
            {
                log_info("kernel '%s' passed.\n", kernel_name.c_str());
                (*m_successHandler)(test_name, kernel_name);
            }
            else
            {
                ++failures;
                log_info("kernel '%s' failed.\n", kernel_name.c_str());
                (*m_failureHandler)(test_name, kernel_name);
            }
        }
        catch (std::runtime_error err)
        {
            ++failures;
            log_info("kernel '%s' failed: %s\n", kernel_name.c_str(), err.what());
            (*m_failureHandler)(test_name, kernel_name);
        }
    }

    log_info("%s %s\n", test_name, failures ? "FAILED" : "passed.");
    return failures == 0;
}