forked from intel/yarpgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpr.cpp
2412 lines (2167 loc) · 87.2 KB
/
expr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2015-2020, Intel Corporation
Copyright (c) 2019-2020, University of Utah
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//////////////////////////////////////////////////////////////////////////////
#include "expr.h"
#include "context.h"
#include "options.h"
#include <algorithm>
#include <deque>
#include <utility>
using namespace yarpgen;
std::unordered_map<std::shared_ptr<Data>, std::shared_ptr<ScalarVarUseExpr>>
yarpgen::ScalarVarUseExpr::scalar_var_use_set;
std::unordered_map<std::shared_ptr<Data>, std::shared_ptr<ArrayUseExpr>>
yarpgen::ArrayUseExpr::array_use_set;
std::unordered_map<std::shared_ptr<Data>, std::shared_ptr<IterUseExpr>>
yarpgen::IterUseExpr::iter_use_set;
std::shared_ptr<Data> Expr::getValue() {
// TODO: it might cause some problems in the future, but it is good for now
return value;
}
std::vector<std::shared_ptr<ConstantExpr>> yarpgen::ConstantExpr::used_consts;
ConstantExpr::ConstantExpr(IRValue _value) {
// TODO: maybe we need a constant data type rather than an anonymous scalar
// variable
value = std::make_shared<ScalarVar>(
"", IntegralType::init(_value.getIntTypeID()), _value);
}
Expr::EvalResType ConstantExpr::evaluate(EvalCtx &ctx) { return value; }
Expr::EvalResType ConstantExpr::rebuild(EvalCtx &ctx) { return evaluate(ctx); }
void ConstantExpr::emit(std::shared_ptr<EmitCtx> ctx, std::ostream &stream,
std::string offset) {
assert(value->isScalarVar() &&
"ConstExpr can represent only scalar constant");
auto scalar_var = std::static_pointer_cast<ScalarVar>(value);
assert(scalar_var->getType()->isIntType() &&
"ConstExpr can represent only scalar integral constant");
auto int_type =
std::static_pointer_cast<IntegralType>(scalar_var->getType());
auto emit_helper = [&stream, &int_type, &ctx]() {
if (int_type->getIntTypeId() < IntTypeID::INT)
stream << "(" << int_type->getName(ctx) << ")";
};
IRValue val = scalar_var->getCurrentValue();
IRValue min_val = int_type->getMin();
IntTypeID max_type_id =
int_type->getIsSigned() ? IntTypeID::LLONG : IntTypeID::ULLONG;
val = val.castToType(max_type_id);
min_val = min_val.castToType(max_type_id);
if (!int_type->getIsSigned() || (val != min_val).getValueRef<bool>()) {
emit_helper();
stream << val << int_type->getLiteralSuffix();
return;
}
// INT_MIN is defined as -INT_MAX - 1, so we have to do the same
IRValue one(max_type_id);
// TODO: this is not an appropriate way to do it
one.setValue(IRValue::AbsValue{false, 1});
IRValue min_one_val = min_val + one;
emit_helper();
stream << "(" << min_one_val << int_type->getLiteralSuffix() << " - " << one
<< int_type->getLiteralSuffix() << ")";
}
std::shared_ptr<ConstantExpr>
ConstantExpr::create(std::shared_ptr<PopulateCtx> ctx) {
auto gen_pol = ctx->getGenPolicy();
bool reuse_const = rand_val_gen->getRandId(gen_pol->reuse_const_prob);
std::shared_ptr<ConstantExpr> ret;
bool can_add_to_buf = true;
bool can_use_offset = true;
IntTypeID type_id;
std::shared_ptr<IntegralType> int_type;
if (reuse_const && !used_consts.empty()) {
bool use_transformation =
rand_val_gen->getRandId(gen_pol->use_const_transform_distr);
ret = rand_val_gen->getRandElem(used_consts);
can_add_to_buf = use_transformation;
assert(ret->getKind() == IRNodeKind::CONST &&
"Buffer of used constants should contain only constants");
auto scalar_val = std::static_pointer_cast<ScalarVar>(ret->getValue());
int_type =
std::static_pointer_cast<IntegralType>(scalar_val->getType());
type_id = int_type->getIntTypeId();
if (use_transformation) {
UnaryOp transformation =
rand_val_gen->getRandId(gen_pol->const_transform_distr);
IRValue ir_val = scalar_val->getCurrentValue();
IntTypeID active_type_id = type_id;
// TODO: do we need to cast to unsigned also?
if (type_id < IntTypeID::INT) {
if (int_type->getIsSigned())
active_type_id = IntTypeID::INT;
else
active_type_id = IntTypeID::UINT;
ir_val = ir_val.castToType(active_type_id);
}
auto active_int_type = IntegralType::init(active_type_id);
if (transformation == UnaryOp::BIT_NOT ||
(transformation == UnaryOp::NEGATE &&
(ir_val == active_int_type->getMin()).getValueRef<bool>()))
ir_val = ~ir_val;
else if (transformation == UnaryOp::NEGATE)
ir_val = -ir_val;
else
ERROR("Unsupported constant transformation");
if (type_id < IntTypeID::INT)
ir_val = ir_val.castToType(type_id);
ret = std::make_shared<ConstantExpr>(ir_val);
}
}
else {
bool use_special_const =
rand_val_gen->getRandId(gen_pol->use_special_const_distr);
type_id = rand_val_gen->getRandId(gen_pol->int_type_distr);
int_type = IntegralType::init(type_id);
IRValue init_val(type_id);
if (use_special_const) {
SpecialConst special_const_kind =
rand_val_gen->getRandId(gen_pol->special_const_distr);
// Utility function for EndBits and BitBlock
auto fill_bits = [](size_t start, size_t end) -> uint64_t {
assert(end >= start &&
"Ends should be sorted in increasing order");
return (end - start) == 63
? UINT64_MAX
: ((1ULL << (end - start + 1)) - 1ULL) << start;
};
if (special_const_kind == SpecialConst::ZERO)
init_val.setValue(IRValue::AbsValue{false, 0});
else if (special_const_kind == SpecialConst::MIN)
init_val = int_type->getMin();
else if (special_const_kind == SpecialConst::MAX)
init_val = int_type->getMax();
else if (special_const_kind == SpecialConst::BIT_BLOCK) {
size_t start = rand_val_gen->getRandValue(
static_cast<size_t>(0), int_type->getBitSize() - 1);
size_t end = rand_val_gen->getRandValue(
start, int_type->getBitSize() - 1);
init_val.setValue(
IRValue::AbsValue{false, fill_bits(start, end)});
// TODO: does it make sense?
can_use_offset = false;
}
else if (special_const_kind == SpecialConst::END_BITS) {
size_t bit_idx = rand_val_gen->getRandValue(
static_cast<size_t>(0), int_type->getBitSize() - 1);
bool use_lsb_end =
rand_val_gen->getRandId(gen_pol->use_lsb_bit_end_distr);
if (use_lsb_end)
init_val.setValue(
IRValue::AbsValue{false, fill_bits(0, bit_idx)});
else
init_val.setValue(IRValue::AbsValue{
false, fill_bits(0, int_type->getBitSize() - 1)});
// TODO: does it make sense?
can_use_offset = false;
}
else
ERROR("Bad special const kind");
}
else
init_val = rand_val_gen->getRandValue(type_id);
ret = std::make_shared<ConstantExpr>(init_val);
}
bool use_offset = rand_val_gen->getRandId(gen_pol->use_const_offset_distr);
if (can_use_offset && use_offset) {
IRValue ir_val = std::static_pointer_cast<ScalarVar>(ret->getValue())
->getCurrentValue();
IRValue offset(type_id);
if (type_id < IntTypeID::INT) {
// TODO: do we need to cast to unsigned also?
if (int_type->getIsSigned()) {
offset = offset.castToType(IntTypeID::INT);
ir_val = ir_val.castToType(IntTypeID::INT);
}
else {
offset = offset.castToType(IntTypeID::UINT);
ir_val = ir_val.castToType(IntTypeID::UINT);
}
}
size_t offset_size =
rand_val_gen->getRandId(gen_pol->const_offset_distr);
offset.setValue(IRValue::AbsValue{false, offset_size});
bool pos_offset =
rand_val_gen->getRandId(gen_pol->pos_const_offset_distr);
if (pos_offset)
ir_val = ir_val + offset;
else
ir_val = ir_val - offset;
if (type_id < IntTypeID::INT)
ir_val = ir_val.castToType(type_id);
if (!ir_val.hasUB()) {
ret = std::make_shared<ConstantExpr>(ir_val);
can_add_to_buf = true;
}
}
bool replace_in_buf =
rand_val_gen->getRandId(gen_pol->replace_in_buf_distr);
// If we are inside mutation, we can't change the buffer. Otherwise,
// this will affect the state of the random generator outside of the mutated
// region
if (!ctx->isInsideMutation() && can_add_to_buf && replace_in_buf) {
if (used_consts.size() < gen_pol->const_buf_size)
used_consts.push_back(ret);
else {
auto replaced_const = rand_val_gen->getRandElem(used_consts);
replaced_const = ret;
}
}
return ret;
}
std::shared_ptr<ScalarVarUseExpr>
ScalarVarUseExpr::init(std::shared_ptr<Data> _val) {
assert(_val->isScalarVar() &&
"ScalarVarUseExpr accepts only scalar variables!");
auto find_res = scalar_var_use_set.find(_val);
if (find_res != scalar_var_use_set.end())
return find_res->second;
auto ret = std::make_shared<ScalarVarUseExpr>(_val);
scalar_var_use_set[_val] = ret;
return ret;
}
void ScalarVarUseExpr::setValue(std::shared_ptr<Expr> _expr) {
std::shared_ptr<Data> new_val = _expr->getValue();
assert(new_val->isScalarVar() && "Can store only scalar variables!");
if (value->getType() != new_val->getType())
ERROR("Can't assign different types!");
std::static_pointer_cast<ScalarVar>(value)->setCurrentValue(
std::static_pointer_cast<ScalarVar>(new_val)->getCurrentValue());
}
Expr::EvalResType ScalarVarUseExpr::evaluate(EvalCtx &ctx) {
// This variable is defined and we can just return it.
auto find_res = ctx.input.find(value->getName(EmitCtx::default_emit_ctx));
if (find_res != ctx.input.end()) {
return find_res->second;
}
return value;
}
Expr::EvalResType ScalarVarUseExpr::rebuild(EvalCtx &ctx) {
return evaluate(ctx);
}
std::shared_ptr<ScalarVarUseExpr>
ScalarVarUseExpr::create(std::shared_ptr<PopulateCtx> ctx) {
auto avail_vars = ctx->getExtInpSymTable()->getAvailVars();
return rand_val_gen->getRandElem(avail_vars);
}
std::shared_ptr<ArrayUseExpr> ArrayUseExpr::init(std::shared_ptr<Data> _val) {
assert(_val->isArray() &&
"ArrayUseExpr can be initialized only with Arrays");
auto find_res = array_use_set.find(_val);
if (find_res != array_use_set.end())
return find_res->second;
auto ret = std::make_shared<ArrayUseExpr>(_val);
array_use_set[_val] = ret;
return ret;
}
void ArrayUseExpr::setValue(std::shared_ptr<Expr> _expr,
std::deque<size_t> &span,
std::deque<size_t> &steps) {
/*
std::shared_ptr<Data> new_val = _expr->getValue();
assert(new_val->isArray() && "ArrayUseExpr can store only Arrays");
auto new_array = std::static_pointer_cast<Array>(new_val);
if (value->getType() != new_array->getType()) {
ERROR("Can't assign incompatible types");
}
*/
auto arr_val = std::static_pointer_cast<Array>(value);
if (!_expr->getValue()->isScalarVar())
ERROR("Only scalar variables are supported for now");
auto expr_scalar_var =
std::static_pointer_cast<ScalarVar>(_expr->getValue());
arr_val->setValue(expr_scalar_var->getCurrentValue(), span, steps);
}
Expr::EvalResType ArrayUseExpr::evaluate(EvalCtx &ctx) {
// This Array is defined and we can just return it.
auto find_res = ctx.input.find(value->getName(EmitCtx::default_emit_ctx));
if (find_res != ctx.input.end()) {
return find_res->second;
}
return value;
}
Expr::EvalResType ArrayUseExpr::rebuild(EvalCtx &ctx) { return evaluate(ctx); }
std::shared_ptr<IterUseExpr> IterUseExpr::init(std::shared_ptr<Data> _iter) {
assert(_iter->isIterator() && "IterUseExpr accepts only iterators!");
auto find_res = iter_use_set.find(_iter);
if (find_res != iter_use_set.end())
return find_res->second;
auto ret = std::make_shared<IterUseExpr>(_iter);
iter_use_set[_iter] = ret;
return ret;
}
void IterUseExpr::setValue(std::shared_ptr<Expr> _expr) {
std::shared_ptr<Data> new_val = _expr->getValue();
assert(new_val->isIterator() && "IterUseExpr can store only iterators!");
auto new_iter = std::static_pointer_cast<Iterator>(new_val);
if (value->getType() != new_iter->getType())
ERROR("Can't assign different types!");
std::static_pointer_cast<Iterator>(value)->setParameters(
new_iter->getStart(), new_iter->getEnd(), new_iter->getStep());
}
Expr::EvalResType IterUseExpr::evaluate(EvalCtx &ctx) {
// This iterator is defined and we can just return it.
auto find_res = ctx.input.find(value->getName(EmitCtx::default_emit_ctx));
if (find_res != ctx.input.end()) {
return find_res->second;
}
return value;
}
Expr::EvalResType IterUseExpr::rebuild(EvalCtx &ctx) { return evaluate(ctx); }
TypeCastExpr::TypeCastExpr(std::shared_ptr<Expr> _expr,
std::shared_ptr<Type> _to_type, bool _is_implicit)
: expr(std::move(_expr)), to_type(std::move(_to_type)),
is_implicit(_is_implicit) {
propagateType();
}
bool TypeCastExpr::propagateType() {
assert(to_type->isIntType() && "We can cast only integral types for now");
auto to_int_type = std::static_pointer_cast<IntegralType>(to_type);
value = std::make_shared<ScalarVar>("", to_int_type,
IRValue(to_int_type->getIntTypeId()));
return true;
}
void TypeCastExpr::emit(std::shared_ptr<EmitCtx> ctx, std::ostream &stream,
std::string offset) {
// TODO: add switch for C++ style conversions and switch for implicit casts
stream << "((" << (is_implicit ? "/* implicit */" : "")
<< to_type->getName(ctx) << ") ";
expr->emit(ctx, stream);
stream << ")";
}
std::shared_ptr<TypeCastExpr>
TypeCastExpr::create(std::shared_ptr<PopulateCtx> ctx) {
auto gen_pol = ctx->getGenPolicy();
// TODO: we might want to create TypeCastExpr not only to integer types
IntTypeID to_type = rand_val_gen->getRandId(gen_pol->int_type_distr);
auto expr = ArithmeticExpr::create(ctx);
Options &options = Options::getInstance();
bool is_uniform = true;
if (options.isISPC()) {
EvalCtx eval_ctx;
EvalResType expr_val = expr->evaluate(eval_ctx);
is_uniform = expr_val->getType()->isUniform();
}
return std::make_shared<TypeCastExpr>(
expr, IntegralType::init(to_type, false, CVQualifier::NONE, is_uniform),
/*is_implicit*/ false);
}
Expr::EvalResType TypeCastExpr::evaluate(EvalCtx &ctx) {
EvalResType expr_eval_res = expr->evaluate(ctx);
std::shared_ptr<Type> base_type = expr_eval_res->getType();
// Check that we try to convert between compatible types.
if (!((base_type->isIntType() && to_type->isIntType()) ||
(base_type->isArrayType() && to_type->isArrayType()))) {
ERROR("Can't create TypeCastExpr for types that can't be casted");
}
if (base_type->isIntType() && expr_eval_res->isScalarVar()) {
std::shared_ptr<IntegralType> to_int_type =
std::static_pointer_cast<IntegralType>(to_type);
auto scalar_val = std::make_shared<ScalarVar>(
"", to_int_type, IRValue(to_int_type->getIntTypeId()));
std::shared_ptr<ScalarVar> base_scalar_var =
std::static_pointer_cast<ScalarVar>(expr_eval_res);
scalar_val->setCurrentValue(
base_scalar_var->getCurrentValue().castToType(
to_int_type->getIntTypeId()));
Options &options = Options::getInstance();
if (options.isISPC()) {
if (to_int_type->isUniform() && !base_type->isUniform())
ERROR("Can't cast varying to uniform");
}
value = scalar_val;
}
else {
// TODO: extend it
ERROR("We can cast only integer scalar variables for now");
}
return value;
}
Expr::EvalResType TypeCastExpr::rebuild(EvalCtx &ctx) {
propagateType();
expr->rebuild(ctx);
std::shared_ptr<Data> eval_res = evaluate(ctx);
assert(eval_res->getKind() == DataKind::VAR &&
"Type Cast operations are only supported for Scalar Variables");
auto eval_scalar_res = std::static_pointer_cast<ScalarVar>(eval_res);
if (!eval_scalar_res->getCurrentValue().hasUB()) {
value = eval_res;
return eval_res;
}
do {
eval_res = evaluate(ctx);
eval_scalar_res = std::static_pointer_cast<ScalarVar>(eval_res);
if (!eval_scalar_res->getCurrentValue().hasUB())
break;
rebuild(ctx);
} while (eval_scalar_res->getCurrentValue().hasUB());
value = eval_res;
return value;
}
std::shared_ptr<Expr> ArithmeticExpr::integralProm(std::shared_ptr<Expr> arg) {
if (!arg->getValue()->isScalarVar()) {
ERROR("Can perform integral promotion only on scalar variables");
}
// C++ draft N4713: 7.6 Integral promotions [conv.prom]
assert(arg->getValue()->getType()->isIntType() &&
"Scalar variable can have only Integral Type");
std::shared_ptr<IntegralType> int_type =
std::static_pointer_cast<IntegralType>(arg->getValue()->getType());
if (int_type->getIntTypeId() >=
IntTypeID::INT) // can't perform integral promotion
return arg;
// TODO: we need to check if type fits in int or unsigned int
return std::make_shared<TypeCastExpr>(
arg,
IntegralType::init(IntTypeID::INT, false, CVQualifier::NONE,
arg->getValue()->getType()->isUniform()),
true);
}
std::shared_ptr<Expr> ArithmeticExpr::convToBool(std::shared_ptr<Expr> arg) {
if (!arg->getValue()->isScalarVar()) {
ERROR("Can perform conversion to bool only on scalar variables");
}
std::shared_ptr<IntegralType> int_type =
std::static_pointer_cast<IntegralType>(arg->getValue()->getType());
if (int_type->getIntTypeId() == IntTypeID::BOOL)
return arg;
return std::make_shared<TypeCastExpr>(
arg,
IntegralType::init(IntTypeID::BOOL, false, CVQualifier::NONE,
arg->getValue()->getType()->isUniform()),
true);
}
void ArithmeticExpr::arithConv(std::shared_ptr<Expr> &lhs,
std::shared_ptr<Expr> &rhs) {
if (!lhs->getValue()->getType()->isIntType() ||
!rhs->getValue()->getType()->isIntType()) {
ERROR("We assume that we can perform binary operations only in Scalar "
"Variables with integral type");
}
auto lhs_type =
std::static_pointer_cast<IntegralType>(lhs->getValue()->getType());
auto rhs_type =
std::static_pointer_cast<IntegralType>(rhs->getValue()->getType());
// C++ draft N4713: 8.3 Usual arithmetic conversions [expr.arith.conv]
// 1.5.1
if (lhs_type->getIntTypeId() == rhs_type->getIntTypeId())
return;
// 1.5.2
if (lhs_type->getIsSigned() == rhs_type->getIsSigned()) {
std::shared_ptr<IntegralType> max_type =
lhs_type->getIntTypeId() > rhs_type->getIntTypeId() ? lhs_type
: rhs_type;
if (lhs_type->getIntTypeId() > rhs_type->getIntTypeId())
rhs = std::make_shared<TypeCastExpr>(rhs, max_type,
/*is_implicit*/ true);
else
lhs = std::make_shared<TypeCastExpr>(lhs, max_type,
/*is_implicit*/ true);
return;
}
// 1.5.3
// Helper function that converts signed type to "bigger" unsigned type
auto signed_to_unsigned_conv = [](std::shared_ptr<IntegralType> &a_type,
std::shared_ptr<IntegralType> &b_type,
std::shared_ptr<Expr> &b_expr) -> bool {
if (!a_type->getIsSigned() &&
(a_type->getIntTypeId() >= b_type->getIntTypeId())) {
b_expr = std::make_shared<TypeCastExpr>(b_expr, a_type,
/*is_implicit*/ true);
return true;
}
return false;
};
if (signed_to_unsigned_conv(lhs_type, rhs_type, rhs) ||
signed_to_unsigned_conv(rhs_type, lhs_type, lhs))
return;
// 1.5.4
// Same idea, but for unsigned to signed conversions
auto unsigned_to_signed_conv = [](std::shared_ptr<IntegralType> &a_type,
std::shared_ptr<IntegralType> &b_type,
std::shared_ptr<Expr> &b_expr) -> bool {
if (a_type->getIsSigned() &&
IntegralType::canRepresentType(a_type->getIntTypeId(),
b_type->getIntTypeId())) {
b_expr = std::make_shared<TypeCastExpr>(b_expr, a_type,
/*is_implicit*/ true);
return true;
}
return false;
};
if (unsigned_to_signed_conv(lhs_type, rhs_type, rhs) ||
unsigned_to_signed_conv(rhs_type, lhs_type, lhs))
return;
// 1.5.5
auto final_conversion = [](std::shared_ptr<IntegralType> &a_type,
std::shared_ptr<Expr> &a_expr,
std::shared_ptr<Expr> &b_expr) -> bool {
if (a_type->getIsSigned()) {
std::shared_ptr<IntegralType> new_type = IntegralType::init(
IntegralType::getCorrUnsigned(a_type->getIntTypeId()));
if (!a_type->isUniform())
new_type = std::static_pointer_cast<IntegralType>(
new_type->makeVarying());
a_expr = std::make_shared<TypeCastExpr>(a_expr, new_type,
/*is_implicit*/ true);
b_expr = std::make_shared<TypeCastExpr>(b_expr, new_type,
/*is_implicit*/ true);
return true;
}
return false;
};
if (final_conversion(lhs_type, lhs, rhs) ||
final_conversion(rhs_type, lhs, rhs))
return;
ERROR("Unreachable: conversions went wrong");
}
void ArithmeticExpr::varyingPromotion(std::shared_ptr<Expr> &lhs,
std::shared_ptr<Expr> &rhs) {
auto lhs_type = lhs->getValue()->getType();
auto rhs_type = rhs->getValue()->getType();
auto varying_conversion = [](std::shared_ptr<Type> &a_type,
std::shared_ptr<Type> &b_type,
std::shared_ptr<Expr> &b_expr) -> bool {
if (!a_type->isUniform() && b_type->isUniform()) {
auto new_type = b_type->makeVarying();
b_expr = std::make_shared<TypeCastExpr>(b_expr, new_type,
/*is_implicit*/ true);
return true;
}
return false;
};
if (varying_conversion(lhs_type, rhs_type, rhs) ||
varying_conversion(rhs_type, lhs_type, lhs))
return;
}
static std::shared_ptr<Expr> createStencil(std::shared_ptr<PopulateCtx> ctx) {
auto gen_pol = ctx->getGenPolicy();
std::shared_ptr<Expr> new_node;
// Disable other kind of leaf exprs
// TODO: This is not the best option
std::vector<Probability<IRNodeKind>> new_node_distr;
auto find_prob = [&gen_pol](IRNodeKind kind) -> uint64_t {
auto find_res = std::find_if(
gen_pol->arith_node_distr.begin(), gen_pol->arith_node_distr.end(),
[kind](Probability<IRNodeKind> prob) -> bool {
return prob.getId() == kind;
});
return (find_res != gen_pol->arith_node_distr.end())
? find_res->getProb()
: 0;
};
uint64_t stencil_prob = find_prob(IRNodeKind::STENCIL);
uint64_t scalar_var_prob = find_prob(IRNodeKind::SCALAR_VAR_USE);
uint64_t subscript_prob = find_prob(IRNodeKind::SUBSCRIPT);
uint64_t const_prob = find_prob(IRNodeKind::CONST);
uint64_t total_prob =
stencil_prob + scalar_var_prob + subscript_prob + const_prob;
subscript_prob = static_cast<uint64_t>(
total_prob * gen_pol->stencil_prob_weight_alternation);
const_prob = scalar_var_prob = static_cast<uint64_t>(
total_prob * (1 - gen_pol->stencil_prob_weight_alternation) * 0.5);
for (auto &item : gen_pol->arith_node_distr) {
Probability<IRNodeKind> prob = item;
if (item.getId() == IRNodeKind::SCALAR_VAR_USE)
prob.setProb(scalar_var_prob);
else if (item.getId() == IRNodeKind::CONST)
prob.setProb(const_prob);
else if (item.getId() == IRNodeKind::SUBSCRIPT)
prob.setProb(subscript_prob);
else if (item.getId() == IRNodeKind::STENCIL)
continue;
new_node_distr.push_back(prob);
}
auto new_gen_pol = std::make_shared<GenPolicy>(*gen_pol);
new_gen_pol->arith_node_distr = new_node_distr;
auto new_ctx = std::make_shared<PopulateCtx>(*ctx);
new_ctx->setGenPolicy(new_gen_pol);
// Pick arrays for stencil
auto avail_arrays = SubscriptExpr::getSuitableArrays(new_ctx);
size_t arrs_in_stencil_num =
rand_val_gen->getRandId(gen_pol->arrs_in_stencil_distr);
auto used_arrays =
rand_val_gen->getRandElems(avail_arrays, arrs_in_stencil_num);
std::vector<ArrayStencilParams> stencils;
stencils.reserve(arrs_in_stencil_num);
for (auto &i : used_arrays) {
stencils.emplace_back(i);
}
// Pick dimensions
// We need to process only special cases here. If each array use have its
// own set of offsets, then they will be generated later
bool same_dims_each =
rand_val_gen->getRandId(gen_pol->stencil_same_dims_one_arr_distr);
bool same_dims_all =
rand_val_gen->getRandId(gen_pol->stencil_same_dims_all_distr);
if (same_dims_each || same_dims_all) {
for (auto &stencil : stencils) {
assert(new_ctx->getDimensions().size() > 0 &&
"Can't create stencil in scalar context!");
size_t num_of_dims_used = rand_val_gen->getRandValue(
static_cast<size_t>(1), new_ctx->getDimensions().size());
// We want to save information about iterator and
// dimension's idx correspondence
std::vector<std::pair<size_t, std::shared_ptr<Iterator>>> dims_idx;
// We check if iterator can be used to create a
// subscription expr with offset
for (size_t i = 0; i < new_ctx->getDimensions().size(); ++i) {
auto used_iter = new_ctx->getLocalSymTable()->getIters().at(i);
size_t max_left_offset = used_iter->getMaxLeftOffset();
size_t max_right_offset = used_iter->getMaxRightOffset();
bool non_zero_offset_exists =
(max_left_offset > 0) || (max_right_offset > 0);
if (non_zero_offset_exists)
dims_idx.emplace_back(i, used_iter);
}
auto chosen_dims =
rand_val_gen->getRandElems(dims_idx, num_of_dims_used);
// Then we sort iterators and suitable dimensions in order
auto cmp_func =
[](std::pair<size_t, std::shared_ptr<Iterator>> a,
std::pair<size_t, std::shared_ptr<Iterator>> b) -> bool {
return a.first < b.first;
};
std::sort(chosen_dims.begin(), chosen_dims.end(), cmp_func);
// We use binary vector to indicate if dimension can be used for
// subscript expr with offset. Now we convert chosen active
// dimensions indexes to such vector
std::vector<std::pair<size_t, std::shared_ptr<Iterator>>>
new_dims_params(new_ctx->getDimensions().size(),
std::make_pair(false, nullptr));
for (const auto &chosen_dim : chosen_dims)
new_dims_params.at(chosen_dim.first) =
std::make_pair(true, chosen_dim.second);
// After that we split vector of pairs into binary vector and
// iterators vector to add that info into stencil parameters
std::vector<size_t> new_dims;
std::vector<std::shared_ptr<Iterator>> new_iters;
for (auto it = std::make_move_iterator(new_dims_params.begin()),
end = std::make_move_iterator(new_dims_params.end());
it != end; ++it) {
new_dims.push_back(it->first);
new_iters.push_back(std::move(it->second));
}
if (same_dims_all) {
for (auto &item : stencils) {
item.setActiveDims(new_dims);
item.setIters(new_iters);
}
break;
}
// If same_dims_each is set is the only possible case
stencil.setActiveDims(new_dims);
stencil.setIters(new_iters);
}
}
// Generate offsets for special cases
bool reuse_offset =
rand_val_gen->getRandId(gen_pol->stencil_reuse_offset_distr);
// Here we process only special cases. General case is handled by each
// subscription expr itself
if (same_dims_all && reuse_offset) {
std::vector<int64_t> used_offsets(new_ctx->getDimensions().size(), 0);
auto &active_dims = stencils.front().getActiveDims();
for (size_t i = 0; i < new_ctx->getDimensions().size(); ++i) {
// All offsets are supposed to be the same, so we can pick the first
// one
if (!active_dims.at(i))
continue;
auto used_iter = new_ctx->getLocalSymTable()->getIters().at(i);
size_t max_left_offset = used_iter->getMaxLeftOffset();
size_t max_right_offset = used_iter->getMaxRightOffset();
bool non_zero_offset_exists =
(max_left_offset > 0) || (max_right_offset > 0);
int64_t offset = 0;
if (non_zero_offset_exists) {
while (offset == 0)
offset = rand_val_gen->getRandValue(
-static_cast<int64_t>(max_left_offset),
static_cast<int64_t>(max_right_offset));
}
used_offsets.at(i) = offset;
}
for (auto &stencil : stencils)
stencil.setOffsets(used_offsets);
}
new_ctx->getLocalSymTable()->setStencilsParams(stencils);
new_ctx->setInStencil(true);
new_node = ArithmeticExpr::create(new_ctx);
new_ctx->setInStencil(false);
return new_node;
}
std::shared_ptr<Expr> ArithmeticExpr::create(std::shared_ptr<PopulateCtx> ctx) {
auto gen_pol = ctx->getGenPolicy();
std::shared_ptr<Expr> new_node;
ctx->incArithDepth();
auto active_ctx = std::make_shared<PopulateCtx>(*ctx);
if (active_ctx->getArithDepth() == gen_pol->max_arith_depth) {
// We can have only constants, variables and arrays as leaves
std::vector<Probability<IRNodeKind>> new_node_distr;
for (auto &item : gen_pol->arith_node_distr) {
if (item.getId() == IRNodeKind::CONST ||
item.getId() == IRNodeKind::SCALAR_VAR_USE ||
item.getId() == IRNodeKind::SUBSCRIPT)
new_node_distr.push_back(item);
}
bool zero_prob = true;
for (auto &item : new_node_distr) {
if (item.getProb())
zero_prob = false;
}
// If after the option shuffling probability of all appropriate leaves
// was set to zero, we need a backup-plan. We just bump it to some
// value.
if (zero_prob) {
for (auto &item : new_node_distr) {
item.increaseProb(GenPolicy::leaves_prob_bump);
}
}
auto new_gen_policy = std::make_shared<GenPolicy>(*gen_pol);
new_gen_policy->arith_node_distr = new_node_distr;
active_ctx->setGenPolicy(new_gen_policy);
}
gen_pol = active_ctx->getGenPolicy();
bool apply_similar_op =
rand_val_gen->getRandId(gen_pol->apply_similar_op_distr);
if (apply_similar_op) {
auto new_gen_policy = std::make_shared<GenPolicy>(*gen_pol);
gen_pol = new_gen_policy;
gen_pol->chooseAndApplySimilarOp();
active_ctx->setGenPolicy(gen_pol);
}
bool apply_const_use =
rand_val_gen->getRandId(gen_pol->apply_const_use_distr);
if (apply_const_use) {
auto new_gen_policy = std::make_shared<GenPolicy>(*gen_pol);
gen_pol = new_gen_policy;
gen_pol->chooseAndApplyConstUse();
active_ctx->setGenPolicy(gen_pol);
}
IRNodeKind node_kind = rand_val_gen->getRandId(gen_pol->arith_node_distr);
if (node_kind == IRNodeKind::CONST) {
new_node = ConstantExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::SCALAR_VAR_USE ||
((active_ctx->getExtInpSymTable()->getArrays().empty() ||
active_ctx->getLocalSymTable()->getIters().empty()) &&
(node_kind == IRNodeKind::SUBSCRIPT ||
node_kind == IRNodeKind::STENCIL))) {
auto new_scalar_var_use_expr = ScalarVarUseExpr::create(active_ctx);
new_scalar_var_use_expr->setIsDead(false);
new_node = new_scalar_var_use_expr;
}
else if (node_kind == IRNodeKind::SUBSCRIPT) {
auto new_subs_expr = SubscriptExpr::create(active_ctx);
new_subs_expr->setIsDead(false);
new_node = new_subs_expr;
}
else if (node_kind == IRNodeKind::TYPE_CAST) {
new_node = TypeCastExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::UNARY) {
new_node = UnaryExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::BINARY) {
new_node = BinaryExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::CALL) {
new_node = LibCallExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::TERNARY) {
new_node = TernaryExpr::create(active_ctx);
}
else if (node_kind == IRNodeKind::STENCIL) {
new_node = createStencil(active_ctx);
}
else
ERROR("Bad node kind");
ctx->decArithDepth();
if (ctx->getArithDepth() == 0) {
Options &options = Options::getInstance();
bool allow_ub = !ctx->isTaken() &&
(options.getAllowUBInDC() == OptionLevel::ALL ||
(options.getAllowUBInDC() == OptionLevel::SOME &&
rand_val_gen->getRandId(gen_pol->ub_in_dc_prob)));
// We normally generate UB in the first place and eliminate it later.
// If we don't do anything to avoid it, we will get it for free
if (!allow_ub) {
new_node->propagateType();
EvalCtx eval_ctx;
new_node->rebuild(eval_ctx);
}
}
return new_node;
}
bool UnaryExpr::propagateType() {
arg->propagateType();
switch (op) {
case UnaryOp::PLUS:
case UnaryOp::NEGATE:
case UnaryOp::BIT_NOT:
arg = integralProm(arg);
break;
case UnaryOp::LOG_NOT:
arg = convToBool(arg);
break;
case UnaryOp::MAX_UN_OP:
ERROR("Bad unary operator");
break;
}
return true;
}
Expr::EvalResType UnaryExpr::evaluate(EvalCtx &ctx) {
propagateType();
EvalResType eval_res = arg->evaluate(ctx);
assert(eval_res->getKind() == DataKind::VAR &&
"Unary operations are supported for Scalar Variables only");
auto scalar_arg = std::static_pointer_cast<ScalarVar>(arg->getValue());
IRValue new_val;
switch (op) {
case UnaryOp::PLUS:
new_val = +scalar_arg->getCurrentValue();
break;
case UnaryOp::NEGATE:
new_val = -scalar_arg->getCurrentValue();
break;
case UnaryOp::LOG_NOT:
new_val = !scalar_arg->getCurrentValue();
break;
case UnaryOp::BIT_NOT:
new_val = ~scalar_arg->getCurrentValue();
break;
case UnaryOp::MAX_UN_OP:
ERROR("Bad unary operator");
break;
}
assert(scalar_arg->getType()->isIntType() &&
"Unary operations are supported for Scalar Variables of Integral "
"Types only");
value = std::make_shared<ScalarVar>(
"",
IntegralType::init(new_val.getIntTypeID(), false, CVQualifier::NONE,
arg->getValue()->getType()->isUniform()),
new_val);
return value;
}
Expr::EvalResType UnaryExpr::rebuild(EvalCtx &ctx) {
propagateType();
arg->rebuild(ctx);
EvalResType eval_res = evaluate(ctx);
assert(eval_res->getKind() == DataKind::VAR &&
"Unary operations are supported for Scalar Variables of Integral "
"Types only");
auto eval_scalar_res = std::static_pointer_cast<ScalarVar>(eval_res);
if (!eval_scalar_res->getCurrentValue().hasUB()) {
value = eval_res;
return value;
}
if (op == UnaryOp::NEGATE) {
op = UnaryOp::PLUS;
}
else {
ERROR("Something went wrong, this should be unreachable");
}
do {
eval_res = evaluate(ctx);
eval_scalar_res = std::static_pointer_cast<ScalarVar>(eval_res);
if (!eval_scalar_res->getCurrentValue().hasUB())
break;
rebuild(ctx);
} while (eval_scalar_res->getCurrentValue().hasUB());
value = eval_res;
return value;
}
void UnaryExpr::emit(std::shared_ptr<EmitCtx> ctx, std::ostream &stream,
std::string offset) {