-
Notifications
You must be signed in to change notification settings - Fork 12.3k
/
RangeConstraintManager.cpp
2283 lines (1932 loc) · 86.9 KB
/
RangeConstraintManager.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
//== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines RangeConstraintManager, a class that tracks simple
// equality and inequality constraints on symbolic values of ProgramState.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/JsonSupport.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/ImmutableSet.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
// This class can be extended with other tables which will help to reason
// about ranges more precisely.
class OperatorRelationsTable {
static_assert(BO_LT < BO_GT && BO_GT < BO_LE && BO_LE < BO_GE &&
BO_GE < BO_EQ && BO_EQ < BO_NE,
"This class relies on operators order. Rework it otherwise.");
public:
enum TriStateKind {
False = 0,
True,
Unknown,
};
private:
// CmpOpTable holds states which represent the corresponding range for
// branching an exploded graph. We can reason about the branch if there is
// a previously known fact of the existence of a comparison expression with
// operands used in the current expression.
// E.g. assuming (x < y) is true that means (x != y) is surely true.
// if (x previous_operation y) // < | != | >
// if (x operation y) // != | > | <
// tristate // True | Unknown | False
//
// CmpOpTable represents next:
// __|< |> |<=|>=|==|!=|UnknownX2|
// < |1 |0 |* |0 |0 |* |1 |
// > |0 |1 |0 |* |0 |* |1 |
// <=|1 |0 |1 |* |1 |* |0 |
// >=|0 |1 |* |1 |1 |* |0 |
// ==|0 |0 |* |* |1 |0 |1 |
// !=|1 |1 |* |* |0 |1 |0 |
//
// Columns stands for a previous operator.
// Rows stands for a current operator.
// Each row has exactly two `Unknown` cases.
// UnknownX2 means that both `Unknown` previous operators are met in code,
// and there is a special column for that, for example:
// if (x >= y)
// if (x != y)
// if (x <= y)
// False only
static constexpr size_t CmpOpCount = BO_NE - BO_LT + 1;
const TriStateKind CmpOpTable[CmpOpCount][CmpOpCount + 1] = {
// < > <= >= == != UnknownX2
{True, False, Unknown, False, False, Unknown, True}, // <
{False, True, False, Unknown, False, Unknown, True}, // >
{True, False, True, Unknown, True, Unknown, False}, // <=
{False, True, Unknown, True, True, Unknown, False}, // >=
{False, False, Unknown, Unknown, True, False, True}, // ==
{True, True, Unknown, Unknown, False, True, False}, // !=
};
static size_t getIndexFromOp(BinaryOperatorKind OP) {
return static_cast<size_t>(OP - BO_LT);
}
public:
constexpr size_t getCmpOpCount() const { return CmpOpCount; }
static BinaryOperatorKind getOpFromIndex(size_t Index) {
return static_cast<BinaryOperatorKind>(Index + BO_LT);
}
TriStateKind getCmpOpState(BinaryOperatorKind CurrentOP,
BinaryOperatorKind QueriedOP) const {
return CmpOpTable[getIndexFromOp(CurrentOP)][getIndexFromOp(QueriedOP)];
}
TriStateKind getCmpOpStateForUnknownX2(BinaryOperatorKind CurrentOP) const {
return CmpOpTable[getIndexFromOp(CurrentOP)][CmpOpCount];
}
};
//===----------------------------------------------------------------------===//
// RangeSet implementation
//===----------------------------------------------------------------------===//
void RangeSet::IntersectInRange(BasicValueFactory &BV, Factory &F,
const llvm::APSInt &Lower,
const llvm::APSInt &Upper,
PrimRangeSet &newRanges,
PrimRangeSet::iterator &i,
PrimRangeSet::iterator &e) const {
// There are six cases for each range R in the set:
// 1. R is entirely before the intersection range.
// 2. R is entirely after the intersection range.
// 3. R contains the entire intersection range.
// 4. R starts before the intersection range and ends in the middle.
// 5. R starts in the middle of the intersection range and ends after it.
// 6. R is entirely contained in the intersection range.
// These correspond to each of the conditions below.
for (/* i = begin(), e = end() */; i != e; ++i) {
if (i->To() < Lower) {
continue;
}
if (i->From() > Upper) {
break;
}
if (i->Includes(Lower)) {
if (i->Includes(Upper)) {
newRanges =
F.add(newRanges, Range(BV.getValue(Lower), BV.getValue(Upper)));
break;
} else
newRanges = F.add(newRanges, Range(BV.getValue(Lower), i->To()));
} else {
if (i->Includes(Upper)) {
newRanges = F.add(newRanges, Range(i->From(), BV.getValue(Upper)));
break;
} else
newRanges = F.add(newRanges, *i);
}
}
}
const llvm::APSInt &RangeSet::getMinValue() const {
assert(!isEmpty());
return begin()->From();
}
const llvm::APSInt &RangeSet::getMaxValue() const {
assert(!isEmpty());
// NOTE: It's a shame that we can't implement 'getMaxValue' without scanning
// the whole tree to get to the last element.
// llvm::ImmutableSet should support decrement for 'end' iterators
// or reverse order iteration.
auto It = begin();
for (auto End = end(); std::next(It) != End; ++It) {
}
return It->To();
}
bool RangeSet::pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
if (isEmpty()) {
// This range is already infeasible.
return false;
}
// This function has nine cases, the cartesian product of range-testing
// both the upper and lower bounds against the symbol's type.
// Each case requires a different pinning operation.
// The function returns false if the described range is entirely outside
// the range of values for the associated symbol.
APSIntType Type(getMinValue());
APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
switch (LowerTest) {
case APSIntType::RTR_Below:
switch (UpperTest) {
case APSIntType::RTR_Below:
// The entire range is outside the symbol's set of possible values.
// If this is a conventionally-ordered range, the state is infeasible.
if (Lower <= Upper)
return false;
// However, if the range wraps around, it spans all possible values.
Lower = Type.getMinValue();
Upper = Type.getMaxValue();
break;
case APSIntType::RTR_Within:
// The range starts below what's possible but ends within it. Pin.
Lower = Type.getMinValue();
Type.apply(Upper);
break;
case APSIntType::RTR_Above:
// The range spans all possible values for the symbol. Pin.
Lower = Type.getMinValue();
Upper = Type.getMaxValue();
break;
}
break;
case APSIntType::RTR_Within:
switch (UpperTest) {
case APSIntType::RTR_Below:
// The range wraps around, but all lower values are not possible.
Type.apply(Lower);
Upper = Type.getMaxValue();
break;
case APSIntType::RTR_Within:
// The range may or may not wrap around, but both limits are valid.
Type.apply(Lower);
Type.apply(Upper);
break;
case APSIntType::RTR_Above:
// The range starts within what's possible but ends above it. Pin.
Type.apply(Lower);
Upper = Type.getMaxValue();
break;
}
break;
case APSIntType::RTR_Above:
switch (UpperTest) {
case APSIntType::RTR_Below:
// The range wraps but is outside the symbol's set of possible values.
return false;
case APSIntType::RTR_Within:
// The range starts above what's possible but ends within it (wrap).
Lower = Type.getMinValue();
Type.apply(Upper);
break;
case APSIntType::RTR_Above:
// The entire range is outside the symbol's set of possible values.
// If this is a conventionally-ordered range, the state is infeasible.
if (Lower <= Upper)
return false;
// However, if the range wraps around, it spans all possible values.
Lower = Type.getMinValue();
Upper = Type.getMaxValue();
break;
}
break;
}
return true;
}
// Returns a set containing the values in the receiving set, intersected with
// the closed range [Lower, Upper]. Unlike the Range type, this range uses
// modular arithmetic, corresponding to the common treatment of C integer
// overflow. Thus, if the Lower bound is greater than the Upper bound, the
// range is taken to wrap around. This is equivalent to taking the
// intersection with the two ranges [Min, Upper] and [Lower, Max],
// or, alternatively, /removing/ all integers between Upper and Lower.
RangeSet RangeSet::Intersect(BasicValueFactory &BV, Factory &F,
llvm::APSInt Lower, llvm::APSInt Upper) const {
PrimRangeSet newRanges = F.getEmptySet();
if (isEmpty() || !pin(Lower, Upper))
return newRanges;
PrimRangeSet::iterator i = begin(), e = end();
if (Lower <= Upper)
IntersectInRange(BV, F, Lower, Upper, newRanges, i, e);
else {
// The order of the next two statements is important!
// IntersectInRange() does not reset the iteration state for i and e.
// Therefore, the lower range most be handled first.
IntersectInRange(BV, F, BV.getMinValue(Upper), Upper, newRanges, i, e);
IntersectInRange(BV, F, Lower, BV.getMaxValue(Lower), newRanges, i, e);
}
return newRanges;
}
// Returns a set containing the values in the receiving set, intersected with
// the range set passed as parameter.
RangeSet RangeSet::Intersect(BasicValueFactory &BV, Factory &F,
const RangeSet &Other) const {
PrimRangeSet newRanges = F.getEmptySet();
for (iterator i = Other.begin(), e = Other.end(); i != e; ++i) {
RangeSet newPiece = Intersect(BV, F, i->From(), i->To());
for (iterator j = newPiece.begin(), ee = newPiece.end(); j != ee; ++j) {
newRanges = F.add(newRanges, *j);
}
}
return newRanges;
}
// Turn all [A, B] ranges to [-B, -A], when "-" is a C-like unary minus
// operation under the values of the type.
//
// We also handle MIN because applying unary minus to MIN does not change it.
// Example 1:
// char x = -128; // -128 is a MIN value in a range of 'char'
// char y = -x; // y: -128
// Example 2:
// unsigned char x = 0; // 0 is a MIN value in a range of 'unsigned char'
// unsigned char y = -x; // y: 0
//
// And it makes us to separate the range
// like [MIN, N] to [MIN, MIN] U [-N,MAX].
// For instance, whole range is {-128..127} and subrange is [-128,-126],
// thus [-128,-127,-126,.....] negates to [-128,.....,126,127].
//
// Negate restores disrupted ranges on bounds,
// e.g. [MIN, B] => [MIN, MIN] U [-B, MAX] => [MIN, B].
RangeSet RangeSet::Negate(BasicValueFactory &BV, Factory &F) const {
PrimRangeSet newRanges = F.getEmptySet();
if (isEmpty())
return newRanges;
const llvm::APSInt sampleValue = getMinValue();
const llvm::APSInt &MIN = BV.getMinValue(sampleValue);
const llvm::APSInt &MAX = BV.getMaxValue(sampleValue);
// Handle a special case for MIN value.
iterator i = begin();
const llvm::APSInt &from = i->From();
const llvm::APSInt &to = i->To();
if (from == MIN) {
// If [from, to] are [MIN, MAX], then just return the same [MIN, MAX].
if (to == MAX) {
newRanges = ranges;
} else {
// Add separate range for the lowest value.
newRanges = F.add(newRanges, Range(MIN, MIN));
// Skip adding the second range in case when [from, to] are [MIN, MIN].
if (to != MIN) {
newRanges = F.add(newRanges, Range(BV.getValue(-to), MAX));
}
}
// Skip the first range in the loop.
++i;
}
// Negate all other ranges.
for (iterator e = end(); i != e; ++i) {
// Negate int values.
const llvm::APSInt &newFrom = BV.getValue(-i->To());
const llvm::APSInt &newTo = BV.getValue(-i->From());
// Add a negated range.
newRanges = F.add(newRanges, Range(newFrom, newTo));
}
if (newRanges.isSingleton())
return newRanges;
// Try to find and unite next ranges:
// [MIN, MIN] & [MIN + 1, N] => [MIN, N].
iterator iter1 = newRanges.begin();
iterator iter2 = std::next(iter1);
if (iter1->To() == MIN && (iter2->From() - 1) == MIN) {
const llvm::APSInt &to = iter2->To();
// remove adjacent ranges
newRanges = F.remove(newRanges, *iter1);
newRanges = F.remove(newRanges, *newRanges.begin());
// add united range
newRanges = F.add(newRanges, Range(MIN, to));
}
return newRanges;
}
RangeSet RangeSet::Delete(BasicValueFactory &BV, Factory &F,
const llvm::APSInt &Point) const {
llvm::APSInt Upper = Point;
llvm::APSInt Lower = Point;
++Upper;
--Lower;
// Notice that the lower bound is greater than the upper bound.
return Intersect(BV, F, Upper, Lower);
}
void RangeSet::print(raw_ostream &os) const {
bool isFirst = true;
os << "{ ";
for (iterator i = begin(), e = end(); i != e; ++i) {
if (isFirst)
isFirst = false;
else
os << ", ";
os << '[' << i->From().toString(10) << ", " << i->To().toString(10)
<< ']';
}
os << " }";
}
REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
namespace {
class EquivalenceClass;
} // end anonymous namespace
REGISTER_MAP_WITH_PROGRAMSTATE(ClassMap, SymbolRef, EquivalenceClass)
REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
namespace {
/// This class encapsulates a set of symbols equal to each other.
///
/// The main idea of the approach requiring such classes is in narrowing
/// and sharing constraints between symbols within the class. Also we can
/// conclude that there is no practical need in storing constraints for
/// every member of the class separately.
///
/// Main terminology:
///
/// * "Equivalence class" is an object of this class, which can be efficiently
/// compared to other classes. It represents the whole class without
/// storing the actual in it. The members of the class however can be
/// retrieved from the state.
///
/// * "Class members" are the symbols corresponding to the class. This means
/// that A == B for every member symbols A and B from the class. Members of
/// each class are stored in the state.
///
/// * "Trivial class" is a class that has and ever had only one same symbol.
///
/// * "Merge operation" merges two classes into one. It is the main operation
/// to produce non-trivial classes.
/// If, at some point, we can assume that two symbols from two distinct
/// classes are equal, we can merge these classes.
class EquivalenceClass : public llvm::FoldingSetNode {
public:
/// Find equivalence class for the given symbol in the given state.
LLVM_NODISCARD static inline EquivalenceClass find(ProgramStateRef State,
SymbolRef Sym);
/// Merge classes for the given symbols and return a new state.
LLVM_NODISCARD static inline ProgramStateRef
merge(BasicValueFactory &BV, RangeSet::Factory &F, ProgramStateRef State,
SymbolRef First, SymbolRef Second);
// Merge this class with the given class and return a new state.
LLVM_NODISCARD inline ProgramStateRef merge(BasicValueFactory &BV,
RangeSet::Factory &F,
ProgramStateRef State,
EquivalenceClass Other);
/// Return a set of class members for the given state.
LLVM_NODISCARD inline SymbolSet getClassMembers(ProgramStateRef State);
/// Return true if the current class is trivial in the given state.
LLVM_NODISCARD inline bool isTrivial(ProgramStateRef State);
/// Return true if the current class is trivial and its only member is dead.
LLVM_NODISCARD inline bool isTriviallyDead(ProgramStateRef State,
SymbolReaper &Reaper);
LLVM_NODISCARD static inline ProgramStateRef
markDisequal(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, SymbolRef First, SymbolRef Second);
LLVM_NODISCARD static inline ProgramStateRef
markDisequal(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, EquivalenceClass First,
EquivalenceClass Second);
LLVM_NODISCARD inline ProgramStateRef
markDisequal(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, EquivalenceClass Other) const;
LLVM_NODISCARD static inline ClassSet
getDisequalClasses(ProgramStateRef State, SymbolRef Sym);
LLVM_NODISCARD inline ClassSet
getDisequalClasses(ProgramStateRef State) const;
LLVM_NODISCARD inline ClassSet
getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const;
LLVM_NODISCARD static inline Optional<bool>
areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second);
/// Check equivalence data for consistency.
LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED static bool
isClassDataConsistent(ProgramStateRef State);
LLVM_NODISCARD QualType getType() const {
return getRepresentativeSymbol()->getType();
}
EquivalenceClass() = delete;
EquivalenceClass(const EquivalenceClass &) = default;
EquivalenceClass &operator=(const EquivalenceClass &) = delete;
EquivalenceClass(EquivalenceClass &&) = default;
EquivalenceClass &operator=(EquivalenceClass &&) = delete;
bool operator==(const EquivalenceClass &Other) const {
return ID == Other.ID;
}
bool operator<(const EquivalenceClass &Other) const { return ID < Other.ID; }
bool operator!=(const EquivalenceClass &Other) const {
return !operator==(Other);
}
static void Profile(llvm::FoldingSetNodeID &ID, uintptr_t CID) {
ID.AddInteger(CID);
}
void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, this->ID); }
private:
/* implicit */ EquivalenceClass(SymbolRef Sym)
: ID(reinterpret_cast<uintptr_t>(Sym)) {}
/// This function is intended to be used ONLY within the class.
/// The fact that ID is a pointer to a symbol is an implementation detail
/// and should stay that way.
/// In the current implementation, we use it to retrieve the only member
/// of the trivial class.
SymbolRef getRepresentativeSymbol() const {
return reinterpret_cast<SymbolRef>(ID);
}
static inline SymbolSet::Factory &getMembersFactory(ProgramStateRef State);
inline ProgramStateRef mergeImpl(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, SymbolSet Members,
EquivalenceClass Other,
SymbolSet OtherMembers);
static inline void
addToDisequalityInfo(DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, EquivalenceClass First,
EquivalenceClass Second);
/// This is a unique identifier of the class.
uintptr_t ID;
};
//===----------------------------------------------------------------------===//
// Constraint functions
//===----------------------------------------------------------------------===//
LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
EquivalenceClass Class) {
return State->get<ConstraintRange>(Class);
}
LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
SymbolRef Sym) {
return getConstraint(State, EquivalenceClass::find(State, Sym));
}
//===----------------------------------------------------------------------===//
// Equality/diseqiality abstraction
//===----------------------------------------------------------------------===//
/// A small helper structure representing symbolic equality.
///
/// Equality check can have different forms (like a == b or a - b) and this
/// class encapsulates those away if the only thing the user wants to check -
/// whether it's equality/diseqiality or not and have an easy access to the
/// compared symbols.
struct EqualityInfo {
public:
SymbolRef Left, Right;
// true for equality and false for disequality.
bool IsEquality = true;
void invert() { IsEquality = !IsEquality; }
/// Extract equality information from the given symbol and the constants.
///
/// This function assumes the following expression Sym + Adjustment != Int.
/// It is a default because the most widespread case of the equality check
/// is (A == B) + 0 != 0.
static Optional<EqualityInfo> extract(SymbolRef Sym, const llvm::APSInt &Int,
const llvm::APSInt &Adjustment) {
// As of now, the only equality form supported is Sym + 0 != 0.
if (!Int.isNullValue() || !Adjustment.isNullValue())
return llvm::None;
return extract(Sym);
}
/// Extract equality information from the given symbol.
static Optional<EqualityInfo> extract(SymbolRef Sym) {
return EqualityExtractor().Visit(Sym);
}
private:
class EqualityExtractor
: public SymExprVisitor<EqualityExtractor, Optional<EqualityInfo>> {
public:
Optional<EqualityInfo> VisitSymSymExpr(const SymSymExpr *Sym) const {
switch (Sym->getOpcode()) {
case BO_Sub:
// This case is: A - B != 0 -> disequality check.
return EqualityInfo{Sym->getLHS(), Sym->getRHS(), false};
case BO_EQ:
// This case is: A == B != 0 -> equality check.
return EqualityInfo{Sym->getLHS(), Sym->getRHS(), true};
case BO_NE:
// This case is: A != B != 0 -> diseqiality check.
return EqualityInfo{Sym->getLHS(), Sym->getRHS(), false};
default:
return llvm::None;
}
}
};
};
//===----------------------------------------------------------------------===//
// Intersection functions
//===----------------------------------------------------------------------===//
template <class SecondTy, class... RestTy>
LLVM_NODISCARD inline RangeSet intersect(BasicValueFactory &BV,
RangeSet::Factory &F, RangeSet Head,
SecondTy Second, RestTy... Tail);
template <class... RangeTy> struct IntersectionTraits;
template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
// Found RangeSet, no need to check any further
using Type = RangeSet;
};
template <> struct IntersectionTraits<> {
// We ran out of types, and we didn't find any RangeSet, so the result should
// be optional.
using Type = Optional<RangeSet>;
};
template <class OptionalOrPointer, class... TailTy>
struct IntersectionTraits<OptionalOrPointer, TailTy...> {
// If current type is Optional or a raw pointer, we should keep looking.
using Type = typename IntersectionTraits<TailTy...>::Type;
};
template <class EndTy>
LLVM_NODISCARD inline EndTy intersect(BasicValueFactory &BV,
RangeSet::Factory &F, EndTy End) {
// If the list contains only RangeSet or Optional<RangeSet>, simply return
// that range set.
return End;
}
LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet>
intersect(BasicValueFactory &BV, RangeSet::Factory &F, const RangeSet *End) {
// This is an extraneous conversion from a raw pointer into Optional<RangeSet>
if (End) {
return *End;
}
return llvm::None;
}
template <class... RestTy>
LLVM_NODISCARD inline RangeSet intersect(BasicValueFactory &BV,
RangeSet::Factory &F, RangeSet Head,
RangeSet Second, RestTy... Tail) {
// Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
// of the function and can be sure that the result is RangeSet.
return intersect(BV, F, Head.Intersect(BV, F, Second), Tail...);
}
template <class SecondTy, class... RestTy>
LLVM_NODISCARD inline RangeSet intersect(BasicValueFactory &BV,
RangeSet::Factory &F, RangeSet Head,
SecondTy Second, RestTy... Tail) {
if (Second) {
// Here we call the <RangeSet,RangeSet,...> version of the function...
return intersect(BV, F, Head, *Second, Tail...);
}
// ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
// means that the result is definitely RangeSet.
return intersect(BV, F, Head, Tail...);
}
/// Main generic intersect function.
/// It intersects all of the given range sets. If some of the given arguments
/// don't hold a range set (nullptr or llvm::None), the function will skip them.
///
/// Available representations for the arguments are:
/// * RangeSet
/// * Optional<RangeSet>
/// * RangeSet *
/// Pointer to a RangeSet is automatically assumed to be nullable and will get
/// checked as well as the optional version. If this behaviour is undesired,
/// please dereference the pointer in the call.
///
/// Return type depends on the arguments' types. If we can be sure in compile
/// time that there will be a range set as a result, the returning type is
/// simply RangeSet, in other cases we have to back off to Optional<RangeSet>.
///
/// Please, prefer optional range sets to raw pointers. If the last argument is
/// a raw pointer and all previous arguments are None, it will cost one
/// additional check to convert RangeSet * into Optional<RangeSet>.
template <class HeadTy, class SecondTy, class... RestTy>
LLVM_NODISCARD inline
typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
intersect(BasicValueFactory &BV, RangeSet::Factory &F, HeadTy Head,
SecondTy Second, RestTy... Tail) {
if (Head) {
return intersect(BV, F, *Head, Second, Tail...);
}
return intersect(BV, F, Second, Tail...);
}
//===----------------------------------------------------------------------===//
// Symbolic reasoning logic
//===----------------------------------------------------------------------===//
/// A little component aggregating all of the reasoning we have about
/// the ranges of symbolic expressions.
///
/// Even when we don't know the exact values of the operands, we still
/// can get a pretty good estimate of the result's range.
class SymbolicRangeInferrer
: public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
public:
template <class SourceType>
static RangeSet inferRange(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef State, SourceType Origin) {
SymbolicRangeInferrer Inferrer(BV, F, State);
return Inferrer.infer(Origin);
}
RangeSet VisitSymExpr(SymbolRef Sym) {
// If we got to this function, the actual type of the symbolic
// expression is not supported for advanced inference.
// In this case, we simply backoff to the default "let's simply
// infer the range from the expression's type".
return infer(Sym->getType());
}
RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
return VisitBinaryOperator(Sym);
}
RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
return VisitBinaryOperator(Sym);
}
RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
return VisitBinaryOperator(Sym);
}
private:
SymbolicRangeInferrer(BasicValueFactory &BV, RangeSet::Factory &F,
ProgramStateRef S)
: ValueFactory(BV), RangeFactory(F), State(S) {}
/// Infer range information from the given integer constant.
///
/// It's not a real "inference", but is here for operating with
/// sub-expressions in a more polymorphic manner.
RangeSet inferAs(const llvm::APSInt &Val, QualType) {
return {RangeFactory, Val};
}
/// Infer range information from symbol in the context of the given type.
RangeSet inferAs(SymbolRef Sym, QualType DestType) {
QualType ActualType = Sym->getType();
// Check that we can reason about the symbol at all.
if (ActualType->isIntegralOrEnumerationType() ||
Loc::isLocType(ActualType)) {
return infer(Sym);
}
// Otherwise, let's simply infer from the destination type.
// We couldn't figure out nothing else about that expression.
return infer(DestType);
}
RangeSet infer(SymbolRef Sym) {
if (Optional<RangeSet> ConstraintBasedRange = intersect(
ValueFactory, RangeFactory, getConstraint(State, Sym),
// If Sym is a difference of symbols A - B, then maybe we have range
// set stored for B - A.
//
// If we have range set stored for both A - B and B - A then
// calculate the effective range set by intersecting the range set
// for A - B and the negated range set of B - A.
getRangeForNegatedSub(Sym), getRangeForEqualities(Sym))) {
return *ConstraintBasedRange;
}
// If Sym is a comparison expression (except <=>),
// find any other comparisons with the same operands.
// See function description.
if (Optional<RangeSet> CmpRangeSet = getRangeForComparisonSymbol(Sym)) {
return *CmpRangeSet;
}
return Visit(Sym);
}
RangeSet infer(EquivalenceClass Class) {
if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
return *AssociatedConstraint;
return infer(Class.getType());
}
/// Infer range information solely from the type.
RangeSet infer(QualType T) {
// Lazily generate a new RangeSet representing all possible values for the
// given symbol type.
RangeSet Result(RangeFactory, ValueFactory.getMinValue(T),
ValueFactory.getMaxValue(T));
// References are known to be non-zero.
if (T->isReferenceType())
return assumeNonZero(Result, T);
return Result;
}
template <class BinarySymExprTy>
RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
// TODO #1: VisitBinaryOperator implementation might not make a good
// use of the inferred ranges. In this case, we might be calculating
// everything for nothing. This being said, we should introduce some
// sort of laziness mechanism here.
//
// TODO #2: We didn't go into the nested expressions before, so it
// might cause us spending much more time doing the inference.
// This can be a problem for deeply nested expressions that are
// involved in conditions and get tested continuously. We definitely
// need to address this issue and introduce some sort of caching
// in here.
QualType ResultType = Sym->getType();
return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
Sym->getOpcode(),
inferAs(Sym->getRHS(), ResultType), ResultType);
}
RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
RangeSet RHS, QualType T) {
switch (Op) {
case BO_Or:
return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
case BO_And:
return VisitBinaryOperator<BO_And>(LHS, RHS, T);
case BO_Rem:
return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
default:
return infer(T);
}
}
//===----------------------------------------------------------------------===//
// Ranges and operators
//===----------------------------------------------------------------------===//
/// Return a rough approximation of the given range set.
///
/// For the range set:
/// { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
/// it will return the range [x_0, y_N].
static Range fillGaps(RangeSet Origin) {
assert(!Origin.isEmpty());
return {Origin.getMinValue(), Origin.getMaxValue()};
}
/// Try to convert given range into the given type.
///
/// It will return llvm::None only when the trivial conversion is possible.
llvm::Optional<Range> convert(const Range &Origin, APSIntType To) {
if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
return llvm::None;
}
return Range(ValueFactory.Convert(To, Origin.From()),
ValueFactory.Convert(To, Origin.To()));
}
template <BinaryOperator::Opcode Op>
RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
// We should propagate information about unfeasbility of one of the
// operands to the resulting range.
if (LHS.isEmpty() || RHS.isEmpty()) {
return RangeFactory.getEmptySet();
}
Range CoarseLHS = fillGaps(LHS);
Range CoarseRHS = fillGaps(RHS);
APSIntType ResultType = ValueFactory.getAPSIntType(T);
// We need to convert ranges to the resulting type, so we can compare values
// and combine them in a meaningful (in terms of the given operation) way.
auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
// It is hard to reason about ranges when conversion changes
// borders of the ranges.
if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
return infer(T);
}
return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
}
template <BinaryOperator::Opcode Op>
RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
return infer(T);
}
/// Return a symmetrical range for the given range and type.
///
/// If T is signed, return the smallest range [-x..x] that covers the original
/// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
/// exist due to original range covering min(T)).
///
/// If T is unsigned, return the smallest range [0..x] that covers the
/// original range.
Range getSymmetricalRange(Range Origin, QualType T) {
APSIntType RangeType = ValueFactory.getAPSIntType(T);
if (RangeType.isUnsigned()) {
return Range(ValueFactory.getMinValue(RangeType), Origin.To());
}
if (Origin.From().isMinSignedValue()) {
// If mini is a minimal signed value, absolute value of it is greater
// than the maximal signed value. In order to avoid these
// complications, we simply return the whole range.
return {ValueFactory.getMinValue(RangeType),
ValueFactory.getMaxValue(RangeType)};
}
// At this point, we are sure that the type is signed and we can safely
// use unary - operator.
//
// While calculating absolute maximum, we can use the following formula
// because of these reasons:
// * If From >= 0 then To >= From and To >= -From.
// AbsMax == To == max(To, -From)
// * If To <= 0 then -From >= -To and -From >= From.
// AbsMax == -From == max(-From, To)
// * Otherwise, From <= 0, To >= 0, and
// AbsMax == max(abs(From), abs(To))
llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
// Intersection is guaranteed to be non-empty.
return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
}
/// Return a range set subtracting zero from \p Domain.
RangeSet assumeNonZero(RangeSet Domain, QualType T) {
APSIntType IntType = ValueFactory.getAPSIntType(T);
return Domain.Delete(ValueFactory, RangeFactory, IntType.getZeroValue());
}
// FIXME: Once SValBuilder supports unary minus, we should use SValBuilder to
// obtain the negated symbolic expression instead of constructing the
// symbol manually. This will allow us to support finding ranges of not
// only negated SymSymExpr-type expressions, but also of other, simpler
// expressions which we currently do not know how to negate.
Optional<RangeSet> getRangeForNegatedSub(SymbolRef Sym) {
if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
if (SSE->getOpcode() == BO_Sub) {
QualType T = Sym->getType();
// Do not negate unsigned ranges
if (!T->isUnsignedIntegerOrEnumerationType() &&
!T->isSignedIntegerOrEnumerationType())
return llvm::None;
SymbolManager &SymMgr = State->getSymbolManager();
SymbolRef NegatedSym =
SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), T);
if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym)) {
return NegatedRange->Negate(ValueFactory, RangeFactory);
}
}
}
return llvm::None;
}
// Returns ranges only for binary comparison operators (except <=>)
// when left and right operands are symbolic values.
// Finds any other comparisons with the same operands.
// Then do logical calculations and refuse impossible branches.
// E.g. (x < y) and (x > y) at the same time are impossible.
// E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
// E.g. (x == y) and (y == x) are just reversed but the same.
// It covers all possible combinations (see CmpOpTable description).
// Note that `x` and `y` can also stand for subexpressions,
// not only for actual symbols.
Optional<RangeSet> getRangeForComparisonSymbol(SymbolRef Sym) {
const auto *SSE = dyn_cast<SymSymExpr>(Sym);
if (!SSE)
return llvm::None;
BinaryOperatorKind CurrentOP = SSE->getOpcode();
// We currently do not support <=> (C++20).
if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
return llvm::None;
static const OperatorRelationsTable CmpOpTable{};
const SymExpr *LHS = SSE->getLHS();
const SymExpr *RHS = SSE->getRHS();
QualType T = SSE->getType();
SymbolManager &SymMgr = State->getSymbolManager();