/
llvm_util.cpp
6674 lines (5635 loc) · 238 KB
/
llvm_util.cpp
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
#include <cinttypes>
#include <memory>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/thread.h>
#include <OSL/llvm_util.h>
#include <OSL/oslconfig.h>
#include <OSL/wide.h>
#if OSL_LLVM_VERSION < 90
# error "LLVM minimum version required for OSL is 9.0"
#endif
#include "llvm_passes.h"
#include <llvm/InitializePasses.h>
#include <llvm/Pass.h>
#include <llvm/IR/Constant.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#if OSL_LLVM_VERSION >= 100
# include <llvm/IR/IntrinsicsX86.h>
#endif
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/ValueSymbolTable.h>
#include <llvm/Linker/Linker.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/ErrorOr.h>
#include <llvm/Support/FileSystem.h>
#if OSL_LLVM_VERSION < 160
# include <llvm/Support/Host.h>
#else
# include <llvm/TargetParser/Host.h>
#endif
#include <llvm/Support/raw_os_ostream.h>
#if OSL_LLVM_VERSION < 140
# include <llvm/Support/TargetRegistry.h>
#else
# include <llvm/MC/TargetRegistry.h>
#endif
#include <llvm/Analysis/BasicAliasAnalysis.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Analysis/TypeBasedAliasAnalysis.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/FunctionAttrs.h>
#include <llvm/Transforms/InstCombine/InstCombine.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Scalar/GVN.h>
#include <llvm/Transforms/Utils.h>
#include <llvm/Transforms/Utils/UnifyFunctionExitNodes.h>
#include <llvm/Support/DynamicLibrary.h>
#if OSL_LLVM_VERSION >= 120
# include <llvm/CodeGen/Passes.h>
#endif
#ifdef OSL_LLVM_NEW_PASS_MANAGER
// New pass manager
# include <llvm/Analysis/LoopAnalysisManager.h>
# include <llvm/Passes/PassBuilder.h>
# include <llvm/Transforms/IPO/ArgumentPromotion.h>
# include <llvm/Transforms/IPO/ConstantMerge.h>
# include <llvm/Transforms/IPO/DeadArgumentElimination.h>
# include <llvm/Transforms/IPO/GlobalDCE.h>
# include <llvm/Transforms/IPO/GlobalOpt.h>
# include <llvm/Transforms/IPO/SCCP.h>
# include <llvm/Transforms/IPO/StripDeadPrototypes.h>
# include <llvm/Transforms/Scalar/ADCE.h>
# include <llvm/Transforms/Scalar/CorrelatedValuePropagation.h>
# include <llvm/Transforms/Scalar/DCE.h>
# include <llvm/Transforms/Scalar/DeadStoreElimination.h>
# include <llvm/Transforms/Scalar/EarlyCSE.h>
# include <llvm/Transforms/Scalar/IndVarSimplify.h>
# include <llvm/Transforms/Scalar/JumpThreading.h>
# include <llvm/Transforms/Scalar/LICM.h>
# include <llvm/Transforms/Scalar/LoopDeletion.h>
# include <llvm/Transforms/Scalar/LoopIdiomRecognize.h>
# include <llvm/Transforms/Scalar/LoopRotation.h>
# include <llvm/Transforms/Scalar/LoopUnrollPass.h>
# include <llvm/Transforms/Scalar/LowerExpectIntrinsic.h>
# include <llvm/Transforms/Scalar/MemCpyOptimizer.h>
# include <llvm/Transforms/Scalar/Reassociate.h>
# include <llvm/Transforms/Scalar/SCCP.h>
# include <llvm/Transforms/Scalar/SROA.h>
# include <llvm/Transforms/Scalar/SimpleLoopUnswitch.h>
# include <llvm/Transforms/Scalar/SimplifyCFG.h>
# include <llvm/Transforms/Scalar/TailRecursionElimination.h>
# include <llvm/Transforms/Utils/Mem2Reg.h>
#else
// Legacy pass manager
# include <llvm/Transforms/IPO/PassManagerBuilder.h>
#endif
// additional includes for PTX generation
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Transforms/Utils/SymbolRewriter.h>
OSL_NAMESPACE_ENTER
// Convert our cspan<> to llvm's ArrayRef.
template<class T>
inline llvm::ArrayRef<T>
toArrayRef(cspan<T> A)
{
return { A.data(), size_t(A.size()) };
}
template<typename T, size_t N>
llvm::ArrayRef<T>
toArrayRef(const T (&Arr)[N])
{
return llvm::ArrayRef<T>(Arr);
}
namespace pvt {
typedef llvm::SectionMemoryManager LLVMMemoryManager;
typedef llvm::Error LLVMErr;
namespace {
// NOTE: This is a COPY of something internal to LLVM, but since we destroy
// our LLVMMemoryManager via global variables we can't rely on the LLVM copy
// sticking around. Because of this, the variable must be declared _before_
// jitmm_hold so that the object stays valid until after we have destroyed
// all our memory managers.
struct DefaultMMapper final : public llvm::SectionMemoryManager::MemoryMapper {
llvm::sys::MemoryBlock allocateMappedMemory(
llvm::SectionMemoryManager::AllocationPurpose /*Purpose*/,
size_t NumBytes, const llvm::sys::MemoryBlock* const NearBlock,
unsigned Flags, std::error_code& EC) override
{
return llvm::sys::Memory::allocateMappedMemory(NumBytes, NearBlock,
Flags, EC);
}
std::error_code protectMappedMemory(const llvm::sys::MemoryBlock& Block,
unsigned Flags) override
{
return llvm::sys::Memory::protectMappedMemory(Block, Flags);
}
std::error_code releaseMappedMemory(llvm::sys::MemoryBlock& M) override
{
return llvm::sys::Memory::releaseMappedMemory(M);
}
};
static DefaultMMapper llvm_default_mapper;
static OIIO::spin_mutex llvm_global_mutex;
static bool setup_done = false;
static std::unique_ptr<std::vector<std::shared_ptr<LLVMMemoryManager>>>
jitmm_hold;
static int jit_mem_hold_users = 0;
#if OSL_LLVM_VERSION >= 120
llvm::raw_os_ostream raw_cout(std::cout);
#endif
}; // namespace
// ScopedJitMemoryUser will keep jitmm_hold alive until the last instance
// is gone then the it will be freed.
LLVM_Util::ScopedJitMemoryUser::ScopedJitMemoryUser()
{
OIIO::spin_lock lock(llvm_global_mutex);
if (jit_mem_hold_users == 0) {
OSL_ASSERT(!jitmm_hold);
jitmm_hold.reset(new std::vector<std::shared_ptr<LLVMMemoryManager>>());
}
++jit_mem_hold_users;
}
LLVM_Util::ScopedJitMemoryUser::~ScopedJitMemoryUser()
{
OIIO::spin_lock lock(llvm_global_mutex);
OSL_ASSERT(jit_mem_hold_users > 0);
--jit_mem_hold_users;
if (jit_mem_hold_users == 0) {
jitmm_hold.reset();
}
}
// We hold certain things (LLVM context and custom JIT memory manager)
// per thread and retained across LLVM_Util invocations.
struct LLVM_Util::PerThreadInfo::Impl {
Impl() {}
~Impl()
{
delete llvm_context;
// N.B. Do NOT delete the jitmm -- another thread may need the
// code! Don't worry, we stashed a pointer in jitmm_hold.
}
llvm::LLVMContext* llvm_context = nullptr;
LLVMMemoryManager* llvm_jitmm = nullptr;
};
LLVM_Util::PerThreadInfo::~PerThreadInfo()
{
// Make sure destructor to PerThreadInfoImpl is only called here
// where we know the definition of the owned PerThreadInfoImpl;
delete m_thread_info;
}
LLVM_Util::PerThreadInfo::Impl*
LLVM_Util::PerThreadInfo::get() const
{
if (!m_thread_info)
m_thread_info = new Impl();
return m_thread_info;
}
size_t
LLVM_Util::total_jit_memory_held()
{
// FIXME: This can't possibly be correct. It will always return 0,
// since jitmem is a local variable.
size_t jitmem = 0;
OIIO::spin_lock lock(llvm_global_mutex);
return jitmem;
}
/// MemoryManager - Create a shell that passes on requests
/// to a real LLVMMemoryManager underneath, but can be retained after the
/// dummy is destroyed. Also, we don't pass along any deallocations.
class LLVM_Util::MemoryManager final : public LLVMMemoryManager {
protected:
LLVMMemoryManager* mm; // the real one
public:
MemoryManager(LLVMMemoryManager* realmm) : mm(realmm) {}
void notifyObjectLoaded(llvm::ExecutionEngine* EE,
const llvm::object::ObjectFile& oi) override
{
mm->notifyObjectLoaded(EE, oi);
}
void notifyObjectLoaded(llvm::RuntimeDyld& RTDyld,
const llvm::object::ObjectFile& Obj) override
{
mm->notifyObjectLoaded(RTDyld, Obj);
}
void reserveAllocationSpace(
#if OSL_LLVM_VERSION >= 160
uintptr_t CodeSize, llvm::Align CodeAlign, uintptr_t RODataSize,
llvm::Align RODataAlign, uintptr_t RWDataSize, llvm::Align RWDataAlign
#else
uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize,
uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign
#endif
) override
{
return mm->reserveAllocationSpace(CodeSize, CodeAlign, RODataSize,
RODataAlign, RWDataSize, RWDataAlign);
}
bool needsToReserveAllocationSpace() override
{
return mm->needsToReserveAllocationSpace();
}
void invalidateInstructionCache() override
{
mm->invalidateInstructionCache();
}
llvm::JITSymbol findSymbol(const std::string& Name) override
{
return mm->findSymbol(Name);
}
uint64_t getSymbolAddressInLogicalDylib(const std::string& Name) override
{
return mm->getSymbolAddressInLogicalDylib(Name);
}
llvm::JITSymbol findSymbolInLogicalDylib(const std::string& Name) override
{
return mm->findSymbolInLogicalDylib(Name);
}
// Common
virtual ~MemoryManager() {}
void* getPointerToNamedFunction(const std::string& Name,
bool AbortOnFailure) override
{
return mm->getPointerToNamedFunction(Name, AbortOnFailure);
}
uint8_t* allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName) override
{
return mm->allocateCodeSection(Size, Alignment, SectionID, SectionName);
}
uint8_t* allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName,
bool IsReadOnly) override
{
return mm->allocateDataSection(Size, Alignment, SectionID, SectionName,
IsReadOnly);
}
void registerEHFrames(uint8_t* Addr, uint64_t LoadAddr,
size_t Size) override
{
mm->registerEHFrames(Addr, LoadAddr, Size);
}
void deregisterEHFrames() override { mm->deregisterEHFrames(); }
uint64_t getSymbolAddress(const std::string& Name) override
{
return mm->getSymbolAddress(Name);
}
bool finalizeMemory(std::string* ErrMsg) override
{
return mm->finalizeMemory(ErrMsg);
}
};
class LLVM_Util::IRBuilder final
: public llvm::IRBuilder<llvm::ConstantFolder,
llvm::IRBuilderDefaultInserter> {
typedef llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>
Base;
public:
IRBuilder(llvm::BasicBlock* TheBB) : Base(TheBB) {}
};
// New pass manager state, mainly here because these are template classes
// for which forward declarations in a public header are tricky.
struct LLVM_Util::NewPassManager {
#ifdef OSL_LLVM_NEW_PASS_MANAGER
llvm::LoopAnalysisManager loop_analysis_manager;
llvm::FunctionAnalysisManager function_analysis_manager;
llvm::CGSCCAnalysisManager cgscc_analysis_manager;
llvm::ModuleAnalysisManager module_analysis_manager;
llvm::ModulePassManager module_pass_manager;
#endif
};
struct SetCommandLineOptionsForLLVM {
SetCommandLineOptionsForLLVM()
{
// Use the command line options interface to toggle static hidden options for the llvm::LegacyPassManager
const char* argv[] = { "SetCommandLineOptionsForLLVM", "-debug-pass",
"Executions" };
llvm::cl::ParseCommandLineOptions(
std::extent<decltype(argv)>::value, argv,
"llvm util for Open Shading Language\n");
}
};
LLVM_Util::LLVM_Util(const PerThreadInfo& per_thread_info, int debuglevel,
int vector_width)
: m_debug(debuglevel)
, m_thread(NULL)
, m_llvm_context(NULL)
, m_llvm_module(NULL)
, m_builder(NULL)
, m_llvm_jitmm(NULL)
, m_current_function(NULL)
, m_llvm_module_passes(NULL)
, m_llvm_func_passes(NULL)
, m_new_pass_manager(NULL)
, m_llvm_exec(NULL)
, m_nvptx_target_machine(nullptr)
, m_vector_width(vector_width)
, m_llvm_type_native_mask(nullptr)
, mVTuneNotifier(nullptr)
, m_llvm_debug_builder(nullptr)
, mDebugCU(nullptr)
, mSubTypeForInlinedFunction(nullptr)
, m_ModuleIsFinalized(false)
, m_ModuleIsPruned(false)
, m_is_masking_required(false)
, m_masked_exit_count(0)
{
OSL_ASSERT(vector_width <= MaxSupportedSimdLaneCount);
SetupLLVM();
m_thread = per_thread_info.get();
OSL_ASSERT(m_thread);
{
OIIO::spin_lock lock(llvm_global_mutex);
if (!m_thread->llvm_context) {
m_thread->llvm_context = new llvm::LLVMContext();
#if OSL_LLVM_VERSION >= 150 && !defined(OSL_LLVM_OPAQUE_POINTERS)
m_thread->llvm_context->setOpaquePointers(false);
// FIXME: For now, keep using typed pointers. We're going to have
// to fix this and switch to opaque pointers by llvm 16.
#endif
//static SetCommandLineOptionsForLLVM sSetCommandLineOptionsForLLVM;
}
if (!m_thread->llvm_jitmm) {
m_thread->llvm_jitmm = new LLVMMemoryManager(&llvm_default_mapper);
OSL_DASSERT(m_thread->llvm_jitmm);
OSL_ASSERT(
jitmm_hold
&& "An instance of OSL::pvt::LLVM_Util::ScopedJitMemoryUser must exist with a longer lifetime than this LLVM_Util object");
jitmm_hold->emplace_back(m_thread->llvm_jitmm);
}
// Hold the REAL manager and use it as an argument later
m_llvm_jitmm = m_thread->llvm_jitmm;
}
OSL_ASSERT(m_thread->llvm_context);
m_llvm_context = m_thread->llvm_context;
// Set up aliases for types we use over and over
m_llvm_type_float = (llvm::Type*)llvm::Type::getFloatTy(*m_llvm_context);
m_llvm_type_double = (llvm::Type*)llvm::Type::getDoubleTy(*m_llvm_context);
m_llvm_type_int = (llvm::Type*)llvm::Type::getInt32Ty(*m_llvm_context);
m_llvm_type_int8 = (llvm::Type*)llvm::Type::getInt8Ty(*m_llvm_context);
m_llvm_type_int16 = (llvm::Type*)llvm::Type::getInt16Ty(*m_llvm_context);
m_llvm_type_int64 = (llvm::Type*)llvm::Type::getInt64Ty(*m_llvm_context);
if (sizeof(char*) == 4)
m_llvm_type_addrint = (llvm::Type*)llvm::Type::getInt32Ty(
*m_llvm_context);
else
m_llvm_type_addrint = (llvm::Type*)llvm::Type::getInt64Ty(
*m_llvm_context);
m_llvm_type_bool = (llvm::Type*)llvm::Type::getInt1Ty(*m_llvm_context);
m_llvm_type_char = (llvm::Type*)llvm::Type::getInt8Ty(*m_llvm_context);
m_llvm_type_longlong = (llvm::Type*)llvm::Type::getInt64Ty(*m_llvm_context);
m_llvm_type_void = (llvm::Type*)llvm::Type::getVoidTy(*m_llvm_context);
m_llvm_type_int_ptr = llvm::PointerType::get(m_llvm_type_int, 0);
m_llvm_type_int8_ptr = llvm::PointerType::get(m_llvm_type_int8, 0);
m_llvm_type_int64_ptr = llvm::PointerType::get(m_llvm_type_int64, 0);
m_llvm_type_bool_ptr = llvm::PointerType::get(m_llvm_type_bool, 0);
m_llvm_type_char_ptr = llvm::PointerType::get(m_llvm_type_char, 0);
m_llvm_type_void_ptr = m_llvm_type_char_ptr;
m_llvm_type_float_ptr = llvm::PointerType::get(m_llvm_type_float, 0);
m_llvm_type_longlong_ptr = llvm::PointerType::get(m_llvm_type_int64, 0);
m_llvm_type_double_ptr = llvm::PointerType::get(m_llvm_type_double, 0);
// A triple is a struct composed of 3 floats
std::vector<llvm::Type*> triplefields(3, m_llvm_type_float);
m_llvm_type_triple = type_struct(triplefields, "Vec3");
m_llvm_type_triple_ptr
= (llvm::PointerType*)llvm::PointerType::get(m_llvm_type_triple, 0);
// A matrix is a struct composed 16 floats
std::vector<llvm::Type*> matrixfields(16, m_llvm_type_float);
m_llvm_type_matrix = type_struct(matrixfields, "Matrix4");
m_llvm_type_matrix_ptr
= (llvm::PointerType*)llvm::PointerType::get(m_llvm_type_matrix, 0);
// Setup up wide aliases
// TODO: why are there casts to the base class llvm::Type *?
m_vector_width = OIIO::floor2(OIIO::clamp(m_vector_width, 4, 16));
m_llvm_type_wide_float = llvm_vector_type(m_llvm_type_float,
m_vector_width);
m_llvm_type_wide_double = llvm_vector_type(m_llvm_type_double,
m_vector_width);
m_llvm_type_wide_int = llvm_vector_type(m_llvm_type_int, m_vector_width);
m_llvm_type_wide_bool = llvm_vector_type(m_llvm_type_bool, m_vector_width);
m_llvm_type_wide_char = llvm_vector_type(m_llvm_type_char, m_vector_width);
m_llvm_type_wide_longlong = llvm_vector_type(m_llvm_type_longlong,
m_vector_width);
m_llvm_type_wide_char_ptr = llvm::PointerType::get(m_llvm_type_wide_char,
0);
m_llvm_type_wide_void_ptr = llvm_vector_type(m_llvm_type_void_ptr,
m_vector_width);
m_llvm_type_wide_int_ptr = llvm::PointerType::get(m_llvm_type_wide_int, 0);
m_llvm_type_wide_bool_ptr = llvm::PointerType::get(m_llvm_type_wide_bool,
0);
m_llvm_type_wide_float_ptr = llvm::PointerType::get(m_llvm_type_wide_float,
0);
// A triple is a struct composed of 3 floats
std::vector<llvm::Type*> triple_wide_fields(3, m_llvm_type_wide_float);
m_llvm_type_wide_triple = type_struct(triple_wide_fields, "WideVec3");
// A matrix is a struct composed 16 floats
std::vector<llvm::Type*> matrix_wide_fields(16, m_llvm_type_wide_float);
m_llvm_type_wide_matrix = type_struct(matrix_wide_fields, "WideMatrix4");
ustring_rep(m_ustring_rep); // setup ustring-related types
}
void
LLVM_Util::ustring_rep(UstringRep rep)
{
m_ustring_rep = rep;
m_llvm_type_real_ustring = m_llvm_type_int8_ptr;
if (m_ustring_rep == UstringRep::charptr) {
m_llvm_type_ustring = m_llvm_type_real_ustring;
} else {
OSL_ASSERT(m_ustring_rep == UstringRep::hash);
m_llvm_type_ustring = llvm::Type::getInt64Ty(*m_llvm_context);
}
m_llvm_type_ustring_ptr = llvm::PointerType::get(m_llvm_type_ustring, 0);
// Batched versions haven't been updated to handle hash yet.
// For now leave them using the real ustring regardless of UstringRep
m_llvm_type_wide_ustring = llvm_vector_type(m_llvm_type_real_ustring,
m_vector_width);
m_llvm_type_wide_ustring_ptr
= llvm::PointerType::get(m_llvm_type_wide_ustring, 0);
}
LLVM_Util::~LLVM_Util()
{
execengine(NULL);
delete m_llvm_module_passes;
delete m_llvm_func_passes;
delete m_new_pass_manager;
delete m_builder;
delete m_llvm_debug_builder;
delete m_nvptx_target_machine;
module(NULL);
// DO NOT delete m_llvm_jitmm; // just the dummy wrapper around the real MM
}
void
LLVM_Util::SetupLLVM()
{
OIIO::spin_lock lock(llvm_global_mutex);
if (setup_done)
return;
// Some global LLVM initialization for the first thread that
// gets here.
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllDisassemblers();
llvm::InitializeAllAsmPrinters();
llvm::InitializeAllAsmParsers();
LLVMLinkInMCJIT();
llvm::PassRegistry& registry = *llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(registry);
llvm::initializeScalarOpts(registry);
llvm::initializeIPO(registry);
llvm::initializeAnalysis(registry);
llvm::initializeTransformUtils(registry);
llvm::initializeInstCombine(registry);
#if OSL_LLVM_VERSION < 160
llvm::initializeInstrumentation(registry);
#endif
llvm::initializeGlobalISel(registry);
llvm::initializeTarget(registry);
llvm::initializeCodeGen(registry);
#ifndef OSL_LLVM_NEW_PASS_MANAGER
// LegacyPreventBitMasksFromBeingLiveinsToBasicBlocks
static llvm::RegisterPass<
LegacyPreventBitMasksFromBeingLiveinsToBasicBlocks<8>>
sRegCustomPass0(
"PreventBitMasksFromBeingLiveinsToBasicBlocks<8>",
"Prevent Bit Masks <8xi1> From Being Liveins To Basic Blocks Pass",
false /* Only looks at CFG */, false /* Analysis Pass */);
static llvm::RegisterPass<
LegacyPreventBitMasksFromBeingLiveinsToBasicBlocks<16>>
sRegCustomPass1(
"PreventBitMasksFromBeingLiveinsToBasicBlocks<16>",
"Prevent Bit Masks <16xi1> From Being Liveins To Basic Blocks Pass",
false /* Only looks at CFG */, false /* Analysis Pass */);
#endif
if (debug()) {
for (auto t : llvm::TargetRegistry::targets())
std::cout << "Target: '" << t.getName() << "' "
<< t.getShortDescription() << "\n";
std::cout << "\n";
}
setup_done = true;
}
llvm::Module*
LLVM_Util::new_module(const char* id)
{
return new llvm::Module(id, context());
}
bool
LLVM_Util::debug_is_enabled() const
{
return m_llvm_debug_builder != nullptr;
}
void
LLVM_Util::debug_setup_compilation_unit(const char* compile_unit_name)
{
OSL_ASSERT(debug_is_enabled());
OSL_ASSERT(mDebugCU == nullptr);
OSL_DEV_ONLY(std::cout << "debug_setup_compilation_unit" << std::endl);
constexpr const char* osl_identity = "OSL_v" OSL_LIBRARY_VERSION_STRING;
mDebugCU = m_llvm_debug_builder->createCompileUnit(
/*llvm::dwarf::DW_LANG_C*/
llvm::dwarf::DW_LANG_C_plus_plus,
m_llvm_debug_builder->createFile(compile_unit_name, // filename
"." // directory
),
osl_identity, // Identify the producer of debugging information and code. Usually this is a compiler version string.
true, // isOptimized
"<todo>", // This string lists command line options. This string is directly embedded in debug info output which may be used by a tool analyzing generated debugging information.
OSL_VERSION, // This indicates runtime version for languages like Objective-C
llvm::StringRef(), // SplitName = he name of the file that we'll split debug info out into.
llvm::DICompileUnit::DebugEmissionKind::
LineTablesOnly, // DICompileUnit::DebugEmissionKind
0, // The DWOId if this is a split skeleton compile unit.
false, // SplitDebugInlining = Whether to emit inline debug info.
true // DebugInfoForProfiling (default=false) = Whether to emit extra debug info for profile collection.
);
OSL_DEV_ONLY(std::cout << "created debug module for " << compile_unit_name
<< std::endl);
}
void
LLVM_Util::debug_push_function(const std::string& function_name,
OIIO::ustring sourcefile, int sourceline)
{
OSL_ASSERT(debug_is_enabled());
#ifdef OSL_DEV
std::cout << "debug_push_function function_name=" << function_name
<< " sourcefile=" << sourcefile << " sourceline=" << sourceline
<< std::endl;
#endif
llvm::DIFile* file = getOrCreateDebugFileFor(sourcefile.string());
const unsigned int method_scope_line = 0;
// Rather than use dummy function parameters, we'll just reuse
// the inlined subroutine type of void func(void).
// TODO: Added DIType * for BatchedShaderGlobals And Groupdata to be
// passed into this function so proper function type can be created.
#if 0
llvm::DISubroutineType *subType;
{
llvm::SmallVector<llvm::Metadata *, 8> EltTys;
//llvm::DIType *DblTy = KSTheDebugInfo.getDoubleTy();
llvm::DIType *debug_double_type = m_llvm_debug_builder->createBasicType(
"double", 64, llvm::dwarf::DW_ATE_float);
EltTys.push_back(debug_double_type);
EltTys.push_back(debug_double_type);
subType = m_llvm_debug_builder->createSubroutineType(
m_llvm_debug_builder->getOrCreateTypeArray(EltTys));
}
#endif
OSL_ASSERT(file);
llvm::DISubprogram* function = m_llvm_debug_builder->createFunction(
mDebugCU, // Scope
function_name.c_str(), // Name
/*function_name.c_str()*/ llvm::StringRef(), // Linkage Name
file, // File
static_cast<unsigned int>(sourceline), // Line Number
mSubTypeForInlinedFunction, // subroutine type
method_scope_line, // Scope Line
llvm::DINode::FlagPrototyped, // Flags
llvm::DISubprogram::toSPFlags(false /*isLocalToUnit*/,
true /*isDefinition*/,
false /*isOptimized*/));
OSL_ASSERT(mLexicalBlocks.empty());
current_function()->setSubprogram(function);
mLexicalBlocks.push_back(function);
}
void
LLVM_Util::debug_push_inlined_function(OIIO::ustring function_name,
OIIO::ustring sourcefile, int sourceline)
{
#ifdef OSL_DEV
std::cout << "debug_push_inlined_function function_name=" << function_name
<< " sourcefile=" << sourcefile << " sourceline=" << sourceline
<< std::endl;
#endif
OSL_ASSERT(debug_is_enabled());
OSL_ASSERT(m_builder);
OSL_ASSERT(m_builder->getCurrentDebugLocation().get() != NULL);
mInliningSites.push_back(m_builder->getCurrentDebugLocation().get());
llvm::DIFile* file = getOrCreateDebugFileFor(sourcefile.string());
unsigned int method_scope_line = 0;
OSL_ASSERT(getCurrentDebugScope());
llvm::DINode::DIFlags fnFlags = (llvm::DINode::DIFlags)(
llvm::DINode::FlagPrototyped | llvm::DINode::FlagNoReturn);
llvm::DISubprogram* function = nullptr;
function = m_llvm_debug_builder->createFunction(
mDebugCU, // Scope
function_name.c_str(), // Name
// We are inlined function so not sure supplying a linkage name
// makes sense
/*function_name.c_str()*/ llvm::StringRef(), // Linkage Name
file, // File
static_cast<unsigned int>(sourceline), // Line Number
mSubTypeForInlinedFunction, // subroutine type
method_scope_line, // Scope Line,
fnFlags,
llvm::DISubprogram::toSPFlags(true /*isLocalToUnit*/,
true /*isDefinition*/,
true /*false*/ /*isOptimized*/));
mLexicalBlocks.push_back(function);
}
void
LLVM_Util::debug_pop_inlined_function()
{
OSL_DEV_ONLY(std::cout << "debug_pop_inlined_function" << std::endl);
OSL_ASSERT(debug_is_enabled());
OSL_ASSERT(!mLexicalBlocks.empty());
llvm::DIScope* scope = mLexicalBlocks.back();
auto* existingLbf = llvm::dyn_cast<llvm::DILexicalBlockFile>(scope);
if (existingLbf) {
// Allow nesting of exactly one DILexicalBlockFile, unwrap it to a
// function.
scope = existingLbf->getScope();
OSL_DEV_ONLY(std::cout << "DILexicalBlockFile popped" << std::endl);
}
auto* function = llvm::dyn_cast<llvm::DISubprogram>(scope);
OSL_ASSERT(function);
mLexicalBlocks.pop_back();
m_llvm_debug_builder->finalizeSubprogram(function);
// Return debug location to where the function was inlined from.
// Necessary to avoid unnecessarily creating DILexicalBlockFile if the
// source file changed.
llvm::DILocation* location_inlined_at = mInliningSites.back();
OSL_ASSERT(location_inlined_at);
OSL_ASSERT(m_builder);
m_builder->SetCurrentDebugLocation(llvm::DebugLoc(location_inlined_at));
mInliningSites.pop_back();
}
void
LLVM_Util::debug_pop_function()
{
OSL_DEV_ONLY(std::cout << "debug_pop_function" << std::endl);
OSL_ASSERT(debug_is_enabled());
OSL_ASSERT(!mLexicalBlocks.empty());
llvm::DIScope* scope = mLexicalBlocks.back();
auto* existingLbf = llvm::dyn_cast<llvm::DILexicalBlockFile>(scope);
if (existingLbf) {
// Allow nesting of exactly one DILexicalBlockFile
// Unwrap it to a function
scope = existingLbf->getScope();
OSL_DEV_ONLY(std::cout << "DILexicalBlockFile popped" << std::endl);
}
auto* function = llvm::dyn_cast<llvm::DISubprogram>(scope);
OSL_ASSERT(function);
mLexicalBlocks.pop_back();
OSL_ASSERT(mLexicalBlocks.empty());
// Make sure our current debug location isn't pointing at a subprogram
// that has been finalized, point it back to the compilation unit
OSL_ASSERT(m_builder);
OSL_ASSERT(m_builder->getCurrentDebugLocation().get() != nullptr);
m_builder->SetCurrentDebugLocation(llvm::DILocation::get(
getCurrentDebugScope()->getContext(), static_cast<unsigned int>(1),
static_cast<unsigned int>(
0), /* column? we don't know it, may be worth tracking through osl->oso*/
getCurrentDebugScope()));
m_llvm_debug_builder->finalizeSubprogram(function);
}
void
LLVM_Util::debug_set_location(ustring sourcefile, int sourceline)
{
OSL_DEV_ONLY(std::cout << "LLVM_Util::debug_set_location:" << sourcefile
<< "(" << sourceline << ")" << std::endl);
OSL_ASSERT(debug_is_enabled());
OSL_ASSERT(
sourceline > 0
&& "GDB doesn't like 0 because its a nonsensical as a line number");
llvm::DIScope* sp = getCurrentDebugScope();
llvm::DILocation* inlineSite = getCurrentInliningSite();
OSL_ASSERT(sp != nullptr);
// If the file changed on us (due to an #include or inlined function
// that we missed) update the scope. As we do model inlined functions,
// don't expect this code path to be taken unless support for the
// functioncall_nr has been disabled.
if (sp->getFilename().compare(llvm::StringRef(sourcefile.c_str()))) {
llvm::DIFile* file = getOrCreateDebugFileFor(sourcefile.string());
// Don't nest DILexicalBlockFile's (don't allow DILexicalBlockFile's
// to be a parent to another DILexicalBlockFile's). Instead make the
// parent of the new DILexicalBlockFile the same as the existing
// DILexicalBlockFile's parent.
auto* existingLbf = llvm::dyn_cast<llvm::DILexicalBlockFile>(sp);
bool requiresNewLBF = true;
llvm::DIScope* parentScope;
if (existingLbf) {
parentScope = existingLbf->getScope();
// Only allow a single LBF, check for any logic bugs here
OSL_ASSERT(!llvm::dyn_cast<llvm::DILexicalBlockFile>(parentScope));
// If the parent scope has the same filename, no need to create
// a LBF we can directly use the parentScope.
if (!parentScope->getFilename().compare(
llvm::StringRef(sourcefile.c_str()))) {
// The parent scope has the same file name, we can just use
// it directly.
sp = parentScope;
requiresNewLBF = false;
}
} else {
parentScope = sp;
}
if (requiresNewLBF) {
OSL_ASSERT(parentScope != nullptr);
llvm::DILexicalBlockFile* lbf
= m_llvm_debug_builder->createLexicalBlockFile(parentScope,
file);
OSL_DEV_ONLY(std::cout << "createLexicalBlockFile" << std::endl);
sp = lbf;
}
// Swap out the current scope for a scope to the correct file
mLexicalBlocks.pop_back();
mLexicalBlocks.push_back(sp);
}
OSL_ASSERT(sp != NULL);
OSL_ASSERT(m_builder);
const llvm::DebugLoc& current_debug_location
= m_builder->getCurrentDebugLocation();
bool newDebugLocation = true;
if (current_debug_location) {
if (sourceline == static_cast<int>(current_debug_location.getLine())
&& sp == current_debug_location.getScope()
&& inlineSite == current_debug_location.getInlinedAt()) {
newDebugLocation = false;
}
}
if (newDebugLocation) {
llvm::DebugLoc debug_location = llvm::DILocation::get(
sp->getContext(), static_cast<unsigned int>(sourceline),
static_cast<unsigned int>(
0), /* column? we don't know it, may be worth tracking through osl->oso*/
sp, inlineSite);
m_builder->SetCurrentDebugLocation(debug_location);
}
}
namespace { // anonymous
inline bool
error_string(llvm::Error err, std::string* str)
{
if (err) {
if (str) {
llvm::handleAllErrors(std::move(err),
[str](llvm::ErrorInfoBase& E) {
*str += E.message();
});
}
return true;
}
return false;
}
} // anonymous namespace
llvm::Module*
LLVM_Util::module_from_bitcode(const char* bitcode, size_t size,
const std::string& name, std::string* err)
{
if (err)
err->clear();
typedef llvm::Expected<std::unique_ptr<llvm::Module>> ErrorOrModule;
llvm::MemoryBufferRef buf
= llvm::MemoryBufferRef(llvm::StringRef(bitcode, size), name);
#ifdef OSL_FORCE_BITCODE_PARSE
//
// None of the below seems to be an issue for 3.9 and above.
// In other JIT code I've seen a related issue, though only on OS X.
// So if it is still is broken somewhere between 3.6 and 3.8: instead of
// defining OSL_FORCE_BITCODE_PARSE (which is slower), you may want to
// try prepending a "_" in two methods above:
// LLVM_Util::MemoryManager::getPointerToNamedFunction
// LLVM_Util::MemoryManager::getSymbolAddress.
//
// Using MCJIT should not require unconditionally parsing
// the bitcode. But for now, when using getLazyBitcodeModule to
// lazily deserialize the bitcode, MCJIT is unable to find the
// called functions due to disagreement about whether a leading "_"
// is part of the symbol name.
ErrorOrModule ModuleOrErr = llvm::parseBitcodeFile(buf, context());
#else
ErrorOrModule ModuleOrErr = llvm::getLazyBitcodeModule(buf, context());
#endif
if (err) {