src/mesa: add GL_NV_half_float extension support (v2)
[mesa.git] / src / mapi / glapi / gen / gl_marshal.py
1
2 # Copyright (C) 2012 Intel Corporation
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining a
5 # copy of this software and associated documentation files (the "Software"),
6 # to deal in the Software without restriction, including without limitation
7 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Software, and to permit persons to whom the
9 # Software is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice (including the next
12 # paragraph) shall be included in all copies or substantial portions of the
13 # Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 # IN THE SOFTWARE.
22
23 from __future__ import print_function
24
25 import contextlib
26 import getopt
27 import gl_XML
28 import license
29 import marshal_XML
30 import sys
31
32 header = """
33 #include "api_exec.h"
34 #include "glthread_marshal.h"
35 #include "bufferobj.h"
36 #include "dispatch.h"
37
38 #define COMPAT (ctx->API != API_OPENGL_CORE)
39
40 UNUSED static inline int safe_mul(int a, int b)
41 {
42 if (a < 0 || b < 0) return -1;
43 if (a == 0 || b == 0) return 0;
44 if (a > INT_MAX / b) return -1;
45 return a * b;
46 }
47 """
48
49
50 file_index = 0
51 file_count = 1
52 current_indent = 0
53
54
55 def out(str):
56 if str:
57 print(' '*current_indent + str)
58 else:
59 print('')
60
61
62 @contextlib.contextmanager
63 def indent(delta = 3):
64 global current_indent
65 current_indent += delta
66 yield
67 current_indent -= delta
68
69
70 class PrintCode(gl_XML.gl_print_base):
71 def __init__(self):
72 super(PrintCode, self).__init__()
73
74 self.name = 'gl_marshal.py'
75 self.license = license.bsd_license_template % (
76 'Copyright (C) 2012 Intel Corporation', 'INTEL CORPORATION')
77
78 def printRealHeader(self):
79 print(header)
80
81 def printRealFooter(self):
82 pass
83
84 def print_sync_call(self, func, unmarshal = 0):
85 call = 'CALL_{0}(ctx->CurrentServerDispatch, ({1}))'.format(
86 func.name, func.get_called_parameter_string())
87 if func.return_type == 'void':
88 out('{0};'.format(call))
89 if func.marshal_call_after and not unmarshal:
90 out(func.marshal_call_after);
91 else:
92 out('return {0};'.format(call))
93 assert not func.marshal_call_after
94
95 def print_sync_dispatch(self, func):
96 self.print_sync_call(func)
97
98 def print_sync_body(self, func):
99 out('/* {0}: marshalled synchronously */'.format(func.name))
100 out('{0} GLAPIENTRY'.format(func.return_type))
101 out('_mesa_marshal_{0}({1})'.format(func.name, func.get_parameter_string()))
102 out('{')
103 with indent():
104 out('GET_CURRENT_CONTEXT(ctx);')
105 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
106 self.print_sync_call(func)
107 out('}')
108 out('')
109 out('')
110
111 def print_async_dispatch(self, func):
112 out('cmd = _mesa_glthread_allocate_command(ctx, '
113 'DISPATCH_CMD_{0}, cmd_size);'.format(func.name))
114 for p in func.fixed_params:
115 if p.count:
116 out('memcpy(cmd->{0}, {0}, {1});'.format(
117 p.name, p.size_string()))
118 else:
119 out('cmd->{0} = {0};'.format(p.name))
120 if func.variable_params:
121 out('char *variable_data = (char *) (cmd + 1);')
122 i = 1
123 for p in func.variable_params:
124 if p.img_null_flag:
125 out('cmd->{0}_null = !{0};'.format(p.name))
126 out('if (!cmd->{0}_null) {{'.format(p.name))
127 with indent():
128 out(('memcpy(variable_data, {0}, {0}_size);').format(p.name))
129 if i < len(func.variable_params):
130 out('variable_data += {0}_size;'.format(p.name))
131 out('}')
132 else:
133 out(('memcpy(variable_data, {0}, {0}_size);').format(p.name))
134 if i < len(func.variable_params):
135 out('variable_data += {0}_size;'.format(p.name))
136 i += 1
137
138 if not func.fixed_params and not func.variable_params:
139 out('(void) cmd;')
140
141 if func.marshal_call_after:
142 out(func.marshal_call_after);
143
144 # Uncomment this if you want to call _mesa_glthread_finish for debugging
145 #out('_mesa_glthread_finish(ctx);')
146
147 def get_type_size(self, str):
148 if str.find('*') != -1:
149 return 8;
150
151 mapping = {
152 'GLboolean': 1,
153 'GLbyte': 1,
154 'GLubyte': 1,
155 'GLshort': 2,
156 'GLushort': 2,
157 'GLhalfNV': 2,
158 'GLenum': 4,
159 'GLint': 4,
160 'GLuint': 4,
161 'GLbitfield': 4,
162 'GLsizei': 4,
163 'GLfloat': 4,
164 'GLclampf': 4,
165 'GLfixed': 4,
166 'GLclampx': 4,
167 'GLhandleARB': 4,
168 'int': 4,
169 'float': 4,
170 'GLdouble': 8,
171 'GLclampd': 8,
172 'GLintptr': 8,
173 'GLsizeiptr': 8,
174 'GLint64': 8,
175 'GLuint64': 8,
176 'GLuint64EXT': 8,
177 'GLsync': 8,
178 }
179 val = mapping.get(str, 9999)
180 if val == 9999:
181 print('Unhandled type in gl_marshal.py.get_type_size: ' + str, file=sys.stderr)
182 return val
183
184 def print_async_struct(self, func):
185 out('struct marshal_cmd_{0}'.format(func.name))
186 out('{')
187 with indent():
188 out('struct marshal_cmd_base cmd_base;')
189
190 # Sort the parameters according to their size to pack the structure optimally
191 for p in sorted(func.fixed_params, key=lambda p: self.get_type_size(p.type_string())):
192 if p.count:
193 out('{0} {1}[{2}];'.format(
194 p.get_base_type_string(), p.name, p.count))
195 else:
196 out('{0} {1};'.format(p.type_string(), p.name))
197
198 for p in func.variable_params:
199 if p.img_null_flag:
200 out('bool {0}_null; /* If set, no data follows '
201 'for "{0}" */'.format(p.name))
202
203 for p in func.variable_params:
204 if p.count_scale != 1:
205 out(('/* Next {0} bytes are '
206 '{1} {2}[{3}][{4}] */').format(
207 p.size_string(marshal = 1), p.get_base_type_string(),
208 p.name, p.counter, p.count_scale))
209 else:
210 out(('/* Next {0} bytes are '
211 '{1} {2}[{3}] */').format(
212 p.size_string(marshal = 1), p.get_base_type_string(),
213 p.name, p.counter))
214 out('};')
215
216 def print_async_unmarshal(self, func):
217 out('void')
218 out(('_mesa_unmarshal_{0}(struct gl_context *ctx, '
219 'const struct marshal_cmd_{0} *cmd)').format(func.name))
220 out('{')
221 with indent():
222 for p in func.fixed_params:
223 if p.count:
224 p_decl = '{0} * {1} = cmd->{1};'.format(
225 p.get_base_type_string(), p.name)
226 else:
227 p_decl = '{0} {1} = cmd->{1};'.format(
228 p.type_string(), p.name)
229
230 if not p_decl.startswith('const '):
231 # Declare all local function variables as const, even if
232 # the original parameter is not const.
233 p_decl = 'const ' + p_decl
234
235 out(p_decl)
236
237 if func.variable_params:
238 for p in func.variable_params:
239 out('{0} * {1};'.format(
240 p.get_base_type_string(), p.name))
241 out('const char *variable_data = (const char *) (cmd + 1);')
242 i = 1
243 for p in func.variable_params:
244 out('{0} = ({1} *) variable_data;'.format(
245 p.name, p.get_base_type_string()))
246
247 if p.img_null_flag:
248 out('if (cmd->{0}_null)'.format(p.name))
249 with indent():
250 out('{0} = NULL;'.format(p.name))
251 if i < len(func.variable_params):
252 out('else')
253 with indent():
254 out('variable_data += {0};'.format(p.size_string(False, marshal = 1)))
255 elif i < len(func.variable_params):
256 out('variable_data += {0};'.format(p.size_string(False, marshal = 1)))
257 i += 1
258
259 self.print_sync_call(func, unmarshal = 1)
260 out('}')
261
262 def validate_count_or_fallback(self, func):
263 # Check that any counts for variable-length arguments might be < 0, in
264 # which case the command alloc or the memcpy would blow up before we
265 # get to the validation in Mesa core.
266 list = []
267 for p in func.parameters:
268 if p.is_variable_length():
269 list.append('{0}_size < 0'.format(p.name))
270 list.append('({0}_size > 0 && !{0})'.format(p.name))
271
272 if len(list) == 0:
273 return
274
275 list.append('(unsigned)cmd_size > MARSHAL_MAX_CMD_SIZE')
276
277 out('if (unlikely({0})) {{'.format(' || '.join(list)))
278 with indent():
279 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
280 self.print_sync_dispatch(func)
281 out('return;')
282 out('}')
283
284 def print_async_marshal(self, func):
285 out('void GLAPIENTRY')
286 out('_mesa_marshal_{0}({1})'.format(
287 func.name, func.get_parameter_string()))
288 out('{')
289 with indent():
290 out('GET_CURRENT_CONTEXT(ctx);')
291 for p in func.variable_params:
292 out('int {0}_size = {1};'.format(p.name, p.size_string(marshal = 1)))
293
294 struct = 'struct marshal_cmd_{0}'.format(func.name)
295 size_terms = ['sizeof({0})'.format(struct)]
296 for p in func.variable_params:
297 if p.img_null_flag:
298 size_terms.append('({0} ? {0}_size : 0)'.format(p.name))
299 else:
300 size_terms.append('{0}_size'.format(p.name))
301 out('int cmd_size = {0};'.format(' + '.join(size_terms)))
302 out('{0} *cmd;'.format(struct))
303
304 self.validate_count_or_fallback(func)
305
306 if func.marshal_sync:
307 out('if ({0}) {{'.format(func.marshal_sync))
308 with indent():
309 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
310 self.print_sync_dispatch(func)
311 out('return;')
312 out('}')
313
314 with indent():
315 self.print_async_dispatch(func)
316 out('}')
317
318 def print_async_body(self, func):
319 out('/* {0}: marshalled asynchronously */'.format(func.name))
320 self.print_async_struct(func)
321 self.print_async_unmarshal(func)
322 self.print_async_marshal(func)
323 out('')
324 out('')
325
326 def print_unmarshal_dispatch_cmd(self, api):
327 out('const _mesa_unmarshal_func _mesa_unmarshal_dispatch[NUM_DISPATCH_CMD] = {')
328 with indent():
329 for func in api.functionIterateAll():
330 flavor = func.marshal_flavor()
331 if flavor in ('skip', 'sync'):
332 continue
333 out('[DISPATCH_CMD_{0}] = (_mesa_unmarshal_func)_mesa_unmarshal_{0},'.format(func.name))
334 out('};')
335 out('')
336 out('')
337
338 def print_create_marshal_table(self, api):
339 out('/* _mesa_create_marshal_table takes a long time to compile with -O2 */')
340 out('#if defined(__GNUC__) && !defined(__clang__)')
341 out('__attribute__((optimize("O1")))')
342 out('#endif')
343 out('struct _glapi_table *')
344 out('_mesa_create_marshal_table(const struct gl_context *ctx)')
345 out('{')
346 with indent():
347 out('struct _glapi_table *table;')
348 out('')
349 out('table = _mesa_alloc_dispatch_table();')
350 out('if (table == NULL)')
351 with indent():
352 out('return NULL;')
353 out('')
354 for func in api.functionIterateAll():
355 if func.marshal_flavor() == 'skip':
356 continue
357 # Don't use the SET_* functions, because they increase compile time
358 # by 20 seconds (on Ryzen 1700X).
359 out('if (_gloffset_{0} >= 0)'.format(func.name))
360 out(' ((_glapi_proc *)(table))[_gloffset_{0}] = (_glapi_proc)_mesa_marshal_{0};'
361 .format(func.name))
362 out('')
363 out('return table;')
364 out('}')
365 out('')
366 out('')
367
368 def printBody(self, api):
369 # The first file only contains the dispatch tables
370 if file_index == 0:
371 self.print_unmarshal_dispatch_cmd(api)
372 self.print_create_marshal_table(api)
373 return
374
375 # The remaining files contain the marshal and unmarshal functions
376 func_per_file = (len(api.functionIterateAll()) // (file_count - 1)) + 1
377 i = -1
378 for func in api.functionIterateAll():
379 i += 1
380 if i // func_per_file != (file_index - 1):
381 continue
382
383 flavor = func.marshal_flavor()
384 if flavor in ('skip', 'custom'):
385 continue
386 elif flavor == 'async':
387 self.print_async_body(func)
388 elif flavor == 'sync':
389 self.print_sync_body(func)
390
391
392 def show_usage():
393 print('Usage: %s [-f input_file_name]' % sys.argv[0])
394 sys.exit(1)
395
396
397 if __name__ == '__main__':
398 file_name = 'gl_API.xml'
399
400 try:
401 (args, trail) = getopt.getopt(sys.argv[1:], 'm:f:i:n:')
402 except Exception:
403 show_usage()
404
405 for (arg,val) in args:
406 if arg == '-f':
407 file_name = val
408 elif arg == '-i':
409 file_index = int(val)
410 elif arg == '-n':
411 file_count = int(val)
412
413 assert file_index < file_count
414 printer = PrintCode()
415
416 api = gl_XML.parse_GL_API(file_name, marshal_XML.marshal_item_factory())
417 printer.Print(api)