-
Notifications
You must be signed in to change notification settings - Fork 13k
/
Copy pathValueTracking.cpp
10367 lines (9236 loc) · 380 KB
/
ValueTracking.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
//===- ValueTracking.cpp - Walk computations to compute properties --------===//
//
// 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 contains routines that help analyze properties that chains of
// computations have.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumeBundleQueries.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/DomConditionCache.h"
#include "llvm/Analysis/GuardUtils.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/Analysis/WithCache.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/EHPersonalities.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsAArch64.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#include "llvm/IR/IntrinsicsRISCV.h"
#include "llvm/IR/IntrinsicsX86.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/TargetParser/RISCVTargetParser.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <optional>
#include <utility>
using namespace llvm;
using namespace llvm::PatternMatch;
// Controls the number of uses of the value searched for possible
// dominating comparisons.
static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
cl::Hidden, cl::init(20));
/// Returns the bitwidth of the given scalar or pointer type. For vector types,
/// returns the element type's bitwidth.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
if (unsigned BitWidth = Ty->getScalarSizeInBits())
return BitWidth;
return DL.getPointerTypeSizeInBits(Ty);
}
// Given the provided Value and, potentially, a context instruction, return
// the preferred context instruction (if any).
static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
// If we've been provided with a context instruction, then use that (provided
// it has been inserted).
if (CxtI && CxtI->getParent())
return CxtI;
// If the value is really an already-inserted instruction, then use that.
CxtI = dyn_cast<Instruction>(V);
if (CxtI && CxtI->getParent())
return CxtI;
return nullptr;
}
static bool getShuffleDemandedElts(const ShuffleVectorInst *Shuf,
const APInt &DemandedElts,
APInt &DemandedLHS, APInt &DemandedRHS) {
if (isa<ScalableVectorType>(Shuf->getType())) {
assert(DemandedElts == APInt(1,1));
DemandedLHS = DemandedRHS = DemandedElts;
return true;
}
int NumElts =
cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
DemandedElts, DemandedLHS, DemandedRHS);
}
static void computeKnownBits(const Value *V, const APInt &DemandedElts,
KnownBits &Known, unsigned Depth,
const SimplifyQuery &Q);
void llvm::computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
const SimplifyQuery &Q) {
// Since the number of lanes in a scalable vector is unknown at compile time,
// we track one bit which is implicitly broadcast to all lanes. This means
// that all lanes in a scalable vector are considered demanded.
auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
APInt DemandedElts =
FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
::computeKnownBits(V, DemandedElts, Known, Depth, Q);
}
void llvm::computeKnownBits(const Value *V, KnownBits &Known,
const DataLayout &DL, unsigned Depth,
AssumptionCache *AC, const Instruction *CxtI,
const DominatorTree *DT, bool UseInstrInfo) {
computeKnownBits(
V, Known, Depth,
SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
}
KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
unsigned Depth, AssumptionCache *AC,
const Instruction *CxtI,
const DominatorTree *DT, bool UseInstrInfo) {
return computeKnownBits(
V, Depth, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
}
KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
const DataLayout &DL, unsigned Depth,
AssumptionCache *AC, const Instruction *CxtI,
const DominatorTree *DT, bool UseInstrInfo) {
return computeKnownBits(
V, DemandedElts, Depth,
SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
}
static bool haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS,
const SimplifyQuery &SQ) {
// Look for an inverted mask: (X & ~M) op (Y & M).
{
Value *M;
if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
match(RHS, m_c_And(m_Specific(M), m_Value())) &&
isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT))
return true;
}
// X op (Y & ~X)
if (match(RHS, m_c_And(m_Not(m_Specific(LHS)), m_Value())) &&
isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
return true;
// X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
// for constant Y.
Value *Y;
if (match(RHS,
m_c_Xor(m_c_And(m_Specific(LHS), m_Value(Y)), m_Deferred(Y))) &&
isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT))
return true;
// Peek through extends to find a 'not' of the other side:
// (ext Y) op ext(~Y)
if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
match(RHS, m_ZExtOrSExt(m_Not(m_Specific(Y)))) &&
isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT))
return true;
// Look for: (A & B) op ~(A | B)
{
Value *A, *B;
if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
match(RHS, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))) &&
isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT))
return true;
}
// Look for: (X << V) op (Y >> (BitWidth - V))
// or (X >> V) op (Y << (BitWidth - V))
{
const Value *V;
const APInt *R;
if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
(match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
R->uge(LHS->getType()->getScalarSizeInBits()))
return true;
}
return false;
}
bool llvm::haveNoCommonBitsSet(const WithCache<const Value *> &LHSCache,
const WithCache<const Value *> &RHSCache,
const SimplifyQuery &SQ) {
const Value *LHS = LHSCache.getValue();
const Value *RHS = RHSCache.getValue();
assert(LHS->getType() == RHS->getType() &&
"LHS and RHS should have the same type");
assert(LHS->getType()->isIntOrIntVectorTy() &&
"LHS and RHS should be integers");
if (haveNoCommonBitsSetSpecialCases(LHS, RHS, SQ) ||
haveNoCommonBitsSetSpecialCases(RHS, LHS, SQ))
return true;
return KnownBits::haveNoCommonBitsSet(LHSCache.getKnownBits(SQ),
RHSCache.getKnownBits(SQ));
}
bool llvm::isOnlyUsedInZeroComparison(const Instruction *I) {
return !I->user_empty() && all_of(I->users(), [](const User *U) {
return match(U, m_ICmp(m_Value(), m_Zero()));
});
}
bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *I) {
return !I->user_empty() && all_of(I->users(), [](const User *U) {
CmpPredicate P;
return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
});
}
bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
bool OrZero, unsigned Depth,
AssumptionCache *AC, const Instruction *CxtI,
const DominatorTree *DT, bool UseInstrInfo) {
return ::isKnownToBeAPowerOfTwo(
V, OrZero, Depth,
SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
}
static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
const SimplifyQuery &Q, unsigned Depth);
bool llvm::isKnownNonNegative(const Value *V, const SimplifyQuery &SQ,
unsigned Depth) {
return computeKnownBits(V, Depth, SQ).isNonNegative();
}
bool llvm::isKnownPositive(const Value *V, const SimplifyQuery &SQ,
unsigned Depth) {
if (auto *CI = dyn_cast<ConstantInt>(V))
return CI->getValue().isStrictlyPositive();
// If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
// this updated.
KnownBits Known = computeKnownBits(V, Depth, SQ);
return Known.isNonNegative() &&
(Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
}
bool llvm::isKnownNegative(const Value *V, const SimplifyQuery &SQ,
unsigned Depth) {
return computeKnownBits(V, Depth, SQ).isNegative();
}
static bool isKnownNonEqual(const Value *V1, const Value *V2,
const APInt &DemandedElts, unsigned Depth,
const SimplifyQuery &Q);
bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
const SimplifyQuery &Q, unsigned Depth) {
// We don't support looking through casts.
if (V1 == V2 || V1->getType() != V2->getType())
return false;
auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
APInt DemandedElts =
FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
return ::isKnownNonEqual(V1, V2, DemandedElts, Depth, Q);
}
bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
const SimplifyQuery &SQ, unsigned Depth) {
KnownBits Known(Mask.getBitWidth());
computeKnownBits(V, Known, Depth, SQ);
return Mask.isSubsetOf(Known.Zero);
}
static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
unsigned Depth, const SimplifyQuery &Q);
static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
const SimplifyQuery &Q) {
auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
APInt DemandedElts =
FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
return ComputeNumSignBits(V, DemandedElts, Depth, Q);
}
unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
unsigned Depth, AssumptionCache *AC,
const Instruction *CxtI,
const DominatorTree *DT, bool UseInstrInfo) {
return ::ComputeNumSignBits(
V, Depth, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
}
unsigned llvm::ComputeMaxSignificantBits(const Value *V, const DataLayout &DL,
unsigned Depth, AssumptionCache *AC,
const Instruction *CxtI,
const DominatorTree *DT) {
unsigned SignBits = ComputeNumSignBits(V, DL, Depth, AC, CxtI, DT);
return V->getType()->getScalarSizeInBits() - SignBits + 1;
}
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
bool NSW, bool NUW,
const APInt &DemandedElts,
KnownBits &KnownOut, KnownBits &Known2,
unsigned Depth, const SimplifyQuery &Q) {
computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q);
// If one operand is unknown and we have no nowrap information,
// the result will be unknown independently of the second operand.
if (KnownOut.isUnknown() && !NSW && !NUW)
return;
computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
}
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
bool NUW, const APInt &DemandedElts,
KnownBits &Known, KnownBits &Known2,
unsigned Depth, const SimplifyQuery &Q) {
computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q);
computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
bool isKnownNegative = false;
bool isKnownNonNegative = false;
// If the multiplication is known not to overflow, compute the sign bit.
if (NSW) {
if (Op0 == Op1) {
// The product of a number with itself is non-negative.
isKnownNonNegative = true;
} else {
bool isKnownNonNegativeOp1 = Known.isNonNegative();
bool isKnownNonNegativeOp0 = Known2.isNonNegative();
bool isKnownNegativeOp1 = Known.isNegative();
bool isKnownNegativeOp0 = Known2.isNegative();
// The product of two numbers with the same sign is non-negative.
isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
(isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
if (!isKnownNonNegative && NUW) {
// mul nuw nsw with a factor > 1 is non-negative.
KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
KnownBits::sgt(Known2, One).value_or(false);
}
// The product of a negative number and a non-negative number is either
// negative or zero.
if (!isKnownNonNegative)
isKnownNegative =
(isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Known2.isNonZero()) ||
(isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
}
}
bool SelfMultiply = Op0 == Op1;
if (SelfMultiply)
SelfMultiply &=
isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
Known = KnownBits::mul(Known, Known2, SelfMultiply);
// Only make use of no-wrap flags if we failed to compute the sign bit
// directly. This matters if the multiplication always overflows, in
// which case we prefer to follow the result of the direct computation,
// though as the program is invoking undefined behaviour we can choose
// whatever we like here.
if (isKnownNonNegative && !Known.isNegative())
Known.makeNonNegative();
else if (isKnownNegative && !Known.isNonNegative())
Known.makeNegative();
}
void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
KnownBits &Known) {
unsigned BitWidth = Known.getBitWidth();
unsigned NumRanges = Ranges.getNumOperands() / 2;
assert(NumRanges >= 1);
Known.Zero.setAllBits();
Known.One.setAllBits();
for (unsigned i = 0; i < NumRanges; ++i) {
ConstantInt *Lower =
mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
ConstantInt *Upper =
mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
ConstantRange Range(Lower->getValue(), Upper->getValue());
// The first CommonPrefixBits of all values in Range are equal.
unsigned CommonPrefixBits =
(Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
Known.One &= UnsignedMax & Mask;
Known.Zero &= ~UnsignedMax & Mask;
}
}
static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
SmallVector<const Value *, 16> WorkSet(1, I);
SmallPtrSet<const Value *, 32> Visited;
SmallPtrSet<const Value *, 16> EphValues;
// The instruction defining an assumption's condition itself is always
// considered ephemeral to that assumption (even if it has other
// non-ephemeral users). See r246696's test case for an example.
if (is_contained(I->operands(), E))
return true;
while (!WorkSet.empty()) {
const Value *V = WorkSet.pop_back_val();
if (!Visited.insert(V).second)
continue;
// If all uses of this value are ephemeral, then so is this value.
if (llvm::all_of(V->users(), [&](const User *U) {
return EphValues.count(U);
})) {
if (V == E)
return true;
if (V == I || (isa<Instruction>(V) &&
!cast<Instruction>(V)->mayHaveSideEffects() &&
!cast<Instruction>(V)->isTerminator())) {
EphValues.insert(V);
if (const User *U = dyn_cast<User>(V))
append_range(WorkSet, U->operands());
}
}
}
return false;
}
// Is this an intrinsic that cannot be speculated but also cannot trap?
bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
return CI->isAssumeLikeIntrinsic();
return false;
}
bool llvm::isValidAssumeForContext(const Instruction *Inv,
const Instruction *CxtI,
const DominatorTree *DT,
bool AllowEphemerals) {
// There are two restrictions on the use of an assume:
// 1. The assume must dominate the context (or the control flow must
// reach the assume whenever it reaches the context).
// 2. The context must not be in the assume's set of ephemeral values
// (otherwise we will use the assume to prove that the condition
// feeding the assume is trivially true, thus causing the removal of
// the assume).
if (Inv->getParent() == CxtI->getParent()) {
// If Inv and CtxI are in the same block, check if the assume (Inv) is first
// in the BB.
if (Inv->comesBefore(CxtI))
return true;
// Don't let an assume affect itself - this would cause the problems
// `isEphemeralValueOf` is trying to prevent, and it would also make
// the loop below go out of bounds.
if (!AllowEphemerals && Inv == CxtI)
return false;
// The context comes first, but they're both in the same block.
// Make sure there is nothing in between that might interrupt
// the control flow, not even CxtI itself.
// We limit the scan distance between the assume and its context instruction
// to avoid a compile-time explosion. This limit is chosen arbitrarily, so
// it can be adjusted if needed (could be turned into a cl::opt).
auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
if (!isGuaranteedToTransferExecutionToSuccessor(Range, 15))
return false;
return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
}
// Inv and CxtI are in different blocks.
if (DT) {
if (DT->dominates(Inv, CxtI))
return true;
} else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
Inv->getParent()->isEntryBlock()) {
// We don't have a DT, but this trivially dominates.
return true;
}
return false;
}
// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
// we still have enough information about `RHS` to conclude non-zero. For
// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
// so the extra compile time may not be worth it, but possibly a second API
// should be created for use outside of loops.
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
// v u> y implies v != 0.
if (Pred == ICmpInst::ICMP_UGT)
return true;
// Special-case v != 0 to also handle v != null.
if (Pred == ICmpInst::ICMP_NE)
return match(RHS, m_Zero());
// All other predicates - rely on generic ConstantRange handling.
const APInt *C;
auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
if (match(RHS, m_APInt(C))) {
ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(Pred, *C);
return !TrueValues.contains(Zero);
}
auto *VC = dyn_cast<ConstantDataVector>(RHS);
if (VC == nullptr)
return false;
for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
++ElemIdx) {
ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
Pred, VC->getElementAsAPInt(ElemIdx));
if (TrueValues.contains(Zero))
return false;
}
return true;
}
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
Value *&ValOut, Instruction *&CtxIOut,
const PHINode **PhiOut = nullptr) {
ValOut = U->get();
if (ValOut == PHI)
return;
CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
if (PhiOut)
*PhiOut = PHI;
Value *V;
// If the Use is a select of this phi, compute analysis on other arm to break
// recursion.
// TODO: Min/Max
if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
ValOut = V;
// Same for select, if this phi is 2-operand phi, compute analysis on other
// incoming value to break recursion.
// TODO: We could handle any number of incoming edges as long as we only have
// two unique values.
if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
IncPhi && IncPhi->getNumIncomingValues() == 2) {
for (int Idx = 0; Idx < 2; ++Idx) {
if (IncPhi->getIncomingValue(Idx) == PHI) {
ValOut = IncPhi->getIncomingValue(1 - Idx);
if (PhiOut)
*PhiOut = IncPhi;
CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
break;
}
}
}
}
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
// Use of assumptions is context-sensitive. If we don't have a context, we
// cannot use them!
if (!Q.AC || !Q.CxtI)
return false;
for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
if (!Elem.Assume)
continue;
AssumeInst *I = cast<AssumeInst>(Elem.Assume);
assert(I->getFunction() == Q.CxtI->getFunction() &&
"Got assumption for the wrong function!");
if (Elem.Index != AssumptionCache::ExprResultIdx) {
if (!V->getType()->isPointerTy())
continue;
if (RetainedKnowledge RK = getKnowledgeFromBundle(
*I, I->bundle_op_info_begin()[Elem.Index])) {
if (RK.WasOn == V &&
(RK.AttrKind == Attribute::NonNull ||
(RK.AttrKind == Attribute::Dereferenceable &&
!NullPointerIsDefined(Q.CxtI->getFunction(),
V->getType()->getPointerAddressSpace()))) &&
isValidAssumeForContext(I, Q.CxtI, Q.DT))
return true;
}
continue;
}
// Warning: This loop can end up being somewhat performance sensitive.
// We're running this loop for once for each value queried resulting in a
// runtime of ~O(#assumes * #values).
Value *RHS;
CmpPredicate Pred;
auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
continue;
if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT))
return true;
}
return false;
}
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred,
Value *LHS, Value *RHS, KnownBits &Known,
const SimplifyQuery &Q) {
if (RHS->getType()->isPointerTy()) {
// Handle comparison of pointer to null explicitly, as it will not be
// covered by the m_APInt() logic below.
if (LHS == V && match(RHS, m_Zero())) {
switch (Pred) {
case ICmpInst::ICMP_EQ:
Known.setAllZero();
break;
case ICmpInst::ICMP_SGE:
case ICmpInst::ICMP_SGT:
Known.makeNonNegative();
break;
case ICmpInst::ICMP_SLT:
Known.makeNegative();
break;
default:
break;
}
}
return;
}
unsigned BitWidth = Known.getBitWidth();
auto m_V =
m_CombineOr(m_Specific(V), m_PtrToIntSameSize(Q.DL, m_Specific(V)));
Value *Y;
const APInt *Mask, *C;
if (!match(RHS, m_APInt(C)))
return;
uint64_t ShAmt;
switch (Pred) {
case ICmpInst::ICMP_EQ:
// assume(V = C)
if (match(LHS, m_V)) {
Known = Known.unionWith(KnownBits::makeConstant(*C));
// assume(V & Mask = C)
} else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
// For one bits in Mask, we can propagate bits from C to V.
Known.One |= *C;
if (match(Y, m_APInt(Mask)))
Known.Zero |= ~*C & *Mask;
// assume(V | Mask = C)
} else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
// For zero bits in Mask, we can propagate bits from C to V.
Known.Zero |= ~*C;
if (match(Y, m_APInt(Mask)))
Known.One |= *C & ~*Mask;
// assume(V << ShAmt = C)
} else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
ShAmt < BitWidth) {
// For those bits in C that are known, we can propagate them to known
// bits in V shifted to the right by ShAmt.
KnownBits RHSKnown = KnownBits::makeConstant(*C);
RHSKnown.Zero.lshrInPlace(ShAmt);
RHSKnown.One.lshrInPlace(ShAmt);
Known = Known.unionWith(RHSKnown);
// assume(V >> ShAmt = C)
} else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
ShAmt < BitWidth) {
KnownBits RHSKnown = KnownBits::makeConstant(*C);
// For those bits in RHS that are known, we can propagate them to known
// bits in V shifted to the right by C.
Known.Zero |= RHSKnown.Zero << ShAmt;
Known.One |= RHSKnown.One << ShAmt;
}
break;
case ICmpInst::ICMP_NE: {
// assume (V & B != 0) where B is a power of 2
const APInt *BPow2;
if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
Known.One |= *BPow2;
break;
}
default: {
const APInt *Offset = nullptr;
if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
ConstantRange LHSRange = ConstantRange::makeAllowedICmpRegion(Pred, *C);
if (Offset)
LHSRange = LHSRange.sub(*Offset);
Known = Known.unionWith(LHSRange.toKnownBits());
}
if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
// X & Y u> C -> X u> C && Y u> C
// X nuw- Y u> C -> X u> C
if (match(LHS, m_c_And(m_V, m_Value())) ||
match(LHS, m_NUWSub(m_V, m_Value())))
Known.One.setHighBits(
(*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
}
if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
// X | Y u< C -> X u< C && Y u< C
// X nuw+ Y u< C -> X u< C && Y u< C
if (match(LHS, m_c_Or(m_V, m_Value())) ||
match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
Known.Zero.setHighBits(
(*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
}
}
} break;
}
}
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
KnownBits &Known,
const SimplifyQuery &SQ, bool Invert) {
ICmpInst::Predicate Pred =
Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
Value *LHS = Cmp->getOperand(0);
Value *RHS = Cmp->getOperand(1);
// Handle icmp pred (trunc V), C
if (match(LHS, m_Trunc(m_Specific(V)))) {
KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
if (cast<TruncInst>(LHS)->hasNoUnsignedWrap())
Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
else
Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
return;
}
computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
}
static void computeKnownBitsFromCond(const Value *V, Value *Cond,
KnownBits &Known, unsigned Depth,
const SimplifyQuery &SQ, bool Invert) {
Value *A, *B;
if (Depth < MaxAnalysisRecursionDepth &&
match(Cond, m_LogicalOp(m_Value(A), m_Value(B)))) {
KnownBits Known2(Known.getBitWidth());
KnownBits Known3(Known.getBitWidth());
computeKnownBitsFromCond(V, A, Known2, Depth + 1, SQ, Invert);
computeKnownBitsFromCond(V, B, Known3, Depth + 1, SQ, Invert);
if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
: match(Cond, m_LogicalAnd(m_Value(), m_Value())))
Known2 = Known2.unionWith(Known3);
else
Known2 = Known2.intersectWith(Known3);
Known = Known.unionWith(Known2);
return;
}
if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
return;
}
if (match(Cond, m_Trunc(m_Specific(V)))) {
KnownBits DstKnown(1);
if (Invert) {
DstKnown.setAllZero();
} else {
DstKnown.setAllOnes();
}
if (cast<TruncInst>(Cond)->hasNoUnsignedWrap()) {
Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
return;
}
Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
return;
}
if (Depth < MaxAnalysisRecursionDepth && match(Cond, m_Not(m_Value(A))))
computeKnownBitsFromCond(V, A, Known, Depth + 1, SQ, !Invert);
}
void llvm::computeKnownBitsFromContext(const Value *V, KnownBits &Known,
unsigned Depth, const SimplifyQuery &Q) {
// Handle injected condition.
if (Q.CC && Q.CC->AffectedValues.contains(V))
computeKnownBitsFromCond(V, Q.CC->Cond, Known, Depth, Q, Q.CC->Invert);
if (!Q.CxtI)
return;
if (Q.DC && Q.DT) {
// Handle dominating conditions.
for (BranchInst *BI : Q.DC->conditionsFor(V)) {
BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
computeKnownBitsFromCond(V, BI->getCondition(), Known, Depth, Q,
/*Invert*/ false);
BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
computeKnownBitsFromCond(V, BI->getCondition(), Known, Depth, Q,
/*Invert*/ true);
}
if (Known.hasConflict())
Known.resetAll();
}
if (!Q.AC)
return;
unsigned BitWidth = Known.getBitWidth();
// Note that the patterns below need to be kept in sync with the code
// in AssumptionCache::updateAffectedValues.
for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
if (!Elem.Assume)
continue;
AssumeInst *I = cast<AssumeInst>(Elem.Assume);
assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
"Got assumption for the wrong function!");
if (Elem.Index != AssumptionCache::ExprResultIdx) {
if (!V->getType()->isPointerTy())
continue;
if (RetainedKnowledge RK = getKnowledgeFromBundle(
*I, I->bundle_op_info_begin()[Elem.Index])) {
// Allow AllowEphemerals in isValidAssumeForContext, as the CxtI might
// be the producer of the pointer in the bundle. At the moment, align
// assumptions aren't optimized away.
if (RK.WasOn == V && RK.AttrKind == Attribute::Alignment &&
isPowerOf2_64(RK.ArgValue) &&
isValidAssumeForContext(I, Q.CxtI, Q.DT, /*AllowEphemerals*/ true))
Known.Zero.setLowBits(Log2_64(RK.ArgValue));
}
continue;
}
// Warning: This loop can end up being somewhat performance sensitive.
// We're running this loop for once for each value queried resulting in a
// runtime of ~O(#assumes * #values).
Value *Arg = I->getArgOperand(0);
if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
assert(BitWidth == 1 && "assume operand is not i1?");
(void)BitWidth;
Known.setAllOnes();
return;
}
if (match(Arg, m_Not(m_Specific(V))) &&
isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
assert(BitWidth == 1 && "assume operand is not i1?");
(void)BitWidth;
Known.setAllZero();
return;
}
// The remaining tests are all recursive, so bail out if we hit the limit.
if (Depth == MaxAnalysisRecursionDepth)
continue;
ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
if (!Cmp)
continue;
if (!isValidAssumeForContext(I, Q.CxtI, Q.DT))
continue;
computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
}
// Conflicting assumption: Undefined behavior will occur on this execution
// path.
if (Known.hasConflict())
Known.resetAll();
}
/// Compute known bits from a shift operator, including those with a
/// non-constant shift amount. Known is the output of this function. Known2 is a
/// pre-allocated temporary with the same bit width as Known and on return
/// contains the known bit of the shift value source. KF is an
/// operator-specific function that, given the known-bits and a shift amount,
/// compute the implied known-bits of the shift operator's result respectively
/// for that shift amount. The results from calling KF are conservatively
/// combined for all permitted shift amounts.
static void computeKnownBitsFromShiftOperator(
const Operator *I, const APInt &DemandedElts, KnownBits &Known,
KnownBits &Known2, unsigned Depth, const SimplifyQuery &Q,
function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
// To limit compile-time impact, only query isKnownNonZero() if we know at
// least something about the shift amount.
bool ShAmtNonZero =
Known.isNonZero() ||
(Known.getMaxValue().ult(Known.getBitWidth()) &&
isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
Known = KF(Known2, Known, ShAmtNonZero);
}
static KnownBits
getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
const KnownBits &KnownLHS, const KnownBits &KnownRHS,
unsigned Depth, const SimplifyQuery &Q) {
unsigned BitWidth = KnownLHS.getBitWidth();
KnownBits KnownOut(BitWidth);
bool IsAnd = false;
bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
Value *X = nullptr, *Y = nullptr;
switch (I->getOpcode()) {
case Instruction::And:
KnownOut = KnownLHS & KnownRHS;
IsAnd = true;
// and(x, -x) is common idioms that will clear all but lowest set
// bit. If we have a single known bit in x, we can clear all bits
// above it.
// TODO: instcombine often reassociates independent `and` which can hide
// this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
// -(-x) == x so using whichever (LHS/RHS) gets us a better result.
if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
KnownOut = KnownLHS.blsi();
else
KnownOut = KnownRHS.blsi();
}
break;
case Instruction::Or:
KnownOut = KnownLHS | KnownRHS;
break;
case Instruction::Xor:
KnownOut = KnownLHS ^ KnownRHS;
// xor(x, x-1) is common idioms that will clear all but lowest set
// bit. If we have a single known bit in x, we can clear all bits
// above it.
// TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
// -1 but for the purpose of demanded bits (xor(x, x-C) &
// Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
// to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
if (HasKnownOne &&
match(I, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())))) {
const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
KnownOut = XBits.blsmsk();
}
break;
default:
llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
}
// and(x, add (x, -1)) is a common idiom that always clears the low bit;
// xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
// here we handle the more general case of adding any odd number by