1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains routines that help analyze properties that chains of
10 // computations have.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/ValueTracking.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/GuardUtils.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/ConstantRange.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GetElementPtrTypeIterator.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/IntrinsicInst.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/IR/PatternMatch.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/User.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/KnownBits.h"
67 #include "llvm/Support/MathExtras.h"
68 #include <algorithm>
69 #include <array>
70 #include <cassert>
71 #include <cstdint>
72 #include <iterator>
73 #include <utility>
74 
75 using namespace llvm;
76 using namespace llvm::PatternMatch;
77 
78 const unsigned MaxDepth = 6;
79 
80 // Controls the number of uses of the value searched for possible
81 // dominating comparisons.
82 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
83                                               cl::Hidden, cl::init(20));
84 
85 /// Returns the bitwidth of the given scalar or pointer type. For vector types,
86 /// returns the element type's bitwidth.
87 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
88   if (unsigned BitWidth = Ty->getScalarSizeInBits())
89     return BitWidth;
90 
91   return DL.getIndexTypeSizeInBits(Ty);
92 }
93 
94 namespace {
95 
96 // Simplifying using an assume can only be done in a particular control-flow
97 // context (the context instruction provides that context). If an assume and
98 // the context instruction are not in the same block then the DT helps in
99 // figuring out if we can use it.
100 struct Query {
101   const DataLayout &DL;
102   AssumptionCache *AC;
103   const Instruction *CxtI;
104   const DominatorTree *DT;
105 
106   // Unlike the other analyses, this may be a nullptr because not all clients
107   // provide it currently.
108   OptimizationRemarkEmitter *ORE;
109 
110   /// Set of assumptions that should be excluded from further queries.
111   /// This is because of the potential for mutual recursion to cause
112   /// computeKnownBits to repeatedly visit the same assume intrinsic. The
113   /// classic case of this is assume(x = y), which will attempt to determine
114   /// bits in x from bits in y, which will attempt to determine bits in y from
115   /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
116   /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
117   /// (all of which can call computeKnownBits), and so on.
118   std::array<const Value *, MaxDepth> Excluded;
119 
120   /// If true, it is safe to use metadata during simplification.
121   InstrInfoQuery IIQ;
122 
123   unsigned NumExcluded = 0;
124 
125   Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
126         const DominatorTree *DT, bool UseInstrInfo,
127         OptimizationRemarkEmitter *ORE = nullptr)
128       : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
129 
130   Query(const Query &Q, const Value *NewExcl)
131       : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE), IIQ(Q.IIQ),
132         NumExcluded(Q.NumExcluded) {
133     Excluded = Q.Excluded;
134     Excluded[NumExcluded++] = NewExcl;
135     assert(NumExcluded <= Excluded.size());
136   }
137 
138   bool isExcluded(const Value *Value) const {
139     if (NumExcluded == 0)
140       return false;
141     auto End = Excluded.begin() + NumExcluded;
142     return std::find(Excluded.begin(), End, Value) != End;
143   }
144 };
145 
146 } // end anonymous namespace
147 
148 // Given the provided Value and, potentially, a context instruction, return
149 // the preferred context instruction (if any).
150 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
151   // If we've been provided with a context instruction, then use that (provided
152   // it has been inserted).
153   if (CxtI && CxtI->getParent())
154     return CxtI;
155 
156   // If the value is really an already-inserted instruction, then use that.
157   CxtI = dyn_cast<Instruction>(V);
158   if (CxtI && CxtI->getParent())
159     return CxtI;
160 
161   return nullptr;
162 }
163 
164 static void computeKnownBits(const Value *V, KnownBits &Known,
165                              unsigned Depth, const Query &Q);
166 
167 void llvm::computeKnownBits(const Value *V, KnownBits &Known,
168                             const DataLayout &DL, unsigned Depth,
169                             AssumptionCache *AC, const Instruction *CxtI,
170                             const DominatorTree *DT,
171                             OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
172   ::computeKnownBits(V, Known, Depth,
173                      Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
174 }
175 
176 static KnownBits computeKnownBits(const Value *V, unsigned Depth,
177                                   const Query &Q);
178 
179 KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
180                                  unsigned Depth, AssumptionCache *AC,
181                                  const Instruction *CxtI,
182                                  const DominatorTree *DT,
183                                  OptimizationRemarkEmitter *ORE,
184                                  bool UseInstrInfo) {
185   return ::computeKnownBits(
186       V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
187 }
188 
189 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
190                                const DataLayout &DL, AssumptionCache *AC,
191                                const Instruction *CxtI, const DominatorTree *DT,
192                                bool UseInstrInfo) {
193   assert(LHS->getType() == RHS->getType() &&
194          "LHS and RHS should have the same type");
195   assert(LHS->getType()->isIntOrIntVectorTy() &&
196          "LHS and RHS should be integers");
197   // Look for an inverted mask: (X & ~M) op (Y & M).
198   Value *M;
199   if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
200       match(RHS, m_c_And(m_Specific(M), m_Value())))
201     return true;
202   if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
203       match(LHS, m_c_And(m_Specific(M), m_Value())))
204     return true;
205   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
206   KnownBits LHSKnown(IT->getBitWidth());
207   KnownBits RHSKnown(IT->getBitWidth());
208   computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
209   computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
210   return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
211 }
212 
213 bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
214   for (const User *U : CxtI->users()) {
215     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
216       if (IC->isEquality())
217         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
218           if (C->isNullValue())
219             continue;
220     return false;
221   }
222   return true;
223 }
224 
225 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
226                                    const Query &Q);
227 
228 bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
229                                   bool OrZero, unsigned Depth,
230                                   AssumptionCache *AC, const Instruction *CxtI,
231                                   const DominatorTree *DT, bool UseInstrInfo) {
232   return ::isKnownToBeAPowerOfTwo(
233       V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
234 }
235 
236 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
237 
238 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
239                           AssumptionCache *AC, const Instruction *CxtI,
240                           const DominatorTree *DT, bool UseInstrInfo) {
241   return ::isKnownNonZero(V, Depth,
242                           Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
243 }
244 
245 bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
246                               unsigned Depth, AssumptionCache *AC,
247                               const Instruction *CxtI, const DominatorTree *DT,
248                               bool UseInstrInfo) {
249   KnownBits Known =
250       computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
251   return Known.isNonNegative();
252 }
253 
254 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
255                            AssumptionCache *AC, const Instruction *CxtI,
256                            const DominatorTree *DT, bool UseInstrInfo) {
257   if (auto *CI = dyn_cast<ConstantInt>(V))
258     return CI->getValue().isStrictlyPositive();
259 
260   // TODO: We'd doing two recursive queries here.  We should factor this such
261   // that only a single query is needed.
262   return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
263          isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
264 }
265 
266 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
267                            AssumptionCache *AC, const Instruction *CxtI,
268                            const DominatorTree *DT, bool UseInstrInfo) {
269   KnownBits Known =
270       computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
271   return Known.isNegative();
272 }
273 
274 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
275 
276 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
277                            const DataLayout &DL, AssumptionCache *AC,
278                            const Instruction *CxtI, const DominatorTree *DT,
279                            bool UseInstrInfo) {
280   return ::isKnownNonEqual(V1, V2,
281                            Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
282                                  UseInstrInfo, /*ORE=*/nullptr));
283 }
284 
285 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
286                               const Query &Q);
287 
288 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
289                              const DataLayout &DL, unsigned Depth,
290                              AssumptionCache *AC, const Instruction *CxtI,
291                              const DominatorTree *DT, bool UseInstrInfo) {
292   return ::MaskedValueIsZero(
293       V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
294 }
295 
296 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
297                                    const Query &Q);
298 
299 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
300                                   unsigned Depth, AssumptionCache *AC,
301                                   const Instruction *CxtI,
302                                   const DominatorTree *DT, bool UseInstrInfo) {
303   return ::ComputeNumSignBits(
304       V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
305 }
306 
307 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
308                                    bool NSW,
309                                    KnownBits &KnownOut, KnownBits &Known2,
310                                    unsigned Depth, const Query &Q) {
311   unsigned BitWidth = KnownOut.getBitWidth();
312 
313   // If an initial sequence of bits in the result is not needed, the
314   // corresponding bits in the operands are not needed.
315   KnownBits LHSKnown(BitWidth);
316   computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
317   computeKnownBits(Op1, Known2, Depth + 1, Q);
318 
319   KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
320 }
321 
322 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
323                                 KnownBits &Known, KnownBits &Known2,
324                                 unsigned Depth, const Query &Q) {
325   unsigned BitWidth = Known.getBitWidth();
326   computeKnownBits(Op1, Known, Depth + 1, Q);
327   computeKnownBits(Op0, Known2, Depth + 1, Q);
328 
329   bool isKnownNegative = false;
330   bool isKnownNonNegative = false;
331   // If the multiplication is known not to overflow, compute the sign bit.
332   if (NSW) {
333     if (Op0 == Op1) {
334       // The product of a number with itself is non-negative.
335       isKnownNonNegative = true;
336     } else {
337       bool isKnownNonNegativeOp1 = Known.isNonNegative();
338       bool isKnownNonNegativeOp0 = Known2.isNonNegative();
339       bool isKnownNegativeOp1 = Known.isNegative();
340       bool isKnownNegativeOp0 = Known2.isNegative();
341       // The product of two numbers with the same sign is non-negative.
342       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
343         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
344       // The product of a negative number and a non-negative number is either
345       // negative or zero.
346       if (!isKnownNonNegative)
347         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
348                            isKnownNonZero(Op0, Depth, Q)) ||
349                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
350                            isKnownNonZero(Op1, Depth, Q));
351     }
352   }
353 
354   assert(!Known.hasConflict() && !Known2.hasConflict());
355   // Compute a conservative estimate for high known-0 bits.
356   unsigned LeadZ =  std::max(Known.countMinLeadingZeros() +
357                              Known2.countMinLeadingZeros(),
358                              BitWidth) - BitWidth;
359   LeadZ = std::min(LeadZ, BitWidth);
360 
361   // The result of the bottom bits of an integer multiply can be
362   // inferred by looking at the bottom bits of both operands and
363   // multiplying them together.
364   // We can infer at least the minimum number of known trailing bits
365   // of both operands. Depending on number of trailing zeros, we can
366   // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
367   // a and b are divisible by m and n respectively.
368   // We then calculate how many of those bits are inferrable and set
369   // the output. For example, the i8 mul:
370   //  a = XXXX1100 (12)
371   //  b = XXXX1110 (14)
372   // We know the bottom 3 bits are zero since the first can be divided by
373   // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
374   // Applying the multiplication to the trimmed arguments gets:
375   //    XX11 (3)
376   //    X111 (7)
377   // -------
378   //    XX11
379   //   XX11
380   //  XX11
381   // XX11
382   // -------
383   // XXXXX01
384   // Which allows us to infer the 2 LSBs. Since we're multiplying the result
385   // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
386   // The proof for this can be described as:
387   // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
388   //      (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
389   //                    umin(countTrailingZeros(C2), C6) +
390   //                    umin(C5 - umin(countTrailingZeros(C1), C5),
391   //                         C6 - umin(countTrailingZeros(C2), C6)))) - 1)
392   // %aa = shl i8 %a, C5
393   // %bb = shl i8 %b, C6
394   // %aaa = or i8 %aa, C1
395   // %bbb = or i8 %bb, C2
396   // %mul = mul i8 %aaa, %bbb
397   // %mask = and i8 %mul, C7
398   //   =>
399   // %mask = i8 ((C1*C2)&C7)
400   // Where C5, C6 describe the known bits of %a, %b
401   // C1, C2 describe the known bottom bits of %a, %b.
402   // C7 describes the mask of the known bits of the result.
403   APInt Bottom0 = Known.One;
404   APInt Bottom1 = Known2.One;
405 
406   // How many times we'd be able to divide each argument by 2 (shr by 1).
407   // This gives us the number of trailing zeros on the multiplication result.
408   unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
409   unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
410   unsigned TrailZero0 = Known.countMinTrailingZeros();
411   unsigned TrailZero1 = Known2.countMinTrailingZeros();
412   unsigned TrailZ = TrailZero0 + TrailZero1;
413 
414   // Figure out the fewest known-bits operand.
415   unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
416                                       TrailBitsKnown1 - TrailZero1);
417   unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
418 
419   APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
420                       Bottom1.getLoBits(TrailBitsKnown1);
421 
422   Known.resetAll();
423   Known.Zero.setHighBits(LeadZ);
424   Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
425   Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
426 
427   // Only make use of no-wrap flags if we failed to compute the sign bit
428   // directly.  This matters if the multiplication always overflows, in
429   // which case we prefer to follow the result of the direct computation,
430   // though as the program is invoking undefined behaviour we can choose
431   // whatever we like here.
432   if (isKnownNonNegative && !Known.isNegative())
433     Known.makeNonNegative();
434   else if (isKnownNegative && !Known.isNonNegative())
435     Known.makeNegative();
436 }
437 
438 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
439                                              KnownBits &Known) {
440   unsigned BitWidth = Known.getBitWidth();
441   unsigned NumRanges = Ranges.getNumOperands() / 2;
442   assert(NumRanges >= 1);
443 
444   Known.Zero.setAllBits();
445   Known.One.setAllBits();
446 
447   for (unsigned i = 0; i < NumRanges; ++i) {
448     ConstantInt *Lower =
449         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
450     ConstantInt *Upper =
451         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
452     ConstantRange Range(Lower->getValue(), Upper->getValue());
453 
454     // The first CommonPrefixBits of all values in Range are equal.
455     unsigned CommonPrefixBits =
456         (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
457 
458     APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
459     Known.One &= Range.getUnsignedMax() & Mask;
460     Known.Zero &= ~Range.getUnsignedMax() & Mask;
461   }
462 }
463 
464 static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
465   SmallVector<const Value *, 16> WorkSet(1, I);
466   SmallPtrSet<const Value *, 32> Visited;
467   SmallPtrSet<const Value *, 16> EphValues;
468 
469   // The instruction defining an assumption's condition itself is always
470   // considered ephemeral to that assumption (even if it has other
471   // non-ephemeral users). See r246696's test case for an example.
472   if (is_contained(I->operands(), E))
473     return true;
474 
475   while (!WorkSet.empty()) {
476     const Value *V = WorkSet.pop_back_val();
477     if (!Visited.insert(V).second)
478       continue;
479 
480     // If all uses of this value are ephemeral, then so is this value.
481     if (llvm::all_of(V->users(), [&](const User *U) {
482                                    return EphValues.count(U);
483                                  })) {
484       if (V == E)
485         return true;
486 
487       if (V == I || isSafeToSpeculativelyExecute(V)) {
488        EphValues.insert(V);
489        if (const User *U = dyn_cast<User>(V))
490          for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
491               J != JE; ++J)
492            WorkSet.push_back(*J);
493       }
494     }
495   }
496 
497   return false;
498 }
499 
500 // Is this an intrinsic that cannot be speculated but also cannot trap?
501 bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
502   if (const CallInst *CI = dyn_cast<CallInst>(I))
503     if (Function *F = CI->getCalledFunction())
504       switch (F->getIntrinsicID()) {
505       default: break;
506       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
507       case Intrinsic::assume:
508       case Intrinsic::sideeffect:
509       case Intrinsic::dbg_declare:
510       case Intrinsic::dbg_value:
511       case Intrinsic::dbg_label:
512       case Intrinsic::invariant_start:
513       case Intrinsic::invariant_end:
514       case Intrinsic::lifetime_start:
515       case Intrinsic::lifetime_end:
516       case Intrinsic::objectsize:
517       case Intrinsic::ptr_annotation:
518       case Intrinsic::var_annotation:
519         return true;
520       }
521 
522   return false;
523 }
524 
525 bool llvm::isValidAssumeForContext(const Instruction *Inv,
526                                    const Instruction *CxtI,
527                                    const DominatorTree *DT) {
528   // There are two restrictions on the use of an assume:
529   //  1. The assume must dominate the context (or the control flow must
530   //     reach the assume whenever it reaches the context).
531   //  2. The context must not be in the assume's set of ephemeral values
532   //     (otherwise we will use the assume to prove that the condition
533   //     feeding the assume is trivially true, thus causing the removal of
534   //     the assume).
535 
536   if (DT) {
537     if (DT->dominates(Inv, CxtI))
538       return true;
539   } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
540     // We don't have a DT, but this trivially dominates.
541     return true;
542   }
543 
544   // With or without a DT, the only remaining case we will check is if the
545   // instructions are in the same BB.  Give up if that is not the case.
546   if (Inv->getParent() != CxtI->getParent())
547     return false;
548 
549   // If we have a dom tree, then we now know that the assume doesn't dominate
550   // the other instruction.  If we don't have a dom tree then we can check if
551   // the assume is first in the BB.
552   if (!DT) {
553     // Search forward from the assume until we reach the context (or the end
554     // of the block); the common case is that the assume will come first.
555     for (auto I = std::next(BasicBlock::const_iterator(Inv)),
556          IE = Inv->getParent()->end(); I != IE; ++I)
557       if (&*I == CxtI)
558         return true;
559   }
560 
561   // The context comes first, but they're both in the same block. Make sure
562   // there is nothing in between that might interrupt the control flow.
563   for (BasicBlock::const_iterator I =
564          std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
565        I != IE; ++I)
566     if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
567       return false;
568 
569   return !isEphemeralValueOf(Inv, CxtI);
570 }
571 
572 static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
573                                        unsigned Depth, const Query &Q) {
574   // Use of assumptions is context-sensitive. If we don't have a context, we
575   // cannot use them!
576   if (!Q.AC || !Q.CxtI)
577     return;
578 
579   unsigned BitWidth = Known.getBitWidth();
580 
581   // Note that the patterns below need to be kept in sync with the code
582   // in AssumptionCache::updateAffectedValues.
583 
584   for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
585     if (!AssumeVH)
586       continue;
587     CallInst *I = cast<CallInst>(AssumeVH);
588     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
589            "Got assumption for the wrong function!");
590     if (Q.isExcluded(I))
591       continue;
592 
593     // Warning: This loop can end up being somewhat performance sensitive.
594     // We're running this loop for once for each value queried resulting in a
595     // runtime of ~O(#assumes * #values).
596 
597     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
598            "must be an assume intrinsic");
599 
600     Value *Arg = I->getArgOperand(0);
601 
602     if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
603       assert(BitWidth == 1 && "assume operand is not i1?");
604       Known.setAllOnes();
605       return;
606     }
607     if (match(Arg, m_Not(m_Specific(V))) &&
608         isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
609       assert(BitWidth == 1 && "assume operand is not i1?");
610       Known.setAllZero();
611       return;
612     }
613 
614     // The remaining tests are all recursive, so bail out if we hit the limit.
615     if (Depth == MaxDepth)
616       continue;
617 
618     ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
619     if (!Cmp)
620       continue;
621 
622     Value *A, *B;
623     auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
624 
625     CmpInst::Predicate Pred;
626     uint64_t C;
627     switch (Cmp->getPredicate()) {
628     default:
629       break;
630     case ICmpInst::ICMP_EQ:
631       // assume(v = a)
632       if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
633           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
634         KnownBits RHSKnown(BitWidth);
635         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
636         Known.Zero |= RHSKnown.Zero;
637         Known.One  |= RHSKnown.One;
638       // assume(v & b = a)
639       } else if (match(Cmp,
640                        m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
641                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
642         KnownBits RHSKnown(BitWidth);
643         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
644         KnownBits MaskKnown(BitWidth);
645         computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
646 
647         // For those bits in the mask that are known to be one, we can propagate
648         // known bits from the RHS to V.
649         Known.Zero |= RHSKnown.Zero & MaskKnown.One;
650         Known.One  |= RHSKnown.One  & MaskKnown.One;
651       // assume(~(v & b) = a)
652       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
653                                      m_Value(A))) &&
654                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
655         KnownBits RHSKnown(BitWidth);
656         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
657         KnownBits MaskKnown(BitWidth);
658         computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
659 
660         // For those bits in the mask that are known to be one, we can propagate
661         // inverted known bits from the RHS to V.
662         Known.Zero |= RHSKnown.One  & MaskKnown.One;
663         Known.One  |= RHSKnown.Zero & MaskKnown.One;
664       // assume(v | b = a)
665       } else if (match(Cmp,
666                        m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
667                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
668         KnownBits RHSKnown(BitWidth);
669         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
670         KnownBits BKnown(BitWidth);
671         computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
672 
673         // For those bits in B that are known to be zero, we can propagate known
674         // bits from the RHS to V.
675         Known.Zero |= RHSKnown.Zero & BKnown.Zero;
676         Known.One  |= RHSKnown.One  & BKnown.Zero;
677       // assume(~(v | b) = a)
678       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
679                                      m_Value(A))) &&
680                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
681         KnownBits RHSKnown(BitWidth);
682         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
683         KnownBits BKnown(BitWidth);
684         computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
685 
686         // For those bits in B that are known to be zero, we can propagate
687         // inverted known bits from the RHS to V.
688         Known.Zero |= RHSKnown.One  & BKnown.Zero;
689         Known.One  |= RHSKnown.Zero & BKnown.Zero;
690       // assume(v ^ b = a)
691       } else if (match(Cmp,
692                        m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
693                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
694         KnownBits RHSKnown(BitWidth);
695         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
696         KnownBits BKnown(BitWidth);
697         computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
698 
699         // For those bits in B that are known to be zero, we can propagate known
700         // bits from the RHS to V. For those bits in B that are known to be one,
701         // we can propagate inverted known bits from the RHS to V.
702         Known.Zero |= RHSKnown.Zero & BKnown.Zero;
703         Known.One  |= RHSKnown.One  & BKnown.Zero;
704         Known.Zero |= RHSKnown.One  & BKnown.One;
705         Known.One  |= RHSKnown.Zero & BKnown.One;
706       // assume(~(v ^ b) = a)
707       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
708                                      m_Value(A))) &&
709                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
710         KnownBits RHSKnown(BitWidth);
711         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
712         KnownBits BKnown(BitWidth);
713         computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
714 
715         // For those bits in B that are known to be zero, we can propagate
716         // inverted known bits from the RHS to V. For those bits in B that are
717         // known to be one, we can propagate known bits from the RHS to V.
718         Known.Zero |= RHSKnown.One  & BKnown.Zero;
719         Known.One  |= RHSKnown.Zero & BKnown.Zero;
720         Known.Zero |= RHSKnown.Zero & BKnown.One;
721         Known.One  |= RHSKnown.One  & BKnown.One;
722       // assume(v << c = a)
723       } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
724                                      m_Value(A))) &&
725                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
726         KnownBits RHSKnown(BitWidth);
727         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
728         // For those bits in RHS that are known, we can propagate them to known
729         // bits in V shifted to the right by C.
730         RHSKnown.Zero.lshrInPlace(C);
731         Known.Zero |= RHSKnown.Zero;
732         RHSKnown.One.lshrInPlace(C);
733         Known.One  |= RHSKnown.One;
734       // assume(~(v << c) = a)
735       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
736                                      m_Value(A))) &&
737                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
738         KnownBits RHSKnown(BitWidth);
739         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
740         // For those bits in RHS that are known, we can propagate them inverted
741         // to known bits in V shifted to the right by C.
742         RHSKnown.One.lshrInPlace(C);
743         Known.Zero |= RHSKnown.One;
744         RHSKnown.Zero.lshrInPlace(C);
745         Known.One  |= RHSKnown.Zero;
746       // assume(v >> c = a)
747       } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
748                                      m_Value(A))) &&
749                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
750         KnownBits RHSKnown(BitWidth);
751         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
752         // For those bits in RHS that are known, we can propagate them to known
753         // bits in V shifted to the right by C.
754         Known.Zero |= RHSKnown.Zero << C;
755         Known.One  |= RHSKnown.One  << C;
756       // assume(~(v >> c) = a)
757       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
758                                      m_Value(A))) &&
759                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
760         KnownBits RHSKnown(BitWidth);
761         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
762         // For those bits in RHS that are known, we can propagate them inverted
763         // to known bits in V shifted to the right by C.
764         Known.Zero |= RHSKnown.One  << C;
765         Known.One  |= RHSKnown.Zero << C;
766       }
767       break;
768     case ICmpInst::ICMP_SGE:
769       // assume(v >=_s c) where c is non-negative
770       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
771           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
772         KnownBits RHSKnown(BitWidth);
773         computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
774 
775         if (RHSKnown.isNonNegative()) {
776           // We know that the sign bit is zero.
777           Known.makeNonNegative();
778         }
779       }
780       break;
781     case ICmpInst::ICMP_SGT:
782       // assume(v >_s c) where c is at least -1.
783       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
784           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
785         KnownBits RHSKnown(BitWidth);
786         computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
787 
788         if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
789           // We know that the sign bit is zero.
790           Known.makeNonNegative();
791         }
792       }
793       break;
794     case ICmpInst::ICMP_SLE:
795       // assume(v <=_s c) where c is negative
796       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
797           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
798         KnownBits RHSKnown(BitWidth);
799         computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
800 
801         if (RHSKnown.isNegative()) {
802           // We know that the sign bit is one.
803           Known.makeNegative();
804         }
805       }
806       break;
807     case ICmpInst::ICMP_SLT:
808       // assume(v <_s c) where c is non-positive
809       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
810           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
811         KnownBits RHSKnown(BitWidth);
812         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
813 
814         if (RHSKnown.isZero() || RHSKnown.isNegative()) {
815           // We know that the sign bit is one.
816           Known.makeNegative();
817         }
818       }
819       break;
820     case ICmpInst::ICMP_ULE:
821       // assume(v <=_u c)
822       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
823           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
824         KnownBits RHSKnown(BitWidth);
825         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
826 
827         // Whatever high bits in c are zero are known to be zero.
828         Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
829       }
830       break;
831     case ICmpInst::ICMP_ULT:
832       // assume(v <_u c)
833       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
834           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
835         KnownBits RHSKnown(BitWidth);
836         computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
837 
838         // If the RHS is known zero, then this assumption must be wrong (nothing
839         // is unsigned less than zero). Signal a conflict and get out of here.
840         if (RHSKnown.isZero()) {
841           Known.Zero.setAllBits();
842           Known.One.setAllBits();
843           break;
844         }
845 
846         // Whatever high bits in c are zero are known to be zero (if c is a power
847         // of 2, then one more).
848         if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
849           Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
850         else
851           Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
852       }
853       break;
854     }
855   }
856 
857   // If assumptions conflict with each other or previous known bits, then we
858   // have a logical fallacy. It's possible that the assumption is not reachable,
859   // so this isn't a real bug. On the other hand, the program may have undefined
860   // behavior, or we might have a bug in the compiler. We can't assert/crash, so
861   // clear out the known bits, try to warn the user, and hope for the best.
862   if (Known.Zero.intersects(Known.One)) {
863     Known.resetAll();
864 
865     if (Q.ORE)
866       Q.ORE->emit([&]() {
867         auto *CxtI = const_cast<Instruction *>(Q.CxtI);
868         return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
869                                           CxtI)
870                << "Detected conflicting code assumptions. Program may "
871                   "have undefined behavior, or compiler may have "
872                   "internal error.";
873       });
874   }
875 }
876 
877 /// Compute known bits from a shift operator, including those with a
878 /// non-constant shift amount. Known is the output of this function. Known2 is a
879 /// pre-allocated temporary with the same bit width as Known. KZF and KOF are
880 /// operator-specific functions that, given the known-zero or known-one bits
881 /// respectively, and a shift amount, compute the implied known-zero or
882 /// known-one bits of the shift operator's result respectively for that shift
883 /// amount. The results from calling KZF and KOF are conservatively combined for
884 /// all permitted shift amounts.
885 static void computeKnownBitsFromShiftOperator(
886     const Operator *I, KnownBits &Known, KnownBits &Known2,
887     unsigned Depth, const Query &Q,
888     function_ref<APInt(const APInt &, unsigned)> KZF,
889     function_ref<APInt(const APInt &, unsigned)> KOF) {
890   unsigned BitWidth = Known.getBitWidth();
891 
892   if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
893     unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
894 
895     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
896     Known.Zero = KZF(Known.Zero, ShiftAmt);
897     Known.One  = KOF(Known.One, ShiftAmt);
898     // If the known bits conflict, this must be an overflowing left shift, so
899     // the shift result is poison. We can return anything we want. Choose 0 for
900     // the best folding opportunity.
901     if (Known.hasConflict())
902       Known.setAllZero();
903 
904     return;
905   }
906 
907   computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
908 
909   // If the shift amount could be greater than or equal to the bit-width of the
910   // LHS, the value could be poison, but bail out because the check below is
911   // expensive. TODO: Should we just carry on?
912   if ((~Known.Zero).uge(BitWidth)) {
913     Known.resetAll();
914     return;
915   }
916 
917   // Note: We cannot use Known.Zero.getLimitedValue() here, because if
918   // BitWidth > 64 and any upper bits are known, we'll end up returning the
919   // limit value (which implies all bits are known).
920   uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
921   uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
922 
923   // It would be more-clearly correct to use the two temporaries for this
924   // calculation. Reusing the APInts here to prevent unnecessary allocations.
925   Known.resetAll();
926 
927   // If we know the shifter operand is nonzero, we can sometimes infer more
928   // known bits. However this is expensive to compute, so be lazy about it and
929   // only compute it when absolutely necessary.
930   Optional<bool> ShifterOperandIsNonZero;
931 
932   // Early exit if we can't constrain any well-defined shift amount.
933   if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
934       !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
935     ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
936     if (!*ShifterOperandIsNonZero)
937       return;
938   }
939 
940   computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
941 
942   Known.Zero.setAllBits();
943   Known.One.setAllBits();
944   for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
945     // Combine the shifted known input bits only for those shift amounts
946     // compatible with its known constraints.
947     if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
948       continue;
949     if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
950       continue;
951     // If we know the shifter is nonzero, we may be able to infer more known
952     // bits. This check is sunk down as far as possible to avoid the expensive
953     // call to isKnownNonZero if the cheaper checks above fail.
954     if (ShiftAmt == 0) {
955       if (!ShifterOperandIsNonZero.hasValue())
956         ShifterOperandIsNonZero =
957             isKnownNonZero(I->getOperand(1), Depth + 1, Q);
958       if (*ShifterOperandIsNonZero)
959         continue;
960     }
961 
962     Known.Zero &= KZF(Known2.Zero, ShiftAmt);
963     Known.One  &= KOF(Known2.One, ShiftAmt);
964   }
965 
966   // If the known bits conflict, the result is poison. Return a 0 and hope the
967   // caller can further optimize that.
968   if (Known.hasConflict())
969     Known.setAllZero();
970 }
971 
972 static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
973                                          unsigned Depth, const Query &Q) {
974   unsigned BitWidth = Known.getBitWidth();
975 
976   KnownBits Known2(Known);
977   switch (I->getOpcode()) {
978   default: break;
979   case Instruction::Load:
980     if (MDNode *MD =
981             Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
982       computeKnownBitsFromRangeMetadata(*MD, Known);
983     break;
984   case Instruction::And: {
985     // If either the LHS or the RHS are Zero, the result is zero.
986     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
987     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
988 
989     // Output known-1 bits are only known if set in both the LHS & RHS.
990     Known.One &= Known2.One;
991     // Output known-0 are known to be clear if zero in either the LHS | RHS.
992     Known.Zero |= Known2.Zero;
993 
994     // and(x, add (x, -1)) is a common idiom that always clears the low bit;
995     // here we handle the more general case of adding any odd number by
996     // matching the form add(x, add(x, y)) where y is odd.
997     // TODO: This could be generalized to clearing any bit set in y where the
998     // following bit is known to be unset in y.
999     Value *X = nullptr, *Y = nullptr;
1000     if (!Known.Zero[0] && !Known.One[0] &&
1001         match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
1002       Known2.resetAll();
1003       computeKnownBits(Y, Known2, Depth + 1, Q);
1004       if (Known2.countMinTrailingOnes() > 0)
1005         Known.Zero.setBit(0);
1006     }
1007     break;
1008   }
1009   case Instruction::Or:
1010     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1011     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1012 
1013     // Output known-0 bits are only known if clear in both the LHS & RHS.
1014     Known.Zero &= Known2.Zero;
1015     // Output known-1 are known to be set if set in either the LHS | RHS.
1016     Known.One |= Known2.One;
1017     break;
1018   case Instruction::Xor: {
1019     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1020     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1021 
1022     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1023     APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
1024     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1025     Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1026     Known.Zero = std::move(KnownZeroOut);
1027     break;
1028   }
1029   case Instruction::Mul: {
1030     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1031     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1032                         Known2, Depth, Q);
1033     break;
1034   }
1035   case Instruction::UDiv: {
1036     // For the purposes of computing leading zeros we can conservatively
1037     // treat a udiv as a logical right shift by the power of 2 known to
1038     // be less than the denominator.
1039     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1040     unsigned LeadZ = Known2.countMinLeadingZeros();
1041 
1042     Known2.resetAll();
1043     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1044     unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1045     if (RHSMaxLeadingZeros != BitWidth)
1046       LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
1047 
1048     Known.Zero.setHighBits(LeadZ);
1049     break;
1050   }
1051   case Instruction::Select: {
1052     const Value *LHS, *RHS;
1053     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1054     if (SelectPatternResult::isMinOrMax(SPF)) {
1055       computeKnownBits(RHS, Known, Depth + 1, Q);
1056       computeKnownBits(LHS, Known2, Depth + 1, Q);
1057     } else {
1058       computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1059       computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1060     }
1061 
1062     unsigned MaxHighOnes = 0;
1063     unsigned MaxHighZeros = 0;
1064     if (SPF == SPF_SMAX) {
1065       // If both sides are negative, the result is negative.
1066       if (Known.isNegative() && Known2.isNegative())
1067         // We can derive a lower bound on the result by taking the max of the
1068         // leading one bits.
1069         MaxHighOnes =
1070             std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
1071       // If either side is non-negative, the result is non-negative.
1072       else if (Known.isNonNegative() || Known2.isNonNegative())
1073         MaxHighZeros = 1;
1074     } else if (SPF == SPF_SMIN) {
1075       // If both sides are non-negative, the result is non-negative.
1076       if (Known.isNonNegative() && Known2.isNonNegative())
1077         // We can derive an upper bound on the result by taking the max of the
1078         // leading zero bits.
1079         MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1080                                 Known2.countMinLeadingZeros());
1081       // If either side is negative, the result is negative.
1082       else if (Known.isNegative() || Known2.isNegative())
1083         MaxHighOnes = 1;
1084     } else if (SPF == SPF_UMAX) {
1085       // We can derive a lower bound on the result by taking the max of the
1086       // leading one bits.
1087       MaxHighOnes =
1088           std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
1089     } else if (SPF == SPF_UMIN) {
1090       // We can derive an upper bound on the result by taking the max of the
1091       // leading zero bits.
1092       MaxHighZeros =
1093           std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
1094     } else if (SPF == SPF_ABS) {
1095       // RHS from matchSelectPattern returns the negation part of abs pattern.
1096       // If the negate has an NSW flag we can assume the sign bit of the result
1097       // will be 0 because that makes abs(INT_MIN) undefined.
1098       if (match(RHS, m_Neg(m_Specific(LHS))) &&
1099           Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
1100         MaxHighZeros = 1;
1101     }
1102 
1103     // Only known if known in both the LHS and RHS.
1104     Known.One &= Known2.One;
1105     Known.Zero &= Known2.Zero;
1106     if (MaxHighOnes > 0)
1107       Known.One.setHighBits(MaxHighOnes);
1108     if (MaxHighZeros > 0)
1109       Known.Zero.setHighBits(MaxHighZeros);
1110     break;
1111   }
1112   case Instruction::FPTrunc:
1113   case Instruction::FPExt:
1114   case Instruction::FPToUI:
1115   case Instruction::FPToSI:
1116   case Instruction::SIToFP:
1117   case Instruction::UIToFP:
1118     break; // Can't work with floating point.
1119   case Instruction::PtrToInt:
1120   case Instruction::IntToPtr:
1121     // Fall through and handle them the same as zext/trunc.
1122     LLVM_FALLTHROUGH;
1123   case Instruction::ZExt:
1124   case Instruction::Trunc: {
1125     Type *SrcTy = I->getOperand(0)->getType();
1126 
1127     unsigned SrcBitWidth;
1128     // Note that we handle pointer operands here because of inttoptr/ptrtoint
1129     // which fall through here.
1130     Type *ScalarTy = SrcTy->getScalarType();
1131     SrcBitWidth = ScalarTy->isPointerTy() ?
1132       Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1133       Q.DL.getTypeSizeInBits(ScalarTy);
1134 
1135     assert(SrcBitWidth && "SrcBitWidth can't be zero");
1136     Known = Known.zextOrTrunc(SrcBitWidth, false);
1137     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1138     Known = Known.zextOrTrunc(BitWidth, true /* ExtendedBitsAreKnownZero */);
1139     break;
1140   }
1141   case Instruction::BitCast: {
1142     Type *SrcTy = I->getOperand(0)->getType();
1143     if (SrcTy->isIntOrPtrTy() &&
1144         // TODO: For now, not handling conversions like:
1145         // (bitcast i64 %x to <2 x i32>)
1146         !I->getType()->isVectorTy()) {
1147       computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1148       break;
1149     }
1150     break;
1151   }
1152   case Instruction::SExt: {
1153     // Compute the bits in the result that are not present in the input.
1154     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1155 
1156     Known = Known.trunc(SrcBitWidth);
1157     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1158     // If the sign bit of the input is known set or clear, then we know the
1159     // top bits of the result.
1160     Known = Known.sext(BitWidth);
1161     break;
1162   }
1163   case Instruction::Shl: {
1164     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1165     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1166     auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1167       APInt KZResult = KnownZero << ShiftAmt;
1168       KZResult.setLowBits(ShiftAmt); // Low bits known 0.
1169       // If this shift has "nsw" keyword, then the result is either a poison
1170       // value or has the same sign bit as the first operand.
1171       if (NSW && KnownZero.isSignBitSet())
1172         KZResult.setSignBit();
1173       return KZResult;
1174     };
1175 
1176     auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1177       APInt KOResult = KnownOne << ShiftAmt;
1178       if (NSW && KnownOne.isSignBitSet())
1179         KOResult.setSignBit();
1180       return KOResult;
1181     };
1182 
1183     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1184     break;
1185   }
1186   case Instruction::LShr: {
1187     // (lshr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1188     auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1189       APInt KZResult = KnownZero.lshr(ShiftAmt);
1190       // High bits known zero.
1191       KZResult.setHighBits(ShiftAmt);
1192       return KZResult;
1193     };
1194 
1195     auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1196       return KnownOne.lshr(ShiftAmt);
1197     };
1198 
1199     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1200     break;
1201   }
1202   case Instruction::AShr: {
1203     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1204     auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1205       return KnownZero.ashr(ShiftAmt);
1206     };
1207 
1208     auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1209       return KnownOne.ashr(ShiftAmt);
1210     };
1211 
1212     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1213     break;
1214   }
1215   case Instruction::Sub: {
1216     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1217     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1218                            Known, Known2, Depth, Q);
1219     break;
1220   }
1221   case Instruction::Add: {
1222     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1223     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1224                            Known, Known2, Depth, Q);
1225     break;
1226   }
1227   case Instruction::SRem:
1228     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1229       APInt RA = Rem->getValue().abs();
1230       if (RA.isPowerOf2()) {
1231         APInt LowBits = RA - 1;
1232         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1233 
1234         // The low bits of the first operand are unchanged by the srem.
1235         Known.Zero = Known2.Zero & LowBits;
1236         Known.One = Known2.One & LowBits;
1237 
1238         // If the first operand is non-negative or has all low bits zero, then
1239         // the upper bits are all zero.
1240         if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
1241           Known.Zero |= ~LowBits;
1242 
1243         // If the first operand is negative and not all low bits are zero, then
1244         // the upper bits are all one.
1245         if (Known2.isNegative() && LowBits.intersects(Known2.One))
1246           Known.One |= ~LowBits;
1247 
1248         assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1249         break;
1250       }
1251     }
1252 
1253     // The sign bit is the LHS's sign bit, except when the result of the
1254     // remainder is zero.
1255     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1256     // If it's known zero, our sign bit is also zero.
1257     if (Known2.isNonNegative())
1258       Known.makeNonNegative();
1259 
1260     break;
1261   case Instruction::URem: {
1262     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263       const APInt &RA = Rem->getValue();
1264       if (RA.isPowerOf2()) {
1265         APInt LowBits = (RA - 1);
1266         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1267         Known.Zero |= ~LowBits;
1268         Known.One &= LowBits;
1269         break;
1270       }
1271     }
1272 
1273     // Since the result is less than or equal to either operand, any leading
1274     // zero bits in either operand must also exist in the result.
1275     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1276     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1277 
1278     unsigned Leaders =
1279         std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
1280     Known.resetAll();
1281     Known.Zero.setHighBits(Leaders);
1282     break;
1283   }
1284 
1285   case Instruction::Alloca: {
1286     const AllocaInst *AI = cast<AllocaInst>(I);
1287     unsigned Align = AI->getAlignment();
1288     if (Align == 0)
1289       Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
1290 
1291     if (Align > 0)
1292       Known.Zero.setLowBits(countTrailingZeros(Align));
1293     break;
1294   }
1295   case Instruction::GetElementPtr: {
1296     // Analyze all of the subscripts of this getelementptr instruction
1297     // to determine if we can prove known low zero bits.
1298     KnownBits LocalKnown(BitWidth);
1299     computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
1300     unsigned TrailZ = LocalKnown.countMinTrailingZeros();
1301 
1302     gep_type_iterator GTI = gep_type_begin(I);
1303     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1304       Value *Index = I->getOperand(i);
1305       if (StructType *STy = GTI.getStructTypeOrNull()) {
1306         // Handle struct member offset arithmetic.
1307 
1308         // Handle case when index is vector zeroinitializer
1309         Constant *CIndex = cast<Constant>(Index);
1310         if (CIndex->isZeroValue())
1311           continue;
1312 
1313         if (CIndex->getType()->isVectorTy())
1314           Index = CIndex->getSplatValue();
1315 
1316         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1317         const StructLayout *SL = Q.DL.getStructLayout(STy);
1318         uint64_t Offset = SL->getElementOffset(Idx);
1319         TrailZ = std::min<unsigned>(TrailZ,
1320                                     countTrailingZeros(Offset));
1321       } else {
1322         // Handle array index arithmetic.
1323         Type *IndexedTy = GTI.getIndexedType();
1324         if (!IndexedTy->isSized()) {
1325           TrailZ = 0;
1326           break;
1327         }
1328         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1329         uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1330         LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1331         computeKnownBits(Index, LocalKnown, Depth + 1, Q);
1332         TrailZ = std::min(TrailZ,
1333                           unsigned(countTrailingZeros(TypeSize) +
1334                                    LocalKnown.countMinTrailingZeros()));
1335       }
1336     }
1337 
1338     Known.Zero.setLowBits(TrailZ);
1339     break;
1340   }
1341   case Instruction::PHI: {
1342     const PHINode *P = cast<PHINode>(I);
1343     // Handle the case of a simple two-predecessor recurrence PHI.
1344     // There's a lot more that could theoretically be done here, but
1345     // this is sufficient to catch some interesting cases.
1346     if (P->getNumIncomingValues() == 2) {
1347       for (unsigned i = 0; i != 2; ++i) {
1348         Value *L = P->getIncomingValue(i);
1349         Value *R = P->getIncomingValue(!i);
1350         Operator *LU = dyn_cast<Operator>(L);
1351         if (!LU)
1352           continue;
1353         unsigned Opcode = LU->getOpcode();
1354         // Check for operations that have the property that if
1355         // both their operands have low zero bits, the result
1356         // will have low zero bits.
1357         if (Opcode == Instruction::Add ||
1358             Opcode == Instruction::Sub ||
1359             Opcode == Instruction::And ||
1360             Opcode == Instruction::Or ||
1361             Opcode == Instruction::Mul) {
1362           Value *LL = LU->getOperand(0);
1363           Value *LR = LU->getOperand(1);
1364           // Find a recurrence.
1365           if (LL == I)
1366             L = LR;
1367           else if (LR == I)
1368             L = LL;
1369           else
1370             break;
1371           // Ok, we have a PHI of the form L op= R. Check for low
1372           // zero bits.
1373           computeKnownBits(R, Known2, Depth + 1, Q);
1374 
1375           // We need to take the minimum number of known bits
1376           KnownBits Known3(Known);
1377           computeKnownBits(L, Known3, Depth + 1, Q);
1378 
1379           Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1380                                          Known3.countMinTrailingZeros()));
1381 
1382           auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1383           if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
1384             // If initial value of recurrence is nonnegative, and we are adding
1385             // a nonnegative number with nsw, the result can only be nonnegative
1386             // or poison value regardless of the number of times we execute the
1387             // add in phi recurrence. If initial value is negative and we are
1388             // adding a negative number with nsw, the result can only be
1389             // negative or poison value. Similar arguments apply to sub and mul.
1390             //
1391             // (add non-negative, non-negative) --> non-negative
1392             // (add negative, negative) --> negative
1393             if (Opcode == Instruction::Add) {
1394               if (Known2.isNonNegative() && Known3.isNonNegative())
1395                 Known.makeNonNegative();
1396               else if (Known2.isNegative() && Known3.isNegative())
1397                 Known.makeNegative();
1398             }
1399 
1400             // (sub nsw non-negative, negative) --> non-negative
1401             // (sub nsw negative, non-negative) --> negative
1402             else if (Opcode == Instruction::Sub && LL == I) {
1403               if (Known2.isNonNegative() && Known3.isNegative())
1404                 Known.makeNonNegative();
1405               else if (Known2.isNegative() && Known3.isNonNegative())
1406                 Known.makeNegative();
1407             }
1408 
1409             // (mul nsw non-negative, non-negative) --> non-negative
1410             else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1411                      Known3.isNonNegative())
1412               Known.makeNonNegative();
1413           }
1414 
1415           break;
1416         }
1417       }
1418     }
1419 
1420     // Unreachable blocks may have zero-operand PHI nodes.
1421     if (P->getNumIncomingValues() == 0)
1422       break;
1423 
1424     // Otherwise take the unions of the known bit sets of the operands,
1425     // taking conservative care to avoid excessive recursion.
1426     if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
1427       // Skip if every incoming value references to ourself.
1428       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1429         break;
1430 
1431       Known.Zero.setAllBits();
1432       Known.One.setAllBits();
1433       for (Value *IncValue : P->incoming_values()) {
1434         // Skip direct self references.
1435         if (IncValue == P) continue;
1436 
1437         Known2 = KnownBits(BitWidth);
1438         // Recurse, but cap the recursion to one level, because we don't
1439         // want to waste time spinning around in loops.
1440         computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1441         Known.Zero &= Known2.Zero;
1442         Known.One &= Known2.One;
1443         // If all bits have been ruled out, there's no need to check
1444         // more operands.
1445         if (!Known.Zero && !Known.One)
1446           break;
1447       }
1448     }
1449     break;
1450   }
1451   case Instruction::Call:
1452   case Instruction::Invoke:
1453     // If range metadata is attached to this call, set known bits from that,
1454     // and then intersect with known bits based on other properties of the
1455     // function.
1456     if (MDNode *MD =
1457             Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
1458       computeKnownBitsFromRangeMetadata(*MD, Known);
1459     if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
1460       computeKnownBits(RV, Known2, Depth + 1, Q);
1461       Known.Zero |= Known2.Zero;
1462       Known.One |= Known2.One;
1463     }
1464     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1465       switch (II->getIntrinsicID()) {
1466       default: break;
1467       case Intrinsic::bitreverse:
1468         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1469         Known.Zero |= Known2.Zero.reverseBits();
1470         Known.One |= Known2.One.reverseBits();
1471         break;
1472       case Intrinsic::bswap:
1473         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1474         Known.Zero |= Known2.Zero.byteSwap();
1475         Known.One |= Known2.One.byteSwap();
1476         break;
1477       case Intrinsic::ctlz: {
1478         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1479         // If we have a known 1, its position is our upper bound.
1480         unsigned PossibleLZ = Known2.One.countLeadingZeros();
1481         // If this call is undefined for 0, the result will be less than 2^n.
1482         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1483           PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1484         unsigned LowBits = Log2_32(PossibleLZ)+1;
1485         Known.Zero.setBitsFrom(LowBits);
1486         break;
1487       }
1488       case Intrinsic::cttz: {
1489         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1490         // If we have a known 1, its position is our upper bound.
1491         unsigned PossibleTZ = Known2.One.countTrailingZeros();
1492         // If this call is undefined for 0, the result will be less than 2^n.
1493         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1494           PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1495         unsigned LowBits = Log2_32(PossibleTZ)+1;
1496         Known.Zero.setBitsFrom(LowBits);
1497         break;
1498       }
1499       case Intrinsic::ctpop: {
1500         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1501         // We can bound the space the count needs.  Also, bits known to be zero
1502         // can't contribute to the population.
1503         unsigned BitsPossiblySet = Known2.countMaxPopulation();
1504         unsigned LowBits = Log2_32(BitsPossiblySet)+1;
1505         Known.Zero.setBitsFrom(LowBits);
1506         // TODO: we could bound KnownOne using the lower bound on the number
1507         // of bits which might be set provided by popcnt KnownOne2.
1508         break;
1509       }
1510       case Intrinsic::fshr:
1511       case Intrinsic::fshl: {
1512         const APInt *SA;
1513         if (!match(I->getOperand(2), m_APInt(SA)))
1514           break;
1515 
1516         // Normalize to funnel shift left.
1517         uint64_t ShiftAmt = SA->urem(BitWidth);
1518         if (II->getIntrinsicID() == Intrinsic::fshr)
1519           ShiftAmt = BitWidth - ShiftAmt;
1520 
1521         KnownBits Known3(Known);
1522         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1523         computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1524 
1525         Known.Zero =
1526             Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1527         Known.One =
1528             Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1529         break;
1530       }
1531       case Intrinsic::uadd_sat:
1532       case Intrinsic::usub_sat: {
1533         bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1534         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1535         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1536 
1537         // Add: Leading ones of either operand are preserved.
1538         // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1539         // as leading zeros in the result.
1540         unsigned LeadingKnown;
1541         if (IsAdd)
1542           LeadingKnown = std::max(Known.countMinLeadingOnes(),
1543                                   Known2.countMinLeadingOnes());
1544         else
1545           LeadingKnown = std::max(Known.countMinLeadingZeros(),
1546                                   Known2.countMinLeadingOnes());
1547 
1548         Known = KnownBits::computeForAddSub(
1549             IsAdd, /* NSW */ false, Known, Known2);
1550 
1551         // We select between the operation result and all-ones/zero
1552         // respectively, so we can preserve known ones/zeros.
1553         if (IsAdd) {
1554           Known.One.setHighBits(LeadingKnown);
1555           Known.Zero.clearAllBits();
1556         } else {
1557           Known.Zero.setHighBits(LeadingKnown);
1558           Known.One.clearAllBits();
1559         }
1560         break;
1561       }
1562       case Intrinsic::x86_sse42_crc32_64_64:
1563         Known.Zero.setBitsFrom(32);
1564         break;
1565       }
1566     }
1567     break;
1568   case Instruction::ExtractElement:
1569     // Look through extract element. At the moment we keep this simple and skip
1570     // tracking the specific element. But at least we might find information
1571     // valid for all elements of the vector (for example if vector is sign
1572     // extended, shifted, etc).
1573     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1574     break;
1575   case Instruction::ExtractValue:
1576     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1577       const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1578       if (EVI->getNumIndices() != 1) break;
1579       if (EVI->getIndices()[0] == 0) {
1580         switch (II->getIntrinsicID()) {
1581         default: break;
1582         case Intrinsic::uadd_with_overflow:
1583         case Intrinsic::sadd_with_overflow:
1584           computeKnownBitsAddSub(true, II->getArgOperand(0),
1585                                  II->getArgOperand(1), false, Known, Known2,
1586                                  Depth, Q);
1587           break;
1588         case Intrinsic::usub_with_overflow:
1589         case Intrinsic::ssub_with_overflow:
1590           computeKnownBitsAddSub(false, II->getArgOperand(0),
1591                                  II->getArgOperand(1), false, Known, Known2,
1592                                  Depth, Q);
1593           break;
1594         case Intrinsic::umul_with_overflow:
1595         case Intrinsic::smul_with_overflow:
1596           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1597                               Known, Known2, Depth, Q);
1598           break;
1599         }
1600       }
1601     }
1602   }
1603 }
1604 
1605 /// Determine which bits of V are known to be either zero or one and return
1606 /// them.
1607 KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1608   KnownBits Known(getBitWidth(V->getType(), Q.DL));
1609   computeKnownBits(V, Known, Depth, Q);
1610   return Known;
1611 }
1612 
1613 /// Determine which bits of V are known to be either zero or one and return
1614 /// them in the Known bit set.
1615 ///
1616 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
1617 /// we cannot optimize based on the assumption that it is zero without changing
1618 /// it to be an explicit zero.  If we don't change it to zero, other code could
1619 /// optimized based on the contradictory assumption that it is non-zero.
1620 /// Because instcombine aggressively folds operations with undef args anyway,
1621 /// this won't lose us code quality.
1622 ///
1623 /// This function is defined on values with integer type, values with pointer
1624 /// type, and vectors of integers.  In the case
1625 /// where V is a vector, known zero, and known one values are the
1626 /// same width as the vector element, and the bit is set only if it is true
1627 /// for all of the elements in the vector.
1628 void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1629                       const Query &Q) {
1630   assert(V && "No Value?");
1631   assert(Depth <= MaxDepth && "Limit Search Depth");
1632   unsigned BitWidth = Known.getBitWidth();
1633 
1634   assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
1635           V->getType()->isPtrOrPtrVectorTy()) &&
1636          "Not integer or pointer type!");
1637 
1638   Type *ScalarTy = V->getType()->getScalarType();
1639   unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1640     Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1641   assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
1642   (void)BitWidth;
1643   (void)ExpectedWidth;
1644 
1645   const APInt *C;
1646   if (match(V, m_APInt(C))) {
1647     // We know all of the bits for a scalar constant or a splat vector constant!
1648     Known.One = *C;
1649     Known.Zero = ~Known.One;
1650     return;
1651   }
1652   // Null and aggregate-zero are all-zeros.
1653   if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1654     Known.setAllZero();
1655     return;
1656   }
1657   // Handle a constant vector by taking the intersection of the known bits of
1658   // each element.
1659   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1660     // We know that CDS must be a vector of integers. Take the intersection of
1661     // each element.
1662     Known.Zero.setAllBits(); Known.One.setAllBits();
1663     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1664       APInt Elt = CDS->getElementAsAPInt(i);
1665       Known.Zero &= ~Elt;
1666       Known.One &= Elt;
1667     }
1668     return;
1669   }
1670 
1671   if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1672     // We know that CV must be a vector of integers. Take the intersection of
1673     // each element.
1674     Known.Zero.setAllBits(); Known.One.setAllBits();
1675     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1676       Constant *Element = CV->getAggregateElement(i);
1677       auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1678       if (!ElementCI) {
1679         Known.resetAll();
1680         return;
1681       }
1682       const APInt &Elt = ElementCI->getValue();
1683       Known.Zero &= ~Elt;
1684       Known.One &= Elt;
1685     }
1686     return;
1687   }
1688 
1689   // Start out not knowing anything.
1690   Known.resetAll();
1691 
1692   // We can't imply anything about undefs.
1693   if (isa<UndefValue>(V))
1694     return;
1695 
1696   // There's no point in looking through other users of ConstantData for
1697   // assumptions.  Confirm that we've handled them all.
1698   assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1699 
1700   // Limit search depth.
1701   // All recursive calls that increase depth must come after this.
1702   if (Depth == MaxDepth)
1703     return;
1704 
1705   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1706   // the bits of its aliasee.
1707   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1708     if (!GA->isInterposable())
1709       computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1710     return;
1711   }
1712 
1713   if (const Operator *I = dyn_cast<Operator>(V))
1714     computeKnownBitsFromOperator(I, Known, Depth, Q);
1715 
1716   // Aligned pointers have trailing zeros - refine Known.Zero set
1717   if (V->getType()->isPointerTy()) {
1718     unsigned Align = V->getPointerAlignment(Q.DL);
1719     if (Align)
1720       Known.Zero.setLowBits(countTrailingZeros(Align));
1721   }
1722 
1723   // computeKnownBitsFromAssume strictly refines Known.
1724   // Therefore, we run them after computeKnownBitsFromOperator.
1725 
1726   // Check whether a nearby assume intrinsic can determine some known bits.
1727   computeKnownBitsFromAssume(V, Known, Depth, Q);
1728 
1729   assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1730 }
1731 
1732 /// Return true if the given value is known to have exactly one
1733 /// bit set when defined. For vectors return true if every element is known to
1734 /// be a power of two when defined. Supports values with integer or pointer
1735 /// types and vectors of integers.
1736 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1737                             const Query &Q) {
1738   assert(Depth <= MaxDepth && "Limit Search Depth");
1739 
1740   // Attempt to match against constants.
1741   if (OrZero && match(V, m_Power2OrZero()))
1742       return true;
1743   if (match(V, m_Power2()))
1744       return true;
1745 
1746   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1747   // it is shifted off the end then the result is undefined.
1748   if (match(V, m_Shl(m_One(), m_Value())))
1749     return true;
1750 
1751   // (signmask) >>l X is clearly a power of two if the one is not shifted off
1752   // the bottom.  If it is shifted off the bottom then the result is undefined.
1753   if (match(V, m_LShr(m_SignMask(), m_Value())))
1754     return true;
1755 
1756   // The remaining tests are all recursive, so bail out if we hit the limit.
1757   if (Depth++ == MaxDepth)
1758     return false;
1759 
1760   Value *X = nullptr, *Y = nullptr;
1761   // A shift left or a logical shift right of a power of two is a power of two
1762   // or zero.
1763   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1764                  match(V, m_LShr(m_Value(X), m_Value()))))
1765     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
1766 
1767   if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1768     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1769 
1770   if (const SelectInst *SI = dyn_cast<SelectInst>(V))
1771     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1772            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1773 
1774   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1775     // A power of two and'd with anything is a power of two or zero.
1776     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1777         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
1778       return true;
1779     // X & (-X) is always a power of two or zero.
1780     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1781       return true;
1782     return false;
1783   }
1784 
1785   // Adding a power-of-two or zero to the same power-of-two or zero yields
1786   // either the original power-of-two, a larger power-of-two or zero.
1787   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1788     const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1789     if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1790         Q.IIQ.hasNoSignedWrap(VOBO)) {
1791       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1792           match(X, m_And(m_Value(), m_Specific(Y))))
1793         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1794           return true;
1795       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1796           match(Y, m_And(m_Value(), m_Specific(X))))
1797         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1798           return true;
1799 
1800       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1801       KnownBits LHSBits(BitWidth);
1802       computeKnownBits(X, LHSBits, Depth, Q);
1803 
1804       KnownBits RHSBits(BitWidth);
1805       computeKnownBits(Y, RHSBits, Depth, Q);
1806       // If i8 V is a power of two or zero:
1807       //  ZeroBits: 1 1 1 0 1 1 1 1
1808       // ~ZeroBits: 0 0 0 1 0 0 0 0
1809       if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
1810         // If OrZero isn't set, we cannot give back a zero result.
1811         // Make sure either the LHS or RHS has a bit set.
1812         if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
1813           return true;
1814     }
1815   }
1816 
1817   // An exact divide or right shift can only shift off zero bits, so the result
1818   // is a power of two only if the first operand is a power of two and not
1819   // copying a sign bit (sdiv int_min, 2).
1820   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1821       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1822     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1823                                   Depth, Q);
1824   }
1825 
1826   return false;
1827 }
1828 
1829 /// Test whether a GEP's result is known to be non-null.
1830 ///
1831 /// Uses properties inherent in a GEP to try to determine whether it is known
1832 /// to be non-null.
1833 ///
1834 /// Currently this routine does not support vector GEPs.
1835 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
1836                               const Query &Q) {
1837   const Function *F = nullptr;
1838   if (const Instruction *I = dyn_cast<Instruction>(GEP))
1839     F = I->getFunction();
1840 
1841   if (!GEP->isInBounds() ||
1842       NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
1843     return false;
1844 
1845   // FIXME: Support vector-GEPs.
1846   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1847 
1848   // If the base pointer is non-null, we cannot walk to a null address with an
1849   // inbounds GEP in address space zero.
1850   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
1851     return true;
1852 
1853   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1854   // If so, then the GEP cannot produce a null pointer, as doing so would
1855   // inherently violate the inbounds contract within address space zero.
1856   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1857        GTI != GTE; ++GTI) {
1858     // Struct types are easy -- they must always be indexed by a constant.
1859     if (StructType *STy = GTI.getStructTypeOrNull()) {
1860       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1861       unsigned ElementIdx = OpC->getZExtValue();
1862       const StructLayout *SL = Q.DL.getStructLayout(STy);
1863       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1864       if (ElementOffset > 0)
1865         return true;
1866       continue;
1867     }
1868 
1869     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1870     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1871       continue;
1872 
1873     // Fast path the constant operand case both for efficiency and so we don't
1874     // increment Depth when just zipping down an all-constant GEP.
1875     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1876       if (!OpC->isZero())
1877         return true;
1878       continue;
1879     }
1880 
1881     // We post-increment Depth here because while isKnownNonZero increments it
1882     // as well, when we pop back up that increment won't persist. We don't want
1883     // to recurse 10k times just because we have 10k GEP operands. We don't
1884     // bail completely out because we want to handle constant GEPs regardless
1885     // of depth.
1886     if (Depth++ >= MaxDepth)
1887       continue;
1888 
1889     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
1890       return true;
1891   }
1892 
1893   return false;
1894 }
1895 
1896 static bool isKnownNonNullFromDominatingCondition(const Value *V,
1897                                                   const Instruction *CtxI,
1898                                                   const DominatorTree *DT) {
1899   assert(V->getType()->isPointerTy() && "V must be pointer type");
1900   assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1901 
1902   if (!CtxI || !DT)
1903     return false;
1904 
1905   unsigned NumUsesExplored = 0;
1906   for (auto *U : V->users()) {
1907     // Avoid massive lists
1908     if (NumUsesExplored >= DomConditionsMaxUses)
1909       break;
1910     NumUsesExplored++;
1911 
1912     // If the value is used as an argument to a call or invoke, then argument
1913     // attributes may provide an answer about null-ness.
1914     if (auto CS = ImmutableCallSite(U))
1915       if (auto *CalledFunc = CS.getCalledFunction())
1916         for (const Argument &Arg : CalledFunc->args())
1917           if (CS.getArgOperand(Arg.getArgNo()) == V &&
1918               Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1919             return true;
1920 
1921     // Consider only compare instructions uniquely controlling a branch
1922     CmpInst::Predicate Pred;
1923     if (!match(const_cast<User *>(U),
1924                m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1925         (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1926       continue;
1927 
1928     SmallVector<const User *, 4> WorkList;
1929     SmallPtrSet<const User *, 4> Visited;
1930     for (auto *CmpU : U->users()) {
1931       assert(WorkList.empty() && "Should be!");
1932       if (Visited.insert(CmpU).second)
1933         WorkList.push_back(CmpU);
1934 
1935       while (!WorkList.empty()) {
1936         auto *Curr = WorkList.pop_back_val();
1937 
1938         // If a user is an AND, add all its users to the work list. We only
1939         // propagate "pred != null" condition through AND because it is only
1940         // correct to assume that all conditions of AND are met in true branch.
1941         // TODO: Support similar logic of OR and EQ predicate?
1942         if (Pred == ICmpInst::ICMP_NE)
1943           if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1944             if (BO->getOpcode() == Instruction::And) {
1945               for (auto *BOU : BO->users())
1946                 if (Visited.insert(BOU).second)
1947                   WorkList.push_back(BOU);
1948               continue;
1949             }
1950 
1951         if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1952           assert(BI->isConditional() && "uses a comparison!");
1953 
1954           BasicBlock *NonNullSuccessor =
1955               BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1956           BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1957           if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1958             return true;
1959         } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
1960                    DT->dominates(cast<Instruction>(Curr), CtxI)) {
1961           return true;
1962         }
1963       }
1964     }
1965   }
1966 
1967   return false;
1968 }
1969 
1970 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1971 /// ensure that the value it's attached to is never Value?  'RangeType' is
1972 /// is the type of the value described by the range.
1973 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
1974   const unsigned NumRanges = Ranges->getNumOperands() / 2;
1975   assert(NumRanges >= 1);
1976   for (unsigned i = 0; i < NumRanges; ++i) {
1977     ConstantInt *Lower =
1978         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1979     ConstantInt *Upper =
1980         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1981     ConstantRange Range(Lower->getValue(), Upper->getValue());
1982     if (Range.contains(Value))
1983       return false;
1984   }
1985   return true;
1986 }
1987 
1988 /// Return true if the given value is known to be non-zero when defined. For
1989 /// vectors, return true if every element is known to be non-zero when
1990 /// defined. For pointers, if the context instruction and dominator tree are
1991 /// specified, perform context-sensitive analysis and return true if the
1992 /// pointer couldn't possibly be null at the specified instruction.
1993 /// Supports values with integer or pointer type and vectors of integers.
1994 bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
1995   if (auto *C = dyn_cast<Constant>(V)) {
1996     if (C->isNullValue())
1997       return false;
1998     if (isa<ConstantInt>(C))
1999       // Must be non-zero due to null test above.
2000       return true;
2001 
2002     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2003       // See the comment for IntToPtr/PtrToInt instructions below.
2004       if (CE->getOpcode() == Instruction::IntToPtr ||
2005           CE->getOpcode() == Instruction::PtrToInt)
2006         if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType()) <=
2007             Q.DL.getTypeSizeInBits(CE->getType()))
2008           return isKnownNonZero(CE->getOperand(0), Depth, Q);
2009     }
2010 
2011     // For constant vectors, check that all elements are undefined or known
2012     // non-zero to determine that the whole vector is known non-zero.
2013     if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
2014       for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2015         Constant *Elt = C->getAggregateElement(i);
2016         if (!Elt || Elt->isNullValue())
2017           return false;
2018         if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2019           return false;
2020       }
2021       return true;
2022     }
2023 
2024     // A global variable in address space 0 is non null unless extern weak
2025     // or an absolute symbol reference. Other address spaces may have null as a
2026     // valid address for a global, so we can't assume anything.
2027     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2028       if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2029           GV->getType()->getAddressSpace() == 0)
2030         return true;
2031     } else
2032       return false;
2033   }
2034 
2035   if (auto *I = dyn_cast<Instruction>(V)) {
2036     if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
2037       // If the possible ranges don't contain zero, then the value is
2038       // definitely non-zero.
2039       if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
2040         const APInt ZeroValue(Ty->getBitWidth(), 0);
2041         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2042           return true;
2043       }
2044     }
2045   }
2046 
2047   // Some of the tests below are recursive, so bail out if we hit the limit.
2048   if (Depth++ >= MaxDepth)
2049     return false;
2050 
2051   // Check for pointer simplifications.
2052   if (V->getType()->isPointerTy()) {
2053     // Alloca never returns null, malloc might.
2054     if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2055       return true;
2056 
2057     // A byval, inalloca, or nonnull argument is never null.
2058     if (const Argument *A = dyn_cast<Argument>(V))
2059       if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
2060         return true;
2061 
2062     // A Load tagged with nonnull metadata is never null.
2063     if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2064       if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
2065         return true;
2066 
2067     if (const auto *Call = dyn_cast<CallBase>(V)) {
2068       if (Call->isReturnNonNull())
2069         return true;
2070       if (const auto *RP = getArgumentAliasingToReturnedPointer(Call))
2071         return isKnownNonZero(RP, Depth, Q);
2072     }
2073   }
2074 
2075 
2076   // Check for recursive pointer simplifications.
2077   if (V->getType()->isPointerTy()) {
2078     if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2079       return true;
2080 
2081     // Look through bitcast operations, GEPs, and int2ptr instructions as they
2082     // do not alter the value, or at least not the nullness property of the
2083     // value, e.g., int2ptr is allowed to zero/sign extend the value.
2084     //
2085     // Note that we have to take special care to avoid looking through
2086     // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2087     // as casts that can alter the value, e.g., AddrSpaceCasts.
2088     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
2089       if (isGEPKnownNonNull(GEP, Depth, Q))
2090         return true;
2091 
2092     if (auto *BCO = dyn_cast<BitCastOperator>(V))
2093       return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2094 
2095     if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2096       if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()) <=
2097           Q.DL.getTypeSizeInBits(I2P->getDestTy()))
2098         return isKnownNonZero(I2P->getOperand(0), Depth, Q);
2099   }
2100 
2101   // Similar to int2ptr above, we can look through ptr2int here if the cast
2102   // is a no-op or an extend and not a truncate.
2103   if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2104     if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()) <=
2105         Q.DL.getTypeSizeInBits(P2I->getDestTy()))
2106       return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2107 
2108   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
2109 
2110   // X | Y != 0 if X != 0 or Y != 0.
2111   Value *X = nullptr, *Y = nullptr;
2112   if (match(V, m_Or(m_Value(X), m_Value(Y))))
2113     return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
2114 
2115   // ext X != 0 if X != 0.
2116   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
2117     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
2118 
2119   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
2120   // if the lowest bit is shifted off the end.
2121   if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
2122     // shl nuw can't remove any non-zero bits.
2123     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2124     if (Q.IIQ.hasNoUnsignedWrap(BO))
2125       return isKnownNonZero(X, Depth, Q);
2126 
2127     KnownBits Known(BitWidth);
2128     computeKnownBits(X, Known, Depth, Q);
2129     if (Known.One[0])
2130       return true;
2131   }
2132   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
2133   // defined if the sign bit is shifted off the end.
2134   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
2135     // shr exact can only shift out zero bits.
2136     const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
2137     if (BO->isExact())
2138       return isKnownNonZero(X, Depth, Q);
2139 
2140     KnownBits Known = computeKnownBits(X, Depth, Q);
2141     if (Known.isNegative())
2142       return true;
2143 
2144     // If the shifter operand is a constant, and all of the bits shifted
2145     // out are known to be zero, and X is known non-zero then at least one
2146     // non-zero bit must remain.
2147     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
2148       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2149       // Is there a known one in the portion not shifted out?
2150       if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
2151         return true;
2152       // Are all the bits to be shifted out known zero?
2153       if (Known.countMinTrailingZeros() >= ShiftVal)
2154         return isKnownNonZero(X, Depth, Q);
2155     }
2156   }
2157   // div exact can only produce a zero if the dividend is zero.
2158   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
2159     return isKnownNonZero(X, Depth, Q);
2160   }
2161   // X + Y.
2162   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2163     KnownBits XKnown = computeKnownBits(X, Depth, Q);
2164     KnownBits YKnown = computeKnownBits(Y, Depth, Q);
2165 
2166     // If X and Y are both non-negative (as signed values) then their sum is not
2167     // zero unless both X and Y are zero.
2168     if (XKnown.isNonNegative() && YKnown.isNonNegative())
2169       if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
2170         return true;
2171 
2172     // If X and Y are both negative (as signed values) then their sum is not
2173     // zero unless both X and Y equal INT_MIN.
2174     if (XKnown.isNegative() && YKnown.isNegative()) {
2175       APInt Mask = APInt::getSignedMaxValue(BitWidth);
2176       // The sign bit of X is set.  If some other bit is set then X is not equal
2177       // to INT_MIN.
2178       if (XKnown.One.intersects(Mask))
2179         return true;
2180       // The sign bit of Y is set.  If some other bit is set then Y is not equal
2181       // to INT_MIN.
2182       if (YKnown.One.intersects(Mask))
2183         return true;
2184     }
2185 
2186     // The sum of a non-negative number and a power of two is not zero.
2187     if (XKnown.isNonNegative() &&
2188         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2189       return true;
2190     if (YKnown.isNonNegative() &&
2191         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2192       return true;
2193   }
2194   // X * Y.
2195   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2196     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2197     // If X and Y are non-zero then so is X * Y as long as the multiplication
2198     // does not overflow.
2199     if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2200         isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
2201       return true;
2202   }
2203   // (C ? X : Y) != 0 if X != 0 and Y != 0.
2204   else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
2205     if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2206         isKnownNonZero(SI->getFalseValue(), Depth, Q))
2207       return true;
2208   }
2209   // PHI
2210   else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2211     // Try and detect a recurrence that monotonically increases from a
2212     // starting value, as these are common as induction variables.
2213     if (PN->getNumIncomingValues() == 2) {
2214       Value *Start = PN->getIncomingValue(0);
2215       Value *Induction = PN->getIncomingValue(1);
2216       if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2217         std::swap(Start, Induction);
2218       if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2219         if (!C->isZero() && !C->isNegative()) {
2220           ConstantInt *X;
2221           if (Q.IIQ.UseInstrInfo &&
2222               (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2223                match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2224               !X->isNegative())
2225             return true;
2226         }
2227       }
2228     }
2229     // Check if all incoming values are non-zero constant.
2230     bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
2231       return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
2232     });
2233     if (AllNonZeroConstants)
2234       return true;
2235   }
2236 
2237   KnownBits Known(BitWidth);
2238   computeKnownBits(V, Known, Depth, Q);
2239   return Known.One != 0;
2240 }
2241 
2242 /// Return true if V2 == V1 + X, where X is known non-zero.
2243 static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2244   const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2245   if (!BO || BO->getOpcode() != Instruction::Add)
2246     return false;
2247   Value *Op = nullptr;
2248   if (V2 == BO->getOperand(0))
2249     Op = BO->getOperand(1);
2250   else if (V2 == BO->getOperand(1))
2251     Op = BO->getOperand(0);
2252   else
2253     return false;
2254   return isKnownNonZero(Op, 0, Q);
2255 }
2256 
2257 /// Return true if it is known that V1 != V2.
2258 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
2259   if (V1 == V2)
2260     return false;
2261   if (V1->getType() != V2->getType())
2262     // We can't look through casts yet.
2263     return false;
2264   if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
2265     return true;
2266 
2267   if (V1->getType()->isIntOrIntVectorTy()) {
2268     // Are any known bits in V1 contradictory to known bits in V2? If V1
2269     // has a known zero where V2 has a known one, they must not be equal.
2270     KnownBits Known1 = computeKnownBits(V1, 0, Q);
2271     KnownBits Known2 = computeKnownBits(V2, 0, Q);
2272 
2273     if (Known1.Zero.intersects(Known2.One) ||
2274         Known2.Zero.intersects(Known1.One))
2275       return true;
2276   }
2277   return false;
2278 }
2279 
2280 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
2281 /// simplify operations downstream. Mask is known to be zero for bits that V
2282 /// cannot have.
2283 ///
2284 /// This function is defined on values with integer type, values with pointer
2285 /// type, and vectors of integers.  In the case
2286 /// where V is a vector, the mask, known zero, and known one values are the
2287 /// same width as the vector element, and the bit is set only if it is true
2288 /// for all of the elements in the vector.
2289 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2290                        const Query &Q) {
2291   KnownBits Known(Mask.getBitWidth());
2292   computeKnownBits(V, Known, Depth, Q);
2293   return Mask.isSubsetOf(Known.Zero);
2294 }
2295 
2296 // Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2297 // Returns the input and lower/upper bounds.
2298 static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2299                                 const APInt *&CLow, const APInt *&CHigh) {
2300   assert(isa<Operator>(Select) &&
2301          cast<Operator>(Select)->getOpcode() == Instruction::Select &&
2302          "Input should be a Select!");
2303 
2304   const Value *LHS, *RHS, *LHS2, *RHS2;
2305   SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2306   if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2307     return false;
2308 
2309   if (!match(RHS, m_APInt(CLow)))
2310     return false;
2311 
2312   SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2313   if (getInverseMinMaxFlavor(SPF) != SPF2)
2314     return false;
2315 
2316   if (!match(RHS2, m_APInt(CHigh)))
2317     return false;
2318 
2319   if (SPF == SPF_SMIN)
2320     std::swap(CLow, CHigh);
2321 
2322   In = LHS2;
2323   return CLow->sle(*CHigh);
2324 }
2325 
2326 /// For vector constants, loop over the elements and find the constant with the
2327 /// minimum number of sign bits. Return 0 if the value is not a vector constant
2328 /// or if any element was not analyzed; otherwise, return the count for the
2329 /// element with the minimum number of sign bits.
2330 static unsigned computeNumSignBitsVectorConstant(const Value *V,
2331                                                  unsigned TyBits) {
2332   const auto *CV = dyn_cast<Constant>(V);
2333   if (!CV || !CV->getType()->isVectorTy())
2334     return 0;
2335 
2336   unsigned MinSignBits = TyBits;
2337   unsigned NumElts = CV->getType()->getVectorNumElements();
2338   for (unsigned i = 0; i != NumElts; ++i) {
2339     // If we find a non-ConstantInt, bail out.
2340     auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2341     if (!Elt)
2342       return 0;
2343 
2344     MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
2345   }
2346 
2347   return MinSignBits;
2348 }
2349 
2350 static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2351                                        const Query &Q);
2352 
2353 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2354                                    const Query &Q) {
2355   unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2356   assert(Result > 0 && "At least one sign bit needs to be present!");
2357   return Result;
2358 }
2359 
2360 /// Return the number of times the sign bit of the register is replicated into
2361 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2362 /// (itself), but other cases can give us information. For example, immediately
2363 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2364 /// other, so we return 3. For vectors, return the number of sign bits for the
2365 /// vector element with the minimum number of known sign bits.
2366 static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2367                                        const Query &Q) {
2368   assert(Depth <= MaxDepth && "Limit Search Depth");
2369 
2370   // We return the minimum number of sign bits that are guaranteed to be present
2371   // in V, so for undef we have to conservatively return 1.  We don't have the
2372   // same behavior for poison though -- that's a FIXME today.
2373 
2374   Type *ScalarTy = V->getType()->getScalarType();
2375   unsigned TyBits = ScalarTy->isPointerTy() ?
2376     Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2377     Q.DL.getTypeSizeInBits(ScalarTy);
2378 
2379   unsigned Tmp, Tmp2;
2380   unsigned FirstAnswer = 1;
2381 
2382   // Note that ConstantInt is handled by the general computeKnownBits case
2383   // below.
2384 
2385   if (Depth == MaxDepth)
2386     return 1;  // Limit search depth.
2387 
2388   const Operator *U = dyn_cast<Operator>(V);
2389   switch (Operator::getOpcode(V)) {
2390   default: break;
2391   case Instruction::SExt:
2392     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2393     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2394 
2395   case Instruction::SDiv: {
2396     const APInt *Denominator;
2397     // sdiv X, C -> adds log(C) sign bits.
2398     if (match(U->getOperand(1), m_APInt(Denominator))) {
2399 
2400       // Ignore non-positive denominator.
2401       if (!Denominator->isStrictlyPositive())
2402         break;
2403 
2404       // Calculate the incoming numerator bits.
2405       unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2406 
2407       // Add floor(log(C)) bits to the numerator bits.
2408       return std::min(TyBits, NumBits + Denominator->logBase2());
2409     }
2410     break;
2411   }
2412 
2413   case Instruction::SRem: {
2414     const APInt *Denominator;
2415     // srem X, C -> we know that the result is within [-C+1,C) when C is a
2416     // positive constant.  This let us put a lower bound on the number of sign
2417     // bits.
2418     if (match(U->getOperand(1), m_APInt(Denominator))) {
2419 
2420       // Ignore non-positive denominator.
2421       if (!Denominator->isStrictlyPositive())
2422         break;
2423 
2424       // Calculate the incoming numerator bits. SRem by a positive constant
2425       // can't lower the number of sign bits.
2426       unsigned NumrBits =
2427           ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2428 
2429       // Calculate the leading sign bit constraints by examining the
2430       // denominator.  Given that the denominator is positive, there are two
2431       // cases:
2432       //
2433       //  1. the numerator is positive.  The result range is [0,C) and [0,C) u<
2434       //     (1 << ceilLogBase2(C)).
2435       //
2436       //  2. the numerator is negative.  Then the result range is (-C,0] and
2437       //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2438       //
2439       // Thus a lower bound on the number of sign bits is `TyBits -
2440       // ceilLogBase2(C)`.
2441 
2442       unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2443       return std::max(NumrBits, ResBits);
2444     }
2445     break;
2446   }
2447 
2448   case Instruction::AShr: {
2449     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2450     // ashr X, C   -> adds C sign bits.  Vectors too.
2451     const APInt *ShAmt;
2452     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2453       if (ShAmt->uge(TyBits))
2454         break;  // Bad shift.
2455       unsigned ShAmtLimited = ShAmt->getZExtValue();
2456       Tmp += ShAmtLimited;
2457       if (Tmp > TyBits) Tmp = TyBits;
2458     }
2459     return Tmp;
2460   }
2461   case Instruction::Shl: {
2462     const APInt *ShAmt;
2463     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2464       // shl destroys sign bits.
2465       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2466       if (ShAmt->uge(TyBits) ||      // Bad shift.
2467           ShAmt->uge(Tmp)) break;    // Shifted all sign bits out.
2468       Tmp2 = ShAmt->getZExtValue();
2469       return Tmp - Tmp2;
2470     }
2471     break;
2472   }
2473   case Instruction::And:
2474   case Instruction::Or:
2475   case Instruction::Xor:    // NOT is handled here.
2476     // Logical binary ops preserve the number of sign bits at the worst.
2477     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2478     if (Tmp != 1) {
2479       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2480       FirstAnswer = std::min(Tmp, Tmp2);
2481       // We computed what we know about the sign bits as our first
2482       // answer. Now proceed to the generic code that uses
2483       // computeKnownBits, and pick whichever answer is better.
2484     }
2485     break;
2486 
2487   case Instruction::Select: {
2488     // If we have a clamp pattern, we know that the number of sign bits will be
2489     // the minimum of the clamp min/max range.
2490     const Value *X;
2491     const APInt *CLow, *CHigh;
2492     if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2493       return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2494 
2495     Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2496     if (Tmp == 1) break;
2497     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
2498     return std::min(Tmp, Tmp2);
2499   }
2500 
2501   case Instruction::Add:
2502     // Add can have at most one carry bit.  Thus we know that the output
2503     // is, at worst, one more bit than the inputs.
2504     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2505     if (Tmp == 1) break;
2506 
2507     // Special case decrementing a value (ADD X, -1):
2508     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2509       if (CRHS->isAllOnesValue()) {
2510         KnownBits Known(TyBits);
2511         computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
2512 
2513         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2514         // sign bits set.
2515         if ((Known.Zero | 1).isAllOnesValue())
2516           return TyBits;
2517 
2518         // If we are subtracting one from a positive number, there is no carry
2519         // out of the result.
2520         if (Known.isNonNegative())
2521           return Tmp;
2522       }
2523 
2524     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2525     if (Tmp2 == 1) break;
2526     return std::min(Tmp, Tmp2)-1;
2527 
2528   case Instruction::Sub:
2529     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2530     if (Tmp2 == 1) break;
2531 
2532     // Handle NEG.
2533     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2534       if (CLHS->isNullValue()) {
2535         KnownBits Known(TyBits);
2536         computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
2537         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2538         // sign bits set.
2539         if ((Known.Zero | 1).isAllOnesValue())
2540           return TyBits;
2541 
2542         // If the input is known to be positive (the sign bit is known clear),
2543         // the output of the NEG has the same number of sign bits as the input.
2544         if (Known.isNonNegative())
2545           return Tmp2;
2546 
2547         // Otherwise, we treat this like a SUB.
2548       }
2549 
2550     // Sub can have at most one carry bit.  Thus we know that the output
2551     // is, at worst, one more bit than the inputs.
2552     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2553     if (Tmp == 1) break;
2554     return std::min(Tmp, Tmp2)-1;
2555 
2556   case Instruction::Mul: {
2557     // The output of the Mul can be at most twice the valid bits in the inputs.
2558     unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2559     if (SignBitsOp0 == 1) break;
2560     unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2561     if (SignBitsOp1 == 1) break;
2562     unsigned OutValidBits =
2563         (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2564     return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2565   }
2566 
2567   case Instruction::PHI: {
2568     const PHINode *PN = cast<PHINode>(U);
2569     unsigned NumIncomingValues = PN->getNumIncomingValues();
2570     // Don't analyze large in-degree PHIs.
2571     if (NumIncomingValues > 4) break;
2572     // Unreachable blocks may have zero-operand PHI nodes.
2573     if (NumIncomingValues == 0) break;
2574 
2575     // Take the minimum of all incoming values.  This can't infinitely loop
2576     // because of our depth threshold.
2577     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
2578     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2579       if (Tmp == 1) return Tmp;
2580       Tmp = std::min(
2581           Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
2582     }
2583     return Tmp;
2584   }
2585 
2586   case Instruction::Trunc:
2587     // FIXME: it's tricky to do anything useful for this, but it is an important
2588     // case for targets like X86.
2589     break;
2590 
2591   case Instruction::ExtractElement:
2592     // Look through extract element. At the moment we keep this simple and skip
2593     // tracking the specific element. But at least we might find information
2594     // valid for all elements of the vector (for example if vector is sign
2595     // extended, shifted, etc).
2596     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2597 
2598   case Instruction::ShuffleVector: {
2599     // TODO: This is copied almost directly from the SelectionDAG version of
2600     //       ComputeNumSignBits. It would be better if we could share common
2601     //       code. If not, make sure that changes are translated to the DAG.
2602 
2603     // Collect the minimum number of sign bits that are shared by every vector
2604     // element referenced by the shuffle.
2605     auto *Shuf = cast<ShuffleVectorInst>(U);
2606     int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2607     int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2608     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2609     for (int i = 0; i != NumMaskElts; ++i) {
2610       int M = Shuf->getMaskValue(i);
2611       assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2612       // For undef elements, we don't know anything about the common state of
2613       // the shuffle result.
2614       if (M == -1)
2615         return 1;
2616       if (M < NumElts)
2617         DemandedLHS.setBit(M % NumElts);
2618       else
2619         DemandedRHS.setBit(M % NumElts);
2620     }
2621     Tmp = std::numeric_limits<unsigned>::max();
2622     if (!!DemandedLHS)
2623       Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2624     if (!!DemandedRHS) {
2625       Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2626       Tmp = std::min(Tmp, Tmp2);
2627     }
2628     // If we don't know anything, early out and try computeKnownBits fall-back.
2629     if (Tmp == 1)
2630       break;
2631     assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2632            "Failed to determine minimum sign bits");
2633     return Tmp;
2634   }
2635   }
2636 
2637   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2638   // use this information.
2639 
2640   // If we can examine all elements of a vector constant successfully, we're
2641   // done (we can't do any better than that). If not, keep trying.
2642   if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2643     return VecSignBits;
2644 
2645   KnownBits Known(TyBits);
2646   computeKnownBits(V, Known, Depth, Q);
2647 
2648   // If we know that the sign bit is either zero or one, determine the number of
2649   // identical bits in the top of the input value.
2650   return std::max(FirstAnswer, Known.countMinSignBits());
2651 }
2652 
2653 /// This function computes the integer multiple of Base that equals V.
2654 /// If successful, it returns true and returns the multiple in
2655 /// Multiple. If unsuccessful, it returns false. It looks
2656 /// through SExt instructions only if LookThroughSExt is true.
2657 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2658                            bool LookThroughSExt, unsigned Depth) {
2659   const unsigned MaxDepth = 6;
2660 
2661   assert(V && "No Value?");
2662   assert(Depth <= MaxDepth && "Limit Search Depth");
2663   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2664 
2665   Type *T = V->getType();
2666 
2667   ConstantInt *CI = dyn_cast<ConstantInt>(V);
2668 
2669   if (Base == 0)
2670     return false;
2671 
2672   if (Base == 1) {
2673     Multiple = V;
2674     return true;
2675   }
2676 
2677   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2678   Constant *BaseVal = ConstantInt::get(T, Base);
2679   if (CO && CO == BaseVal) {
2680     // Multiple is 1.
2681     Multiple = ConstantInt::get(T, 1);
2682     return true;
2683   }
2684 
2685   if (CI && CI->getZExtValue() % Base == 0) {
2686     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2687     return true;
2688   }
2689 
2690   if (Depth == MaxDepth) return false;  // Limit search depth.
2691 
2692   Operator *I = dyn_cast<Operator>(V);
2693   if (!I) return false;
2694 
2695   switch (I->getOpcode()) {
2696   default: break;
2697   case Instruction::SExt:
2698     if (!LookThroughSExt) return false;
2699     // otherwise fall through to ZExt
2700     LLVM_FALLTHROUGH;
2701   case Instruction::ZExt:
2702     return ComputeMultiple(I->getOperand(0), Base, Multiple,
2703                            LookThroughSExt, Depth+1);
2704   case Instruction::Shl:
2705   case Instruction::Mul: {
2706     Value *Op0 = I->getOperand(0);
2707     Value *Op1 = I->getOperand(1);
2708 
2709     if (I->getOpcode() == Instruction::Shl) {
2710       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2711       if (!Op1CI) return false;
2712       // Turn Op0 << Op1 into Op0 * 2^Op1
2713       APInt Op1Int = Op1CI->getValue();
2714       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2715       APInt API(Op1Int.getBitWidth(), 0);
2716       API.setBit(BitToSet);
2717       Op1 = ConstantInt::get(V->getContext(), API);
2718     }
2719 
2720     Value *Mul0 = nullptr;
2721     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2722       if (Constant *Op1C = dyn_cast<Constant>(Op1))
2723         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2724           if (Op1C->getType()->getPrimitiveSizeInBits() <
2725               MulC->getType()->getPrimitiveSizeInBits())
2726             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2727           if (Op1C->getType()->getPrimitiveSizeInBits() >
2728               MulC->getType()->getPrimitiveSizeInBits())
2729             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2730 
2731           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2732           Multiple = ConstantExpr::getMul(MulC, Op1C);
2733           return true;
2734         }
2735 
2736       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2737         if (Mul0CI->getValue() == 1) {
2738           // V == Base * Op1, so return Op1
2739           Multiple = Op1;
2740           return true;
2741         }
2742     }
2743 
2744     Value *Mul1 = nullptr;
2745     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2746       if (Constant *Op0C = dyn_cast<Constant>(Op0))
2747         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2748           if (Op0C->getType()->getPrimitiveSizeInBits() <
2749               MulC->getType()->getPrimitiveSizeInBits())
2750             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2751           if (Op0C->getType()->getPrimitiveSizeInBits() >
2752               MulC->getType()->getPrimitiveSizeInBits())
2753             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2754 
2755           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2756           Multiple = ConstantExpr::getMul(MulC, Op0C);
2757           return true;
2758         }
2759 
2760       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2761         if (Mul1CI->getValue() == 1) {
2762           // V == Base * Op0, so return Op0
2763           Multiple = Op0;
2764           return true;
2765         }
2766     }
2767   }
2768   }
2769 
2770   // We could not determine if V is a multiple of Base.
2771   return false;
2772 }
2773 
2774 Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2775                                             const TargetLibraryInfo *TLI) {
2776   const Function *F = ICS.getCalledFunction();
2777   if (!F)
2778     return Intrinsic::not_intrinsic;
2779 
2780   if (F->isIntrinsic())
2781     return F->getIntrinsicID();
2782 
2783   if (!TLI)
2784     return Intrinsic::not_intrinsic;
2785 
2786   LibFunc Func;
2787   // We're going to make assumptions on the semantics of the functions, check
2788   // that the target knows that it's available in this environment and it does
2789   // not have local linkage.
2790   if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2791     return Intrinsic::not_intrinsic;
2792 
2793   if (!ICS.onlyReadsMemory())
2794     return Intrinsic::not_intrinsic;
2795 
2796   // Otherwise check if we have a call to a function that can be turned into a
2797   // vector intrinsic.
2798   switch (Func) {
2799   default:
2800     break;
2801   case LibFunc_sin:
2802   case LibFunc_sinf:
2803   case LibFunc_sinl:
2804     return Intrinsic::sin;
2805   case LibFunc_cos:
2806   case LibFunc_cosf:
2807   case LibFunc_cosl:
2808     return Intrinsic::cos;
2809   case LibFunc_exp:
2810   case LibFunc_expf:
2811   case LibFunc_expl:
2812     return Intrinsic::exp;
2813   case LibFunc_exp2:
2814   case LibFunc_exp2f:
2815   case LibFunc_exp2l:
2816     return Intrinsic::exp2;
2817   case LibFunc_log:
2818   case LibFunc_logf:
2819   case LibFunc_logl:
2820     return Intrinsic::log;
2821   case LibFunc_log10:
2822   case LibFunc_log10f:
2823   case LibFunc_log10l:
2824     return Intrinsic::log10;
2825   case LibFunc_log2:
2826   case LibFunc_log2f:
2827   case LibFunc_log2l:
2828     return Intrinsic::log2;
2829   case LibFunc_fabs:
2830   case LibFunc_fabsf:
2831   case LibFunc_fabsl:
2832     return Intrinsic::fabs;
2833   case LibFunc_fmin:
2834   case LibFunc_fminf:
2835   case LibFunc_fminl:
2836     return Intrinsic::minnum;
2837   case LibFunc_fmax:
2838   case LibFunc_fmaxf:
2839   case LibFunc_fmaxl:
2840     return Intrinsic::maxnum;
2841   case LibFunc_copysign:
2842   case LibFunc_copysignf:
2843   case LibFunc_copysignl:
2844     return Intrinsic::copysign;
2845   case LibFunc_floor:
2846   case LibFunc_floorf:
2847   case LibFunc_floorl:
2848     return Intrinsic::floor;
2849   case LibFunc_ceil:
2850   case LibFunc_ceilf:
2851   case LibFunc_ceill:
2852     return Intrinsic::ceil;
2853   case LibFunc_trunc:
2854   case LibFunc_truncf:
2855   case LibFunc_truncl:
2856     return Intrinsic::trunc;
2857   case LibFunc_rint:
2858   case LibFunc_rintf:
2859   case LibFunc_rintl:
2860     return Intrinsic::rint;
2861   case LibFunc_nearbyint:
2862   case LibFunc_nearbyintf:
2863   case LibFunc_nearbyintl:
2864     return Intrinsic::nearbyint;
2865   case LibFunc_round:
2866   case LibFunc_roundf:
2867   case LibFunc_roundl:
2868     return Intrinsic::round;
2869   case LibFunc_pow:
2870   case LibFunc_powf:
2871   case LibFunc_powl:
2872     return Intrinsic::pow;
2873   case LibFunc_sqrt:
2874   case LibFunc_sqrtf:
2875   case LibFunc_sqrtl:
2876     return Intrinsic::sqrt;
2877   }
2878 
2879   return Intrinsic::not_intrinsic;
2880 }
2881 
2882 /// Return true if we can prove that the specified FP value is never equal to
2883 /// -0.0.
2884 ///
2885 /// NOTE: this function will need to be revisited when we support non-default
2886 /// rounding modes!
2887 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2888                                 unsigned Depth) {
2889   if (auto *CFP = dyn_cast<ConstantFP>(V))
2890     return !CFP->getValueAPF().isNegZero();
2891 
2892   // Limit search depth.
2893   if (Depth == MaxDepth)
2894     return false;
2895 
2896   auto *Op = dyn_cast<Operator>(V);
2897   if (!Op)
2898     return false;
2899 
2900   // Check if the nsz fast-math flag is set.
2901   if (auto *FPO = dyn_cast<FPMathOperator>(Op))
2902     if (FPO->hasNoSignedZeros())
2903       return true;
2904 
2905   // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
2906   if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
2907     return true;
2908 
2909   // sitofp and uitofp turn into +0.0 for zero.
2910   if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
2911     return true;
2912 
2913   if (auto *Call = dyn_cast<CallInst>(Op)) {
2914     Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
2915     switch (IID) {
2916     default:
2917       break;
2918     // sqrt(-0.0) = -0.0, no other negative results are possible.
2919     case Intrinsic::sqrt:
2920     case Intrinsic::canonicalize:
2921       return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
2922     // fabs(x) != -0.0
2923     case Intrinsic::fabs:
2924       return true;
2925     }
2926   }
2927 
2928   return false;
2929 }
2930 
2931 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2932 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2933 /// bit despite comparing equal.
2934 static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2935                                             const TargetLibraryInfo *TLI,
2936                                             bool SignBitOnly,
2937                                             unsigned Depth) {
2938   // TODO: This function does not do the right thing when SignBitOnly is true
2939   // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2940   // which flips the sign bits of NaNs.  See
2941   // https://llvm.org/bugs/show_bug.cgi?id=31702.
2942 
2943   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2944     return !CFP->getValueAPF().isNegative() ||
2945            (!SignBitOnly && CFP->getValueAPF().isZero());
2946   }
2947 
2948   // Handle vector of constants.
2949   if (auto *CV = dyn_cast<Constant>(V)) {
2950     if (CV->getType()->isVectorTy()) {
2951       unsigned NumElts = CV->getType()->getVectorNumElements();
2952       for (unsigned i = 0; i != NumElts; ++i) {
2953         auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2954         if (!CFP)
2955           return false;
2956         if (CFP->getValueAPF().isNegative() &&
2957             (SignBitOnly || !CFP->getValueAPF().isZero()))
2958           return false;
2959       }
2960 
2961       // All non-negative ConstantFPs.
2962       return true;
2963     }
2964   }
2965 
2966   if (Depth == MaxDepth)
2967     return false; // Limit search depth.
2968 
2969   const Operator *I = dyn_cast<Operator>(V);
2970   if (!I)
2971     return false;
2972 
2973   switch (I->getOpcode()) {
2974   default:
2975     break;
2976   // Unsigned integers are always nonnegative.
2977   case Instruction::UIToFP:
2978     return true;
2979   case Instruction::FMul:
2980     // x*x is always non-negative or a NaN.
2981     if (I->getOperand(0) == I->getOperand(1) &&
2982         (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
2983       return true;
2984 
2985     LLVM_FALLTHROUGH;
2986   case Instruction::FAdd:
2987   case Instruction::FDiv:
2988   case Instruction::FRem:
2989     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2990                                            Depth + 1) &&
2991            cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2992                                            Depth + 1);
2993   case Instruction::Select:
2994     return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2995                                            Depth + 1) &&
2996            cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2997                                            Depth + 1);
2998   case Instruction::FPExt:
2999   case Instruction::FPTrunc:
3000     // Widening/narrowing never change sign.
3001     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3002                                            Depth + 1);
3003   case Instruction::ExtractElement:
3004     // Look through extract element. At the moment we keep this simple and skip
3005     // tracking the specific element. But at least we might find information
3006     // valid for all elements of the vector.
3007     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3008                                            Depth + 1);
3009   case Instruction::Call:
3010     const auto *CI = cast<CallInst>(I);
3011     Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
3012     switch (IID) {
3013     default:
3014       break;
3015     case Intrinsic::maxnum:
3016       return (isKnownNeverNaN(I->getOperand(0), TLI) &&
3017               cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
3018                                               SignBitOnly, Depth + 1)) ||
3019             (isKnownNeverNaN(I->getOperand(1), TLI) &&
3020               cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3021                                               SignBitOnly, Depth + 1));
3022 
3023     case Intrinsic::maximum:
3024       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3025                                              Depth + 1) ||
3026              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3027                                              Depth + 1);
3028     case Intrinsic::minnum:
3029     case Intrinsic::minimum:
3030       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3031                                              Depth + 1) &&
3032              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3033                                              Depth + 1);
3034     case Intrinsic::exp:
3035     case Intrinsic::exp2:
3036     case Intrinsic::fabs:
3037       return true;
3038 
3039     case Intrinsic::sqrt:
3040       // sqrt(x) is always >= -0 or NaN.  Moreover, sqrt(x) == -0 iff x == -0.
3041       if (!SignBitOnly)
3042         return true;
3043       return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3044                                  CannotBeNegativeZero(CI->getOperand(0), TLI));
3045 
3046     case Intrinsic::powi:
3047       if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
3048         // powi(x,n) is non-negative if n is even.
3049         if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
3050           return true;
3051       }
3052       // TODO: This is not correct.  Given that exp is an integer, here are the
3053       // ways that pow can return a negative value:
3054       //
3055       //   pow(x, exp)    --> negative if exp is odd and x is negative.
3056       //   pow(-0, exp)   --> -inf if exp is negative odd.
3057       //   pow(-0, exp)   --> -0 if exp is positive odd.
3058       //   pow(-inf, exp) --> -0 if exp is negative odd.
3059       //   pow(-inf, exp) --> -inf if exp is positive odd.
3060       //
3061       // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3062       // but we must return false if x == -0.  Unfortunately we do not currently
3063       // have a way of expressing this constraint.  See details in
3064       // https://llvm.org/bugs/show_bug.cgi?id=31702.
3065       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3066                                              Depth + 1);
3067 
3068     case Intrinsic::fma:
3069     case Intrinsic::fmuladd:
3070       // x*x+y is non-negative if y is non-negative.
3071       return I->getOperand(0) == I->getOperand(1) &&
3072              (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3073              cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3074                                              Depth + 1);
3075     }
3076     break;
3077   }
3078   return false;
3079 }
3080 
3081 bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3082                                        const TargetLibraryInfo *TLI) {
3083   return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3084 }
3085 
3086 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3087   return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3088 }
3089 
3090 bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3091                            unsigned Depth) {
3092   assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3093 
3094   // If we're told that NaNs won't happen, assume they won't.
3095   if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3096     if (FPMathOp->hasNoNaNs())
3097       return true;
3098 
3099   // Handle scalar constants.
3100   if (auto *CFP = dyn_cast<ConstantFP>(V))
3101     return !CFP->isNaN();
3102 
3103   if (Depth == MaxDepth)
3104     return false;
3105 
3106   if (auto *Inst = dyn_cast<Instruction>(V)) {
3107     switch (Inst->getOpcode()) {
3108     case Instruction::FAdd:
3109     case Instruction::FMul:
3110     case Instruction::FSub:
3111     case Instruction::FDiv:
3112     case Instruction::FRem: {
3113       // TODO: Need isKnownNeverInfinity
3114       return false;
3115     }
3116     case Instruction::Select: {
3117       return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3118              isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3119     }
3120     case Instruction::SIToFP:
3121     case Instruction::UIToFP:
3122       return true;
3123     case Instruction::FPTrunc:
3124     case Instruction::FPExt:
3125       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3126     default:
3127       break;
3128     }
3129   }
3130 
3131   if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3132     switch (II->getIntrinsicID()) {
3133     case Intrinsic::canonicalize:
3134     case Intrinsic::fabs:
3135     case Intrinsic::copysign:
3136     case Intrinsic::exp:
3137     case Intrinsic::exp2:
3138     case Intrinsic::floor:
3139     case Intrinsic::ceil:
3140     case Intrinsic::trunc:
3141     case Intrinsic::rint:
3142     case Intrinsic::nearbyint:
3143     case Intrinsic::round:
3144       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3145     case Intrinsic::sqrt:
3146       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3147              CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3148     case Intrinsic::minnum:
3149     case Intrinsic::maxnum:
3150       // If either operand is not NaN, the result is not NaN.
3151       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3152              isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
3153     default:
3154       return false;
3155     }
3156   }
3157 
3158   // Bail out for constant expressions, but try to handle vector constants.
3159   if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3160     return false;
3161 
3162   // For vectors, verify that each element is not NaN.
3163   unsigned NumElts = V->getType()->getVectorNumElements();
3164   for (unsigned i = 0; i != NumElts; ++i) {
3165     Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3166     if (!Elt)
3167       return false;
3168     if (isa<UndefValue>(Elt))
3169       continue;
3170     auto *CElt = dyn_cast<ConstantFP>(Elt);
3171     if (!CElt || CElt->isNaN())
3172       return false;
3173   }
3174   // All elements were confirmed not-NaN or undefined.
3175   return true;
3176 }
3177 
3178 Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
3179 
3180   // All byte-wide stores are splatable, even of arbitrary variables.
3181   if (V->getType()->isIntegerTy(8))
3182     return V;
3183 
3184   LLVMContext &Ctx = V->getContext();
3185 
3186   // Undef don't care.
3187   auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3188   if (isa<UndefValue>(V))
3189     return UndefInt8;
3190 
3191   const uint64_t Size = DL.getTypeStoreSize(V->getType());
3192   if (!Size)
3193     return UndefInt8;
3194 
3195   Constant *C = dyn_cast<Constant>(V);
3196   if (!C) {
3197     // Conceptually, we could handle things like:
3198     //   %a = zext i8 %X to i16
3199     //   %b = shl i16 %a, 8
3200     //   %c = or i16 %a, %b
3201     // but until there is an example that actually needs this, it doesn't seem
3202     // worth worrying about.
3203     return nullptr;
3204   }
3205 
3206   // Handle 'null' ConstantArrayZero etc.
3207   if (C->isNullValue())
3208     return Constant::getNullValue(Type::getInt8Ty(Ctx));
3209 
3210   // Constant floating-point values can be handled as integer values if the
3211   // corresponding integer value is "byteable".  An important case is 0.0.
3212   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3213     Type *Ty = nullptr;
3214     if (CFP->getType()->isHalfTy())
3215       Ty = Type::getInt16Ty(Ctx);
3216     else if (CFP->getType()->isFloatTy())
3217       Ty = Type::getInt32Ty(Ctx);
3218     else if (CFP->getType()->isDoubleTy())
3219       Ty = Type::getInt64Ty(Ctx);
3220     // Don't handle long double formats, which have strange constraints.
3221     return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3222               : nullptr;
3223   }
3224 
3225   // We can handle constant integers that are multiple of 8 bits.
3226   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
3227     if (CI->getBitWidth() % 8 == 0) {
3228       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
3229       if (!CI->getValue().isSplat(8))
3230         return nullptr;
3231       return ConstantInt::get(Ctx, CI->getValue().trunc(8));
3232     }
3233   }
3234 
3235   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3236     if (CE->getOpcode() == Instruction::IntToPtr) {
3237       auto PS = DL.getPointerSizeInBits(
3238           cast<PointerType>(CE->getType())->getAddressSpace());
3239       return isBytewiseValue(
3240           ConstantExpr::getIntegerCast(CE->getOperand(0),
3241                                        Type::getIntNTy(Ctx, PS), false),
3242           DL);
3243     }
3244   }
3245 
3246   auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3247     if (LHS == RHS)
3248       return LHS;
3249     if (!LHS || !RHS)
3250       return nullptr;
3251     if (LHS == UndefInt8)
3252       return RHS;
3253     if (RHS == UndefInt8)
3254       return LHS;
3255     return nullptr;
3256   };
3257 
3258   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3259     Value *Val = UndefInt8;
3260     for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3261       if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
3262         return nullptr;
3263     return Val;
3264   }
3265 
3266   if (isa<ConstantAggregate>(C)) {
3267     Value *Val = UndefInt8;
3268     for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3269       if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
3270         return nullptr;
3271     return Val;
3272   }
3273 
3274   // Don't try to handle the handful of other constants.
3275   return nullptr;
3276 }
3277 
3278 // This is the recursive version of BuildSubAggregate. It takes a few different
3279 // arguments. Idxs is the index within the nested struct From that we are
3280 // looking at now (which is of type IndexedType). IdxSkip is the number of
3281 // indices from Idxs that should be left out when inserting into the resulting
3282 // struct. To is the result struct built so far, new insertvalue instructions
3283 // build on that.
3284 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
3285                                 SmallVectorImpl<unsigned> &Idxs,
3286                                 unsigned IdxSkip,
3287                                 Instruction *InsertBefore) {
3288   StructType *STy = dyn_cast<StructType>(IndexedType);
3289   if (STy) {
3290     // Save the original To argument so we can modify it
3291     Value *OrigTo = To;
3292     // General case, the type indexed by Idxs is a struct
3293     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3294       // Process each struct element recursively
3295       Idxs.push_back(i);
3296       Value *PrevTo = To;
3297       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
3298                              InsertBefore);
3299       Idxs.pop_back();
3300       if (!To) {
3301         // Couldn't find any inserted value for this index? Cleanup
3302         while (PrevTo != OrigTo) {
3303           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3304           PrevTo = Del->getAggregateOperand();
3305           Del->eraseFromParent();
3306         }
3307         // Stop processing elements
3308         break;
3309       }
3310     }
3311     // If we successfully found a value for each of our subaggregates
3312     if (To)
3313       return To;
3314   }
3315   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3316   // the struct's elements had a value that was inserted directly. In the latter
3317   // case, perhaps we can't determine each of the subelements individually, but
3318   // we might be able to find the complete struct somewhere.
3319 
3320   // Find the value that is at that particular spot
3321   Value *V = FindInsertedValue(From, Idxs);
3322 
3323   if (!V)
3324     return nullptr;
3325 
3326   // Insert the value in the new (sub) aggregate
3327   return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3328                                  "tmp", InsertBefore);
3329 }
3330 
3331 // This helper takes a nested struct and extracts a part of it (which is again a
3332 // struct) into a new value. For example, given the struct:
3333 // { a, { b, { c, d }, e } }
3334 // and the indices "1, 1" this returns
3335 // { c, d }.
3336 //
3337 // It does this by inserting an insertvalue for each element in the resulting
3338 // struct, as opposed to just inserting a single struct. This will only work if
3339 // each of the elements of the substruct are known (ie, inserted into From by an
3340 // insertvalue instruction somewhere).
3341 //
3342 // All inserted insertvalue instructions are inserted before InsertBefore
3343 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
3344                                 Instruction *InsertBefore) {
3345   assert(InsertBefore && "Must have someplace to insert!");
3346   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
3347                                                              idx_range);
3348   Value *To = UndefValue::get(IndexedType);
3349   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
3350   unsigned IdxSkip = Idxs.size();
3351 
3352   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
3353 }
3354 
3355 /// Given an aggregate and a sequence of indices, see if the scalar value
3356 /// indexed is already around as a register, for example if it was inserted
3357 /// directly into the aggregate.
3358 ///
3359 /// If InsertBefore is not null, this function will duplicate (modified)
3360 /// insertvalues when a part of a nested struct is extracted.
3361 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3362                                Instruction *InsertBefore) {
3363   // Nothing to index? Just return V then (this is useful at the end of our
3364   // recursion).
3365   if (idx_range.empty())
3366     return V;
3367   // We have indices, so V should have an indexable type.
3368   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3369          "Not looking at a struct or array?");
3370   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3371          "Invalid indices for type?");
3372 
3373   if (Constant *C = dyn_cast<Constant>(V)) {
3374     C = C->getAggregateElement(idx_range[0]);
3375     if (!C) return nullptr;
3376     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3377   }
3378 
3379   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
3380     // Loop the indices for the insertvalue instruction in parallel with the
3381     // requested indices
3382     const unsigned *req_idx = idx_range.begin();
3383     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3384          i != e; ++i, ++req_idx) {
3385       if (req_idx == idx_range.end()) {
3386         // We can't handle this without inserting insertvalues
3387         if (!InsertBefore)
3388           return nullptr;
3389 
3390         // The requested index identifies a part of a nested aggregate. Handle
3391         // this specially. For example,
3392         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3393         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3394         // %C = extractvalue {i32, { i32, i32 } } %B, 1
3395         // This can be changed into
3396         // %A = insertvalue {i32, i32 } undef, i32 10, 0
3397         // %C = insertvalue {i32, i32 } %A, i32 11, 1
3398         // which allows the unused 0,0 element from the nested struct to be
3399         // removed.
3400         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3401                                  InsertBefore);
3402       }
3403 
3404       // This insert value inserts something else than what we are looking for.
3405       // See if the (aggregate) value inserted into has the value we are
3406       // looking for, then.
3407       if (*req_idx != *i)
3408         return FindInsertedValue(I->getAggregateOperand(), idx_range,
3409                                  InsertBefore);
3410     }
3411     // If we end up here, the indices of the insertvalue match with those
3412     // requested (though possibly only partially). Now we recursively look at
3413     // the inserted value, passing any remaining indices.
3414     return FindInsertedValue(I->getInsertedValueOperand(),
3415                              makeArrayRef(req_idx, idx_range.end()),
3416                              InsertBefore);
3417   }
3418 
3419   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
3420     // If we're extracting a value from an aggregate that was extracted from
3421     // something else, we can extract from that something else directly instead.
3422     // However, we will need to chain I's indices with the requested indices.
3423 
3424     // Calculate the number of indices required
3425     unsigned size = I->getNumIndices() + idx_range.size();
3426     // Allocate some space to put the new indices in
3427     SmallVector<unsigned, 5> Idxs;
3428     Idxs.reserve(size);
3429     // Add indices from the extract value instruction
3430     Idxs.append(I->idx_begin(), I->idx_end());
3431 
3432     // Add requested indices
3433     Idxs.append(idx_range.begin(), idx_range.end());
3434 
3435     assert(Idxs.size() == size
3436            && "Number of indices added not correct?");
3437 
3438     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
3439   }
3440   // Otherwise, we don't know (such as, extracting from a function return value
3441   // or load instruction)
3442   return nullptr;
3443 }
3444 
3445 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3446                                        unsigned CharSize) {
3447   // Make sure the GEP has exactly three arguments.
3448   if (GEP->getNumOperands() != 3)
3449     return false;
3450 
3451   // Make sure the index-ee is a pointer to array of \p CharSize integers.
3452   // CharSize.
3453   ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
3454   if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
3455     return false;
3456 
3457   // Check to make sure that the first operand of the GEP is an integer and
3458   // has value 0 so that we are sure we're indexing into the initializer.
3459   const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3460   if (!FirstIdx || !FirstIdx->isZero())
3461     return false;
3462 
3463   return true;
3464 }
3465 
3466 bool llvm::getConstantDataArrayInfo(const Value *V,
3467                                     ConstantDataArraySlice &Slice,
3468                                     unsigned ElementSize, uint64_t Offset) {
3469   assert(V);
3470 
3471   // Look through bitcast instructions and geps.
3472   V = V->stripPointerCasts();
3473 
3474   // If the value is a GEP instruction or constant expression, treat it as an
3475   // offset.
3476   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3477     // The GEP operator should be based on a pointer to string constant, and is
3478     // indexing into the string constant.
3479     if (!isGEPBasedOnPointerToString(GEP, ElementSize))
3480       return false;
3481 
3482     // If the second index isn't a ConstantInt, then this is a variable index
3483     // into the array.  If this occurs, we can't say anything meaningful about
3484     // the string.
3485     uint64_t StartIdx = 0;
3486     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
3487       StartIdx = CI->getZExtValue();
3488     else
3489       return false;
3490     return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3491                                     StartIdx + Offset);
3492   }
3493 
3494   // The GEP instruction, constant or instruction, must reference a global
3495   // variable that is a constant and is initialized. The referenced constant
3496   // initializer is the array that we'll use for optimization.
3497   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3498   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
3499     return false;
3500 
3501   const ConstantDataArray *Array;
3502   ArrayType *ArrayTy;
3503   if (GV->getInitializer()->isNullValue()) {
3504     Type *GVTy = GV->getValueType();
3505     if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
3506       // A zeroinitializer for the array; there is no ConstantDataArray.
3507       Array = nullptr;
3508     } else {
3509       const DataLayout &DL = GV->getParent()->getDataLayout();
3510       uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3511       uint64_t Length = SizeInBytes / (ElementSize / 8);
3512       if (Length <= Offset)
3513         return false;
3514 
3515       Slice.Array = nullptr;
3516       Slice.Offset = 0;
3517       Slice.Length = Length - Offset;
3518       return true;
3519     }
3520   } else {
3521     // This must be a ConstantDataArray.
3522     Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3523     if (!Array)
3524       return false;
3525     ArrayTy = Array->getType();
3526   }
3527   if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
3528     return false;
3529 
3530   uint64_t NumElts = ArrayTy->getArrayNumElements();
3531   if (Offset > NumElts)
3532     return false;
3533 
3534   Slice.Array = Array;
3535   Slice.Offset = Offset;
3536   Slice.Length = NumElts - Offset;
3537   return true;
3538 }
3539 
3540 /// This function computes the length of a null-terminated C string pointed to
3541 /// by V. If successful, it returns true and returns the string in Str.
3542 /// If unsuccessful, it returns false.
3543 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3544                                  uint64_t Offset, bool TrimAtNul) {
3545   ConstantDataArraySlice Slice;
3546   if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3547     return false;
3548 
3549   if (Slice.Array == nullptr) {
3550     if (TrimAtNul) {
3551       Str = StringRef();
3552       return true;
3553     }
3554     if (Slice.Length == 1) {
3555       Str = StringRef("", 1);
3556       return true;
3557     }
3558     // We cannot instantiate a StringRef as we do not have an appropriate string
3559     // of 0s at hand.
3560     return false;
3561   }
3562 
3563   // Start out with the entire array in the StringRef.
3564   Str = Slice.Array->getAsString();
3565   // Skip over 'offset' bytes.
3566   Str = Str.substr(Slice.Offset);
3567 
3568   if (TrimAtNul) {
3569     // Trim off the \0 and anything after it.  If the array is not nul
3570     // terminated, we just return the whole end of string.  The client may know
3571     // some other way that the string is length-bound.
3572     Str = Str.substr(0, Str.find('\0'));
3573   }
3574   return true;
3575 }
3576 
3577 // These next two are very similar to the above, but also look through PHI
3578 // nodes.
3579 // TODO: See if we can integrate these two together.
3580 
3581 /// If we can compute the length of the string pointed to by
3582 /// the specified pointer, return 'len+1'.  If we can't, return 0.
3583 static uint64_t GetStringLengthH(const Value *V,
3584                                  SmallPtrSetImpl<const PHINode*> &PHIs,
3585                                  unsigned CharSize) {
3586   // Look through noop bitcast instructions.
3587   V = V->stripPointerCasts();
3588 
3589   // If this is a PHI node, there are two cases: either we have already seen it
3590   // or we haven't.
3591   if (const PHINode *PN = dyn_cast<PHINode>(V)) {
3592     if (!PHIs.insert(PN).second)
3593       return ~0ULL;  // already in the set.
3594 
3595     // If it was new, see if all the input strings are the same length.
3596     uint64_t LenSoFar = ~0ULL;
3597     for (Value *IncValue : PN->incoming_values()) {
3598       uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
3599       if (Len == 0) return 0; // Unknown length -> unknown.
3600 
3601       if (Len == ~0ULL) continue;
3602 
3603       if (Len != LenSoFar && LenSoFar != ~0ULL)
3604         return 0;    // Disagree -> unknown.
3605       LenSoFar = Len;
3606     }
3607 
3608     // Success, all agree.
3609     return LenSoFar;
3610   }
3611 
3612   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
3613   if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
3614     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
3615     if (Len1 == 0) return 0;
3616     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
3617     if (Len2 == 0) return 0;
3618     if (Len1 == ~0ULL) return Len2;
3619     if (Len2 == ~0ULL) return Len1;
3620     if (Len1 != Len2) return 0;
3621     return Len1;
3622   }
3623 
3624   // Otherwise, see if we can read the string.
3625   ConstantDataArraySlice Slice;
3626   if (!getConstantDataArrayInfo(V, Slice, CharSize))
3627     return 0;
3628 
3629   if (Slice.Array == nullptr)
3630     return 1;
3631 
3632   // Search for nul characters
3633   unsigned NullIndex = 0;
3634   for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3635     if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3636       break;
3637   }
3638 
3639   return NullIndex + 1;
3640 }
3641 
3642 /// If we can compute the length of the string pointed to by
3643 /// the specified pointer, return 'len+1'.  If we can't, return 0.
3644 uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
3645   if (!V->getType()->isPointerTy())
3646     return 0;
3647 
3648   SmallPtrSet<const PHINode*, 32> PHIs;
3649   uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
3650   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3651   // an empty string as a length.
3652   return Len == ~0ULL ? 1 : Len;
3653 }
3654 
3655 const Value *llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call) {
3656   assert(Call &&
3657          "getArgumentAliasingToReturnedPointer only works on nonnull calls");
3658   if (const Value *RV = Call->getReturnedArgOperand())
3659     return RV;
3660   // This can be used only as a aliasing property.
3661   if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call))
3662     return Call->getArgOperand(0);
3663   return nullptr;
3664 }
3665 
3666 bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
3667     const CallBase *Call) {
3668   return Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
3669          Call->getIntrinsicID() == Intrinsic::strip_invariant_group ||
3670          Call->getIntrinsicID() == Intrinsic::aarch64_irg ||
3671          Call->getIntrinsicID() == Intrinsic::aarch64_tagp;
3672 }
3673 
3674 /// \p PN defines a loop-variant pointer to an object.  Check if the
3675 /// previous iteration of the loop was referring to the same object as \p PN.
3676 static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3677                                          const LoopInfo *LI) {
3678   // Find the loop-defined value.
3679   Loop *L = LI->getLoopFor(PN->getParent());
3680   if (PN->getNumIncomingValues() != 2)
3681     return true;
3682 
3683   // Find the value from previous iteration.
3684   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3685   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3686     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3687   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3688     return true;
3689 
3690   // If a new pointer is loaded in the loop, the pointer references a different
3691   // object in every iteration.  E.g.:
3692   //    for (i)
3693   //       int *p = a[i];
3694   //       ...
3695   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3696     if (!L->isLoopInvariant(Load->getPointerOperand()))
3697       return false;
3698   return true;
3699 }
3700 
3701 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3702                                  unsigned MaxLookup) {
3703   if (!V->getType()->isPointerTy())
3704     return V;
3705   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3706     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3707       V = GEP->getPointerOperand();
3708     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3709                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3710       V = cast<Operator>(V)->getOperand(0);
3711     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3712       if (GA->isInterposable())
3713         return V;
3714       V = GA->getAliasee();
3715     } else if (isa<AllocaInst>(V)) {
3716       // An alloca can't be further simplified.
3717       return V;
3718     } else {
3719       if (auto *Call = dyn_cast<CallBase>(V)) {
3720         // CaptureTracking can know about special capturing properties of some
3721         // intrinsics like launder.invariant.group, that can't be expressed with
3722         // the attributes, but have properties like returning aliasing pointer.
3723         // Because some analysis may assume that nocaptured pointer is not
3724         // returned from some special intrinsic (because function would have to
3725         // be marked with returns attribute), it is crucial to use this function
3726         // because it should be in sync with CaptureTracking. Not using it may
3727         // cause weird miscompilations where 2 aliasing pointers are assumed to
3728         // noalias.
3729         if (auto *RP = getArgumentAliasingToReturnedPointer(Call)) {
3730           V = RP;
3731           continue;
3732         }
3733       }
3734 
3735       // See if InstructionSimplify knows any relevant tricks.
3736       if (Instruction *I = dyn_cast<Instruction>(V))
3737         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3738         if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
3739           V = Simplified;
3740           continue;
3741         }
3742 
3743       return V;
3744     }
3745     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3746   }
3747   return V;
3748 }
3749 
3750 void llvm::GetUnderlyingObjects(const Value *V,
3751                                 SmallVectorImpl<const Value *> &Objects,
3752                                 const DataLayout &DL, LoopInfo *LI,
3753                                 unsigned MaxLookup) {
3754   SmallPtrSet<const Value *, 4> Visited;
3755   SmallVector<const Value *, 4> Worklist;
3756   Worklist.push_back(V);
3757   do {
3758     const Value *P = Worklist.pop_back_val();
3759     P = GetUnderlyingObject(P, DL, MaxLookup);
3760 
3761     if (!Visited.insert(P).second)
3762       continue;
3763 
3764     if (auto *SI = dyn_cast<SelectInst>(P)) {
3765       Worklist.push_back(SI->getTrueValue());
3766       Worklist.push_back(SI->getFalseValue());
3767       continue;
3768     }
3769 
3770     if (auto *PN = dyn_cast<PHINode>(P)) {
3771       // If this PHI changes the underlying object in every iteration of the
3772       // loop, don't look through it.  Consider:
3773       //   int **A;
3774       //   for (i) {
3775       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
3776       //     Curr = A[i];
3777       //     *Prev, *Curr;
3778       //
3779       // Prev is tracking Curr one iteration behind so they refer to different
3780       // underlying objects.
3781       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3782           isSameUnderlyingObjectInLoop(PN, LI))
3783         for (Value *IncValue : PN->incoming_values())
3784           Worklist.push_back(IncValue);
3785       continue;
3786     }
3787 
3788     Objects.push_back(P);
3789   } while (!Worklist.empty());
3790 }
3791 
3792 /// This is the function that does the work of looking through basic
3793 /// ptrtoint+arithmetic+inttoptr sequences.
3794 static const Value *getUnderlyingObjectFromInt(const Value *V) {
3795   do {
3796     if (const Operator *U = dyn_cast<Operator>(V)) {
3797       // If we find a ptrtoint, we can transfer control back to the
3798       // regular getUnderlyingObjectFromInt.
3799       if (U->getOpcode() == Instruction::PtrToInt)
3800         return U->getOperand(0);
3801       // If we find an add of a constant, a multiplied value, or a phi, it's
3802       // likely that the other operand will lead us to the base
3803       // object. We don't have to worry about the case where the
3804       // object address is somehow being computed by the multiply,
3805       // because our callers only care when the result is an
3806       // identifiable object.
3807       if (U->getOpcode() != Instruction::Add ||
3808           (!isa<ConstantInt>(U->getOperand(1)) &&
3809            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3810            !isa<PHINode>(U->getOperand(1))))
3811         return V;
3812       V = U->getOperand(0);
3813     } else {
3814       return V;
3815     }
3816     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3817   } while (true);
3818 }
3819 
3820 /// This is a wrapper around GetUnderlyingObjects and adds support for basic
3821 /// ptrtoint+arithmetic+inttoptr sequences.
3822 /// It returns false if unidentified object is found in GetUnderlyingObjects.
3823 bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
3824                           SmallVectorImpl<Value *> &Objects,
3825                           const DataLayout &DL) {
3826   SmallPtrSet<const Value *, 16> Visited;
3827   SmallVector<const Value *, 4> Working(1, V);
3828   do {
3829     V = Working.pop_back_val();
3830 
3831     SmallVector<const Value *, 4> Objs;
3832     GetUnderlyingObjects(V, Objs, DL);
3833 
3834     for (const Value *V : Objs) {
3835       if (!Visited.insert(V).second)
3836         continue;
3837       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3838         const Value *O =
3839           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3840         if (O->getType()->isPointerTy()) {
3841           Working.push_back(O);
3842           continue;
3843         }
3844       }
3845       // If GetUnderlyingObjects fails to find an identifiable object,
3846       // getUnderlyingObjectsForCodeGen also fails for safety.
3847       if (!isIdentifiedObject(V)) {
3848         Objects.clear();
3849         return false;
3850       }
3851       Objects.push_back(const_cast<Value *>(V));
3852     }
3853   } while (!Working.empty());
3854   return true;
3855 }
3856 
3857 /// Return true if the only users of this pointer are lifetime markers.
3858 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3859   for (const User *U : V->users()) {
3860     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3861     if (!II) return false;
3862 
3863     if (!II->isLifetimeStartOrEnd())
3864       return false;
3865   }
3866   return true;
3867 }
3868 
3869 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3870                                         const Instruction *CtxI,
3871                                         const DominatorTree *DT) {
3872   const Operator *Inst = dyn_cast<Operator>(V);
3873   if (!Inst)
3874     return false;
3875 
3876   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3877     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3878       if (C->canTrap())
3879         return false;
3880 
3881   switch (Inst->getOpcode()) {
3882   default:
3883     return true;
3884   case Instruction::UDiv:
3885   case Instruction::URem: {
3886     // x / y is undefined if y == 0.
3887     const APInt *V;
3888     if (match(Inst->getOperand(1), m_APInt(V)))
3889       return *V != 0;
3890     return false;
3891   }
3892   case Instruction::SDiv:
3893   case Instruction::SRem: {
3894     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3895     const APInt *Numerator, *Denominator;
3896     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3897       return false;
3898     // We cannot hoist this division if the denominator is 0.
3899     if (*Denominator == 0)
3900       return false;
3901     // It's safe to hoist if the denominator is not 0 or -1.
3902     if (*Denominator != -1)
3903       return true;
3904     // At this point we know that the denominator is -1.  It is safe to hoist as
3905     // long we know that the numerator is not INT_MIN.
3906     if (match(Inst->getOperand(0), m_APInt(Numerator)))
3907       return !Numerator->isMinSignedValue();
3908     // The numerator *might* be MinSignedValue.
3909     return false;
3910   }
3911   case Instruction::Load: {
3912     const LoadInst *LI = cast<LoadInst>(Inst);
3913     if (!LI->isUnordered() ||
3914         // Speculative load may create a race that did not exist in the source.
3915         LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
3916         // Speculative load may load data from dirty regions.
3917         LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3918         LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3919       return false;
3920     const DataLayout &DL = LI->getModule()->getDataLayout();
3921     return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3922                                               LI->getType(), LI->getAlignment(),
3923                                               DL, CtxI, DT);
3924   }
3925   case Instruction::Call: {
3926     auto *CI = cast<const CallInst>(Inst);
3927     const Function *Callee = CI->getCalledFunction();
3928 
3929     // The called function could have undefined behavior or side-effects, even
3930     // if marked readnone nounwind.
3931     return Callee && Callee->isSpeculatable();
3932   }
3933   case Instruction::VAArg:
3934   case Instruction::Alloca:
3935   case Instruction::Invoke:
3936   case Instruction::CallBr:
3937   case Instruction::PHI:
3938   case Instruction::Store:
3939   case Instruction::Ret:
3940   case Instruction::Br:
3941   case Instruction::IndirectBr:
3942   case Instruction::Switch:
3943   case Instruction::Unreachable:
3944   case Instruction::Fence:
3945   case Instruction::AtomicRMW:
3946   case Instruction::AtomicCmpXchg:
3947   case Instruction::LandingPad:
3948   case Instruction::Resume:
3949   case Instruction::CatchSwitch:
3950   case Instruction::CatchPad:
3951   case Instruction::CatchRet:
3952   case Instruction::CleanupPad:
3953   case Instruction::CleanupRet:
3954     return false; // Misc instructions which have effects
3955   }
3956 }
3957 
3958 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3959   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3960 }
3961 
3962 /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
3963 static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
3964   switch (OR) {
3965     case ConstantRange::OverflowResult::MayOverflow:
3966       return OverflowResult::MayOverflow;
3967     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
3968       return OverflowResult::AlwaysOverflowsLow;
3969     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
3970       return OverflowResult::AlwaysOverflowsHigh;
3971     case ConstantRange::OverflowResult::NeverOverflows:
3972       return OverflowResult::NeverOverflows;
3973   }
3974   llvm_unreachable("Unknown OverflowResult");
3975 }
3976 
3977 /// Combine constant ranges from computeConstantRange() and computeKnownBits().
3978 static ConstantRange computeConstantRangeIncludingKnownBits(
3979     const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
3980     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3981     OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
3982   KnownBits Known = computeKnownBits(
3983       V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
3984   ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
3985   ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
3986   ConstantRange::PreferredRangeType RangeType =
3987       ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
3988   return CR1.intersectWith(CR2, RangeType);
3989 }
3990 
3991 OverflowResult llvm::computeOverflowForUnsignedMul(
3992     const Value *LHS, const Value *RHS, const DataLayout &DL,
3993     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3994     bool UseInstrInfo) {
3995   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3996                                         nullptr, UseInstrInfo);
3997   KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
3998                                         nullptr, UseInstrInfo);
3999   ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4000   ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4001   return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
4002 }
4003 
4004 OverflowResult
4005 llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4006                                   const DataLayout &DL, AssumptionCache *AC,
4007                                   const Instruction *CxtI,
4008                                   const DominatorTree *DT, bool UseInstrInfo) {
4009   // Multiplying n * m significant bits yields a result of n + m significant
4010   // bits. If the total number of significant bits does not exceed the
4011   // result bit width (minus 1), there is no overflow.
4012   // This means if we have enough leading sign bits in the operands
4013   // we can guarantee that the result does not overflow.
4014   // Ref: "Hacker's Delight" by Henry Warren
4015   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4016 
4017   // Note that underestimating the number of sign bits gives a more
4018   // conservative answer.
4019   unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4020                       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4021 
4022   // First handle the easy case: if we have enough sign bits there's
4023   // definitely no overflow.
4024   if (SignBits > BitWidth + 1)
4025     return OverflowResult::NeverOverflows;
4026 
4027   // There are two ambiguous cases where there can be no overflow:
4028   //   SignBits == BitWidth + 1    and
4029   //   SignBits == BitWidth
4030   // The second case is difficult to check, therefore we only handle the
4031   // first case.
4032   if (SignBits == BitWidth + 1) {
4033     // It overflows only when both arguments are negative and the true
4034     // product is exactly the minimum negative number.
4035     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4036     // For simplicity we just check if at least one side is not negative.
4037     KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4038                                           nullptr, UseInstrInfo);
4039     KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4040                                           nullptr, UseInstrInfo);
4041     if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4042       return OverflowResult::NeverOverflows;
4043   }
4044   return OverflowResult::MayOverflow;
4045 }
4046 
4047 OverflowResult llvm::computeOverflowForUnsignedAdd(
4048     const Value *LHS, const Value *RHS, const DataLayout &DL,
4049     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4050     bool UseInstrInfo) {
4051   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4052       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4053       nullptr, UseInstrInfo);
4054   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4055       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4056       nullptr, UseInstrInfo);
4057   return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
4058 }
4059 
4060 static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4061                                                   const Value *RHS,
4062                                                   const AddOperator *Add,
4063                                                   const DataLayout &DL,
4064                                                   AssumptionCache *AC,
4065                                                   const Instruction *CxtI,
4066                                                   const DominatorTree *DT) {
4067   if (Add && Add->hasNoSignedWrap()) {
4068     return OverflowResult::NeverOverflows;
4069   }
4070 
4071   // If LHS and RHS each have at least two sign bits, the addition will look
4072   // like
4073   //
4074   // XX..... +
4075   // YY.....
4076   //
4077   // If the carry into the most significant position is 0, X and Y can't both
4078   // be 1 and therefore the carry out of the addition is also 0.
4079   //
4080   // If the carry into the most significant position is 1, X and Y can't both
4081   // be 0 and therefore the carry out of the addition is also 1.
4082   //
4083   // Since the carry into the most significant position is always equal to
4084   // the carry out of the addition, there is no signed overflow.
4085   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4086       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4087     return OverflowResult::NeverOverflows;
4088 
4089   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4090       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4091   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4092       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4093   OverflowResult OR =
4094       mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4095   if (OR != OverflowResult::MayOverflow)
4096     return OR;
4097 
4098   // The remaining code needs Add to be available. Early returns if not so.
4099   if (!Add)
4100     return OverflowResult::MayOverflow;
4101 
4102   // If the sign of Add is the same as at least one of the operands, this add
4103   // CANNOT overflow. If this can be determined from the known bits of the
4104   // operands the above signedAddMayOverflow() check will have already done so.
4105   // The only other way to improve on the known bits is from an assumption, so
4106   // call computeKnownBitsFromAssume() directly.
4107   bool LHSOrRHSKnownNonNegative =
4108       (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
4109   bool LHSOrRHSKnownNegative =
4110       (LHSRange.isAllNegative() || RHSRange.isAllNegative());
4111   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4112     KnownBits AddKnown(LHSRange.getBitWidth());
4113     computeKnownBitsFromAssume(
4114         Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
4115     if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4116         (AddKnown.isNegative() && LHSOrRHSKnownNegative))
4117       return OverflowResult::NeverOverflows;
4118   }
4119 
4120   return OverflowResult::MayOverflow;
4121 }
4122 
4123 OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4124                                                    const Value *RHS,
4125                                                    const DataLayout &DL,
4126                                                    AssumptionCache *AC,
4127                                                    const Instruction *CxtI,
4128                                                    const DominatorTree *DT) {
4129   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4130       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4131   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4132       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4133   return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
4134 }
4135 
4136 OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4137                                                  const Value *RHS,
4138                                                  const DataLayout &DL,
4139                                                  AssumptionCache *AC,
4140                                                  const Instruction *CxtI,
4141                                                  const DominatorTree *DT) {
4142   // If LHS and RHS each have at least two sign bits, the subtraction
4143   // cannot overflow.
4144   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4145       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4146     return OverflowResult::NeverOverflows;
4147 
4148   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4149       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4150   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4151       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4152   return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
4153 }
4154 
4155 bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
4156                                      const DominatorTree &DT) {
4157   SmallVector<const BranchInst *, 2> GuardingBranches;
4158   SmallVector<const ExtractValueInst *, 2> Results;
4159 
4160   for (const User *U : WO->users()) {
4161     if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4162       assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4163 
4164       if (EVI->getIndices()[0] == 0)
4165         Results.push_back(EVI);
4166       else {
4167         assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4168 
4169         for (const auto *U : EVI->users())
4170           if (const auto *B = dyn_cast<BranchInst>(U)) {
4171             assert(B->isConditional() && "How else is it using an i1?");
4172             GuardingBranches.push_back(B);
4173           }
4174       }
4175     } else {
4176       // We are using the aggregate directly in a way we don't want to analyze
4177       // here (storing it to a global, say).
4178       return false;
4179     }
4180   }
4181 
4182   auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
4183     BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4184     if (!NoWrapEdge.isSingleEdge())
4185       return false;
4186 
4187     // Check if all users of the add are provably no-wrap.
4188     for (const auto *Result : Results) {
4189       // If the extractvalue itself is not executed on overflow, the we don't
4190       // need to check each use separately, since domination is transitive.
4191       if (DT.dominates(NoWrapEdge, Result->getParent()))
4192         continue;
4193 
4194       for (auto &RU : Result->uses())
4195         if (!DT.dominates(NoWrapEdge, RU))
4196           return false;
4197     }
4198 
4199     return true;
4200   };
4201 
4202   return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
4203 }
4204 
4205 
4206 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
4207                                                  const DataLayout &DL,
4208                                                  AssumptionCache *AC,
4209                                                  const Instruction *CxtI,
4210                                                  const DominatorTree *DT) {
4211   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
4212                                        Add, DL, AC, CxtI, DT);
4213 }
4214 
4215 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4216                                                  const Value *RHS,
4217                                                  const DataLayout &DL,
4218                                                  AssumptionCache *AC,
4219                                                  const Instruction *CxtI,
4220                                                  const DominatorTree *DT) {
4221   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
4222 }
4223 
4224 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
4225   // Note: An atomic operation isn't guaranteed to return in a reasonable amount
4226   // of time because it's possible for another thread to interfere with it for an
4227   // arbitrary length of time, but programs aren't allowed to rely on that.
4228 
4229   // If there is no successor, then execution can't transfer to it.
4230   if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4231     return !CRI->unwindsToCaller();
4232   if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4233     return !CatchSwitch->unwindsToCaller();
4234   if (isa<ResumeInst>(I))
4235     return false;
4236   if (isa<ReturnInst>(I))
4237     return false;
4238   if (isa<UnreachableInst>(I))
4239     return false;
4240 
4241   // Calls can throw, or contain an infinite loop, or kill the process.
4242   if (auto CS = ImmutableCallSite(I)) {
4243     // Call sites that throw have implicit non-local control flow.
4244     if (!CS.doesNotThrow())
4245       return false;
4246 
4247     // A function which doens't throw and has "willreturn" attribute will
4248     // always return.
4249     if (CS.hasFnAttr(Attribute::WillReturn))
4250       return true;
4251 
4252     // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4253     // etc. and thus not return.  However, LLVM already assumes that
4254     //
4255     //  - Thread exiting actions are modeled as writes to memory invisible to
4256     //    the program.
4257     //
4258     //  - Loops that don't have side effects (side effects are volatile/atomic
4259     //    stores and IO) always terminate (see http://llvm.org/PR965).
4260     //    Furthermore IO itself is also modeled as writes to memory invisible to
4261     //    the program.
4262     //
4263     // We rely on those assumptions here, and use the memory effects of the call
4264     // target as a proxy for checking that it always returns.
4265 
4266     // FIXME: This isn't aggressive enough; a call which only writes to a global
4267     // is guaranteed to return.
4268     return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory();
4269   }
4270 
4271   // Other instructions return normally.
4272   return true;
4273 }
4274 
4275 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
4276   // TODO: This is slightly conservative for invoke instruction since exiting
4277   // via an exception *is* normal control for them.
4278   for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4279     if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4280       return false;
4281   return true;
4282 }
4283 
4284 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4285                                                   const Loop *L) {
4286   // The loop header is guaranteed to be executed for every iteration.
4287   //
4288   // FIXME: Relax this constraint to cover all basic blocks that are
4289   // guaranteed to be executed at every iteration.
4290   if (I->getParent() != L->getHeader()) return false;
4291 
4292   for (const Instruction &LI : *L->getHeader()) {
4293     if (&LI == I) return true;
4294     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4295   }
4296   llvm_unreachable("Instruction not contained in its own parent basic block.");
4297 }
4298 
4299 bool llvm::propagatesFullPoison(const Instruction *I) {
4300   // TODO: This should include all instructions apart from phis, selects and
4301   // call-like instructions.
4302   switch (I->getOpcode()) {
4303   case Instruction::Add:
4304   case Instruction::Sub:
4305   case Instruction::Xor:
4306   case Instruction::Trunc:
4307   case Instruction::BitCast:
4308   case Instruction::AddrSpaceCast:
4309   case Instruction::Mul:
4310   case Instruction::Shl:
4311   case Instruction::GetElementPtr:
4312     // These operations all propagate poison unconditionally. Note that poison
4313     // is not any particular value, so xor or subtraction of poison with
4314     // itself still yields poison, not zero.
4315     return true;
4316 
4317   case Instruction::AShr:
4318   case Instruction::SExt:
4319     // For these operations, one bit of the input is replicated across
4320     // multiple output bits. A replicated poison bit is still poison.
4321     return true;
4322 
4323   case Instruction::ICmp:
4324     // Comparing poison with any value yields poison.  This is why, for
4325     // instance, x s< (x +nsw 1) can be folded to true.
4326     return true;
4327 
4328   default:
4329     return false;
4330   }
4331 }
4332 
4333 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4334   switch (I->getOpcode()) {
4335     case Instruction::Store:
4336       return cast<StoreInst>(I)->getPointerOperand();
4337 
4338     case Instruction::Load:
4339       return cast<LoadInst>(I)->getPointerOperand();
4340 
4341     case Instruction::AtomicCmpXchg:
4342       return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4343 
4344     case Instruction::AtomicRMW:
4345       return cast<AtomicRMWInst>(I)->getPointerOperand();
4346 
4347     case Instruction::UDiv:
4348     case Instruction::SDiv:
4349     case Instruction::URem:
4350     case Instruction::SRem:
4351       return I->getOperand(1);
4352 
4353     default:
4354       // Note: It's really tempting to think that a conditional branch or
4355       // switch should be listed here, but that's incorrect.  It's not
4356       // branching off of poison which is UB, it is executing a side effecting
4357       // instruction which follows the branch.
4358       return nullptr;
4359   }
4360 }
4361 
4362 bool llvm::mustTriggerUB(const Instruction *I,
4363                          const SmallSet<const Value *, 16>& KnownPoison) {
4364   auto *NotPoison = getGuaranteedNonFullPoisonOp(I);
4365   return (NotPoison && KnownPoison.count(NotPoison));
4366 }
4367 
4368 
4369 bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
4370   // We currently only look for uses of poison values within the same basic
4371   // block, as that makes it easier to guarantee that the uses will be
4372   // executed given that PoisonI is executed.
4373   //
4374   // FIXME: Expand this to consider uses beyond the same basic block. To do
4375   // this, look out for the distinction between post-dominance and strong
4376   // post-dominance.
4377   const BasicBlock *BB = PoisonI->getParent();
4378 
4379   // Set of instructions that we have proved will yield poison if PoisonI
4380   // does.
4381   SmallSet<const Value *, 16> YieldsPoison;
4382   SmallSet<const BasicBlock *, 4> Visited;
4383   YieldsPoison.insert(PoisonI);
4384   Visited.insert(PoisonI->getParent());
4385 
4386   BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
4387 
4388   unsigned Iter = 0;
4389   while (Iter++ < MaxDepth) {
4390     for (auto &I : make_range(Begin, End)) {
4391       if (&I != PoisonI) {
4392         if (mustTriggerUB(&I, YieldsPoison))
4393           return true;
4394         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4395           return false;
4396       }
4397 
4398       // Mark poison that propagates from I through uses of I.
4399       if (YieldsPoison.count(&I)) {
4400         for (const User *User : I.users()) {
4401           const Instruction *UserI = cast<Instruction>(User);
4402           if (propagatesFullPoison(UserI))
4403             YieldsPoison.insert(User);
4404         }
4405       }
4406     }
4407 
4408     if (auto *NextBB = BB->getSingleSuccessor()) {
4409       if (Visited.insert(NextBB).second) {
4410         BB = NextBB;
4411         Begin = BB->getFirstNonPHI()->getIterator();
4412         End = BB->end();
4413         continue;
4414       }
4415     }
4416 
4417     break;
4418   }
4419   return false;
4420 }
4421 
4422 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
4423   if (FMF.noNaNs())
4424     return true;
4425 
4426   if (auto *C = dyn_cast<ConstantFP>(V))
4427     return !C->isNaN();
4428 
4429   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4430     if (!C->getElementType()->isFloatingPointTy())
4431       return false;
4432     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4433       if (C->getElementAsAPFloat(I).isNaN())
4434         return false;
4435     }
4436     return true;
4437   }
4438 
4439   return false;
4440 }
4441 
4442 static bool isKnownNonZero(const Value *V) {
4443   if (auto *C = dyn_cast<ConstantFP>(V))
4444     return !C->isZero();
4445 
4446   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4447     if (!C->getElementType()->isFloatingPointTy())
4448       return false;
4449     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4450       if (C->getElementAsAPFloat(I).isZero())
4451         return false;
4452     }
4453     return true;
4454   }
4455 
4456   return false;
4457 }
4458 
4459 /// Match clamp pattern for float types without care about NaNs or signed zeros.
4460 /// Given non-min/max outer cmp/select from the clamp pattern this
4461 /// function recognizes if it can be substitued by a "canonical" min/max
4462 /// pattern.
4463 static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4464                                                Value *CmpLHS, Value *CmpRHS,
4465                                                Value *TrueVal, Value *FalseVal,
4466                                                Value *&LHS, Value *&RHS) {
4467   // Try to match
4468   //   X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4469   //   X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4470   // and return description of the outer Max/Min.
4471 
4472   // First, check if select has inverse order:
4473   if (CmpRHS == FalseVal) {
4474     std::swap(TrueVal, FalseVal);
4475     Pred = CmpInst::getInversePredicate(Pred);
4476   }
4477 
4478   // Assume success now. If there's no match, callers should not use these anyway.
4479   LHS = TrueVal;
4480   RHS = FalseVal;
4481 
4482   const APFloat *FC1;
4483   if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4484     return {SPF_UNKNOWN, SPNB_NA, false};
4485 
4486   const APFloat *FC2;
4487   switch (Pred) {
4488   case CmpInst::FCMP_OLT:
4489   case CmpInst::FCMP_OLE:
4490   case CmpInst::FCMP_ULT:
4491   case CmpInst::FCMP_ULE:
4492     if (match(FalseVal,
4493               m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4494                           m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4495         FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4496       return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4497     break;
4498   case CmpInst::FCMP_OGT:
4499   case CmpInst::FCMP_OGE:
4500   case CmpInst::FCMP_UGT:
4501   case CmpInst::FCMP_UGE:
4502     if (match(FalseVal,
4503               m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4504                           m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4505         FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4506       return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4507     break;
4508   default:
4509     break;
4510   }
4511 
4512   return {SPF_UNKNOWN, SPNB_NA, false};
4513 }
4514 
4515 /// Recognize variations of:
4516 ///   CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4517 static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4518                                       Value *CmpLHS, Value *CmpRHS,
4519                                       Value *TrueVal, Value *FalseVal) {
4520   // Swap the select operands and predicate to match the patterns below.
4521   if (CmpRHS != TrueVal) {
4522     Pred = ICmpInst::getSwappedPredicate(Pred);
4523     std::swap(TrueVal, FalseVal);
4524   }
4525   const APInt *C1;
4526   if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4527     const APInt *C2;
4528     // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4529     if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4530         C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
4531       return {SPF_SMAX, SPNB_NA, false};
4532 
4533     // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4534     if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4535         C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
4536       return {SPF_SMIN, SPNB_NA, false};
4537 
4538     // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4539     if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4540         C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
4541       return {SPF_UMAX, SPNB_NA, false};
4542 
4543     // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4544     if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4545         C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
4546       return {SPF_UMIN, SPNB_NA, false};
4547   }
4548   return {SPF_UNKNOWN, SPNB_NA, false};
4549 }
4550 
4551 /// Recognize variations of:
4552 ///   a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4553 static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4554                                                Value *CmpLHS, Value *CmpRHS,
4555                                                Value *TVal, Value *FVal,
4556                                                unsigned Depth) {
4557   // TODO: Allow FP min/max with nnan/nsz.
4558   assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4559 
4560   Value *A, *B;
4561   SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
4562   if (!SelectPatternResult::isMinOrMax(L.Flavor))
4563     return {SPF_UNKNOWN, SPNB_NA, false};
4564 
4565   Value *C, *D;
4566   SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
4567   if (L.Flavor != R.Flavor)
4568     return {SPF_UNKNOWN, SPNB_NA, false};
4569 
4570   // We have something like: x Pred y ? min(a, b) : min(c, d).
4571   // Try to match the compare to the min/max operations of the select operands.
4572   // First, make sure we have the right compare predicate.
4573   switch (L.Flavor) {
4574   case SPF_SMIN:
4575     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4576       Pred = ICmpInst::getSwappedPredicate(Pred);
4577       std::swap(CmpLHS, CmpRHS);
4578     }
4579     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4580       break;
4581     return {SPF_UNKNOWN, SPNB_NA, false};
4582   case SPF_SMAX:
4583     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4584       Pred = ICmpInst::getSwappedPredicate(Pred);
4585       std::swap(CmpLHS, CmpRHS);
4586     }
4587     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4588       break;
4589     return {SPF_UNKNOWN, SPNB_NA, false};
4590   case SPF_UMIN:
4591     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4592       Pred = ICmpInst::getSwappedPredicate(Pred);
4593       std::swap(CmpLHS, CmpRHS);
4594     }
4595     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4596       break;
4597     return {SPF_UNKNOWN, SPNB_NA, false};
4598   case SPF_UMAX:
4599     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4600       Pred = ICmpInst::getSwappedPredicate(Pred);
4601       std::swap(CmpLHS, CmpRHS);
4602     }
4603     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4604       break;
4605     return {SPF_UNKNOWN, SPNB_NA, false};
4606   default:
4607     return {SPF_UNKNOWN, SPNB_NA, false};
4608   }
4609 
4610   // If there is a common operand in the already matched min/max and the other
4611   // min/max operands match the compare operands (either directly or inverted),
4612   // then this is min/max of the same flavor.
4613 
4614   // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4615   // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4616   if (D == B) {
4617     if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4618                                          match(A, m_Not(m_Specific(CmpRHS)))))
4619       return {L.Flavor, SPNB_NA, false};
4620   }
4621   // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4622   // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4623   if (C == B) {
4624     if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4625                                          match(A, m_Not(m_Specific(CmpRHS)))))
4626       return {L.Flavor, SPNB_NA, false};
4627   }
4628   // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4629   // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4630   if (D == A) {
4631     if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4632                                          match(B, m_Not(m_Specific(CmpRHS)))))
4633       return {L.Flavor, SPNB_NA, false};
4634   }
4635   // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4636   // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4637   if (C == A) {
4638     if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4639                                          match(B, m_Not(m_Specific(CmpRHS)))))
4640       return {L.Flavor, SPNB_NA, false};
4641   }
4642 
4643   return {SPF_UNKNOWN, SPNB_NA, false};
4644 }
4645 
4646 /// Match non-obvious integer minimum and maximum sequences.
4647 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4648                                        Value *CmpLHS, Value *CmpRHS,
4649                                        Value *TrueVal, Value *FalseVal,
4650                                        Value *&LHS, Value *&RHS,
4651                                        unsigned Depth) {
4652   // Assume success. If there's no match, callers should not use these anyway.
4653   LHS = TrueVal;
4654   RHS = FalseVal;
4655 
4656   SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4657   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4658     return SPR;
4659 
4660   SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
4661   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4662     return SPR;
4663 
4664   if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
4665     return {SPF_UNKNOWN, SPNB_NA, false};
4666 
4667   // Z = X -nsw Y
4668   // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4669   // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4670   if (match(TrueVal, m_Zero()) &&
4671       match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4672     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4673 
4674   // Z = X -nsw Y
4675   // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4676   // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4677   if (match(FalseVal, m_Zero()) &&
4678       match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4679     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4680 
4681   const APInt *C1;
4682   if (!match(CmpRHS, m_APInt(C1)))
4683     return {SPF_UNKNOWN, SPNB_NA, false};
4684 
4685   // An unsigned min/max can be written with a signed compare.
4686   const APInt *C2;
4687   if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4688       (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4689     // Is the sign bit set?
4690     // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4691     // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
4692     if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4693         C2->isMaxSignedValue())
4694       return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4695 
4696     // Is the sign bit clear?
4697     // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4698     // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4699     if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4700         C2->isMinSignedValue())
4701       return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4702   }
4703 
4704   // Look through 'not' ops to find disguised signed min/max.
4705   // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4706   // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4707   if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
4708       match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
4709     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4710 
4711   // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4712   // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4713   if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
4714       match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
4715     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4716 
4717   return {SPF_UNKNOWN, SPNB_NA, false};
4718 }
4719 
4720 bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
4721   assert(X && Y && "Invalid operand");
4722 
4723   // X = sub (0, Y) || X = sub nsw (0, Y)
4724   if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4725       (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
4726     return true;
4727 
4728   // Y = sub (0, X) || Y = sub nsw (0, X)
4729   if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4730       (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
4731     return true;
4732 
4733   // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
4734   Value *A, *B;
4735   return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4736                         match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4737          (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4738                        match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
4739 }
4740 
4741 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4742                                               FastMathFlags FMF,
4743                                               Value *CmpLHS, Value *CmpRHS,
4744                                               Value *TrueVal, Value *FalseVal,
4745                                               Value *&LHS, Value *&RHS,
4746                                               unsigned Depth) {
4747   if (CmpInst::isFPPredicate(Pred)) {
4748     // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4749     // 0.0 operand, set the compare's 0.0 operands to that same value for the
4750     // purpose of identifying min/max. Disregard vector constants with undefined
4751     // elements because those can not be back-propagated for analysis.
4752     Value *OutputZeroVal = nullptr;
4753     if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4754         !cast<Constant>(TrueVal)->containsUndefElement())
4755       OutputZeroVal = TrueVal;
4756     else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4757              !cast<Constant>(FalseVal)->containsUndefElement())
4758       OutputZeroVal = FalseVal;
4759 
4760     if (OutputZeroVal) {
4761       if (match(CmpLHS, m_AnyZeroFP()))
4762         CmpLHS = OutputZeroVal;
4763       if (match(CmpRHS, m_AnyZeroFP()))
4764         CmpRHS = OutputZeroVal;
4765     }
4766   }
4767 
4768   LHS = CmpLHS;
4769   RHS = CmpRHS;
4770 
4771   // Signed zero may return inconsistent results between implementations.
4772   //  (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4773   //  minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4774   // Therefore, we behave conservatively and only proceed if at least one of the
4775   // operands is known to not be zero or if we don't care about signed zero.
4776   switch (Pred) {
4777   default: break;
4778   // FIXME: Include OGT/OLT/UGT/ULT.
4779   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4780   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4781     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4782         !isKnownNonZero(CmpRHS))
4783       return {SPF_UNKNOWN, SPNB_NA, false};
4784   }
4785 
4786   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4787   bool Ordered = false;
4788 
4789   // When given one NaN and one non-NaN input:
4790   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4791   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4792   //     ordered comparison fails), which could be NaN or non-NaN.
4793   // so here we discover exactly what NaN behavior is required/accepted.
4794   if (CmpInst::isFPPredicate(Pred)) {
4795     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4796     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4797 
4798     if (LHSSafe && RHSSafe) {
4799       // Both operands are known non-NaN.
4800       NaNBehavior = SPNB_RETURNS_ANY;
4801     } else if (CmpInst::isOrdered(Pred)) {
4802       // An ordered comparison will return false when given a NaN, so it
4803       // returns the RHS.
4804       Ordered = true;
4805       if (LHSSafe)
4806         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
4807         NaNBehavior = SPNB_RETURNS_NAN;
4808       else if (RHSSafe)
4809         NaNBehavior = SPNB_RETURNS_OTHER;
4810       else
4811         // Completely unsafe.
4812         return {SPF_UNKNOWN, SPNB_NA, false};
4813     } else {
4814       Ordered = false;
4815       // An unordered comparison will return true when given a NaN, so it
4816       // returns the LHS.
4817       if (LHSSafe)
4818         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
4819         NaNBehavior = SPNB_RETURNS_OTHER;
4820       else if (RHSSafe)
4821         NaNBehavior = SPNB_RETURNS_NAN;
4822       else
4823         // Completely unsafe.
4824         return {SPF_UNKNOWN, SPNB_NA, false};
4825     }
4826   }
4827 
4828   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
4829     std::swap(CmpLHS, CmpRHS);
4830     Pred = CmpInst::getSwappedPredicate(Pred);
4831     if (NaNBehavior == SPNB_RETURNS_NAN)
4832       NaNBehavior = SPNB_RETURNS_OTHER;
4833     else if (NaNBehavior == SPNB_RETURNS_OTHER)
4834       NaNBehavior = SPNB_RETURNS_NAN;
4835     Ordered = !Ordered;
4836   }
4837 
4838   // ([if]cmp X, Y) ? X : Y
4839   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
4840     switch (Pred) {
4841     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
4842     case ICmpInst::ICMP_UGT:
4843     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
4844     case ICmpInst::ICMP_SGT:
4845     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
4846     case ICmpInst::ICMP_ULT:
4847     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
4848     case ICmpInst::ICMP_SLT:
4849     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4850     case FCmpInst::FCMP_UGT:
4851     case FCmpInst::FCMP_UGE:
4852     case FCmpInst::FCMP_OGT:
4853     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4854     case FCmpInst::FCMP_ULT:
4855     case FCmpInst::FCMP_ULE:
4856     case FCmpInst::FCMP_OLT:
4857     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
4858     }
4859   }
4860 
4861   if (isKnownNegation(TrueVal, FalseVal)) {
4862     // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4863     // match against either LHS or sext(LHS).
4864     auto MaybeSExtCmpLHS =
4865         m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4866     auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4867     auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4868     if (match(TrueVal, MaybeSExtCmpLHS)) {
4869       // Set the return values. If the compare uses the negated value (-X >s 0),
4870       // swap the return values because the negated value is always 'RHS'.
4871       LHS = TrueVal;
4872       RHS = FalseVal;
4873       if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4874         std::swap(LHS, RHS);
4875 
4876       // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4877       // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4878       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4879         return {SPF_ABS, SPNB_NA, false};
4880 
4881       // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
4882       if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
4883         return {SPF_ABS, SPNB_NA, false};
4884 
4885       // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4886       // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4887       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4888         return {SPF_NABS, SPNB_NA, false};
4889     }
4890     else if (match(FalseVal, MaybeSExtCmpLHS)) {
4891       // Set the return values. If the compare uses the negated value (-X >s 0),
4892       // swap the return values because the negated value is always 'RHS'.
4893       LHS = FalseVal;
4894       RHS = TrueVal;
4895       if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4896         std::swap(LHS, RHS);
4897 
4898       // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4899       // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4900       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4901         return {SPF_NABS, SPNB_NA, false};
4902 
4903       // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4904       // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4905       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4906         return {SPF_ABS, SPNB_NA, false};
4907     }
4908   }
4909 
4910   if (CmpInst::isIntPredicate(Pred))
4911     return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
4912 
4913   // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4914   // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4915   // semantics than minNum. Be conservative in such case.
4916   if (NaNBehavior != SPNB_RETURNS_ANY ||
4917       (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4918        !isKnownNonZero(CmpRHS)))
4919     return {SPF_UNKNOWN, SPNB_NA, false};
4920 
4921   return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4922 }
4923 
4924 /// Helps to match a select pattern in case of a type mismatch.
4925 ///
4926 /// The function processes the case when type of true and false values of a
4927 /// select instruction differs from type of the cmp instruction operands because
4928 /// of a cast instruction. The function checks if it is legal to move the cast
4929 /// operation after "select". If yes, it returns the new second value of
4930 /// "select" (with the assumption that cast is moved):
4931 /// 1. As operand of cast instruction when both values of "select" are same cast
4932 /// instructions.
4933 /// 2. As restored constant (by applying reverse cast operation) when the first
4934 /// value of the "select" is a cast operation and the second value is a
4935 /// constant.
4936 /// NOTE: We return only the new second value because the first value could be
4937 /// accessed as operand of cast instruction.
4938 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4939                               Instruction::CastOps *CastOp) {
4940   auto *Cast1 = dyn_cast<CastInst>(V1);
4941   if (!Cast1)
4942     return nullptr;
4943 
4944   *CastOp = Cast1->getOpcode();
4945   Type *SrcTy = Cast1->getSrcTy();
4946   if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4947     // If V1 and V2 are both the same cast from the same type, look through V1.
4948     if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4949       return Cast2->getOperand(0);
4950     return nullptr;
4951   }
4952 
4953   auto *C = dyn_cast<Constant>(V2);
4954   if (!C)
4955     return nullptr;
4956 
4957   Constant *CastedTo = nullptr;
4958   switch (*CastOp) {
4959   case Instruction::ZExt:
4960     if (CmpI->isUnsigned())
4961       CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4962     break;
4963   case Instruction::SExt:
4964     if (CmpI->isSigned())
4965       CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4966     break;
4967   case Instruction::Trunc:
4968     Constant *CmpConst;
4969     if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4970         CmpConst->getType() == SrcTy) {
4971       // Here we have the following case:
4972       //
4973       //   %cond = cmp iN %x, CmpConst
4974       //   %tr = trunc iN %x to iK
4975       //   %narrowsel = select i1 %cond, iK %t, iK C
4976       //
4977       // We can always move trunc after select operation:
4978       //
4979       //   %cond = cmp iN %x, CmpConst
4980       //   %widesel = select i1 %cond, iN %x, iN CmpConst
4981       //   %tr = trunc iN %widesel to iK
4982       //
4983       // Note that C could be extended in any way because we don't care about
4984       // upper bits after truncation. It can't be abs pattern, because it would
4985       // look like:
4986       //
4987       //   select i1 %cond, x, -x.
4988       //
4989       // So only min/max pattern could be matched. Such match requires widened C
4990       // == CmpConst. That is why set widened C = CmpConst, condition trunc
4991       // CmpConst == C is checked below.
4992       CastedTo = CmpConst;
4993     } else {
4994       CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4995     }
4996     break;
4997   case Instruction::FPTrunc:
4998     CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4999     break;
5000   case Instruction::FPExt:
5001     CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5002     break;
5003   case Instruction::FPToUI:
5004     CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5005     break;
5006   case Instruction::FPToSI:
5007     CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5008     break;
5009   case Instruction::UIToFP:
5010     CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5011     break;
5012   case Instruction::SIToFP:
5013     CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5014     break;
5015   default:
5016     break;
5017   }
5018 
5019   if (!CastedTo)
5020     return nullptr;
5021 
5022   // Make sure the cast doesn't lose any information.
5023   Constant *CastedBack =
5024       ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
5025   if (CastedBack != C)
5026     return nullptr;
5027 
5028   return CastedTo;
5029 }
5030 
5031 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
5032                                              Instruction::CastOps *CastOp,
5033                                              unsigned Depth) {
5034   if (Depth >= MaxDepth)
5035     return {SPF_UNKNOWN, SPNB_NA, false};
5036 
5037   SelectInst *SI = dyn_cast<SelectInst>(V);
5038   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
5039 
5040   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5041   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
5042 
5043   Value *TrueVal = SI->getTrueValue();
5044   Value *FalseVal = SI->getFalseValue();
5045 
5046   return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
5047                                             CastOp, Depth);
5048 }
5049 
5050 SelectPatternResult llvm::matchDecomposedSelectPattern(
5051     CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
5052     Instruction::CastOps *CastOp, unsigned Depth) {
5053   CmpInst::Predicate Pred = CmpI->getPredicate();
5054   Value *CmpLHS = CmpI->getOperand(0);
5055   Value *CmpRHS = CmpI->getOperand(1);
5056   FastMathFlags FMF;
5057   if (isa<FPMathOperator>(CmpI))
5058     FMF = CmpI->getFastMathFlags();
5059 
5060   // Bail out early.
5061   if (CmpI->isEquality())
5062     return {SPF_UNKNOWN, SPNB_NA, false};
5063 
5064   // Deal with type mismatches.
5065   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
5066     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5067       // If this is a potential fmin/fmax with a cast to integer, then ignore
5068       // -0.0 because there is no corresponding integer value.
5069       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5070         FMF.setNoSignedZeros();
5071       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
5072                                   cast<CastInst>(TrueVal)->getOperand(0), C,
5073                                   LHS, RHS, Depth);
5074     }
5075     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5076       // If this is a potential fmin/fmax with a cast to integer, then ignore
5077       // -0.0 because there is no corresponding integer value.
5078       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5079         FMF.setNoSignedZeros();
5080       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
5081                                   C, cast<CastInst>(FalseVal)->getOperand(0),
5082                                   LHS, RHS, Depth);
5083     }
5084   }
5085   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
5086                               LHS, RHS, Depth);
5087 }
5088 
5089 CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5090   if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5091   if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5092   if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5093   if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5094   if (SPF == SPF_FMINNUM)
5095     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5096   if (SPF == SPF_FMAXNUM)
5097     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5098   llvm_unreachable("unhandled!");
5099 }
5100 
5101 SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5102   if (SPF == SPF_SMIN) return SPF_SMAX;
5103   if (SPF == SPF_UMIN) return SPF_UMAX;
5104   if (SPF == SPF_SMAX) return SPF_SMIN;
5105   if (SPF == SPF_UMAX) return SPF_UMIN;
5106   llvm_unreachable("unhandled!");
5107 }
5108 
5109 CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5110   return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5111 }
5112 
5113 /// Return true if "icmp Pred LHS RHS" is always true.
5114 static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5115                             const Value *RHS, const DataLayout &DL,
5116                             unsigned Depth) {
5117   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
5118   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5119     return true;
5120 
5121   switch (Pred) {
5122   default:
5123     return false;
5124 
5125   case CmpInst::ICMP_SLE: {
5126     const APInt *C;
5127 
5128     // LHS s<= LHS +_{nsw} C   if C >= 0
5129     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
5130       return !C->isNegative();
5131     return false;
5132   }
5133 
5134   case CmpInst::ICMP_ULE: {
5135     const APInt *C;
5136 
5137     // LHS u<= LHS +_{nuw} C   for any C
5138     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
5139       return true;
5140 
5141     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
5142     auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5143                                        const Value *&X,
5144                                        const APInt *&CA, const APInt *&CB) {
5145       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5146           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5147         return true;
5148 
5149       // If X & C == 0 then (X | C) == X +_{nuw} C
5150       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5151           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
5152         KnownBits Known(CA->getBitWidth());
5153         computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5154                          /*CxtI*/ nullptr, /*DT*/ nullptr);
5155         if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
5156           return true;
5157       }
5158 
5159       return false;
5160     };
5161 
5162     const Value *X;
5163     const APInt *CLHS, *CRHS;
5164     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5165       return CLHS->ule(*CRHS);
5166 
5167     return false;
5168   }
5169   }
5170 }
5171 
5172 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
5173 /// ALHS ARHS" is true.  Otherwise, return None.
5174 static Optional<bool>
5175 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
5176                       const Value *ARHS, const Value *BLHS, const Value *BRHS,
5177                       const DataLayout &DL, unsigned Depth) {
5178   switch (Pred) {
5179   default:
5180     return None;
5181 
5182   case CmpInst::ICMP_SLT:
5183   case CmpInst::ICMP_SLE:
5184     if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5185         isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
5186       return true;
5187     return None;
5188 
5189   case CmpInst::ICMP_ULT:
5190   case CmpInst::ICMP_ULE:
5191     if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5192         isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
5193       return true;
5194     return None;
5195   }
5196 }
5197 
5198 /// Return true if the operands of the two compares match.  IsSwappedOps is true
5199 /// when the operands match, but are swapped.
5200 static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5201                           const Value *BLHS, const Value *BRHS,
5202                           bool &IsSwappedOps) {
5203 
5204   bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5205   IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5206   return IsMatchingOps || IsSwappedOps;
5207 }
5208 
5209 /// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
5210 /// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
5211 /// Otherwise, return None if we can't infer anything.
5212 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
5213                                                     CmpInst::Predicate BPred,
5214                                                     bool AreSwappedOps) {
5215   // Canonicalize the predicate as if the operands were not commuted.
5216   if (AreSwappedOps)
5217     BPred = ICmpInst::getSwappedPredicate(BPred);
5218 
5219   if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
5220     return true;
5221   if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
5222     return false;
5223 
5224   return None;
5225 }
5226 
5227 /// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
5228 /// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
5229 /// Otherwise, return None if we can't infer anything.
5230 static Optional<bool>
5231 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
5232                                  const ConstantInt *C1,
5233                                  CmpInst::Predicate BPred,
5234                                  const ConstantInt *C2) {
5235   ConstantRange DomCR =
5236       ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5237   ConstantRange CR =
5238       ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5239   ConstantRange Intersection = DomCR.intersectWith(CR);
5240   ConstantRange Difference = DomCR.difference(CR);
5241   if (Intersection.isEmptySet())
5242     return false;
5243   if (Difference.isEmptySet())
5244     return true;
5245   return None;
5246 }
5247 
5248 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
5249 /// false.  Otherwise, return None if we can't infer anything.
5250 static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5251                                          const ICmpInst *RHS,
5252                                          const DataLayout &DL, bool LHSIsTrue,
5253                                          unsigned Depth) {
5254   Value *ALHS = LHS->getOperand(0);
5255   Value *ARHS = LHS->getOperand(1);
5256   // The rest of the logic assumes the LHS condition is true.  If that's not the
5257   // case, invert the predicate to make it so.
5258   ICmpInst::Predicate APred =
5259       LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
5260 
5261   Value *BLHS = RHS->getOperand(0);
5262   Value *BRHS = RHS->getOperand(1);
5263   ICmpInst::Predicate BPred = RHS->getPredicate();
5264 
5265   // Can we infer anything when the two compares have matching operands?
5266   bool AreSwappedOps;
5267   if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
5268     if (Optional<bool> Implication = isImpliedCondMatchingOperands(
5269             APred, BPred, AreSwappedOps))
5270       return Implication;
5271     // No amount of additional analysis will infer the second condition, so
5272     // early exit.
5273     return None;
5274   }
5275 
5276   // Can we infer anything when the LHS operands match and the RHS operands are
5277   // constants (not necessarily matching)?
5278   if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5279     if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
5280             APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
5281       return Implication;
5282     // No amount of additional analysis will infer the second condition, so
5283     // early exit.
5284     return None;
5285   }
5286 
5287   if (APred == BPred)
5288     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
5289   return None;
5290 }
5291 
5292 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
5293 /// false.  Otherwise, return None if we can't infer anything.  We expect the
5294 /// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5295 static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5296                                          const ICmpInst *RHS,
5297                                          const DataLayout &DL, bool LHSIsTrue,
5298                                          unsigned Depth) {
5299   // The LHS must be an 'or' or an 'and' instruction.
5300   assert((LHS->getOpcode() == Instruction::And ||
5301           LHS->getOpcode() == Instruction::Or) &&
5302          "Expected LHS to be 'and' or 'or'.");
5303 
5304   assert(Depth <= MaxDepth && "Hit recursion limit");
5305 
5306   // If the result of an 'or' is false, then we know both legs of the 'or' are
5307   // false.  Similarly, if the result of an 'and' is true, then we know both
5308   // legs of the 'and' are true.
5309   Value *ALHS, *ARHS;
5310   if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5311       (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
5312     // FIXME: Make this non-recursion.
5313     if (Optional<bool> Implication =
5314             isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
5315       return Implication;
5316     if (Optional<bool> Implication =
5317             isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
5318       return Implication;
5319     return None;
5320   }
5321   return None;
5322 }
5323 
5324 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
5325                                         const DataLayout &DL, bool LHSIsTrue,
5326                                         unsigned Depth) {
5327   // Bail out when we hit the limit.
5328   if (Depth == MaxDepth)
5329     return None;
5330 
5331   // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5332   // example.
5333   if (LHS->getType() != RHS->getType())
5334     return None;
5335 
5336   Type *OpTy = LHS->getType();
5337   assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
5338 
5339   // LHS ==> RHS by definition
5340   if (LHS == RHS)
5341     return LHSIsTrue;
5342 
5343   // FIXME: Extending the code below to handle vectors.
5344   if (OpTy->isVectorTy())
5345     return None;
5346 
5347   assert(OpTy->isIntegerTy(1) && "implied by above");
5348 
5349   // Both LHS and RHS are icmps.
5350   const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5351   const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5352   if (LHSCmp && RHSCmp)
5353     return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
5354 
5355   // The LHS should be an 'or' or an 'and' instruction.  We expect the RHS to be
5356   // an icmp. FIXME: Add support for and/or on the RHS.
5357   const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5358   if (LHSBO && RHSCmp) {
5359     if ((LHSBO->getOpcode() == Instruction::And ||
5360          LHSBO->getOpcode() == Instruction::Or))
5361       return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
5362   }
5363   return None;
5364 }
5365 
5366 Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
5367                                              const Instruction *ContextI,
5368                                              const DataLayout &DL) {
5369   assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
5370   if (!ContextI || !ContextI->getParent())
5371     return None;
5372 
5373   // TODO: This is a poor/cheap way to determine dominance. Should we use a
5374   // dominator tree (eg, from a SimplifyQuery) instead?
5375   const BasicBlock *ContextBB = ContextI->getParent();
5376   const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
5377   if (!PredBB)
5378     return None;
5379 
5380   // We need a conditional branch in the predecessor.
5381   Value *PredCond;
5382   BasicBlock *TrueBB, *FalseBB;
5383   if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
5384     return None;
5385 
5386   // The branch should get simplified. Don't bother simplifying this condition.
5387   if (TrueBB == FalseBB)
5388     return None;
5389 
5390   assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
5391          "Predecessor block does not point to successor?");
5392 
5393   // Is this condition implied by the predecessor condition?
5394   bool CondIsTrue = TrueBB == ContextBB;
5395   return isImpliedCondition(PredCond, Cond, DL, CondIsTrue);
5396 }
5397 
5398 static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
5399                               APInt &Upper, const InstrInfoQuery &IIQ) {
5400   unsigned Width = Lower.getBitWidth();
5401   const APInt *C;
5402   switch (BO.getOpcode()) {
5403   case Instruction::Add:
5404     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5405       // FIXME: If we have both nuw and nsw, we should reduce the range further.
5406       if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5407         // 'add nuw x, C' produces [C, UINT_MAX].
5408         Lower = *C;
5409       } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5410         if (C->isNegative()) {
5411           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
5412           Lower = APInt::getSignedMinValue(Width);
5413           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5414         } else {
5415           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
5416           Lower = APInt::getSignedMinValue(Width) + *C;
5417           Upper = APInt::getSignedMaxValue(Width) + 1;
5418         }
5419       }
5420     }
5421     break;
5422 
5423   case Instruction::And:
5424     if (match(BO.getOperand(1), m_APInt(C)))
5425       // 'and x, C' produces [0, C].
5426       Upper = *C + 1;
5427     break;
5428 
5429   case Instruction::Or:
5430     if (match(BO.getOperand(1), m_APInt(C)))
5431       // 'or x, C' produces [C, UINT_MAX].
5432       Lower = *C;
5433     break;
5434 
5435   case Instruction::AShr:
5436     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5437       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
5438       Lower = APInt::getSignedMinValue(Width).ashr(*C);
5439       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
5440     } else if (match(BO.getOperand(0), m_APInt(C))) {
5441       unsigned ShiftAmount = Width - 1;
5442       if (!C->isNullValue() && IIQ.isExact(&BO))
5443         ShiftAmount = C->countTrailingZeros();
5444       if (C->isNegative()) {
5445         // 'ashr C, x' produces [C, C >> (Width-1)]
5446         Lower = *C;
5447         Upper = C->ashr(ShiftAmount) + 1;
5448       } else {
5449         // 'ashr C, x' produces [C >> (Width-1), C]
5450         Lower = C->ashr(ShiftAmount);
5451         Upper = *C + 1;
5452       }
5453     }
5454     break;
5455 
5456   case Instruction::LShr:
5457     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5458       // 'lshr x, C' produces [0, UINT_MAX >> C].
5459       Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
5460     } else if (match(BO.getOperand(0), m_APInt(C))) {
5461       // 'lshr C, x' produces [C >> (Width-1), C].
5462       unsigned ShiftAmount = Width - 1;
5463       if (!C->isNullValue() && IIQ.isExact(&BO))
5464         ShiftAmount = C->countTrailingZeros();
5465       Lower = C->lshr(ShiftAmount);
5466       Upper = *C + 1;
5467     }
5468     break;
5469 
5470   case Instruction::Shl:
5471     if (match(BO.getOperand(0), m_APInt(C))) {
5472       if (IIQ.hasNoUnsignedWrap(&BO)) {
5473         // 'shl nuw C, x' produces [C, C << CLZ(C)]
5474         Lower = *C;
5475         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
5476       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
5477         if (C->isNegative()) {
5478           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
5479           unsigned ShiftAmount = C->countLeadingOnes() - 1;
5480           Lower = C->shl(ShiftAmount);
5481           Upper = *C + 1;
5482         } else {
5483           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
5484           unsigned ShiftAmount = C->countLeadingZeros() - 1;
5485           Lower = *C;
5486           Upper = C->shl(ShiftAmount) + 1;
5487         }
5488       }
5489     }
5490     break;
5491 
5492   case Instruction::SDiv:
5493     if (match(BO.getOperand(1), m_APInt(C))) {
5494       APInt IntMin = APInt::getSignedMinValue(Width);
5495       APInt IntMax = APInt::getSignedMaxValue(Width);
5496       if (C->isAllOnesValue()) {
5497         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
5498         //    where C != -1 and C != 0 and C != 1
5499         Lower = IntMin + 1;
5500         Upper = IntMax + 1;
5501       } else if (C->countLeadingZeros() < Width - 1) {
5502         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
5503         //    where C != -1 and C != 0 and C != 1
5504         Lower = IntMin.sdiv(*C);
5505         Upper = IntMax.sdiv(*C);
5506         if (Lower.sgt(Upper))
5507           std::swap(Lower, Upper);
5508         Upper = Upper + 1;
5509         assert(Upper != Lower && "Upper part of range has wrapped!");
5510       }
5511     } else if (match(BO.getOperand(0), m_APInt(C))) {
5512       if (C->isMinSignedValue()) {
5513         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
5514         Lower = *C;
5515         Upper = Lower.lshr(1) + 1;
5516       } else {
5517         // 'sdiv C, x' produces [-|C|, |C|].
5518         Upper = C->abs() + 1;
5519         Lower = (-Upper) + 1;
5520       }
5521     }
5522     break;
5523 
5524   case Instruction::UDiv:
5525     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5526       // 'udiv x, C' produces [0, UINT_MAX / C].
5527       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
5528     } else if (match(BO.getOperand(0), m_APInt(C))) {
5529       // 'udiv C, x' produces [0, C].
5530       Upper = *C + 1;
5531     }
5532     break;
5533 
5534   case Instruction::SRem:
5535     if (match(BO.getOperand(1), m_APInt(C))) {
5536       // 'srem x, C' produces (-|C|, |C|).
5537       Upper = C->abs();
5538       Lower = (-Upper) + 1;
5539     }
5540     break;
5541 
5542   case Instruction::URem:
5543     if (match(BO.getOperand(1), m_APInt(C)))
5544       // 'urem x, C' produces [0, C).
5545       Upper = *C;
5546     break;
5547 
5548   default:
5549     break;
5550   }
5551 }
5552 
5553 static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
5554                                   APInt &Upper) {
5555   unsigned Width = Lower.getBitWidth();
5556   const APInt *C;
5557   switch (II.getIntrinsicID()) {
5558   case Intrinsic::uadd_sat:
5559     // uadd.sat(x, C) produces [C, UINT_MAX].
5560     if (match(II.getOperand(0), m_APInt(C)) ||
5561         match(II.getOperand(1), m_APInt(C)))
5562       Lower = *C;
5563     break;
5564   case Intrinsic::sadd_sat:
5565     if (match(II.getOperand(0), m_APInt(C)) ||
5566         match(II.getOperand(1), m_APInt(C))) {
5567       if (C->isNegative()) {
5568         // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
5569         Lower = APInt::getSignedMinValue(Width);
5570         Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5571       } else {
5572         // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
5573         Lower = APInt::getSignedMinValue(Width) + *C;
5574         Upper = APInt::getSignedMaxValue(Width) + 1;
5575       }
5576     }
5577     break;
5578   case Intrinsic::usub_sat:
5579     // usub.sat(C, x) produces [0, C].
5580     if (match(II.getOperand(0), m_APInt(C)))
5581       Upper = *C + 1;
5582     // usub.sat(x, C) produces [0, UINT_MAX - C].
5583     else if (match(II.getOperand(1), m_APInt(C)))
5584       Upper = APInt::getMaxValue(Width) - *C + 1;
5585     break;
5586   case Intrinsic::ssub_sat:
5587     if (match(II.getOperand(0), m_APInt(C))) {
5588       if (C->isNegative()) {
5589         // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
5590         Lower = APInt::getSignedMinValue(Width);
5591         Upper = *C - APInt::getSignedMinValue(Width) + 1;
5592       } else {
5593         // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
5594         Lower = *C - APInt::getSignedMaxValue(Width);
5595         Upper = APInt::getSignedMaxValue(Width) + 1;
5596       }
5597     } else if (match(II.getOperand(1), m_APInt(C))) {
5598       if (C->isNegative()) {
5599         // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
5600         Lower = APInt::getSignedMinValue(Width) - *C;
5601         Upper = APInt::getSignedMaxValue(Width) + 1;
5602       } else {
5603         // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
5604         Lower = APInt::getSignedMinValue(Width);
5605         Upper = APInt::getSignedMaxValue(Width) - *C + 1;
5606       }
5607     }
5608     break;
5609   default:
5610     break;
5611   }
5612 }
5613 
5614 static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
5615                                       APInt &Upper, const InstrInfoQuery &IIQ) {
5616   const Value *LHS, *RHS;
5617   SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
5618   if (R.Flavor == SPF_UNKNOWN)
5619     return;
5620 
5621   unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5622 
5623   if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
5624     // If the negation part of the abs (in RHS) has the NSW flag,
5625     // then the result of abs(X) is [0..SIGNED_MAX],
5626     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
5627     Lower = APInt::getNullValue(BitWidth);
5628     if (match(RHS, m_Neg(m_Specific(LHS))) &&
5629         IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
5630       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5631     else
5632       Upper = APInt::getSignedMinValue(BitWidth) + 1;
5633     return;
5634   }
5635 
5636   if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
5637     // The result of -abs(X) is <= 0.
5638     Lower = APInt::getSignedMinValue(BitWidth);
5639     Upper = APInt(BitWidth, 1);
5640     return;
5641   }
5642 
5643   const APInt *C;
5644   if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
5645     return;
5646 
5647   switch (R.Flavor) {
5648     case SPF_UMIN:
5649       Upper = *C + 1;
5650       break;
5651     case SPF_UMAX:
5652       Lower = *C;
5653       break;
5654     case SPF_SMIN:
5655       Lower = APInt::getSignedMinValue(BitWidth);
5656       Upper = *C + 1;
5657       break;
5658     case SPF_SMAX:
5659       Lower = *C;
5660       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5661       break;
5662     default:
5663       break;
5664   }
5665 }
5666 
5667 ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo) {
5668   assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
5669 
5670   const APInt *C;
5671   if (match(V, m_APInt(C)))
5672     return ConstantRange(*C);
5673 
5674   InstrInfoQuery IIQ(UseInstrInfo);
5675   unsigned BitWidth = V->getType()->getScalarSizeInBits();
5676   APInt Lower = APInt(BitWidth, 0);
5677   APInt Upper = APInt(BitWidth, 0);
5678   if (auto *BO = dyn_cast<BinaryOperator>(V))
5679     setLimitsForBinOp(*BO, Lower, Upper, IIQ);
5680   else if (auto *II = dyn_cast<IntrinsicInst>(V))
5681     setLimitsForIntrinsic(*II, Lower, Upper);
5682   else if (auto *SI = dyn_cast<SelectInst>(V))
5683     setLimitsForSelectPattern(*SI, Lower, Upper, IIQ);
5684 
5685   ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
5686 
5687   if (auto *I = dyn_cast<Instruction>(V))
5688     if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
5689       CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
5690 
5691   return CR;
5692 }
5693