forked from apache/tvm
-
Notifications
You must be signed in to change notification settings - Fork 3
/
zero_elimination.cc
2741 lines (2357 loc) · 97.6 KB
/
zero_elimination.cc
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) 2018 by Contributors
* \file zero_elimination.cc
* \brief Transform tensors in such a way as to eliminate summation over zeros.
*/
#include "zero_elimination.h"
#include <tvm/api_registry.h>
#include <tvm/ir_functor_ext.h>
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <tvm/ir_visitor.h>
#include <tvm/operation.h>
#include <dmlc/optional.h>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include "../op/op_util.h"
// Uncomment this line to make zero elimination very verbose
//#define ZERO_ELIMINATION_VERBOSE true
#ifdef ZERO_ELIMINATION_VERBOSE
#define ZE_LOG_NL() (std::cout << std::endl)
#define ZE_LOG(text, value) \
ZELog(std::string(__FUNCTION__) + ": " + text, (value))
#define ZE_LOG_VAR(var) ZE_LOG(#var, var)
#define ZE_LOG_RES(value) \
ZELog(std::string(__FUNCTION__) + " returned", (value))
#define ZE_LOG_ENTER() auto _ze_log_scope = ZELogScope(__FUNCTION__)
#else
#define ZE_LOG_NL()
#define ZE_LOG(text, value)
#define ZE_LOG_VAR(var)
#define ZE_LOG_RES(value) (value)
#define ZE_LOG_ENTER()
#endif
namespace tvm {
namespace ir {
// Convert a variable map into a sorted vector of pairs. Sorting is done with deep expr comparison.
template <typename T>
std::vector<std::pair<Var, T>> VarMapToVectorOfPairs(const Map<Var, T>& varmap) {
using tpair = std::pair<Var, T>;
std::vector<tpair> res;
for (const tpair& pair : varmap) {
res.push_back(pair);
}
std::sort(res.begin(), res.end(),
[](const tpair& l, const tpair& r) { return Compare(l.first, r.first) < 0; });
return res;
}
template <typename T>
struct PrintSortedVarMapImpl {
const Map<Var, T>& varmap_;
PrintSortedVarMapImpl(const Map<Var, T>& varmap) : varmap_(varmap) {}
};
template <typename T>
std::ostream& operator<<(std::ostream& stream, const PrintSortedVarMapImpl<T>& varmap) {
stream << "{";
bool first_iteration = true;
for (const auto& pair : VarMapToVectorOfPairs(varmap.varmap_)) {
if (!first_iteration) {
stream << ", ";
}
stream << pair.first << ": " << pair.second;
first_iteration = false;
}
stream << "}";
return stream;
}
// Print a variable map as a map sorted by variables
// Usage: std::cout << PrintSortedVarMap(varmap);
template <typename T>
PrintSortedVarMapImpl<T> PrintSortedVarMap(const Map<Var, T>& varmap) {
return PrintSortedVarMapImpl<T>(varmap);
}
#ifdef ZERO_ELIMINATION_VERBOSE
thread_local size_t ze_log_shift = 0;
class ZELogScope {
public:
std::string function_name;
explicit ZELogScope(const std::string& fname) : function_name(fname) {
std::cout << std::endl << std::string(ze_log_shift*2, ' ') << fname << " {" << std::endl;
++ze_log_shift;
}
~ZELogScope() {
--ze_log_shift;
std::cout << std::string(ze_log_shift*2, ' ')
<< "} end " << function_name << std::endl << std::endl;
}
};
template <typename tvalue>
tvalue ZELog(const std::string& message, tvalue&& val) {
std::cout << std::string(ze_log_shift*2, ' ')
<< message << " " << val << std::endl;
return val;
}
template <class tvalue>
Map<Var, tvalue> ZELog(const std::string& message, const Map<Var, tvalue>& val) {
std::cout << std::string(ze_log_shift*2, ' ')
<< message << " " << PrintSortedVarMap(val) << std::endl;
return val;
}
#endif
bool DoBadThings() {
static int step = 0;
static int bad_start = 0, bad_end = 0;
if (step == 0) {
if (getenv("TVM_ZE_BAD_START")) {
bad_start = std::atoi(getenv("TVM_ZE_BAD_START"));
}
if (getenv("TVM_ZE_BAD_END")) {
bad_end = std::atoi(getenv("TVM_ZE_BAD_END"));
}
}
++step;
ZE_LOG("step", step);
if (step >= bad_start && step < bad_end) {
ZE_LOG("Doing bad things!", "");
return true;
} else {
return false;
}
}
int gcd(int a, int b) {
if (a < b) std::swap(a, b);
while (b != 0) {
int64_t tmp = b;
b = a % b;
a = tmp;
}
return a;
}
int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
struct ExprLess {
bool operator()(const Expr& l, const Expr& r) const {
return Compare(l, r) < 0;
}
};
struct ExprEq {
bool operator()(const Expr& l, const Expr& r) const {
return Compare(l, r) == 0;
}
};
// Merge two maps, prefer the right one on conflict
template <class K, class V>
Map<K, V> Merge(Map<K, V> original, const Map<K, V>& update) {
for (const auto& p : update) {
original.Set(p.first, p.second);
}
return std::move(original);
}
// Concatenate two arrays
template <class T>
Array<T> Concat(Array<T> a, const Array<T>& b) {
for (const auto& x : b) {
a.push_back(x);
}
return std::move(a);
}
// Combine all expressions from the container using &&.
template <class container>
Expr All(const container& c) {
Expr res;
for (const auto& e : c) {
if (res.get()) {
res = res && e;
} else {
res = e;
}
}
if (res.get()) {
return res;
} else {
return const_true();
}
}
// Create a select statement of the form cond ? on_true : 0
Expr SelectElseZero(const Expr& cond, const Expr& on_true) {
return Select::make(cond, on_true, make_zero(on_true.type()));
}
// Simplify the expression as thoroughly as possible by using all available simplifiers.
Expr SuperSimplify(Expr e, const Map<Var, Range>& vranges = Map<Var, Range>()) {
// For some reason no simplifier can detect that there is only one value of the variable
std::unordered_map<const Variable*, Expr> vmap;
for (const auto& var_range : vranges) {
if (is_const_int(var_range.second->extent, 1)) {
vmap[var_range.first.get()] = var_range.second->min;
}
}
if (!vmap.empty()) {
e = Substitute(e, vmap);
}
arith::Analyzer an;
for (const auto& var_range : vranges) {
an.Bind(var_range.first, var_range.second);
}
// According to my experiments two best simplifications orders were can->rw and rw->can->rw,
// but rw->can->rw is better for a couple of cases.
// Note that we should end with rw because it factors multipliers out.
Expr res = e;
res = an.rewrite_simplify(res);
res = an.canonical_simplify(res);
res = an.rewrite_simplify(res);
return res;
}
// Provability check that uses SuperSimplify
bool CanProve(Expr e, const Map<Var, Range>& vranges = Map<Var, Range>()) {
return is_one(SuperSimplify(e, vranges));
}
class ExprFreeVarsVisitor : public IRVisitor {
public:
std::vector<Var> free_array;
std::unordered_set<const Variable*> bound;
std::unordered_set<const Variable*> free;
virtual void Visit(const NodeRef& node) {
if (const Variable* v = node.as<Variable>()) {
if (!bound.count(v) && !free.count(v)) {
free.insert(v);
free_array.push_back(Downcast<Var>(node));
}
} else {
IRVisitor::Visit(node);
}
}
void Visit_(const Variable* op) {
CHECK(false) << "This case shouldn't happen";
}
void Visit_(const LetStmt* op) {
bound.insert(op->var.get());
IRVisitor::Visit_(op);
}
void Visit_(const For* op) {
bound.insert(op->loop_var.get());
IRVisitor::Visit_(op);
}
void Visit_(const Let* op) {
bound.insert(op->var.get());
IRVisitor::Visit_(op);
}
void Visit_(const Reduce* op) {
for (const auto& iv : op->axis) {
bound.insert(iv->var.get());
}
IRVisitor::Visit_(op);
}
void Visit_(const Store* op) {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Allocate* op) {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Free* op) {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
void Visit_(const Load* op) {
Visit(op->buffer_var);
IRVisitor::Visit_(op);
}
};
// Get free variables of an expression
Array<Var> ExprFreeVars(const Expr& expr) {
ExprFreeVarsVisitor visitor;
visitor.Visit(expr);
return visitor.free_array;
}
DomainTransformation ComposeDomainTransformations(const DomainTransformation& first,
const DomainTransformation& second) {
CHECK(second->old_domain.same_as(first->new_domain));
Map<Var, Expr> new_to_old;
Map<Var, Expr> old_to_new;
for (auto p : second->new_to_old) {
new_to_old.Set(p.first, SuperSimplify(Substitute(p.second, first->new_to_old),
first->old_domain->ranges));
}
for (auto p : first->old_to_new) {
old_to_new.Set(p.first, SuperSimplify(Substitute(p.second, second->old_to_new),
second->new_domain->ranges));
}
return DomainTransformationNode::make(second->new_domain, first->old_domain,
new_to_old, old_to_new);
}
DomainTransformation DomainTransformation::operator+=(const DomainTransformation& other) {
*this = ComposeDomainTransformations(*this, other);
return *this;
}
DomainTransformation EmptyDomainTransformation(const Domain& domain) {
Map<Var, Expr> new_to_old;
Map<Var, Expr> old_to_new;
for (const Var& v : domain->variables) {
old_to_new.Set(v, make_zero(v.type()));
}
Domain new_domain = DomainNode::make({}, {make_zero(Bool())}, {});
return DomainTransformationNode::make(new_domain, domain, new_to_old, old_to_new);
}
DomainTransformation IdDomainTransformation(const Domain& domain) {
Map<Var, Expr> new_to_old;
for (const Var& v : domain->variables) {
new_to_old.Set(v, v);
}
return DomainTransformationNode::make(domain, domain, new_to_old, new_to_old);
}
// Convert an array of itervars to an array of inequalities
Array<Expr> IterVarsToInequalities(const Array<IterVar>& itervars) {
Array<Expr> res;
for (const IterVar& v : itervars) {
res.push_back(GE::make(v->var, v->dom->min));
res.push_back(LT::make(v->var, v->dom->min + v->dom->extent));
}
return res;
}
// Convert an array of itervars to a map from vars to ranges
Map<Var, Range> IterVarsToMap(const Array<IterVar>& itervars) {
Map<Var, Range> res;
for (const IterVar& v : itervars) {
res.Set(v->var, v->dom);
}
return res;
}
// Convert an array of itervars to an array of vars
Array<Var> IterVarsToVars(const Array<IterVar>& itervars) {
Array<Var> res;
for (const IterVar& v : itervars) {
res.push_back(v->var);
}
return res;
}
// Given a map from vars to ranges create an array of itervars
Array<IterVar> IterVarsFromMap(const Array<Var>& vars, const Map<Var, Range>& vranges,
IterVarType iter_type = kDataPar, std::string thread_tag = "") {
Array<IterVar> res;
for (const Var& v : vars) {
CHECK(vranges.count(v)) << "A range for the variable " << v
<< " was not provided in map " << vranges;
res.push_back(IterVarNode::make(vranges[v], v, iter_type, thread_tag));
}
return res;
}
// Return true if this combiner is just a sum.
bool IsSumCombiner(const CommReducer& combiner, const Map<Var, Range>& vranges) {
ZE_LOG_ENTER();
ZE_LOG_VAR(combiner);
ZE_LOG_VAR(vranges);
if (combiner->result.size() != 1) {
return ZE_LOG_RES(false);
}
if (!is_const_value(SuperSimplify(combiner->identity_element[0], vranges), 0)) {
return ZE_LOG_RES(false);
}
Expr combiner_result = SuperSimplify(combiner->result[0], vranges);
return ZE_LOG_RES(Equal(combiner_result, combiner->lhs[0] + combiner->rhs[0]) ||
Equal(combiner_result, combiner->rhs[0] + combiner->lhs[0]));
}
// Return true if zero may be factored out of a reduction with this combiner.
bool CanFactorZeroFromCombiner(const CommReducer& combiner, int value_index,
const Map<Var, Range>& vranges) {
ZE_LOG_ENTER();
ZE_LOG_VAR(combiner);
ZE_LOG_VAR(value_index);
ZE_LOG_VAR(vranges);
if (!is_const_value(SuperSimplify(combiner->identity_element[value_index], vranges), 0)) {
return ZE_LOG_RES(false);
}
Expr zero = make_zero(combiner->result[value_index].type());
Expr in = Substitute(combiner->result[value_index],
{{combiner->lhs[value_index], zero},
{combiner->rhs[value_index], zero}});
in = SuperSimplify(in, vranges);
return ZE_LOG_RES(is_const_value(in, 0));
}
// If expr is a Call node, perform inlining, otherwise do nothing
Expr InlineThisCall(const Expr& expr) {
ZE_LOG_ENTER();
ZE_LOG_VAR(expr);
if (const Call* op = expr.as<Call>()) {
if (op->call_type == Call::CallType::Halide) {
if (const ComputeOpNode* op_comp = op->func.as<ComputeOpNode>()) {
Array<Var> tensor_axes;
for (const auto& var : op_comp->axis) {
tensor_axes.push_back(var->var);
}
Stmt inlined = Inline(Evaluate::make(expr), op->func, tensor_axes,
op_comp->body[op->value_index]);
if (const ir::Evaluate* ev = inlined.as<ir::Evaluate>()) {
// If it is a reduction, clone it
return ZE_LOG_RES(op::CloneReduction(ev->value));
}
}
}
}
return ZE_LOG_RES(expr);
}
Tensor InlineTailCall(const Tensor& tensor) {
return op::TransformBody(tensor, InlineThisCall);
}
// Implements InlineTensors by trying to inline every Call of the given Expr
class InlineTensorsMutator : public IRMutator {
public:
explicit InlineTensorsMutator(const Array<Tensor>& inlineable, bool inline_reductions = false)
: inline_reductions_(inline_reductions) {
for (const Tensor& tensor : inlineable) {
inlineable_.emplace(tensor->op.operator->(), tensor->value_index);
}
}
Expr Mutate_(const Call* op, const Expr& e) {
if (op->call_type == Call::CallType::Halide) {
if (const ComputeOpNode* op_comp = op->func.as<ComputeOpNode>()) {
// Inline only if the array of inlineable tensors is empty or contains this tensor
if (inlineable_.empty() || inlineable_.count({op_comp, op->value_index})) {
// Inline only compute nodes that are not reductions (unless inline reductions is allowed)
if (inline_reductions_ || !op_comp->body[0].as<Reduce>()) {
// Inline this call and then try to perform further inlining
return Mutate(InlineThisCall(e));
}
}
}
}
// If we cannot inline this call, we should try to do inlining in its arguments
return IRMutator::Mutate_(op, e);
}
private:
// Tensors which are allowed to be inlined, represented as pairs (op_node, value_index)
std::set<std::pair<const OperationNode*, int>> inlineable_;
bool inline_reductions_;
};
Expr InlineTensors(const Expr& expr, const Array<Tensor>& inlineable,
bool inline_reductions) {
ZE_LOG_ENTER();
ZE_LOG_VAR(expr);
ZE_LOG_VAR(inlineable);
ZE_LOG_VAR(inline_reductions);
return ZE_LOG_RES(InlineTensorsMutator(inlineable, inline_reductions).Mutate(expr));
}
Tensor InlineTensors(const Tensor& tensor, const Array<Tensor>& inlineable,
bool inline_reductions) {
auto transformation =
[inlineable, inline_reductions](const Expr& e) {
return InlineTensorsMutator(inlineable, inline_reductions).Mutate(e); };
return op::TransformBody(tensor, transformation);
}
struct NonzeronessConditionResult {
Expr cond;
Expr value;
Expr to_expr() const {
return SelectElseZero(cond, value);
}
friend std::ostream& operator<<(std::ostream& os, const NonzeronessConditionResult& r) {
return os << r.to_expr();
}
};
// The implementation of NonzeronessCondition
class NonzeronessConditionFunctor
: public ExprFunctor<NonzeronessConditionResult(const Expr&, const Expr&)> {
public:
NonzeronessConditionResult NonzeronessCondition(const Expr& e) {
if (e.type().is_bool()) {
// Boolean expressions are non-zero whenever they are true themselves
return {e, const_true()};
} else {
return VisitExpr(e, e);
}
}
// Most of the cases are implemented using helpers below
result_type VisitExpr_(const Variable*, const Expr& e) final { return Default_(e); }
result_type VisitExpr_(const IntImm* op, const Expr& e) final { return Const_(op, e); }
result_type VisitExpr_(const UIntImm* op, const Expr& e) final { return Const_(op, e); }
result_type VisitExpr_(const FloatImm* op, const Expr& e) final { return Const_(op, e); }
result_type VisitExpr_(const StringImm*, const Expr& e) final { return Default_(e); }
result_type VisitExpr_(const Add* op, const Expr& e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Sub* op, const Expr& e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Mul* op, const Expr& e) final { return BinOpMulLike_(op, e); }
result_type VisitExpr_(const Div* op, const Expr& e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const Mod* op, const Expr& e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const FloorDiv* op, const Expr& e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const FloorMod* op, const Expr& e) final { return BinOpDivLike_(op, e); }
result_type VisitExpr_(const Min* op, const Expr& e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Max* op, const Expr& e) final { return BinOpAddLike_(op, e); }
result_type VisitExpr_(const Cast* op, const Expr& e) final {
auto nz_a = NonzeronessCondition(op->value);
if (nz_a.value.same_as(op->value)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, Cast::make(op->type, nz_a.value)};
}
}
result_type VisitExpr_(const Select* op, const Expr& e) final {
Expr cond = op->condition, true_val = op->true_value, false_val = op->false_value;
auto nz_a = NonzeronessCondition(true_val);
auto nz_b = NonzeronessCondition(false_val);
// If the false part is zero, we can get rid of the select
if (is_const_value(nz_b.value, 0)) {
Expr new_cond = SuperSimplify(nz_a.cond && cond);
return {new_cond, nz_a.value};
}
// If the true part is zero, we can also get rid of the select
if (is_const_value(nz_a.value, 0)) {
Expr new_cond = SuperSimplify(nz_b.cond && !cond);
return {new_cond, nz_b.value};
}
// Otherwise we retain the select and combine the conditions into this
Expr new_cond = SuperSimplify((cond && nz_a.cond) || (!cond && nz_b.cond));
if (nz_a.value.same_as(true_val) && nz_b.value.same_as(false_val)) {
return {new_cond, e};
} else {
return {new_cond, Select::make(cond, nz_a.value, nz_b.value)};
}
}
result_type VisitExpr_(const Call* op, const Expr& e) final {
if (op->name == intrinsic::tvm_if_then_else) {
Expr cond = op->args[0], true_val = op->args[1], false_val = op->args[2];
auto nz_a = NonzeronessCondition(true_val);
auto nz_b = NonzeronessCondition(false_val);
// We don't have as much freedom here as in the select case
// since the `if` must be preserved in any case
Expr new_cond = SuperSimplify((cond && nz_a.cond) || (!cond && nz_b.cond));
if (nz_a.value.same_as(true_val) && nz_b.value.same_as(false_val)) {
return {new_cond, e};
} else {
return {new_cond, if_then_else(cond, nz_a.value, nz_b.value)};
}
} else {
return Default_(e);
}
}
NonzeronessConditionResult Default_(const Expr& e) {
// This is always correct, so it's the default
return {const_true(), e};
}
template <class TNode>
NonzeronessConditionResult Const_(const TNode* op, const Expr& e) {
if (op->value == 0) {
return {const_false(), e};
} else {
return {const_true(), e};
}
}
template <class TNode>
NonzeronessConditionResult BinOpAddLike_(const TNode* op, const Expr& e) {
auto nz_a = NonzeronessCondition(op->a);
auto nz_b = NonzeronessCondition(op->b);
// For addition and similar ops the result may be nonzero if either of the arguments is
// nonzero, so we combine the conditions with Or.
if (Equal(nz_a.cond, nz_b.cond)) {
// If the conditions are the same, we don't need Or
if (nz_a.value.same_as(op->a) && nz_b.value.same_as(op->b)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, TNode::make(nz_a.value, nz_b.value)};
}
} else {
// Otherwise use Or
Expr new_cond = SuperSimplify(nz_a.cond || nz_b.cond);
// A little optimization: if the combined condition is the same as one of the inner
// conditions, we don't need to guard the inner value with a select, otherwise
// we create a select in the `to_expr` call.
Expr new_a = Equal(nz_a.cond, new_cond) ? nz_a.value : nz_a.to_expr();
Expr new_b = Equal(nz_b.cond, new_cond) ? nz_b.value : nz_b.to_expr();
Expr new_expr = TNode::make(new_a, new_b);
return {new_cond, new_expr};
}
}
template <class TNode>
NonzeronessConditionResult BinOpMulLike_(const TNode* op, const Expr& e) {
auto nz_a = NonzeronessCondition(op->a);
auto nz_b = NonzeronessCondition(op->b);
// For multiplication and similar ops the result may be nonzero if
// both the arguments are nonzero, so we combine with And.
Expr new_cond = SuperSimplify(nz_a.cond && nz_b.cond);
if (nz_a.value.same_as(op->a) && nz_b.value.same_as(op->b)) {
return {new_cond, e};
} else {
return {new_cond, TNode::make(nz_a.value, nz_b.value)};
}
}
template <class TNode>
NonzeronessConditionResult BinOpDivLike_(const TNode* op, const Expr& e) {
auto nz_a = NonzeronessCondition(op->a);
// For Div we simply use the condition of the numerator.
if (nz_a.value.same_as(op->a)) {
return {nz_a.cond, e};
} else {
return {nz_a.cond, TNode::make(nz_a.value, op->b)};
}
}
};
// Transform expr into a pair (condition, new_expr) such that the old expr is equivalent to
// `select(condition, new_expr, 0)`. The pair is represented as a struct for clarity.
NonzeronessConditionResult NonzeronessCondition(const Expr& expr) {
ZE_LOG_ENTER();
ZE_LOG_VAR(expr);
return ZE_LOG_RES(NonzeronessConditionFunctor().NonzeronessCondition(expr));
}
Expr LiftNonzeronessCondition(const Expr& expr) {
return NonzeronessCondition(expr).to_expr();
}
class NormalizeComparisonsMutator : public IRMutator {
public:
virtual Expr Mutate_(const EQ* op, const Expr& e) { return Make<EQ>(op->a, op->b); }
virtual Expr Mutate_(const NE* op, const Expr& e) { return Make<NE>(op->a, op->b); }
virtual Expr Mutate_(const LT* op, const Expr& e) { return Make<LT>(op->a, op->b); }
virtual Expr Mutate_(const LE* op, const Expr& e) { return Make<LE>(op->a, op->b); }
virtual Expr Mutate_(const GT* op, const Expr& e) { return Make<LT>(op->b, op->a); }
virtual Expr Mutate_(const GE* op, const Expr& e) { return Make<LE>(op->b, op->a); }
private:
template <class TNode>
Expr Make(const Expr& a, const Expr& b) {
// rewrite LT to LE for ints
if (std::is_same<TNode, LT>::value && (a.type().is_int() || a.type().is_uint())) {
return LE::make(SuperSimplify(a - b + 1), make_zero(a.type()));
}
return TNode::make(SuperSimplify(a - b), make_zero(a.type()));
}
};
// Rewrite every comparison into the form a == 0, a != 0, a <= 0, and sometimes for floats a < 0
Expr NormalizeComparisons(const Expr& expr) {
return NormalizeComparisonsMutator().Mutate(expr);
}
struct FactorOutAtomicFormulasResult {
std::vector<Expr> atomic_formulas;
Expr rest;
Expr to_expr() const {
Expr res = rest;
for (const Expr& e : atomic_formulas) {
res = And::make(e, res);
}
return res;
}
Array<Expr> to_array() const {
Array<Expr> res = atomic_formulas;
res.push_back(rest);
return res;
}
};
// The implementation of FactorOutAtomicFormulas
class FactorOutAtomicFormulasFunctor
: public ExprFunctor<FactorOutAtomicFormulasResult(const Expr&, const Expr&)> {
public:
result_type Atomic_(const Expr& e) {
// For atomic expressions the result is the expr itself with True as the residual
return {{e}, make_const(e.type(), 1)};
}
// This is basically the list of expression kinds that are considered atomic
result_type VisitExpr_(const Variable*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const Call*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const IntImm*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const UIntImm*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const EQ*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const NE*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const LE*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const LT*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const GE*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const GT*, const Expr& e) final { return Atomic_(e); }
result_type VisitExpr_(const Select* op, const Expr& e) final {
// Select can be rewritten through other logical ops
Expr expr = (op->condition && op->true_value) || (!op->condition && op->false_value);
return VisitExpr(expr, expr);
}
result_type VisitExpr_(const Not* op, const Expr& e) final {
// Not should be moved down
if (const Or* or_expr = op->a.as<Or>()) {
Expr expr = !or_expr->a && !or_expr->b;
return VisitExpr(expr, expr);
} else if (const And* and_expr = op->a.as<And>()) {
Expr expr = !and_expr->a || !and_expr->b;
return VisitExpr(expr, expr);
} if (const Select* sel_expr = op->a.as<Select>()) {
Expr expr = ((!sel_expr->condition || !sel_expr->true_value) &&
(sel_expr->condition || !sel_expr->false_value));
return VisitExpr(expr, expr);
}
return Atomic_(e);
}
result_type VisitExpr_(const And* op, const Expr& e) final {
auto res_a = VisitExpr(op->a, op->a);
auto res_b = VisitExpr(op->b, op->b);
// For the And case we return the union of the sets of atomic formulas
std::vector<Expr> res;
res.reserve(res_a.atomic_formulas.size() + res_b.atomic_formulas.size());
std::set_union(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(),
res_b.atomic_formulas.begin(), res_b.atomic_formulas.end(),
std::back_inserter(res),
ExprLess());
// And the residuals are combined with &&
return {res, res_a.rest && res_b.rest};
}
result_type VisitExpr_(const Mul* op, const Expr& e) final {
// Since we work with bools, for multiplication we do the same thing as for And
Expr e_and = op->a && op->b;
return VisitExpr(e_and, e_and);
}
result_type VisitExpr_(const Or* op, const Expr& e) final {
auto res_a = VisitExpr(op->a, op->a);
auto res_b = VisitExpr(op->b, op->b);
// For the Or case we intersect the sets of atomic formulas
std::vector<Expr> res;
res.reserve(std::min(res_a.atomic_formulas.size(), res_b.atomic_formulas.size()));
std::set_intersection(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(),
res_b.atomic_formulas.begin(), res_b.atomic_formulas.end(),
std::back_inserter(res),
ExprLess());
// Computing the residual is more complex: we have to compute the sets of atomic formulas
// which are left behind, and then combine them with the residuals into the new residual.
std::vector<Expr> new_cond_a;
new_cond_a.reserve(res_a.atomic_formulas.size() - res.size());
std::set_difference(res_a.atomic_formulas.begin(), res_a.atomic_formulas.end(),
res.begin(), res.end(),
std::back_inserter(new_cond_a),
ExprLess());
std::vector<Expr> new_cond_b;
new_cond_b.reserve(res_b.atomic_formulas.size() - res.size());
std::set_difference(res_b.atomic_formulas.begin(), res_b.atomic_formulas.end(),
res.begin(), res.end(),
std::back_inserter(new_cond_b),
ExprLess());
res_a.atomic_formulas = std::move(new_cond_a);
res_b.atomic_formulas = std::move(new_cond_b);
Expr new_rest = res_a.to_expr() || res_b.to_expr();
return {res, new_rest};
}
};
// Transform the given formula into a conjunction of atomic formulas (represented as an array)
// and a non-atomic residual. Atomic formulas are consts, calls, variables and comparisons (a <= b,
// etc), i.e. formulas which are not logical operators (||, &&, !) on the top level.
FactorOutAtomicFormulasResult FactorOutAtomicFormulas(const Expr& e) {
CHECK(e.type().is_bool());
return FactorOutAtomicFormulasFunctor().VisitExpr(e, e);
}
class RemoveRedundantInequalitiesMutator : public IRMutator {
public:
explicit RemoveRedundantInequalitiesMutator(Array<Expr> known) {
for (const Expr& cond : known) {
known_.push_back(SuperSimplify(cond));
}
}
virtual Expr Mutate_(const Select* op, const Expr& e) {
bool has_side_effect = HasSideEffect(e);
Expr new_cond = SuperSimplify(Mutate(op->condition));
if (is_one(new_cond) && !has_side_effect) {
return Mutate(op->true_value);
} else if (is_zero(new_cond) && !has_side_effect) {
return Mutate(op->false_value);
} else {
Array<Expr> new_known = known_;
for (const Expr& atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
// Note that we mutate only the true value with the new mutator
// TODO(sgrechanik-h): Update known conditions for the false value as well
return Select::make(new_cond, new_mutator.Mutate(op->true_value), Mutate(op->false_value));
}
}
virtual Expr Mutate_(const Call* op, const Expr& e) {
if (op->name == intrinsic::tvm_if_then_else) {
Expr new_cond = SuperSimplify(Mutate(op->args[0]));
if (is_one(new_cond)) {
return Mutate(op->args[1]);
} else if (is_zero(new_cond)) {
return Mutate(op->args[2]);
} else {
Array<Expr> new_known = known_;
for (const Expr& atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
// Note that we mutate only the true value with the new mutator
// TODO(sgrechanik-h): Update known conditions for the false value as well
return if_then_else(new_cond, new_mutator.Mutate(op->args[1]), Mutate(op->args[2]));
}
} else {
return IRMutator::Mutate_(op, e);
}
}
virtual Expr Mutate_(const Reduce* op, const Expr& e) {
Array<Expr> known_with_axes = known_;
for (const Expr& axis_cond : IterVarsToInequalities(op->axis)) {
known_with_axes.push_back(axis_cond);
}
RemoveRedundantInequalitiesMutator mutator_with_axes(known_with_axes);
Expr new_cond = mutator_with_axes.Mutate(op->condition);
Array<Expr> new_known = known_with_axes;
for (const Expr& atomic : FactorOutAtomicFormulas(new_cond).atomic_formulas) {
new_known.push_back(atomic);
}
RemoveRedundantInequalitiesMutator new_mutator(new_known);
Array<Expr> new_source;
for (const Expr& src : op->source) {
new_source.push_back(new_mutator.Mutate(src));
}
return Reduce::make(op->combiner, new_source, op->axis, new_cond, op->value_index);
}
virtual Expr Mutate_(const EQ* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const NE* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const LT* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const LE* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const GT* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const GE* op, const Expr& e) { return MutateAtomic_(e); }
virtual Expr Mutate_(const And* op, const Expr& e) {
return Mutate(op->a) && Mutate(op->b);
}
private:
Expr MutateAtomic_(const Expr& e) {
Expr simplified = SuperSimplify(e);
for (const Expr& other : known_) {
if (Equal(simplified, other)) {
return const_true();
}
}
return simplified;
}
Array<Expr> known_;
};
// Propagate information from conditions and remove redundant inequalities
// TODO(sgrechanik-h): This should be merged into standard simplifiers
Expr RemoveRedundantInequalities(const Expr& expr, const Array<Expr>& known) {
ZE_LOG_ENTER();
ZE_LOG_VAR(expr);
ZE_LOG_VAR(known);
return ZE_LOG_RES(RemoveRedundantInequalitiesMutator(known).Mutate(expr));
}
struct EliminateDivModResult {
Expr expr;
Map<Var, Expr> substitution;
Array<Var> new_variables;
Array<Expr> conditions;
Map<Var, Range> ranges;
};
// TODO: This is a duplicate of the same enum from canonical_simplify.cc, they should be merged
enum DivMode {
/*! \brief Truncated division. */
kTruncDiv,
/*! \brief Floor division. */
kFloorDiv
};
inline Expr ModImpl(Expr a, Expr b, DivMode mode) {
if (mode == kTruncDiv) {
return truncmod(a, b);
} else {
CHECK_EQ(mode, kFloorDiv);
return floormod(a, b);
}
}
inline Expr DivImpl(Expr a, Expr b, DivMode mode) {
if (mode == kTruncDiv) {
return truncdiv(a, b);
} else {
CHECK_EQ(mode, kFloorDiv);
return floordiv(a, b);
}
}
class EliminateDivModMutator : public IRMutator {
public: