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