-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathGenerator.cpp
More file actions
2272 lines (1988 loc) · 87.7 KB
/
Generator.cpp
File metadata and controls
2272 lines (1988 loc) · 87.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <fstream>
#include <memory>
#include <unordered_map>
#include <utility>
#include "CompilerLogger.h"
#include "Generator.h"
#include "IRPrinter.h"
#include "Module.h"
#include "Serialization.h"
#include "Simplify.h"
#ifdef HALIDE_ALLOW_GENERATOR_BUILD_METHOD
#pragma message "Support for Generator build() methods has been removed in Halide version 15."
#endif
namespace Halide {
GeneratorContext::GeneratorContext(const Target &target)
: target_(target),
autoscheduler_params_() {
}
GeneratorContext::GeneratorContext(const Target &target,
const AutoschedulerParams &autoscheduler_params)
: target_(target),
autoscheduler_params_(autoscheduler_params) {
}
GeneratorContext GeneratorContext::with_target(const Target &t) const {
return GeneratorContext(t, autoscheduler_params_);
}
namespace Internal {
namespace {
// Return true iff the name is valid for Generators or Params.
// (NOTE: gcc didn't add proper std::regex support until v4.9;
// we don't yet require this, hence the hand-rolled replacement.)
bool is_alpha(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
// Note that this includes '_'
bool is_alnum(char c) {
return is_alpha(c) || (c == '_') || (c >= '0' && c <= '9');
}
// Basically, a valid C identifier, except:
//
// -- initial _ is forbidden (rather than merely "reserved")
// -- two underscores in a row is also forbidden
bool is_valid_name(const std::string &n) {
if (n.empty()) {
return false;
}
if (!is_alpha(n[0])) {
return false;
}
for (size_t i = 1; i < n.size(); ++i) {
if (!is_alnum(n[i])) {
return false;
}
if (n[i] == '_' && n[i - 1] == '_') {
return false;
}
}
// prohibit this specific string so that we can use it for
// passing GeneratorParams in Python.
if (n == "generator_params") {
return false;
}
return true;
}
std::map<OutputFileType, std::string> compute_output_files(const Target &target,
const std::string &base_path,
const std::set<OutputFileType> &outputs) {
std::map<OutputFileType, const OutputInfo> output_info = get_output_info(target);
std::map<OutputFileType, std::string> output_files;
for (auto o : outputs) {
output_files[o] = base_path + output_info.at(o).extension;
}
return output_files;
}
Func make_param_func(const Parameter &p, const std::string &name) {
internal_assert(p.is_buffer());
Func f(p.type(), p.dimensions(), name + "_im");
auto b = p.buffer();
if (b.defined()) {
// If the Parameter has an explicit BufferPtr set, bind directly to it
f(_) = b(_);
} else {
std::vector<Var> args;
std::vector<Expr> args_expr;
for (int i = 0; i < p.dimensions(); ++i) {
Var v = Var::implicit(i);
args.push_back(v);
args_expr.push_back(v);
}
f(args) = Internal::Call::make(p, args_expr);
}
return f;
}
} // namespace
std::vector<Type> parse_halide_type_list(const std::string &types) {
const auto &e = get_halide_type_enum_map();
std::vector<Type> result;
for (const auto &t : split_string(types, ",")) {
auto it = e.find(t);
user_assert(it != e.end()) << "Type not found: " << t;
result.push_back(it->second);
}
return result;
}
class StubEmitter {
public:
StubEmitter(std::ostream &dest,
const std::string &generator_registered_name,
const std::string &generator_stub_name,
const std::vector<Internal::GeneratorParamBase *> &generator_params,
const std::vector<Internal::GeneratorInputBase *> &inputs,
const std::vector<Internal::GeneratorOutputBase *> &outputs)
: stream(dest),
generator_registered_name(generator_registered_name),
generator_stub_name(generator_stub_name),
generator_params(select_generator_params(generator_params)),
inputs(inputs),
outputs(outputs) {
namespaces = split_string(generator_stub_name, "::");
internal_assert(!namespaces.empty());
if (namespaces[0].empty()) {
// We have a name like ::foo::bar::baz; omit the first empty ns.
namespaces.erase(namespaces.begin());
internal_assert(namespaces.size() >= 2);
}
class_name = namespaces.back();
namespaces.pop_back();
}
void emit();
private:
std::ostream &stream;
const std::string generator_registered_name;
const std::string generator_stub_name;
std::string class_name;
std::vector<std::string> namespaces;
const std::vector<Internal::GeneratorParamBase *> generator_params;
const std::vector<Internal::GeneratorInputBase *> inputs;
const std::vector<Internal::GeneratorOutputBase *> outputs;
int indent_level{0};
std::vector<Internal::GeneratorParamBase *> select_generator_params(const std::vector<Internal::GeneratorParamBase *> &in) {
std::vector<Internal::GeneratorParamBase *> out;
for (auto *p : in) {
// These are always propagated specially.
if (p->name() == "target" ||
p->name() == "autoscheduler") {
continue;
}
if (p->is_synthetic_param()) {
continue;
}
out.push_back(p);
}
return out;
}
/** Emit spaces according to the current indentation level */
Indentation get_indent() const {
return Indentation{indent_level};
}
void emit_inputs_struct();
void emit_generator_params_struct();
};
void StubEmitter::emit_generator_params_struct() {
const auto &v = generator_params;
std::string name = "GeneratorParams";
stream << get_indent() << "struct " << name << " final {\n";
indent_level++;
if (!v.empty()) {
for (auto *p : v) {
stream << get_indent() << p->get_c_type() << " " << p->name() << "{ " << p->get_default_value() << " };\n";
}
stream << "\n";
}
stream << get_indent() << name << "() {}\n";
stream << "\n";
if (!v.empty()) {
stream << get_indent() << name << "(\n";
indent_level++;
std::string comma = "";
for (auto *p : v) {
std::string c_type = p->get_c_type();
if (c_type == "AutoschedulerParams") {
c_type = "const AutoschedulerParams&";
}
stream << get_indent() << comma << c_type << " " << p->name() << "\n";
comma = ", ";
}
indent_level--;
stream << get_indent() << ") : \n";
indent_level++;
comma = "";
for (auto *p : v) {
stream << get_indent() << comma << p->name() << "(" << p->name() << ")\n";
comma = ", ";
}
indent_level--;
stream << get_indent() << "{\n";
stream << get_indent() << "}\n";
stream << "\n";
}
indent_level--;
stream << get_indent() << "};\n";
stream << "\n";
}
void StubEmitter::emit_inputs_struct() {
struct InInfo {
std::string c_type;
std::string name;
};
std::vector<InInfo> in_info;
for (auto *input : inputs) {
std::stringstream c_type;
if (input->is_array()) {
c_type << "std::vector<";
}
c_type << input->get_c_type();
if (input->is_array()) {
c_type << ">";
}
in_info.push_back({c_type.str(), input->name()});
}
const std::string name = "Inputs";
stream << get_indent() << "struct " << name << " final {\n";
indent_level++;
for (const auto &in : in_info) {
stream << get_indent() << in.c_type << " " << in.name << ";\n";
}
stream << "\n";
stream << get_indent() << name << "() {}\n";
stream << "\n";
if (!in_info.empty()) {
stream << get_indent() << name << "(\n";
indent_level++;
std::string comma = "";
for (const auto &in : in_info) {
stream << get_indent() << comma << "const " << in.c_type << "& " << in.name << "\n";
comma = ", ";
}
indent_level--;
stream << get_indent() << ") : \n";
indent_level++;
comma = "";
for (const auto &in : in_info) {
stream << get_indent() << comma << in.name << "(" << in.name << ")\n";
comma = ", ";
}
indent_level--;
stream << get_indent() << "{\n";
stream << get_indent() << "}\n";
indent_level--;
}
stream << get_indent() << "};\n";
stream << "\n";
}
void StubEmitter::emit() {
if (outputs.empty()) {
// The generator can't support a real stub. Instead, generate an (essentially)
// empty .stub.h file, so that build systems like Bazel will still get the output file
// they expected. Note that we deliberately don't emit an ifndef header guard,
// since we can't reliably assume that the generator_name will be globally unique;
// on the other hand, since this file is just a couple of comments, it's
// really not an issue if it's included multiple times.
stream << "/* MACHINE-GENERATED - DO NOT EDIT */\n";
stream << "/* The Generator named " << generator_registered_name << " uses ImageParam or Param, thus cannot have a Stub generated. */\n";
return;
}
struct OutputInfo {
std::string name;
std::string ctype;
std::string getter;
};
bool all_outputs_are_func = true;
std::vector<OutputInfo> out_info;
for (auto *output : outputs) {
std::string c_type = output->get_c_type();
const bool is_func = (c_type == "Func");
std::stringstream getter;
if (!is_func) {
getter << c_type << "::to_output_buffers(";
}
getter << "generator->output_func(\"" << output->name() << "\")";
if (!is_func) {
getter << ", generator)";
}
if (!output->is_array()) {
getter << ".at(0)";
}
out_info.push_back({output->name(),
output->is_array() ? "std::vector<" + c_type + ">" : c_type,
getter.str()});
if (c_type != "Func") {
all_outputs_are_func = false;
}
}
std::ostringstream guard;
guard << "HALIDE_STUB";
for (const auto &ns : namespaces) {
guard << "_" << ns;
}
guard << "_" << class_name;
stream << get_indent() << "#ifndef " << guard.str() << "\n";
stream << get_indent() << "#define " << guard.str() << "\n";
stream << "\n";
stream << get_indent() << "/* MACHINE-GENERATED - DO NOT EDIT */\n";
stream << "\n";
stream << get_indent() << "#include <cassert>\n";
stream << get_indent() << "#include <iterator>\n";
stream << get_indent() << "#include <map>\n";
stream << get_indent() << "#include <memory>\n";
stream << get_indent() << "#include <string>\n";
stream << get_indent() << "#include <utility>\n";
stream << get_indent() << "#include <vector>\n";
stream << "\n";
stream << get_indent() << "#include \"Halide.h\"\n";
stream << "\n";
stream << "namespace halide_register_generator {\n";
stream << "namespace " << generator_registered_name << "_ns {\n";
stream << "extern std::unique_ptr<Halide::Internal::AbstractGenerator> factory(const Halide::GeneratorContext& context);\n";
stream << "} // namespace halide_register_generator\n";
stream << "} // namespace " << generator_registered_name << "\n";
stream << "\n";
for (const auto &ns : namespaces) {
stream << get_indent() << "namespace " << ns << " {\n";
}
stream << "\n";
for (auto *p : generator_params) {
std::string decl = p->get_type_decls();
if (decl.empty()) {
continue;
}
stream << decl << "\n";
}
stream << get_indent() << "class " << class_name << " final : public Halide::NamesInterface {\n";
stream << get_indent() << "public:\n";
indent_level++;
emit_inputs_struct();
emit_generator_params_struct();
stream << get_indent() << "struct Outputs final {\n";
indent_level++;
stream << get_indent() << "// Outputs\n";
for (const auto &out : out_info) {
stream << get_indent() << out.ctype << " " << out.name << ";\n";
}
stream << "\n";
stream << get_indent() << "// The Target used\n";
stream << get_indent() << "Target target;\n";
if (out_info.size() == 1) {
stream << "\n";
if (all_outputs_are_func) {
std::string name = out_info.at(0).name;
auto *output = outputs[0];
if (output->is_array()) {
stream << get_indent() << "operator std::vector<Halide::Func>() const {\n";
indent_level++;
stream << get_indent() << "return " << name << ";\n";
indent_level--;
stream << get_indent() << "}\n";
stream << get_indent() << "Halide::Func operator[](size_t i) const {\n";
indent_level++;
stream << get_indent() << "return " << name << "[i];\n";
indent_level--;
stream << get_indent() << "}\n";
stream << get_indent() << "Halide::Func at(size_t i) const {\n";
indent_level++;
stream << get_indent() << "return " << name << ".at(i);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << get_indent() << "// operator operator()() overloads omitted because the sole Output is array-of-Func.\n";
} else {
// If there is exactly one output, add overloads
// for operator Func and operator().
stream << get_indent() << "operator Halide::Func() const {\n";
indent_level++;
stream << get_indent() << "return " << name << ";\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "template <typename... Args>\n";
stream << get_indent() << "Halide::FuncRef operator()(Args&&... args) const {\n";
indent_level++;
stream << get_indent() << "return " << name << "(std::forward<Args>(args)...);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "template <typename ExprOrVar>\n";
stream << get_indent() << "Halide::FuncRef operator()(std::vector<ExprOrVar> args) const {\n";
indent_level++;
stream << get_indent() << "return " << name << "()(args);\n";
indent_level--;
stream << get_indent() << "}\n";
}
} else {
stream << get_indent() << "// operator Func() and operator()() overloads omitted because the sole Output is not Func.\n";
}
}
stream << "\n";
if (all_outputs_are_func) {
stream << get_indent() << "Halide::Pipeline get_pipeline() const {\n";
indent_level++;
stream << get_indent() << "return Halide::Pipeline(std::vector<Halide::Func>{\n";
indent_level++;
int commas = (int)out_info.size() - 1;
for (const auto &out : out_info) {
stream << get_indent() << out.name << (commas-- ? "," : "") << "\n";
}
indent_level--;
stream << get_indent() << "});\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "Halide::Realization realize(std::vector<int32_t> sizes) {\n";
indent_level++;
stream << get_indent() << "return get_pipeline().realize(sizes, target);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "template <typename... Args, typename std::enable_if<Halide::Internal::NoRealizations<Args...>::value>::type * = nullptr>\n";
stream << get_indent() << "Halide::Realization realize(Args&&... args) {\n";
indent_level++;
stream << get_indent() << "return get_pipeline().realize(std::forward<Args>(args)..., target);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "void realize(Halide::Realization r) {\n";
indent_level++;
stream << get_indent() << "get_pipeline().realize(r, target);\n";
indent_level--;
stream << get_indent() << "}\n";
} else {
stream << get_indent() << "// get_pipeline() and realize() overloads omitted because some Outputs are not Func.\n";
}
indent_level--;
stream << get_indent() << "};\n";
stream << "\n";
stream << get_indent() << "HALIDE_NO_USER_CODE_INLINE static Outputs generate(\n";
indent_level++;
stream << get_indent() << "const GeneratorContext& context,\n";
stream << get_indent() << "const Inputs& inputs,\n";
stream << get_indent() << "const GeneratorParams& generator_params = GeneratorParams()\n";
indent_level--;
stream << get_indent() << ")\n";
stream << get_indent() << "{\n";
indent_level++;
stream << get_indent() << "std::shared_ptr<Halide::Internal::AbstractGenerator> generator = halide_register_generator::" << generator_registered_name << "_ns::factory(context);\n";
for (auto *p : generator_params) {
stream << get_indent();
if (p->is_looplevel_param()) {
stream << "generator->set_generatorparam_value(";
} else {
stream << "generator->set_generatorparam_value(";
}
stream << "\"" << p->name() << "\", ";
if (p->is_looplevel_param()) {
stream << "generator_params." << p->name();
} else {
stream << p->call_to_string("generator_params." + p->name());
}
stream << ");\n";
}
for (auto *p : inputs) {
stream << get_indent() << "generator->bind_input("
<< "\"" << p->name() << "\", ";
if (p->kind() == ArgInfoKind::Buffer) {
stream << "Halide::Internal::StubInputBuffer<>::to_parameter_vector(inputs." << p->name() << ")";
} else {
// Func or Expr
if (!p->is_array()) {
stream << "{";
}
stream << "inputs." << p->name();
if (!p->is_array()) {
stream << "}";
}
}
stream << ");\n";
}
stream << get_indent() << "generator->build_pipeline();\n";
stream << get_indent() << "return {\n";
indent_level++;
for (const auto &out : out_info) {
stream << get_indent() << out.getter << ",\n";
}
stream << get_indent() << "generator->context().target()\n";
indent_level--;
stream << get_indent() << "};\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "// overload to allow GeneratorBase-pointer\n";
stream << get_indent() << "inline static Outputs generate(\n";
indent_level++;
stream << get_indent() << "const Halide::Internal::GeneratorBase* generator,\n";
stream << get_indent() << "const Inputs& inputs,\n";
stream << get_indent() << "const GeneratorParams& generator_params = GeneratorParams()\n";
indent_level--;
stream << get_indent() << ")\n";
stream << get_indent() << "{\n";
indent_level++;
stream << get_indent() << "return generate(generator->context(), inputs, generator_params);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << "// overload to allow Target instead of GeneratorContext.\n";
stream << get_indent() << "inline static Outputs generate(\n";
indent_level++;
stream << get_indent() << "const Target& target,\n";
stream << get_indent() << "const Inputs& inputs,\n";
stream << get_indent() << "const GeneratorParams& generator_params = GeneratorParams()\n";
indent_level--;
stream << get_indent() << ")\n";
stream << get_indent() << "{\n";
indent_level++;
stream << get_indent() << "return generate(Halide::GeneratorContext(target), inputs, generator_params);\n";
indent_level--;
stream << get_indent() << "}\n";
stream << "\n";
stream << get_indent() << class_name << "() = delete;\n";
indent_level--;
stream << get_indent() << "};\n";
stream << "\n";
for (const auto &ns : reverse_view(namespaces)) {
stream << get_indent() << "} // namespace " << ns << "\n";
}
stream << "\n";
stream << get_indent() << "#endif // " << guard.str() << "\n";
}
const std::map<std::string, Type> &get_halide_type_enum_map() {
static const std::map<std::string, Type> halide_type_enum_map{
{"bool", Bool()},
{"int8", Int(8)},
{"int16", Int(16)},
{"int32", Int(32)},
{"int64", Int(64)},
{"uint8", UInt(8)},
{"uint16", UInt(16)},
{"uint32", UInt(32)},
{"uint64", UInt(64)},
{"float16", Float(16)},
{"float32", Float(32)},
{"float64", Float(64)},
{"bfloat16", BFloat(16)}};
return halide_type_enum_map;
}
std::string halide_type_to_c_source(const Type &t) {
static const std::map<halide_type_code_t, std::string> m = {
{halide_type_int, "Int"},
{halide_type_uint, "UInt"},
{halide_type_float, "Float"},
{halide_type_handle, "Handle"},
};
std::ostringstream oss;
oss << "Halide::" << m.at(t.code()) << "(" << t.bits() << +")";
return oss.str();
}
std::string halide_type_to_c_type(const Type &t) {
auto encode = [](const Type &t) -> int { return t.code() << 16 | t.bits(); };
static const std::map<int, std::string> m = {
{encode(Int(8)), "int8_t"},
{encode(Int(16)), "int16_t"},
{encode(Int(32)), "int32_t"},
{encode(Int(64)), "int64_t"},
{encode(UInt(1)), "bool"},
{encode(UInt(8)), "uint8_t"},
{encode(UInt(16)), "uint16_t"},
{encode(UInt(32)), "uint32_t"},
{encode(UInt(64)), "uint64_t"},
{encode(BFloat(16)), "uint16_t"}, // TODO: see Issues #3709, #3967
{encode(Float(16)), "uint16_t"}, // TODO: see Issues #3709, #3967
{encode(Float(32)), "float"},
{encode(Float(64)), "double"},
{encode(Handle(64)), "void*"}};
internal_assert(m.count(encode(t))) << t << " " << encode(t);
return m.at(encode(t));
}
namespace {
int generate_filter_main_inner(int argc,
char **argv,
const GeneratorFactoryProvider &generator_factory_provider) {
static const char kUsage[] = R"INLINE_CODE(
gengen
[-g GENERATOR_NAME] [-f FUNCTION_NAME] [-o OUTPUT_DIR] [-r RUNTIME_NAME]
[-d 1|0] [-e EMIT_OPTIONS] [-n FILE_BASE_NAME] [-p PLUGIN_NAME]
[-s AUTOSCHEDULER_NAME] [-t TIMEOUT]
target=target-string[,target-string...]
[generator_param=value [...]]
-d Build a module that is suitable for using for gradient descent calculation
in TensorFlow or PyTorch. See Generator::build_gradient_module()
documentation.
-e A comma separated list of files to emit. Accepted values are:
[assembly, bitcode, c_header, c_source, cpp_stub, featurization,
llvm_assembly, object, python_extension, pytorch_wrapper, registration,
schedule, static_library, stmt, stmt_html, conceptual_stmt,
conceptual_stmt_html, compiler_log, hlpipe, device_code].
If omitted, default value is [c_header, static_library, registration].
-p A comma-separated list of shared libraries that will be loaded before the
generator is run. Useful for custom auto-schedulers. The generator must
either be linked against a shared libHalide or compiled with -rdynamic
so that references in the shared library to libHalide can resolve.
(Note that this does not change the default autoscheduler; use the -s flag
to set that value.)"
-r The name of a standalone runtime to generate. Only honors EMIT_OPTIONS 'o'
and 'static_library'. When multiple targets are specified, it picks a
runtime that is compatible with all of the targets, or fails if it cannot
find one. Flags across all of the targets that do not affect runtime code
generation, such as `no_asserts` and `no_runtime`, are ignored.
-t Timeout for the Generator to run, in seconds; mainly useful to ensure that
bugs and/or degenerate cases don't stall build systems. Specify 0 to allow
infinite time. Defaults to infinite.
-v If nonzero, log the path to all generated files to stdout.
)INLINE_CODE";
std::map<std::string, std::string> flags_info = {
{"-d", "0"},
{"-e", ""},
{"-f", ""},
{"-g", ""},
{"-n", ""},
{"-o", ""},
{"-p", ""},
{"-r", ""},
{"-v", "0"},
{"-t", "0"},
};
ExecuteGeneratorArgs args;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] != '-') {
std::vector<std::string> v = split_string(argv[i], "=");
user_assert(v.size() == 2 && !v[0].empty() && !v[1].empty()) << kUsage;
args.generator_params[v[0]] = v[1];
} else if (auto it = flags_info.find(argv[i]); it != flags_info.end()) {
user_assert(i + 1 < argc) << kUsage;
it->second = argv[i + 1];
++i;
continue;
} else {
if (!strcmp(argv[i], "-s")) {
user_error << "-s is no longer supported for setting autoscheduler; specify autoschduler.name=NAME instead.\n"
<< kUsage;
}
user_error << "Unknown flag: " << argv[i] << "\n"
<< kUsage;
}
}
// It's possible that in the future loaded plugins might change
// how arguments are parsed, so we handle those first.
for (const auto &lib_path : split_string(flags_info["-p"], ",")) {
if (!lib_path.empty()) {
load_plugin(lib_path);
}
}
if (args.generator_params.count("auto_schedule")) {
user_error << "auto_schedule=true is no longer supported for enabling autoscheduling; specify autoscheduler=NAME instead.\n"
<< kUsage;
}
if (args.generator_params.count("machine_params")) {
user_error << "machine_params is no longer supported as a GeneratorParam; specify autoscheduler.FIELD=VALUE instead.\n"
<< kUsage;
}
const auto &d_val = flags_info["-d"];
user_assert(d_val == "1" || d_val == "0") << "-d must be 0 or 1\n"
<< kUsage;
const auto &v_val = flags_info["-v"];
user_assert(v_val == "1" || v_val == "0") << "-v must be 0 or 1\n"
<< kUsage;
const std::vector<std::string> generator_names = generator_factory_provider.enumerate();
const auto create_generator = [&](const std::string &generator_name, const Halide::GeneratorContext &context) -> AbstractGeneratorPtr {
internal_assert(generator_name == args.generator_name);
auto g = generator_factory_provider.create(generator_name, context);
if (!g) {
std::ostringstream o;
o << "Generator not found: " << generator_name << "\n";
o << "Did you mean:\n";
for (const auto &n : generator_names) {
o << " " << n << "\n";
}
user_error << o.str();
}
return g;
};
const auto build_target_strings = [](GeneratorParamsMap *gp) {
std::vector<std::string> target_strings;
if (gp->find("target") != gp->end()) {
target_strings = split_string((*gp)["target"], ",");
gp->erase("target");
}
return target_strings;
};
const auto build_targets = [](const std::vector<std::string> &target_strings) {
std::vector<Target> targets;
targets.reserve(target_strings.size());
for (const auto &s : target_strings) {
targets.emplace_back(s);
}
return targets;
};
const auto build_output_types = [&]() {
std::set<OutputFileType> output_types;
std::string emit_flags_string = flags_info["-e"];
// If omitted or empty, assume .a and .h and registration.cpp
if (emit_flags_string.empty()) {
emit_flags_string = "c_header,registration,static_library";
}
// If HL_EXTRA_OUTPUTS is defined, assume it's extra outputs we want to generate
// (usually for temporary debugging purposes) and just tack it on to the -e contents.
std::string extra_outputs = get_env_variable("HL_EXTRA_OUTPUTS");
if (!extra_outputs.empty()) {
if (!emit_flags_string.empty()) {
emit_flags_string += ",";
}
emit_flags_string += extra_outputs;
}
const std::vector<std::string> emit_flags = split_string(emit_flags_string, ",");
internal_assert(!emit_flags.empty()) << "Empty emit flags.\n";
// Build a reverse lookup table. Allow some legacy aliases on the command line,
// to allow legacy build systems to work more easily.
std::map<std::string, OutputFileType> output_name_to_enum = {
{"cpp", OutputFileType::c_source},
{"h", OutputFileType::c_header},
{"hlpipe", OutputFileType::hlpipe},
{"html", OutputFileType::stmt_html},
{"o", OutputFileType::object},
{"py.c", OutputFileType::python_extension},
};
// extensions won't vary across multitarget output
const Target t = args.targets.empty() ? Target() : args.targets[0];
const std::map<OutputFileType, const OutputInfo> output_info = get_output_info(t);
for (const auto &it : output_info) {
output_name_to_enum[it.second.name] = it.first;
}
for (const std::string &opt : emit_flags) {
auto it = output_name_to_enum.find(opt);
if (it == output_name_to_enum.end()) {
std::ostringstream o;
o << "Unrecognized emit option: " << opt << " is not one of [";
auto end = output_info.cend();
auto last = std::prev(end);
for (auto iter = output_info.cbegin(); iter != end; ++iter) {
o << iter->second.name;
if (iter != last) {
o << " ";
}
}
o << "], ignoring.\n";
o << kUsage;
user_error << o.str();
}
output_types.insert(it->second);
}
return output_types;
};
// Always specify target_strings for suffixes: if we omit this, we'll use *canonical* target strings
// for suffixes, but our caller might have passed non-canonical-but-still-legal target strings,
// and if we don't use those, the output filenames might not match what the caller expects.
args.suffixes = build_target_strings(&args.generator_params);
args.targets = build_targets(args.suffixes);
args.output_dir = flags_info["-o"];
args.output_types = build_output_types();
args.generator_name = flags_info["-g"];
args.function_name = flags_info["-f"];
args.file_base_name = flags_info["-n"];
args.runtime_name = flags_info["-r"];
args.build_mode = (d_val == "1") ? ExecuteGeneratorArgs::Gradient : ExecuteGeneratorArgs::Default;
args.create_generator = create_generator;
// args.generator_params is already set
// If true, log the path of all output files to stdout.
args.log_outputs = (v_val == "1");
// Allow quick-n-dirty use of compiler logging via HL_DEBUG_COMPILER_LOGGER env var
const bool do_compiler_logging = args.output_types.count(OutputFileType::compiler_log) ||
(get_env_variable("HL_DEBUG_COMPILER_LOGGER") == "1");
if (do_compiler_logging) {
const bool obfuscate_compiler_logging = get_env_variable("HL_OBFUSCATE_COMPILER_LOGGER") == "1";
args.compiler_logger_factory =
[obfuscate_compiler_logging, &args](const std::string &function_name, const Target &target) -> std::unique_ptr<CompilerLogger> {
// rebuild generator_args from the map so that they are always canonical
std::stringstream generator_args_string;
std::string autoscheduler_name;
std::string sep;
for (const auto &it : args.generator_params) {
std::string quote = it.second.find(' ') != std::string::npos ? "\\\"" : "";
generator_args_string << sep << it.first << "=" << quote << it.second << quote;
sep = " ";
if (it.first == "autoscheduler") {
autoscheduler_name = it.second;
}
}
std::unique_ptr<JSONCompilerLogger> t(new JSONCompilerLogger(
obfuscate_compiler_logging ? "" : args.generator_name,
obfuscate_compiler_logging ? "" : args.function_name,
obfuscate_compiler_logging ? "" : autoscheduler_name,
obfuscate_compiler_logging ? Target() : target,
obfuscate_compiler_logging ? "" : generator_args_string.str(),
obfuscate_compiler_logging));
return t;
};
}
// Do some preflighting here to emit errors that are likely from the command line
// but not necessarily from the API call.
user_assert(!(generator_names.empty() && args.runtime_name.empty()))
<< "No generators have been registered and not compiling a standalone runtime\n"
<< kUsage;
if (args.generator_name.empty() && args.runtime_name.empty()) {
// Require at least one of -g or -r to be specified.
std::ostringstream o;
o << "Either -g <name> or -r must be specified; available Generators are:\n";
if (!generator_names.empty()) {
for (const auto &name : generator_names) {
o << " " << name << "\n";
}
} else {
o << " <none>\n";
}
user_error << o.str();
}
execute_generator(args);
return 0;
}
class GeneratorsFromRegistry : public GeneratorFactoryProvider {
public:
GeneratorsFromRegistry() = default;
~GeneratorsFromRegistry() override = default;
std::vector<std::string> enumerate() const override {
return GeneratorRegistry::enumerate();
}
AbstractGeneratorPtr create(const std::string &name,
const Halide::GeneratorContext &context) const override {
return GeneratorRegistry::create(name, context);
}
};
} // namespace
const GeneratorFactoryProvider &get_registered_generators() {
static GeneratorsFromRegistry g;
return g;
}
} // namespace Internal
Callable create_callable_from_generator(const GeneratorContext &context,
const std::string &name,
const GeneratorParamsMap &generator_params) {
auto g = Internal::get_registered_generators().create(name, context);
user_assert(g != nullptr) << "There is no Generator with the name '" << name << "' currently available.";
g->set_generatorparam_values(generator_params);
return g->compile_to_callable();
}
Callable create_callable_from_generator(const Target &target,
const std::string &name,
const GeneratorParamsMap &generator_params) {
return create_callable_from_generator(GeneratorContext(target), name, generator_params);
}
namespace Internal {
#ifdef HALIDE_WITH_EXCEPTIONS
int generate_filter_main(int argc, char **argv, const GeneratorFactoryProvider &generator_factory_provider) {
try {
return generate_filter_main_inner(argc, argv, generator_factory_provider);
} catch (::Halide::Error &err) {
// Do *not* use user_error here (or elsewhere in this function): it
// will throw an exception, and since there is almost certainly no
// try/catch block in our caller, it will call std::terminate,
// swallowing all error messages.
std::cerr << "Unhandled exception: " << err.what() << "\n";
return -1;
} catch (std::exception &err) {
std::cerr << "Unhandled exception: " << err.what() << "\n";
return -1;
} catch (...) {
std::cerr << "Unhandled exception: (unknown)\n";
return -1;
}
}
#else
int generate_filter_main(int argc, char **argv, const GeneratorFactoryProvider &generator_factory_provider) {
return generate_filter_main_inner(argc, argv, generator_factory_provider);
}
#endif
int generate_filter_main(int argc, char **argv) {
return generate_filter_main(argc, argv, GeneratorsFromRegistry());
}
void execute_generator(const ExecuteGeneratorArgs &args_in) {
const auto fix_defaults = [](const ExecuteGeneratorArgs &args_in) -> ExecuteGeneratorArgs {
ExecuteGeneratorArgs args = args_in;
if (!args.create_generator) {
args.create_generator = [](const std::string &generator_name, const GeneratorContext &context) -> AbstractGeneratorPtr {
return GeneratorRegistry::create(generator_name, context);
};
}
if (!args.compiler_logger_factory) {
args.compiler_logger_factory = [](const std::string &, const Target &) -> std::unique_ptr<CompilerLogger> {
return nullptr;