-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathbatched_backendllvm.cpp
More file actions
2191 lines (1880 loc) · 80.2 KB
/
batched_backendllvm.cpp
File metadata and controls
2191 lines (1880 loc) · 80.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
// #define OSL_DEV 1
#include <type_traits>
#include "batched_backendllvm.h"
#include "oslexec_pvt.h"
#include <llvm/ADT/Twine.h>
#include <llvm/IR/Constant.h>
#include <llvm/IR/Type.h>
#include <llvm/Support/raw_os_ostream.h>
using namespace OSL;
using namespace OSL::pvt;
OSL_NAMESPACE_ENTER
namespace pvt {
namespace // Unnamed
{
// The order of names in this table MUST exactly match the
// BatchedShaderGlobals struct in batched_shaderglobals.h,
// as well as the llvm 'sg' type
// defined in BatchedBackendLLVM::llvm_type_sg().
static ustringhash fields[] = {
// Uniform
ustringhash("renderstate"), //
ustringhash("tracedata"), //
ustringhash("objdata"), //
ustringhash("shadingcontext"), //
ustringhash("renderer"), //
Hashes::raytype, //
ustringhash("pad0"), //
ustringhash("pad1"), //
ustringhash("pad2"), //
ustringhash("pad3"), //
ustringhash("pad4"), //
// Varying
Hashes::P, //
ustringhash("dPdz"), //
Hashes::I, //
Hashes::N, //
Hashes::Ng, //
Hashes::u, //
Hashes::v, //
Hashes::dPdu, //
Hashes::dPdv, //
Hashes::time, //
Hashes::dtime, //
Hashes::dPdtime, //
Hashes::Ps, //
ustringhash("object2common"), //
ustringhash("shader2common"), //
Hashes::Ci, //
ustringhash("surfacearea"), //
ustringhash("flipHandedness"), //
ustringhash("backfacing")
};
static bool field_is_uniform[] = {
// Uniform
true, // renderstate
true, // tracedata
true, // objdata
true, // shadingcontext
true, // renderer
true, // raytype
true, // pad0
true, // pad1
true, // pad2
true, // pad3
true, // pad4
// Varying
false, // P
false, // dPdz
false, // I
false, // N
false, // Ng
false, // u
false, // v
false, // dPdu
false, // dPdv
false, // time
false, // dtime
false, // dPdtime
false, // Ps
false, // object2common
false, // shader2common
false, // Ci,
false, // surfacearea
false, // flipHandedness
false, // backfacing
};
} // namespace
extern bool
is_shader_global_uniform_by_name(ustring name)
{
for (int i = 0; i < int(std::extent<decltype(fields)>::value); ++i) {
if (name == fields[i]) {
return field_is_uniform[i];
}
}
return false;
}
BatchedBackendLLVM::BatchedBackendLLVM(ShadingSystemImpl& shadingsys,
ShaderGroup& group, ShadingContext* ctx,
int width)
: OSOProcessorBase(shadingsys, group, ctx)
, ll(ctx->llvm_thread_info(), llvm_debug(), width)
, m_width(width)
, m_library_selector(nullptr)
, m_stat_total_llvm_time(0)
, m_stat_llvm_setup_time(0)
, m_stat_llvm_irgen_time(0)
, m_stat_llvm_opt_time(0)
, m_stat_llvm_jit_time(0)
{
m_name_llvm_syms = shadingsys.m_llvm_output_bitcode;
m_wide_arg_prefix = "W";
switch (vector_width()) {
case 16: m_true_mask_value = Mask<16>(true).value(); break;
case 8: m_true_mask_value = Mask<8>(true).value(); break;
default: OSL_ASSERT(0 && "unsupported vector width");
}
// Select the appropriate ustring representation
ll.ustring_rep(LLVM_Util::UstringRep::hash);
ll.dumpasm(shadingsys.m_llvm_dumpasm);
ll.jit_fma(shadingsys.m_llvm_jit_fma);
ll.jit_aggressive(shadingsys.m_llvm_jit_aggressive);
}
BatchedBackendLLVM::~BatchedBackendLLVM() {}
int
BatchedBackendLLVM::llvm_debug() const
{
if (shadingsys().llvm_debug() == 0)
return 0;
if (!shadingsys().debug_groupname().empty()
&& shadingsys().debug_groupname() != group().name()) {
return 0;
}
if (inst() && !shadingsys().debug_layername().empty()
&& shadingsys().debug_layername() != inst()->layername())
return 0;
return shadingsys().llvm_debug();
}
void
BatchedBackendLLVM::set_inst(int layer)
{
OSOProcessorBase::set_inst(layer); // parent does the heavy lifting
ll.debug(llvm_debug());
}
llvm::Type*
BatchedBackendLLVM::llvm_pass_type(const TypeSpec& typespec)
{
if (typespec.is_closure_based())
return (llvm::Type*)ll.type_void_ptr();
TypeDesc t = typespec.simpletype().elementtype();
llvm::Type* lt = NULL;
if (t == TypeDesc::FLOAT)
lt = ll.type_float();
else if (t == TypeDesc::INT)
lt = ll.type_int();
else if (t == TypeDesc::STRING)
lt = (llvm::Type*)ll.type_real_ustring();
else if (t.aggregate == TypeDesc::VEC3)
lt = (llvm::Type*)ll.type_void_ptr(); //llvm_type_triple_ptr();
else if (t.aggregate == TypeDesc::MATRIX44)
lt = (llvm::Type*)ll.type_void_ptr(); //llvm_type_matrix_ptr();
else if (t == TypeDesc::NONE)
lt = ll.type_void();
else if (t == TypeDesc::PTR)
lt = (llvm::Type*)ll.type_void_ptr();
else if (t == TypeDesc::LONGLONG)
lt = ll.type_longlong();
else if (t == OSL::TypeUInt64)
lt = ll.type_int64(); //LLVM does not recognize signed bits
else {
std::cerr << "Bad llvm_pass_type(" << typespec.c_str() << ")\n";
OSL_ASSERT(0 && "not handling this type yet");
}
if (t.arraylen) {
OSL_ASSERT(0 && "should never pass an array directly as a parameter");
}
return lt;
}
llvm::Type*
BatchedBackendLLVM::llvm_pass_wide_type(const TypeSpec& typespec)
{
if (typespec.is_closure_based())
return (llvm::Type*)ll.type_void_ptr();
TypeDesc t = typespec.simpletype().elementtype();
llvm::Type* lt = NULL;
if (t == TypeDesc::FLOAT)
lt = (llvm::Type*)ll.type_void_ptr(); // ll.type_wide_float();
else if (t == TypeDesc::INT)
lt = (llvm::Type*)ll.type_void_ptr(); // ll.type_wide_int();
else if (t == TypeDesc::STRING)
lt = (llvm::Type*)
ll.type_void_ptr(); // (llvm::Type *) ll.type_wide_ string();
else if (t.aggregate == TypeDesc::VEC3)
lt = (llvm::Type*)ll.type_void_ptr(); //llvm_type_wide_triple_ptr();
else if (t.aggregate == TypeDesc::MATRIX44)
lt = (llvm::Type*)ll.type_void_ptr(); //llvm_type_wide_matrix_ptr();
else if (t == TypeDesc::NONE)
lt = ll.type_void();
else if (t == TypeDesc::PTR)
lt = (llvm::Type*)ll.type_void_ptr();
else if (t == TypeDesc::LONGLONG)
lt = (llvm::Type*)ll.type_void_ptr(); // ll.type_wide_longlong();
else {
std::cerr << "Bad llvm_pass_type(" << typespec.c_str() << ")\n";
OSL_ASSERT(0 && "not handling this type yet");
}
if (t.arraylen) {
OSL_ASSERT(0 && "should never pass an array directly as a parameter");
}
return lt;
}
void
BatchedBackendLLVM::llvm_assign_zero(const Symbol& sym)
{
llvm::Value* zero;
const TypeSpec& t = sym.typespec();
TypeSpec elemtype = t.elementtype();
if (elemtype.is_float_based()) {
if (sym.is_uniform())
zero = ll.constant(0.0f);
else
zero = ll.wide_constant(0.0f);
} else if (elemtype.is_int_based()) {
if (sym.is_uniform())
zero = ll.constant(0);
else
zero = ll.wide_constant(0);
} else if (elemtype.is_string_based()) {
if (sym.is_uniform())
zero = ll.constant(uint64_t(0));
else
zero = ll.wide_constant(uint64_t(0));
} else if (elemtype.is_closure_based()) {
if (sym.is_uniform())
zero = ll.void_ptr_null();
else
zero = ll.widen_value(ll.void_ptr_null());
} else {
OSL_ASSERT(0 && "Unsupported element type");
zero = nullptr;
}
int num_elements = t.numelements();
for (int a = 0; a < num_elements; ++a) {
int numDeriv = sym.has_derivs() ? 3 : 1;
llvm::Value* arrind = t.simpletype().arraylen ? ll.constant(a) : NULL;
for (int d = 0; d < numDeriv; ++d) {
for (int c = 0; c < t.aggregate(); ++c) {
llvm_store_value(zero, sym, d, arrind, c);
}
}
}
}
void
BatchedBackendLLVM::llvm_zero_derivs(const Symbol& sym)
{
const TypeSpec& t = sym.typespec();
if (t.is_closure_based())
return; // Closures don't have derivs
TypeSpec elemtype = t.elementtype();
if (sym.has_derivs() && elemtype.is_float_based()) {
llvm::Value* zero;
if (sym.is_uniform())
zero = ll.constant(0.0f);
else
zero = ll.wide_constant(0.0f);
int start_array_index = -1;
int end_array_index = start_array_index + 1;
if (t.is_array()) {
// TODO: investigate doing a memset for arrays & matrices,
// but not for simple aggregates
start_array_index = 0;
end_array_index = t.arraylength();
}
for (int arrayindex = start_array_index; arrayindex < end_array_index;
++arrayindex) {
llvm::Value* arrind = arrayindex >= 0 ? ll.constant(arrayindex)
: NULL;
for (int c = 0; c < t.aggregate(); ++c)
llvm_store_value(zero, sym, 1, arrind, c);
for (int c = 0; c < t.aggregate(); ++c)
llvm_store_value(zero, sym, 2, arrind, c);
}
}
}
void
BatchedBackendLLVM::llvm_zero_derivs(const Symbol& sym, llvm::Value* count)
{
// Same thing as the above version but with just the first count derivs
const TypeSpec& t = sym.typespec();
OSL_ASSERT((count->getType() == ll.type_int())
|| (count->getType() == ll.type_wide_int()));
if (t.is_closure_based())
return; // Closures don't have derivs
TypeSpec elemtype = t.elementtype();
if (sym.has_derivs() && elemtype.is_float_based()) {
llvm::Value* zero;
if (sym.is_uniform())
zero = ll.constant(0.0f);
else
zero = ll.wide_constant(0.0f);
if (!t.is_array()) {
// Not an array, probably shouldn't have called this method
// just fallback to non-count based version
llvm_zero_derivs(sym);
return;
}
llvm::Value* pre_condition_mask = ll.current_mask();
llvm::Value* index_loc = ll.op_alloca(ll.type_int(), 1);
ll.op_store(ll.constant(0), index_loc);
llvm::BasicBlock* cond_block = ll.new_basic_block("zero deriv cond");
llvm::BasicBlock* body_block = ll.new_basic_block("zero deriv body");
llvm::BasicBlock* step_block = ll.new_basic_block("zero deriv step");
llvm::BasicBlock* after_block = ll.new_basic_block("zero deriv after");
ll.op_branch(cond_block);
llvm::Value* index_val = ll.op_load(ll.type_int(), index_loc);
llvm::Value* windex_val = ll.widen_value(index_val);
llvm::Value* condition_mask = ll.op_lt(windex_val, count);
llvm::Value* post_condition_mask = ll.op_and(condition_mask,
pre_condition_mask);
llvm::Value* cond_val = ll.test_if_mask_is_non_zero(
post_condition_mask);
// Jump to either LoopBody or AfterLoop
ll.op_branch(cond_val, body_block, after_block);
ll.push_mask(post_condition_mask, false /* negate */,
true /* absolute */);
for (int c = 0; c < t.aggregate(); ++c)
llvm_store_value(zero, sym, 1, index_val, c);
for (int c = 0; c < t.aggregate(); ++c)
llvm_store_value(zero, sym, 2, index_val, c);
ll.pop_mask();
ll.op_branch(step_block);
index_val = ll.op_add(index_val, ll.constant(1));
ll.op_store(index_val, index_loc);
ll.op_branch(cond_block);
// Continue on with the previous flow
ll.set_insert_point(after_block);
}
}
int
BatchedBackendLLVM::ShaderGlobalNameToIndex(ustring name, bool& is_uniform)
{
for (int i = 0; i < int(sizeof(fields) / sizeof(fields[0])); ++i)
if (name == fields[i]) {
is_uniform = field_is_uniform[i];
return i;
}
OSL_DEV_ONLY(std::cout << "ShaderGlobalNameToIndex failed with " << name
<< std::endl);
return -1;
}
llvm::Value*
BatchedBackendLLVM::llvm_global_symbol_ptr(ustring name, bool& is_uniform)
{
// Special case for globals -- they live in the ShaderGlobals struct,
// we use the name of the global to find the index of the field within
// the ShaderGlobals struct.
int sg_index = ShaderGlobalNameToIndex(name, is_uniform);
OSL_ASSERT(sg_index >= 0);
return ll.void_ptr(ll.GEP(llvm_type_sg(), sg_ptr(), 0, sg_index));
}
llvm::Value*
BatchedBackendLLVM::getLLVMSymbolBase(const Symbol& sym)
{
Symbol* dealiased = sym.dealias();
bool is_uniform = sym.is_uniform();
if (sym.symtype() == SymTypeGlobal) {
llvm::Value* result = llvm_global_symbol_ptr(sym.name(), is_uniform);
OSL_ASSERT(result);
if (is_uniform) {
result = ll.ptr_to_cast(result,
llvm_type(sym.typespec().elementtype()));
} else {
result = ll.ptr_to_cast(result, llvm_wide_type(
sym.typespec().elementtype()));
}
return result;
}
if (sym.symtype() == SymTypeParam && sym.interactive()) {
// Special case for interactively-edited parameters -- they live in
// the interactive data block for the group.
// Generate the pointer to this symbol by offsetting into the
// interactive data block.
int offset = group().interactive_param_offset(layer(), sym.name());
return ll.offset_ptr(m_llvm_interactive_params_ptr, offset,
llvm_ptr_type(sym.typespec().elementtype()));
}
if (sym.symtype() == SymTypeParam
|| (sym.symtype() == SymTypeOutputParam
&& !can_treat_param_as_local(sym))) {
// Special case for most params -- they live in the group data
int fieldnum = m_param_order_map[&sym];
return groupdata_field_ptr(fieldnum,
sym.typespec().elementtype().simpletype(),
is_uniform, sym.forced_llvm_bool());
}
std::string mangled_name = dealiased->mangled();
AllocationMap::iterator map_iter = named_values().find(mangled_name);
if (map_iter == named_values().end()) {
shadingcontext()->errorfmt(
"Couldn't find symbol '{}' (unmangled = '{}'). Did you forget to allocate it?",
mangled_name, dealiased->unmangled());
return 0;
}
return (llvm::Value*)map_iter->second;
}
llvm::Value*
BatchedBackendLLVM::llvm_alloca(const TypeSpec& type, bool derivs,
bool is_uniform, bool forceBool,
const std::string& name)
{
OSL_DEV_ONLY(std::cout << "llvm_alloca " << name);
TypeDesc t = llvm_typedesc(type);
int n = derivs ? 3 : 1;
OSL_DEV_ONLY(std::cout << " n=" << n << " t.size()=" << t.size());
m_llvm_local_mem += t.size() * n;
if (is_uniform) {
OSL_DEV_ONLY(std::cout << " as UNIFORM " << std::endl);
if (forceBool) {
return ll.op_alloca(ll.type_bool(), n, name);
} else {
return ll.op_alloca(t, n, name);
}
} else {
OSL_DEV_ONLY(std::cout << " as VARYING " << std::endl);
if (forceBool) {
return ll.op_alloca(ll.type_native_mask(), n, name);
} else {
return ll.wide_op_alloca(t, n, name);
}
}
}
BatchedBackendLLVM::TempScope::TempScope(BatchedBackendLLVM& backend)
: m_backend(backend)
{
m_backend.m_temp_scopes.push_back(this);
}
BatchedBackendLLVM::TempScope::~TempScope()
{
OSL_ASSERT(!m_backend.m_temp_scopes.empty()
&& m_backend.m_temp_scopes.back() == this);
OSL_MAYBE_UNUSED int temp_count = static_cast<int>(
m_backend.m_temp_allocs.size());
// Any temps we used will no longer be needed,
// so we can mark them to be reused
for (int temp_index : m_in_use_indices) {
OSL_DASSERT(temp_index < temp_count && temp_index >= 0);
m_backend.m_temp_allocs[temp_index].in_use = false;
}
m_backend.m_temp_scopes.pop_back();
}
llvm::Value*
BatchedBackendLLVM::getOrAllocateTemp(const TypeSpec& type, bool derivs,
bool is_uniform, bool forceBool,
const std::string& name)
{
OSL_ASSERT(
!m_temp_scopes.empty()
&& "an instance of BatchedBackendLLVM::TempScope must exist higher up on the stack");
// Check to see if we have a free temp meeting the request
// using simple reverse linear search
int temp_count = static_cast<int>(m_temp_allocs.size());
for (int temp_index = temp_count - 1; temp_index >= 0; --temp_index) {
TempAlloc& temp_alloc = m_temp_allocs[temp_index];
if (!temp_alloc.in_use && temp_alloc.derivs == derivs
&& temp_alloc.is_uniform == is_uniform
&& temp_alloc.forceBool == forceBool) {
// If we are forcing bool, we don't care about the actual type requested
if (forceBool || temp_alloc.type == type) {
llvm::Value* cached_alloc = temp_alloc.llvm_value;
m_temp_scopes.back()->m_in_use_indices.push_back(temp_index);
temp_alloc.in_use = true;
return cached_alloc;
}
}
}
// No free temp matched the request, so allocate one
// NOTE: the name will be of the 1st user of the temp, it may get reused out of
// the cache for other purposes than named. Debatable if the name should be dropped
// it may hurt more than help
llvm::Value* allocation = llvm_alloca(type, derivs, is_uniform, forceBool,
name);
m_temp_allocs.push_back(TempAlloc { true /*in_use*/, derivs, is_uniform,
forceBool, type, allocation });
m_temp_scopes.back()->m_in_use_indices.push_back(temp_count);
return allocation;
}
bool
BatchedBackendLLVM::can_treat_param_as_local(const Symbol& sym)
{
if (!shadingsys().m_opt_groupdata)
return false;
// Some output parameters that are never needed before or
// after layer execution can be relocated from GroupData
// onto the stack.
return sym.symtype() == SymTypeOutputParam && !sym.renderer_output()
&& !sym.typespec().is_closure_based() && !sym.connected();
}
llvm::Value*
BatchedBackendLLVM::getOrAllocateLLVMSymbol(const Symbol& sym)
{
OSL_DASSERT(
(sym.symtype() == SymTypeLocal || sym.symtype() == SymTypeTemp
|| sym.symtype() == SymTypeConst || can_treat_param_as_local(sym))
&& "getOrAllocateLLVMSymbol should only be for local, tmp, const");
Symbol* dealiased = sym.dealias();
std::string mangled_name = dealiased->mangled();
AllocationMap::iterator map_iter = named_values().find(mangled_name);
if (map_iter == named_values().end()) {
bool is_uniform = sym.is_uniform();
bool forceBool = sym.forced_llvm_bool();
llvm::Value* a = llvm_alloca(sym.typespec(), sym.has_derivs(),
is_uniform, forceBool, mangled_name);
named_values()[mangled_name] = a;
return a;
}
return map_iter->second;
}
llvm::Value*
BatchedBackendLLVM::llvm_get_pointer(const Symbol& sym, int deriv,
llvm::Value* arrayindex)
{
bool has_derivs = sym.has_derivs();
if (!has_derivs && deriv != 0) {
// Return NULL for request for pointer to derivs that don't exist
return ll.ptr_cast(ll.void_ptr_null(),
ll.type_ptr(llvm_type(sym.typespec().elementtype())));
}
llvm::Value* result = NULL;
if (sym.symtype() == SymTypeConst) {
// For constants, start with *OUR* pointer to the constant values.
result
= ll.ptr_cast(ll.constant_ptr(sym.data()),
// Constants by definition should always be UNIFORM
ll.type_ptr(llvm_type(sym.typespec().elementtype())));
} else {
// Start with the initial pointer to the variable's memory location
result = getLLVMSymbolBase(sym);
#ifdef OSL_DEV
std::cerr << " llvm_get_pointer(" << sym.name() << ") result=";
{
llvm::raw_os_ostream os_cerr(std::cerr);
ll.llvm_typeof(result)->print(os_cerr);
}
std::cerr << std::endl;
#endif
}
if (!result)
return NULL; // Error
// If it's an array or we're dealing with derivatives, step to the
// right element.
TypeDesc t = sym.typespec().simpletype();
if (t.arraylen || has_derivs) {
#ifdef OSL_DEV
std::cout << "llvm_get_pointer we're dealing with an array("
<< t.arraylen << ") or has_derivs(" << has_derivs
<< ")<<-------" << std::endl;
std::cout << "arrayindex=" << arrayindex << " deriv=" << deriv
<< " t.arraylen=" << t.arraylen;
std::cout << " is_uniform=" << sym.is_uniform() << std::endl;
#endif
int d = deriv * std::max(1, t.arraylen);
if (arrayindex)
arrayindex = ll.op_add(arrayindex, ll.constant(d));
else
arrayindex = ll.constant(d);
llvm::Type* result_type = llvm_type(t.elementtype());
if (!sym.is_uniform()) {
result_type = ll.type_wide(result_type);
}
// Arrays will not be forced_llvm_bool, so no need to check
result = ll.GEP(result_type, result, arrayindex);
}
return result;
}
llvm::Value*
BatchedBackendLLVM::llvm_widen_value_into_temp(const Symbol& sym, int deriv)
{
OSL_ASSERT(
!m_temp_scopes.empty()
&& "An instance of BatchedBackendLLVM::TempScope must exist higher up in the call stack");
OSL_ASSERT(sym.is_uniform() == true);
const TypeSpec& t = sym.typespec();
TypeDesc symType = t.simpletype();
OSL_ASSERT(symType.is_unknown() == false);
llvm::Value* widePtr = getOrAllocateTemp(t, false /*derivs*/,
false /*is_uniform*/);
auto disable_masked_stores = ll.create_masking_scope(false);
for (int c = 0; c < t.aggregate(); ++c) {
// NOTE: we use the passed deriv to load, but store to value (deriv==0)
llvm::Value* v = llvm_load_value(sym, deriv, c, TypeUnknown,
/*is_uniform*/ false);
llvm_store_value(v, widePtr, t, 0, NULL, c, /*is_uniform*/ false);
}
return ll.void_ptr(widePtr);
}
llvm::Value*
BatchedBackendLLVM::llvm_load_value(const Symbol& sym, int deriv,
llvm::Value* arrayindex, int component,
TypeDesc cast, bool op_is_uniform,
bool index_is_uniform,
bool always_real_ustring)
{
// A uniform symbol can be broadcast into a varying value.
// But a varying symbol can NOT be loaded into a uniform value.
OSL_ASSERT(!op_is_uniform || sym.is_uniform());
bool has_derivs = sym.has_derivs();
if (!has_derivs && deriv != 0) {
// Regardless of what object this is, if it doesn't have derivs but
// we're asking for them, return 0. Integers don't have derivs
// so we don't need to worry about that case.
if (op_is_uniform) {
return ll.constant(0.0f);
} else {
return ll.wide_constant(0.0f);
}
}
// arrayindex should be non-NULL if and only if sym is an array
OSL_ASSERT(sym.typespec().is_array() == (arrayindex != NULL));
if (sym.is_constant() && !sym.typespec().is_array() && !arrayindex) {
// Shortcut for simple constants
if (sym.typespec().is_float()) {
float float_val = sym.get_float();
if (cast == TypeInt) {
int int_val = static_cast<int>(float_val);
if (op_is_uniform) {
return ll.constant(int_val);
} else {
return ll.wide_constant(int_val);
}
} else if (op_is_uniform) {
return ll.constant(float_val);
} else {
return ll.wide_constant(float_val);
}
}
if (sym.typespec().is_int()) {
int int_val = sym.get_int();
if (cast == TypeFloat) {
float float_val = static_cast<float>(int_val);
if (op_is_uniform) {
return ll.constant(float_val);
} else {
return ll.wide_constant(float_val);
}
} else {
if (op_is_uniform) {
return ll.constant(int_val);
} else {
return ll.wide_constant(int_val);
}
}
}
if (sym.typespec().is_triple() || sym.typespec().is_matrix()) {
float float_val = sym.get_float(component);
if (op_is_uniform) {
return ll.constant(float_val);
} else {
return ll.wide_constant(float_val);
}
}
if (sym.typespec().is_string()) {
ustring string_val = sym.get_string();
if (op_is_uniform) {
if (!always_real_ustring)
return ll.constant(string_val);
else
return ll.constant_real_ustring(string_val);
} else {
if (!always_real_ustring)
return ll.wide_constant(string_val);
else
return ll.wide_constant_real_ustring(string_val);
}
}
OSL_ASSERT(0 && "unhandled constant type");
}
OSL_DEV_ONLY(std::cout << " llvm_load_value " << sym.typespec().string()
<< " cast " << cast << std::endl);
return llvm_load_value(llvm_get_pointer(sym), sym.typespec(), deriv,
arrayindex, component, sym.is_uniform(), cast,
op_is_uniform, index_is_uniform,
sym.forced_llvm_bool());
}
llvm::Value*
BatchedBackendLLVM::llvm_const_hash(string_view str)
{
return llvm_const_hash(ustring(str));
}
llvm::Value*
BatchedBackendLLVM::llvm_const_hash(ustring str)
{
return ll.constant64((uint64_t)str.hash());
}
llvm::Value*
BatchedBackendLLVM::llvm_load_mask(const Symbol& cond)
{
OSL_ASSERT(cond.is_varying());
OSL_ASSERT(cond.typespec().is_int());
llvm::Value* llvm_mask = nullptr;
llvm::Value* llvm_mask_or_wide_int
= llvm_load_value(cond, /*deriv*/ 0, /*component*/ 0,
/*cast*/ TypeUnknown, /*op_is_uniform*/ false);
if (cond.forced_llvm_bool()) {
// The llvm_load_value + TypeUnknown will check and convert to llvm mask already
llvm_mask = llvm_mask_or_wide_int;
} else {
OSL_ASSERT(ll.llvm_typeof(llvm_mask_or_wide_int) == ll.type_wide_int());
llvm_mask = ll.op_int_to_bool(llvm_mask_or_wide_int);
}
OSL_ASSERT(ll.llvm_typeof(llvm_mask) == ll.type_wide_bool());
return llvm_mask;
}
llvm::Value*
BatchedBackendLLVM::llvm_load_value(llvm::Value* src_ptr, const TypeSpec& type,
int deriv, llvm::Value* arrayindex,
int component, bool src_is_uniform,
TypeDesc cast, bool op_is_uniform,
bool index_is_uniform,
bool symbol_forced_boolean)
{
if (!src_ptr)
return NULL; // Error
TypeDesc t = type.simpletype();
llvm::Type *src_type, *src_component_type;
if (symbol_forced_boolean) {
if (src_is_uniform) {
src_type = ll.type_bool();
src_component_type = ll.type_bool();
} else {
src_type = ll.type_native_mask();
src_component_type = ll.type_native_mask();
}
} else {
src_type = llvm_type(t.elementtype());
src_component_type = llvm_type(t.scalartype());
if (!src_is_uniform) {
src_type = ll.type_wide(src_type);
src_component_type = ll.type_wide(src_component_type);
}
}
if (index_is_uniform) {
// If it's an array or we're dealing with derivatives, step to the
// right element.
if (t.arraylen || deriv) {
int d = deriv * std::max(1, t.arraylen);
llvm::Value* elem;
if (arrayindex)
elem = ll.op_add(arrayindex, ll.constant(d));
else
elem = ll.constant(d);
src_ptr = ll.GEP(src_type, src_ptr, elem);
}
// If it's multi-component (triple or matrix), step to the right field
if (!type.is_closure_based() && t.aggregate > 1) {
OSL_DEV_ONLY(std::cout << "step to the right field " << component
<< std::endl);
src_ptr = ll.GEP(src_type, src_ptr, 0, component);
}
// Now grab the value
llvm::Value* result = ll.op_load(src_component_type, src_ptr);
if (type.is_closure_based())
return result;
// We may have bool masquarading as int's and need to promote them for
// use in any int arithmetic
if (type.is_int() && symbol_forced_boolean) {
// We only need to convert wide native masks
// and op_is_uniform doesn't guarantee that the symbol it self
// in non-unform, it could just be a single bool (vs. mask).
if (!op_is_uniform && (ll.llvm_typeof(result) != ll.type_bool())) {
// We just loaded a native mask need to convert it
// to a vector of bools
result = ll.native_to_llvm_mask(result);
}
if (cast != TypeUnknown) {
if (cast == TypeInt) {
result = ll.op_bool_to_int(result);
} else if (cast == TypeFloat) {
result = ll.op_bool_to_float(result);
}
}
}
// Handle int<->float type casting
if (type.is_float_based() && cast == TypeInt)
result = ll.op_float_to_int(result);
else if (type.is_int() && cast == TypeFloat)
result = ll.op_int_to_float(result);
else if (type.is_string() && cast == TypeDesc::LONGLONG)
result = ll.ptr_to_cast(result, ll.type_longlong());
if (!op_is_uniform) {
// TODO: remove this assert once we have confirmed correct handling off all the
// different data types. Using OSL_ASSERT as a checklist to verify what we have
// handled so far during development
OSL_ASSERT(cast == TypeUnknown || cast == TypeColor
|| cast == TypeVector || cast == TypePoint
|| cast == TypeNormal || cast == TypeFloat
|| cast == TypeInt || cast == TypeString
|| cast == TypeMatrix || cast == TypeDesc::LONGLONG);
if ((ll.llvm_typeof(result) == ll.type_bool())
|| (ll.llvm_typeof(result) == ll.type_float())
|| (ll.llvm_typeof(result) == ll.type_triple())
|| (ll.llvm_typeof(result) == ll.type_int())
|| (ll.llvm_typeof(result) == ll.type_ustring())
|| (ll.llvm_typeof(result) == ll.type_matrix())
|| (ll.llvm_typeof(result) == ll.type_longlong())) {
result = ll.widen_value(result);
} else {
#ifdef OSL_DEV
if (!((ll.llvm_typeof(result) == ll.type_wide_float())
|| (ll.llvm_typeof(result) == ll.type_wide_int())
|| (ll.llvm_typeof(result) == ll.type_wide_matrix())
|| (ll.llvm_typeof(result) == ll.type_wide_triple())
|| (ll.llvm_typeof(result) == ll.type_wide_ustring())
|| (ll.llvm_typeof(result) == ll.type_wide_bool()))) {
OSL_DEV_ONLY(std::cout << ">>>>>>>>>>>>>> TYPENAME OF "
<< ll.llvm_typenameof(result)
<< std::endl);
}
#endif
OSL_ASSERT(
(ll.llvm_typeof(result) == ll.type_wide_float())
|| (ll.llvm_typeof(result) == ll.type_wide_int())
|| (ll.llvm_typeof(result) == ll.type_wide_triple())
|| (ll.llvm_typeof(result) == ll.type_wide_ustring())
|| (ll.llvm_typeof(result) == ll.type_wide_bool())
|| (ll.llvm_typeof(result) == ll.type_wide_matrix())
|| (ll.llvm_typeof(result) == ll.type_wide_longlong()));
}
}
return result;
} else {
OSL_ASSERT(!op_is_uniform);
OSL_ASSERT(nullptr != arrayindex);
// If it's an array or we're dealing with derivatives, step to the
// right element.
if (t.arraylen || deriv) {
int d = deriv * std::max(1, t.arraylen);
llvm::Value* elem = ll.constant(d);
src_ptr = ll.GEP(src_type, src_ptr, elem);
}
// If it's multi-component (triple or matrix), step to the right field
if (!type.is_closure_based() && t.aggregate > 1) {
OSL_DEV_ONLY(std::cout << "step to the right field " << component
<< std::endl);
src_ptr = ll.GEP(src_type, src_ptr, 0, component);
// Need to scale the indices by the stride
// of the type
int elem_stride = t.aggregate;
arrayindex = ll.op_mul(arrayindex, ll.wide_constant(elem_stride));
// TODO: possible optimization when elem_stride == 2 && sizeof(type) == 4,
// could have optional parameter gather operation to use a scale of 8 (2*4)
// vs. the hardcoded 4 and avoid the multiplication above
}
// Now grab the value
llvm::Value* result = ll.op_gather(src_component_type, src_ptr,
arrayindex);
// TODO: possible optimization when we know the array size is small (<= 4)
// instead of performing a gather, we could load each value of the the array,
// compare the index array against that value's index and select/blend
// the results together. Basically we will loading the entire content of the
// array, but can avoid branching or any gather statements.
if (type.is_closure_based())
return result;
OSL_ASSERT(ll.llvm_typeof(result) != ll.type_wide_bool());
// Handle int<->float type casting