-
Notifications
You must be signed in to change notification settings - Fork 709
/
program_manager.cpp
2110 lines (1806 loc) · 81.6 KB
/
program_manager.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
//==------ program_manager.cpp --- SYCL program manager---------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <detail/config.hpp>
#include <detail/context_impl.hpp>
#include <detail/device_image_impl.hpp>
#include <detail/device_impl.hpp>
#include <detail/global_handler.hpp>
#include <detail/persistent_device_code_cache.hpp>
#include <detail/program_impl.hpp>
#include <detail/program_manager/program_manager.hpp>
#include <detail/spec_constant_impl.hpp>
#include <sycl/aspects.hpp>
#include <sycl/backend_types.hpp>
#include <sycl/context.hpp>
#include <sycl/detail/common.hpp>
#include <sycl/detail/os_util.hpp>
#include <sycl/detail/type_traits.hpp>
#include <sycl/detail/util.hpp>
#include <sycl/device.hpp>
#include <sycl/exception.hpp>
#include <sycl/ext/oneapi/experimental/spec_constant.hpp>
#include <sycl/stl.hpp>
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
namespace sycl {
__SYCL_INLINE_VER_NAMESPACE(_V1) {
namespace detail {
using ContextImplPtr = std::shared_ptr<sycl::detail::context_impl>;
static constexpr int DbgProgMgr = 0;
enum BuildState { BS_InProgress, BS_Done, BS_Failed };
static constexpr char UseSpvEnv[]("SYCL_USE_KERNEL_SPV");
/// This function enables ITT annotations in SPIR-V module by setting
/// a specialization constant if INTEL_LIBITTNOTIFY64 env variable is set.
static void enableITTAnnotationsIfNeeded(const RT::PiProgram &Prog,
const plugin &Plugin) {
if (SYCLConfig<INTEL_ENABLE_OFFLOAD_ANNOTATIONS>::get() != nullptr) {
constexpr char SpecValue = 1;
Plugin.call<PiApiKind::piextProgramSetSpecializationConstant>(
Prog, ITTSpecConstId, sizeof(char), &SpecValue);
}
}
ProgramManager &ProgramManager::getInstance() {
return GlobalHandler::instance().getProgramManager();
}
static RT::PiProgram
createBinaryProgram(const ContextImplPtr Context, const device &Device,
const unsigned char *Data, size_t DataLen,
const std::vector<pi_device_binary_property> Metadata) {
const detail::plugin &Plugin = Context->getPlugin();
#ifndef _NDEBUG
pi_uint32 NumDevices = 0;
Plugin.call<PiApiKind::piContextGetInfo>(Context->getHandleRef(),
PI_CONTEXT_INFO_NUM_DEVICES,
sizeof(NumDevices), &NumDevices,
/*param_value_size_ret=*/nullptr);
assert(NumDevices > 0 &&
"Only a single device is supported for AOT compilation");
#endif
RT::PiProgram Program;
const RT::PiDevice PiDevice = getSyclObjImpl(Device)->getHandleRef();
pi_int32 BinaryStatus = CL_SUCCESS;
Plugin.call<PiApiKind::piProgramCreateWithBinary>(
Context->getHandleRef(), 1 /*one binary*/, &PiDevice, &DataLen, &Data,
Metadata.size(), Metadata.data(), &BinaryStatus, &Program);
if (BinaryStatus != CL_SUCCESS) {
throw runtime_error("Creating program with binary failed.", BinaryStatus);
}
return Program;
}
static RT::PiProgram createSpirvProgram(const ContextImplPtr Context,
const unsigned char *Data,
size_t DataLen) {
RT::PiProgram Program = nullptr;
const detail::plugin &Plugin = Context->getPlugin();
Plugin.call<PiApiKind::piProgramCreate>(Context->getHandleRef(), Data,
DataLen, &Program);
return Program;
}
RTDeviceBinaryImage &
ProgramManager::getDeviceImage(OSModuleHandle M, const std::string &KernelName,
const context &Context, const device &Device,
bool JITCompilationIsRequired) {
if (DbgProgMgr > 0)
std::cerr << ">>> ProgramManager::getDeviceImage(" << M << ", \""
<< KernelName << "\", " << getRawSyclObjImpl(Context) << ", "
<< getRawSyclObjImpl(Device) << ", " << JITCompilationIsRequired
<< ")\n";
KernelSetId KSId = getKernelSetId(M, KernelName);
return getDeviceImage(M, KSId, Context, Device, JITCompilationIsRequired);
}
template <typename ExceptionT, typename RetT>
RetT *waitUntilBuilt(KernelProgramCache &Cache,
KernelProgramCache::BuildResult<RetT> *BuildResult) {
// any thread which will find nullptr in cache will wait until the pointer
// is not null anymore
Cache.waitUntilBuilt(*BuildResult, [BuildResult]() {
int State = BuildResult->State.load();
return State == BS_Done || State == BS_Failed;
});
if (BuildResult->Error.isFilledIn()) {
const KernelProgramCache::BuildError &Error = BuildResult->Error;
throw ExceptionT(Error.Msg, Error.Code);
}
RetT *Result = BuildResult->Ptr.load();
return Result;
}
/// Try to fetch entity (kernel or program) from cache. If there is no such
/// entity try to build it. Throw any exception build process may throw.
/// This method eliminates unwanted builds by employing atomic variable with
/// build state and waiting until the entity is built in another thread.
/// If the building thread has failed the awaiting thread will fail either.
/// Exception thrown by build procedure are rethrown.
///
/// \tparam RetT type of entity to get
/// \tparam ExceptionT type of exception to throw on awaiting thread if the
/// building thread fails build step.
/// \tparam KeyT key (in cache) to fetch built entity with
/// \tparam AcquireFT type of function which will acquire the locked version of
/// the cache. Accept reference to KernelProgramCache.
/// \tparam GetCacheFT type of function which will fetch proper cache from
/// locked version. Accepts reference to locked version of cache.
/// \tparam BuildFT type of function which will build the entity if it is not in
/// cache. Accepts nothing. Return pointer to built entity.
///
/// \return a pointer to cached build result, return value must not be nullptr.
template <typename RetT, typename ExceptionT, typename KeyT, typename AcquireFT,
typename GetCacheFT, typename BuildFT>
KernelProgramCache::BuildResult<RetT> *
getOrBuild(KernelProgramCache &KPCache, KeyT &&CacheKey, AcquireFT &&Acquire,
GetCacheFT &&GetCache, BuildFT &&Build) {
bool InsertionTookPlace;
KernelProgramCache::BuildResult<RetT> *BuildResult;
{
auto LockedCache = Acquire(KPCache);
auto &Cache = GetCache(LockedCache);
auto Inserted =
Cache.emplace(std::piecewise_construct, std::forward_as_tuple(CacheKey),
std::forward_as_tuple(nullptr, BS_InProgress));
InsertionTookPlace = Inserted.second;
BuildResult = &Inserted.first->second;
}
// no insertion took place, thus some other thread has already inserted smth
// in the cache
if (!InsertionTookPlace) {
for (;;) {
RetT *Result = waitUntilBuilt<ExceptionT>(KPCache, BuildResult);
if (Result)
return BuildResult;
// Previous build is failed. There was no SYCL exception though.
// We might try to build once more.
int Expected = BS_Failed;
int Desired = BS_InProgress;
if (BuildResult->State.compare_exchange_strong(Expected, Desired))
break; // this thread is the building thread now
}
}
// only the building thread will run this
try {
RetT *Desired = Build();
#ifndef NDEBUG
RetT *Expected = nullptr;
if (!BuildResult->Ptr.compare_exchange_strong(Expected, Desired))
// We've got a funny story here
assert(false && "We've build an entity that is already have been built.");
#else
BuildResult->Ptr.store(Desired);
#endif
{
// Even if shared variable is atomic, it must be modified under the mutex
// in order to correctly publish the modification to the waiting thread
std::lock_guard<std::mutex> Lock(BuildResult->MBuildResultMutex);
BuildResult->State.store(BS_Done);
}
KPCache.notifyAllBuild(*BuildResult);
return BuildResult;
} catch (const exception &Ex) {
BuildResult->Error.Msg = Ex.what();
BuildResult->Error.Code = Ex.get_cl_code();
{
std::lock_guard<std::mutex> Lock(BuildResult->MBuildResultMutex);
BuildResult->State.store(BS_Failed);
}
KPCache.notifyAllBuild(*BuildResult);
std::rethrow_exception(std::current_exception());
} catch (...) {
{
std::lock_guard<std::mutex> Lock(BuildResult->MBuildResultMutex);
BuildResult->State.store(BS_Failed);
}
KPCache.notifyAllBuild(*BuildResult);
std::rethrow_exception(std::current_exception());
}
}
// TODO replace this with a new PI API function
static bool isDeviceBinaryTypeSupported(const context &C,
RT::PiDeviceBinaryType Format) {
// All formats except PI_DEVICE_BINARY_TYPE_SPIRV are supported.
if (Format != PI_DEVICE_BINARY_TYPE_SPIRV)
return true;
const backend ContextBackend =
detail::getSyclObjImpl(C)->getPlugin().getBackend();
// The CUDA backend cannot use SPIR-V
if (ContextBackend == backend::ext_oneapi_cuda)
return false;
std::vector<device> Devices = C.get_devices();
// Program type is SPIR-V, so we need a device compiler to do JIT.
for (const device &D : Devices) {
if (!D.get_info<info::device::is_compiler_available>())
return false;
}
// OpenCL 2.1 and greater require clCreateProgramWithIL
if (ContextBackend == backend::opencl) {
std::string ver = C.get_platform().get_info<info::platform::version>();
if (ver.find("OpenCL 1.0") == std::string::npos &&
ver.find("OpenCL 1.1") == std::string::npos &&
ver.find("OpenCL 1.2") == std::string::npos &&
ver.find("OpenCL 2.0") == std::string::npos)
return true;
}
for (const device &D : Devices) {
// We need cl_khr_il_program extension to be present
// and we can call clCreateProgramWithILKHR using the extension
std::vector<std::string> Extensions =
D.get_info<info::device::extensions>();
if (Extensions.end() ==
std::find(Extensions.begin(), Extensions.end(), "cl_khr_il_program"))
return false;
}
return true;
}
static const char *getFormatStr(RT::PiDeviceBinaryType Format) {
switch (Format) {
case PI_DEVICE_BINARY_TYPE_NONE:
return "none";
case PI_DEVICE_BINARY_TYPE_NATIVE:
return "native";
case PI_DEVICE_BINARY_TYPE_SPIRV:
return "SPIR-V";
case PI_DEVICE_BINARY_TYPE_LLVMIR_BITCODE:
return "LLVM IR";
}
assert(false && "Unknown device image format");
return "unknown";
}
RT::PiProgram ProgramManager::createPIProgram(const RTDeviceBinaryImage &Img,
const context &Context,
const device &Device) {
if (DbgProgMgr > 0)
std::cerr << ">>> ProgramManager::createPIProgram(" << &Img << ", "
<< getRawSyclObjImpl(Context) << ", " << getRawSyclObjImpl(Device)
<< ")\n";
const pi_device_binary_struct &RawImg = Img.getRawData();
// perform minimal sanity checks on the device image and the descriptor
if (RawImg.BinaryEnd < RawImg.BinaryStart) {
throw runtime_error("Malformed device program image descriptor",
PI_ERROR_INVALID_VALUE);
}
if (RawImg.BinaryEnd == RawImg.BinaryStart) {
throw runtime_error("Invalid device program image: size is zero",
PI_ERROR_INVALID_VALUE);
}
size_t ImgSize = Img.getSize();
// TODO if the binary image is a part of the fat binary, the clang
// driver should have set proper format option to the
// clang-offload-wrapper. The fix depends on AOT compilation
// implementation, so will be implemented together with it.
// Img->Format can't be updated as it is inside of the in-memory
// OS module binary.
RT::PiDeviceBinaryType Format = Img.getFormat();
if (Format == PI_DEVICE_BINARY_TYPE_NONE)
Format = pi::getBinaryImageFormat(RawImg.BinaryStart, ImgSize);
// RT::PiDeviceBinaryType Format = Img->Format;
// assert(Format != PI_DEVICE_BINARY_TYPE_NONE && "Image format not set");
if (!isDeviceBinaryTypeSupported(Context, Format))
throw feature_not_supported(
"SPIR-V online compilation is not supported in this context",
PI_ERROR_INVALID_OPERATION);
// Get program metadata from properties
auto ProgMetadata = Img.getProgramMetadata();
std::vector<pi_device_binary_property> ProgMetadataVector{
ProgMetadata.begin(), ProgMetadata.end()};
// Load the image
const ContextImplPtr Ctx = getSyclObjImpl(Context);
RT::PiProgram Res = Format == PI_DEVICE_BINARY_TYPE_SPIRV
? createSpirvProgram(Ctx, RawImg.BinaryStart, ImgSize)
: createBinaryProgram(Ctx, Device, RawImg.BinaryStart,
ImgSize, ProgMetadataVector);
{
std::lock_guard<std::mutex> Lock(MNativeProgramsMutex);
// associate the PI program with the image it was created for
NativePrograms[Res] = &Img;
}
if (DbgProgMgr > 1)
std::cerr << "created program: " << Res
<< "; image format: " << getFormatStr(Format) << "\n";
return Res;
}
static void appendLinkOptionsFromImage(std::string &LinkOpts,
const RTDeviceBinaryImage &Img) {
static const char *LinkOptsEnv = SYCLConfig<SYCL_PROGRAM_LINK_OPTIONS>::get();
// Update only if link options are not overwritten by environment variable
if (!LinkOptsEnv) {
const char *TemporaryStr = Img.getLinkOptions();
if (TemporaryStr != nullptr) {
if (!LinkOpts.empty())
LinkOpts += " ";
LinkOpts += std::string(TemporaryStr);
}
}
}
static bool getUint32PropAsBool(const RTDeviceBinaryImage &Img,
const char *PropName) {
pi_device_binary_property Prop = Img.getProperty(PropName);
return Prop && (DeviceBinaryProperty(Prop).asUint32() != 0);
}
static void appendCompileOptionsFromImage(std::string &CompileOpts,
const RTDeviceBinaryImage &Img) {
// Build options are overridden if environment variables are present.
// Environment variables are not changed during program lifecycle so it
// is reasonable to use static here to read them only once.
static const char *CompileOptsEnv =
SYCLConfig<SYCL_PROGRAM_COMPILE_OPTIONS>::get();
// Update only if compile options are not overwritten by environment
// variable
if (!CompileOptsEnv) {
if (!CompileOpts.empty())
CompileOpts += " ";
const char *TemporaryStr = Img.getCompileOptions();
if (TemporaryStr != nullptr)
CompileOpts += std::string(TemporaryStr);
}
bool isEsimdImage = getUint32PropAsBool(Img, "isEsimdImage");
// TODO: Remove isDoubleGRF check in next ABI break
bool isLargeGRF = getUint32PropAsBool(Img, "isLargeGRF") ||
getUint32PropAsBool(Img, "isDoubleGRF");
// The -vc-codegen option is always preserved for ESIMD kernels, regardless
// of the contents SYCL_PROGRAM_COMPILE_OPTIONS environment variable.
if (isEsimdImage) {
if (!CompileOpts.empty())
CompileOpts += " ";
CompileOpts += "-vc-codegen";
// Allow warning and performance hints from vc/finalizer if the RT warning
// level is at least 1.
if (detail::SYCLConfig<detail::SYCL_RT_WARNING_LEVEL>::get() == 0)
CompileOpts += " -disable-finalizer-msg";
}
if (isLargeGRF) {
if (!CompileOpts.empty())
CompileOpts += " ";
// TODO: Always use -ze-opt-large-register-file once IGC VC bug ignoring it
// is fixed
CompileOpts += isEsimdImage ? "-doubleGRF" : "-ze-opt-large-register-file";
}
}
static void applyOptionsFromImage(std::string &CompileOpts,
std::string &LinkOpts,
const RTDeviceBinaryImage &Img) {
appendCompileOptionsFromImage(CompileOpts, Img);
appendLinkOptionsFromImage(LinkOpts, Img);
}
static void applyCompileOptionsFromEnvironment(std::string &CompileOpts) {
// Environment variables are not changed during program lifecycle so it
// is reasonable to use static here to read them only once.
static const char *CompileOptsEnv =
SYCLConfig<SYCL_PROGRAM_COMPILE_OPTIONS>::get();
if (CompileOptsEnv) {
CompileOpts = CompileOptsEnv;
}
}
static void applyLinkOptionsFromEnvironment(std::string &LinkOpts) {
// Environment variables are not changed during program lifecycle so it
// is reasonable to use static here to read them only once.
static const char *LinkOptsEnv = SYCLConfig<SYCL_PROGRAM_LINK_OPTIONS>::get();
if (LinkOptsEnv) {
LinkOpts = LinkOptsEnv;
}
}
static void applyOptionsFromEnvironment(std::string &CompileOpts,
std::string &LinkOpts) {
// Build options are overridden if environment variables are present.
applyCompileOptionsFromEnvironment(CompileOpts);
applyLinkOptionsFromEnvironment(LinkOpts);
}
std::pair<RT::PiProgram, bool> ProgramManager::getOrCreatePIProgram(
const RTDeviceBinaryImage &Img, const context &Context,
const device &Device, const std::string &CompileAndLinkOptions,
SerializedObj SpecConsts) {
RT::PiProgram NativePrg;
auto BinProg = PersistentDeviceCodeCache::getItemFromDisc(
Device, Img, SpecConsts, CompileAndLinkOptions);
if (BinProg.size()) {
// Get program metadata from properties
auto ProgMetadata = Img.getProgramMetadata();
std::vector<pi_device_binary_property> ProgMetadataVector{
ProgMetadata.begin(), ProgMetadata.end()};
// TODO: Build for multiple devices once supported by program manager
NativePrg = createBinaryProgram(getSyclObjImpl(Context), Device,
(const unsigned char *)BinProg[0].data(),
BinProg[0].size(), ProgMetadataVector);
} else {
NativePrg = createPIProgram(Img, Context, Device);
}
return {NativePrg, BinProg.size()};
}
/// Emits information about built programs if the appropriate contitions are
/// met, namely when SYCL_RT_WARNING_LEVEL is greater than or equal to 2.
static void emitBuiltProgramInfo(const pi_program &Prog,
const ContextImplPtr &Context) {
if (SYCLConfig<SYCL_RT_WARNING_LEVEL>::get() >= 2) {
std::string ProgramBuildLog =
ProgramManager::getProgramBuildLog(Prog, Context);
std::clog << ProgramBuildLog << std::endl;
}
}
RT::PiProgram ProgramManager::getBuiltPIProgram(
OSModuleHandle M, const ContextImplPtr &ContextImpl,
const DeviceImplPtr &DeviceImpl, const std::string &KernelName,
const program_impl *Prg, bool JITCompilationIsRequired) {
// TODO: Make sure that KSIds will be different for the case when the same
// kernel built with different options is present in the fat binary.
KernelSetId KSId = getKernelSetId(M, KernelName);
using PiProgramT = KernelProgramCache::PiProgramT;
using ProgramCacheT = KernelProgramCache::ProgramCacheT;
KernelProgramCache &Cache = ContextImpl->getKernelProgramCache();
auto AcquireF = [](KernelProgramCache &Cache) {
return Cache.acquireCachedPrograms();
};
auto GetF = [](const Locked<ProgramCacheT> &LockedCache) -> ProgramCacheT & {
return LockedCache.get();
};
std::string CompileOpts;
std::string LinkOpts;
if (Prg) {
CompileOpts = Prg->get_build_options();
}
applyOptionsFromEnvironment(CompileOpts, LinkOpts);
SerializedObj SpecConsts;
if (Prg)
Prg->stableSerializeSpecConstRegistry(SpecConsts);
// Check if we can optimize program builds for sub-devices by using a program
// built for the root device
DeviceImplPtr RootDevImpl = DeviceImpl;
while (!RootDevImpl->isRootDevice()) {
auto ParentDev = detail::getSyclObjImpl(
RootDevImpl->get_info<info::device::parent_device>());
// Sharing is allowed within a single context only
if (!ContextImpl->hasDevice(ParentDev))
break;
RootDevImpl = ParentDev;
}
pi_bool MustBuildOnSubdevice = PI_TRUE;
ContextImpl->getPlugin().call<PiApiKind::piDeviceGetInfo>(
RootDevImpl->getHandleRef(), PI_DEVICE_INFO_BUILD_ON_SUBDEVICE,
sizeof(pi_bool), &MustBuildOnSubdevice, nullptr);
DeviceImplPtr Dev =
(MustBuildOnSubdevice == PI_TRUE) ? DeviceImpl : RootDevImpl;
auto Context = createSyclObjFromImpl<context>(ContextImpl);
auto Device = createSyclObjFromImpl<device>(Dev);
const RTDeviceBinaryImage &Img =
getDeviceImage(M, KSId, Context, Device, JITCompilationIsRequired);
// Check that device supports all aspects used by the kernel
const RTDeviceBinaryImage::PropertyRange &ARange =
Img.getDeviceRequirements();
#define __SYCL_ASPECT(ASPECT, ID) \
case aspect::ASPECT: \
return #ASPECT;
#define __SYCL_ASPECT_DEPRECATED(ASPECT, ID, MESSAGE) __SYCL_ASPECT(ASPECT, ID)
// We don't need "case aspect::usm_allocator" here because it will duplicate
// "case aspect::usm_system_allocations", therefore leave this macro empty
#define __SYCL_ASPECT_DEPRECATED_ALIAS(ASPECT, ID, MESSAGE)
auto getAspectNameStr = [](aspect AspectNum) -> std::string {
switch (AspectNum) {
#include <sycl/info/aspects.def>
#include <sycl/info/aspects_deprecated.def>
}
throw sycl::exception(errc::kernel_not_supported,
"Unknown aspect " +
std::to_string(static_cast<unsigned>(AspectNum)));
};
#undef __SYCL_ASPECT_DEPRECATED_ALIAS
#undef __SYCL_ASPECT_DEPRECATED
#undef __SYCL_ASPECT
for (RTDeviceBinaryImage::PropertyRange::ConstIterator It : ARange) {
using namespace std::literals;
if ((*It)->Name != "aspects"sv)
continue;
ByteArray Aspects = DeviceBinaryProperty(*It).asByteArray();
// 8 because we need to skip 64-bits of size of the byte array
auto *AIt = reinterpret_cast<const std::uint32_t *>(&Aspects[8]);
auto *AEnd =
reinterpret_cast<const std::uint32_t *>(&Aspects[0] + Aspects.size());
while (AIt != AEnd) {
auto Aspect = static_cast<aspect>(*AIt);
if (!Dev->has(Aspect))
throw sycl::exception(errc::kernel_not_supported,
"Required aspect " + getAspectNameStr(Aspect) +
" is not supported on the device");
++AIt;
}
}
auto BuildF = [this, &Img, &Context, &ContextImpl, &Device, Prg, &CompileOpts,
&LinkOpts, SpecConsts] {
applyOptionsFromImage(CompileOpts, LinkOpts, Img);
const detail::plugin &Plugin = ContextImpl->getPlugin();
auto [NativePrg, DeviceCodeWasInCache] = getOrCreatePIProgram(
Img, Context, Device, CompileOpts + LinkOpts, SpecConsts);
if (!DeviceCodeWasInCache) {
if (Prg)
flushSpecConstants(*Prg, NativePrg, &Img);
if (Img.supportsSpecConstants())
enableITTAnnotationsIfNeeded(NativePrg, Plugin);
}
ProgramPtr ProgramManaged(
NativePrg, Plugin.getPiPlugin().PiFunctionTable.piProgramRelease);
// Link a fallback implementation of device libraries if they are not
// supported by a device compiler.
// Pre-compiled programs (after AOT compilation or read from persitent
// cache) are supposed to be already linked.
// If device image is not SPIR-V, DeviceLibReqMask will be 0 which means
// no fallback device library will be linked.
uint32_t DeviceLibReqMask = 0;
if (!DeviceCodeWasInCache &&
Img.getFormat() == PI_DEVICE_BINARY_TYPE_SPIRV &&
!SYCLConfig<SYCL_DEVICELIB_NO_FALLBACK>::get())
DeviceLibReqMask = getDeviceLibReqMask(Img);
ProgramPtr BuiltProgram =
build(std::move(ProgramManaged), ContextImpl, CompileOpts, LinkOpts,
getRawSyclObjImpl(Device)->getHandleRef(), DeviceLibReqMask);
emitBuiltProgramInfo(BuiltProgram.get(), ContextImpl);
{
std::lock_guard<std::mutex> Lock(MNativeProgramsMutex);
NativePrograms[BuiltProgram.get()] = &Img;
}
// Save program to persistent cache if it is not there
if (!DeviceCodeWasInCache)
PersistentDeviceCodeCache::putItemToDisc(
Device, Img, SpecConsts, CompileOpts + LinkOpts, BuiltProgram.get());
return BuiltProgram.release();
};
const RT::PiDevice PiDevice = Dev->getHandleRef();
uint32_t ImgId = Img.getImageID();
auto BuildResult = getOrBuild<PiProgramT, compile_program_error>(
Cache,
std::make_pair(std::make_pair(std::move(SpecConsts), ImgId),
std::make_pair(PiDevice, CompileOpts + LinkOpts)),
AcquireF, GetF, BuildF);
// getOrBuild is not supposed to return nullptr
assert(BuildResult != nullptr && "Invalid build result");
return BuildResult->Ptr.load();
}
std::tuple<RT::PiKernel, std::mutex *, RT::PiProgram>
ProgramManager::getOrCreateKernel(OSModuleHandle M,
const ContextImplPtr &ContextImpl,
const DeviceImplPtr &DeviceImpl,
const std::string &KernelName,
const program_impl *Prg) {
if (DbgProgMgr > 0) {
std::cerr << ">>> ProgramManager::getOrCreateKernel(" << M << ", "
<< ContextImpl.get() << ", " << DeviceImpl.get() << ", "
<< KernelName << ")\n";
}
using PiKernelT = KernelProgramCache::PiKernelT;
using KernelCacheT = KernelProgramCache::KernelCacheT;
using KernelByNameT = KernelProgramCache::KernelByNameT;
KernelProgramCache &Cache = ContextImpl->getKernelProgramCache();
std::string CompileOpts, LinkOpts;
SerializedObj SpecConsts;
if (Prg) {
CompileOpts = Prg->get_build_options();
Prg->stableSerializeSpecConstRegistry(SpecConsts);
}
applyOptionsFromEnvironment(CompileOpts, LinkOpts);
const RT::PiDevice PiDevice = DeviceImpl->getHandleRef();
auto key = std::make_tuple(std::move(SpecConsts), M, PiDevice,
CompileOpts + LinkOpts, KernelName);
auto ret_tuple = Cache.tryToGetKernelFast(key);
if (std::get<0>(ret_tuple))
return ret_tuple;
RT::PiProgram Program =
getBuiltPIProgram(M, ContextImpl, DeviceImpl, KernelName, Prg);
auto AcquireF = [](KernelProgramCache &Cache) {
return Cache.acquireKernelsPerProgramCache();
};
auto GetF =
[&Program](const Locked<KernelCacheT> &LockedCache) -> KernelByNameT & {
return LockedCache.get()[Program];
};
auto BuildF = [&Program, &KernelName, &ContextImpl] {
PiKernelT *Result = nullptr;
const detail::plugin &Plugin = ContextImpl->getPlugin();
Plugin.call<errc::kernel_not_supported, PiApiKind::piKernelCreate>(
Program, KernelName.c_str(), &Result);
// Some PI Plugins (like OpenCL) require this call to enable USM
// For others, PI will turn this into a NOP.
Plugin.call<PiApiKind::piKernelSetExecInfo>(Result, PI_USM_INDIRECT_ACCESS,
sizeof(pi_bool), &PI_TRUE);
return Result;
};
auto BuildResult = getOrBuild<PiKernelT, invalid_object_error>(
Cache, KernelName, AcquireF, GetF, BuildF);
// getOrBuild is not supposed to return nullptr
assert(BuildResult != nullptr && "Invalid build result");
auto ret_val = std::make_tuple(BuildResult->Ptr.load(),
&(BuildResult->MBuildResultMutex), Program);
Cache.saveKernel(key, ret_val);
return ret_val;
}
RT::PiProgram
ProgramManager::getPiProgramFromPiKernel(RT::PiKernel Kernel,
const ContextImplPtr Context) {
RT::PiProgram Program;
const detail::plugin &Plugin = Context->getPlugin();
Plugin.call<PiApiKind::piKernelGetInfo>(
Kernel, PI_KERNEL_INFO_PROGRAM, sizeof(RT::PiProgram), &Program, nullptr);
return Program;
}
std::string ProgramManager::getProgramBuildLog(const RT::PiProgram &Program,
const ContextImplPtr Context) {
size_t PIDevicesSize = 0;
const detail::plugin &Plugin = Context->getPlugin();
Plugin.call<PiApiKind::piProgramGetInfo>(Program, PI_PROGRAM_INFO_DEVICES, 0,
nullptr, &PIDevicesSize);
std::vector<RT::PiDevice> PIDevices(PIDevicesSize / sizeof(RT::PiDevice));
Plugin.call<PiApiKind::piProgramGetInfo>(Program, PI_PROGRAM_INFO_DEVICES,
PIDevicesSize, PIDevices.data(),
nullptr);
std::string Log = "The program was built for " +
std::to_string(PIDevices.size()) + " devices";
for (RT::PiDevice &Device : PIDevices) {
std::string DeviceBuildInfoString;
size_t DeviceBuildInfoStrSize = 0;
Plugin.call<PiApiKind::piProgramGetBuildInfo>(
Program, Device, PI_PROGRAM_BUILD_INFO_LOG, 0, nullptr,
&DeviceBuildInfoStrSize);
if (DeviceBuildInfoStrSize > 0) {
std::vector<char> DeviceBuildInfo(DeviceBuildInfoStrSize);
Plugin.call<PiApiKind::piProgramGetBuildInfo>(
Program, Device, PI_PROGRAM_BUILD_INFO_LOG, DeviceBuildInfoStrSize,
DeviceBuildInfo.data(), nullptr);
DeviceBuildInfoString = std::string(DeviceBuildInfo.data());
}
std::string DeviceNameString;
size_t DeviceNameStrSize = 0;
Plugin.call<PiApiKind::piDeviceGetInfo>(Device, PI_DEVICE_INFO_NAME, 0,
nullptr, &DeviceNameStrSize);
if (DeviceNameStrSize > 0) {
std::vector<char> DeviceName(DeviceNameStrSize);
Plugin.call<PiApiKind::piDeviceGetInfo>(Device, PI_DEVICE_INFO_NAME,
DeviceNameStrSize,
DeviceName.data(), nullptr);
DeviceNameString = std::string(DeviceName.data());
}
Log += "\nBuild program log for '" + DeviceNameString + "':\n" +
DeviceBuildInfoString;
}
return Log;
}
// TODO device libraries may use scpecialization constants, manifest files, etc.
// To support that they need to be delivered in a different container - so that
// pi_device_binary_struct can be created for each of them.
static bool loadDeviceLib(const ContextImplPtr Context, const char *Name,
RT::PiProgram &Prog) {
std::string LibSyclDir = OSUtil::getCurrentDSODir();
std::ifstream File(LibSyclDir + OSUtil::DirSep + Name,
std::ifstream::in | std::ifstream::binary);
if (!File.good()) {
return false;
}
File.seekg(0, std::ios::end);
size_t FileSize = File.tellg();
File.seekg(0, std::ios::beg);
std::vector<char> FileContent(FileSize);
File.read(&FileContent[0], FileSize);
File.close();
Prog =
createSpirvProgram(Context, (unsigned char *)&FileContent[0], FileSize);
return Prog != nullptr;
}
static const char *getDeviceLibFilename(DeviceLibExt Extension) {
switch (Extension) {
case DeviceLibExt::cl_intel_devicelib_assert:
return "libsycl-fallback-cassert.spv";
case DeviceLibExt::cl_intel_devicelib_math:
return "libsycl-fallback-cmath.spv";
case DeviceLibExt::cl_intel_devicelib_math_fp64:
return "libsycl-fallback-cmath-fp64.spv";
case DeviceLibExt::cl_intel_devicelib_complex:
return "libsycl-fallback-complex.spv";
case DeviceLibExt::cl_intel_devicelib_complex_fp64:
return "libsycl-fallback-complex-fp64.spv";
case DeviceLibExt::cl_intel_devicelib_cstring:
return "libsycl-fallback-cstring.spv";
case DeviceLibExt::cl_intel_devicelib_imf:
return "libsycl-fallback-imf.spv";
case DeviceLibExt::cl_intel_devicelib_imf_fp64:
return "libsycl-fallback-imf-fp64.spv";
case DeviceLibExt::cl_intel_devicelib_imf_bf16:
return "libsycl-fallback-imf-bf16.spv";
}
throw compile_program_error("Unhandled (new?) device library extension",
PI_ERROR_INVALID_OPERATION);
}
static const char *getDeviceLibExtensionStr(DeviceLibExt Extension) {
switch (Extension) {
case DeviceLibExt::cl_intel_devicelib_assert:
return "cl_intel_devicelib_assert";
case DeviceLibExt::cl_intel_devicelib_math:
return "cl_intel_devicelib_math";
case DeviceLibExt::cl_intel_devicelib_math_fp64:
return "cl_intel_devicelib_math_fp64";
case DeviceLibExt::cl_intel_devicelib_complex:
return "cl_intel_devicelib_complex";
case DeviceLibExt::cl_intel_devicelib_complex_fp64:
return "cl_intel_devicelib_complex_fp64";
case DeviceLibExt::cl_intel_devicelib_cstring:
return "cl_intel_devicelib_cstring";
case DeviceLibExt::cl_intel_devicelib_imf:
return "cl_intel_devicelib_imf";
case DeviceLibExt::cl_intel_devicelib_imf_fp64:
return "cl_intel_devicelib_imf_fp64";
case DeviceLibExt::cl_intel_devicelib_imf_bf16:
return "cl_intel_devicelib_imf_bf16";
}
throw compile_program_error("Unhandled (new?) device library extension",
PI_ERROR_INVALID_OPERATION);
}
static RT::PiProgram loadDeviceLibFallback(const ContextImplPtr Context,
DeviceLibExt Extension,
const RT::PiDevice &Device) {
const char *LibFileName = getDeviceLibFilename(Extension);
auto LockedCache = Context->acquireCachedLibPrograms();
auto CachedLibPrograms = LockedCache.get();
auto CacheResult = CachedLibPrograms.emplace(
std::make_pair(std::make_pair(Extension, Device), nullptr));
bool Cached = !CacheResult.second;
auto LibProgIt = CacheResult.first;
RT::PiProgram &LibProg = LibProgIt->second;
if (Cached)
return LibProg;
if (!loadDeviceLib(Context, LibFileName, LibProg)) {
CachedLibPrograms.erase(LibProgIt);
throw compile_program_error(std::string("Failed to load ") + LibFileName,
PI_ERROR_INVALID_VALUE);
}
const detail::plugin &Plugin = Context->getPlugin();
// TODO no spec constants are used in the std libraries, support in the future
RT::PiResult Error = Plugin.call_nocheck<PiApiKind::piProgramCompile>(
LibProg,
/*num devices = */ 1, &Device,
// Do not use compile options for library programs: it is not clear
// if user options (image options) are supposed to be applied to
// library program as well, and what actually happens to a SPIR-V
// program if we apply them.
"", 0, nullptr, nullptr, nullptr, nullptr);
if (Error != PI_SUCCESS) {
CachedLibPrograms.erase(LibProgIt);
throw compile_program_error(
ProgramManager::getProgramBuildLog(LibProg, Context), Error);
}
return LibProg;
}
ProgramManager::ProgramManager() {
const char *SpvFile = std::getenv(UseSpvEnv);
// If a SPIR-V file is specified with an environment variable,
// register the corresponding image
if (SpvFile) {
m_UseSpvFile = true;
// The env var requests that the program is loaded from a SPIR-V file on
// disk
std::ifstream File(SpvFile, std::ios::binary);
if (!File.is_open())
throw runtime_error(std::string("Can't open file specified via ") +
UseSpvEnv + ": " + SpvFile,
PI_ERROR_INVALID_VALUE);
File.seekg(0, std::ios::end);
size_t Size = File.tellg();
std::unique_ptr<char[]> Data(new char[Size]);
File.seekg(0);
File.read(Data.get(), Size);
File.close();
if (!File.good())
throw runtime_error(std::string("read from ") + SpvFile +
std::string(" failed"),
PI_ERROR_INVALID_VALUE);
auto ImgPtr = make_unique_ptr<DynRTDeviceBinaryImage>(
std::move(Data), Size, OSUtil::DummyModuleHandle);
if (DbgProgMgr > 0) {
std::cerr << "loaded device image binary from " << SpvFile << "\n";
std::cerr << "format: " << getFormatStr(ImgPtr->getFormat()) << "\n";
}
// No need for a mutex here since all access to these private fields is
// blocked until the construction of the ProgramManager singleton is
// finished.
m_DeviceImages[SpvFileKSId].reset(
new std::vector<RTDeviceBinaryImageUPtr>());
m_DeviceImages[SpvFileKSId]->push_back(std::move(ImgPtr));
}
}
RTDeviceBinaryImage &
ProgramManager::getDeviceImage(OSModuleHandle M, KernelSetId KSId,
const context &Context, const device &Device,
bool JITCompilationIsRequired) {
if (DbgProgMgr > 0) {
std::cerr << ">>> ProgramManager::getDeviceImage(" << M << ", \"" << KSId
<< "\", " << getRawSyclObjImpl(Context) << ", "
<< getRawSyclObjImpl(Device) << ", " << JITCompilationIsRequired
<< ")\n";
std::cerr << "available device images:\n";
debugPrintBinaryImages();
}
std::lock_guard<std::mutex> Guard(Sync::getGlobalLock());
std::vector<RTDeviceBinaryImageUPtr> &Imgs = *m_DeviceImages[KSId];
const ContextImplPtr Ctx = getSyclObjImpl(Context);
pi_uint32 ImgInd = 0;
RTDeviceBinaryImage *Img = nullptr;
// TODO: There may be cases with sycl::program class usage in source code
// that will result in a multi-device context. This case needs to be handled
// here or at the program_impl class level
// Ask the native runtime under the given context to choose the device image
// it prefers.
std::vector<pi_device_binary> RawImgs(Imgs.size());
for (unsigned I = 0; I < Imgs.size(); I++)
RawImgs[I] = const_cast<pi_device_binary>(&Imgs[I]->getRawData());
Ctx->getPlugin().call<PiApiKind::piextDeviceSelectBinary>(
getSyclObjImpl(Device)->getHandleRef(), RawImgs.data(),
(pi_uint32)RawImgs.size(), &ImgInd);
if (JITCompilationIsRequired) {
// If the image is already compiled with AOT, throw an exception.
const pi_device_binary_struct &RawImg = Imgs[ImgInd]->getRawData();
if ((strcmp(RawImg.DeviceTargetSpec,
__SYCL_PI_DEVICE_BINARY_TARGET_SPIRV64_X86_64) == 0) ||
(strcmp(RawImg.DeviceTargetSpec,
__SYCL_PI_DEVICE_BINARY_TARGET_SPIRV64_GEN) == 0) ||
(strcmp(RawImg.DeviceTargetSpec,
__SYCL_PI_DEVICE_BINARY_TARGET_SPIRV64_FPGA) == 0)) {
throw feature_not_supported("Recompiling AOT image is not supported",
PI_ERROR_INVALID_OPERATION);
}
}
Img = Imgs[ImgInd].get();
if (DbgProgMgr > 0) {
std::cerr << "selected device image: " << &Img->getRawData() << "\n";
Img->print();
}
return *Img;
}
static bool isDeviceLibRequired(DeviceLibExt Ext, uint32_t DeviceLibReqMask) {
uint32_t Mask =
0x1 << (static_cast<uint32_t>(Ext) -
static_cast<uint32_t>(DeviceLibExt::cl_intel_devicelib_assert));
return ((DeviceLibReqMask & Mask) == Mask);
}
static std::vector<RT::PiProgram>
getDeviceLibPrograms(const ContextImplPtr Context, const RT::PiDevice &Device,
uint32_t DeviceLibReqMask) {