radeonsi: remove si_llvm_add_attribute
[mesa.git] / src / gallium / drivers / radeonsi / si_shader_tgsi_setup.c
1 /*
2 * Copyright 2016 Advanced Micro Devices, Inc.
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 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the 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 NON-INFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24 #include "si_shader_internal.h"
25 #include "si_pipe.h"
26
27 #include "gallivm/lp_bld_const.h"
28 #include "gallivm/lp_bld_gather.h"
29 #include "gallivm/lp_bld_flow.h"
30 #include "gallivm/lp_bld_init.h"
31 #include "gallivm/lp_bld_intr.h"
32 #include "gallivm/lp_bld_misc.h"
33 #include "gallivm/lp_bld_swizzle.h"
34 #include "tgsi/tgsi_info.h"
35 #include "tgsi/tgsi_parse.h"
36 #include "util/u_math.h"
37 #include "util/u_memory.h"
38 #include "util/u_debug.h"
39
40 #include <stdio.h>
41 #include <llvm-c/Transforms/IPO.h>
42 #include <llvm-c/Transforms/Scalar.h>
43
44 /* Data for if/else/endif and bgnloop/endloop control flow structures.
45 */
46 struct si_llvm_flow {
47 /* Loop exit or next part of if/else/endif. */
48 LLVMBasicBlockRef next_block;
49 LLVMBasicBlockRef loop_entry_block;
50 };
51
52 enum si_llvm_calling_convention {
53 RADEON_LLVM_AMDGPU_VS = 87,
54 RADEON_LLVM_AMDGPU_GS = 88,
55 RADEON_LLVM_AMDGPU_PS = 89,
56 RADEON_LLVM_AMDGPU_CS = 90,
57 RADEON_LLVM_AMDGPU_HS = 93,
58 };
59
60 struct si_llvm_diagnostics {
61 struct pipe_debug_callback *debug;
62 unsigned retval;
63 };
64
65 static void si_diagnostic_handler(LLVMDiagnosticInfoRef di, void *context)
66 {
67 struct si_llvm_diagnostics *diag = (struct si_llvm_diagnostics *)context;
68 LLVMDiagnosticSeverity severity = LLVMGetDiagInfoSeverity(di);
69 char *description = LLVMGetDiagInfoDescription(di);
70 const char *severity_str = NULL;
71
72 switch (severity) {
73 case LLVMDSError:
74 severity_str = "error";
75 break;
76 case LLVMDSWarning:
77 severity_str = "warning";
78 break;
79 case LLVMDSRemark:
80 severity_str = "remark";
81 break;
82 case LLVMDSNote:
83 severity_str = "note";
84 break;
85 default:
86 severity_str = "unknown";
87 }
88
89 pipe_debug_message(diag->debug, SHADER_INFO,
90 "LLVM diagnostic (%s): %s", severity_str, description);
91
92 if (severity == LLVMDSError) {
93 diag->retval = 1;
94 fprintf(stderr,"LLVM triggered Diagnostic Handler: %s\n", description);
95 }
96
97 LLVMDisposeMessage(description);
98 }
99
100 /**
101 * Compile an LLVM module to machine code.
102 *
103 * @returns 0 for success, 1 for failure
104 */
105 unsigned si_llvm_compile(LLVMModuleRef M, struct ac_shader_binary *binary,
106 LLVMTargetMachineRef tm,
107 struct pipe_debug_callback *debug)
108 {
109 struct si_llvm_diagnostics diag;
110 char *err;
111 LLVMContextRef llvm_ctx;
112 LLVMMemoryBufferRef out_buffer;
113 unsigned buffer_size;
114 const char *buffer_data;
115 LLVMBool mem_err;
116
117 diag.debug = debug;
118 diag.retval = 0;
119
120 /* Setup Diagnostic Handler*/
121 llvm_ctx = LLVMGetModuleContext(M);
122
123 LLVMContextSetDiagnosticHandler(llvm_ctx, si_diagnostic_handler, &diag);
124
125 /* Compile IR*/
126 mem_err = LLVMTargetMachineEmitToMemoryBuffer(tm, M, LLVMObjectFile, &err,
127 &out_buffer);
128
129 /* Process Errors/Warnings */
130 if (mem_err) {
131 fprintf(stderr, "%s: %s", __FUNCTION__, err);
132 pipe_debug_message(debug, SHADER_INFO,
133 "LLVM emit error: %s", err);
134 FREE(err);
135 diag.retval = 1;
136 goto out;
137 }
138
139 /* Extract Shader Code*/
140 buffer_size = LLVMGetBufferSize(out_buffer);
141 buffer_data = LLVMGetBufferStart(out_buffer);
142
143 if (!ac_elf_read(buffer_data, buffer_size, binary)) {
144 fprintf(stderr, "radeonsi: cannot read an ELF shader binary\n");
145 diag.retval = 1;
146 }
147
148 /* Clean up */
149 LLVMDisposeMemoryBuffer(out_buffer);
150
151 out:
152 if (diag.retval != 0)
153 pipe_debug_message(debug, SHADER_INFO, "LLVM compile failed");
154 return diag.retval;
155 }
156
157 LLVMTypeRef tgsi2llvmtype(struct lp_build_tgsi_context *bld_base,
158 enum tgsi_opcode_type type)
159 {
160 struct si_shader_context *ctx = si_shader_context(bld_base);
161
162 switch (type) {
163 case TGSI_TYPE_UNSIGNED:
164 case TGSI_TYPE_SIGNED:
165 return ctx->ac.i32;
166 case TGSI_TYPE_UNSIGNED64:
167 case TGSI_TYPE_SIGNED64:
168 return ctx->ac.i64;
169 case TGSI_TYPE_DOUBLE:
170 return ctx->ac.f64;
171 case TGSI_TYPE_UNTYPED:
172 case TGSI_TYPE_FLOAT:
173 return ctx->ac.f32;
174 default: break;
175 }
176 return 0;
177 }
178
179 LLVMValueRef bitcast(struct lp_build_tgsi_context *bld_base,
180 enum tgsi_opcode_type type, LLVMValueRef value)
181 {
182 struct si_shader_context *ctx = si_shader_context(bld_base);
183 LLVMTypeRef dst_type = tgsi2llvmtype(bld_base, type);
184
185 if (dst_type)
186 return LLVMBuildBitCast(ctx->ac.builder, value, dst_type, "");
187 else
188 return value;
189 }
190
191 /**
192 * Return a value that is equal to the given i32 \p index if it lies in [0,num)
193 * or an undefined value in the same interval otherwise.
194 */
195 LLVMValueRef si_llvm_bound_index(struct si_shader_context *ctx,
196 LLVMValueRef index,
197 unsigned num)
198 {
199 LLVMBuilderRef builder = ctx->ac.builder;
200 LLVMValueRef c_max = LLVMConstInt(ctx->i32, num - 1, 0);
201 LLVMValueRef cc;
202
203 if (util_is_power_of_two(num)) {
204 index = LLVMBuildAnd(builder, index, c_max, "");
205 } else {
206 /* In theory, this MAX pattern should result in code that is
207 * as good as the bit-wise AND above.
208 *
209 * In practice, LLVM generates worse code (at the time of
210 * writing), because its value tracking is not strong enough.
211 */
212 cc = LLVMBuildICmp(builder, LLVMIntULE, index, c_max, "");
213 index = LLVMBuildSelect(builder, cc, index, c_max, "");
214 }
215
216 return index;
217 }
218
219 static struct si_llvm_flow *
220 get_current_flow(struct si_shader_context *ctx)
221 {
222 if (ctx->flow_depth > 0)
223 return &ctx->flow[ctx->flow_depth - 1];
224 return NULL;
225 }
226
227 static struct si_llvm_flow *
228 get_innermost_loop(struct si_shader_context *ctx)
229 {
230 for (unsigned i = ctx->flow_depth; i > 0; --i) {
231 if (ctx->flow[i - 1].loop_entry_block)
232 return &ctx->flow[i - 1];
233 }
234 return NULL;
235 }
236
237 static struct si_llvm_flow *
238 push_flow(struct si_shader_context *ctx)
239 {
240 struct si_llvm_flow *flow;
241
242 if (ctx->flow_depth >= ctx->flow_depth_max) {
243 unsigned new_max = MAX2(ctx->flow_depth << 1, RADEON_LLVM_INITIAL_CF_DEPTH);
244 ctx->flow = REALLOC(ctx->flow,
245 ctx->flow_depth_max * sizeof(*ctx->flow),
246 new_max * sizeof(*ctx->flow));
247 ctx->flow_depth_max = new_max;
248 }
249
250 flow = &ctx->flow[ctx->flow_depth];
251 ctx->flow_depth++;
252
253 flow->next_block = NULL;
254 flow->loop_entry_block = NULL;
255 return flow;
256 }
257
258 static LLVMValueRef emit_swizzle(struct lp_build_tgsi_context *bld_base,
259 LLVMValueRef value,
260 unsigned swizzle_x,
261 unsigned swizzle_y,
262 unsigned swizzle_z,
263 unsigned swizzle_w)
264 {
265 struct si_shader_context *ctx = si_shader_context(bld_base);
266 LLVMValueRef swizzles[4];
267
268 swizzles[0] = LLVMConstInt(ctx->i32, swizzle_x, 0);
269 swizzles[1] = LLVMConstInt(ctx->i32, swizzle_y, 0);
270 swizzles[2] = LLVMConstInt(ctx->i32, swizzle_z, 0);
271 swizzles[3] = LLVMConstInt(ctx->i32, swizzle_w, 0);
272
273 return LLVMBuildShuffleVector(ctx->ac.builder,
274 value,
275 LLVMGetUndef(LLVMTypeOf(value)),
276 LLVMConstVector(swizzles, 4), "");
277 }
278
279 /**
280 * Return the description of the array covering the given temporary register
281 * index.
282 */
283 static unsigned
284 get_temp_array_id(struct lp_build_tgsi_context *bld_base,
285 unsigned reg_index,
286 const struct tgsi_ind_register *reg)
287 {
288 struct si_shader_context *ctx = si_shader_context(bld_base);
289 unsigned num_arrays = ctx->bld_base.info->array_max[TGSI_FILE_TEMPORARY];
290 unsigned i;
291
292 if (reg && reg->ArrayID > 0 && reg->ArrayID <= num_arrays)
293 return reg->ArrayID;
294
295 for (i = 0; i < num_arrays; i++) {
296 const struct tgsi_array_info *array = &ctx->temp_arrays[i];
297
298 if (reg_index >= array->range.First && reg_index <= array->range.Last)
299 return i + 1;
300 }
301
302 return 0;
303 }
304
305 static struct tgsi_declaration_range
306 get_array_range(struct lp_build_tgsi_context *bld_base,
307 unsigned File, unsigned reg_index,
308 const struct tgsi_ind_register *reg)
309 {
310 struct si_shader_context *ctx = si_shader_context(bld_base);
311 struct tgsi_declaration_range range;
312
313 if (File == TGSI_FILE_TEMPORARY) {
314 unsigned array_id = get_temp_array_id(bld_base, reg_index, reg);
315 if (array_id)
316 return ctx->temp_arrays[array_id - 1].range;
317 }
318
319 range.First = 0;
320 range.Last = bld_base->info->file_max[File];
321 return range;
322 }
323
324 /**
325 * For indirect registers, construct a pointer directly to the requested
326 * element using getelementptr if possible.
327 *
328 * Returns NULL if the insertelement/extractelement fallback for array access
329 * must be used.
330 */
331 static LLVMValueRef
332 get_pointer_into_array(struct si_shader_context *ctx,
333 unsigned file,
334 unsigned swizzle,
335 unsigned reg_index,
336 const struct tgsi_ind_register *reg_indirect)
337 {
338 unsigned array_id;
339 struct tgsi_array_info *array;
340 LLVMBuilderRef builder = ctx->ac.builder;
341 LLVMValueRef idxs[2];
342 LLVMValueRef index;
343 LLVMValueRef alloca;
344
345 if (file != TGSI_FILE_TEMPORARY)
346 return NULL;
347
348 array_id = get_temp_array_id(&ctx->bld_base, reg_index, reg_indirect);
349 if (!array_id)
350 return NULL;
351
352 alloca = ctx->temp_array_allocas[array_id - 1];
353 if (!alloca)
354 return NULL;
355
356 array = &ctx->temp_arrays[array_id - 1];
357
358 if (!(array->writemask & (1 << swizzle)))
359 return ctx->undef_alloca;
360
361 index = si_get_indirect_index(ctx, reg_indirect, 1,
362 reg_index - ctx->temp_arrays[array_id - 1].range.First);
363
364 /* Ensure that the index is within a valid range, to guard against
365 * VM faults and overwriting critical data (e.g. spilled resource
366 * descriptors).
367 *
368 * TODO It should be possible to avoid the additional instructions
369 * if LLVM is changed so that it guarantuees:
370 * 1. the scratch space descriptor isolates the current wave (this
371 * could even save the scratch offset SGPR at the cost of an
372 * additional SALU instruction)
373 * 2. the memory for allocas must be allocated at the _end_ of the
374 * scratch space (after spilled registers)
375 */
376 index = si_llvm_bound_index(ctx, index, array->range.Last - array->range.First + 1);
377
378 index = LLVMBuildMul(
379 builder, index,
380 LLVMConstInt(ctx->i32, util_bitcount(array->writemask), 0),
381 "");
382 index = LLVMBuildAdd(
383 builder, index,
384 LLVMConstInt(ctx->i32,
385 util_bitcount(array->writemask & ((1 << swizzle) - 1)), 0),
386 "");
387 idxs[0] = ctx->i32_0;
388 idxs[1] = index;
389 return LLVMBuildGEP(ctx->ac.builder, alloca, idxs, 2, "");
390 }
391
392 LLVMValueRef
393 si_llvm_emit_fetch_64bit(struct lp_build_tgsi_context *bld_base,
394 LLVMTypeRef type,
395 LLVMValueRef ptr,
396 LLVMValueRef ptr2)
397 {
398 struct si_shader_context *ctx = si_shader_context(bld_base);
399 LLVMValueRef result;
400
401 result = LLVMGetUndef(LLVMVectorType(ctx->i32, 2));
402
403 result = LLVMBuildInsertElement(ctx->ac.builder,
404 result,
405 ac_to_integer(&ctx->ac, ptr),
406 ctx->i32_0, "");
407 result = LLVMBuildInsertElement(ctx->ac.builder,
408 result,
409 ac_to_integer(&ctx->ac, ptr2),
410 ctx->i32_1, "");
411 return LLVMBuildBitCast(ctx->ac.builder, result, type, "");
412 }
413
414 static LLVMValueRef
415 emit_array_fetch(struct lp_build_tgsi_context *bld_base,
416 unsigned File, enum tgsi_opcode_type type,
417 struct tgsi_declaration_range range,
418 unsigned swizzle)
419 {
420 struct si_shader_context *ctx = si_shader_context(bld_base);
421 unsigned i, size = range.Last - range.First + 1;
422 LLVMTypeRef vec = LLVMVectorType(tgsi2llvmtype(bld_base, type), size);
423 LLVMValueRef result = LLVMGetUndef(vec);
424
425 struct tgsi_full_src_register tmp_reg = {};
426 tmp_reg.Register.File = File;
427
428 for (i = 0; i < size; ++i) {
429 tmp_reg.Register.Index = i + range.First;
430 LLVMValueRef temp = si_llvm_emit_fetch(bld_base, &tmp_reg, type, swizzle);
431 result = LLVMBuildInsertElement(ctx->ac.builder, result, temp,
432 LLVMConstInt(ctx->i32, i, 0), "array_vector");
433 }
434 return result;
435 }
436
437 static LLVMValueRef
438 load_value_from_array(struct lp_build_tgsi_context *bld_base,
439 unsigned file,
440 enum tgsi_opcode_type type,
441 unsigned swizzle,
442 unsigned reg_index,
443 const struct tgsi_ind_register *reg_indirect)
444 {
445 struct si_shader_context *ctx = si_shader_context(bld_base);
446 LLVMBuilderRef builder = ctx->ac.builder;
447 LLVMValueRef ptr;
448
449 ptr = get_pointer_into_array(ctx, file, swizzle, reg_index, reg_indirect);
450 if (ptr) {
451 LLVMValueRef val = LLVMBuildLoad(builder, ptr, "");
452 if (tgsi_type_is_64bit(type)) {
453 LLVMValueRef ptr_hi, val_hi;
454 ptr_hi = LLVMBuildGEP(builder, ptr, &ctx->i32_1, 1, "");
455 val_hi = LLVMBuildLoad(builder, ptr_hi, "");
456 val = si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
457 val, val_hi);
458 }
459
460 return val;
461 } else {
462 struct tgsi_declaration_range range =
463 get_array_range(bld_base, file, reg_index, reg_indirect);
464 LLVMValueRef index =
465 si_get_indirect_index(ctx, reg_indirect, 1, reg_index - range.First);
466 LLVMValueRef array =
467 emit_array_fetch(bld_base, file, type, range, swizzle);
468 return LLVMBuildExtractElement(builder, array, index, "");
469 }
470 }
471
472 static void
473 store_value_to_array(struct lp_build_tgsi_context *bld_base,
474 LLVMValueRef value,
475 unsigned file,
476 unsigned chan_index,
477 unsigned reg_index,
478 const struct tgsi_ind_register *reg_indirect)
479 {
480 struct si_shader_context *ctx = si_shader_context(bld_base);
481 LLVMBuilderRef builder = ctx->ac.builder;
482 LLVMValueRef ptr;
483
484 ptr = get_pointer_into_array(ctx, file, chan_index, reg_index, reg_indirect);
485 if (ptr) {
486 LLVMBuildStore(builder, value, ptr);
487 } else {
488 unsigned i, size;
489 struct tgsi_declaration_range range = get_array_range(bld_base, file, reg_index, reg_indirect);
490 LLVMValueRef index = si_get_indirect_index(ctx, reg_indirect, 1, reg_index - range.First);
491 LLVMValueRef array =
492 emit_array_fetch(bld_base, file, TGSI_TYPE_FLOAT, range, chan_index);
493 LLVMValueRef temp_ptr;
494
495 array = LLVMBuildInsertElement(builder, array, value, index, "");
496
497 size = range.Last - range.First + 1;
498 for (i = 0; i < size; ++i) {
499 switch(file) {
500 case TGSI_FILE_OUTPUT:
501 temp_ptr = ctx->outputs[i + range.First][chan_index];
502 break;
503
504 case TGSI_FILE_TEMPORARY:
505 if (range.First + i >= ctx->temps_count)
506 continue;
507 temp_ptr = ctx->temps[(i + range.First) * TGSI_NUM_CHANNELS + chan_index];
508 break;
509
510 default:
511 continue;
512 }
513 value = LLVMBuildExtractElement(builder, array,
514 LLVMConstInt(ctx->i32, i, 0), "");
515 LLVMBuildStore(builder, value, temp_ptr);
516 }
517 }
518 }
519
520 /* If this is true, preload FS inputs at the beginning of shaders. Otherwise,
521 * reload them at each use. This must be true if the shader is using
522 * derivatives and KILL, because KILL can leave the WQM and then a lazy
523 * input load isn't in the WQM anymore.
524 */
525 static bool si_preload_fs_inputs(struct si_shader_context *ctx)
526 {
527 struct si_shader_selector *sel = ctx->shader->selector;
528
529 return sel->info.uses_derivatives &&
530 sel->info.uses_kill;
531 }
532
533 static LLVMValueRef
534 get_output_ptr(struct lp_build_tgsi_context *bld_base, unsigned index,
535 unsigned chan)
536 {
537 struct si_shader_context *ctx = si_shader_context(bld_base);
538
539 assert(index <= ctx->bld_base.info->file_max[TGSI_FILE_OUTPUT]);
540 return ctx->outputs[index][chan];
541 }
542
543 LLVMValueRef si_llvm_emit_fetch(struct lp_build_tgsi_context *bld_base,
544 const struct tgsi_full_src_register *reg,
545 enum tgsi_opcode_type type,
546 unsigned swizzle)
547 {
548 struct si_shader_context *ctx = si_shader_context(bld_base);
549 LLVMBuilderRef builder = ctx->ac.builder;
550 LLVMValueRef result = NULL, ptr, ptr2;
551
552 if (swizzle == ~0) {
553 LLVMValueRef values[TGSI_NUM_CHANNELS];
554 unsigned chan;
555 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
556 values[chan] = si_llvm_emit_fetch(bld_base, reg, type, chan);
557 }
558 return lp_build_gather_values(&ctx->gallivm, values,
559 TGSI_NUM_CHANNELS);
560 }
561
562 if (reg->Register.Indirect) {
563 LLVMValueRef load = load_value_from_array(bld_base, reg->Register.File, type,
564 swizzle, reg->Register.Index, &reg->Indirect);
565 return bitcast(bld_base, type, load);
566 }
567
568 switch(reg->Register.File) {
569 case TGSI_FILE_IMMEDIATE: {
570 LLVMTypeRef ctype = tgsi2llvmtype(bld_base, type);
571 if (tgsi_type_is_64bit(type)) {
572 result = LLVMGetUndef(LLVMVectorType(ctx->i32, 2));
573 result = LLVMConstInsertElement(result,
574 ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle],
575 ctx->i32_0);
576 result = LLVMConstInsertElement(result,
577 ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1],
578 ctx->i32_1);
579 return LLVMConstBitCast(result, ctype);
580 } else {
581 return LLVMConstBitCast(ctx->imms[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle], ctype);
582 }
583 }
584
585 case TGSI_FILE_INPUT: {
586 unsigned index = reg->Register.Index;
587 LLVMValueRef input[4];
588
589 /* I don't think doing this for vertex shaders is beneficial.
590 * For those, we want to make sure the VMEM loads are executed
591 * only once. Fragment shaders don't care much, because
592 * v_interp instructions are much cheaper than VMEM loads.
593 */
594 if (!si_preload_fs_inputs(ctx) &&
595 ctx->bld_base.info->processor == PIPE_SHADER_FRAGMENT)
596 ctx->load_input(ctx, index, &ctx->input_decls[index], input);
597 else
598 memcpy(input, &ctx->inputs[index * 4], sizeof(input));
599
600 result = input[swizzle];
601
602 if (tgsi_type_is_64bit(type)) {
603 ptr = result;
604 ptr2 = input[swizzle + 1];
605 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
606 ptr, ptr2);
607 }
608 break;
609 }
610
611 case TGSI_FILE_TEMPORARY:
612 if (reg->Register.Index >= ctx->temps_count)
613 return LLVMGetUndef(tgsi2llvmtype(bld_base, type));
614 ptr = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle];
615 if (tgsi_type_is_64bit(type)) {
616 ptr2 = ctx->temps[reg->Register.Index * TGSI_NUM_CHANNELS + swizzle + 1];
617 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
618 LLVMBuildLoad(builder, ptr, ""),
619 LLVMBuildLoad(builder, ptr2, ""));
620 }
621 result = LLVMBuildLoad(builder, ptr, "");
622 break;
623
624 case TGSI_FILE_OUTPUT:
625 ptr = get_output_ptr(bld_base, reg->Register.Index, swizzle);
626 if (tgsi_type_is_64bit(type)) {
627 ptr2 = get_output_ptr(bld_base, reg->Register.Index, swizzle + 1);
628 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
629 LLVMBuildLoad(builder, ptr, ""),
630 LLVMBuildLoad(builder, ptr2, ""));
631 }
632 result = LLVMBuildLoad(builder, ptr, "");
633 break;
634
635 default:
636 return LLVMGetUndef(tgsi2llvmtype(bld_base, type));
637 }
638
639 return bitcast(bld_base, type, result);
640 }
641
642 static LLVMValueRef fetch_system_value(struct lp_build_tgsi_context *bld_base,
643 const struct tgsi_full_src_register *reg,
644 enum tgsi_opcode_type type,
645 unsigned swizzle)
646 {
647 struct si_shader_context *ctx = si_shader_context(bld_base);
648 LLVMBuilderRef builder = ctx->ac.builder;
649 LLVMValueRef cval = ctx->system_values[reg->Register.Index];
650
651 if (tgsi_type_is_64bit(type)) {
652 LLVMValueRef lo, hi;
653
654 assert(swizzle == 0 || swizzle == 2);
655
656 lo = LLVMBuildExtractElement(
657 builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
658 hi = LLVMBuildExtractElement(
659 builder, cval, LLVMConstInt(ctx->i32, swizzle + 1, 0), "");
660
661 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
662 lo, hi);
663 }
664
665 if (LLVMGetTypeKind(LLVMTypeOf(cval)) == LLVMVectorTypeKind) {
666 cval = LLVMBuildExtractElement(
667 builder, cval, LLVMConstInt(ctx->i32, swizzle, 0), "");
668 } else {
669 assert(swizzle == 0);
670 }
671
672 return bitcast(bld_base, type, cval);
673 }
674
675 static void emit_declaration(struct lp_build_tgsi_context *bld_base,
676 const struct tgsi_full_declaration *decl)
677 {
678 struct si_shader_context *ctx = si_shader_context(bld_base);
679 LLVMBuilderRef builder = ctx->ac.builder;
680 unsigned first, last, i;
681 switch(decl->Declaration.File) {
682 case TGSI_FILE_ADDRESS:
683 {
684 unsigned idx;
685 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
686 unsigned chan;
687 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
688 ctx->addrs[idx][chan] = lp_build_alloca_undef(
689 &ctx->gallivm,
690 ctx->i32, "");
691 }
692 }
693 break;
694 }
695
696 case TGSI_FILE_TEMPORARY:
697 {
698 char name[16] = "";
699 LLVMValueRef array_alloca = NULL;
700 unsigned decl_size;
701 unsigned writemask = decl->Declaration.UsageMask;
702 first = decl->Range.First;
703 last = decl->Range.Last;
704 decl_size = 4 * ((last - first) + 1);
705
706 if (decl->Declaration.Array) {
707 unsigned id = decl->Array.ArrayID - 1;
708 unsigned array_size;
709
710 writemask &= ctx->temp_arrays[id].writemask;
711 ctx->temp_arrays[id].writemask = writemask;
712 array_size = ((last - first) + 1) * util_bitcount(writemask);
713
714 /* If the array has more than 16 elements, store it
715 * in memory using an alloca that spans the entire
716 * array.
717 *
718 * Otherwise, store each array element individually.
719 * We will then generate vectors (per-channel, up to
720 * <16 x float> if the usagemask is a single bit) for
721 * indirect addressing.
722 *
723 * Note that 16 is the number of vector elements that
724 * LLVM will store in a register, so theoretically an
725 * array with up to 4 * 16 = 64 elements could be
726 * handled this way, but whether that's a good idea
727 * depends on VGPR register pressure elsewhere.
728 *
729 * FIXME: We shouldn't need to have the non-alloca
730 * code path for arrays. LLVM should be smart enough to
731 * promote allocas into registers when profitable.
732 */
733 if (array_size > 16 ||
734 !ctx->screen->llvm_has_working_vgpr_indexing) {
735 array_alloca = lp_build_alloca_undef(&ctx->gallivm,
736 LLVMArrayType(ctx->f32,
737 array_size), "array");
738 ctx->temp_array_allocas[id] = array_alloca;
739 }
740 }
741
742 if (!ctx->temps_count) {
743 ctx->temps_count = bld_base->info->file_max[TGSI_FILE_TEMPORARY] + 1;
744 ctx->temps = MALLOC(TGSI_NUM_CHANNELS * ctx->temps_count * sizeof(LLVMValueRef));
745 }
746 if (!array_alloca) {
747 for (i = 0; i < decl_size; ++i) {
748 #ifdef DEBUG
749 snprintf(name, sizeof(name), "TEMP%d.%c",
750 first + i / 4, "xyzw"[i % 4]);
751 #endif
752 ctx->temps[first * TGSI_NUM_CHANNELS + i] =
753 lp_build_alloca_undef(&ctx->gallivm,
754 ctx->f32,
755 name);
756 }
757 } else {
758 LLVMValueRef idxs[2] = {
759 ctx->i32_0,
760 NULL
761 };
762 unsigned j = 0;
763
764 if (writemask != TGSI_WRITEMASK_XYZW &&
765 !ctx->undef_alloca) {
766 /* Create a dummy alloca. We use it so that we
767 * have a pointer that is safe to load from if
768 * a shader ever reads from a channel that
769 * it never writes to.
770 */
771 ctx->undef_alloca = lp_build_alloca_undef(
772 &ctx->gallivm,
773 ctx->f32, "undef");
774 }
775
776 for (i = 0; i < decl_size; ++i) {
777 LLVMValueRef ptr;
778 if (writemask & (1 << (i % 4))) {
779 #ifdef DEBUG
780 snprintf(name, sizeof(name), "TEMP%d.%c",
781 first + i / 4, "xyzw"[i % 4]);
782 #endif
783 idxs[1] = LLVMConstInt(ctx->i32, j, 0);
784 ptr = LLVMBuildGEP(builder, array_alloca, idxs, 2, name);
785 j++;
786 } else {
787 ptr = ctx->undef_alloca;
788 }
789 ctx->temps[first * TGSI_NUM_CHANNELS + i] = ptr;
790 }
791 }
792 break;
793 }
794 case TGSI_FILE_INPUT:
795 {
796 unsigned idx;
797 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
798 if (ctx->load_input &&
799 ctx->input_decls[idx].Declaration.File != TGSI_FILE_INPUT) {
800 ctx->input_decls[idx] = *decl;
801 ctx->input_decls[idx].Range.First = idx;
802 ctx->input_decls[idx].Range.Last = idx;
803 ctx->input_decls[idx].Semantic.Index += idx - decl->Range.First;
804
805 if (si_preload_fs_inputs(ctx) ||
806 bld_base->info->processor != PIPE_SHADER_FRAGMENT)
807 ctx->load_input(ctx, idx, &ctx->input_decls[idx],
808 &ctx->inputs[idx * 4]);
809 }
810 }
811 }
812 break;
813
814 case TGSI_FILE_SYSTEM_VALUE:
815 {
816 unsigned idx;
817 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
818 si_load_system_value(ctx, idx, decl);
819 }
820 }
821 break;
822
823 case TGSI_FILE_OUTPUT:
824 {
825 char name[16] = "";
826 unsigned idx;
827 for (idx = decl->Range.First; idx <= decl->Range.Last; idx++) {
828 unsigned chan;
829 assert(idx < RADEON_LLVM_MAX_OUTPUTS);
830 if (ctx->outputs[idx][0])
831 continue;
832 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
833 #ifdef DEBUG
834 snprintf(name, sizeof(name), "OUT%d.%c",
835 idx, "xyzw"[chan % 4]);
836 #endif
837 ctx->outputs[idx][chan] = lp_build_alloca_undef(
838 &ctx->gallivm,
839 ctx->f32, name);
840 }
841 }
842 break;
843 }
844
845 case TGSI_FILE_MEMORY:
846 si_tgsi_declare_compute_memory(ctx, decl);
847 break;
848
849 default:
850 break;
851 }
852 }
853
854 void si_llvm_emit_store(struct lp_build_tgsi_context *bld_base,
855 const struct tgsi_full_instruction *inst,
856 const struct tgsi_opcode_info *info,
857 unsigned index,
858 LLVMValueRef dst[4])
859 {
860 struct si_shader_context *ctx = si_shader_context(bld_base);
861 const struct tgsi_full_dst_register *reg = &inst->Dst[index];
862 LLVMBuilderRef builder = ctx->ac.builder;
863 LLVMValueRef temp_ptr, temp_ptr2 = NULL;
864 bool is_vec_store = false;
865 enum tgsi_opcode_type dtype = tgsi_opcode_infer_dst_type(inst->Instruction.Opcode, index);
866
867 if (dst[0]) {
868 LLVMTypeKind k = LLVMGetTypeKind(LLVMTypeOf(dst[0]));
869 is_vec_store = (k == LLVMVectorTypeKind);
870 }
871
872 if (is_vec_store) {
873 LLVMValueRef values[4] = {};
874 uint32_t writemask = reg->Register.WriteMask;
875 while (writemask) {
876 unsigned chan = u_bit_scan(&writemask);
877 LLVMValueRef index = LLVMConstInt(ctx->i32, chan, 0);
878 values[chan] = LLVMBuildExtractElement(ctx->ac.builder,
879 dst[0], index, "");
880 }
881 bld_base->emit_store(bld_base, inst, info, index, values);
882 return;
883 }
884
885 uint32_t writemask = reg->Register.WriteMask;
886 while (writemask) {
887 unsigned chan_index = u_bit_scan(&writemask);
888 LLVMValueRef value = dst[chan_index];
889
890 if (tgsi_type_is_64bit(dtype) && (chan_index == 1 || chan_index == 3))
891 continue;
892 if (inst->Instruction.Saturate)
893 value = ac_build_clamp(&ctx->ac, value);
894
895 if (reg->Register.File == TGSI_FILE_ADDRESS) {
896 temp_ptr = ctx->addrs[reg->Register.Index][chan_index];
897 LLVMBuildStore(builder, value, temp_ptr);
898 continue;
899 }
900
901 if (!tgsi_type_is_64bit(dtype))
902 value = ac_to_float(&ctx->ac, value);
903
904 if (reg->Register.Indirect) {
905 unsigned file = reg->Register.File;
906 unsigned reg_index = reg->Register.Index;
907 store_value_to_array(bld_base, value, file, chan_index,
908 reg_index, &reg->Indirect);
909 } else {
910 switch(reg->Register.File) {
911 case TGSI_FILE_OUTPUT:
912 temp_ptr = ctx->outputs[reg->Register.Index][chan_index];
913 if (tgsi_type_is_64bit(dtype))
914 temp_ptr2 = ctx->outputs[reg->Register.Index][chan_index + 1];
915 break;
916
917 case TGSI_FILE_TEMPORARY:
918 {
919 if (reg->Register.Index >= ctx->temps_count)
920 continue;
921
922 temp_ptr = ctx->temps[ TGSI_NUM_CHANNELS * reg->Register.Index + chan_index];
923 if (tgsi_type_is_64bit(dtype))
924 temp_ptr2 = ctx->temps[ TGSI_NUM_CHANNELS * reg->Register.Index + chan_index + 1];
925
926 break;
927 }
928 default:
929 return;
930 }
931 if (!tgsi_type_is_64bit(dtype))
932 LLVMBuildStore(builder, value, temp_ptr);
933 else {
934 LLVMValueRef ptr = LLVMBuildBitCast(builder, value,
935 LLVMVectorType(ctx->i32, 2), "");
936 LLVMValueRef val2;
937 value = LLVMBuildExtractElement(builder, ptr,
938 ctx->i32_0, "");
939 val2 = LLVMBuildExtractElement(builder, ptr,
940 ctx->i32_1, "");
941
942 LLVMBuildStore(builder, ac_to_float(&ctx->ac, value), temp_ptr);
943 LLVMBuildStore(builder, ac_to_float(&ctx->ac, val2), temp_ptr2);
944 }
945 }
946 }
947 }
948
949 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base, int pc)
950 {
951 char buf[32];
952 /* Subtract 1 so that the number shown is that of the corresponding
953 * opcode in the TGSI dump, e.g. an if block has the same suffix as
954 * the instruction number of the corresponding TGSI IF.
955 */
956 snprintf(buf, sizeof(buf), "%s%d", base, pc - 1);
957 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
958 }
959
960 /* Append a basic block at the level of the parent flow.
961 */
962 static LLVMBasicBlockRef append_basic_block(struct si_shader_context *ctx,
963 const char *name)
964 {
965 assert(ctx->flow_depth >= 1);
966
967 if (ctx->flow_depth >= 2) {
968 struct si_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
969
970 return LLVMInsertBasicBlockInContext(ctx->ac.context,
971 flow->next_block, name);
972 }
973
974 return LLVMAppendBasicBlockInContext(ctx->ac.context, ctx->main_fn, name);
975 }
976
977 /* Emit a branch to the given default target for the current block if
978 * applicable -- that is, if the current block does not already contain a
979 * branch from a break or continue.
980 */
981 static void emit_default_branch(LLVMBuilderRef builder, LLVMBasicBlockRef target)
982 {
983 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
984 LLVMBuildBr(builder, target);
985 }
986
987 static void bgnloop_emit(const struct lp_build_tgsi_action *action,
988 struct lp_build_tgsi_context *bld_base,
989 struct lp_build_emit_data *emit_data)
990 {
991 struct si_shader_context *ctx = si_shader_context(bld_base);
992 struct si_llvm_flow *flow = push_flow(ctx);
993 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
994 flow->next_block = append_basic_block(ctx, "ENDLOOP");
995 set_basicblock_name(flow->loop_entry_block, "loop", bld_base->pc);
996 LLVMBuildBr(ctx->ac.builder, flow->loop_entry_block);
997 LLVMPositionBuilderAtEnd(ctx->ac.builder, flow->loop_entry_block);
998 }
999
1000 static void brk_emit(const struct lp_build_tgsi_action *action,
1001 struct lp_build_tgsi_context *bld_base,
1002 struct lp_build_emit_data *emit_data)
1003 {
1004 struct si_shader_context *ctx = si_shader_context(bld_base);
1005 struct si_llvm_flow *flow = get_innermost_loop(ctx);
1006
1007 LLVMBuildBr(ctx->ac.builder, flow->next_block);
1008 }
1009
1010 static void cont_emit(const struct lp_build_tgsi_action *action,
1011 struct lp_build_tgsi_context *bld_base,
1012 struct lp_build_emit_data *emit_data)
1013 {
1014 struct si_shader_context *ctx = si_shader_context(bld_base);
1015 struct si_llvm_flow *flow = get_innermost_loop(ctx);
1016
1017 LLVMBuildBr(ctx->ac.builder, flow->loop_entry_block);
1018 }
1019
1020 static void else_emit(const struct lp_build_tgsi_action *action,
1021 struct lp_build_tgsi_context *bld_base,
1022 struct lp_build_emit_data *emit_data)
1023 {
1024 struct si_shader_context *ctx = si_shader_context(bld_base);
1025 struct si_llvm_flow *current_branch = get_current_flow(ctx);
1026 LLVMBasicBlockRef endif_block;
1027
1028 assert(!current_branch->loop_entry_block);
1029
1030 endif_block = append_basic_block(ctx, "ENDIF");
1031 emit_default_branch(ctx->ac.builder, endif_block);
1032
1033 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_branch->next_block);
1034 set_basicblock_name(current_branch->next_block, "else", bld_base->pc);
1035
1036 current_branch->next_block = endif_block;
1037 }
1038
1039 static void endif_emit(const struct lp_build_tgsi_action *action,
1040 struct lp_build_tgsi_context *bld_base,
1041 struct lp_build_emit_data *emit_data)
1042 {
1043 struct si_shader_context *ctx = si_shader_context(bld_base);
1044 struct si_llvm_flow *current_branch = get_current_flow(ctx);
1045
1046 assert(!current_branch->loop_entry_block);
1047
1048 emit_default_branch(ctx->ac.builder, current_branch->next_block);
1049 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_branch->next_block);
1050 set_basicblock_name(current_branch->next_block, "endif", bld_base->pc);
1051
1052 ctx->flow_depth--;
1053 }
1054
1055 static void endloop_emit(const struct lp_build_tgsi_action *action,
1056 struct lp_build_tgsi_context *bld_base,
1057 struct lp_build_emit_data *emit_data)
1058 {
1059 struct si_shader_context *ctx = si_shader_context(bld_base);
1060 struct si_llvm_flow *current_loop = get_current_flow(ctx);
1061
1062 assert(current_loop->loop_entry_block);
1063
1064 emit_default_branch(ctx->ac.builder, current_loop->loop_entry_block);
1065
1066 LLVMPositionBuilderAtEnd(ctx->ac.builder, current_loop->next_block);
1067 set_basicblock_name(current_loop->next_block, "endloop", bld_base->pc);
1068 ctx->flow_depth--;
1069 }
1070
1071 static void if_cond_emit(const struct lp_build_tgsi_action *action,
1072 struct lp_build_tgsi_context *bld_base,
1073 struct lp_build_emit_data *emit_data,
1074 LLVMValueRef cond)
1075 {
1076 struct si_shader_context *ctx = si_shader_context(bld_base);
1077 struct si_llvm_flow *flow = push_flow(ctx);
1078 LLVMBasicBlockRef if_block;
1079
1080 if_block = append_basic_block(ctx, "IF");
1081 flow->next_block = append_basic_block(ctx, "ELSE");
1082 set_basicblock_name(if_block, "if", bld_base->pc);
1083 LLVMBuildCondBr(ctx->ac.builder, cond, if_block, flow->next_block);
1084 LLVMPositionBuilderAtEnd(ctx->ac.builder, if_block);
1085 }
1086
1087 static void if_emit(const struct lp_build_tgsi_action *action,
1088 struct lp_build_tgsi_context *bld_base,
1089 struct lp_build_emit_data *emit_data)
1090 {
1091 struct si_shader_context *ctx = si_shader_context(bld_base);
1092 LLVMValueRef cond;
1093
1094 cond = LLVMBuildFCmp(ctx->ac.builder, LLVMRealUNE,
1095 emit_data->args[0],
1096 ctx->ac.f32_0, "");
1097
1098 if_cond_emit(action, bld_base, emit_data, cond);
1099 }
1100
1101 static void uif_emit(const struct lp_build_tgsi_action *action,
1102 struct lp_build_tgsi_context *bld_base,
1103 struct lp_build_emit_data *emit_data)
1104 {
1105 struct si_shader_context *ctx = si_shader_context(bld_base);
1106 LLVMValueRef cond;
1107
1108 cond = LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
1109 ac_to_integer(&ctx->ac, emit_data->args[0]), ctx->i32_0, "");
1110
1111 if_cond_emit(action, bld_base, emit_data, cond);
1112 }
1113
1114 static void emit_immediate(struct lp_build_tgsi_context *bld_base,
1115 const struct tgsi_full_immediate *imm)
1116 {
1117 unsigned i;
1118 struct si_shader_context *ctx = si_shader_context(bld_base);
1119
1120 for (i = 0; i < 4; ++i) {
1121 ctx->imms[ctx->imms_num * TGSI_NUM_CHANNELS + i] =
1122 LLVMConstInt(ctx->i32, imm->u[i].Uint, false );
1123 }
1124
1125 ctx->imms_num++;
1126 }
1127
1128 void si_llvm_context_init(struct si_shader_context *ctx,
1129 struct si_screen *sscreen,
1130 LLVMTargetMachineRef tm)
1131 {
1132 struct lp_type type;
1133
1134 /* Initialize the gallivm object:
1135 * We are only using the module, context, and builder fields of this struct.
1136 * This should be enough for us to be able to pass our gallivm struct to the
1137 * helper functions in the gallivm module.
1138 */
1139 memset(ctx, 0, sizeof(*ctx));
1140 ctx->screen = sscreen;
1141 ctx->tm = tm;
1142
1143 ctx->gallivm.context = LLVMContextCreate();
1144 ctx->gallivm.module = LLVMModuleCreateWithNameInContext("tgsi",
1145 ctx->gallivm.context);
1146 LLVMSetTarget(ctx->gallivm.module, "amdgcn--");
1147
1148 LLVMTargetDataRef data_layout = LLVMCreateTargetDataLayout(tm);
1149 char *data_layout_str = LLVMCopyStringRepOfTargetData(data_layout);
1150 LLVMSetDataLayout(ctx->gallivm.module, data_layout_str);
1151 LLVMDisposeTargetData(data_layout);
1152 LLVMDisposeMessage(data_layout_str);
1153
1154 bool unsafe_fpmath = (sscreen->debug_flags & DBG(UNSAFE_MATH)) != 0;
1155 enum ac_float_mode float_mode =
1156 unsafe_fpmath ? AC_FLOAT_MODE_UNSAFE_FP_MATH :
1157 AC_FLOAT_MODE_NO_SIGNED_ZEROS_FP_MATH;
1158
1159 ctx->gallivm.builder = ac_create_builder(ctx->gallivm.context,
1160 float_mode);
1161
1162 ac_llvm_context_init(&ctx->ac, ctx->gallivm.context,
1163 sscreen->info.chip_class, sscreen->info.family);
1164 ctx->ac.module = ctx->gallivm.module;
1165 ctx->ac.builder = ctx->gallivm.builder;
1166
1167 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1168
1169 type.floating = true;
1170 type.fixed = false;
1171 type.sign = true;
1172 type.norm = false;
1173 type.width = 32;
1174 type.length = 1;
1175
1176 lp_build_context_init(&bld_base->base, &ctx->gallivm, type);
1177 lp_build_context_init(&ctx->bld_base.uint_bld, &ctx->gallivm, lp_uint_type(type));
1178 lp_build_context_init(&ctx->bld_base.int_bld, &ctx->gallivm, lp_int_type(type));
1179 type.width *= 2;
1180 lp_build_context_init(&ctx->bld_base.dbl_bld, &ctx->gallivm, type);
1181 lp_build_context_init(&ctx->bld_base.uint64_bld, &ctx->gallivm, lp_uint_type(type));
1182 lp_build_context_init(&ctx->bld_base.int64_bld, &ctx->gallivm, lp_int_type(type));
1183
1184 bld_base->soa = 1;
1185 bld_base->emit_swizzle = emit_swizzle;
1186 bld_base->emit_declaration = emit_declaration;
1187 bld_base->emit_immediate = emit_immediate;
1188
1189 bld_base->op_actions[TGSI_OPCODE_BGNLOOP].emit = bgnloop_emit;
1190 bld_base->op_actions[TGSI_OPCODE_BRK].emit = brk_emit;
1191 bld_base->op_actions[TGSI_OPCODE_CONT].emit = cont_emit;
1192 bld_base->op_actions[TGSI_OPCODE_IF].emit = if_emit;
1193 bld_base->op_actions[TGSI_OPCODE_UIF].emit = uif_emit;
1194 bld_base->op_actions[TGSI_OPCODE_ELSE].emit = else_emit;
1195 bld_base->op_actions[TGSI_OPCODE_ENDIF].emit = endif_emit;
1196 bld_base->op_actions[TGSI_OPCODE_ENDLOOP].emit = endloop_emit;
1197
1198 si_shader_context_init_alu(&ctx->bld_base);
1199 si_shader_context_init_mem(ctx);
1200
1201 ctx->voidt = LLVMVoidTypeInContext(ctx->ac.context);
1202 ctx->i1 = LLVMInt1TypeInContext(ctx->ac.context);
1203 ctx->i8 = LLVMInt8TypeInContext(ctx->ac.context);
1204 ctx->i32 = LLVMInt32TypeInContext(ctx->ac.context);
1205 ctx->i64 = LLVMInt64TypeInContext(ctx->ac.context);
1206 ctx->i128 = LLVMIntTypeInContext(ctx->ac.context, 128);
1207 ctx->f32 = LLVMFloatTypeInContext(ctx->ac.context);
1208 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
1209 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
1210 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
1211 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
1212
1213 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, 0);
1214 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, 0);
1215 }
1216
1217 /* Set the context to a certain TGSI shader. Can be called repeatedly
1218 * to change the shader. */
1219 void si_llvm_context_set_tgsi(struct si_shader_context *ctx,
1220 struct si_shader *shader)
1221 {
1222 const struct tgsi_shader_info *info = NULL;
1223 const struct tgsi_token *tokens = NULL;
1224
1225 if (shader && shader->selector) {
1226 info = &shader->selector->info;
1227 tokens = shader->selector->tokens;
1228 }
1229
1230 ctx->shader = shader;
1231 ctx->type = info ? info->processor : -1;
1232 ctx->bld_base.info = info;
1233
1234 /* Clean up the old contents. */
1235 FREE(ctx->temp_arrays);
1236 ctx->temp_arrays = NULL;
1237 FREE(ctx->temp_array_allocas);
1238 ctx->temp_array_allocas = NULL;
1239
1240 FREE(ctx->imms);
1241 ctx->imms = NULL;
1242 ctx->imms_num = 0;
1243
1244 FREE(ctx->temps);
1245 ctx->temps = NULL;
1246 ctx->temps_count = 0;
1247
1248 if (!info)
1249 return;
1250
1251 ctx->num_const_buffers = util_last_bit(info->const_buffers_declared);
1252 ctx->num_shader_buffers = util_last_bit(info->shader_buffers_declared);
1253
1254 ctx->num_samplers = util_last_bit(info->samplers_declared);
1255 ctx->num_images = util_last_bit(info->images_declared);
1256
1257 if (!tokens)
1258 return;
1259
1260 if (info->array_max[TGSI_FILE_TEMPORARY] > 0) {
1261 int size = info->array_max[TGSI_FILE_TEMPORARY];
1262
1263 ctx->temp_arrays = CALLOC(size, sizeof(ctx->temp_arrays[0]));
1264 ctx->temp_array_allocas = CALLOC(size, sizeof(ctx->temp_array_allocas[0]));
1265
1266 tgsi_scan_arrays(tokens, TGSI_FILE_TEMPORARY, size,
1267 ctx->temp_arrays);
1268 }
1269 if (info->file_max[TGSI_FILE_IMMEDIATE] >= 0) {
1270 int size = info->file_max[TGSI_FILE_IMMEDIATE] + 1;
1271 ctx->imms = MALLOC(size * TGSI_NUM_CHANNELS * sizeof(LLVMValueRef));
1272 }
1273
1274 /* Re-set these to start with a clean slate. */
1275 ctx->bld_base.num_instructions = 0;
1276 ctx->bld_base.pc = 0;
1277 memset(ctx->outputs, 0, sizeof(ctx->outputs));
1278
1279 ctx->bld_base.emit_store = si_llvm_emit_store;
1280 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_IMMEDIATE] = si_llvm_emit_fetch;
1281 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_INPUT] = si_llvm_emit_fetch;
1282 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_TEMPORARY] = si_llvm_emit_fetch;
1283 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_OUTPUT] = si_llvm_emit_fetch;
1284 ctx->bld_base.emit_fetch_funcs[TGSI_FILE_SYSTEM_VALUE] = fetch_system_value;
1285 }
1286
1287 void si_llvm_create_func(struct si_shader_context *ctx,
1288 const char *name,
1289 LLVMTypeRef *return_types, unsigned num_return_elems,
1290 LLVMTypeRef *ParamTypes, unsigned ParamCount)
1291 {
1292 LLVMTypeRef main_fn_type, ret_type;
1293 LLVMBasicBlockRef main_fn_body;
1294 enum si_llvm_calling_convention call_conv;
1295 unsigned real_shader_type;
1296
1297 if (num_return_elems)
1298 ret_type = LLVMStructTypeInContext(ctx->ac.context,
1299 return_types,
1300 num_return_elems, true);
1301 else
1302 ret_type = ctx->voidt;
1303
1304 /* Setup the function */
1305 ctx->return_type = ret_type;
1306 main_fn_type = LLVMFunctionType(ret_type, ParamTypes, ParamCount, 0);
1307 ctx->main_fn = LLVMAddFunction(ctx->gallivm.module, name, main_fn_type);
1308 main_fn_body = LLVMAppendBasicBlockInContext(ctx->ac.context,
1309 ctx->main_fn, "main_body");
1310 LLVMPositionBuilderAtEnd(ctx->ac.builder, main_fn_body);
1311
1312 real_shader_type = ctx->type;
1313
1314 /* LS is merged into HS (TCS), and ES is merged into GS. */
1315 if (ctx->screen->info.chip_class >= GFX9) {
1316 if (ctx->shader->key.as_ls)
1317 real_shader_type = PIPE_SHADER_TESS_CTRL;
1318 else if (ctx->shader->key.as_es)
1319 real_shader_type = PIPE_SHADER_GEOMETRY;
1320 }
1321
1322 switch (real_shader_type) {
1323 case PIPE_SHADER_VERTEX:
1324 case PIPE_SHADER_TESS_EVAL:
1325 call_conv = RADEON_LLVM_AMDGPU_VS;
1326 break;
1327 case PIPE_SHADER_TESS_CTRL:
1328 call_conv = HAVE_LLVM >= 0x0500 ? RADEON_LLVM_AMDGPU_HS :
1329 RADEON_LLVM_AMDGPU_VS;
1330 break;
1331 case PIPE_SHADER_GEOMETRY:
1332 call_conv = RADEON_LLVM_AMDGPU_GS;
1333 break;
1334 case PIPE_SHADER_FRAGMENT:
1335 call_conv = RADEON_LLVM_AMDGPU_PS;
1336 break;
1337 case PIPE_SHADER_COMPUTE:
1338 call_conv = RADEON_LLVM_AMDGPU_CS;
1339 break;
1340 default:
1341 unreachable("Unhandle shader type");
1342 }
1343
1344 LLVMSetFunctionCallConv(ctx->main_fn, call_conv);
1345 }
1346
1347 void si_llvm_optimize_module(struct si_shader_context *ctx)
1348 {
1349 struct gallivm_state *gallivm = &ctx->gallivm;
1350 const char *triple = LLVMGetTarget(gallivm->module);
1351 LLVMTargetLibraryInfoRef target_library_info;
1352
1353 /* Dump LLVM IR before any optimization passes */
1354 if (ctx->screen->debug_flags & DBG(PREOPT_IR) &&
1355 si_can_dump_shader(ctx->screen, ctx->type))
1356 LLVMDumpModule(ctx->gallivm.module);
1357
1358 /* Create the pass manager */
1359 gallivm->passmgr = LLVMCreatePassManager();
1360
1361 target_library_info = gallivm_create_target_library_info(triple);
1362 LLVMAddTargetLibraryInfo(target_library_info, gallivm->passmgr);
1363
1364 if (si_extra_shader_checks(ctx->screen, ctx->type))
1365 LLVMAddVerifierPass(gallivm->passmgr);
1366
1367 LLVMAddAlwaysInlinerPass(gallivm->passmgr);
1368
1369 /* This pass should eliminate all the load and store instructions */
1370 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
1371
1372 /* Add some optimization passes */
1373 LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
1374 LLVMAddLICMPass(gallivm->passmgr);
1375 LLVMAddAggressiveDCEPass(gallivm->passmgr);
1376 LLVMAddCFGSimplificationPass(gallivm->passmgr);
1377 /* This is recommended by the instruction combining pass. */
1378 LLVMAddEarlyCSEMemSSAPass(gallivm->passmgr);
1379 LLVMAddInstructionCombiningPass(gallivm->passmgr);
1380
1381 /* Run the pass */
1382 LLVMRunPassManager(gallivm->passmgr, ctx->gallivm.module);
1383
1384 LLVMDisposeBuilder(ctx->ac.builder);
1385 LLVMDisposePassManager(gallivm->passmgr);
1386 gallivm_dispose_target_library_info(target_library_info);
1387 }
1388
1389 void si_llvm_dispose(struct si_shader_context *ctx)
1390 {
1391 LLVMDisposeModule(ctx->gallivm.module);
1392 LLVMContextDispose(ctx->gallivm.context);
1393 FREE(ctx->temp_arrays);
1394 ctx->temp_arrays = NULL;
1395 FREE(ctx->temp_array_allocas);
1396 ctx->temp_array_allocas = NULL;
1397 FREE(ctx->temps);
1398 ctx->temps = NULL;
1399 ctx->temps_count = 0;
1400 FREE(ctx->imms);
1401 ctx->imms = NULL;
1402 ctx->imms_num = 0;
1403 FREE(ctx->flow);
1404 ctx->flow = NULL;
1405 ctx->flow_depth_max = 0;
1406 }