-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathjitify2.hpp
8709 lines (8033 loc) · 315 KB
/
jitify2.hpp
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 (c) 2017-2023, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*! \file jitify2.hpp
* \brief The Jitify v2 library header
*/
/*! \mainpage Jitify - A C++ library that simplifies the use of NVRTC
* \p Use class jitify2::ProgramCache to manage and launch JIT-compiled CUDA
* kernels.
*
* \p Use namespace jitify2::reflection to reflect types and values into
* code-strings.
*/
#ifndef JITIFY2_HPP_INCLUDE_GUARD
#define JITIFY2_HPP_INCLUDE_GUARD
// This macro is used by source files generated by jitify_preprocess to avoid
// unnecessary dependencies.
#ifdef JITIFY_SERIALIZATION_ONLY
#include <algorithm>
#include <cassert>
#include <climits>
#include <initializer_list>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <unordered_map>
#include <vector>
#if __cplusplus >= 201703L
#include <string_view>
#endif
#else // not JITIFY_SERIALIZATION_ONLY
#include <cuda.h>
#include <nvrtc.h>
#if CUDA_VERSION >= 12000
#include <nvJitLink.h>
#endif
// Default to being thread-safe.
#ifndef JITIFY_THREAD_SAFE
#define JITIFY_THREAD_SAFE 1
#endif
// Default to using dynamic linking of NVRTC.
#ifndef JITIFY_LINK_NVRTC_STATIC
#define JITIFY_LINK_NVRTC_STATIC 0
#endif
// Default to using dynamic linking of nvJitLink.
#ifndef JITIFY_LINK_NVJITLINK_STATIC
#define JITIFY_LINK_NVJITLINK_STATIC 0
#endif
// Default to using dynamic linking of CUDA.
#ifndef JITIFY_LINK_CUDA_STATIC
#define JITIFY_LINK_CUDA_STATIC 0
#endif
// Users can enable this for easier debugging.
#ifndef JITIFY_FAIL_IMMEDIATELY
#define JITIFY_FAIL_IMMEDIATELY 0
#endif
#ifndef JITIFY_USE_LIBCUFILT
#define JITIFY_USE_LIBCUFILT 0 // Use Jitify's builtin demangler by default
#endif
#if CUDA_VERSION >= 11040 && JITIFY_USE_LIBCUFILT
#include <nv_decode.h> // For __cu_demangle (requires linking with libcufilt.a)
#endif
#include <algorithm>
#include <array>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstring>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <regex>
#include <sstream>
#include <streambuf>
#include <string>
#include <thread>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#if JITIFY_THREAD_SAFE
#include <mutex>
#define JITIFY_IF_THREAD_SAFE(x) x
#else
#define JITIFY_IF_THREAD_SAFE(x)
#endif
#if __cplusplus >= 201402L
#define JITIFY_DEPRECATED(msg) [[deprecated(msg)]]
#else
#define JITIFY_DEPRECATED(msg)
#endif
#ifdef __linux__
#include <cxxabi.h> // For abi::__cxa_demangle
#include <dirent.h> // For struct dirent, opendir etc.
#include <dlfcn.h> // For ::dlopen, ::dlsym etc.
#include <fcntl.h> // For open
#include <linux/limits.h> // For PATH_MAX
#include <sys/stat.h> // For stat
#include <sys/types.h> // For DIR etc.
#include <unistd.h> // For close
#include <cstdlib> // For realpath
#include <ext/stdio_filebuf.h> // For __gnu_cxx::stdio_filebuf
#define JITIFY_PATH_MAX PATH_MAX
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h> // Must be included first
#include <dbghelp.h> // For UndecorateSymbolName
#include <direct.h> // For mkdir
#include <fcntl.h> // For open, O_RDWR etc.
#include <io.h> // For _sopen_s
#include <sys/locking.h> // For _LK_LOCK etc.
#define JITIFY_PATH_MAX MAX_PATH
#else
#error "Unsupported platform"
#endif
#if defined(_WIN32) || defined(_WIN64)
// WAR for strtok_r being called strtok_s on Windows.
#pragma push_macro("strtok_r")
#undef strtok_r
#define strtok_r strtok_s
// WAR for min and max possibly being macros defined by windows.h
#pragma push_macro("min")
#pragma push_macro("max")
#undef min
#undef max
#endif
#ifndef JITIFY_ENABLE_EXCEPTIONS
// Default to using exceptions.
#define JITIFY_ENABLE_EXCEPTIONS 1
#endif
#if JITIFY_ENABLE_EXCEPTIONS
#include <stdexcept>
#define JITIFY_THROW_OR_TERMINATE(msg) \
throw std::runtime_error(std::string("Jitify fatal error: ") + (msg))
#else
// TODO: Would std::exit or std::abort be better than std::terminate?
#include <exception>
#define JITIFY_THROW_OR_TERMINATE(msg) \
std::cerr << "Jitify fatal error: " << (msg) << std::endl; \
std::terminate()
#endif
#if JITIFY_ENABLE_EXCEPTIONS
#define JITIFY_THROW_OR_RETURN(msg) \
throw std::runtime_error(std::string("Jitify error: ") + (msg))
#else
#define JITIFY_THROW_OR_RETURN(msg) return msg
#endif
#define JITIFY_THROW_OR_RETURN_IF_CUDA_ERROR(call) \
do { \
CUresult jitify_cuda_ret = call; \
if (jitify_cuda_ret != CUDA_SUCCESS) { \
const char* error_c; \
cuda().GetErrorString()(jitify_cuda_ret, &error_c); \
JITIFY_THROW_OR_RETURN(error_c); \
} \
} while (0)
#endif // not JITIFY_SERIALIZATION_ONLY
namespace jitify2 {
// Convenience aliases.
using StringVec = std::vector<std::string>;
using StringMap = std::unordered_map<std::string, std::string>;
#if __cplusplus >= 201703L
using StringRef = std::string_view;
using StringSlice = std::string_view;
#else
using StringRef = const std::string&;
using StringSlice = std::string;
#endif
class Option {
public:
Option() = default;
explicit Option(std::string _key, std::string _value = {},
StringVec _repr = {})
: key_(std::move(_key)),
value_(std::move(_value)),
repr_(std::move(_repr)) {
if (repr_.empty()) {
repr_ = {key_};
if (!value_.empty()) {
repr_.front() += "=" + value_;
}
}
// TODO: Consider changing key and value to be views into key_and_value to
// avoid double-storage.
if (value_.empty()) {
key_and_value_ = key_;
} else {
key_and_value_.reserve(key_.size() + 1 + value_.size());
key_and_value_.append(key_);
key_and_value_.append("=");
key_and_value_.append(value_);
}
}
const std::string& key() const { return key_; }
const std::string& value() const { return value_; }
const std::string& key_and_value() const { return key_and_value_; }
const StringVec& original_representation() const { return repr_; }
friend const std::string& to_string(const Option& option) {
return option.key_and_value();
}
friend std::ostream& operator<<(std::ostream& os, const Option& option) {
return os << option.key_and_value();
}
friend bool operator==(const Option& lhs, const Option& rhs) {
return lhs.key_ == rhs.key_ && lhs.value_ == rhs.value_;
}
friend bool operator!=(const Option& lhs, const Option& rhs) {
return !(lhs == rhs);
}
private:
std::string key_;
std::string value_;
std::string key_and_value_;
StringVec repr_;
};
namespace detail {
// Strip whitespace from string in-place.
inline void ltrim(std::string* s) {
s->erase(s->begin(), std::find_if(s->begin(), s->end(), [](unsigned char c) {
return !std::isspace(c);
}));
}
inline void rtrim(std::string* s) {
s->erase(std::find_if(s->rbegin(), s->rend(),
[](unsigned char c) { return !std::isspace(c); })
.base(),
s->end());
}
inline void trim(std::string* s) {
ltrim(s);
rtrim(s);
}
// Strip whitespace from a string view.
inline StringSlice ltrim(StringRef s) {
size_t beg = std::find_if(s.begin(), s.end(),
[](unsigned char c) { return !std::isspace(c); }) -
s.begin();
return s.substr(beg);
}
inline StringSlice rtrim(StringRef s) {
size_t end = std::find_if(s.rbegin(), s.rend(),
[](unsigned char c) { return !std::isspace(c); })
.base() -
s.begin();
return s.substr(0, end);
}
inline StringSlice trim(StringRef s) { return rtrim(ltrim(s)); }
} // namespace detail
class OptionsVec {
using vec_type = std::vector<Option>;
public:
using iterator = vec_type::iterator;
using const_iterator = vec_type::const_iterator;
OptionsVec() = default;
// Allow implicit conversion.
OptionsVec(std::vector<Option> _options) : options_(std::move(_options)) {}
// Allow implicit conversion (to avoid breaking the old options API).
OptionsVec(const StringVec& raw_options) : ok_(parse(raw_options)) {}
// Allow implicit conversion (to avoid breaking the old options API).
OptionsVec(std::initializer_list<std::string> raw_options)
: OptionsVec(StringVec(raw_options)) {}
explicit operator bool() const { return ok_; }
bool ok() const { return ok_; }
size_t size() const {
assert(ok_);
return options_.size();
}
StringVec serialize() const {
assert(ok_);
return serialize_impl(true);
}
StringVec serialize_canonical() const {
assert(ok_);
return serialize_impl(false);
}
// Allow implicit conversion (to avoid breaking the old options API).
operator StringVec() const { return serialize(); }
// Removes all options with any of the specified keys, and returns whether any
// were removed.
bool pop(std::initializer_list<std::string> keys) {
assert(ok_);
auto iter = std::remove_if(
options_.begin(), options_.end(), [&](const Option& option) {
return std::find(keys.begin(), keys.end(), option.key()) !=
keys.end();
});
if (iter == options_.end()) return false;
options_.resize(iter - options_.begin());
return true;
}
void pop_back() {
assert(ok_);
options_.pop_back();
}
// Returns the indexes of all options that match any of the specified keys.
std::vector<int> find(std::initializer_list<std::string> keys,
size_t max_results = (size_t)-1) const {
assert(ok_);
std::vector<int> results;
for (int i = 0; i < (int)options_.size(); ++i) {
if (results.size() == max_results) break;
// Note: Using std::find instead of a hashmap because keys will typically
// be only 2-3 elements long.
if (std::find(keys.begin(), keys.end(), options_[i].key()) !=
keys.end()) {
results.push_back(i);
}
}
return results;
}
iterator erase(size_t idx) {
assert(ok_);
return options_.erase(options_.begin() + idx);
}
template <class InputIt>
iterator insert(const_iterator pos, InputIt first, InputIt last) {
assert(ok_);
return options_.insert(pos, first, last);
}
void push_back(Option option) {
assert(ok_);
options_.push_back(std::move(option));
}
template <typename... Args>
void emplace_back(Args&&... args) {
assert(ok_);
options_.emplace_back(std::forward<Args>(args)...);
}
iterator begin() {
assert(ok_);
return options_.begin();
}
iterator end() {
assert(ok_);
return options_.end();
}
const_iterator begin() const {
assert(ok_);
return options_.begin();
}
const_iterator end() const {
assert(ok_);
return options_.end();
}
const Option& operator[](size_t idx) const {
assert(ok_);
return options_[idx];
}
Option& operator[](size_t idx) {
assert(ok_);
return options_[idx];
}
friend bool operator==(const OptionsVec& lhs, const OptionsVec& rhs) {
return lhs.ok_ == rhs.ok_ && lhs.options_ == rhs.options_;
}
friend bool operator!=(const OptionsVec& lhs, const OptionsVec& rhs) {
return !(lhs == rhs);
}
private:
// Parses a vector of option strings into a vector of Option objects. Also
// strips whitespace surrounding keys and values. Returns false on failure.
bool parse(const StringVec& options) {
for (size_t i = 0; i < options.size(); ++i) {
std::string option = options[i];
detail::trim(&option); // Strip whitespace
if (option[0] != '-') {
return false; // "Expected an option, got " + option
}
std::string key, val;
StringVec repr = {option};
const size_t eql = option.find('=');
if (i + 1 < options.size() && options[i + 1][0] != '-') {
// Parse "-key" "val".
key = option;
val = options[++i];
repr = {key, val};
} else if (eql != std::string::npos) {
// Parse "-key=val".
key = option.substr(0, eql);
val = option.substr(eql + 1);
} else if (option.size() > 2 &&
// HACK: Special case for '-l<lib>' linker flag.
(std::isupper(static_cast<unsigned char>(option[1])) ||
(option[1] == 'l' && option.substr(0, 9) != "-lineinfo"))) {
// Parse "-Kval".
key = option.substr(0, 2);
val = option.substr(2);
} else {
// Parse "-key" (no value).
key = option;
}
detail::trim(&val); // Strip whitespace
options_.emplace_back(std::move(key), std::move(val), std::move(repr));
}
return true;
}
// This is the inverse of parse().
StringVec serialize_impl(bool use_original_representation) const {
StringVec results;
results.reserve(options_.size());
for (const Option& option : options_) {
if (use_original_representation) {
const StringVec& repr = option.original_representation();
results.insert(results.end(), repr.begin(), repr.end());
} else {
results.push_back(option.key_and_value());
}
}
return results;
}
vec_type options_;
bool ok_ = true;
};
namespace serialization {
// Stream buffer that can be initialized with data without copying.
// Based on https://stackoverflow.com/a/13059195/7228843
struct membuf : std::streambuf {
membuf(const char* data, size_t size) {
char* data_workaround(const_cast<char*>(data));
this->setg(data_workaround, data_workaround, data_workaround + size);
}
};
// Warning: Do not put this inside the serialization::detail namespace, lest the
// wrath of ADL come down upon you from serialization::deserialize(StringRef).
struct imemstream : virtual membuf, std::istream {
imemstream(const char* data, size_t size)
: membuf(data, size), std::istream(static_cast<std::streambuf*>(this)) {}
imemstream(const std::string& str) : imemstream(str.data(), str.size()) {}
#if __cplusplus >= 201703L
imemstream(std::string_view sv) : imemstream(sv.data(), sv.size()) {}
#endif
};
// This should be incremented whenever the serialization format changes in any
// incompatible way.
static constexpr const size_t kSerializationVersion = 0x10;
namespace detail {
inline void serialize(std::ostream& stream, size_t u) {
uint64_t u64 = u;
char bytes[8];
for (int i = 0; i < (int)sizeof(bytes); ++i) {
// Convert to little-endian bytes.
bytes[i] = (unsigned char)(u64 >> (i * CHAR_BIT));
}
stream.write(bytes, sizeof(bytes));
}
inline bool deserialize(std::istream& stream, size_t* size) {
char bytes[8];
stream.read(bytes, sizeof(bytes));
uint64_t u64 = 0;
for (int i = 0; i < (int)sizeof(bytes); ++i) {
// Convert from little-endian bytes.
u64 |= uint64_t((unsigned char)(bytes[i])) << (i * CHAR_BIT);
}
*size = u64;
return stream.good();
}
// Obfuscate so that embedded serializations don't show up in `strings`.
inline std::string obfuscate(std::string s) {
for (char& c : s) {
c = (char)-c;
}
return s;
}
inline std::string deobfuscate(std::string s) {
return obfuscate(std::move(s));
}
inline void serialize(std::ostream& stream, std::string s) {
serialize(stream, s.size());
stream.write(obfuscate(s).data(), s.size());
}
inline bool deserialize(std::istream& stream, std::string* s) {
size_t size;
if (!deserialize(stream, &size)) return false;
s->resize(size);
if (s->size()) {
stream.read(&(*s)[0], s->size());
}
*s = deobfuscate(std::move(*s));
return stream.good();
}
inline void serialize(std::ostream& stream, const StringVec& v) {
serialize(stream, v.size());
for (const auto& s : v) {
serialize(stream, s);
}
}
inline bool deserialize(std::istream& stream, StringVec* v) {
size_t size;
if (!deserialize(stream, &size)) return false;
v->resize(size);
for (auto& s : *v) {
if (!deserialize(stream, &s)) return false;
}
return true;
}
inline void serialize(std::ostream& stream, const OptionsVec& ov) {
serialize(stream, ov.serialize());
}
inline bool deserialize(std::istream& stream, OptionsVec* ov) {
StringVec v;
if (!deserialize(stream, &v)) return false;
*ov = OptionsVec(v);
return static_cast<bool>(*ov);
}
inline void serialize(std::ostream& stream, const StringMap& m) {
serialize(stream, m.size());
for (const auto& kv : m) {
serialize(stream, kv.first);
serialize(stream, kv.second);
}
}
inline bool deserialize(std::istream& stream, StringMap* m) {
size_t size;
if (!deserialize(stream, &size)) return false;
for (size_t i = 0; i < size; ++i) {
std::string key;
if (!deserialize(stream, &key)) return false;
if (!deserialize(stream, &(*m)[key])) return false;
}
return true;
}
template <typename T, typename... Rest>
inline void serialize(std::ostream& stream, const T& value,
const Rest&... rest) {
serialize(stream, value);
serialize(stream, rest...);
}
template <typename T, typename... Rest>
inline bool deserialize(std::istream& stream, T* value, Rest*... rest) {
if (!deserialize(stream, value)) return false;
return deserialize(stream, rest...);
}
inline void serialize_magic_number(std::ostream& stream) {
stream.write("JTFY", 4);
serialize(stream, kSerializationVersion);
}
inline bool deserialize_magic_number(std::istream& stream) {
char magic_number[4] = {0, 0, 0, 0};
stream.read(&magic_number[0], 4);
if (!(magic_number[0] == 'J' && magic_number[1] == 'T' &&
magic_number[2] == 'F' && magic_number[3] == 'Y')) {
return false;
}
size_t serialization_version;
if (!deserialize(stream, &serialization_version)) return false;
return serialization_version == kSerializationVersion;
}
} // namespace detail
template <typename... Values>
inline void serialize(std::ostream& stream, const Values&... values) {
detail::serialize_magic_number(stream);
detail::serialize(stream, values...);
}
template <typename T, typename... Rest,
typename std::enable_if<
!std::is_convertible<T&, std::ostream&>::value, int>::type = 0>
inline std::string serialize(const T& value, const Rest&... rest) {
std::ostringstream ss(std::stringstream::binary);
detail::serialize_magic_number(ss);
detail::serialize(ss, value, rest...);
return ss.str();
}
template <typename... Values>
inline bool deserialize(std::istream& stream, Values*... values) {
if (!detail::deserialize_magic_number(stream)) return false;
return detail::deserialize(stream, values...);
}
template <typename... Values>
inline bool deserialize(StringRef serialized, Values*... values) {
imemstream ms(serialized);
return deserialize(ms, values...);
}
template <class Subclass>
class Serializable {
struct SerializeImpl {
std::ostream& stream_;
SerializeImpl(std::ostream& stream) : stream_(stream) {}
template <typename... Values>
bool operator()(const Values&... values) const {
serialization::serialize(stream_, values...);
return true;
}
};
struct DeserializeImpl {
std::istream& stream_;
DeserializeImpl(std::istream& stream) : stream_(stream) {}
template <typename... Values>
bool operator()(Values&... values) const {
return serialization::deserialize(stream_, &values...);
}
};
public:
/*! Serialize the object to a stream.
* \param stream The stream to output serialized data to.
*/
void serialize(std::ostream& stream) const {
const auto* subclass = static_cast<const Subclass*>(this);
subclass->serialize_members(SerializeImpl(stream));
}
/*! Serialize the object to a string.
* \return A string containing the serialized data.
*/
std::string serialize() const {
std::ostringstream ss(std::stringstream::binary);
serialize(ss);
return ss.str();
}
static bool deserialize(std::istream& stream, Subclass* subclass) {
return subclass->deserialize_members(DeserializeImpl(stream));
}
static bool deserialize(StringRef serialized, Subclass* subclass) {
imemstream ms(serialized);
return subclass->deserialize_members(DeserializeImpl(ms));
}
};
#define JITIFY_DEFINE_SERIALIZABLE_MEMBERS(ClassName, ...) \
friend class serialization::Serializable<ClassName>; \
template <typename Deserializer> \
bool deserialize_members(Deserializer deserializer) { \
return deserializer(__VA_ARGS__); \
} \
template <typename Serializer> \
bool serialize_members(Serializer serializer) const { \
return serializer(__VA_ARGS__); \
}
} // namespace serialization
#ifndef JITIFY_SERIALIZATION_ONLY
namespace detail {
// inline const std::string& to_string(const std::string& s) { return s; }
// TODO: Double-check that this is OK
inline StringRef to_string(StringRef s) { return s; }
inline StringSlice to_string(const char& c) { return StringSlice(&c, 1); }
template <class Func, typename... Args>
inline void for_each(Func function, Args&&... args) {
// Convenient trick to reduce over variadic template args.
int unpack[] = {0, (function(std::forward<Args>(args)), 0)...};
(void)unpack; // Avoid compiler warning about being unused.
}
template <typename... Args>
inline std::string string_concat_strings(const Args&... args) {
size_t size = 0;
for_each([&](StringRef arg) { size += arg.size(); }, args...);
std::string result;
result.reserve(size);
for_each([&](StringRef arg) { result += arg; }, args...);
return result;
}
template <typename... Args>
inline std::string string_concat(const Args&... args) {
using ::jitify2::detail::to_string;
using std::to_string;
return string_concat_strings(to_string(args)...);
}
inline std::string string_join(const StringVec& args, StringRef sep = ",",
StringRef prefix = "", StringRef suffix = "") {
std::string result;
size_t args_size = 0;
for (const std::string& arg : args) {
args_size += arg.size();
}
result.reserve(prefix.size() + args_size +
sep.size() * (std::max(args.size(), size_t(1)) - 1) +
suffix.size());
result += prefix;
for (int i = 0; i < (int)args.size(); ++i) {
if (i > 0) result += sep;
result += args[i];
}
result += suffix;
return result;
}
} // namespace detail
/*! Reflection utilities namespace. */
namespace reflection {
template <typename T, T VALUE>
struct NonType {};
// Forward declaration.
template <typename T>
inline std::string reflect(const T& value);
namespace detail {
template <typename T>
inline std::string value_string(const T& x) {
return std::to_string(x);
}
template <>
inline std::string value_string<bool>(const bool& x) {
return x ? "true" : "false";
}
// Returns the demangled name corresponding to the given typeinfo structure.
inline std::string get_type_name(const std::type_info& typeinfo) {
#ifdef _MSC_VER // MSVC compiler
// Get the decorated name and skip over the leading '.'.
const char* raw_name = typeinfo.raw_name();
if (!raw_name || raw_name[0] != '.') return {}; // Unexpected error
const char* decorated_name = raw_name + 1;
char undecorated_name[4096];
// Note: UNDNAME_NO_MS_KEYWORDS removes __cdecl, __ptr64 etc. but has a bug in
// some versions that breaks function types. Instead, we leave these tokens in
// and #define them away as necessary.
// Note: UnDecorateSymbolName is not thread safe.
JITIFY_IF_THREAD_SAFE(static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);)
if (!UnDecorateSymbolName(
decorated_name, undecorated_name,
sizeof(undecorated_name) / sizeof(*undecorated_name),
UNDNAME_NO_ARGUMENTS | // Treat input as a type name
UNDNAME_NAME_ONLY // No "class" and "struct" prefixes
/*UNDNAME_NO_MS_KEYWORDS*/)) { // No "__cdecl", "__ptr64" etc. BUGGED
return {}; // Error
}
return undecorated_name;
#else // not MSVC
const char* mangled_name = typeinfo.name();
size_t bufsize = 0;
char* buf = nullptr;
int status;
auto demangled_ptr = std::unique_ptr<char, void (*)(void*)>(
abi::__cxa_demangle(mangled_name, buf, &bufsize, &status), std::free);
// clang-format off
switch (status) {
case 0: return demangled_ptr.get(); // Demangled successfully
case -2: return mangled_name; // Interpret as plain unmangled name
case -1: // fall-through // Memory allocation failure
case -3: // fall-through // Invalid argument
default: return {};
}
// clang-format on
#endif // not MSVC
}
template <typename>
class JitifyTypeNameWrapper_ {};
// Returns the demangled name of the given type.
template <typename T>
inline std::string get_type_name() {
// WAR for typeid discarding cv qualifiers on value-types.
// Wraps type in dummy template class to preserve cv-qualifiers, then strips
// off the wrapper from the resulting string.
std::string wrapped_name = get_type_name(typeid(JitifyTypeNameWrapper_<T>));
// Note: The reflected name of this class also has namespace prefixes.
const std::string wrapper_class_name = "JitifyTypeNameWrapper_<";
size_t start = wrapped_name.find(wrapper_class_name);
if (start == std::string::npos) return {}; // Unexpected error
start += wrapper_class_name.size();
return wrapped_name.substr(start, wrapped_name.size() - (start + 1));
}
template <typename T>
struct ReflectType {
const std::string& operator()() const {
// Storing this statically means it is cached after the first call.
static const std::string type_name = get_type_name<T>();
return type_name;
}
};
template <typename T, T VALUE>
struct ReflectType<NonType<T, VALUE>> {
std::string operator()() const { return reflect(VALUE); }
};
} // namespace detail
/*! A wrapper used for representing types as values. */
template <typename T>
struct Type {};
/*! Create an Instance object that contains a const reference to the
* value. We use this to wrap abstract objects from which we want to extract
* their type at runtime (e.g., derived type). This is used to facilitate
* templating on derived type when all we know at compile time is abstract
* type.
*/
template <typename T>
struct Instance {
const T& value;
Instance(const T& value_arg) : value(value_arg) {}
};
/*! Create an Instance object from which we can extract the value's run-time
* type.
* \param value The const value to be captured.
*/
template <typename T>
inline Instance<T const> instance_of(T const& value) {
return Instance<T const>(value);
}
/*! Generate a code-string for a type.
* \code{.cpp}reflect<float>() --> "float"\endcode
*/
template <typename T>
inline std::string reflect() {
return detail::ReflectType<T>()();
}
/*! Generate a code-string for a value.
* \code{.cpp}reflect(3.14f) --> "(float)3.14"\endcode
*/
template <typename T>
inline std::string reflect(const T& value) {
return "(" + reflect<T>() + ")" + detail::value_string(value);
}
/*! Generate a code-string for an integer non-type template argument
* (via implicit conversion to int64_t).
* \code{.cpp}reflect<7>() --> "(int64_t)7"\endcode
*/
template <int64_t N>
inline std::string reflect() {
return reflect<NonType<int64_t, N>>();
}
/*! Generate a code-string for a generic non-type template argument.
* \code{.cpp} reflect<int,7>() --> "(int)7" \endcode
*/
template <typename T, T N>
inline std::string reflect() {
return reflect<NonType<T, N>>();
}
/*! Generate a code-string for a type wrapped as a Type instance.
* \code{.cpp}reflect(Type<float>()) --> "float"\endcode
*/
template <typename T>
inline std::string reflect(Type<T>) {
return reflect<T>();
}
/*! Generate a code-string for a type wrapped as an Instance instance.
* \code{.cpp}reflect(Instance<float>(3.1f)) --> "float"\endcode
* or more simply when passed to a instance_of helper
* \code{.cpp}reflect(instance_of(3.1f)) --> "float"\endcodei
* This is specifically for the case where we want to extract the run-time
* type, i.e., derived type, of an object pointer.
*/
template <typename T>
inline std::string reflect(const Instance<T>& value) {
return detail::get_type_name(typeid(value.value));
}
// TODO: Would there ever be a need to reflect a string literal?
/*! Use an existing code string as-is. */
inline std::string reflect(const std::string& s) { return s; }
/*! Use an existing code string as-is. */
inline const char* reflect(const char* s) { return s; }
#if __cplusplus >= 201703L
/*! Use an existing code string as-is. */
inline std::string_view reflect(std::string_view s) { return s; }
#endif
/*! Create a Type object representing a value's type.
* \code{.cpp}type_of(3.14f) -> Type<float>()\endcode
* \param [unnamed] The value whose type is to be captured.
*/
template <typename T>
inline Type<T> type_of(T&) {
return Type<T>();
}
/*! Create a Type object representing a value's type.
* \param [unnamed] The const value whose type is to be captured.