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