aboutsummaryrefslogtreecommitdiff
path: root/src/builtins/printf.c
blob: c42341e2e113b3875f77b567ea6c0efe31fcaa94 (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
/* OpenCL built-in library: printf()

   Copyright (c) 2013 Erik Schnetter <eschnetter@perimeterinstitute.ca>
                      Perimeter Institute for Theoretical Physics
   
   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.
*/

// Make the C99 printf visible again
#undef printf

// GP: Add the OpenCL types for "C":
#define cl_khr_fp64
#define cl_khr_int64
#include "_kernel_c.h"

#include <limits.h>
#include <stdarg.h>
#include <stdbool.h>

// We implement the OpenCL printf by calling the C99 printf. This is
// not very efficient, but is easy to implement.
int printf(const char* restrict fmt, ...);
int snprintf(char* restrict str, size_t size, const char* restrict fmt, ...);

// For debugging
void debug_ptr(void * arg);

// Use as: DEBUG_PRINTF((fmt, args...)) -- note double parentheses!
//#define DEBUG_PRINTF(args) printf args
#define DEBUG_PRINTF(args) ((void)0)

// Conversion flags
typedef struct {
  bool left;
  bool plus;
  bool space;
  bool alt;
  bool zero;
} flags_t;



// Helper routines to output integers

#define INT_CONV_char  "hh"
#define INT_CONV_short "h"
#define INT_CONV_int   ""
#define INT_CONV_long  "ll"     // C99 printf uses "ll" for int64_t

#define DEFINE_PRINT_INTS(WIDTH)                                        \
  void _cl_print_ints_##WIDTH(flags_t flags, int field_width, int precision, \
                              char conv, const void* vals, int n)       \
  {                                                                     \
    DEBUG_PRINTF(("[printf:ints:n=%df]\n", n));                         \
    char outfmt[1000];                                                  \
    snprintf(outfmt, sizeof outfmt,                                     \
             "%%%s%s%s%s%s%.0d%s%.0d" INT_CONV_##WIDTH "%c",            \
             flags.left ? "-" : "",                                     \
             flags.plus ? "+" : "",                                     \
             flags.space ? " " : "",                                    \
             flags.alt ? "#" : "",                                      \
             flags.zero ? "0" : "",                                     \
             field_width,                                               \
             precision != -1 ? "." : "",                                \
             precision != -1 ? precision : 0,                           \
             conv);                                                     \
    DEBUG_PRINTF(("[printf:ints:outfmt=%s]\n", outfmt));                \
    for (int d=0; d<n; ++d) {                                           \
      DEBUG_PRINTF(("[printf:ints:d=%d]\n", d));                        \
      if (d != 0) printf(",");                                          \
      printf(outfmt, ((const WIDTH*)vals)[d]);                          \
    }                                                                   \
    DEBUG_PRINTF(("[printf:ints:done]\n"));                             \
  }

DEFINE_PRINT_INTS(char)
DEFINE_PRINT_INTS(short)
DEFINE_PRINT_INTS(int)
#ifdef cl_khr_int64
DEFINE_PRINT_INTS(long)
#endif

#undef DEFINE_PRINT_INTS



// Helper routines to output floats

// Defined in OpenCL
float __attribute__((overloadable)) vload_half(size_t offset, const half *p);

// Note: To simplify implementation, we print double values with %lf,
// although %f would suffice as well
#define FLOAT_CONV_half   "h"
#define FLOAT_CONV_float  ""
#define FLOAT_CONV_double "l"
#define FLOAT_GET_half(ptr)   vload_half(0, ptr)
#define FLOAT_GET_float(ptr)  (*(ptr))
#define FLOAT_GET_double(ptr) (*(ptr))

#define DEFINE_PRINT_FLOATS(WIDTH)                                      \
  void _cl_print_floats_##WIDTH(flags_t flags, int field_width, int precision, \
                                char conv, const void* vals, int n)     \
  {                                                                     \
    char outfmt[1000];                                                  \
    DEBUG_PRINTF(("[printf:floats:n=%dd]\n", n));                       \
    snprintf(outfmt, sizeof outfmt,                                     \
             "%%%s%s%s%s%s%.0d%s%.0d" FLOAT_CONV_##WIDTH "%c",          \
             flags.left ? "-" : "",                                     \
             flags.plus ? "+" : "",                                     \
             flags.space ? " " : "",                                    \
             flags.alt ? "#" : "",                                      \
             flags.zero ? "0" : "",                                     \
             field_width,                                               \
             precision != -1 ? "." : "",                                \
             precision != -1 ? precision : 0,                           \
             conv);                                                     \
    DEBUG_PRINTF(("[printf:floats:outfmt=%s]\n", outfmt));              \
    debug_ptr((void *)outfmt); \
    for (int d=0; d<n; ++d) {                                           \
      DEBUG_PRINTF(("[printf:floats:d=%d]\n", d));                      \
      if (d != 0) printf(",");                                          \
      debug_ptr((void *)((const WIDTH*)vals+d));			\
      printf(outfmt, FLOAT_GET_##WIDTH((const WIDTH*)vals+d));	\
    }                                                                   \
    DEBUG_PRINTF(("[printf:floats:done]\n"));                           \
  }

#ifdef cl_khr_fp16
DEFINE_PRINT_FLOATS(half)
#endif
DEFINE_PRINT_FLOATS(float)
#ifdef cl_khr_fp64
DEFINE_PRINT_FLOATS(double)
#endif

#undef DEFINE_PRINT_FLOATS



// Helper routines to output characters, strings, and pointers

void _cl_print_char(flags_t flags, int field_width, int val)
{
  DEBUG_PRINTF(("[printf:char]\n"));
  char outfmt[1000];
  snprintf(outfmt, sizeof outfmt,
           "%%%s%.0dc",
           flags.left ? "-" : "",
           field_width);
  DEBUG_PRINTF(("[printf:char:outfmt=%s]\n", outfmt));
  printf(outfmt, val);
  DEBUG_PRINTF(("[printf:char:done]\n"));
}

void _cl_print_string(flags_t flags, int field_width, int precision, const char* val)
{
  DEBUG_PRINTF(("[printf:char]\n"));
  char outfmt[1000];
  snprintf(outfmt, sizeof outfmt,
           precision < 0 ? "%%%s%.0ds" : "%%%s.%.0ds",
           flags.left ? "-" : "",
	   precision < 0 ? field_width : precision);
  DEBUG_PRINTF(("[printf:char:outfmt=%s]\n", outfmt));
  debug_ptr((void *)outfmt);
  printf(outfmt, val);
  DEBUG_PRINTF(("[printf:char:done]\n"));
}

void _cl_print_pointer(flags_t flags, int field_width, const void* val)
{
  DEBUG_PRINTF(("[printf:char]\n"));
  char outfmt[1000];
  snprintf(outfmt, sizeof outfmt,
           "%%%s%.0dp",
           flags.left ? "-" : "",
           field_width);
  DEBUG_PRINTF(("[printf:char:outfmt=%s]\n", outfmt));
  printf(outfmt, val);
  DEBUG_PRINTF(("[printf:char:done]\n"));
}



// The OpenCL printf routine.

// The implementation is straightforward:
// - walk through the format string
// - when a variable should be output, parse flags, field width,
//   precision, vector specifier, length, and conversion specifier
// - call a helper routine to perform the actual output
// - the helper routine is based on calling C99 printf, and constructs
//   a format string via snprintf
// - if there is an error during parsing, a "goto error" aborts the
//   routine, returning -1

#define OCL_CONSTANT_AS __attribute__((address_space(3)))
int _cl_printf(const OCL_CONSTANT_AS char* restrict format, ...)
{
  DEBUG_PRINTF(("[printf:format=%s]\n", format));
  va_list ap;
  va_start(ap, format);
  
  char ch = *format;
  while (ch) {
    if (ch == '%') {
      ch = *++format;
      
      if (ch == '%') {
        DEBUG_PRINTF(("[printf:%%]\n"));
        printf("%%");           // literal %
        ch = *++format;
      } else {
        DEBUG_PRINTF(("[printf:arg]\n"));
        // Flags
        flags_t flags;
        flags.left = false;
        flags.plus = false;
        flags.space = false;
        flags.alt = false;
        flags.zero = false;
        for (;;) {
          switch (ch) {
          case '-': if (flags.left) goto error; flags.left = true; break;
          case '+': if (flags.plus) goto error; flags.plus = true; break;
          case ' ': if (flags.space) goto error; flags.space = true; break;
          case '#': if (flags.alt) goto error; flags.alt = true; break;
          case '0': if (flags.zero) goto error; flags.zero = true; break;
          default: goto flags_done;
          }
          ch = *++format;
        }
      flags_done:;
        DEBUG_PRINTF(("[printf:flags:left=%d,plus=%d,space=%d,alt=%d,zero=%d]\n",
                      flags.left, flags.plus, flags.space, flags.alt, flags.zero));
        
        // Field width
        int field_width = 0;
        while (ch >= '0' && ch <= '9') {
          if (ch == '0' && field_width == 0) goto error;
          if (field_width > (INT_MAX - 9) / 10) goto error;
          field_width = 10 * field_width + (ch - '0');
          ch = *++format;
        }
        DEBUG_PRINTF(("[printf:width=%d]\n", field_width));
        
        // Precision
        int precision = -1;
        if (ch == '.') {
          ch = *++format;
          precision = 0;
          while (ch >= '0' && ch <= '9') {
            if (precision > (INT_MAX - 9) / 10) goto error;
            precision = 10 * precision + (ch - '0');
            ch = *++format;
          }
        }
        DEBUG_PRINTF(("[printf:precision=%d]\n", precision));
        
        // Vector specifier
        int vector_length = 0;
        if (ch == 'v') {
          ch = *++format;
          while (ch >= '0' && ch <= '9') {
            if (ch == '0' && vector_length == 0) goto error;
            if (vector_length > (INT_MAX - 9) / 10) goto error;
            vector_length = 10 * vector_length + (ch - '0');
            ch = *++format;
          }
          if (! (vector_length == 2 ||
                 vector_length == 3 ||
                 vector_length == 4 ||
                 vector_length == 8 ||
                 vector_length == 16)) goto error;
        }
        DEBUG_PRINTF(("[printf:vector_length=%d]\n", vector_length));
        
        // Length modifier
        int length = 0;           // default
        if (ch == 'h') {
          ch = *++format;
          if (ch == 'h') {
            ch = *++format;
            length = 1;           // "hh" -> char
          } else if (ch == 'l') {
            ch = *++format;
            length = 4;           // "hl" -> int or float
          } else {
            length = 2;           // "h" -> short
          }
        } else if (ch == 'l') {
          ch = *++format;
          length = 8;             // "l" -> long
        }
        if (vector_length > 0 && length == 0) goto error;
        if (vector_length == 0 && length == 4) goto error;
        if (vector_length == 0) vector_length = 1;
        DEBUG_PRINTF(("[printf:length=%d]\n", length));
        
        // Conversion specifier
        switch (ch) {
          
          // Output integers
        case 'd':
        case 'i':
        case 'o':
        case 'u':
        case 'x':
        case 'X':
          
#define CALL_PRINT_INTS(WIDTH, PROMOTED_WIDTH)                          \
          {                                                             \
            WIDTH##16 val;                                              \
            switch (vector_length) {                                    \
            default: __builtin_unreachable();                           \
            case 1: val.s0 = va_arg(ap, PROMOTED_WIDTH); break;         \
            case 2: val.s01 = va_arg(ap, WIDTH##2); break;              \
            case 3: val.s012 = va_arg(ap, WIDTH##3); break;             \
            case 4: val.s0123 = va_arg(ap, WIDTH##4); break;            \
            case 8: val.lo = va_arg(ap, WIDTH##8); break;               \
            case 16: val = va_arg(ap, WIDTH##16); break;                \
            }                                                           \
            _cl_print_ints_##WIDTH(flags, field_width, precision,       \
                                   ch, &val, vector_length);            \
          }
          
          DEBUG_PRINTF(("[printf:int:conversion=%c]\n", ch));
          switch (length) {
          default: __builtin_unreachable();
          case 1: CALL_PRINT_INTS(char, int); break;
          case 2: CALL_PRINT_INTS(short, int); break;
          case 0:
          case 4: CALL_PRINT_INTS(int, int); break;
#ifdef cl_khr_int64
          case 8: CALL_PRINT_INTS(long, long); break;
#endif
          }

#undef CALL_PRINT_INTS
          
          break;
          
          // Output floats
        case 'f':
        case 'F':
        case 'e':
        case 'E':
        case 'g':
        case 'G':
        case 'a':
        case 'A':
          
#define CALL_PRINT_FLOATS(WIDTH, PROMOTED_WIDTH)                        \
          {                                                             \
            WIDTH##16 val;                                              \
            switch (vector_length) {                                    \
            default: __builtin_unreachable();                           \
            case 1: val.s0 = va_arg(ap, PROMOTED_WIDTH); break;         \
            case 2: val.s01 = va_arg(ap, WIDTH##2); break;              \
            case 3: val.s012 = va_arg(ap, WIDTH##3); break;             \
            case 4: val.s0123 = va_arg(ap, WIDTH##4); break;            \
            case 8: val.lo = va_arg(ap, WIDTH##8); break;               \
            case 16: val = va_arg(ap, WIDTH##16); break;                \
            }                                                           \
            float tmp;\
	    tmp = val.s0; \
            debug_ptr((void *)&tmp);				\
	    tmp = val.s1; \
            debug_ptr((void *)&tmp);				\
	    tmp = val.s2; \
            debug_ptr((void *)&tmp);				\
	    tmp = val.s3; \
            debug_ptr((void *)&tmp);				\
            _cl_print_floats_##WIDTH(flags, field_width, precision,     \
                                     ch, &val, vector_length);          \
          }
          
          DEBUG_PRINTF(("[printf:float:conversion=%c]\n", ch));
          switch (length) {
          default: __builtin_unreachable();
#ifdef cl_khr_fp16
            // case 2: CALL_PRINT_FLOATS(half, double); break;
          case 2: goto error;   // not yet implemented
#endif
          case 0:
            // Note: width 0 cleverly falls through to float if double
            // is not supported
#ifdef cl_khr_fp64
          case 8: CALL_PRINT_FLOATS(double, double); break;
          case 4: CALL_PRINT_FLOATS(float, double); break;
#else
              break;
#endif
          }
          
#undef CALL_PRINT_FLOATS
          
          break;
          
          // Output a character
        case 'c': {
          DEBUG_PRINTF(("[printf:char]\n"));
          if (flags.plus || flags.space || flags.alt || flags.zero) goto error;
          DEBUG_PRINTF(("[printf:char1]\n"));
          if (precision != -1) goto error;
          DEBUG_PRINTF(("[printf:char2]\n"));
          if (vector_length != 1) goto error;
          DEBUG_PRINTF(("[printf:char3]\n"));
          if (length != 0) goto error;
          DEBUG_PRINTF(("[printf:char4]\n"));
          int val = va_arg(ap, int);
          _cl_print_char(flags, field_width, val);
          break;
        }
          
          // Output a string
        case 's': {
          if (flags.plus || flags.space || flags.alt || flags.zero) goto error;
          if (vector_length != 1) goto error;
          if (length != 0) goto error;
          const char* val = va_arg(ap, const char*);
          // GP: Note: v1.2 Khronos test_printf tests for "%.1s", so need to check precision
          _cl_print_string(flags, field_width, precision, val);
          break;
        }
          
          // Output a pointer
        case 'p': {
          if (flags.plus || flags.space || flags.alt || flags.zero) goto error;
          if (precision != -1) goto error;
          if (vector_length != 1) goto error;
          if (length != 0) goto error;
          const void* val = va_arg(ap, const void*);
          _cl_print_pointer(flags, field_width, val);
          break;
        }
          
        default: goto error;
        }
        ch = *++format;
        
      } // not a literal %

    } else {
      DEBUG_PRINTF(("[printf:literal]\n"));
      printf("%c", ch);
      ch = *++format;
    }
  }
  
  va_end(ap);
  DEBUG_PRINTF(("[printf:done]\n"));
  return 0;
  
 error:;
  va_end(ap);
  DEBUG_PRINTF(("[printf:error]\n"));
  printf("(printf format string error)");
  return -1;
}