draw_llvm.c revision 6b63e25b3d7a6ac0bd738c139ead0c7e7ad84368
1/**************************************************************************
2 *
3 * Copyright 2010 VMware, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include "draw_llvm.h"
29
30#include "draw_context.h"
31#include "draw_vs.h"
32
33#include "gallivm/lp_bld_arit.h"
34#include "gallivm/lp_bld_logic.h"
35#include "gallivm/lp_bld_const.h"
36#include "gallivm/lp_bld_swizzle.h"
37#include "gallivm/lp_bld_struct.h"
38#include "gallivm/lp_bld_type.h"
39#include "gallivm/lp_bld_flow.h"
40#include "gallivm/lp_bld_debug.h"
41#include "gallivm/lp_bld_tgsi.h"
42#include "gallivm/lp_bld_printf.h"
43#include "gallivm/lp_bld_intr.h"
44#include "gallivm/lp_bld_init.h"
45#include "gallivm/lp_bld_type.h"
46
47#include "tgsi/tgsi_exec.h"
48#include "tgsi/tgsi_dump.h"
49
50#include "util/u_math.h"
51#include "util/u_pointer.h"
52#include "util/u_string.h"
53#include "util/u_simple_list.h"
54
55
56#define DEBUG_STORE 0
57
58
59/**
60 * This function is called by the gallivm "garbage collector" when
61 * the LLVM global data structures are freed.  We must free all LLVM-related
62 * data.  Specifically, all JIT'd shader variants.
63 */
64static void
65draw_llvm_garbage_collect_callback(void *cb_data)
66{
67   struct draw_llvm *llvm = (struct draw_llvm *) cb_data;
68   struct draw_context *draw = llvm->draw;
69   struct draw_llvm_variant_list_item *li;
70
71   /* Ensure prepare will be run and shaders recompiled */
72   assert(!draw->suspend_flushing);
73   draw_do_flush(draw, DRAW_FLUSH_STATE_CHANGE);
74
75   /* free all shader variants */
76   li = first_elem(&llvm->vs_variants_list);
77   while (!at_end(&llvm->vs_variants_list, li)) {
78      struct draw_llvm_variant_list_item *next = next_elem(li);
79      draw_llvm_destroy_variant(li->base);
80      li = next;
81   }
82
83   /* Null-out these pointers so they get remade next time they're needed.
84    * See the accessor functions below.
85    */
86   llvm->context_ptr_type = NULL;
87   llvm->buffer_ptr_type = NULL;
88   llvm->vb_ptr_type = NULL;
89   llvm->vertex_header_ptr_type = NULL;
90}
91
92
93static void
94draw_llvm_generate(struct draw_llvm *llvm, struct draw_llvm_variant *var,
95                   boolean elts);
96
97
98/**
99 * Create LLVM type for struct draw_jit_texture
100 */
101static LLVMTypeRef
102create_jit_texture_type(struct gallivm_state *gallivm, const char *struct_name)
103{
104   LLVMTargetDataRef target = gallivm->target;
105   LLVMTypeRef texture_type;
106   LLVMTypeRef elem_types[DRAW_JIT_TEXTURE_NUM_FIELDS];
107   LLVMTypeRef int32_type = LLVMInt32TypeInContext(gallivm->context);
108
109   elem_types[DRAW_JIT_TEXTURE_WIDTH]  =
110   elem_types[DRAW_JIT_TEXTURE_HEIGHT] =
111   elem_types[DRAW_JIT_TEXTURE_DEPTH] =
112   elem_types[DRAW_JIT_TEXTURE_FIRST_LEVEL] =
113   elem_types[DRAW_JIT_TEXTURE_LAST_LEVEL] = int32_type;
114   elem_types[DRAW_JIT_TEXTURE_ROW_STRIDE] =
115   elem_types[DRAW_JIT_TEXTURE_IMG_STRIDE] =
116      LLVMArrayType(int32_type, PIPE_MAX_TEXTURE_LEVELS);
117   elem_types[DRAW_JIT_TEXTURE_DATA] =
118      LLVMArrayType(LLVMPointerType(LLVMInt8TypeInContext(gallivm->context), 0),
119                    PIPE_MAX_TEXTURE_LEVELS);
120   elem_types[DRAW_JIT_TEXTURE_MIN_LOD] =
121   elem_types[DRAW_JIT_TEXTURE_MAX_LOD] =
122   elem_types[DRAW_JIT_TEXTURE_LOD_BIAS] = LLVMFloatTypeInContext(gallivm->context);
123   elem_types[DRAW_JIT_TEXTURE_BORDER_COLOR] =
124      LLVMArrayType(LLVMFloatTypeInContext(gallivm->context), 4);
125
126#if HAVE_LLVM >= 0x0300
127   texture_type = LLVMStructCreateNamed(gallivm->context, struct_name);
128   LLVMStructSetBody(texture_type, elem_types,
129                     Elements(elem_types), 0);
130#else
131   texture_type = LLVMStructTypeInContext(gallivm->context, elem_types,
132                                          Elements(elem_types), 0);
133
134   LLVMAddTypeName(gallivm->module, struct_name, texture_type);
135
136   /* Make sure the target's struct layout cache doesn't return
137    * stale/invalid data.
138    */
139   LLVMInvalidateStructLayout(gallivm->target, texture_type);
140#endif
141
142   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, width,
143                          target, texture_type,
144                          DRAW_JIT_TEXTURE_WIDTH);
145   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, height,
146                          target, texture_type,
147                          DRAW_JIT_TEXTURE_HEIGHT);
148   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, depth,
149                          target, texture_type,
150                          DRAW_JIT_TEXTURE_DEPTH);
151   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, first_level,
152                          target, texture_type,
153                          DRAW_JIT_TEXTURE_FIRST_LEVEL);
154   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, last_level,
155                          target, texture_type,
156                          DRAW_JIT_TEXTURE_LAST_LEVEL);
157   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, row_stride,
158                          target, texture_type,
159                          DRAW_JIT_TEXTURE_ROW_STRIDE);
160   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, img_stride,
161                          target, texture_type,
162                          DRAW_JIT_TEXTURE_IMG_STRIDE);
163   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, data,
164                          target, texture_type,
165                          DRAW_JIT_TEXTURE_DATA);
166   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, min_lod,
167                          target, texture_type,
168                          DRAW_JIT_TEXTURE_MIN_LOD);
169   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, max_lod,
170                          target, texture_type,
171                          DRAW_JIT_TEXTURE_MAX_LOD);
172   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, lod_bias,
173                          target, texture_type,
174                          DRAW_JIT_TEXTURE_LOD_BIAS);
175   LP_CHECK_MEMBER_OFFSET(struct draw_jit_texture, border_color,
176                          target, texture_type,
177                          DRAW_JIT_TEXTURE_BORDER_COLOR);
178
179   LP_CHECK_STRUCT_SIZE(struct draw_jit_texture, target, texture_type);
180
181   return texture_type;
182}
183
184
185/**
186 * Create LLVM type for struct draw_jit_texture
187 */
188static LLVMTypeRef
189create_jit_context_type(struct gallivm_state *gallivm,
190                        LLVMTypeRef texture_type, const char *struct_name)
191{
192   LLVMTargetDataRef target = gallivm->target;
193   LLVMTypeRef float_type = LLVMFloatTypeInContext(gallivm->context);
194   LLVMTypeRef elem_types[5];
195   LLVMTypeRef context_type;
196
197   elem_types[0] = LLVMPointerType(float_type, 0); /* vs_constants */
198   elem_types[1] = LLVMPointerType(float_type, 0); /* gs_constants */
199   elem_types[2] = LLVMPointerType(LLVMArrayType(LLVMArrayType(float_type, 4),
200                                                 DRAW_TOTAL_CLIP_PLANES), 0);
201   elem_types[3] = LLVMPointerType(float_type, 0); /* viewport */
202   elem_types[4] = LLVMArrayType(texture_type,
203                                 PIPE_MAX_VERTEX_SAMPLERS); /* textures */
204#if HAVE_LLVM >= 0x0300
205   context_type = LLVMStructCreateNamed(gallivm->context, struct_name);
206   LLVMStructSetBody(context_type, elem_types,
207                     Elements(elem_types), 0);
208#else
209   context_type = LLVMStructTypeInContext(gallivm->context, elem_types,
210                                          Elements(elem_types), 0);
211   LLVMAddTypeName(gallivm->module, struct_name, context_type);
212
213   LLVMInvalidateStructLayout(gallivm->target, context_type);
214#endif
215
216   LP_CHECK_MEMBER_OFFSET(struct draw_jit_context, vs_constants,
217                          target, context_type, 0);
218   LP_CHECK_MEMBER_OFFSET(struct draw_jit_context, gs_constants,
219                          target, context_type, 1);
220   LP_CHECK_MEMBER_OFFSET(struct draw_jit_context, planes,
221                          target, context_type, 2);
222   LP_CHECK_MEMBER_OFFSET(struct draw_jit_context, textures,
223                          target, context_type,
224                          DRAW_JIT_CTX_TEXTURES);
225   LP_CHECK_STRUCT_SIZE(struct draw_jit_context,
226                        target, context_type);
227
228   return context_type;
229}
230
231
232/**
233 * Create LLVM type for struct pipe_vertex_buffer
234 */
235static LLVMTypeRef
236create_jit_vertex_buffer_type(struct gallivm_state *gallivm, const char *struct_name)
237{
238   LLVMTargetDataRef target = gallivm->target;
239   LLVMTypeRef elem_types[3];
240   LLVMTypeRef vb_type;
241
242   elem_types[0] =
243   elem_types[1] = LLVMInt32TypeInContext(gallivm->context);
244   elem_types[2] = LLVMPointerType(LLVMInt8TypeInContext(gallivm->context), 0); /* vs_constants */
245
246#if HAVE_LLVM >= 0x0300
247   vb_type = LLVMStructCreateNamed(gallivm->context, struct_name);
248   LLVMStructSetBody(vb_type, elem_types,
249                     Elements(elem_types), 0);
250#else
251   vb_type = LLVMStructTypeInContext(gallivm->context, elem_types,
252                                     Elements(elem_types), 0);
253   LLVMAddTypeName(gallivm->module, struct_name, vb_type);
254
255   LLVMInvalidateStructLayout(gallivm->target, vb_type);
256#endif
257
258   LP_CHECK_MEMBER_OFFSET(struct pipe_vertex_buffer, stride,
259                          target, vb_type, 0);
260   LP_CHECK_MEMBER_OFFSET(struct pipe_vertex_buffer, buffer_offset,
261                          target, vb_type, 1);
262
263   LP_CHECK_STRUCT_SIZE(struct pipe_vertex_buffer, target, vb_type);
264
265   return vb_type;
266}
267
268
269/**
270 * Create LLVM type for struct vertex_header;
271 */
272static LLVMTypeRef
273create_jit_vertex_header(struct gallivm_state *gallivm, int data_elems)
274{
275   LLVMTargetDataRef target = gallivm->target;
276   LLVMTypeRef elem_types[4];
277   LLVMTypeRef vertex_header;
278   char struct_name[24];
279
280   util_snprintf(struct_name, 23, "vertex_header%d", data_elems);
281
282   elem_types[DRAW_JIT_VERTEX_VERTEX_ID]  = LLVMIntTypeInContext(gallivm->context, 32);
283   elem_types[DRAW_JIT_VERTEX_CLIP]  = LLVMArrayType(LLVMFloatTypeInContext(gallivm->context), 4);
284   elem_types[DRAW_JIT_VERTEX_PRE_CLIP_POS]  = LLVMArrayType(LLVMFloatTypeInContext(gallivm->context), 4);
285   elem_types[DRAW_JIT_VERTEX_DATA]  = LLVMArrayType(elem_types[1], data_elems);
286
287#if HAVE_LLVM >= 0x0300
288   vertex_header = LLVMStructCreateNamed(gallivm->context, struct_name);
289   LLVMStructSetBody(vertex_header, elem_types,
290                     Elements(elem_types), 0);
291#else
292   vertex_header = LLVMStructTypeInContext(gallivm->context, elem_types,
293                                           Elements(elem_types), 0);
294   LLVMAddTypeName(gallivm->module, struct_name, vertex_header);
295
296   LLVMInvalidateStructLayout(gallivm->target, vertex_header);
297#endif
298
299   /* these are bit-fields and we can't take address of them
300      LP_CHECK_MEMBER_OFFSET(struct vertex_header, clipmask,
301      target, vertex_header,
302      DRAW_JIT_VERTEX_CLIPMASK);
303      LP_CHECK_MEMBER_OFFSET(struct vertex_header, edgeflag,
304      target, vertex_header,
305      DRAW_JIT_VERTEX_EDGEFLAG);
306      LP_CHECK_MEMBER_OFFSET(struct vertex_header, pad,
307      target, vertex_header,
308      DRAW_JIT_VERTEX_PAD);
309      LP_CHECK_MEMBER_OFFSET(struct vertex_header, vertex_id,
310      target, vertex_header,
311      DRAW_JIT_VERTEX_VERTEX_ID);
312   */
313   LP_CHECK_MEMBER_OFFSET(struct vertex_header, clip,
314                          target, vertex_header,
315                          DRAW_JIT_VERTEX_CLIP);
316   LP_CHECK_MEMBER_OFFSET(struct vertex_header, pre_clip_pos,
317                          target, vertex_header,
318                          DRAW_JIT_VERTEX_PRE_CLIP_POS);
319   LP_CHECK_MEMBER_OFFSET(struct vertex_header, data,
320                          target, vertex_header,
321                          DRAW_JIT_VERTEX_DATA);
322
323   return vertex_header;
324}
325
326
327/**
328 * Create LLVM types for various structures.
329 */
330static void
331create_jit_types(struct draw_llvm *llvm)
332{
333   struct gallivm_state *gallivm = llvm->gallivm;
334   LLVMTypeRef texture_type, context_type, buffer_type, vb_type;
335
336   texture_type = create_jit_texture_type(gallivm, "texture");
337
338   context_type = create_jit_context_type(gallivm, texture_type, "draw_jit_context");
339   llvm->context_ptr_type = LLVMPointerType(context_type, 0);
340
341   buffer_type = LLVMPointerType(LLVMIntTypeInContext(gallivm->context, 8), 0);
342   llvm->buffer_ptr_type = LLVMPointerType(buffer_type, 0);
343
344   vb_type = create_jit_vertex_buffer_type(gallivm, "pipe_vertex_buffer");
345   llvm->vb_ptr_type = LLVMPointerType(vb_type, 0);
346}
347
348
349static LLVMTypeRef
350get_context_ptr_type(struct draw_llvm *llvm)
351{
352   if (!llvm->context_ptr_type)
353      create_jit_types(llvm);
354   return llvm->context_ptr_type;
355}
356
357
358static LLVMTypeRef
359get_buffer_ptr_type(struct draw_llvm *llvm)
360{
361   if (!llvm->buffer_ptr_type)
362      create_jit_types(llvm);
363   return llvm->buffer_ptr_type;
364}
365
366
367static LLVMTypeRef
368get_vb_ptr_type(struct draw_llvm *llvm)
369{
370   if (!llvm->vb_ptr_type)
371      create_jit_types(llvm);
372   return llvm->vb_ptr_type;
373}
374
375static LLVMTypeRef
376get_vertex_header_ptr_type(struct draw_llvm *llvm)
377{
378   if (!llvm->vertex_header_ptr_type)
379      create_jit_types(llvm);
380   return llvm->vertex_header_ptr_type;
381}
382
383
384/**
385 * Create per-context LLVM info.
386 */
387struct draw_llvm *
388draw_llvm_create(struct draw_context *draw, struct gallivm_state *gallivm)
389{
390   struct draw_llvm *llvm;
391
392   llvm = CALLOC_STRUCT( draw_llvm );
393   if (!llvm)
394      return NULL;
395
396   lp_build_init();
397
398   llvm->draw = draw;
399   llvm->gallivm = gallivm;
400
401   if (gallivm_debug & GALLIVM_DEBUG_IR) {
402      LLVMDumpModule(llvm->gallivm->module);
403   }
404
405   llvm->nr_variants = 0;
406   make_empty_list(&llvm->vs_variants_list);
407
408   gallivm_register_garbage_collector_callback(
409                              draw_llvm_garbage_collect_callback, llvm);
410
411   return llvm;
412}
413
414
415/**
416 * Free per-context LLVM info.
417 */
418void
419draw_llvm_destroy(struct draw_llvm *llvm)
420{
421   gallivm_remove_garbage_collector_callback(
422                              draw_llvm_garbage_collect_callback, llvm);
423
424   /* XXX free other draw_llvm data? */
425   FREE(llvm);
426}
427
428
429/**
430 * Create LLVM-generated code for a vertex shader.
431 */
432struct draw_llvm_variant *
433draw_llvm_create_variant(struct draw_llvm *llvm,
434			 unsigned num_inputs,
435			 const struct draw_llvm_variant_key *key)
436{
437   struct draw_llvm_variant *variant;
438   struct llvm_vertex_shader *shader =
439      llvm_vertex_shader(llvm->draw->vs.vertex_shader);
440   LLVMTypeRef vertex_header;
441
442   variant = MALLOC(sizeof *variant +
443		    shader->variant_key_size -
444		    sizeof variant->key);
445   if (variant == NULL)
446      return NULL;
447
448   variant->llvm = llvm;
449
450   memcpy(&variant->key, key, shader->variant_key_size);
451
452   vertex_header = create_jit_vertex_header(llvm->gallivm, num_inputs);
453
454   llvm->vertex_header_ptr_type = LLVMPointerType(vertex_header, 0);
455
456   draw_llvm_generate(llvm, variant, FALSE);  /* linear */
457   draw_llvm_generate(llvm, variant, TRUE);   /* elts */
458
459   variant->shader = shader;
460   variant->list_item_global.base = variant;
461   variant->list_item_local.base = variant;
462   /*variant->no = */shader->variants_created++;
463   variant->list_item_global.base = variant;
464
465   return variant;
466}
467
468
469static void
470generate_vs(struct draw_llvm *llvm,
471            LLVMBuilderRef builder,
472            LLVMValueRef (*outputs)[TGSI_NUM_CHANNELS],
473            const LLVMValueRef (*inputs)[TGSI_NUM_CHANNELS],
474            LLVMValueRef system_values_array,
475            LLVMValueRef context_ptr,
476            struct lp_build_sampler_soa *draw_sampler,
477            boolean clamp_vertex_color)
478{
479   const struct tgsi_token *tokens = llvm->draw->vs.vertex_shader->state.tokens;
480   struct lp_type vs_type;
481   LLVMValueRef consts_ptr = draw_jit_context_vs_constants(llvm->gallivm, context_ptr);
482   struct lp_build_sampler_soa *sampler = 0;
483
484   memset(&vs_type, 0, sizeof vs_type);
485   vs_type.floating = TRUE; /* floating point values */
486   vs_type.sign = TRUE;     /* values are signed */
487   vs_type.norm = FALSE;    /* values are not limited to [0,1] or [-1,1] */
488   vs_type.width = 32;      /* 32-bit float */
489   vs_type.length = 4;      /* 4 elements per vector */
490#if 0
491   num_vs = 4;              /* number of vertices per block */
492#endif
493
494   if (gallivm_debug & GALLIVM_DEBUG_IR) {
495      tgsi_dump(tokens, 0);
496   }
497
498   if (llvm->draw->num_sampler_views && llvm->draw->num_samplers)
499      sampler = draw_sampler;
500
501   lp_build_tgsi_soa(llvm->gallivm,
502                     tokens,
503                     vs_type,
504                     NULL /*struct lp_build_mask_context *mask*/,
505                     consts_ptr,
506                     system_values_array,
507                     NULL /*pos*/,
508                     inputs,
509                     outputs,
510                     sampler,
511                     &llvm->draw->vs.vertex_shader->info);
512
513   if (clamp_vertex_color) {
514      LLVMValueRef out;
515      unsigned chan, attrib;
516      struct lp_build_context bld;
517      struct tgsi_shader_info* info = &llvm->draw->vs.vertex_shader->info;
518      lp_build_context_init(&bld, llvm->gallivm, vs_type);
519
520      for (attrib = 0; attrib < info->num_outputs; ++attrib) {
521         for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
522            if (outputs[attrib][chan]) {
523               switch (info->output_semantic_name[attrib]) {
524               case TGSI_SEMANTIC_COLOR:
525               case TGSI_SEMANTIC_BCOLOR:
526                  out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
527                  out = lp_build_clamp(&bld, out, bld.zero, bld.one);
528                  LLVMBuildStore(builder, out, outputs[attrib][chan]);
529                  break;
530               }
531            }
532         }
533      }
534   }
535}
536
537
538#if DEBUG_STORE
539static void print_vectorf(LLVMBuilderRef builder,
540                         LLVMValueRef vec)
541{
542   LLVMValueRef val[4];
543   val[0] = LLVMBuildExtractElement(builder, vec,
544                                    lp_build_const_int32(gallivm, 0), "");
545   val[1] = LLVMBuildExtractElement(builder, vec,
546                                    lp_build_const_int32(gallivm, 1), "");
547   val[2] = LLVMBuildExtractElement(builder, vec,
548                                    lp_build_const_int32(gallivm, 2), "");
549   val[3] = LLVMBuildExtractElement(builder, vec,
550                                    lp_build_const_int32(gallivm, 3), "");
551   lp_build_printf(builder, "vector = [%f, %f, %f, %f]\n",
552                   val[0], val[1], val[2], val[3]);
553}
554#endif
555
556
557static void
558generate_fetch(struct gallivm_state *gallivm,
559               LLVMValueRef vbuffers_ptr,
560               LLVMValueRef *res,
561               struct pipe_vertex_element *velem,
562               LLVMValueRef vbuf,
563               LLVMValueRef index,
564               LLVMValueRef instance_id)
565{
566   LLVMBuilderRef builder = gallivm->builder;
567   LLVMValueRef indices =
568      LLVMConstInt(LLVMInt64TypeInContext(gallivm->context),
569                   velem->vertex_buffer_index, 0);
570   LLVMValueRef vbuffer_ptr = LLVMBuildGEP(builder, vbuffers_ptr,
571                                           &indices, 1, "");
572   LLVMValueRef vb_stride = draw_jit_vbuffer_stride(gallivm, vbuf);
573   LLVMValueRef vb_buffer_offset = draw_jit_vbuffer_offset(gallivm, vbuf);
574   LLVMValueRef stride;
575
576   if (velem->instance_divisor) {
577      /* array index = instance_id / instance_divisor */
578      index = LLVMBuildUDiv(builder, instance_id,
579                            lp_build_const_int32(gallivm, velem->instance_divisor),
580                            "instance_divisor");
581   }
582
583   stride = LLVMBuildMul(builder, vb_stride, index, "");
584
585   vbuffer_ptr = LLVMBuildLoad(builder, vbuffer_ptr, "vbuffer");
586
587   stride = LLVMBuildAdd(builder, stride,
588                         vb_buffer_offset,
589                         "");
590   stride = LLVMBuildAdd(builder, stride,
591                         lp_build_const_int32(gallivm, velem->src_offset),
592                         "");
593
594   /*lp_build_printf(builder, "vbuf index = %d, stride is %d\n", indices, stride);*/
595   vbuffer_ptr = LLVMBuildGEP(builder, vbuffer_ptr, &stride, 1, "");
596
597   *res = draw_llvm_translate_from(gallivm, vbuffer_ptr, velem->src_format);
598}
599
600
601static LLVMValueRef
602aos_to_soa(struct gallivm_state *gallivm,
603           LLVMValueRef val0,
604           LLVMValueRef val1,
605           LLVMValueRef val2,
606           LLVMValueRef val3,
607           LLVMValueRef channel)
608{
609   LLVMBuilderRef builder = gallivm->builder;
610   LLVMValueRef ex, res;
611
612   ex = LLVMBuildExtractElement(builder, val0,
613                                channel, "");
614   res = LLVMBuildInsertElement(builder,
615                                LLVMConstNull(LLVMTypeOf(val0)),
616                                ex,
617                                lp_build_const_int32(gallivm, 0),
618                                "");
619
620   ex = LLVMBuildExtractElement(builder, val1,
621                                channel, "");
622   res = LLVMBuildInsertElement(builder,
623                                res, ex,
624                                lp_build_const_int32(gallivm, 1),
625                                "");
626
627   ex = LLVMBuildExtractElement(builder, val2,
628                                channel, "");
629   res = LLVMBuildInsertElement(builder,
630                                res, ex,
631                                lp_build_const_int32(gallivm, 2),
632                                "");
633
634   ex = LLVMBuildExtractElement(builder, val3,
635                                channel, "");
636   res = LLVMBuildInsertElement(builder,
637                                res, ex,
638                                lp_build_const_int32(gallivm, 3),
639                                "");
640
641   return res;
642}
643
644
645static void
646soa_to_aos(struct gallivm_state *gallivm,
647           LLVMValueRef soa[TGSI_NUM_CHANNELS],
648           LLVMValueRef aos[TGSI_NUM_CHANNELS])
649{
650   LLVMBuilderRef builder = gallivm->builder;
651   LLVMValueRef comp;
652   int i = 0;
653
654   debug_assert(TGSI_NUM_CHANNELS == 4);
655
656   aos[0] = LLVMConstNull(LLVMTypeOf(soa[0]));
657   aos[1] = aos[2] = aos[3] = aos[0];
658
659   for (i = 0; i < TGSI_NUM_CHANNELS; ++i) {
660      LLVMValueRef channel = lp_build_const_int32(gallivm, i);
661
662      comp = LLVMBuildExtractElement(builder, soa[i],
663                                     lp_build_const_int32(gallivm, 0), "");
664      aos[0] = LLVMBuildInsertElement(builder, aos[0], comp, channel, "");
665
666      comp = LLVMBuildExtractElement(builder, soa[i],
667                                     lp_build_const_int32(gallivm, 1), "");
668      aos[1] = LLVMBuildInsertElement(builder, aos[1], comp, channel, "");
669
670      comp = LLVMBuildExtractElement(builder, soa[i],
671                                     lp_build_const_int32(gallivm, 2), "");
672      aos[2] = LLVMBuildInsertElement(builder, aos[2], comp, channel, "");
673
674      comp = LLVMBuildExtractElement(builder, soa[i],
675                                     lp_build_const_int32(gallivm, 3), "");
676      aos[3] = LLVMBuildInsertElement(builder, aos[3], comp, channel, "");
677
678   }
679}
680
681
682static void
683convert_to_soa(struct gallivm_state *gallivm,
684               LLVMValueRef (*aos)[TGSI_NUM_CHANNELS],
685               LLVMValueRef (*soa)[TGSI_NUM_CHANNELS],
686               int num_attribs)
687{
688   int i;
689
690   debug_assert(TGSI_NUM_CHANNELS == 4);
691
692   for (i = 0; i < num_attribs; ++i) {
693      LLVMValueRef val0 = aos[i][0];
694      LLVMValueRef val1 = aos[i][1];
695      LLVMValueRef val2 = aos[i][2];
696      LLVMValueRef val3 = aos[i][3];
697
698      soa[i][0] = aos_to_soa(gallivm, val0, val1, val2, val3,
699                             lp_build_const_int32(gallivm, 0));
700      soa[i][1] = aos_to_soa(gallivm, val0, val1, val2, val3,
701                             lp_build_const_int32(gallivm, 1));
702      soa[i][2] = aos_to_soa(gallivm, val0, val1, val2, val3,
703                             lp_build_const_int32(gallivm, 2));
704      soa[i][3] = aos_to_soa(gallivm, val0, val1, val2, val3,
705                             lp_build_const_int32(gallivm, 3));
706   }
707}
708
709
710static void
711store_aos(struct gallivm_state *gallivm,
712          LLVMValueRef io_ptr,
713          LLVMValueRef index,
714          LLVMValueRef value,
715          LLVMValueRef clipmask)
716{
717   LLVMBuilderRef builder = gallivm->builder;
718   LLVMValueRef id_ptr = draw_jit_header_id(gallivm, io_ptr);
719   LLVMValueRef data_ptr = draw_jit_header_data(gallivm, io_ptr);
720   LLVMValueRef indices[3];
721   LLVMValueRef val;
722   int vertex_id_pad_edgeflag;
723
724   indices[0] = lp_build_const_int32(gallivm, 0);
725   indices[1] = index;
726   indices[2] = lp_build_const_int32(gallivm, 0);
727
728   /* If this assertion fails, it means we need to update the bit twidding
729    * code here.  See struct vertex_header in draw_private.h.
730    */
731   assert(DRAW_TOTAL_CLIP_PLANES==14);
732   /* initialize vertex id:16 = 0xffff, pad:1 = 0, edgeflag:1 = 1 */
733   vertex_id_pad_edgeflag = (0xffff << 16) | (1 << DRAW_TOTAL_CLIP_PLANES);
734   val = lp_build_const_int32(gallivm, vertex_id_pad_edgeflag);
735   /* OR with the clipmask */
736   val = LLVMBuildOr(builder, val, clipmask, "");
737
738   /* store vertex header */
739   LLVMBuildStore(builder, val, id_ptr);
740
741
742#if DEBUG_STORE
743   lp_build_printf(builder, "    ---- %p storing attribute %d (io = %p)\n", data_ptr, index, io_ptr);
744#endif
745#if 0
746   /*lp_build_printf(builder, " ---- %p storing at %d (%p)  ", io_ptr, index, data_ptr);
747     print_vectorf(builder, value);*/
748   data_ptr = LLVMBuildBitCast(builder, data_ptr,
749                               LLVMPointerType(LLVMArrayType(LLVMVectorType(LLVMFloatTypeInContext(gallivm->context), 4), 0), 0),
750                               "datavec");
751   data_ptr = LLVMBuildGEP(builder, data_ptr, indices, 2, "");
752
753   LLVMBuildStore(builder, value, data_ptr);
754#else
755   {
756      LLVMValueRef x, y, z, w;
757      LLVMValueRef idx0, idx1, idx2, idx3;
758      LLVMValueRef gep0, gep1, gep2, gep3;
759      data_ptr = LLVMBuildGEP(builder, data_ptr, indices, 3, "");
760
761      idx0 = lp_build_const_int32(gallivm, 0);
762      idx1 = lp_build_const_int32(gallivm, 1);
763      idx2 = lp_build_const_int32(gallivm, 2);
764      idx3 = lp_build_const_int32(gallivm, 3);
765
766      x = LLVMBuildExtractElement(builder, value,
767                                  idx0, "");
768      y = LLVMBuildExtractElement(builder, value,
769                                  idx1, "");
770      z = LLVMBuildExtractElement(builder, value,
771                                  idx2, "");
772      w = LLVMBuildExtractElement(builder, value,
773                                  idx3, "");
774
775      gep0 = LLVMBuildGEP(builder, data_ptr, &idx0, 1, "");
776      gep1 = LLVMBuildGEP(builder, data_ptr, &idx1, 1, "");
777      gep2 = LLVMBuildGEP(builder, data_ptr, &idx2, 1, "");
778      gep3 = LLVMBuildGEP(builder, data_ptr, &idx3, 1, "");
779
780      /*lp_build_printf(builder, "##### x = %f (%p), y = %f (%p), z = %f (%p), w = %f (%p)\n",
781        x, gep0, y, gep1, z, gep2, w, gep3);*/
782      LLVMBuildStore(builder, x, gep0);
783      LLVMBuildStore(builder, y, gep1);
784      LLVMBuildStore(builder, z, gep2);
785      LLVMBuildStore(builder, w, gep3);
786   }
787#endif
788}
789
790
791static void
792store_aos_array(struct gallivm_state *gallivm,
793                LLVMValueRef io_ptr,
794                LLVMValueRef aos[TGSI_NUM_CHANNELS],
795                int attrib,
796                int num_outputs,
797                LLVMValueRef clipmask)
798{
799   LLVMBuilderRef builder = gallivm->builder;
800   LLVMValueRef attr_index = lp_build_const_int32(gallivm, attrib);
801   LLVMValueRef ind0 = lp_build_const_int32(gallivm, 0);
802   LLVMValueRef ind1 = lp_build_const_int32(gallivm, 1);
803   LLVMValueRef ind2 = lp_build_const_int32(gallivm, 2);
804   LLVMValueRef ind3 = lp_build_const_int32(gallivm, 3);
805   LLVMValueRef io0_ptr, io1_ptr, io2_ptr, io3_ptr;
806   LLVMValueRef clipmask0, clipmask1, clipmask2, clipmask3;
807
808   debug_assert(TGSI_NUM_CHANNELS == 4);
809
810   io0_ptr = LLVMBuildGEP(builder, io_ptr,
811                          &ind0, 1, "");
812   io1_ptr = LLVMBuildGEP(builder, io_ptr,
813                          &ind1, 1, "");
814   io2_ptr = LLVMBuildGEP(builder, io_ptr,
815                          &ind2, 1, "");
816   io3_ptr = LLVMBuildGEP(builder, io_ptr,
817                          &ind3, 1, "");
818
819   clipmask0 = LLVMBuildExtractElement(builder, clipmask,
820                                       ind0, "");
821   clipmask1 = LLVMBuildExtractElement(builder, clipmask,
822                                       ind1, "");
823   clipmask2 = LLVMBuildExtractElement(builder, clipmask,
824                                       ind2, "");
825   clipmask3 = LLVMBuildExtractElement(builder, clipmask,
826                                       ind3, "");
827
828#if DEBUG_STORE
829   lp_build_printf(builder, "io = %p, indexes[%d, %d, %d, %d]\n, clipmask0 = %x, clipmask1 = %x, clipmask2 = %x, clipmask3 = %x\n",
830                   io_ptr, ind0, ind1, ind2, ind3, clipmask0, clipmask1, clipmask2, clipmask3);
831#endif
832   /* store for each of the 4 vertices */
833   store_aos(gallivm, io0_ptr, attr_index, aos[0], clipmask0);
834   store_aos(gallivm, io1_ptr, attr_index, aos[1], clipmask1);
835   store_aos(gallivm, io2_ptr, attr_index, aos[2], clipmask2);
836   store_aos(gallivm, io3_ptr, attr_index, aos[3], clipmask3);
837}
838
839
840static void
841convert_to_aos(struct gallivm_state *gallivm,
842               LLVMValueRef io,
843               LLVMValueRef (*outputs)[TGSI_NUM_CHANNELS],
844               LLVMValueRef clipmask,
845               int num_outputs,
846               int max_vertices)
847{
848   LLVMBuilderRef builder = gallivm->builder;
849   unsigned chan, attrib;
850
851#if DEBUG_STORE
852   lp_build_printf(builder, "   # storing begin\n");
853#endif
854   for (attrib = 0; attrib < num_outputs; ++attrib) {
855      LLVMValueRef soa[4];
856      LLVMValueRef aos[4];
857      for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan) {
858         if (outputs[attrib][chan]) {
859            LLVMValueRef out = LLVMBuildLoad(builder, outputs[attrib][chan], "");
860            lp_build_name(out, "output%u.%c", attrib, "xyzw"[chan]);
861            /*lp_build_printf(builder, "output %d : %d ",
862                            LLVMConstInt(LLVMInt32Type(), attrib, 0),
863                            LLVMConstInt(LLVMInt32Type(), chan, 0));
864              print_vectorf(builder, out);*/
865            soa[chan] = out;
866         }
867         else {
868            soa[chan] = 0;
869         }
870      }
871      soa_to_aos(gallivm, soa, aos);
872      store_aos_array(gallivm,
873                      io,
874                      aos,
875                      attrib,
876                      num_outputs,
877                      clipmask);
878   }
879#if DEBUG_STORE
880   lp_build_printf(builder, "   # storing end\n");
881#endif
882}
883
884
885/**
886 * Stores original vertex positions in clip coordinates
887 * There is probably a more efficient way to do this, 4 floats at once
888 * rather than extracting each element one by one.
889 */
890static void
891store_clip(struct gallivm_state *gallivm,
892           LLVMValueRef io_ptr,
893           LLVMValueRef (*outputs)[TGSI_NUM_CHANNELS],
894           boolean pre_clip_pos)
895{
896   LLVMBuilderRef builder = gallivm->builder;
897   LLVMValueRef out[4];
898   LLVMValueRef indices[2];
899   LLVMValueRef io0_ptr, io1_ptr, io2_ptr, io3_ptr;
900   LLVMValueRef clip_ptr0, clip_ptr1, clip_ptr2, clip_ptr3;
901   LLVMValueRef clip0_ptr, clip1_ptr, clip2_ptr, clip3_ptr;
902   LLVMValueRef out0elem, out1elem, out2elem, out3elem;
903   int i;
904
905   LLVMValueRef ind0 = lp_build_const_int32(gallivm, 0);
906   LLVMValueRef ind1 = lp_build_const_int32(gallivm, 1);
907   LLVMValueRef ind2 = lp_build_const_int32(gallivm, 2);
908   LLVMValueRef ind3 = lp_build_const_int32(gallivm, 3);
909
910   indices[0] =
911   indices[1] = lp_build_const_int32(gallivm, 0);
912
913   out[0] = LLVMBuildLoad(builder, outputs[0][0], ""); /*x0 x1 x2 x3*/
914   out[1] = LLVMBuildLoad(builder, outputs[0][1], ""); /*y0 y1 y2 y3*/
915   out[2] = LLVMBuildLoad(builder, outputs[0][2], ""); /*z0 z1 z2 z3*/
916   out[3] = LLVMBuildLoad(builder, outputs[0][3], ""); /*w0 w1 w2 w3*/
917
918   io0_ptr = LLVMBuildGEP(builder, io_ptr, &ind0, 1, "");
919   io1_ptr = LLVMBuildGEP(builder, io_ptr, &ind1, 1, "");
920   io2_ptr = LLVMBuildGEP(builder, io_ptr, &ind2, 1, "");
921   io3_ptr = LLVMBuildGEP(builder, io_ptr, &ind3, 1, "");
922
923   /* FIXME: this needs updating for clip vertex support */
924   if (!pre_clip_pos) {
925      clip_ptr0 = draw_jit_header_clip(gallivm, io0_ptr);
926      clip_ptr1 = draw_jit_header_clip(gallivm, io1_ptr);
927      clip_ptr2 = draw_jit_header_clip(gallivm, io2_ptr);
928      clip_ptr3 = draw_jit_header_clip(gallivm, io3_ptr);
929   } else {
930      clip_ptr0 = draw_jit_header_pre_clip_pos(gallivm, io0_ptr);
931      clip_ptr1 = draw_jit_header_pre_clip_pos(gallivm, io1_ptr);
932      clip_ptr2 = draw_jit_header_pre_clip_pos(gallivm, io2_ptr);
933      clip_ptr3 = draw_jit_header_pre_clip_pos(gallivm, io3_ptr);
934   }
935
936   for (i = 0; i<4; i++) {
937      clip0_ptr = LLVMBuildGEP(builder, clip_ptr0, indices, 2, ""); /* x0 */
938      clip1_ptr = LLVMBuildGEP(builder, clip_ptr1, indices, 2, ""); /* x1 */
939      clip2_ptr = LLVMBuildGEP(builder, clip_ptr2, indices, 2, ""); /* x2 */
940      clip3_ptr = LLVMBuildGEP(builder, clip_ptr3, indices, 2, ""); /* x3 */
941
942      out0elem = LLVMBuildExtractElement(builder, out[i], ind0, ""); /* x0 */
943      out1elem = LLVMBuildExtractElement(builder, out[i], ind1, ""); /* x1 */
944      out2elem = LLVMBuildExtractElement(builder, out[i], ind2, ""); /* x2 */
945      out3elem = LLVMBuildExtractElement(builder, out[i], ind3, ""); /* x3 */
946
947      LLVMBuildStore(builder, out0elem, clip0_ptr);
948      LLVMBuildStore(builder, out1elem, clip1_ptr);
949      LLVMBuildStore(builder, out2elem, clip2_ptr);
950      LLVMBuildStore(builder, out3elem, clip3_ptr);
951
952      indices[1]= LLVMBuildAdd(builder, indices[1], ind1, "");
953   }
954
955}
956
957
958/**
959 * Equivalent of _mm_set1_ps(a)
960 */
961static LLVMValueRef
962vec4f_from_scalar(struct gallivm_state *gallivm,
963                  LLVMValueRef a,
964                  const char *name)
965{
966   LLVMTypeRef float_type = LLVMFloatTypeInContext(gallivm->context);
967   LLVMValueRef res = LLVMGetUndef(LLVMVectorType(float_type, 4));
968   int i;
969
970   for (i = 0; i < 4; ++i) {
971      LLVMValueRef index = lp_build_const_int32(gallivm, i);
972      res = LLVMBuildInsertElement(gallivm->builder, res, a,
973                                   index, i == 3 ? name : "");
974   }
975
976   return res;
977}
978
979
980/**
981 * Transforms the outputs for viewport mapping
982 */
983static void
984generate_viewport(struct draw_llvm *llvm,
985                  LLVMBuilderRef builder,
986                  LLVMValueRef (*outputs)[TGSI_NUM_CHANNELS],
987                  LLVMValueRef context_ptr)
988{
989   int i;
990   struct gallivm_state *gallivm = llvm->gallivm;
991   struct lp_type f32_type = lp_type_float_vec(32);
992   LLVMValueRef out3 = LLVMBuildLoad(builder, outputs[0][3], ""); /*w0 w1 w2 w3*/
993   LLVMValueRef const1 = lp_build_const_vec(gallivm, f32_type, 1.0);       /*1.0 1.0 1.0 1.0*/
994   LLVMValueRef vp_ptr = draw_jit_context_viewport(gallivm, context_ptr);
995
996   /* for 1/w convention*/
997   out3 = LLVMBuildFDiv(builder, const1, out3, "");
998   LLVMBuildStore(builder, out3, outputs[0][3]);
999
1000   /* Viewport Mapping */
1001   for (i=0; i<3; i++) {
1002      LLVMValueRef out = LLVMBuildLoad(builder, outputs[0][i], ""); /*x0 x1 x2 x3*/
1003      LLVMValueRef scale;
1004      LLVMValueRef trans;
1005      LLVMValueRef scale_i;
1006      LLVMValueRef trans_i;
1007      LLVMValueRef index;
1008
1009      index = lp_build_const_int32(gallivm, i);
1010      scale_i = LLVMBuildGEP(builder, vp_ptr, &index, 1, "");
1011
1012      index = lp_build_const_int32(gallivm, i+4);
1013      trans_i = LLVMBuildGEP(builder, vp_ptr, &index, 1, "");
1014
1015      scale = vec4f_from_scalar(gallivm, LLVMBuildLoad(builder, scale_i, ""), "scale");
1016      trans = vec4f_from_scalar(gallivm, LLVMBuildLoad(builder, trans_i, ""), "trans");
1017
1018      /* divide by w */
1019      out = LLVMBuildFMul(builder, out, out3, "");
1020      /* mult by scale */
1021      out = LLVMBuildFMul(builder, out, scale, "");
1022      /* add translation */
1023      out = LLVMBuildFAdd(builder, out, trans, "");
1024
1025      /* store transformed outputs */
1026      LLVMBuildStore(builder, out, outputs[0][i]);
1027   }
1028
1029}
1030
1031
1032/**
1033 * Returns clipmask as 4xi32 bitmask for the 4 vertices
1034 */
1035static LLVMValueRef
1036generate_clipmask(struct gallivm_state *gallivm,
1037                  LLVMValueRef (*outputs)[TGSI_NUM_CHANNELS],
1038                  boolean clip_xy,
1039                  boolean clip_z,
1040                  boolean clip_user,
1041                  boolean clip_halfz,
1042                  unsigned ucp_enable,
1043                  LLVMValueRef context_ptr)
1044{
1045   LLVMBuilderRef builder = gallivm->builder;
1046   LLVMValueRef mask; /* stores the <4xi32> clipmasks */
1047   LLVMValueRef test, temp;
1048   LLVMValueRef zero, shift;
1049   LLVMValueRef pos_x, pos_y, pos_z, pos_w;
1050   LLVMValueRef plane1, planes, plane_ptr, sum;
1051   struct lp_type f32_type = lp_type_float_vec(32);
1052
1053   mask = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 0);
1054   temp = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 0);
1055   zero = lp_build_const_vec(gallivm, f32_type, 0);                    /* 0.0f 0.0f 0.0f 0.0f */
1056   shift = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 1);    /* 1 1 1 1 */
1057
1058   /* Assuming position stored at output[0] */
1059   pos_x = LLVMBuildLoad(builder, outputs[0][0], ""); /*x0 x1 x2 x3*/
1060   pos_y = LLVMBuildLoad(builder, outputs[0][1], ""); /*y0 y1 y2 y3*/
1061   pos_z = LLVMBuildLoad(builder, outputs[0][2], ""); /*z0 z1 z2 z3*/
1062   pos_w = LLVMBuildLoad(builder, outputs[0][3], ""); /*w0 w1 w2 w3*/
1063
1064   /* Cliptest, for hardwired planes */
1065   if (clip_xy) {
1066      /* plane 1 */
1067      test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, pos_x , pos_w);
1068      temp = shift;
1069      test = LLVMBuildAnd(builder, test, temp, "");
1070      mask = test;
1071
1072      /* plane 2 */
1073      test = LLVMBuildFAdd(builder, pos_x, pos_w, "");
1074      test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, zero, test);
1075      temp = LLVMBuildShl(builder, temp, shift, "");
1076      test = LLVMBuildAnd(builder, test, temp, "");
1077      mask = LLVMBuildOr(builder, mask, test, "");
1078
1079      /* plane 3 */
1080      test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, pos_y, pos_w);
1081      temp = LLVMBuildShl(builder, temp, shift, "");
1082      test = LLVMBuildAnd(builder, test, temp, "");
1083      mask = LLVMBuildOr(builder, mask, test, "");
1084
1085      /* plane 4 */
1086      test = LLVMBuildFAdd(builder, pos_y, pos_w, "");
1087      test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, zero, test);
1088      temp = LLVMBuildShl(builder, temp, shift, "");
1089      test = LLVMBuildAnd(builder, test, temp, "");
1090      mask = LLVMBuildOr(builder, mask, test, "");
1091   }
1092
1093   if (clip_z) {
1094      temp = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 16);
1095      if (clip_halfz) {
1096         /* plane 5 */
1097         test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, zero, pos_z);
1098         test = LLVMBuildAnd(builder, test, temp, "");
1099         mask = LLVMBuildOr(builder, mask, test, "");
1100      }
1101      else {
1102         /* plane 5 */
1103         test = LLVMBuildFAdd(builder, pos_z, pos_w, "");
1104         test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, zero, test);
1105         test = LLVMBuildAnd(builder, test, temp, "");
1106         mask = LLVMBuildOr(builder, mask, test, "");
1107      }
1108      /* plane 6 */
1109      test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, pos_z, pos_w);
1110      temp = LLVMBuildShl(builder, temp, shift, "");
1111      test = LLVMBuildAnd(builder, test, temp, "");
1112      mask = LLVMBuildOr(builder, mask, test, "");
1113   }
1114
1115   if (clip_user) {
1116      LLVMValueRef planes_ptr = draw_jit_context_planes(gallivm, context_ptr);
1117      LLVMValueRef indices[3];
1118
1119      /* userclip planes */
1120      while (ucp_enable) {
1121         unsigned plane_idx = ffs(ucp_enable)-1;
1122         ucp_enable &= ~(1 << plane_idx);
1123         plane_idx += 6;
1124
1125         indices[0] = lp_build_const_int32(gallivm, 0);
1126         indices[1] = lp_build_const_int32(gallivm, plane_idx);
1127
1128         indices[2] = lp_build_const_int32(gallivm, 0);
1129         plane_ptr = LLVMBuildGEP(builder, planes_ptr, indices, 3, "");
1130         plane1 = LLVMBuildLoad(builder, plane_ptr, "plane_x");
1131         planes = vec4f_from_scalar(gallivm, plane1, "plane4_x");
1132         sum = LLVMBuildFMul(builder, planes, pos_x, "");
1133
1134         indices[2] = lp_build_const_int32(gallivm, 1);
1135         plane_ptr = LLVMBuildGEP(builder, planes_ptr, indices, 3, "");
1136         plane1 = LLVMBuildLoad(builder, plane_ptr, "plane_y");
1137         planes = vec4f_from_scalar(gallivm, plane1, "plane4_y");
1138         test = LLVMBuildFMul(builder, planes, pos_y, "");
1139         sum = LLVMBuildFAdd(builder, sum, test, "");
1140
1141         indices[2] = lp_build_const_int32(gallivm, 2);
1142         plane_ptr = LLVMBuildGEP(builder, planes_ptr, indices, 3, "");
1143         plane1 = LLVMBuildLoad(builder, plane_ptr, "plane_z");
1144         planes = vec4f_from_scalar(gallivm, plane1, "plane4_z");
1145         test = LLVMBuildFMul(builder, planes, pos_z, "");
1146         sum = LLVMBuildFAdd(builder, sum, test, "");
1147
1148         indices[2] = lp_build_const_int32(gallivm, 3);
1149         plane_ptr = LLVMBuildGEP(builder, planes_ptr, indices, 3, "");
1150         plane1 = LLVMBuildLoad(builder, plane_ptr, "plane_w");
1151         planes = vec4f_from_scalar(gallivm, plane1, "plane4_w");
1152         test = LLVMBuildFMul(builder, planes, pos_w, "");
1153         sum = LLVMBuildFAdd(builder, sum, test, "");
1154
1155         test = lp_build_compare(gallivm, f32_type, PIPE_FUNC_GREATER, zero, sum);
1156         temp = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 1 << plane_idx);
1157         test = LLVMBuildAnd(builder, test, temp, "");
1158         mask = LLVMBuildOr(builder, mask, test, "");
1159      }
1160   }
1161   return mask;
1162}
1163
1164
1165/**
1166 * Returns boolean if any clipping has occurred
1167 * Used zero/non-zero i32 value to represent boolean
1168 */
1169static void
1170clipmask_bool(struct gallivm_state *gallivm,
1171              LLVMValueRef clipmask,
1172              LLVMValueRef ret_ptr)
1173{
1174   LLVMBuilderRef builder = gallivm->builder;
1175   LLVMValueRef ret = LLVMBuildLoad(builder, ret_ptr, "");
1176   LLVMValueRef temp;
1177   int i;
1178
1179   for (i=0; i<4; i++) {
1180      temp = LLVMBuildExtractElement(builder, clipmask,
1181                                     lp_build_const_int32(gallivm, i) , "");
1182      ret = LLVMBuildOr(builder, ret, temp, "");
1183   }
1184
1185   LLVMBuildStore(builder, ret, ret_ptr);
1186}
1187
1188
1189static void
1190draw_llvm_generate(struct draw_llvm *llvm, struct draw_llvm_variant *variant,
1191                   boolean elts)
1192{
1193   struct gallivm_state *gallivm = llvm->gallivm;
1194   LLVMContextRef context = gallivm->context;
1195   LLVMTypeRef int32_type = LLVMInt32TypeInContext(context);
1196   LLVMTypeRef arg_types[8];
1197   LLVMTypeRef func_type;
1198   LLVMValueRef context_ptr;
1199   LLVMBasicBlockRef block;
1200   LLVMBuilderRef builder;
1201   LLVMValueRef end, start;
1202   LLVMValueRef count, fetch_elts, fetch_count;
1203   LLVMValueRef stride, step, io_itr;
1204   LLVMValueRef io_ptr, vbuffers_ptr, vb_ptr;
1205   LLVMValueRef instance_id;
1206   LLVMValueRef system_values_array;
1207   LLVMValueRef zero = lp_build_const_int32(gallivm, 0);
1208   LLVMValueRef one = lp_build_const_int32(gallivm, 1);
1209   struct draw_context *draw = llvm->draw;
1210   const struct tgsi_shader_info *vs_info = &draw->vs.vertex_shader->info;
1211   unsigned i, j;
1212   struct lp_build_context bld;
1213   struct lp_build_loop_state lp_loop;
1214   const int max_vertices = 4;
1215   LLVMValueRef outputs[PIPE_MAX_SHADER_OUTPUTS][TGSI_NUM_CHANNELS];
1216   LLVMValueRef fetch_max;
1217   void *code;
1218   struct lp_build_sampler_soa *sampler = 0;
1219   LLVMValueRef ret, ret_ptr;
1220   const boolean bypass_viewport = variant->key.bypass_viewport;
1221   const boolean enable_cliptest = variant->key.clip_xy ||
1222                                   variant->key.clip_z  ||
1223                                   variant->key.clip_user;
1224   LLVMValueRef variant_func;
1225
1226   arg_types[0] = get_context_ptr_type(llvm);       /* context */
1227   arg_types[1] = get_vertex_header_ptr_type(llvm); /* vertex_header */
1228   arg_types[2] = get_buffer_ptr_type(llvm);        /* vbuffers */
1229   if (elts)
1230      arg_types[3] = LLVMPointerType(int32_type, 0);/* fetch_elts * */
1231   else
1232      arg_types[3] = int32_type;                    /* start */
1233   arg_types[4] = int32_type;                       /* fetch_count / count */
1234   arg_types[5] = int32_type;                       /* stride */
1235   arg_types[6] = get_vb_ptr_type(llvm);            /* pipe_vertex_buffer's */
1236   arg_types[7] = int32_type;                       /* instance_id */
1237
1238   func_type = LLVMFunctionType(int32_type, arg_types, Elements(arg_types), 0);
1239
1240   variant_func = LLVMAddFunction(gallivm->module,
1241                                  elts ? "draw_llvm_shader_elts" : "draw_llvm_shader",
1242                                  func_type);
1243
1244   if (elts)
1245      variant->function_elts = variant_func;
1246   else
1247      variant->function = variant_func;
1248
1249   LLVMSetFunctionCallConv(variant_func, LLVMCCallConv);
1250   for (i = 0; i < Elements(arg_types); ++i)
1251      if (LLVMGetTypeKind(arg_types[i]) == LLVMPointerTypeKind)
1252         LLVMAddAttribute(LLVMGetParam(variant_func, i),
1253                          LLVMNoAliasAttribute);
1254
1255   context_ptr  = LLVMGetParam(variant_func, 0);
1256   io_ptr       = LLVMGetParam(variant_func, 1);
1257   vbuffers_ptr = LLVMGetParam(variant_func, 2);
1258   stride       = LLVMGetParam(variant_func, 5);
1259   vb_ptr       = LLVMGetParam(variant_func, 6);
1260   instance_id  = LLVMGetParam(variant_func, 7);
1261
1262   lp_build_name(context_ptr, "context");
1263   lp_build_name(io_ptr, "io");
1264   lp_build_name(vbuffers_ptr, "vbuffers");
1265   lp_build_name(stride, "stride");
1266   lp_build_name(vb_ptr, "vb");
1267   lp_build_name(instance_id, "instance_id");
1268
1269   if (elts) {
1270      fetch_elts   = LLVMGetParam(variant_func, 3);
1271      fetch_count  = LLVMGetParam(variant_func, 4);
1272      lp_build_name(fetch_elts, "fetch_elts");
1273      lp_build_name(fetch_count, "fetch_count");
1274      start = count = NULL;
1275   }
1276   else {
1277      start        = LLVMGetParam(variant_func, 3);
1278      count        = LLVMGetParam(variant_func, 4);
1279      lp_build_name(start, "start");
1280      lp_build_name(count, "count");
1281      fetch_elts = fetch_count = NULL;
1282   }
1283
1284   /*
1285    * Function body
1286    */
1287
1288   block = LLVMAppendBasicBlockInContext(gallivm->context, variant_func, "entry");
1289   builder = gallivm->builder;
1290   LLVMPositionBuilderAtEnd(builder, block);
1291
1292   lp_build_context_init(&bld, gallivm, lp_type_int(32));
1293
1294   system_values_array = lp_build_system_values_array(gallivm, vs_info,
1295                                                      instance_id, NULL);
1296
1297   /* function will return non-zero i32 value if any clipped vertices */
1298   ret_ptr = lp_build_alloca(gallivm, int32_type, "");
1299   LLVMBuildStore(builder, zero, ret_ptr);
1300
1301   /* code generated texture sampling */
1302   sampler = draw_llvm_sampler_soa_create(
1303      draw_llvm_variant_key_samplers(&variant->key),
1304      context_ptr);
1305
1306   if (elts) {
1307      start = zero;
1308      end = fetch_count;
1309   }
1310   else {
1311      end = lp_build_add(&bld, start, count);
1312   }
1313
1314   step = lp_build_const_int32(gallivm, max_vertices);
1315
1316   fetch_max = LLVMBuildSub(builder, end, one, "fetch_max");
1317
1318   lp_build_loop_begin(&lp_loop, gallivm, start);
1319   {
1320      LLVMValueRef inputs[PIPE_MAX_SHADER_INPUTS][TGSI_NUM_CHANNELS];
1321      LLVMValueRef aos_attribs[PIPE_MAX_SHADER_INPUTS][TGSI_NUM_CHANNELS] = { { 0 } };
1322      LLVMValueRef io;
1323      LLVMValueRef clipmask;   /* holds the clipmask value */
1324      const LLVMValueRef (*ptr_aos)[TGSI_NUM_CHANNELS];
1325
1326      if (elts)
1327         io_itr = lp_loop.counter;
1328      else
1329         io_itr = LLVMBuildSub(builder, lp_loop.counter, start, "");
1330
1331      io = LLVMBuildGEP(builder, io_ptr, &io_itr, 1, "");
1332#if DEBUG_STORE
1333      lp_build_printf(builder, " --- io %d = %p, loop counter %d\n",
1334                      io_itr, io, lp_loop.counter);
1335#endif
1336      for (i = 0; i < TGSI_NUM_CHANNELS; ++i) {
1337         LLVMValueRef true_index =
1338            LLVMBuildAdd(builder,
1339                         lp_loop.counter,
1340                         lp_build_const_int32(gallivm, i), "");
1341
1342         /* make sure we're not out of bounds which can happen
1343          * if fetch_count % 4 != 0, because on the last iteration
1344          * a few of the 4 vertex fetches will be out of bounds */
1345         true_index = lp_build_min(&bld, true_index, fetch_max);
1346
1347         if (elts) {
1348            LLVMValueRef fetch_ptr;
1349            fetch_ptr = LLVMBuildGEP(builder, fetch_elts,
1350                                     &true_index, 1, "");
1351            true_index = LLVMBuildLoad(builder, fetch_ptr, "fetch_elt");
1352         }
1353
1354         for (j = 0; j < draw->pt.nr_vertex_elements; ++j) {
1355            struct pipe_vertex_element *velem = &draw->pt.vertex_element[j];
1356            LLVMValueRef vb_index =
1357               lp_build_const_int32(gallivm, velem->vertex_buffer_index);
1358            LLVMValueRef vb = LLVMBuildGEP(builder, vb_ptr, &vb_index, 1, "");
1359            generate_fetch(gallivm, vbuffers_ptr,
1360                           &aos_attribs[j][i], velem, vb, true_index,
1361                           instance_id);
1362         }
1363      }
1364      convert_to_soa(gallivm, aos_attribs, inputs,
1365                     draw->pt.nr_vertex_elements);
1366
1367      ptr_aos = (const LLVMValueRef (*)[TGSI_NUM_CHANNELS]) inputs;
1368      generate_vs(llvm,
1369                  builder,
1370                  outputs,
1371                  ptr_aos,
1372                  system_values_array,
1373                  context_ptr,
1374                  sampler,
1375                  variant->key.clamp_vertex_color);
1376
1377      /* store original positions in clip before further manipulation */
1378      store_clip(gallivm, io, outputs, 0);
1379      store_clip(gallivm, io, outputs, 1);
1380
1381      /* do cliptest */
1382      if (enable_cliptest) {
1383         /* allocate clipmask, assign it integer type */
1384         clipmask = generate_clipmask(gallivm, outputs,
1385                                      variant->key.clip_xy,
1386                                      variant->key.clip_z,
1387                                      variant->key.clip_user,
1388                                      variant->key.clip_halfz,
1389                                      variant->key.ucp_enable,
1390                                      context_ptr);
1391         /* return clipping boolean value for function */
1392         clipmask_bool(gallivm, clipmask, ret_ptr);
1393      }
1394      else {
1395         clipmask = lp_build_const_int_vec(gallivm, lp_type_int_vec(32), 0);
1396      }
1397
1398      /* do viewport mapping */
1399      if (!bypass_viewport) {
1400         generate_viewport(llvm, builder, outputs, context_ptr);
1401      }
1402
1403      /* store clipmask in vertex header,
1404       * original positions in clip
1405       * and transformed positions in data
1406       */
1407      convert_to_aos(gallivm, io, outputs, clipmask,
1408                     vs_info->num_outputs, max_vertices);
1409   }
1410
1411   lp_build_loop_end_cond(&lp_loop, end, step, LLVMIntUGE);
1412
1413   sampler->destroy(sampler);
1414
1415   ret = LLVMBuildLoad(builder, ret_ptr, "");
1416   LLVMBuildRet(builder, ret);
1417
1418   /*
1419    * Translate the LLVM IR into machine code.
1420    */
1421#ifdef DEBUG
1422   if (LLVMVerifyFunction(variant_func, LLVMPrintMessageAction)) {
1423      lp_debug_dump_value(variant_func);
1424      assert(0);
1425   }
1426#endif
1427
1428   LLVMRunFunctionPassManager(gallivm->passmgr, variant_func);
1429
1430   if (gallivm_debug & GALLIVM_DEBUG_IR) {
1431      lp_debug_dump_value(variant_func);
1432      debug_printf("\n");
1433   }
1434
1435   code = LLVMGetPointerToGlobal(gallivm->engine, variant_func);
1436   if (elts)
1437      variant->jit_func_elts = (draw_jit_vert_func_elts) pointer_to_func(code);
1438   else
1439      variant->jit_func = (draw_jit_vert_func) pointer_to_func(code);
1440
1441   if (gallivm_debug & GALLIVM_DEBUG_ASM) {
1442      lp_disassemble(code);
1443   }
1444   lp_func_delete_body(variant_func);
1445}
1446
1447
1448struct draw_llvm_variant_key *
1449draw_llvm_make_variant_key(struct draw_llvm *llvm, char *store)
1450{
1451   unsigned i;
1452   struct draw_llvm_variant_key *key;
1453   struct lp_sampler_static_state *sampler;
1454
1455   key = (struct draw_llvm_variant_key *)store;
1456
1457   key->clamp_vertex_color = llvm->draw->rasterizer->clamp_vertex_color; /**/
1458
1459   /* Presumably all variants of the shader should have the same
1460    * number of vertex elements - ie the number of shader inputs.
1461    */
1462   key->nr_vertex_elements = llvm->draw->pt.nr_vertex_elements;
1463
1464   /* will have to rig this up properly later */
1465   key->clip_xy = llvm->draw->clip_xy;
1466   key->clip_z = llvm->draw->clip_z;
1467   key->clip_user = llvm->draw->clip_user;
1468   key->bypass_viewport = llvm->draw->identity_viewport;
1469   key->clip_halfz = !llvm->draw->rasterizer->gl_rasterization_rules;
1470   key->need_edgeflags = (llvm->draw->vs.edgeflag_output ? TRUE : FALSE);
1471   key->ucp_enable = llvm->draw->rasterizer->clip_plane_enable;
1472   key->pad = 0;
1473
1474   /* All variants of this shader will have the same value for
1475    * nr_samplers.  Not yet trying to compact away holes in the
1476    * sampler array.
1477    */
1478   key->nr_samplers = llvm->draw->vs.vertex_shader->info.file_max[TGSI_FILE_SAMPLER] + 1;
1479
1480   sampler = draw_llvm_variant_key_samplers(key);
1481
1482   memcpy(key->vertex_element,
1483          llvm->draw->pt.vertex_element,
1484          sizeof(struct pipe_vertex_element) * key->nr_vertex_elements);
1485
1486   memset(sampler, 0, key->nr_samplers * sizeof *sampler);
1487
1488   for (i = 0 ; i < key->nr_samplers; i++) {
1489      lp_sampler_static_state(&sampler[i],
1490			      llvm->draw->sampler_views[i],
1491			      llvm->draw->samplers[i]);
1492   }
1493
1494   return key;
1495}
1496
1497
1498void
1499draw_llvm_set_mapped_texture(struct draw_context *draw,
1500                             unsigned sampler_idx,
1501                             uint32_t width, uint32_t height, uint32_t depth,
1502                             uint32_t first_level, uint32_t last_level,
1503                             uint32_t row_stride[PIPE_MAX_TEXTURE_LEVELS],
1504                             uint32_t img_stride[PIPE_MAX_TEXTURE_LEVELS],
1505                             const void *data[PIPE_MAX_TEXTURE_LEVELS])
1506{
1507   unsigned j;
1508   struct draw_jit_texture *jit_tex;
1509
1510   assert(sampler_idx < PIPE_MAX_VERTEX_SAMPLERS);
1511
1512   jit_tex = &draw->llvm->jit_context.textures[sampler_idx];
1513
1514   jit_tex->width = width;
1515   jit_tex->height = height;
1516   jit_tex->depth = depth;
1517   jit_tex->first_level = first_level;
1518   jit_tex->last_level = last_level;
1519
1520   for (j = first_level; j <= last_level; j++) {
1521      jit_tex->data[j] = data[j];
1522      jit_tex->row_stride[j] = row_stride[j];
1523      jit_tex->img_stride[j] = img_stride[j];
1524   }
1525}
1526
1527
1528void
1529draw_llvm_set_sampler_state(struct draw_context *draw)
1530{
1531   unsigned i;
1532
1533   for (i = 0; i < draw->num_samplers; i++) {
1534      struct draw_jit_texture *jit_tex = &draw->llvm->jit_context.textures[i];
1535
1536      if (draw->samplers[i]) {
1537         jit_tex->min_lod = draw->samplers[i]->min_lod;
1538         jit_tex->max_lod = draw->samplers[i]->max_lod;
1539         jit_tex->lod_bias = draw->samplers[i]->lod_bias;
1540         COPY_4V(jit_tex->border_color, draw->samplers[i]->border_color.f);
1541      }
1542   }
1543}
1544
1545
1546void
1547draw_llvm_destroy_variant(struct draw_llvm_variant *variant)
1548{
1549   struct draw_llvm *llvm = variant->llvm;
1550
1551   if (variant->function_elts) {
1552      LLVMFreeMachineCodeForFunction(llvm->gallivm->engine,
1553                                     variant->function_elts);
1554      LLVMDeleteFunction(variant->function_elts);
1555   }
1556
1557   if (variant->function) {
1558      LLVMFreeMachineCodeForFunction(llvm->gallivm->engine,
1559                                     variant->function);
1560      LLVMDeleteFunction(variant->function);
1561   }
1562
1563   remove_from_list(&variant->list_item_local);
1564   variant->shader->variants_cached--;
1565   remove_from_list(&variant->list_item_global);
1566   llvm->nr_variants--;
1567   FREE(variant);
1568}
1569