1/*
2 * Copyright (C) 2014 Rob Clark <robclark@freedesktop.org>
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 FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 *
23 * Authors:
24 *    Rob Clark <robclark@freedesktop.org>
25 */
26
27#ifndef IR3_SHADER_H_
28#define IR3_SHADER_H_
29
30#include <stdio.h>
31
32#include "compiler/shader_enums.h"
33#include "compiler/nir/nir.h"
34#include "util/bitscan.h"
35
36#include "ir3.h"
37
38struct glsl_type;
39
40/* driver param indices: */
41enum ir3_driver_param {
42	/* compute shader driver params: */
43	IR3_DP_NUM_WORK_GROUPS_X = 0,
44	IR3_DP_NUM_WORK_GROUPS_Y = 1,
45	IR3_DP_NUM_WORK_GROUPS_Z = 2,
46	IR3_DP_LOCAL_GROUP_SIZE_X = 4,
47	IR3_DP_LOCAL_GROUP_SIZE_Y = 5,
48	IR3_DP_LOCAL_GROUP_SIZE_Z = 6,
49	/* NOTE: gl_NumWorkGroups should be vec4 aligned because
50	 * glDispatchComputeIndirect() needs to load these from
51	 * the info->indirect buffer.  Keep that in mind when/if
52	 * adding any addition CS driver params.
53	 */
54	IR3_DP_CS_COUNT   = 8,   /* must be aligned to vec4 */
55
56	/* vertex shader driver params: */
57	IR3_DP_VTXID_BASE = 0,
58	IR3_DP_VTXCNT_MAX = 1,
59	/* user-clip-plane components, up to 8x vec4's: */
60	IR3_DP_UCP0_X     = 4,
61	/* .... */
62	IR3_DP_UCP7_W     = 35,
63	IR3_DP_VS_COUNT   = 36   /* must be aligned to vec4 */
64};
65
66#define IR3_MAX_SHADER_BUFFERS   32
67#define IR3_MAX_SHADER_IMAGES    32
68#define IR3_MAX_SO_BUFFERS        4
69#define IR3_MAX_SO_OUTPUTS       64
70#define IR3_MAX_CONSTANT_BUFFERS 32
71
72
73/**
74 * For consts needed to pass internal values to shader which may or may not
75 * be required, rather than allocating worst-case const space, we scan the
76 * shader and allocate consts as-needed:
77 *
78 *   + SSBO sizes: only needed if shader has a get_buffer_size intrinsic
79 *     for a given SSBO
80 *
81 *   + Image dimensions: needed to calculate pixel offset, but only for
82 *     images that have a image_store intrinsic
83 */
84struct ir3_driver_const_layout {
85	struct {
86		uint32_t mask;  /* bitmask of SSBOs that have get_buffer_size */
87		uint32_t count; /* number of consts allocated */
88		/* one const allocated per SSBO which has get_buffer_size,
89		 * ssbo_sizes.off[ssbo_id] is offset from start of ssbo_sizes
90		 * consts:
91		 */
92		uint32_t off[IR3_MAX_SHADER_BUFFERS];
93	} ssbo_size;
94
95	struct {
96		uint32_t mask;  /* bitmask of images that have image_store */
97		uint32_t count; /* number of consts allocated */
98		/* three const allocated per image which has image_store:
99		 *  + cpp         (bytes per pixel)
100		 *  + pitch       (y pitch)
101		 *  + array_pitch (z pitch)
102		 */
103		uint32_t off[IR3_MAX_SHADER_IMAGES];
104	} image_dims;
105};
106
107/**
108 * A single output for vertex transform feedback.
109 */
110struct ir3_stream_output {
111	unsigned register_index:6;  /**< 0 to 63 (OUT index) */
112	unsigned start_component:2; /** 0 to 3 */
113	unsigned num_components:3;  /** 1 to 4 */
114	unsigned output_buffer:3;   /**< 0 to PIPE_MAX_SO_BUFFERS */
115	unsigned dst_offset:16;     /**< offset into the buffer in dwords */
116	unsigned stream:2;          /**< 0 to 3 */
117};
118
119/**
120 * Stream output for vertex transform feedback.
121 */
122struct ir3_stream_output_info {
123	unsigned num_outputs;
124	/** stride for an entire vertex for each buffer in dwords */
125	uint16_t stride[IR3_MAX_SO_BUFFERS];
126
127	/**
128	 * Array of stream outputs, in the order they are to be written in.
129	 * Selected components are tightly packed into the output buffer.
130	 */
131	struct ir3_stream_output output[IR3_MAX_SO_OUTPUTS];
132};
133
134/* Configuration key used to identify a shader variant.. different
135 * shader variants can be used to implement features not supported
136 * in hw (two sided color), binning-pass vertex shader, etc.
137 */
138struct ir3_shader_key {
139	union {
140		struct {
141			/*
142			 * Combined Vertex/Fragment shader parameters:
143			 */
144			unsigned ucp_enables : 8;
145
146			/* do we need to check {v,f}saturate_{s,t,r}? */
147			unsigned has_per_samp : 1;
148
149			/*
150			 * Vertex shader variant parameters:
151			 */
152			unsigned vclamp_color : 1;
153
154			/*
155			 * Fragment shader variant parameters:
156			 */
157			unsigned sample_shading : 1;
158			unsigned msaa           : 1;
159			unsigned color_two_side : 1;
160			unsigned half_precision : 1;
161			/* used when shader needs to handle flat varyings (a4xx)
162			 * for front/back color inputs to frag shader:
163			 */
164			unsigned rasterflat : 1;
165			unsigned fclamp_color : 1;
166		};
167		uint32_t global;
168	};
169
170	/* bitmask of sampler which needs coords clamped for vertex
171	 * shader:
172	 */
173	uint16_t vsaturate_s, vsaturate_t, vsaturate_r;
174
175	/* bitmask of sampler which needs coords clamped for frag
176	 * shader:
177	 */
178	uint16_t fsaturate_s, fsaturate_t, fsaturate_r;
179
180	/* bitmask of ms shifts */
181	uint32_t vsamples, fsamples;
182
183	/* bitmask of samplers which need astc srgb workaround: */
184	uint16_t vastc_srgb, fastc_srgb;
185};
186
187static inline bool
188ir3_shader_key_equal(struct ir3_shader_key *a, struct ir3_shader_key *b)
189{
190	/* slow-path if we need to check {v,f}saturate_{s,t,r} */
191	if (a->has_per_samp || b->has_per_samp)
192		return memcmp(a, b, sizeof(struct ir3_shader_key)) == 0;
193	return a->global == b->global;
194}
195
196/* will the two keys produce different lowering for a fragment shader? */
197static inline bool
198ir3_shader_key_changes_fs(struct ir3_shader_key *key, struct ir3_shader_key *last_key)
199{
200	if (last_key->has_per_samp || key->has_per_samp) {
201		if ((last_key->fsaturate_s != key->fsaturate_s) ||
202				(last_key->fsaturate_t != key->fsaturate_t) ||
203				(last_key->fsaturate_r != key->fsaturate_r) ||
204				(last_key->fsamples != key->fsamples) ||
205				(last_key->fastc_srgb != key->fastc_srgb))
206			return true;
207	}
208
209	if (last_key->fclamp_color != key->fclamp_color)
210		return true;
211
212	if (last_key->color_two_side != key->color_two_side)
213		return true;
214
215	if (last_key->half_precision != key->half_precision)
216		return true;
217
218	if (last_key->rasterflat != key->rasterflat)
219		return true;
220
221	if (last_key->ucp_enables != key->ucp_enables)
222		return true;
223
224	return false;
225}
226
227/* will the two keys produce different lowering for a vertex shader? */
228static inline bool
229ir3_shader_key_changes_vs(struct ir3_shader_key *key, struct ir3_shader_key *last_key)
230{
231	if (last_key->has_per_samp || key->has_per_samp) {
232		if ((last_key->vsaturate_s != key->vsaturate_s) ||
233				(last_key->vsaturate_t != key->vsaturate_t) ||
234				(last_key->vsaturate_r != key->vsaturate_r) ||
235				(last_key->vsamples != key->vsamples) ||
236				(last_key->vastc_srgb != key->vastc_srgb))
237			return true;
238	}
239
240	if (last_key->vclamp_color != key->vclamp_color)
241		return true;
242
243	if (last_key->ucp_enables != key->ucp_enables)
244		return true;
245
246	return false;
247}
248
249/* clears shader-key flags which don't apply to the given shader
250 * stage
251 */
252static inline void
253ir3_normalize_key(struct ir3_shader_key *key, gl_shader_stage type)
254{
255	switch (type) {
256	case MESA_SHADER_FRAGMENT:
257		if (key->has_per_samp) {
258			key->vsaturate_s = 0;
259			key->vsaturate_t = 0;
260			key->vsaturate_r = 0;
261			key->vastc_srgb = 0;
262			key->vsamples = 0;
263		}
264		break;
265	case MESA_SHADER_VERTEX:
266		key->color_two_side = false;
267		key->half_precision = false;
268		key->rasterflat = false;
269		if (key->has_per_samp) {
270			key->fsaturate_s = 0;
271			key->fsaturate_t = 0;
272			key->fsaturate_r = 0;
273			key->fastc_srgb = 0;
274			key->fsamples = 0;
275		}
276		break;
277	default:
278		/* TODO */
279		break;
280	}
281}
282
283/**
284 * On a4xx+a5xx, Images share state with textures and SSBOs:
285 *
286 *   + Uses texture (cat5) state/instruction (isam) to read
287 *   + Uses SSBO state and instructions (cat6) to write and for atomics
288 *
289 * Starting with a6xx, Images and SSBOs are basically the same thing,
290 * with texture state and isam also used for SSBO reads.
291 *
292 * On top of that, gallium makes the SSBO (shader_buffers) state semi
293 * sparse, with the first half of the state space used for atomic
294 * counters lowered to atomic buffers.  We could ignore this, but I
295 * don't think we could *really* handle the case of a single shader
296 * that used the max # of textures + images + SSBOs.  And once we are
297 * offsetting images by num_ssbos (or visa versa) to map them into
298 * the same hardware state, the hardware state has become coupled to
299 * the shader state, so at this point we might as well just use a
300 * mapping table to remap things from image/SSBO idx to hw idx.
301 *
302 * To make things less (more?) confusing, for the hw "SSBO" state
303 * (since it is really both SSBO and Image) I'll use the name "IBO"
304 */
305struct ir3_ibo_mapping {
306#define IBO_INVALID 0xff
307	/* Maps logical SSBO state to hw state: */
308	uint8_t ssbo_to_ibo[IR3_MAX_SHADER_BUFFERS];
309	uint8_t ssbo_to_tex[IR3_MAX_SHADER_BUFFERS];
310
311	/* Maps logical Image state to hw state: */
312	uint8_t image_to_ibo[IR3_MAX_SHADER_IMAGES];
313	uint8_t image_to_tex[IR3_MAX_SHADER_IMAGES];
314
315	/* Maps hw state back to logical SSBO or Image state:
316	 *
317	 * note IBO_SSBO ORd into values to indicate that the
318	 * hw slot is used for SSBO state vs Image state.
319	 */
320#define IBO_SSBO    0x80
321	uint8_t ibo_to_image[32];
322	uint8_t tex_to_image[32];
323
324	uint8_t num_ibo;
325	uint8_t num_tex;    /* including real textures */
326	uint8_t tex_base;   /* the number of real textures, ie. image/ssbo start here */
327};
328
329struct ir3_shader_variant {
330	struct fd_bo *bo;
331
332	/* variant id (for debug) */
333	uint32_t id;
334
335	struct ir3_shader_key key;
336
337	/* vertex shaders can have an extra version for hwbinning pass,
338	 * which is pointed to by so->binning:
339	 */
340	bool binning_pass;
341	struct ir3_shader_variant *binning;
342
343	struct ir3_driver_const_layout const_layout;
344	struct ir3_info info;
345	struct ir3 *ir;
346
347	/* Levels of nesting of flow control:
348	 */
349	unsigned branchstack;
350
351	unsigned max_sun;
352
353	/* the instructions length is in units of instruction groups
354	 * (4 instructions for a3xx, 16 instructions for a4xx.. each
355	 * instruction is 2 dwords):
356	 */
357	unsigned instrlen;
358
359	/* the constants length is in units of vec4's, and is the sum of
360	 * the uniforms and the built-in compiler constants
361	 */
362	unsigned constlen;
363
364	/* number of uniforms (in vec4), not including built-in compiler
365	 * constants, etc.
366	 */
367	unsigned num_uniforms;
368
369	unsigned num_ubos;
370
371	/* About Linkage:
372	 *   + Let the frag shader determine the position/compmask for the
373	 *     varyings, since it is the place where we know if the varying
374	 *     is actually used, and if so, which components are used.  So
375	 *     what the hw calls "outloc" is taken from the "inloc" of the
376	 *     frag shader.
377	 *   + From the vert shader, we only need the output regid
378	 */
379
380	bool frag_coord, frag_face, color0_mrt;
381
382	/* NOTE: for input/outputs, slot is:
383	 *   gl_vert_attrib  - for VS inputs
384	 *   gl_varying_slot - for VS output / FS input
385	 *   gl_frag_result  - for FS output
386	 */
387
388	/* varyings/outputs: */
389	unsigned outputs_count;
390	struct {
391		uint8_t slot;
392		uint8_t regid;
393		bool    half : 1;
394	} outputs[16 + 2];  /* +POSITION +PSIZE */
395	bool writes_pos, writes_smask, writes_psize;
396
397	/* attributes (VS) / varyings (FS):
398	 * Note that sysval's should come *after* normal inputs.
399	 */
400	unsigned inputs_count;
401	struct {
402		uint8_t slot;
403		uint8_t regid;
404		uint8_t compmask;
405		uint8_t ncomp;
406		/* location of input (ie. offset passed to bary.f, etc).  This
407		 * matches the SP_VS_VPC_DST_REG.OUTLOCn value (a3xx and a4xx
408		 * have the OUTLOCn value offset by 8, presumably to account
409		 * for gl_Position/gl_PointSize)
410		 */
411		uint8_t inloc;
412		/* vertex shader specific: */
413		bool    sysval     : 1;   /* slot is a gl_system_value */
414		/* fragment shader specific: */
415		bool    bary       : 1;   /* fetched varying (vs one loaded into reg) */
416		bool    rasterflat : 1;   /* special handling for emit->rasterflat */
417		bool    use_ldlv   : 1;   /* internal to ir3_compiler_nir */
418		bool    half       : 1;
419		enum glsl_interp_mode interpolate;
420	} inputs[16 + 2];  /* +POSITION +FACE */
421
422	/* sum of input components (scalar).  For frag shaders, it only counts
423	 * the varying inputs:
424	 */
425	unsigned total_in;
426
427	/* For frag shaders, the total number of inputs (not scalar,
428	 * ie. SP_VS_PARAM_REG.TOTALVSOUTVAR)
429	 */
430	unsigned varying_in;
431
432	/* Remapping table to map Image and SSBO to hw state: */
433	struct ir3_ibo_mapping image_mapping;
434
435	/* number of samplers/textures (which are currently 1:1): */
436	int num_samp;
437
438	/* is there an implicit sampler to read framebuffer (FS only).. if
439	 * so the sampler-idx is 'num_samp - 1' (ie. it is appended after
440	 * the last "real" texture)
441	 */
442	bool fb_read;
443
444	/* do we have one or more SSBO instructions: */
445	bool has_ssbo;
446
447	/* do we need derivatives: */
448	bool need_pixlod;
449
450	/* do we have kill, image write, etc (which prevents early-z): */
451	bool no_earlyz;
452
453	bool per_samp;
454
455	/* Layout of constant registers, each section (in vec4). Pointer size
456	 * is 32b (a3xx, a4xx), or 64b (a5xx+), which effects the size of the
457	 * UBO and stream-out consts.
458	 */
459	struct {
460		/* user const start at zero */
461		unsigned ubo;
462		/* NOTE that a3xx might need a section for SSBO addresses too */
463		unsigned ssbo_sizes;
464		unsigned image_dims;
465		unsigned driver_param;
466		unsigned tfbo;
467		unsigned immediate;
468	} constbase;
469
470	unsigned immediates_count;
471	unsigned immediates_size;
472	struct {
473		uint32_t val[4];
474	} *immediates;
475
476	/* for astc srgb workaround, the number/base of additional
477	 * alpha tex states we need, and index of original tex states
478	 */
479	struct {
480		unsigned base, count;
481		unsigned orig_idx[16];
482	} astc_srgb;
483
484	/* shader variants form a linked list: */
485	struct ir3_shader_variant *next;
486
487	/* replicated here to avoid passing extra ptrs everywhere: */
488	gl_shader_stage type;
489	struct ir3_shader *shader;
490};
491
492struct ir3_ubo_range {
493	uint32_t offset; /* start offset of this block in const register file */
494	uint32_t start, end; /* range of block that's actually used */
495};
496
497struct ir3_ubo_analysis_state
498{
499	struct ir3_ubo_range range[IR3_MAX_CONSTANT_BUFFERS];
500	uint32_t size;
501	uint32_t lower_count;
502};
503
504
505struct ir3_shader {
506	gl_shader_stage type;
507
508	/* shader id (for debug): */
509	uint32_t id;
510	uint32_t variant_count;
511
512	/* so we know when we can disable TGSI related hacks: */
513	bool from_tgsi;
514
515	struct ir3_compiler *compiler;
516
517	struct ir3_ubo_analysis_state ubo_state;
518
519	struct nir_shader *nir;
520	struct ir3_stream_output_info stream_output;
521
522	struct ir3_shader_variant *variants;
523};
524
525void * ir3_shader_assemble(struct ir3_shader_variant *v, uint32_t gpu_id);
526struct ir3_shader_variant * ir3_shader_get_variant(struct ir3_shader *shader,
527		struct ir3_shader_key *key, bool binning_pass, bool *created);
528struct ir3_shader * ir3_shader_from_nir(struct ir3_compiler *compiler, nir_shader *nir);
529void ir3_shader_destroy(struct ir3_shader *shader);
530void ir3_shader_disasm(struct ir3_shader_variant *so, uint32_t *bin, FILE *out);
531uint64_t ir3_shader_outputs(const struct ir3_shader *so);
532
533int
534ir3_glsl_type_size(const struct glsl_type *type, bool bindless);
535
536static inline const char *
537ir3_shader_stage(struct ir3_shader *shader)
538{
539	switch (shader->type) {
540	case MESA_SHADER_VERTEX:     return "VERT";
541	case MESA_SHADER_FRAGMENT:   return "FRAG";
542	case MESA_SHADER_COMPUTE:    return "CL";
543	default:
544		unreachable("invalid type");
545		return NULL;
546	}
547}
548
549/*
550 * Helper/util:
551 */
552
553static inline int
554ir3_find_output(const struct ir3_shader_variant *so, gl_varying_slot slot)
555{
556	int j;
557
558	for (j = 0; j < so->outputs_count; j++)
559		if (so->outputs[j].slot == slot)
560			return j;
561
562	/* it seems optional to have a OUT.BCOLOR[n] for each OUT.COLOR[n]
563	 * in the vertex shader.. but the fragment shader doesn't know this
564	 * so  it will always have both IN.COLOR[n] and IN.BCOLOR[n].  So
565	 * at link time if there is no matching OUT.BCOLOR[n], we must map
566	 * OUT.COLOR[n] to IN.BCOLOR[n].  And visa versa if there is only
567	 * a OUT.BCOLOR[n] but no matching OUT.COLOR[n]
568	 */
569	if (slot == VARYING_SLOT_BFC0) {
570		slot = VARYING_SLOT_COL0;
571	} else if (slot == VARYING_SLOT_BFC1) {
572		slot = VARYING_SLOT_COL1;
573	} else if (slot == VARYING_SLOT_COL0) {
574		slot = VARYING_SLOT_BFC0;
575	} else if (slot == VARYING_SLOT_COL1) {
576		slot = VARYING_SLOT_BFC1;
577	} else {
578		return 0;
579	}
580
581	for (j = 0; j < so->outputs_count; j++)
582		if (so->outputs[j].slot == slot)
583			return j;
584
585	debug_assert(0);
586
587	return 0;
588}
589
590static inline int
591ir3_next_varying(const struct ir3_shader_variant *so, int i)
592{
593	while (++i < so->inputs_count)
594		if (so->inputs[i].compmask && so->inputs[i].bary)
595			break;
596	return i;
597}
598
599struct ir3_shader_linkage {
600	uint8_t max_loc;
601	uint8_t cnt;
602	struct {
603		uint8_t regid;
604		uint8_t compmask;
605		uint8_t loc;
606	} var[32];
607};
608
609static inline void
610ir3_link_add(struct ir3_shader_linkage *l, uint8_t regid, uint8_t compmask, uint8_t loc)
611{
612	int i = l->cnt++;
613
614	debug_assert(i < ARRAY_SIZE(l->var));
615
616	l->var[i].regid    = regid;
617	l->var[i].compmask = compmask;
618	l->var[i].loc      = loc;
619	l->max_loc = MAX2(l->max_loc, loc + util_last_bit(compmask));
620}
621
622static inline void
623ir3_link_shaders(struct ir3_shader_linkage *l,
624		const struct ir3_shader_variant *vs,
625		const struct ir3_shader_variant *fs)
626{
627	int j = -1, k;
628
629	while (l->cnt < ARRAY_SIZE(l->var)) {
630		j = ir3_next_varying(fs, j);
631
632		if (j >= fs->inputs_count)
633			break;
634
635		if (fs->inputs[j].inloc >= fs->total_in)
636			continue;
637
638		k = ir3_find_output(vs, fs->inputs[j].slot);
639
640		ir3_link_add(l, vs->outputs[k].regid,
641			fs->inputs[j].compmask, fs->inputs[j].inloc);
642	}
643}
644
645static inline uint32_t
646ir3_find_output_regid(const struct ir3_shader_variant *so, unsigned slot)
647{
648	int j;
649	for (j = 0; j < so->outputs_count; j++)
650		if (so->outputs[j].slot == slot)
651			return so->outputs[j].regid;
652	return regid(63, 0);
653}
654
655static inline uint32_t
656ir3_find_sysval_regid(const struct ir3_shader_variant *so, unsigned slot)
657{
658	int j;
659	for (j = 0; j < so->inputs_count; j++)
660		if (so->inputs[j].sysval && (so->inputs[j].slot == slot))
661			return so->inputs[j].regid;
662	return regid(63, 0);
663}
664
665/* calculate register footprint in terms of half-regs (ie. one full
666 * reg counts as two half-regs).
667 */
668static inline uint32_t
669ir3_shader_halfregs(const struct ir3_shader_variant *v)
670{
671	return (2 * (v->info.max_reg + 1)) + (v->info.max_half_reg + 1);
672}
673
674#endif /* IR3_SHADER_H_ */
675