1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions.  This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/InstructionSimplify.h"
20 
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/CmpInstAnalysis.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/InstSimplifyFolder.h"
31 #include "llvm/Analysis/LoopAnalysisManager.h"
32 #include "llvm/Analysis/MemoryBuiltins.h"
33 #include "llvm/Analysis/OverflowInstAnalysis.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Analysis/VectorUtils.h"
36 #include "llvm/IR/ConstantRange.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/GetElementPtrTypeIterator.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Operator.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/ValueHandle.h"
46 #include "llvm/Support/KnownBits.h"
47 #include <algorithm>
48 using namespace llvm;
49 using namespace llvm::PatternMatch;
50 
51 #define DEBUG_TYPE "instsimplify"
52 
53 enum { RecursionLimit = 3 };
54 
55 STATISTIC(NumExpand,  "Number of expansions");
56 STATISTIC(NumReassoc, "Number of reassociations");
57 
58 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
59 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
60 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
61                              const SimplifyQuery &, unsigned);
62 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
63                             unsigned);
64 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
65                             const SimplifyQuery &, unsigned);
66 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
67                               unsigned);
68 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
69                                const SimplifyQuery &Q, unsigned MaxRecurse);
70 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
71 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
72 static Value *SimplifyCastInst(unsigned, Value *, Type *,
73                                const SimplifyQuery &, unsigned);
74 static Value *SimplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
75                               const SimplifyQuery &, unsigned);
76 static Value *SimplifySelectInst(Value *, Value *, Value *,
77                                  const SimplifyQuery &, unsigned);
78 
79 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
80                                      Value *FalseVal) {
81   BinaryOperator::BinaryOps BinOpCode;
82   if (auto *BO = dyn_cast<BinaryOperator>(Cond))
83     BinOpCode = BO->getOpcode();
84   else
85     return nullptr;
86 
87   CmpInst::Predicate ExpectedPred, Pred1, Pred2;
88   if (BinOpCode == BinaryOperator::Or) {
89     ExpectedPred = ICmpInst::ICMP_NE;
90   } else if (BinOpCode == BinaryOperator::And) {
91     ExpectedPred = ICmpInst::ICMP_EQ;
92   } else
93     return nullptr;
94 
95   // %A = icmp eq %TV, %FV
96   // %B = icmp eq %X, %Y (and one of these is a select operand)
97   // %C = and %A, %B
98   // %D = select %C, %TV, %FV
99   // -->
100   // %FV
101 
102   // %A = icmp ne %TV, %FV
103   // %B = icmp ne %X, %Y (and one of these is a select operand)
104   // %C = or %A, %B
105   // %D = select %C, %TV, %FV
106   // -->
107   // %TV
108   Value *X, *Y;
109   if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
110                                       m_Specific(FalseVal)),
111                              m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
112       Pred1 != Pred2 || Pred1 != ExpectedPred)
113     return nullptr;
114 
115   if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
116     return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
117 
118   return nullptr;
119 }
120 
121 /// For a boolean type or a vector of boolean type, return false or a vector
122 /// with every element false.
123 static Constant *getFalse(Type *Ty) {
124   return ConstantInt::getFalse(Ty);
125 }
126 
127 /// For a boolean type or a vector of boolean type, return true or a vector
128 /// with every element true.
129 static Constant *getTrue(Type *Ty) {
130   return ConstantInt::getTrue(Ty);
131 }
132 
133 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
134 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
135                           Value *RHS) {
136   CmpInst *Cmp = dyn_cast<CmpInst>(V);
137   if (!Cmp)
138     return false;
139   CmpInst::Predicate CPred = Cmp->getPredicate();
140   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
141   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
142     return true;
143   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
144     CRHS == LHS;
145 }
146 
147 /// Simplify comparison with true or false branch of select:
148 ///  %sel = select i1 %cond, i32 %tv, i32 %fv
149 ///  %cmp = icmp sle i32 %sel, %rhs
150 /// Compose new comparison by substituting %sel with either %tv or %fv
151 /// and see if it simplifies.
152 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
153                                  Value *RHS, Value *Cond,
154                                  const SimplifyQuery &Q, unsigned MaxRecurse,
155                                  Constant *TrueOrFalse) {
156   Value *SimplifiedCmp = SimplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
157   if (SimplifiedCmp == Cond) {
158     // %cmp simplified to the select condition (%cond).
159     return TrueOrFalse;
160   } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
161     // It didn't simplify. However, if composed comparison is equivalent
162     // to the select condition (%cond) then we can replace it.
163     return TrueOrFalse;
164   }
165   return SimplifiedCmp;
166 }
167 
168 /// Simplify comparison with true branch of select
169 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
170                                      Value *RHS, Value *Cond,
171                                      const SimplifyQuery &Q,
172                                      unsigned MaxRecurse) {
173   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
174                             getTrue(Cond->getType()));
175 }
176 
177 /// Simplify comparison with false branch of select
178 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
179                                       Value *RHS, Value *Cond,
180                                       const SimplifyQuery &Q,
181                                       unsigned MaxRecurse) {
182   return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
183                             getFalse(Cond->getType()));
184 }
185 
186 /// We know comparison with both branches of select can be simplified, but they
187 /// are not equal. This routine handles some logical simplifications.
188 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
189                                                Value *Cond,
190                                                const SimplifyQuery &Q,
191                                                unsigned MaxRecurse) {
192   // If the false value simplified to false, then the result of the compare
193   // is equal to "Cond && TCmp".  This also catches the case when the false
194   // value simplified to false and the true value to true, returning "Cond".
195   // Folding select to and/or isn't poison-safe in general; impliesPoison
196   // checks whether folding it does not convert a well-defined value into
197   // poison.
198   if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
199     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
200       return V;
201   // If the true value simplified to true, then the result of the compare
202   // is equal to "Cond || FCmp".
203   if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
204     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
205       return V;
206   // Finally, if the false value simplified to true and the true value to
207   // false, then the result of the compare is equal to "!Cond".
208   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
209     if (Value *V = SimplifyXorInst(
210             Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
211       return V;
212   return nullptr;
213 }
214 
215 /// Does the given value dominate the specified phi node?
216 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
217   Instruction *I = dyn_cast<Instruction>(V);
218   if (!I)
219     // Arguments and constants dominate all instructions.
220     return true;
221 
222   // If we are processing instructions (and/or basic blocks) that have not been
223   // fully added to a function, the parent nodes may still be null. Simply
224   // return the conservative answer in these cases.
225   if (!I->getParent() || !P->getParent() || !I->getFunction())
226     return false;
227 
228   // If we have a DominatorTree then do a precise test.
229   if (DT)
230     return DT->dominates(I, P);
231 
232   // Otherwise, if the instruction is in the entry block and is not an invoke,
233   // then it obviously dominates all phi nodes.
234   if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
235       !isa<CallBrInst>(I))
236     return true;
237 
238   return false;
239 }
240 
241 /// Try to simplify a binary operator of form "V op OtherOp" where V is
242 /// "(B0 opex B1)" by distributing 'op' across 'opex' as
243 /// "(B0 op OtherOp) opex (B1 op OtherOp)".
244 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
245                           Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
246                           const SimplifyQuery &Q, unsigned MaxRecurse) {
247   auto *B = dyn_cast<BinaryOperator>(V);
248   if (!B || B->getOpcode() != OpcodeToExpand)
249     return nullptr;
250   Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
251   Value *L = SimplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(),
252                            MaxRecurse);
253   if (!L)
254     return nullptr;
255   Value *R = SimplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(),
256                            MaxRecurse);
257   if (!R)
258     return nullptr;
259 
260   // Does the expanded pair of binops simplify to the existing binop?
261   if ((L == B0 && R == B1) ||
262       (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
263     ++NumExpand;
264     return B;
265   }
266 
267   // Otherwise, return "L op' R" if it simplifies.
268   Value *S = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
269   if (!S)
270     return nullptr;
271 
272   ++NumExpand;
273   return S;
274 }
275 
276 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
277 /// distributing op over op'.
278 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode,
279                                      Value *L, Value *R,
280                                      Instruction::BinaryOps OpcodeToExpand,
281                                      const SimplifyQuery &Q,
282                                      unsigned MaxRecurse) {
283   // Recursion is always used, so bail out at once if we already hit the limit.
284   if (!MaxRecurse--)
285     return nullptr;
286 
287   if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
288     return V;
289   if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
290     return V;
291   return nullptr;
292 }
293 
294 /// Generic simplifications for associative binary operations.
295 /// Returns the simpler value, or null if none was found.
296 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
297                                        Value *LHS, Value *RHS,
298                                        const SimplifyQuery &Q,
299                                        unsigned MaxRecurse) {
300   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
301 
302   // Recursion is always used, so bail out at once if we already hit the limit.
303   if (!MaxRecurse--)
304     return nullptr;
305 
306   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
307   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
308 
309   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
310   if (Op0 && Op0->getOpcode() == Opcode) {
311     Value *A = Op0->getOperand(0);
312     Value *B = Op0->getOperand(1);
313     Value *C = RHS;
314 
315     // Does "B op C" simplify?
316     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
317       // It does!  Return "A op V" if it simplifies or is already available.
318       // If V equals B then "A op V" is just the LHS.
319       if (V == B) return LHS;
320       // Otherwise return "A op V" if it simplifies.
321       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
322         ++NumReassoc;
323         return W;
324       }
325     }
326   }
327 
328   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
329   if (Op1 && Op1->getOpcode() == Opcode) {
330     Value *A = LHS;
331     Value *B = Op1->getOperand(0);
332     Value *C = Op1->getOperand(1);
333 
334     // Does "A op B" simplify?
335     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
336       // It does!  Return "V op C" if it simplifies or is already available.
337       // If V equals B then "V op C" is just the RHS.
338       if (V == B) return RHS;
339       // Otherwise return "V op C" if it simplifies.
340       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
341         ++NumReassoc;
342         return W;
343       }
344     }
345   }
346 
347   // The remaining transforms require commutativity as well as associativity.
348   if (!Instruction::isCommutative(Opcode))
349     return nullptr;
350 
351   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
352   if (Op0 && Op0->getOpcode() == Opcode) {
353     Value *A = Op0->getOperand(0);
354     Value *B = Op0->getOperand(1);
355     Value *C = RHS;
356 
357     // Does "C op A" simplify?
358     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
359       // It does!  Return "V op B" if it simplifies or is already available.
360       // If V equals A then "V op B" is just the LHS.
361       if (V == A) return LHS;
362       // Otherwise return "V op B" if it simplifies.
363       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
364         ++NumReassoc;
365         return W;
366       }
367     }
368   }
369 
370   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
371   if (Op1 && Op1->getOpcode() == Opcode) {
372     Value *A = LHS;
373     Value *B = Op1->getOperand(0);
374     Value *C = Op1->getOperand(1);
375 
376     // Does "C op A" simplify?
377     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
378       // It does!  Return "B op V" if it simplifies or is already available.
379       // If V equals C then "B op V" is just the RHS.
380       if (V == C) return RHS;
381       // Otherwise return "B op V" if it simplifies.
382       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
383         ++NumReassoc;
384         return W;
385       }
386     }
387   }
388 
389   return nullptr;
390 }
391 
392 /// In the case of a binary operation with a select instruction as an operand,
393 /// try to simplify the binop by seeing whether evaluating it on both branches
394 /// of the select results in the same value. Returns the common value if so,
395 /// otherwise returns null.
396 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
397                                     Value *RHS, const SimplifyQuery &Q,
398                                     unsigned MaxRecurse) {
399   // Recursion is always used, so bail out at once if we already hit the limit.
400   if (!MaxRecurse--)
401     return nullptr;
402 
403   SelectInst *SI;
404   if (isa<SelectInst>(LHS)) {
405     SI = cast<SelectInst>(LHS);
406   } else {
407     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
408     SI = cast<SelectInst>(RHS);
409   }
410 
411   // Evaluate the BinOp on the true and false branches of the select.
412   Value *TV;
413   Value *FV;
414   if (SI == LHS) {
415     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
416     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
417   } else {
418     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
419     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
420   }
421 
422   // If they simplified to the same value, then return the common value.
423   // If they both failed to simplify then return null.
424   if (TV == FV)
425     return TV;
426 
427   // If one branch simplified to undef, return the other one.
428   if (TV && Q.isUndefValue(TV))
429     return FV;
430   if (FV && Q.isUndefValue(FV))
431     return TV;
432 
433   // If applying the operation did not change the true and false select values,
434   // then the result of the binop is the select itself.
435   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
436     return SI;
437 
438   // If one branch simplified and the other did not, and the simplified
439   // value is equal to the unsimplified one, return the simplified value.
440   // For example, select (cond, X, X & Z) & Z -> X & Z.
441   if ((FV && !TV) || (TV && !FV)) {
442     // Check that the simplified value has the form "X op Y" where "op" is the
443     // same as the original operation.
444     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
445     if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
446       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
447       // We already know that "op" is the same as for the simplified value.  See
448       // if the operands match too.  If so, return the simplified value.
449       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
450       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
451       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
452       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
453           Simplified->getOperand(1) == UnsimplifiedRHS)
454         return Simplified;
455       if (Simplified->isCommutative() &&
456           Simplified->getOperand(1) == UnsimplifiedLHS &&
457           Simplified->getOperand(0) == UnsimplifiedRHS)
458         return Simplified;
459     }
460   }
461 
462   return nullptr;
463 }
464 
465 /// In the case of a comparison with a select instruction, try to simplify the
466 /// comparison by seeing whether both branches of the select result in the same
467 /// value. Returns the common value if so, otherwise returns null.
468 /// For example, if we have:
469 ///  %tmp = select i1 %cmp, i32 1, i32 2
470 ///  %cmp1 = icmp sle i32 %tmp, 3
471 /// We can simplify %cmp1 to true, because both branches of select are
472 /// less than 3. We compose new comparison by substituting %tmp with both
473 /// branches of select and see if it can be simplified.
474 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
475                                   Value *RHS, const SimplifyQuery &Q,
476                                   unsigned MaxRecurse) {
477   // Recursion is always used, so bail out at once if we already hit the limit.
478   if (!MaxRecurse--)
479     return nullptr;
480 
481   // Make sure the select is on the LHS.
482   if (!isa<SelectInst>(LHS)) {
483     std::swap(LHS, RHS);
484     Pred = CmpInst::getSwappedPredicate(Pred);
485   }
486   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
487   SelectInst *SI = cast<SelectInst>(LHS);
488   Value *Cond = SI->getCondition();
489   Value *TV = SI->getTrueValue();
490   Value *FV = SI->getFalseValue();
491 
492   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
493   // Does "cmp TV, RHS" simplify?
494   Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
495   if (!TCmp)
496     return nullptr;
497 
498   // Does "cmp FV, RHS" simplify?
499   Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
500   if (!FCmp)
501     return nullptr;
502 
503   // If both sides simplified to the same value, then use it as the result of
504   // the original comparison.
505   if (TCmp == FCmp)
506     return TCmp;
507 
508   // The remaining cases only make sense if the select condition has the same
509   // type as the result of the comparison, so bail out if this is not so.
510   if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
511     return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
512 
513   return nullptr;
514 }
515 
516 /// In the case of a binary operation with an operand that is a PHI instruction,
517 /// try to simplify the binop by seeing whether evaluating it on the incoming
518 /// phi values yields the same result for every value. If so returns the common
519 /// value, otherwise returns null.
520 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
521                                  Value *RHS, const SimplifyQuery &Q,
522                                  unsigned MaxRecurse) {
523   // Recursion is always used, so bail out at once if we already hit the limit.
524   if (!MaxRecurse--)
525     return nullptr;
526 
527   PHINode *PI;
528   if (isa<PHINode>(LHS)) {
529     PI = cast<PHINode>(LHS);
530     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
531     if (!valueDominatesPHI(RHS, PI, Q.DT))
532       return nullptr;
533   } else {
534     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
535     PI = cast<PHINode>(RHS);
536     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
537     if (!valueDominatesPHI(LHS, PI, Q.DT))
538       return nullptr;
539   }
540 
541   // Evaluate the BinOp on the incoming phi values.
542   Value *CommonValue = nullptr;
543   for (Value *Incoming : PI->incoming_values()) {
544     // If the incoming value is the phi node itself, it can safely be skipped.
545     if (Incoming == PI) continue;
546     Value *V = PI == LHS ?
547       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
548       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
549     // If the operation failed to simplify, or simplified to a different value
550     // to previously, then give up.
551     if (!V || (CommonValue && V != CommonValue))
552       return nullptr;
553     CommonValue = V;
554   }
555 
556   return CommonValue;
557 }
558 
559 /// In the case of a comparison with a PHI instruction, try to simplify the
560 /// comparison by seeing whether comparing with all of the incoming phi values
561 /// yields the same result every time. If so returns the common result,
562 /// otherwise returns null.
563 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
564                                const SimplifyQuery &Q, unsigned MaxRecurse) {
565   // Recursion is always used, so bail out at once if we already hit the limit.
566   if (!MaxRecurse--)
567     return nullptr;
568 
569   // Make sure the phi is on the LHS.
570   if (!isa<PHINode>(LHS)) {
571     std::swap(LHS, RHS);
572     Pred = CmpInst::getSwappedPredicate(Pred);
573   }
574   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
575   PHINode *PI = cast<PHINode>(LHS);
576 
577   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
578   if (!valueDominatesPHI(RHS, PI, Q.DT))
579     return nullptr;
580 
581   // Evaluate the BinOp on the incoming phi values.
582   Value *CommonValue = nullptr;
583   for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
584     Value *Incoming = PI->getIncomingValue(u);
585     Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
586     // If the incoming value is the phi node itself, it can safely be skipped.
587     if (Incoming == PI) continue;
588     // Change the context instruction to the "edge" that flows into the phi.
589     // This is important because that is where incoming is actually "evaluated"
590     // even though it is used later somewhere else.
591     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
592                                MaxRecurse);
593     // If the operation failed to simplify, or simplified to a different value
594     // to previously, then give up.
595     if (!V || (CommonValue && V != CommonValue))
596       return nullptr;
597     CommonValue = V;
598   }
599 
600   return CommonValue;
601 }
602 
603 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
604                                        Value *&Op0, Value *&Op1,
605                                        const SimplifyQuery &Q) {
606   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
607     if (auto *CRHS = dyn_cast<Constant>(Op1))
608       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
609 
610     // Canonicalize the constant to the RHS if this is a commutative operation.
611     if (Instruction::isCommutative(Opcode))
612       std::swap(Op0, Op1);
613   }
614   return nullptr;
615 }
616 
617 /// Given operands for an Add, see if we can fold the result.
618 /// If not, this returns null.
619 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
620                               const SimplifyQuery &Q, unsigned MaxRecurse) {
621   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
622     return C;
623 
624   // X + poison -> poison
625   if (isa<PoisonValue>(Op1))
626     return Op1;
627 
628   // X + undef -> undef
629   if (Q.isUndefValue(Op1))
630     return Op1;
631 
632   // X + 0 -> X
633   if (match(Op1, m_Zero()))
634     return Op0;
635 
636   // If two operands are negative, return 0.
637   if (isKnownNegation(Op0, Op1))
638     return Constant::getNullValue(Op0->getType());
639 
640   // X + (Y - X) -> Y
641   // (Y - X) + X -> Y
642   // Eg: X + -X -> 0
643   Value *Y = nullptr;
644   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
645       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
646     return Y;
647 
648   // X + ~X -> -1   since   ~X = -X-1
649   Type *Ty = Op0->getType();
650   if (match(Op0, m_Not(m_Specific(Op1))) ||
651       match(Op1, m_Not(m_Specific(Op0))))
652     return Constant::getAllOnesValue(Ty);
653 
654   // add nsw/nuw (xor Y, signmask), signmask --> Y
655   // The no-wrapping add guarantees that the top bit will be set by the add.
656   // Therefore, the xor must be clearing the already set sign bit of Y.
657   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
658       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
659     return Y;
660 
661   // add nuw %x, -1  ->  -1, because %x can only be 0.
662   if (IsNUW && match(Op1, m_AllOnes()))
663     return Op1; // Which is -1.
664 
665   /// i1 add -> xor.
666   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
667     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
668       return V;
669 
670   // Try some generic simplifications for associative operations.
671   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
672                                           MaxRecurse))
673     return V;
674 
675   // Threading Add over selects and phi nodes is pointless, so don't bother.
676   // Threading over the select in "A + select(cond, B, C)" means evaluating
677   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
678   // only if B and C are equal.  If B and C are equal then (since we assume
679   // that operands have already been simplified) "select(cond, B, C)" should
680   // have been simplified to the common value of B and C already.  Analysing
681   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
682   // for threading over phi nodes.
683 
684   return nullptr;
685 }
686 
687 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
688                              const SimplifyQuery &Query) {
689   return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
690 }
691 
692 /// Compute the base pointer and cumulative constant offsets for V.
693 ///
694 /// This strips all constant offsets off of V, leaving it the base pointer, and
695 /// accumulates the total constant offset applied in the returned constant.
696 /// It returns zero if there are no constant offsets applied.
697 ///
698 /// This is very similar to stripAndAccumulateConstantOffsets(), except it
699 /// normalizes the offset bitwidth to the stripped pointer type, not the
700 /// original pointer type.
701 static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
702                                             bool AllowNonInbounds = false) {
703   assert(V->getType()->isPtrOrPtrVectorTy());
704 
705   APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
706   V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
707   // As that strip may trace through `addrspacecast`, need to sext or trunc
708   // the offset calculated.
709   return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
710 }
711 
712 /// Compute the constant difference between two pointer values.
713 /// If the difference is not a constant, returns zero.
714 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
715                                           Value *RHS) {
716   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
717   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
718 
719   // If LHS and RHS are not related via constant offsets to the same base
720   // value, there is nothing we can do here.
721   if (LHS != RHS)
722     return nullptr;
723 
724   // Otherwise, the difference of LHS - RHS can be computed as:
725   //    LHS - RHS
726   //  = (LHSOffset + Base) - (RHSOffset + Base)
727   //  = LHSOffset - RHSOffset
728   Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
729   if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
730     Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
731   return Res;
732 }
733 
734 /// Given operands for a Sub, see if we can fold the result.
735 /// If not, this returns null.
736 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
737                               const SimplifyQuery &Q, unsigned MaxRecurse) {
738   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
739     return C;
740 
741   // X - poison -> poison
742   // poison - X -> poison
743   if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
744     return PoisonValue::get(Op0->getType());
745 
746   // X - undef -> undef
747   // undef - X -> undef
748   if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
749     return UndefValue::get(Op0->getType());
750 
751   // X - 0 -> X
752   if (match(Op1, m_Zero()))
753     return Op0;
754 
755   // X - X -> 0
756   if (Op0 == Op1)
757     return Constant::getNullValue(Op0->getType());
758 
759   // Is this a negation?
760   if (match(Op0, m_Zero())) {
761     // 0 - X -> 0 if the sub is NUW.
762     if (isNUW)
763       return Constant::getNullValue(Op0->getType());
764 
765     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
766     if (Known.Zero.isMaxSignedValue()) {
767       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
768       // Op1 must be 0 because negating the minimum signed value is undefined.
769       if (isNSW)
770         return Constant::getNullValue(Op0->getType());
771 
772       // 0 - X -> X if X is 0 or the minimum signed value.
773       return Op1;
774     }
775   }
776 
777   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
778   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
779   Value *X = nullptr, *Y = nullptr, *Z = Op1;
780   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
781     // See if "V === Y - Z" simplifies.
782     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
783       // It does!  Now see if "X + V" simplifies.
784       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
785         // It does, we successfully reassociated!
786         ++NumReassoc;
787         return W;
788       }
789     // See if "V === X - Z" simplifies.
790     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
791       // It does!  Now see if "Y + V" simplifies.
792       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
793         // It does, we successfully reassociated!
794         ++NumReassoc;
795         return W;
796       }
797   }
798 
799   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
800   // For example, X - (X + 1) -> -1
801   X = Op0;
802   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
803     // See if "V === X - Y" simplifies.
804     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
805       // It does!  Now see if "V - Z" simplifies.
806       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
807         // It does, we successfully reassociated!
808         ++NumReassoc;
809         return W;
810       }
811     // See if "V === X - Z" simplifies.
812     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
813       // It does!  Now see if "V - Y" simplifies.
814       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
815         // It does, we successfully reassociated!
816         ++NumReassoc;
817         return W;
818       }
819   }
820 
821   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
822   // For example, X - (X - Y) -> Y.
823   Z = Op0;
824   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
825     // See if "V === Z - X" simplifies.
826     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
827       // It does!  Now see if "V + Y" simplifies.
828       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
829         // It does, we successfully reassociated!
830         ++NumReassoc;
831         return W;
832       }
833 
834   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
835   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
836       match(Op1, m_Trunc(m_Value(Y))))
837     if (X->getType() == Y->getType())
838       // See if "V === X - Y" simplifies.
839       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
840         // It does!  Now see if "trunc V" simplifies.
841         if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
842                                         Q, MaxRecurse - 1))
843           // It does, return the simplified "trunc V".
844           return W;
845 
846   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
847   if (match(Op0, m_PtrToInt(m_Value(X))) &&
848       match(Op1, m_PtrToInt(m_Value(Y))))
849     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
850       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
851 
852   // i1 sub -> xor.
853   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
854     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
855       return V;
856 
857   // Threading Sub over selects and phi nodes is pointless, so don't bother.
858   // Threading over the select in "A - select(cond, B, C)" means evaluating
859   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
860   // only if B and C are equal.  If B and C are equal then (since we assume
861   // that operands have already been simplified) "select(cond, B, C)" should
862   // have been simplified to the common value of B and C already.  Analysing
863   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
864   // for threading over phi nodes.
865 
866   return nullptr;
867 }
868 
869 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
870                              const SimplifyQuery &Q) {
871   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
872 }
873 
874 /// Given operands for a Mul, see if we can fold the result.
875 /// If not, this returns null.
876 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
877                               unsigned MaxRecurse) {
878   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
879     return C;
880 
881   // X * poison -> poison
882   if (isa<PoisonValue>(Op1))
883     return Op1;
884 
885   // X * undef -> 0
886   // X * 0 -> 0
887   if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
888     return Constant::getNullValue(Op0->getType());
889 
890   // X * 1 -> X
891   if (match(Op1, m_One()))
892     return Op0;
893 
894   // (X / Y) * Y -> X if the division is exact.
895   Value *X = nullptr;
896   if (Q.IIQ.UseInstrInfo &&
897       (match(Op0,
898              m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) ||     // (X / Y) * Y
899        match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
900     return X;
901 
902   // i1 mul -> and.
903   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
904     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
905       return V;
906 
907   // Try some generic simplifications for associative operations.
908   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
909                                           MaxRecurse))
910     return V;
911 
912   // Mul distributes over Add. Try some generic simplifications based on this.
913   if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
914                                         Instruction::Add, Q, MaxRecurse))
915     return V;
916 
917   // If the operation is with the result of a select instruction, check whether
918   // operating on either branch of the select always yields the same value.
919   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
920     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
921                                          MaxRecurse))
922       return V;
923 
924   // If the operation is with the result of a phi instruction, check whether
925   // operating on all incoming values of the phi always yields the same value.
926   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
927     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
928                                       MaxRecurse))
929       return V;
930 
931   return nullptr;
932 }
933 
934 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
935   return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
936 }
937 
938 /// Check for common or similar folds of integer division or integer remainder.
939 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
940 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
941                              Value *Op1, const SimplifyQuery &Q) {
942   bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
943   bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
944 
945   Type *Ty = Op0->getType();
946 
947   // X / undef -> poison
948   // X % undef -> poison
949   if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
950     return PoisonValue::get(Ty);
951 
952   // X / 0 -> poison
953   // X % 0 -> poison
954   // We don't need to preserve faults!
955   if (match(Op1, m_Zero()))
956     return PoisonValue::get(Ty);
957 
958   // If any element of a constant divisor fixed width vector is zero or undef
959   // the behavior is undefined and we can fold the whole op to poison.
960   auto *Op1C = dyn_cast<Constant>(Op1);
961   auto *VTy = dyn_cast<FixedVectorType>(Ty);
962   if (Op1C && VTy) {
963     unsigned NumElts = VTy->getNumElements();
964     for (unsigned i = 0; i != NumElts; ++i) {
965       Constant *Elt = Op1C->getAggregateElement(i);
966       if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
967         return PoisonValue::get(Ty);
968     }
969   }
970 
971   // poison / X -> poison
972   // poison % X -> poison
973   if (isa<PoisonValue>(Op0))
974     return Op0;
975 
976   // undef / X -> 0
977   // undef % X -> 0
978   if (Q.isUndefValue(Op0))
979     return Constant::getNullValue(Ty);
980 
981   // 0 / X -> 0
982   // 0 % X -> 0
983   if (match(Op0, m_Zero()))
984     return Constant::getNullValue(Op0->getType());
985 
986   // X / X -> 1
987   // X % X -> 0
988   if (Op0 == Op1)
989     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
990 
991   // X / 1 -> X
992   // X % 1 -> 0
993   // If this is a boolean op (single-bit element type), we can't have
994   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
995   // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
996   Value *X;
997   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
998       (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
999     return IsDiv ? Op0 : Constant::getNullValue(Ty);
1000 
1001   // If X * Y does not overflow, then:
1002   //   X * Y / Y -> X
1003   //   X * Y % Y -> 0
1004   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1005     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1006     // The multiplication can't overflow if it is defined not to, or if
1007     // X == A / Y for some A.
1008     if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1009         (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1010         (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1011         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1012       return IsDiv ? X : Constant::getNullValue(Op0->getType());
1013     }
1014   }
1015 
1016   return nullptr;
1017 }
1018 
1019 /// Given a predicate and two operands, return true if the comparison is true.
1020 /// This is a helper for div/rem simplification where we return some other value
1021 /// when we can prove a relationship between the operands.
1022 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
1023                        const SimplifyQuery &Q, unsigned MaxRecurse) {
1024   Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
1025   Constant *C = dyn_cast_or_null<Constant>(V);
1026   return (C && C->isAllOnesValue());
1027 }
1028 
1029 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
1030 /// to simplify X % Y to X.
1031 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
1032                       unsigned MaxRecurse, bool IsSigned) {
1033   // Recursion is always used, so bail out at once if we already hit the limit.
1034   if (!MaxRecurse--)
1035     return false;
1036 
1037   if (IsSigned) {
1038     // |X| / |Y| --> 0
1039     //
1040     // We require that 1 operand is a simple constant. That could be extended to
1041     // 2 variables if we computed the sign bit for each.
1042     //
1043     // Make sure that a constant is not the minimum signed value because taking
1044     // the abs() of that is undefined.
1045     Type *Ty = X->getType();
1046     const APInt *C;
1047     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1048       // Is the variable divisor magnitude always greater than the constant
1049       // dividend magnitude?
1050       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1051       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1052       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1053       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1054           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1055         return true;
1056     }
1057     if (match(Y, m_APInt(C))) {
1058       // Special-case: we can't take the abs() of a minimum signed value. If
1059       // that's the divisor, then all we have to do is prove that the dividend
1060       // is also not the minimum signed value.
1061       if (C->isMinSignedValue())
1062         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1063 
1064       // Is the variable dividend magnitude always less than the constant
1065       // divisor magnitude?
1066       // |X| < |C| --> X > -abs(C) and X < abs(C)
1067       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1068       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1069       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1070           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1071         return true;
1072     }
1073     return false;
1074   }
1075 
1076   // IsSigned == false.
1077 
1078   // Is the unsigned dividend known to be less than a constant divisor?
1079   // TODO: Convert this (and above) to range analysis
1080   //      ("computeConstantRangeIncludingKnownBits")?
1081   const APInt *C;
1082   if (match(Y, m_APInt(C)) &&
1083       computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
1084     return true;
1085 
1086   // Try again for any divisor:
1087   // Is the dividend unsigned less than the divisor?
1088   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1089 }
1090 
1091 /// These are simplifications common to SDiv and UDiv.
1092 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1093                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1094   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1095     return C;
1096 
1097   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
1098     return V;
1099 
1100   bool IsSigned = Opcode == Instruction::SDiv;
1101 
1102   // (X rem Y) / Y -> 0
1103   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1104       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1105     return Constant::getNullValue(Op0->getType());
1106 
1107   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1108   ConstantInt *C1, *C2;
1109   if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
1110       match(Op1, m_ConstantInt(C2))) {
1111     bool Overflow;
1112     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1113     if (Overflow)
1114       return Constant::getNullValue(Op0->getType());
1115   }
1116 
1117   // If the operation is with the result of a select instruction, check whether
1118   // operating on either branch of the select always yields the same value.
1119   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1120     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1121       return V;
1122 
1123   // If the operation is with the result of a phi instruction, check whether
1124   // operating on all incoming values of the phi always yields the same value.
1125   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1126     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1127       return V;
1128 
1129   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1130     return Constant::getNullValue(Op0->getType());
1131 
1132   return nullptr;
1133 }
1134 
1135 /// These are simplifications common to SRem and URem.
1136 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1137                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1138   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1139     return C;
1140 
1141   if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
1142     return V;
1143 
1144   // (X % Y) % Y -> X % Y
1145   if ((Opcode == Instruction::SRem &&
1146        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1147       (Opcode == Instruction::URem &&
1148        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1149     return Op0;
1150 
1151   // (X << Y) % X -> 0
1152   if (Q.IIQ.UseInstrInfo &&
1153       ((Opcode == Instruction::SRem &&
1154         match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1155        (Opcode == Instruction::URem &&
1156         match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1157     return Constant::getNullValue(Op0->getType());
1158 
1159   // If the operation is with the result of a select instruction, check whether
1160   // operating on either branch of the select always yields the same value.
1161   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1162     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1163       return V;
1164 
1165   // If the operation is with the result of a phi instruction, check whether
1166   // operating on all incoming values of the phi always yields the same value.
1167   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1168     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1169       return V;
1170 
1171   // If X / Y == 0, then X % Y == X.
1172   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1173     return Op0;
1174 
1175   return nullptr;
1176 }
1177 
1178 /// Given operands for an SDiv, see if we can fold the result.
1179 /// If not, this returns null.
1180 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1181                                unsigned MaxRecurse) {
1182   // If two operands are negated and no signed overflow, return -1.
1183   if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1184     return Constant::getAllOnesValue(Op0->getType());
1185 
1186   return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1187 }
1188 
1189 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1190   return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1191 }
1192 
1193 /// Given operands for a UDiv, see if we can fold the result.
1194 /// If not, this returns null.
1195 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1196                                unsigned MaxRecurse) {
1197   return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1198 }
1199 
1200 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1201   return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1202 }
1203 
1204 /// Given operands for an SRem, see if we can fold the result.
1205 /// If not, this returns null.
1206 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1207                                unsigned MaxRecurse) {
1208   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1209   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1210   Value *X;
1211   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1212     return ConstantInt::getNullValue(Op0->getType());
1213 
1214   // If the two operands are negated, return 0.
1215   if (isKnownNegation(Op0, Op1))
1216     return ConstantInt::getNullValue(Op0->getType());
1217 
1218   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1219 }
1220 
1221 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1222   return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1223 }
1224 
1225 /// Given operands for a URem, see if we can fold the result.
1226 /// If not, this returns null.
1227 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1228                                unsigned MaxRecurse) {
1229   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1230 }
1231 
1232 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1233   return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1234 }
1235 
1236 /// Returns true if a shift by \c Amount always yields poison.
1237 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1238   Constant *C = dyn_cast<Constant>(Amount);
1239   if (!C)
1240     return false;
1241 
1242   // X shift by undef -> poison because it may shift by the bitwidth.
1243   if (Q.isUndefValue(C))
1244     return true;
1245 
1246   // Shifting by the bitwidth or more is undefined.
1247   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1248     if (CI->getValue().uge(CI->getType()->getScalarSizeInBits()))
1249       return true;
1250 
1251   // If all lanes of a vector shift are undefined the whole shift is.
1252   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1253     for (unsigned I = 0,
1254                   E = cast<FixedVectorType>(C->getType())->getNumElements();
1255          I != E; ++I)
1256       if (!isPoisonShift(C->getAggregateElement(I), Q))
1257         return false;
1258     return true;
1259   }
1260 
1261   return false;
1262 }
1263 
1264 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1265 /// If not, this returns null.
1266 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1267                             Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1268                             unsigned MaxRecurse) {
1269   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1270     return C;
1271 
1272   // poison shift by X -> poison
1273   if (isa<PoisonValue>(Op0))
1274     return Op0;
1275 
1276   // 0 shift by X -> 0
1277   if (match(Op0, m_Zero()))
1278     return Constant::getNullValue(Op0->getType());
1279 
1280   // X shift by 0 -> X
1281   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1282   // would be poison.
1283   Value *X;
1284   if (match(Op1, m_Zero()) ||
1285       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1286     return Op0;
1287 
1288   // Fold undefined shifts.
1289   if (isPoisonShift(Op1, Q))
1290     return PoisonValue::get(Op0->getType());
1291 
1292   // If the operation is with the result of a select instruction, check whether
1293   // operating on either branch of the select always yields the same value.
1294   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1295     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1296       return V;
1297 
1298   // If the operation is with the result of a phi instruction, check whether
1299   // operating on all incoming values of the phi always yields the same value.
1300   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1301     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1302       return V;
1303 
1304   // If any bits in the shift amount make that value greater than or equal to
1305   // the number of bits in the type, the shift is undefined.
1306   KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1307   if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1308     return PoisonValue::get(Op0->getType());
1309 
1310   // If all valid bits in the shift amount are known zero, the first operand is
1311   // unchanged.
1312   unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1313   if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1314     return Op0;
1315 
1316   // Check for nsw shl leading to a poison value.
1317   if (IsNSW) {
1318     assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1319     KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1320     KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1321 
1322     if (KnownVal.Zero.isSignBitSet())
1323       KnownShl.Zero.setSignBit();
1324     if (KnownVal.One.isSignBitSet())
1325       KnownShl.One.setSignBit();
1326 
1327     if (KnownShl.hasConflict())
1328       return PoisonValue::get(Op0->getType());
1329   }
1330 
1331   return nullptr;
1332 }
1333 
1334 /// Given operands for an Shl, LShr or AShr, see if we can
1335 /// fold the result.  If not, this returns null.
1336 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1337                                  Value *Op1, bool isExact, const SimplifyQuery &Q,
1338                                  unsigned MaxRecurse) {
1339   if (Value *V =
1340           SimplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1341     return V;
1342 
1343   // X >> X -> 0
1344   if (Op0 == Op1)
1345     return Constant::getNullValue(Op0->getType());
1346 
1347   // undef >> X -> 0
1348   // undef >> X -> undef (if it's exact)
1349   if (Q.isUndefValue(Op0))
1350     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1351 
1352   // The low bit cannot be shifted out of an exact shift if it is set.
1353   if (isExact) {
1354     KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1355     if (Op0Known.One[0])
1356       return Op0;
1357   }
1358 
1359   return nullptr;
1360 }
1361 
1362 /// Given operands for an Shl, see if we can fold the result.
1363 /// If not, this returns null.
1364 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1365                               const SimplifyQuery &Q, unsigned MaxRecurse) {
1366   if (Value *V =
1367           SimplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse))
1368     return V;
1369 
1370   // undef << X -> 0
1371   // undef << X -> undef if (if it's NSW/NUW)
1372   if (Q.isUndefValue(Op0))
1373     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1374 
1375   // (X >> A) << A -> X
1376   Value *X;
1377   if (Q.IIQ.UseInstrInfo &&
1378       match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1379     return X;
1380 
1381   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1382   if (isNUW && match(Op0, m_Negative()))
1383     return Op0;
1384   // NOTE: could use computeKnownBits() / LazyValueInfo,
1385   // but the cost-benefit analysis suggests it isn't worth it.
1386 
1387   return nullptr;
1388 }
1389 
1390 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1391                              const SimplifyQuery &Q) {
1392   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1393 }
1394 
1395 /// Given operands for an LShr, see if we can fold the result.
1396 /// If not, this returns null.
1397 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1398                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1399   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1400                                     MaxRecurse))
1401       return V;
1402 
1403   // (X << A) >> A -> X
1404   Value *X;
1405   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1406     return X;
1407 
1408   // ((X << A) | Y) >> A -> X  if effective width of Y is not larger than A.
1409   // We can return X as we do in the above case since OR alters no bits in X.
1410   // SimplifyDemandedBits in InstCombine can do more general optimization for
1411   // bit manipulation. This pattern aims to provide opportunities for other
1412   // optimizers by supporting a simple but common case in InstSimplify.
1413   Value *Y;
1414   const APInt *ShRAmt, *ShLAmt;
1415   if (match(Op1, m_APInt(ShRAmt)) &&
1416       match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1417       *ShRAmt == *ShLAmt) {
1418     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1419     const unsigned EffWidthY = YKnown.countMaxActiveBits();
1420     if (ShRAmt->uge(EffWidthY))
1421       return X;
1422   }
1423 
1424   return nullptr;
1425 }
1426 
1427 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1428                               const SimplifyQuery &Q) {
1429   return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1430 }
1431 
1432 /// Given operands for an AShr, see if we can fold the result.
1433 /// If not, this returns null.
1434 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1435                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1436   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1437                                     MaxRecurse))
1438     return V;
1439 
1440   // -1 >>a X --> -1
1441   // (-1 << X) a>> X --> -1
1442   // Do not return Op0 because it may contain undef elements if it's a vector.
1443   if (match(Op0, m_AllOnes()) ||
1444       match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1445     return Constant::getAllOnesValue(Op0->getType());
1446 
1447   // (X << A) >> A -> X
1448   Value *X;
1449   if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1450     return X;
1451 
1452   // Arithmetic shifting an all-sign-bit value is a no-op.
1453   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1454   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1455     return Op0;
1456 
1457   return nullptr;
1458 }
1459 
1460 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1461                               const SimplifyQuery &Q) {
1462   return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1463 }
1464 
1465 /// Commuted variants are assumed to be handled by calling this function again
1466 /// with the parameters swapped.
1467 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1468                                          ICmpInst *UnsignedICmp, bool IsAnd,
1469                                          const SimplifyQuery &Q) {
1470   Value *X, *Y;
1471 
1472   ICmpInst::Predicate EqPred;
1473   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1474       !ICmpInst::isEquality(EqPred))
1475     return nullptr;
1476 
1477   ICmpInst::Predicate UnsignedPred;
1478 
1479   Value *A, *B;
1480   // Y = (A - B);
1481   if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1482     if (match(UnsignedICmp,
1483               m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1484         ICmpInst::isUnsigned(UnsignedPred)) {
1485       // A >=/<= B || (A - B) != 0  <-->  true
1486       if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1487            UnsignedPred == ICmpInst::ICMP_ULE) &&
1488           EqPred == ICmpInst::ICMP_NE && !IsAnd)
1489         return ConstantInt::getTrue(UnsignedICmp->getType());
1490       // A </> B && (A - B) == 0  <-->  false
1491       if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1492            UnsignedPred == ICmpInst::ICMP_UGT) &&
1493           EqPred == ICmpInst::ICMP_EQ && IsAnd)
1494         return ConstantInt::getFalse(UnsignedICmp->getType());
1495 
1496       // A </> B && (A - B) != 0  <-->  A </> B
1497       // A </> B || (A - B) != 0  <-->  (A - B) != 0
1498       if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1499                                           UnsignedPred == ICmpInst::ICMP_UGT))
1500         return IsAnd ? UnsignedICmp : ZeroICmp;
1501 
1502       // A <=/>= B && (A - B) == 0  <-->  (A - B) == 0
1503       // A <=/>= B || (A - B) == 0  <-->  A <=/>= B
1504       if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1505                                           UnsignedPred == ICmpInst::ICMP_UGE))
1506         return IsAnd ? ZeroICmp : UnsignedICmp;
1507     }
1508 
1509     // Given  Y = (A - B)
1510     //   Y >= A && Y != 0  --> Y >= A  iff B != 0
1511     //   Y <  A || Y == 0  --> Y <  A  iff B != 0
1512     if (match(UnsignedICmp,
1513               m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1514       if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1515           EqPred == ICmpInst::ICMP_NE &&
1516           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1517         return UnsignedICmp;
1518       if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1519           EqPred == ICmpInst::ICMP_EQ &&
1520           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1521         return UnsignedICmp;
1522     }
1523   }
1524 
1525   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1526       ICmpInst::isUnsigned(UnsignedPred))
1527     ;
1528   else if (match(UnsignedICmp,
1529                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1530            ICmpInst::isUnsigned(UnsignedPred))
1531     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1532   else
1533     return nullptr;
1534 
1535   // X > Y && Y == 0  -->  Y == 0  iff X != 0
1536   // X > Y || Y == 0  -->  X > Y   iff X != 0
1537   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1538       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1539     return IsAnd ? ZeroICmp : UnsignedICmp;
1540 
1541   // X <= Y && Y != 0  -->  X <= Y  iff X != 0
1542   // X <= Y || Y != 0  -->  Y != 0  iff X != 0
1543   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1544       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1545     return IsAnd ? UnsignedICmp : ZeroICmp;
1546 
1547   // The transforms below here are expected to be handled more generally with
1548   // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1549   // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1550   // these are candidates for removal.
1551 
1552   // X < Y && Y != 0  -->  X < Y
1553   // X < Y || Y != 0  -->  Y != 0
1554   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1555     return IsAnd ? UnsignedICmp : ZeroICmp;
1556 
1557   // X >= Y && Y == 0  -->  Y == 0
1558   // X >= Y || Y == 0  -->  X >= Y
1559   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1560     return IsAnd ? ZeroICmp : UnsignedICmp;
1561 
1562   // X < Y && Y == 0  -->  false
1563   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1564       IsAnd)
1565     return getFalse(UnsignedICmp->getType());
1566 
1567   // X >= Y || Y != 0  -->  true
1568   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1569       !IsAnd)
1570     return getTrue(UnsignedICmp->getType());
1571 
1572   return nullptr;
1573 }
1574 
1575 /// Commuted variants are assumed to be handled by calling this function again
1576 /// with the parameters swapped.
1577 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1578   ICmpInst::Predicate Pred0, Pred1;
1579   Value *A ,*B;
1580   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1581       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1582     return nullptr;
1583 
1584   // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1585   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1586   // can eliminate Op1 from this 'and'.
1587   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1588     return Op0;
1589 
1590   // Check for any combination of predicates that are guaranteed to be disjoint.
1591   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1592       (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1593       (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1594       (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1595     return getFalse(Op0->getType());
1596 
1597   return nullptr;
1598 }
1599 
1600 /// Commuted variants are assumed to be handled by calling this function again
1601 /// with the parameters swapped.
1602 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1603   ICmpInst::Predicate Pred0, Pred1;
1604   Value *A ,*B;
1605   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1606       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1607     return nullptr;
1608 
1609   // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1610   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1611   // can eliminate Op0 from this 'or'.
1612   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1613     return Op1;
1614 
1615   // Check for any combination of predicates that cover the entire range of
1616   // possibilities.
1617   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1618       (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1619       (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1620       (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1621     return getTrue(Op0->getType());
1622 
1623   return nullptr;
1624 }
1625 
1626 /// Test if a pair of compares with a shared operand and 2 constants has an
1627 /// empty set intersection, full set union, or if one compare is a superset of
1628 /// the other.
1629 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1630                                                 bool IsAnd) {
1631   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1632   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1633     return nullptr;
1634 
1635   const APInt *C0, *C1;
1636   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1637       !match(Cmp1->getOperand(1), m_APInt(C1)))
1638     return nullptr;
1639 
1640   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1641   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1642 
1643   // For and-of-compares, check if the intersection is empty:
1644   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1645   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1646     return getFalse(Cmp0->getType());
1647 
1648   // For or-of-compares, check if the union is full:
1649   // (icmp X, C0) || (icmp X, C1) --> full set --> true
1650   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1651     return getTrue(Cmp0->getType());
1652 
1653   // Is one range a superset of the other?
1654   // If this is and-of-compares, take the smaller set:
1655   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1656   // If this is or-of-compares, take the larger set:
1657   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1658   if (Range0.contains(Range1))
1659     return IsAnd ? Cmp1 : Cmp0;
1660   if (Range1.contains(Range0))
1661     return IsAnd ? Cmp0 : Cmp1;
1662 
1663   return nullptr;
1664 }
1665 
1666 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1667                                            bool IsAnd) {
1668   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1669   if (!match(Cmp0->getOperand(1), m_Zero()) ||
1670       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1671     return nullptr;
1672 
1673   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1674     return nullptr;
1675 
1676   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1677   Value *X = Cmp0->getOperand(0);
1678   Value *Y = Cmp1->getOperand(0);
1679 
1680   // If one of the compares is a masked version of a (not) null check, then
1681   // that compare implies the other, so we eliminate the other. Optionally, look
1682   // through a pointer-to-int cast to match a null check of a pointer type.
1683 
1684   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1685   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1686   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1687   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1688   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1689       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1690     return Cmp1;
1691 
1692   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1693   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1694   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1695   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1696   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1697       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1698     return Cmp0;
1699 
1700   return nullptr;
1701 }
1702 
1703 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1704                                         const InstrInfoQuery &IIQ) {
1705   // (icmp (add V, C0), C1) & (icmp V, C0)
1706   ICmpInst::Predicate Pred0, Pred1;
1707   const APInt *C0, *C1;
1708   Value *V;
1709   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1710     return nullptr;
1711 
1712   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1713     return nullptr;
1714 
1715   auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1716   if (AddInst->getOperand(1) != Op1->getOperand(1))
1717     return nullptr;
1718 
1719   Type *ITy = Op0->getType();
1720   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1721   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1722 
1723   const APInt Delta = *C1 - *C0;
1724   if (C0->isStrictlyPositive()) {
1725     if (Delta == 2) {
1726       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1727         return getFalse(ITy);
1728       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1729         return getFalse(ITy);
1730     }
1731     if (Delta == 1) {
1732       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1733         return getFalse(ITy);
1734       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1735         return getFalse(ITy);
1736     }
1737   }
1738   if (C0->getBoolValue() && isNUW) {
1739     if (Delta == 2)
1740       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1741         return getFalse(ITy);
1742     if (Delta == 1)
1743       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1744         return getFalse(ITy);
1745   }
1746 
1747   return nullptr;
1748 }
1749 
1750 /// Try to eliminate compares with signed or unsigned min/max constants.
1751 static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
1752                                                  bool IsAnd) {
1753   // Canonicalize an equality compare as Cmp0.
1754   if (Cmp1->isEquality())
1755     std::swap(Cmp0, Cmp1);
1756   if (!Cmp0->isEquality())
1757     return nullptr;
1758 
1759   // The non-equality compare must include a common operand (X). Canonicalize
1760   // the common operand as operand 0 (the predicate is swapped if the common
1761   // operand was operand 1).
1762   ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
1763   Value *X = Cmp0->getOperand(0);
1764   ICmpInst::Predicate Pred1;
1765   bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
1766   if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
1767     return nullptr;
1768   if (ICmpInst::isEquality(Pred1))
1769     return nullptr;
1770 
1771   // The equality compare must be against a constant. Flip bits if we matched
1772   // a bitwise not. Convert a null pointer constant to an integer zero value.
1773   APInt MinMaxC;
1774   const APInt *C;
1775   if (match(Cmp0->getOperand(1), m_APInt(C)))
1776     MinMaxC = HasNotOp ? ~*C : *C;
1777   else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
1778     MinMaxC = APInt::getZero(8);
1779   else
1780     return nullptr;
1781 
1782   // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
1783   if (!IsAnd) {
1784     Pred0 = ICmpInst::getInversePredicate(Pred0);
1785     Pred1 = ICmpInst::getInversePredicate(Pred1);
1786   }
1787 
1788   // Normalize to unsigned compare and unsigned min/max value.
1789   // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
1790   if (ICmpInst::isSigned(Pred1)) {
1791     Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
1792     MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
1793   }
1794 
1795   // (X != MAX) && (X < Y) --> X < Y
1796   // (X == MAX) || (X >= Y) --> X >= Y
1797   if (MinMaxC.isMaxValue())
1798     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
1799       return Cmp1;
1800 
1801   // (X != MIN) && (X > Y) -->  X > Y
1802   // (X == MIN) || (X <= Y) --> X <= Y
1803   if (MinMaxC.isMinValue())
1804     if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
1805       return Cmp1;
1806 
1807   return nullptr;
1808 }
1809 
1810 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1811                                  const SimplifyQuery &Q) {
1812   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1813     return X;
1814   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1815     return X;
1816 
1817   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1818     return X;
1819   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1820     return X;
1821 
1822   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1823     return X;
1824 
1825   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1826     return X;
1827 
1828   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1829     return X;
1830 
1831   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1832     return X;
1833   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1834     return X;
1835 
1836   return nullptr;
1837 }
1838 
1839 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1840                                        const InstrInfoQuery &IIQ) {
1841   // (icmp (add V, C0), C1) | (icmp V, C0)
1842   ICmpInst::Predicate Pred0, Pred1;
1843   const APInt *C0, *C1;
1844   Value *V;
1845   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1846     return nullptr;
1847 
1848   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1849     return nullptr;
1850 
1851   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1852   if (AddInst->getOperand(1) != Op1->getOperand(1))
1853     return nullptr;
1854 
1855   Type *ITy = Op0->getType();
1856   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1857   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1858 
1859   const APInt Delta = *C1 - *C0;
1860   if (C0->isStrictlyPositive()) {
1861     if (Delta == 2) {
1862       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1863         return getTrue(ITy);
1864       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1865         return getTrue(ITy);
1866     }
1867     if (Delta == 1) {
1868       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1869         return getTrue(ITy);
1870       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1871         return getTrue(ITy);
1872     }
1873   }
1874   if (C0->getBoolValue() && isNUW) {
1875     if (Delta == 2)
1876       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1877         return getTrue(ITy);
1878     if (Delta == 1)
1879       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1880         return getTrue(ITy);
1881   }
1882 
1883   return nullptr;
1884 }
1885 
1886 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1887                                 const SimplifyQuery &Q) {
1888   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1889     return X;
1890   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1891     return X;
1892 
1893   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1894     return X;
1895   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1896     return X;
1897 
1898   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1899     return X;
1900 
1901   if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1902     return X;
1903 
1904   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1905     return X;
1906 
1907   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1908     return X;
1909   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1910     return X;
1911 
1912   return nullptr;
1913 }
1914 
1915 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1916                                    FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1917   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1918   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1919   if (LHS0->getType() != RHS0->getType())
1920     return nullptr;
1921 
1922   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1923   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1924       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1925     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1926     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1927     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1928     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1929     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1930     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1931     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1932     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1933     if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1934         (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1935       return RHS;
1936 
1937     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1938     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1939     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1940     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1941     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1942     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1943     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1944     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1945     if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1946         (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1947       return LHS;
1948   }
1949 
1950   return nullptr;
1951 }
1952 
1953 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
1954                                   Value *Op0, Value *Op1, bool IsAnd) {
1955   // Look through casts of the 'and' operands to find compares.
1956   auto *Cast0 = dyn_cast<CastInst>(Op0);
1957   auto *Cast1 = dyn_cast<CastInst>(Op1);
1958   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1959       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1960     Op0 = Cast0->getOperand(0);
1961     Op1 = Cast1->getOperand(0);
1962   }
1963 
1964   Value *V = nullptr;
1965   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1966   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1967   if (ICmp0 && ICmp1)
1968     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1969               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1970 
1971   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1972   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1973   if (FCmp0 && FCmp1)
1974     V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
1975 
1976   if (!V)
1977     return nullptr;
1978   if (!Cast0)
1979     return V;
1980 
1981   // If we looked through casts, we can only handle a constant simplification
1982   // because we are not allowed to create a cast instruction here.
1983   if (auto *C = dyn_cast<Constant>(V))
1984     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1985 
1986   return nullptr;
1987 }
1988 
1989 /// Given a bitwise logic op, check if the operands are add/sub with a common
1990 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
1991 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
1992                                     Instruction::BinaryOps Opcode) {
1993   assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
1994   assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
1995   Value *X;
1996   Constant *C1, *C2;
1997   if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
1998        match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
1999       (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2000        match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2001     if (ConstantExpr::getNot(C1) == C2) {
2002       // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2003       // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2004       // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2005       Type *Ty = Op0->getType();
2006       return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2007                                         : ConstantInt::getAllOnesValue(Ty);
2008     }
2009   }
2010   return nullptr;
2011 }
2012 
2013 /// Given operands for an And, see if we can fold the result.
2014 /// If not, this returns null.
2015 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2016                               unsigned MaxRecurse) {
2017   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2018     return C;
2019 
2020   // X & poison -> poison
2021   if (isa<PoisonValue>(Op1))
2022     return Op1;
2023 
2024   // X & undef -> 0
2025   if (Q.isUndefValue(Op1))
2026     return Constant::getNullValue(Op0->getType());
2027 
2028   // X & X = X
2029   if (Op0 == Op1)
2030     return Op0;
2031 
2032   // X & 0 = 0
2033   if (match(Op1, m_Zero()))
2034     return Constant::getNullValue(Op0->getType());
2035 
2036   // X & -1 = X
2037   if (match(Op1, m_AllOnes()))
2038     return Op0;
2039 
2040   // A & ~A  =  ~A & A  =  0
2041   if (match(Op0, m_Not(m_Specific(Op1))) ||
2042       match(Op1, m_Not(m_Specific(Op0))))
2043     return Constant::getNullValue(Op0->getType());
2044 
2045   // (A | ?) & A = A
2046   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2047     return Op1;
2048 
2049   // A & (A | ?) = A
2050   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
2051     return Op0;
2052 
2053   // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2054   Value *X, *Y;
2055   if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2056       match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2057     return X;
2058   if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2059       match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2060     return X;
2061 
2062   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2063     return V;
2064 
2065   // A mask that only clears known zeros of a shifted value is a no-op.
2066   const APInt *Mask;
2067   const APInt *ShAmt;
2068   if (match(Op1, m_APInt(Mask))) {
2069     // If all bits in the inverted and shifted mask are clear:
2070     // and (shl X, ShAmt), Mask --> shl X, ShAmt
2071     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2072         (~(*Mask)).lshr(*ShAmt).isZero())
2073       return Op0;
2074 
2075     // If all bits in the inverted and shifted mask are clear:
2076     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2077     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2078         (~(*Mask)).shl(*ShAmt).isZero())
2079       return Op0;
2080   }
2081 
2082   // If we have a multiplication overflow check that is being 'and'ed with a
2083   // check that one of the multipliers is not zero, we can omit the 'and', and
2084   // only keep the overflow check.
2085   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2086     return Op1;
2087   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
2088     return Op0;
2089 
2090   // A & (-A) = A if A is a power of two or zero.
2091   if (match(Op0, m_Neg(m_Specific(Op1))) ||
2092       match(Op1, m_Neg(m_Specific(Op0)))) {
2093     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2094                                Q.DT))
2095       return Op0;
2096     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2097                                Q.DT))
2098       return Op1;
2099   }
2100 
2101   // This is a similar pattern used for checking if a value is a power-of-2:
2102   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2103   // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
2104   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2105       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2106     return Constant::getNullValue(Op1->getType());
2107   if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
2108       isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2109     return Constant::getNullValue(Op0->getType());
2110 
2111   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2112     return V;
2113 
2114   // Try some generic simplifications for associative operations.
2115   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
2116                                           MaxRecurse))
2117     return V;
2118 
2119   // And distributes over Or.  Try some generic simplifications based on this.
2120   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2121                                         Instruction::Or, Q, MaxRecurse))
2122     return V;
2123 
2124   // And distributes over Xor.  Try some generic simplifications based on this.
2125   if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2126                                         Instruction::Xor, Q, MaxRecurse))
2127     return V;
2128 
2129   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2130     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2131       // A & (A && B) -> A && B
2132       if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2133         return Op1;
2134       else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2135         return Op0;
2136     }
2137     // If the operation is with the result of a select instruction, check
2138     // whether operating on either branch of the select always yields the same
2139     // value.
2140     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
2141                                          MaxRecurse))
2142       return V;
2143   }
2144 
2145   // If the operation is with the result of a phi instruction, check whether
2146   // operating on all incoming values of the phi always yields the same value.
2147   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2148     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
2149                                       MaxRecurse))
2150       return V;
2151 
2152   // Assuming the effective width of Y is not larger than A, i.e. all bits
2153   // from X and Y are disjoint in (X << A) | Y,
2154   // if the mask of this AND op covers all bits of X or Y, while it covers
2155   // no bits from the other, we can bypass this AND op. E.g.,
2156   // ((X << A) | Y) & Mask -> Y,
2157   //     if Mask = ((1 << effective_width_of(Y)) - 1)
2158   // ((X << A) | Y) & Mask -> X << A,
2159   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
2160   // SimplifyDemandedBits in InstCombine can optimize the general case.
2161   // This pattern aims to help other passes for a common case.
2162   Value *XShifted;
2163   if (match(Op1, m_APInt(Mask)) &&
2164       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2165                                      m_Value(XShifted)),
2166                         m_Value(Y)))) {
2167     const unsigned Width = Op0->getType()->getScalarSizeInBits();
2168     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2169     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2170     const unsigned EffWidthY = YKnown.countMaxActiveBits();
2171     if (EffWidthY <= ShftCnt) {
2172       const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
2173                                                 Q.DT);
2174       const unsigned EffWidthX = XKnown.countMaxActiveBits();
2175       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2176       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2177       // If the mask is extracting all bits from X or Y as is, we can skip
2178       // this AND op.
2179       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2180         return Y;
2181       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2182         return XShifted;
2183     }
2184   }
2185 
2186   // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2187   // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2188   BinaryOperator *Or;
2189   if (match(Op0, m_c_Xor(m_Value(X),
2190                          m_CombineAnd(m_BinOp(Or),
2191                                       m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2192       match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2193     return Constant::getNullValue(Op0->getType());
2194 
2195   return nullptr;
2196 }
2197 
2198 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2199   return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
2200 }
2201 
2202 static Value *simplifyOrLogic(Value *X, Value *Y) {
2203   assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2204   Type *Ty = X->getType();
2205 
2206   // X | ~X --> -1
2207   if (match(Y, m_Not(m_Specific(X))))
2208     return ConstantInt::getAllOnesValue(Ty);
2209 
2210   // X | ~(X & ?) = -1
2211   if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2212     return ConstantInt::getAllOnesValue(Ty);
2213 
2214   // X | (X & ?) --> X
2215   if (match(Y, m_c_And(m_Specific(X), m_Value())))
2216     return X;
2217 
2218   Value *A, *B;
2219 
2220   // (A ^ B) | (A | B) --> A | B
2221   // (A ^ B) | (B | A) --> B | A
2222   if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2223       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2224     return Y;
2225 
2226   // ~(A ^ B) | (A | B) --> -1
2227   // ~(A ^ B) | (B | A) --> -1
2228   if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2229       match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2230     return ConstantInt::getAllOnesValue(Ty);
2231 
2232   // (A & ~B) | (A ^ B) --> A ^ B
2233   // (~B & A) | (A ^ B) --> A ^ B
2234   // (A & ~B) | (B ^ A) --> B ^ A
2235   // (~B & A) | (B ^ A) --> B ^ A
2236   if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2237       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2238     return Y;
2239 
2240   // (~A ^ B) | (A & B) --> ~A ^ B
2241   // (B ^ ~A) | (A & B) --> B ^ ~A
2242   // (~A ^ B) | (B & A) --> ~A ^ B
2243   // (B ^ ~A) | (B & A) --> B ^ ~A
2244   if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2245       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2246     return X;
2247 
2248   // (~A | B) | (A ^ B) --> -1
2249   // (~A | B) | (B ^ A) --> -1
2250   // (B | ~A) | (A ^ B) --> -1
2251   // (B | ~A) | (B ^ A) --> -1
2252   if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2253       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2254     return ConstantInt::getAllOnesValue(Ty);
2255 
2256   // (~A & B) | ~(A | B) --> ~A
2257   // (~A & B) | ~(B | A) --> ~A
2258   // (B & ~A) | ~(A | B) --> ~A
2259   // (B & ~A) | ~(B | A) --> ~A
2260   Value *NotA;
2261   if (match(X,
2262             m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2263                     m_Value(B))) &&
2264       match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2265     return NotA;
2266 
2267   // ~(A ^ B) | (A & B) --> ~(A ^ B)
2268   // ~(A ^ B) | (B & A) --> ~(A ^ B)
2269   Value *NotAB;
2270   if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
2271                             m_Value(NotAB))) &&
2272       match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2273     return NotAB;
2274 
2275   // ~(A & B) | (A ^ B) --> ~(A & B)
2276   // ~(A & B) | (B ^ A) --> ~(A & B)
2277   if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
2278                             m_Value(NotAB))) &&
2279       match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2280     return NotAB;
2281 
2282   return nullptr;
2283 }
2284 
2285 /// Given operands for an Or, see if we can fold the result.
2286 /// If not, this returns null.
2287 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2288                              unsigned MaxRecurse) {
2289   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2290     return C;
2291 
2292   // X | poison -> poison
2293   if (isa<PoisonValue>(Op1))
2294     return Op1;
2295 
2296   // X | undef -> -1
2297   // X | -1 = -1
2298   // Do not return Op1 because it may contain undef elements if it's a vector.
2299   if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2300     return Constant::getAllOnesValue(Op0->getType());
2301 
2302   // X | X = X
2303   // X | 0 = X
2304   if (Op0 == Op1 || match(Op1, m_Zero()))
2305     return Op0;
2306 
2307   if (Value *R = simplifyOrLogic(Op0, Op1))
2308     return R;
2309   if (Value *R = simplifyOrLogic(Op1, Op0))
2310     return R;
2311 
2312   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2313     return V;
2314 
2315   // Rotated -1 is still -1:
2316   // (-1 << X) | (-1 >> (C - X)) --> -1
2317   // (-1 >> X) | (-1 << (C - X)) --> -1
2318   // ...with C <= bitwidth (and commuted variants).
2319   Value *X, *Y;
2320   if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2321        match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2322       (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2323        match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2324     const APInt *C;
2325     if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2326          match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2327         C->ule(X->getType()->getScalarSizeInBits())) {
2328       return ConstantInt::getAllOnesValue(X->getType());
2329     }
2330   }
2331 
2332   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2333     return V;
2334 
2335   // If we have a multiplication overflow check that is being 'and'ed with a
2336   // check that one of the multipliers is not zero, we can omit the 'and', and
2337   // only keep the overflow check.
2338   if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2339     return Op1;
2340   if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2341     return Op0;
2342 
2343   // Try some generic simplifications for associative operations.
2344   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2345                                           MaxRecurse))
2346     return V;
2347 
2348   // Or distributes over And.  Try some generic simplifications based on this.
2349   if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2350                                         Instruction::And, Q, MaxRecurse))
2351     return V;
2352 
2353   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2354     if (Op0->getType()->isIntOrIntVectorTy(1)) {
2355       // A | (A || B) -> A || B
2356       if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2357         return Op1;
2358       else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2359         return Op0;
2360     }
2361     // If the operation is with the result of a select instruction, check
2362     // whether operating on either branch of the select always yields the same
2363     // value.
2364     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2365                                          MaxRecurse))
2366       return V;
2367   }
2368 
2369   // (A & C1)|(B & C2)
2370   Value *A, *B;
2371   const APInt *C1, *C2;
2372   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2373       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2374     if (*C1 == ~*C2) {
2375       // (A & C1)|(B & C2)
2376       // If we have: ((V + N) & C1) | (V & C2)
2377       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2378       // replace with V+N.
2379       Value *N;
2380       if (C2->isMask() && // C2 == 0+1+
2381           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2382         // Add commutes, try both ways.
2383         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2384           return A;
2385       }
2386       // Or commutes, try both ways.
2387       if (C1->isMask() &&
2388           match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2389         // Add commutes, try both ways.
2390         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2391           return B;
2392       }
2393     }
2394   }
2395 
2396   // If the operation is with the result of a phi instruction, check whether
2397   // operating on all incoming values of the phi always yields the same value.
2398   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2399     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2400       return V;
2401 
2402   return nullptr;
2403 }
2404 
2405 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2406   return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2407 }
2408 
2409 /// Given operands for a Xor, see if we can fold the result.
2410 /// If not, this returns null.
2411 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2412                               unsigned MaxRecurse) {
2413   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2414     return C;
2415 
2416   // X ^ poison -> poison
2417   if (isa<PoisonValue>(Op1))
2418     return Op1;
2419 
2420   // A ^ undef -> undef
2421   if (Q.isUndefValue(Op1))
2422     return Op1;
2423 
2424   // A ^ 0 = A
2425   if (match(Op1, m_Zero()))
2426     return Op0;
2427 
2428   // A ^ A = 0
2429   if (Op0 == Op1)
2430     return Constant::getNullValue(Op0->getType());
2431 
2432   // A ^ ~A  =  ~A ^ A  =  -1
2433   if (match(Op0, m_Not(m_Specific(Op1))) ||
2434       match(Op1, m_Not(m_Specific(Op0))))
2435     return Constant::getAllOnesValue(Op0->getType());
2436 
2437   auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2438     Value *A, *B;
2439     // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2440     if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2441         match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2442       return A;
2443 
2444     // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2445     // The 'not' op must contain a complete -1 operand (no undef elements for
2446     // vector) for the transform to be safe.
2447     Value *NotA;
2448     if (match(X,
2449               m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
2450                      m_Value(B))) &&
2451         match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2452       return NotA;
2453 
2454     return nullptr;
2455   };
2456   if (Value *R = foldAndOrNot(Op0, Op1))
2457     return R;
2458   if (Value *R = foldAndOrNot(Op1, Op0))
2459     return R;
2460 
2461   if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2462     return V;
2463 
2464   // Try some generic simplifications for associative operations.
2465   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2466                                           MaxRecurse))
2467     return V;
2468 
2469   // Threading Xor over selects and phi nodes is pointless, so don't bother.
2470   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2471   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2472   // only if B and C are equal.  If B and C are equal then (since we assume
2473   // that operands have already been simplified) "select(cond, B, C)" should
2474   // have been simplified to the common value of B and C already.  Analysing
2475   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
2476   // for threading over phi nodes.
2477 
2478   return nullptr;
2479 }
2480 
2481 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2482   return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2483 }
2484 
2485 
2486 static Type *GetCompareTy(Value *Op) {
2487   return CmpInst::makeCmpResultType(Op->getType());
2488 }
2489 
2490 /// Rummage around inside V looking for something equivalent to the comparison
2491 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2492 /// Helper function for analyzing max/min idioms.
2493 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2494                                          Value *LHS, Value *RHS) {
2495   SelectInst *SI = dyn_cast<SelectInst>(V);
2496   if (!SI)
2497     return nullptr;
2498   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2499   if (!Cmp)
2500     return nullptr;
2501   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2502   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2503     return Cmp;
2504   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2505       LHS == CmpRHS && RHS == CmpLHS)
2506     return Cmp;
2507   return nullptr;
2508 }
2509 
2510 /// Return true if the underlying object (storage) must be disjoint from
2511 /// storage returned by any noalias return call.
2512 static bool IsAllocDisjoint(const Value *V) {
2513   // For allocas, we consider only static ones (dynamic
2514   // allocas might be transformed into calls to malloc not simultaneously
2515   // live with the compared-to allocation). For globals, we exclude symbols
2516   // that might be resolve lazily to symbols in another dynamically-loaded
2517   // library (and, thus, could be malloc'ed by the implementation).
2518   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2519     return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2520   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2521     return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2522             GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2523       !GV->isThreadLocal();
2524   if (const Argument *A = dyn_cast<Argument>(V))
2525     return A->hasByValAttr();
2526   return false;
2527 }
2528 
2529 /// Return true if V1 and V2 are each the base of some distict storage region
2530 /// [V, object_size(V)] which do not overlap.  Note that zero sized regions
2531 /// *are* possible, and that zero sized regions do not overlap with any other.
2532 static bool HaveNonOverlappingStorage(const Value *V1, const Value *V2) {
2533   // Global variables always exist, so they always exist during the lifetime
2534   // of each other and all allocas.  Global variables themselves usually have
2535   // non-overlapping storage, but since their addresses are constants, the
2536   // case involving two globals does not reach here and is instead handled in
2537   // constant folding.
2538   //
2539   // Two different allocas usually have different addresses...
2540   //
2541   // However, if there's an @llvm.stackrestore dynamically in between two
2542   // allocas, they may have the same address. It's tempting to reduce the
2543   // scope of the problem by only looking at *static* allocas here. That would
2544   // cover the majority of allocas while significantly reducing the likelihood
2545   // of having an @llvm.stackrestore pop up in the middle. However, it's not
2546   // actually impossible for an @llvm.stackrestore to pop up in the middle of
2547   // an entry block. Also, if we have a block that's not attached to a
2548   // function, we can't tell if it's "static" under the current definition.
2549   // Theoretically, this problem could be fixed by creating a new kind of
2550   // instruction kind specifically for static allocas. Such a new instruction
2551   // could be required to be at the top of the entry block, thus preventing it
2552   // from being subject to a @llvm.stackrestore. Instcombine could even
2553   // convert regular allocas into these special allocas. It'd be nifty.
2554   // However, until then, this problem remains open.
2555   //
2556   // So, we'll assume that two non-empty allocas have different addresses
2557   // for now.
2558   auto isByValArg = [](const Value *V) {
2559     const Argument *A = dyn_cast<Argument>(V);
2560     return A && A->hasByValAttr();
2561   };
2562 
2563   // Byval args are backed by store which does not overlap with each other,
2564   // allocas, or globals.
2565   if (isByValArg(V1))
2566     return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2567   if (isByValArg(V2))
2568     return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2569 
2570  return isa<AllocaInst>(V1) &&
2571     (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2572 }
2573 
2574 // A significant optimization not implemented here is assuming that alloca
2575 // addresses are not equal to incoming argument values. They don't *alias*,
2576 // as we say, but that doesn't mean they aren't equal, so we take a
2577 // conservative approach.
2578 //
2579 // This is inspired in part by C++11 5.10p1:
2580 //   "Two pointers of the same type compare equal if and only if they are both
2581 //    null, both point to the same function, or both represent the same
2582 //    address."
2583 //
2584 // This is pretty permissive.
2585 //
2586 // It's also partly due to C11 6.5.9p6:
2587 //   "Two pointers compare equal if and only if both are null pointers, both are
2588 //    pointers to the same object (including a pointer to an object and a
2589 //    subobject at its beginning) or function, both are pointers to one past the
2590 //    last element of the same array object, or one is a pointer to one past the
2591 //    end of one array object and the other is a pointer to the start of a
2592 //    different array object that happens to immediately follow the first array
2593 //    object in the address space.)
2594 //
2595 // C11's version is more restrictive, however there's no reason why an argument
2596 // couldn't be a one-past-the-end value for a stack object in the caller and be
2597 // equal to the beginning of a stack object in the callee.
2598 //
2599 // If the C and C++ standards are ever made sufficiently restrictive in this
2600 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2601 // this optimization.
2602 static Constant *
2603 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
2604                    const SimplifyQuery &Q) {
2605   const DataLayout &DL = Q.DL;
2606   const TargetLibraryInfo *TLI = Q.TLI;
2607   const DominatorTree *DT = Q.DT;
2608   const Instruction *CxtI = Q.CxtI;
2609   const InstrInfoQuery &IIQ = Q.IIQ;
2610 
2611   // First, skip past any trivial no-ops.
2612   LHS = LHS->stripPointerCasts();
2613   RHS = RHS->stripPointerCasts();
2614 
2615   // A non-null pointer is not equal to a null pointer.
2616   if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2617       llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2618                            IIQ.UseInstrInfo))
2619     return ConstantInt::get(GetCompareTy(LHS),
2620                             !CmpInst::isTrueWhenEqual(Pred));
2621 
2622   // We can only fold certain predicates on pointer comparisons.
2623   switch (Pred) {
2624   default:
2625     return nullptr;
2626 
2627     // Equality comaprisons are easy to fold.
2628   case CmpInst::ICMP_EQ:
2629   case CmpInst::ICMP_NE:
2630     break;
2631 
2632     // We can only handle unsigned relational comparisons because 'inbounds' on
2633     // a GEP only protects against unsigned wrapping.
2634   case CmpInst::ICMP_UGT:
2635   case CmpInst::ICMP_UGE:
2636   case CmpInst::ICMP_ULT:
2637   case CmpInst::ICMP_ULE:
2638     // However, we have to switch them to their signed variants to handle
2639     // negative indices from the base pointer.
2640     Pred = ICmpInst::getSignedPredicate(Pred);
2641     break;
2642   }
2643 
2644   // Strip off any constant offsets so that we can reason about them.
2645   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2646   // here and compare base addresses like AliasAnalysis does, however there are
2647   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2648   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2649   // doesn't need to guarantee pointer inequality when it says NoAlias.
2650 
2651   // Even if an non-inbounds GEP occurs along the path we can still optimize
2652   // equality comparisons concerning the result.
2653   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2654   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2655   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
2656 
2657   // If LHS and RHS are related via constant offsets to the same base
2658   // value, we can replace it with an icmp which just compares the offsets.
2659   if (LHS == RHS)
2660     return ConstantInt::get(
2661         GetCompareTy(LHS), ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2662 
2663   // Various optimizations for (in)equality comparisons.
2664   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2665     // Different non-empty allocations that exist at the same time have
2666     // different addresses (if the program can tell). If the offsets are
2667     // within the bounds of their allocations (and not one-past-the-end!
2668     // so we can't use inbounds!), and their allocations aren't the same,
2669     // the pointers are not equal.
2670     if (HaveNonOverlappingStorage(LHS, RHS)) {
2671       uint64_t LHSSize, RHSSize;
2672       ObjectSizeOpts Opts;
2673       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2674       auto *F = [](Value *V) {
2675         if (auto *I = dyn_cast<Instruction>(V))
2676           return I->getFunction();
2677         return cast<Argument>(V)->getParent();
2678       }(LHS);
2679       Opts.NullIsUnknownSize = NullPointerIsDefined(F);
2680       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2681           getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2682           !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2683           LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2684         return ConstantInt::get(GetCompareTy(LHS),
2685                                 !CmpInst::isTrueWhenEqual(Pred));
2686       }
2687     }
2688 
2689     // If one side of the equality comparison must come from a noalias call
2690     // (meaning a system memory allocation function), and the other side must
2691     // come from a pointer that cannot overlap with dynamically-allocated
2692     // memory within the lifetime of the current function (allocas, byval
2693     // arguments, globals), then determine the comparison result here.
2694     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2695     getUnderlyingObjects(LHS, LHSUObjs);
2696     getUnderlyingObjects(RHS, RHSUObjs);
2697 
2698     // Is the set of underlying objects all noalias calls?
2699     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2700       return all_of(Objects, isNoAliasCall);
2701     };
2702 
2703     // Is the set of underlying objects all things which must be disjoint from
2704     // noalias calls.  We assume that indexing from such disjoint storage
2705     // into the heap is undefined, and thus offsets can be safely ignored.
2706     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2707       return all_of(Objects, ::IsAllocDisjoint);
2708     };
2709 
2710     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2711         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2712         return ConstantInt::get(GetCompareTy(LHS),
2713                                 !CmpInst::isTrueWhenEqual(Pred));
2714 
2715     // Fold comparisons for non-escaping pointer even if the allocation call
2716     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2717     // dynamic allocation call could be either of the operands.  Note that
2718     // the other operand can not be based on the alloc - if it were, then
2719     // the cmp itself would be a capture.
2720     Value *MI = nullptr;
2721     if (isAllocLikeFn(LHS, TLI) &&
2722         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2723       MI = LHS;
2724     else if (isAllocLikeFn(RHS, TLI) &&
2725              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2726       MI = RHS;
2727     // FIXME: We should also fold the compare when the pointer escapes, but the
2728     // compare dominates the pointer escape
2729     if (MI && !PointerMayBeCaptured(MI, true, true))
2730       return ConstantInt::get(GetCompareTy(LHS),
2731                               CmpInst::isFalseWhenEqual(Pred));
2732   }
2733 
2734   // Otherwise, fail.
2735   return nullptr;
2736 }
2737 
2738 /// Fold an icmp when its operands have i1 scalar type.
2739 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2740                                   Value *RHS, const SimplifyQuery &Q) {
2741   Type *ITy = GetCompareTy(LHS); // The return type.
2742   Type *OpTy = LHS->getType();   // The operand type.
2743   if (!OpTy->isIntOrIntVectorTy(1))
2744     return nullptr;
2745 
2746   // A boolean compared to true/false can be reduced in 14 out of the 20
2747   // (10 predicates * 2 constants) possible combinations. The other
2748   // 6 cases require a 'not' of the LHS.
2749 
2750   auto ExtractNotLHS = [](Value *V) -> Value * {
2751     Value *X;
2752     if (match(V, m_Not(m_Value(X))))
2753       return X;
2754     return nullptr;
2755   };
2756 
2757   if (match(RHS, m_Zero())) {
2758     switch (Pred) {
2759     case CmpInst::ICMP_NE:  // X !=  0 -> X
2760     case CmpInst::ICMP_UGT: // X >u  0 -> X
2761     case CmpInst::ICMP_SLT: // X <s  0 -> X
2762       return LHS;
2763 
2764     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2765     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2766     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2767       if (Value *X = ExtractNotLHS(LHS))
2768         return X;
2769       break;
2770 
2771     case CmpInst::ICMP_ULT: // X <u  0 -> false
2772     case CmpInst::ICMP_SGT: // X >s  0 -> false
2773       return getFalse(ITy);
2774 
2775     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2776     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2777       return getTrue(ITy);
2778 
2779     default: break;
2780     }
2781   } else if (match(RHS, m_One())) {
2782     switch (Pred) {
2783     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2784     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2785     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2786       return LHS;
2787 
2788     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2789     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2790     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2791       if (Value *X = ExtractNotLHS(LHS))
2792         return X;
2793       break;
2794 
2795     case CmpInst::ICMP_UGT: // X >u   1 -> false
2796     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2797       return getFalse(ITy);
2798 
2799     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2800     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2801       return getTrue(ITy);
2802 
2803     default: break;
2804     }
2805   }
2806 
2807   switch (Pred) {
2808   default:
2809     break;
2810   case ICmpInst::ICMP_UGE:
2811     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2812       return getTrue(ITy);
2813     break;
2814   case ICmpInst::ICMP_SGE:
2815     /// For signed comparison, the values for an i1 are 0 and -1
2816     /// respectively. This maps into a truth table of:
2817     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2818     ///  0  |  0  |  1 (0 >= 0)   |  1
2819     ///  0  |  1  |  1 (0 >= -1)  |  1
2820     ///  1  |  0  |  0 (-1 >= 0)  |  0
2821     ///  1  |  1  |  1 (-1 >= -1) |  1
2822     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2823       return getTrue(ITy);
2824     break;
2825   case ICmpInst::ICMP_ULE:
2826     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2827       return getTrue(ITy);
2828     break;
2829   }
2830 
2831   return nullptr;
2832 }
2833 
2834 /// Try hard to fold icmp with zero RHS because this is a common case.
2835 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2836                                    Value *RHS, const SimplifyQuery &Q) {
2837   if (!match(RHS, m_Zero()))
2838     return nullptr;
2839 
2840   Type *ITy = GetCompareTy(LHS); // The return type.
2841   switch (Pred) {
2842   default:
2843     llvm_unreachable("Unknown ICmp predicate!");
2844   case ICmpInst::ICMP_ULT:
2845     return getFalse(ITy);
2846   case ICmpInst::ICMP_UGE:
2847     return getTrue(ITy);
2848   case ICmpInst::ICMP_EQ:
2849   case ICmpInst::ICMP_ULE:
2850     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2851       return getFalse(ITy);
2852     break;
2853   case ICmpInst::ICMP_NE:
2854   case ICmpInst::ICMP_UGT:
2855     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2856       return getTrue(ITy);
2857     break;
2858   case ICmpInst::ICMP_SLT: {
2859     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2860     if (LHSKnown.isNegative())
2861       return getTrue(ITy);
2862     if (LHSKnown.isNonNegative())
2863       return getFalse(ITy);
2864     break;
2865   }
2866   case ICmpInst::ICMP_SLE: {
2867     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2868     if (LHSKnown.isNegative())
2869       return getTrue(ITy);
2870     if (LHSKnown.isNonNegative() &&
2871         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2872       return getFalse(ITy);
2873     break;
2874   }
2875   case ICmpInst::ICMP_SGE: {
2876     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2877     if (LHSKnown.isNegative())
2878       return getFalse(ITy);
2879     if (LHSKnown.isNonNegative())
2880       return getTrue(ITy);
2881     break;
2882   }
2883   case ICmpInst::ICMP_SGT: {
2884     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2885     if (LHSKnown.isNegative())
2886       return getFalse(ITy);
2887     if (LHSKnown.isNonNegative() &&
2888         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2889       return getTrue(ITy);
2890     break;
2891   }
2892   }
2893 
2894   return nullptr;
2895 }
2896 
2897 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2898                                        Value *RHS, const InstrInfoQuery &IIQ) {
2899   Type *ITy = GetCompareTy(RHS); // The return type.
2900 
2901   Value *X;
2902   // Sign-bit checks can be optimized to true/false after unsigned
2903   // floating-point casts:
2904   // icmp slt (bitcast (uitofp X)),  0 --> false
2905   // icmp sgt (bitcast (uitofp X)), -1 --> true
2906   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2907     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2908       return ConstantInt::getFalse(ITy);
2909     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2910       return ConstantInt::getTrue(ITy);
2911   }
2912 
2913   const APInt *C;
2914   if (!match(RHS, m_APIntAllowUndef(C)))
2915     return nullptr;
2916 
2917   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2918   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2919   if (RHS_CR.isEmptySet())
2920     return ConstantInt::getFalse(ITy);
2921   if (RHS_CR.isFullSet())
2922     return ConstantInt::getTrue(ITy);
2923 
2924   ConstantRange LHS_CR =
2925       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
2926   if (!LHS_CR.isFullSet()) {
2927     if (RHS_CR.contains(LHS_CR))
2928       return ConstantInt::getTrue(ITy);
2929     if (RHS_CR.inverse().contains(LHS_CR))
2930       return ConstantInt::getFalse(ITy);
2931   }
2932 
2933   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
2934   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
2935   const APInt *MulC;
2936   if (ICmpInst::isEquality(Pred) &&
2937       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2938         *MulC != 0 && C->urem(*MulC) != 0) ||
2939        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2940         *MulC != 0 && C->srem(*MulC) != 0)))
2941     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
2942 
2943   return nullptr;
2944 }
2945 
2946 static Value *simplifyICmpWithBinOpOnLHS(
2947     CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS,
2948     const SimplifyQuery &Q, unsigned MaxRecurse) {
2949   Type *ITy = GetCompareTy(RHS); // The return type.
2950 
2951   Value *Y = nullptr;
2952   // icmp pred (or X, Y), X
2953   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2954     if (Pred == ICmpInst::ICMP_ULT)
2955       return getFalse(ITy);
2956     if (Pred == ICmpInst::ICMP_UGE)
2957       return getTrue(ITy);
2958 
2959     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2960       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2961       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2962       if (RHSKnown.isNonNegative() && YKnown.isNegative())
2963         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2964       if (RHSKnown.isNegative() || YKnown.isNonNegative())
2965         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2966     }
2967   }
2968 
2969   // icmp pred (and X, Y), X
2970   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2971     if (Pred == ICmpInst::ICMP_UGT)
2972       return getFalse(ITy);
2973     if (Pred == ICmpInst::ICMP_ULE)
2974       return getTrue(ITy);
2975   }
2976 
2977   // icmp pred (urem X, Y), Y
2978   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2979     switch (Pred) {
2980     default:
2981       break;
2982     case ICmpInst::ICMP_SGT:
2983     case ICmpInst::ICMP_SGE: {
2984       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2985       if (!Known.isNonNegative())
2986         break;
2987       LLVM_FALLTHROUGH;
2988     }
2989     case ICmpInst::ICMP_EQ:
2990     case ICmpInst::ICMP_UGT:
2991     case ICmpInst::ICMP_UGE:
2992       return getFalse(ITy);
2993     case ICmpInst::ICMP_SLT:
2994     case ICmpInst::ICMP_SLE: {
2995       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2996       if (!Known.isNonNegative())
2997         break;
2998       LLVM_FALLTHROUGH;
2999     }
3000     case ICmpInst::ICMP_NE:
3001     case ICmpInst::ICMP_ULT:
3002     case ICmpInst::ICMP_ULE:
3003       return getTrue(ITy);
3004     }
3005   }
3006 
3007   // icmp pred (urem X, Y), X
3008   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3009     if (Pred == ICmpInst::ICMP_ULE)
3010       return getTrue(ITy);
3011     if (Pred == ICmpInst::ICMP_UGT)
3012       return getFalse(ITy);
3013   }
3014 
3015   // x >>u y <=u x --> true.
3016   // x >>u y >u  x --> false.
3017   // x udiv y <=u x --> true.
3018   // x udiv y >u  x --> false.
3019   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3020       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3021     // icmp pred (X op Y), X
3022     if (Pred == ICmpInst::ICMP_UGT)
3023       return getFalse(ITy);
3024     if (Pred == ICmpInst::ICMP_ULE)
3025       return getTrue(ITy);
3026   }
3027 
3028   // If x is nonzero:
3029   // x >>u C <u  x --> true  for C != 0.
3030   // x >>u C !=  x --> true  for C != 0.
3031   // x >>u C >=u x --> false for C != 0.
3032   // x >>u C ==  x --> false for C != 0.
3033   // x udiv C <u  x --> true  for C != 1.
3034   // x udiv C !=  x --> true  for C != 1.
3035   // x udiv C >=u x --> false for C != 1.
3036   // x udiv C ==  x --> false for C != 1.
3037   // TODO: allow non-constant shift amount/divisor
3038   const APInt *C;
3039   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3040       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3041     if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3042       switch (Pred) {
3043       default:
3044         break;
3045       case ICmpInst::ICMP_EQ:
3046       case ICmpInst::ICMP_UGE:
3047         return getFalse(ITy);
3048       case ICmpInst::ICMP_NE:
3049       case ICmpInst::ICMP_ULT:
3050         return getTrue(ITy);
3051       case ICmpInst::ICMP_UGT:
3052       case ICmpInst::ICMP_ULE:
3053         // UGT/ULE are handled by the more general case just above
3054         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3055       }
3056     }
3057   }
3058 
3059   // (x*C1)/C2 <= x for C1 <= C2.
3060   // This holds even if the multiplication overflows: Assume that x != 0 and
3061   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3062   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3063   //
3064   // Additionally, either the multiplication and division might be represented
3065   // as shifts:
3066   // (x*C1)>>C2 <= x for C1 < 2**C2.
3067   // (x<<C1)/C2 <= x for 2**C1 < C2.
3068   const APInt *C1, *C2;
3069   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3070        C1->ule(*C2)) ||
3071       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3072        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3073       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3074        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3075     if (Pred == ICmpInst::ICMP_UGT)
3076       return getFalse(ITy);
3077     if (Pred == ICmpInst::ICMP_ULE)
3078       return getTrue(ITy);
3079   }
3080 
3081   return nullptr;
3082 }
3083 
3084 
3085 // If only one of the icmp's operands has NSW flags, try to prove that:
3086 //
3087 //   icmp slt (x + C1), (x +nsw C2)
3088 //
3089 // is equivalent to:
3090 //
3091 //   icmp slt C1, C2
3092 //
3093 // which is true if x + C2 has the NSW flags set and:
3094 // *) C1 < C2 && C1 >= 0, or
3095 // *) C2 < C1 && C1 <= 0.
3096 //
3097 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3098                                     Value *RHS) {
3099   // TODO: only support icmp slt for now.
3100   if (Pred != CmpInst::ICMP_SLT)
3101     return false;
3102 
3103   // Canonicalize nsw add as RHS.
3104   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3105     std::swap(LHS, RHS);
3106   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3107     return false;
3108 
3109   Value *X;
3110   const APInt *C1, *C2;
3111   if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3112       !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3113     return false;
3114 
3115   return (C1->slt(*C2) && C1->isNonNegative()) ||
3116          (C2->slt(*C1) && C1->isNonPositive());
3117 }
3118 
3119 
3120 /// TODO: A large part of this logic is duplicated in InstCombine's
3121 /// foldICmpBinOp(). We should be able to share that and avoid the code
3122 /// duplication.
3123 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3124                                     Value *RHS, const SimplifyQuery &Q,
3125                                     unsigned MaxRecurse) {
3126   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3127   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3128   if (MaxRecurse && (LBO || RBO)) {
3129     // Analyze the case when either LHS or RHS is an add instruction.
3130     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3131     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3132     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3133     if (LBO && LBO->getOpcode() == Instruction::Add) {
3134       A = LBO->getOperand(0);
3135       B = LBO->getOperand(1);
3136       NoLHSWrapProblem =
3137           ICmpInst::isEquality(Pred) ||
3138           (CmpInst::isUnsigned(Pred) &&
3139            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3140           (CmpInst::isSigned(Pred) &&
3141            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3142     }
3143     if (RBO && RBO->getOpcode() == Instruction::Add) {
3144       C = RBO->getOperand(0);
3145       D = RBO->getOperand(1);
3146       NoRHSWrapProblem =
3147           ICmpInst::isEquality(Pred) ||
3148           (CmpInst::isUnsigned(Pred) &&
3149            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3150           (CmpInst::isSigned(Pred) &&
3151            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3152     }
3153 
3154     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3155     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3156       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
3157                                       Constant::getNullValue(RHS->getType()), Q,
3158                                       MaxRecurse - 1))
3159         return V;
3160 
3161     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3162     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3163       if (Value *V =
3164               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3165                                C == LHS ? D : C, Q, MaxRecurse - 1))
3166         return V;
3167 
3168     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3169     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3170                        trySimplifyICmpWithAdds(Pred, LHS, RHS);
3171     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3172       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3173       Value *Y, *Z;
3174       if (A == C) {
3175         // C + B == C + D  ->  B == D
3176         Y = B;
3177         Z = D;
3178       } else if (A == D) {
3179         // D + B == C + D  ->  B == C
3180         Y = B;
3181         Z = C;
3182       } else if (B == C) {
3183         // A + C == C + D  ->  A == D
3184         Y = A;
3185         Z = D;
3186       } else {
3187         assert(B == D);
3188         // A + D == C + D  ->  A == C
3189         Y = A;
3190         Z = C;
3191       }
3192       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3193         return V;
3194     }
3195   }
3196 
3197   if (LBO)
3198     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3199       return V;
3200 
3201   if (RBO)
3202     if (Value *V = simplifyICmpWithBinOpOnLHS(
3203             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3204       return V;
3205 
3206   // 0 - (zext X) pred C
3207   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3208     const APInt *C;
3209     if (match(RHS, m_APInt(C))) {
3210       if (C->isStrictlyPositive()) {
3211         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3212           return ConstantInt::getTrue(GetCompareTy(RHS));
3213         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3214           return ConstantInt::getFalse(GetCompareTy(RHS));
3215       }
3216       if (C->isNonNegative()) {
3217         if (Pred == ICmpInst::ICMP_SLE)
3218           return ConstantInt::getTrue(GetCompareTy(RHS));
3219         if (Pred == ICmpInst::ICMP_SGT)
3220           return ConstantInt::getFalse(GetCompareTy(RHS));
3221       }
3222     }
3223   }
3224 
3225   //   If C2 is a power-of-2 and C is not:
3226   //   (C2 << X) == C --> false
3227   //   (C2 << X) != C --> true
3228   const APInt *C;
3229   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3230       match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3231     // C2 << X can equal zero in some circumstances.
3232     // This simplification might be unsafe if C is zero.
3233     //
3234     // We know it is safe if:
3235     // - The shift is nsw. We can't shift out the one bit.
3236     // - The shift is nuw. We can't shift out the one bit.
3237     // - C2 is one.
3238     // - C isn't zero.
3239     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3240         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3241         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3242       if (Pred == ICmpInst::ICMP_EQ)
3243         return ConstantInt::getFalse(GetCompareTy(RHS));
3244       if (Pred == ICmpInst::ICMP_NE)
3245         return ConstantInt::getTrue(GetCompareTy(RHS));
3246     }
3247   }
3248 
3249   // TODO: This is overly constrained. LHS can be any power-of-2.
3250   // (1 << X)  >u 0x8000 --> false
3251   // (1 << X) <=u 0x8000 --> true
3252   if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
3253     if (Pred == ICmpInst::ICMP_UGT)
3254       return ConstantInt::getFalse(GetCompareTy(RHS));
3255     if (Pred == ICmpInst::ICMP_ULE)
3256       return ConstantInt::getTrue(GetCompareTy(RHS));
3257   }
3258 
3259   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3260       LBO->getOperand(1) == RBO->getOperand(1)) {
3261     switch (LBO->getOpcode()) {
3262     default:
3263       break;
3264     case Instruction::UDiv:
3265     case Instruction::LShr:
3266       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3267           !Q.IIQ.isExact(RBO))
3268         break;
3269       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3270                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3271           return V;
3272       break;
3273     case Instruction::SDiv:
3274       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3275           !Q.IIQ.isExact(RBO))
3276         break;
3277       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3278                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3279         return V;
3280       break;
3281     case Instruction::AShr:
3282       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3283         break;
3284       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3285                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3286         return V;
3287       break;
3288     case Instruction::Shl: {
3289       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3290       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3291       if (!NUW && !NSW)
3292         break;
3293       if (!NSW && ICmpInst::isSigned(Pred))
3294         break;
3295       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3296                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3297         return V;
3298       break;
3299     }
3300     }
3301   }
3302   return nullptr;
3303 }
3304 
3305 /// Simplify integer comparisons where at least one operand of the compare
3306 /// matches an integer min/max idiom.
3307 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3308                                      Value *RHS, const SimplifyQuery &Q,
3309                                      unsigned MaxRecurse) {
3310   Type *ITy = GetCompareTy(LHS); // The return type.
3311   Value *A, *B;
3312   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3313   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3314 
3315   // Signed variants on "max(a,b)>=a -> true".
3316   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3317     if (A != RHS)
3318       std::swap(A, B);       // smax(A, B) pred A.
3319     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3320     // We analyze this as smax(A, B) pred A.
3321     P = Pred;
3322   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3323              (A == LHS || B == LHS)) {
3324     if (A != LHS)
3325       std::swap(A, B);       // A pred smax(A, B).
3326     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3327     // We analyze this as smax(A, B) swapped-pred A.
3328     P = CmpInst::getSwappedPredicate(Pred);
3329   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3330              (A == RHS || B == RHS)) {
3331     if (A != RHS)
3332       std::swap(A, B);       // smin(A, B) pred A.
3333     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3334     // We analyze this as smax(-A, -B) swapped-pred -A.
3335     // Note that we do not need to actually form -A or -B thanks to EqP.
3336     P = CmpInst::getSwappedPredicate(Pred);
3337   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3338              (A == LHS || B == LHS)) {
3339     if (A != LHS)
3340       std::swap(A, B);       // A pred smin(A, B).
3341     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3342     // We analyze this as smax(-A, -B) pred -A.
3343     // Note that we do not need to actually form -A or -B thanks to EqP.
3344     P = Pred;
3345   }
3346   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3347     // Cases correspond to "max(A, B) p A".
3348     switch (P) {
3349     default:
3350       break;
3351     case CmpInst::ICMP_EQ:
3352     case CmpInst::ICMP_SLE:
3353       // Equivalent to "A EqP B".  This may be the same as the condition tested
3354       // in the max/min; if so, we can just return that.
3355       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3356         return V;
3357       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3358         return V;
3359       // Otherwise, see if "A EqP B" simplifies.
3360       if (MaxRecurse)
3361         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3362           return V;
3363       break;
3364     case CmpInst::ICMP_NE:
3365     case CmpInst::ICMP_SGT: {
3366       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3367       // Equivalent to "A InvEqP B".  This may be the same as the condition
3368       // tested in the max/min; if so, we can just return that.
3369       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3370         return V;
3371       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3372         return V;
3373       // Otherwise, see if "A InvEqP B" simplifies.
3374       if (MaxRecurse)
3375         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3376           return V;
3377       break;
3378     }
3379     case CmpInst::ICMP_SGE:
3380       // Always true.
3381       return getTrue(ITy);
3382     case CmpInst::ICMP_SLT:
3383       // Always false.
3384       return getFalse(ITy);
3385     }
3386   }
3387 
3388   // Unsigned variants on "max(a,b)>=a -> true".
3389   P = CmpInst::BAD_ICMP_PREDICATE;
3390   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3391     if (A != RHS)
3392       std::swap(A, B);       // umax(A, B) pred A.
3393     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3394     // We analyze this as umax(A, B) pred A.
3395     P = Pred;
3396   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3397              (A == LHS || B == LHS)) {
3398     if (A != LHS)
3399       std::swap(A, B);       // A pred umax(A, B).
3400     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3401     // We analyze this as umax(A, B) swapped-pred A.
3402     P = CmpInst::getSwappedPredicate(Pred);
3403   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3404              (A == RHS || B == RHS)) {
3405     if (A != RHS)
3406       std::swap(A, B);       // umin(A, B) pred A.
3407     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3408     // We analyze this as umax(-A, -B) swapped-pred -A.
3409     // Note that we do not need to actually form -A or -B thanks to EqP.
3410     P = CmpInst::getSwappedPredicate(Pred);
3411   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3412              (A == LHS || B == LHS)) {
3413     if (A != LHS)
3414       std::swap(A, B);       // A pred umin(A, B).
3415     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3416     // We analyze this as umax(-A, -B) pred -A.
3417     // Note that we do not need to actually form -A or -B thanks to EqP.
3418     P = Pred;
3419   }
3420   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3421     // Cases correspond to "max(A, B) p A".
3422     switch (P) {
3423     default:
3424       break;
3425     case CmpInst::ICMP_EQ:
3426     case CmpInst::ICMP_ULE:
3427       // Equivalent to "A EqP B".  This may be the same as the condition tested
3428       // in the max/min; if so, we can just return that.
3429       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3430         return V;
3431       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3432         return V;
3433       // Otherwise, see if "A EqP B" simplifies.
3434       if (MaxRecurse)
3435         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3436           return V;
3437       break;
3438     case CmpInst::ICMP_NE:
3439     case CmpInst::ICMP_UGT: {
3440       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3441       // Equivalent to "A InvEqP B".  This may be the same as the condition
3442       // tested in the max/min; if so, we can just return that.
3443       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3444         return V;
3445       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3446         return V;
3447       // Otherwise, see if "A InvEqP B" simplifies.
3448       if (MaxRecurse)
3449         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3450           return V;
3451       break;
3452     }
3453     case CmpInst::ICMP_UGE:
3454       return getTrue(ITy);
3455     case CmpInst::ICMP_ULT:
3456       return getFalse(ITy);
3457     }
3458   }
3459 
3460   // Comparing 1 each of min/max with a common operand?
3461   // Canonicalize min operand to RHS.
3462   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3463       match(LHS, m_SMin(m_Value(), m_Value()))) {
3464     std::swap(LHS, RHS);
3465     Pred = ICmpInst::getSwappedPredicate(Pred);
3466   }
3467 
3468   Value *C, *D;
3469   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3470       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3471       (A == C || A == D || B == C || B == D)) {
3472     // smax(A, B) >=s smin(A, D) --> true
3473     if (Pred == CmpInst::ICMP_SGE)
3474       return getTrue(ITy);
3475     // smax(A, B) <s smin(A, D) --> false
3476     if (Pred == CmpInst::ICMP_SLT)
3477       return getFalse(ITy);
3478   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3479              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3480              (A == C || A == D || B == C || B == D)) {
3481     // umax(A, B) >=u umin(A, D) --> true
3482     if (Pred == CmpInst::ICMP_UGE)
3483       return getTrue(ITy);
3484     // umax(A, B) <u umin(A, D) --> false
3485     if (Pred == CmpInst::ICMP_ULT)
3486       return getFalse(ITy);
3487   }
3488 
3489   return nullptr;
3490 }
3491 
3492 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3493                                                Value *LHS, Value *RHS,
3494                                                const SimplifyQuery &Q) {
3495   // Gracefully handle instructions that have not been inserted yet.
3496   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3497     return nullptr;
3498 
3499   for (Value *AssumeBaseOp : {LHS, RHS}) {
3500     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3501       if (!AssumeVH)
3502         continue;
3503 
3504       CallInst *Assume = cast<CallInst>(AssumeVH);
3505       if (Optional<bool> Imp =
3506               isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS,
3507                                  Q.DL))
3508         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3509           return ConstantInt::get(GetCompareTy(LHS), *Imp);
3510     }
3511   }
3512 
3513   return nullptr;
3514 }
3515 
3516 /// Given operands for an ICmpInst, see if we can fold the result.
3517 /// If not, this returns null.
3518 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3519                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3520   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3521   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3522 
3523   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3524     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3525       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3526 
3527     // If we have a constant, make sure it is on the RHS.
3528     std::swap(LHS, RHS);
3529     Pred = CmpInst::getSwappedPredicate(Pred);
3530   }
3531   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3532 
3533   Type *ITy = GetCompareTy(LHS); // The return type.
3534 
3535   // icmp poison, X -> poison
3536   if (isa<PoisonValue>(RHS))
3537     return PoisonValue::get(ITy);
3538 
3539   // For EQ and NE, we can always pick a value for the undef to make the
3540   // predicate pass or fail, so we can return undef.
3541   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3542   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3543     return UndefValue::get(ITy);
3544 
3545   // icmp X, X -> true/false
3546   // icmp X, undef -> true/false because undef could be X.
3547   if (LHS == RHS || Q.isUndefValue(RHS))
3548     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3549 
3550   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3551     return V;
3552 
3553   // TODO: Sink/common this with other potentially expensive calls that use
3554   //       ValueTracking? See comment below for isKnownNonEqual().
3555   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3556     return V;
3557 
3558   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3559     return V;
3560 
3561   // If both operands have range metadata, use the metadata
3562   // to simplify the comparison.
3563   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3564     auto RHS_Instr = cast<Instruction>(RHS);
3565     auto LHS_Instr = cast<Instruction>(LHS);
3566 
3567     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3568         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3569       auto RHS_CR = getConstantRangeFromMetadata(
3570           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3571       auto LHS_CR = getConstantRangeFromMetadata(
3572           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3573 
3574       if (LHS_CR.icmp(Pred, RHS_CR))
3575         return ConstantInt::getTrue(RHS->getContext());
3576 
3577       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3578         return ConstantInt::getFalse(RHS->getContext());
3579     }
3580   }
3581 
3582   // Compare of cast, for example (zext X) != 0 -> X != 0
3583   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3584     Instruction *LI = cast<CastInst>(LHS);
3585     Value *SrcOp = LI->getOperand(0);
3586     Type *SrcTy = SrcOp->getType();
3587     Type *DstTy = LI->getType();
3588 
3589     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3590     // if the integer type is the same size as the pointer type.
3591     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3592         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3593       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3594         // Transfer the cast to the constant.
3595         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3596                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3597                                         Q, MaxRecurse-1))
3598           return V;
3599       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3600         if (RI->getOperand(0)->getType() == SrcTy)
3601           // Compare without the cast.
3602           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3603                                           Q, MaxRecurse-1))
3604             return V;
3605       }
3606     }
3607 
3608     if (isa<ZExtInst>(LHS)) {
3609       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3610       // same type.
3611       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3612         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3613           // Compare X and Y.  Note that signed predicates become unsigned.
3614           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3615                                           SrcOp, RI->getOperand(0), Q,
3616                                           MaxRecurse-1))
3617             return V;
3618       }
3619       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3620       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3621         if (SrcOp == RI->getOperand(0)) {
3622           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3623             return ConstantInt::getTrue(ITy);
3624           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3625             return ConstantInt::getFalse(ITy);
3626         }
3627       }
3628       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3629       // too.  If not, then try to deduce the result of the comparison.
3630       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3631         // Compute the constant that would happen if we truncated to SrcTy then
3632         // reextended to DstTy.
3633         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3634         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3635 
3636         // If the re-extended constant didn't change then this is effectively
3637         // also a case of comparing two zero-extended values.
3638         if (RExt == CI && MaxRecurse)
3639           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3640                                         SrcOp, Trunc, Q, MaxRecurse-1))
3641             return V;
3642 
3643         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3644         // there.  Use this to work out the result of the comparison.
3645         if (RExt != CI) {
3646           switch (Pred) {
3647           default: llvm_unreachable("Unknown ICmp predicate!");
3648           // LHS <u RHS.
3649           case ICmpInst::ICMP_EQ:
3650           case ICmpInst::ICMP_UGT:
3651           case ICmpInst::ICMP_UGE:
3652             return ConstantInt::getFalse(CI->getContext());
3653 
3654           case ICmpInst::ICMP_NE:
3655           case ICmpInst::ICMP_ULT:
3656           case ICmpInst::ICMP_ULE:
3657             return ConstantInt::getTrue(CI->getContext());
3658 
3659           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3660           // is non-negative then LHS <s RHS.
3661           case ICmpInst::ICMP_SGT:
3662           case ICmpInst::ICMP_SGE:
3663             return CI->getValue().isNegative() ?
3664               ConstantInt::getTrue(CI->getContext()) :
3665               ConstantInt::getFalse(CI->getContext());
3666 
3667           case ICmpInst::ICMP_SLT:
3668           case ICmpInst::ICMP_SLE:
3669             return CI->getValue().isNegative() ?
3670               ConstantInt::getFalse(CI->getContext()) :
3671               ConstantInt::getTrue(CI->getContext());
3672           }
3673         }
3674       }
3675     }
3676 
3677     if (isa<SExtInst>(LHS)) {
3678       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3679       // same type.
3680       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3681         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3682           // Compare X and Y.  Note that the predicate does not change.
3683           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3684                                           Q, MaxRecurse-1))
3685             return V;
3686       }
3687       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3688       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3689         if (SrcOp == RI->getOperand(0)) {
3690           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3691             return ConstantInt::getTrue(ITy);
3692           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3693             return ConstantInt::getFalse(ITy);
3694         }
3695       }
3696       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3697       // too.  If not, then try to deduce the result of the comparison.
3698       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3699         // Compute the constant that would happen if we truncated to SrcTy then
3700         // reextended to DstTy.
3701         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3702         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3703 
3704         // If the re-extended constant didn't change then this is effectively
3705         // also a case of comparing two sign-extended values.
3706         if (RExt == CI && MaxRecurse)
3707           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3708             return V;
3709 
3710         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3711         // bits there.  Use this to work out the result of the comparison.
3712         if (RExt != CI) {
3713           switch (Pred) {
3714           default: llvm_unreachable("Unknown ICmp predicate!");
3715           case ICmpInst::ICMP_EQ:
3716             return ConstantInt::getFalse(CI->getContext());
3717           case ICmpInst::ICMP_NE:
3718             return ConstantInt::getTrue(CI->getContext());
3719 
3720           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3721           // LHS >s RHS.
3722           case ICmpInst::ICMP_SGT:
3723           case ICmpInst::ICMP_SGE:
3724             return CI->getValue().isNegative() ?
3725               ConstantInt::getTrue(CI->getContext()) :
3726               ConstantInt::getFalse(CI->getContext());
3727           case ICmpInst::ICMP_SLT:
3728           case ICmpInst::ICMP_SLE:
3729             return CI->getValue().isNegative() ?
3730               ConstantInt::getFalse(CI->getContext()) :
3731               ConstantInt::getTrue(CI->getContext());
3732 
3733           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3734           // LHS >u RHS.
3735           case ICmpInst::ICMP_UGT:
3736           case ICmpInst::ICMP_UGE:
3737             // Comparison is true iff the LHS <s 0.
3738             if (MaxRecurse)
3739               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3740                                               Constant::getNullValue(SrcTy),
3741                                               Q, MaxRecurse-1))
3742                 return V;
3743             break;
3744           case ICmpInst::ICMP_ULT:
3745           case ICmpInst::ICMP_ULE:
3746             // Comparison is true iff the LHS >=s 0.
3747             if (MaxRecurse)
3748               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3749                                               Constant::getNullValue(SrcTy),
3750                                               Q, MaxRecurse-1))
3751                 return V;
3752             break;
3753           }
3754         }
3755       }
3756     }
3757   }
3758 
3759   // icmp eq|ne X, Y -> false|true if X != Y
3760   // This is potentially expensive, and we have already computedKnownBits for
3761   // compares with 0 above here, so only try this for a non-zero compare.
3762   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
3763       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3764     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3765   }
3766 
3767   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3768     return V;
3769 
3770   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3771     return V;
3772 
3773   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3774     return V;
3775 
3776   // Simplify comparisons of related pointers using a powerful, recursive
3777   // GEP-walk when we have target data available..
3778   if (LHS->getType()->isPointerTy())
3779     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3780       return C;
3781   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3782     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3783       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3784               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3785           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3786               Q.DL.getTypeSizeInBits(CRHS->getType()))
3787         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3788                                          CRHS->getPointerOperand(), Q))
3789           return C;
3790 
3791   // If the comparison is with the result of a select instruction, check whether
3792   // comparing with either branch of the select always yields the same value.
3793   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3794     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3795       return V;
3796 
3797   // If the comparison is with the result of a phi instruction, check whether
3798   // doing the compare with each incoming phi value yields a common result.
3799   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3800     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3801       return V;
3802 
3803   return nullptr;
3804 }
3805 
3806 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3807                               const SimplifyQuery &Q) {
3808   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3809 }
3810 
3811 /// Given operands for an FCmpInst, see if we can fold the result.
3812 /// If not, this returns null.
3813 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3814                                FastMathFlags FMF, const SimplifyQuery &Q,
3815                                unsigned MaxRecurse) {
3816   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3817   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3818 
3819   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3820     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3821       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3822 
3823     // If we have a constant, make sure it is on the RHS.
3824     std::swap(LHS, RHS);
3825     Pred = CmpInst::getSwappedPredicate(Pred);
3826   }
3827 
3828   // Fold trivial predicates.
3829   Type *RetTy = GetCompareTy(LHS);
3830   if (Pred == FCmpInst::FCMP_FALSE)
3831     return getFalse(RetTy);
3832   if (Pred == FCmpInst::FCMP_TRUE)
3833     return getTrue(RetTy);
3834 
3835   // Fold (un)ordered comparison if we can determine there are no NaNs.
3836   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3837     if (FMF.noNaNs() ||
3838         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3839       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3840 
3841   // NaN is unordered; NaN is not ordered.
3842   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3843          "Comparison must be either ordered or unordered");
3844   if (match(RHS, m_NaN()))
3845     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3846 
3847   // fcmp pred x, poison and  fcmp pred poison, x
3848   // fold to poison
3849   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
3850     return PoisonValue::get(RetTy);
3851 
3852   // fcmp pred x, undef  and  fcmp pred undef, x
3853   // fold to true if unordered, false if ordered
3854   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3855     // Choosing NaN for the undef will always make unordered comparison succeed
3856     // and ordered comparison fail.
3857     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3858   }
3859 
3860   // fcmp x,x -> true/false.  Not all compares are foldable.
3861   if (LHS == RHS) {
3862     if (CmpInst::isTrueWhenEqual(Pred))
3863       return getTrue(RetTy);
3864     if (CmpInst::isFalseWhenEqual(Pred))
3865       return getFalse(RetTy);
3866   }
3867 
3868   // Handle fcmp with constant RHS.
3869   // TODO: Use match with a specific FP value, so these work with vectors with
3870   // undef lanes.
3871   const APFloat *C;
3872   if (match(RHS, m_APFloat(C))) {
3873     // Check whether the constant is an infinity.
3874     if (C->isInfinity()) {
3875       if (C->isNegative()) {
3876         switch (Pred) {
3877         case FCmpInst::FCMP_OLT:
3878           // No value is ordered and less than negative infinity.
3879           return getFalse(RetTy);
3880         case FCmpInst::FCMP_UGE:
3881           // All values are unordered with or at least negative infinity.
3882           return getTrue(RetTy);
3883         default:
3884           break;
3885         }
3886       } else {
3887         switch (Pred) {
3888         case FCmpInst::FCMP_OGT:
3889           // No value is ordered and greater than infinity.
3890           return getFalse(RetTy);
3891         case FCmpInst::FCMP_ULE:
3892           // All values are unordered with and at most infinity.
3893           return getTrue(RetTy);
3894         default:
3895           break;
3896         }
3897       }
3898 
3899       // LHS == Inf
3900       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3901         return getFalse(RetTy);
3902       // LHS != Inf
3903       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3904         return getTrue(RetTy);
3905       // LHS == Inf || LHS == NaN
3906       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3907           isKnownNeverNaN(LHS, Q.TLI))
3908         return getFalse(RetTy);
3909       // LHS != Inf && LHS != NaN
3910       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3911           isKnownNeverNaN(LHS, Q.TLI))
3912         return getTrue(RetTy);
3913     }
3914     if (C->isNegative() && !C->isNegZero()) {
3915       assert(!C->isNaN() && "Unexpected NaN constant!");
3916       // TODO: We can catch more cases by using a range check rather than
3917       //       relying on CannotBeOrderedLessThanZero.
3918       switch (Pred) {
3919       case FCmpInst::FCMP_UGE:
3920       case FCmpInst::FCMP_UGT:
3921       case FCmpInst::FCMP_UNE:
3922         // (X >= 0) implies (X > C) when (C < 0)
3923         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3924           return getTrue(RetTy);
3925         break;
3926       case FCmpInst::FCMP_OEQ:
3927       case FCmpInst::FCMP_OLE:
3928       case FCmpInst::FCMP_OLT:
3929         // (X >= 0) implies !(X < C) when (C < 0)
3930         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3931           return getFalse(RetTy);
3932         break;
3933       default:
3934         break;
3935       }
3936     }
3937 
3938     // Check comparison of [minnum/maxnum with constant] with other constant.
3939     const APFloat *C2;
3940     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3941          *C2 < *C) ||
3942         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3943          *C2 > *C)) {
3944       bool IsMaxNum =
3945           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3946       // The ordered relationship and minnum/maxnum guarantee that we do not
3947       // have NaN constants, so ordered/unordered preds are handled the same.
3948       switch (Pred) {
3949       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3950         // minnum(X, LesserC)  == C --> false
3951         // maxnum(X, GreaterC) == C --> false
3952         return getFalse(RetTy);
3953       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3954         // minnum(X, LesserC)  != C --> true
3955         // maxnum(X, GreaterC) != C --> true
3956         return getTrue(RetTy);
3957       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3958       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3959         // minnum(X, LesserC)  >= C --> false
3960         // minnum(X, LesserC)  >  C --> false
3961         // maxnum(X, GreaterC) >= C --> true
3962         // maxnum(X, GreaterC) >  C --> true
3963         return ConstantInt::get(RetTy, IsMaxNum);
3964       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3965       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3966         // minnum(X, LesserC)  <= C --> true
3967         // minnum(X, LesserC)  <  C --> true
3968         // maxnum(X, GreaterC) <= C --> false
3969         // maxnum(X, GreaterC) <  C --> false
3970         return ConstantInt::get(RetTy, !IsMaxNum);
3971       default:
3972         // TRUE/FALSE/ORD/UNO should be handled before this.
3973         llvm_unreachable("Unexpected fcmp predicate");
3974       }
3975     }
3976   }
3977 
3978   if (match(RHS, m_AnyZeroFP())) {
3979     switch (Pred) {
3980     case FCmpInst::FCMP_OGE:
3981     case FCmpInst::FCMP_ULT:
3982       // Positive or zero X >= 0.0 --> true
3983       // Positive or zero X <  0.0 --> false
3984       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3985           CannotBeOrderedLessThanZero(LHS, Q.TLI))
3986         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3987       break;
3988     case FCmpInst::FCMP_UGE:
3989     case FCmpInst::FCMP_OLT:
3990       // Positive or zero or nan X >= 0.0 --> true
3991       // Positive or zero or nan X <  0.0 --> false
3992       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3993         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3994       break;
3995     default:
3996       break;
3997     }
3998   }
3999 
4000   // If the comparison is with the result of a select instruction, check whether
4001   // comparing with either branch of the select always yields the same value.
4002   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4003     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4004       return V;
4005 
4006   // If the comparison is with the result of a phi instruction, check whether
4007   // doing the compare with each incoming phi value yields a common result.
4008   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4009     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4010       return V;
4011 
4012   return nullptr;
4013 }
4014 
4015 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4016                               FastMathFlags FMF, const SimplifyQuery &Q) {
4017   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4018 }
4019 
4020 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4021                                      const SimplifyQuery &Q,
4022                                      bool AllowRefinement,
4023                                      unsigned MaxRecurse) {
4024   assert(!Op->getType()->isVectorTy() && "This is not safe for vectors");
4025 
4026   // Trivial replacement.
4027   if (V == Op)
4028     return RepOp;
4029 
4030   // We cannot replace a constant, and shouldn't even try.
4031   if (isa<Constant>(Op))
4032     return nullptr;
4033 
4034   auto *I = dyn_cast<Instruction>(V);
4035   if (!I || !is_contained(I->operands(), Op))
4036     return nullptr;
4037 
4038   // Replace Op with RepOp in instruction operands.
4039   SmallVector<Value *, 8> NewOps(I->getNumOperands());
4040   transform(I->operands(), NewOps.begin(),
4041             [&](Value *V) { return V == Op ? RepOp : V; });
4042 
4043   if (!AllowRefinement) {
4044     // General InstSimplify functions may refine the result, e.g. by returning
4045     // a constant for a potentially poison value. To avoid this, implement only
4046     // a few non-refining but profitable transforms here.
4047 
4048     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4049       unsigned Opcode = BO->getOpcode();
4050       // id op x -> x, x op id -> x
4051       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4052         return NewOps[1];
4053       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4054                                                       /* RHS */ true))
4055         return NewOps[0];
4056 
4057       // x & x -> x, x | x -> x
4058       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4059           NewOps[0] == NewOps[1])
4060         return NewOps[0];
4061     }
4062 
4063     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4064       // getelementptr x, 0 -> x
4065       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
4066           !GEP->isInBounds())
4067         return NewOps[0];
4068     }
4069   } else if (MaxRecurse) {
4070     // The simplification queries below may return the original value. Consider:
4071     //   %div = udiv i32 %arg, %arg2
4072     //   %mul = mul nsw i32 %div, %arg2
4073     //   %cmp = icmp eq i32 %mul, %arg
4074     //   %sel = select i1 %cmp, i32 %div, i32 undef
4075     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4076     // simplifies back to %arg. This can only happen because %mul does not
4077     // dominate %div. To ensure a consistent return value contract, we make sure
4078     // that this case returns nullptr as well.
4079     auto PreventSelfSimplify = [V](Value *Simplified) {
4080       return Simplified != V ? Simplified : nullptr;
4081     };
4082 
4083     if (auto *B = dyn_cast<BinaryOperator>(I))
4084       return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0],
4085                                                NewOps[1], Q, MaxRecurse - 1));
4086 
4087     if (CmpInst *C = dyn_cast<CmpInst>(I))
4088       return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0],
4089                                                  NewOps[1], Q, MaxRecurse - 1));
4090 
4091     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4092       return PreventSelfSimplify(SimplifyGEPInst(
4093           GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
4094           GEP->isInBounds(), Q, MaxRecurse - 1));
4095 
4096     if (isa<SelectInst>(I))
4097       return PreventSelfSimplify(
4098           SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q,
4099                              MaxRecurse - 1));
4100     // TODO: We could hand off more cases to instsimplify here.
4101   }
4102 
4103   // If all operands are constant after substituting Op for RepOp then we can
4104   // constant fold the instruction.
4105   SmallVector<Constant *, 8> ConstOps;
4106   for (Value *NewOp : NewOps) {
4107     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4108       ConstOps.push_back(ConstOp);
4109     else
4110       return nullptr;
4111   }
4112 
4113   // Consider:
4114   //   %cmp = icmp eq i32 %x, 2147483647
4115   //   %add = add nsw i32 %x, 1
4116   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4117   //
4118   // We can't replace %sel with %add unless we strip away the flags (which
4119   // will be done in InstCombine).
4120   // TODO: This may be unsound, because it only catches some forms of
4121   // refinement.
4122   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4123     return nullptr;
4124 
4125   if (CmpInst *C = dyn_cast<CmpInst>(I))
4126     return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4127                                            ConstOps[1], Q.DL, Q.TLI);
4128 
4129   if (LoadInst *LI = dyn_cast<LoadInst>(I))
4130     if (!LI->isVolatile())
4131       return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4132 
4133   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4134 }
4135 
4136 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4137                                     const SimplifyQuery &Q,
4138                                     bool AllowRefinement) {
4139   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4140                                   RecursionLimit);
4141 }
4142 
4143 /// Try to simplify a select instruction when its condition operand is an
4144 /// integer comparison where one operand of the compare is a constant.
4145 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4146                                     const APInt *Y, bool TrueWhenUnset) {
4147   const APInt *C;
4148 
4149   // (X & Y) == 0 ? X & ~Y : X  --> X
4150   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4151   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4152       *Y == ~*C)
4153     return TrueWhenUnset ? FalseVal : TrueVal;
4154 
4155   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4156   // (X & Y) != 0 ? X : X & ~Y  --> X
4157   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4158       *Y == ~*C)
4159     return TrueWhenUnset ? FalseVal : TrueVal;
4160 
4161   if (Y->isPowerOf2()) {
4162     // (X & Y) == 0 ? X | Y : X  --> X | Y
4163     // (X & Y) != 0 ? X | Y : X  --> X
4164     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4165         *Y == *C)
4166       return TrueWhenUnset ? TrueVal : FalseVal;
4167 
4168     // (X & Y) == 0 ? X : X | Y  --> X
4169     // (X & Y) != 0 ? X : X | Y  --> X | Y
4170     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4171         *Y == *C)
4172       return TrueWhenUnset ? TrueVal : FalseVal;
4173   }
4174 
4175   return nullptr;
4176 }
4177 
4178 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4179 /// eq/ne.
4180 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4181                                            ICmpInst::Predicate Pred,
4182                                            Value *TrueVal, Value *FalseVal) {
4183   Value *X;
4184   APInt Mask;
4185   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4186     return nullptr;
4187 
4188   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4189                                Pred == ICmpInst::ICMP_EQ);
4190 }
4191 
4192 /// Try to simplify a select instruction when its condition operand is an
4193 /// integer comparison.
4194 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4195                                          Value *FalseVal, const SimplifyQuery &Q,
4196                                          unsigned MaxRecurse) {
4197   ICmpInst::Predicate Pred;
4198   Value *CmpLHS, *CmpRHS;
4199   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4200     return nullptr;
4201 
4202   // Canonicalize ne to eq predicate.
4203   if (Pred == ICmpInst::ICMP_NE) {
4204     Pred = ICmpInst::ICMP_EQ;
4205     std::swap(TrueVal, FalseVal);
4206   }
4207 
4208   // Check for integer min/max with a limit constant:
4209   // X > MIN_INT ? X : MIN_INT --> X
4210   // X < MAX_INT ? X : MAX_INT --> X
4211   if (TrueVal->getType()->isIntOrIntVectorTy()) {
4212     Value *X, *Y;
4213     SelectPatternFlavor SPF =
4214         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4215                                      X, Y).Flavor;
4216     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4217       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4218                                     X->getType()->getScalarSizeInBits());
4219       if (match(Y, m_SpecificInt(LimitC)))
4220         return X;
4221     }
4222   }
4223 
4224   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4225     Value *X;
4226     const APInt *Y;
4227     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4228       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4229                                            /*TrueWhenUnset=*/true))
4230         return V;
4231 
4232     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4233     Value *ShAmt;
4234     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4235                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4236     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4237     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4238     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4239       return X;
4240 
4241     // Test for a zero-shift-guard-op around rotates. These are used to
4242     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4243     // intrinsics do not have that problem.
4244     // We do not allow this transform for the general funnel shift case because
4245     // that would not preserve the poison safety of the original code.
4246     auto isRotate =
4247         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4248                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4249     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4250     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4251     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4252         Pred == ICmpInst::ICMP_EQ)
4253       return FalseVal;
4254 
4255     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4256     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4257     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4258         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4259       return FalseVal;
4260     if (match(TrueVal,
4261               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4262         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4263       return FalseVal;
4264   }
4265 
4266   // Check for other compares that behave like bit test.
4267   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
4268                                               TrueVal, FalseVal))
4269     return V;
4270 
4271   // If we have a scalar equality comparison, then we know the value in one of
4272   // the arms of the select. See if substituting this value into the arm and
4273   // simplifying the result yields the same value as the other arm.
4274   // Note that the equivalence/replacement opportunity does not hold for vectors
4275   // because each element of a vector select is chosen independently.
4276   if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
4277     if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4278                                /* AllowRefinement */ false, MaxRecurse) ==
4279             TrueVal ||
4280         simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4281                                /* AllowRefinement */ false, MaxRecurse) ==
4282             TrueVal)
4283       return FalseVal;
4284     if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4285                                /* AllowRefinement */ true, MaxRecurse) ==
4286             FalseVal ||
4287         simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4288                                /* AllowRefinement */ true, MaxRecurse) ==
4289             FalseVal)
4290       return FalseVal;
4291   }
4292 
4293   return nullptr;
4294 }
4295 
4296 /// Try to simplify a select instruction when its condition operand is a
4297 /// floating-point comparison.
4298 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4299                                      const SimplifyQuery &Q) {
4300   FCmpInst::Predicate Pred;
4301   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4302       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4303     return nullptr;
4304 
4305   // This transform is safe if we do not have (do not care about) -0.0 or if
4306   // at least one operand is known to not be -0.0. Otherwise, the select can
4307   // change the sign of a zero operand.
4308   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4309                           Q.CxtI->hasNoSignedZeros();
4310   const APFloat *C;
4311   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4312                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4313     // (T == F) ? T : F --> F
4314     // (F == T) ? T : F --> F
4315     if (Pred == FCmpInst::FCMP_OEQ)
4316       return F;
4317 
4318     // (T != F) ? T : F --> T
4319     // (F != T) ? T : F --> T
4320     if (Pred == FCmpInst::FCMP_UNE)
4321       return T;
4322   }
4323 
4324   return nullptr;
4325 }
4326 
4327 /// Given operands for a SelectInst, see if we can fold the result.
4328 /// If not, this returns null.
4329 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4330                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4331   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4332     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4333       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4334         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4335 
4336     // select poison, X, Y -> poison
4337     if (isa<PoisonValue>(CondC))
4338       return PoisonValue::get(TrueVal->getType());
4339 
4340     // select undef, X, Y -> X or Y
4341     if (Q.isUndefValue(CondC))
4342       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4343 
4344     // select true,  X, Y --> X
4345     // select false, X, Y --> Y
4346     // For vectors, allow undef/poison elements in the condition to match the
4347     // defined elements, so we can eliminate the select.
4348     if (match(CondC, m_One()))
4349       return TrueVal;
4350     if (match(CondC, m_Zero()))
4351       return FalseVal;
4352   }
4353 
4354   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4355          "Select must have bool or bool vector condition");
4356   assert(TrueVal->getType() == FalseVal->getType() &&
4357          "Select must have same types for true/false ops");
4358 
4359   if (Cond->getType() == TrueVal->getType()) {
4360     // select i1 Cond, i1 true, i1 false --> i1 Cond
4361     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4362       return Cond;
4363 
4364     // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4365     Value *X, *Y;
4366     if (match(FalseVal, m_ZeroInt())) {
4367       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4368           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4369         return X;
4370       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4371           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4372         return X;
4373     }
4374   }
4375 
4376   // select ?, X, X -> X
4377   if (TrueVal == FalseVal)
4378     return TrueVal;
4379 
4380   // If the true or false value is poison, we can fold to the other value.
4381   // If the true or false value is undef, we can fold to the other value as
4382   // long as the other value isn't poison.
4383   // select ?, poison, X -> X
4384   // select ?, undef,  X -> X
4385   if (isa<PoisonValue>(TrueVal) ||
4386       (Q.isUndefValue(TrueVal) &&
4387        isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
4388     return FalseVal;
4389   // select ?, X, poison -> X
4390   // select ?, X, undef  -> X
4391   if (isa<PoisonValue>(FalseVal) ||
4392       (Q.isUndefValue(FalseVal) &&
4393        isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
4394     return TrueVal;
4395 
4396   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4397   Constant *TrueC, *FalseC;
4398   if (isa<FixedVectorType>(TrueVal->getType()) &&
4399       match(TrueVal, m_Constant(TrueC)) &&
4400       match(FalseVal, m_Constant(FalseC))) {
4401     unsigned NumElts =
4402         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4403     SmallVector<Constant *, 16> NewC;
4404     for (unsigned i = 0; i != NumElts; ++i) {
4405       // Bail out on incomplete vector constants.
4406       Constant *TEltC = TrueC->getAggregateElement(i);
4407       Constant *FEltC = FalseC->getAggregateElement(i);
4408       if (!TEltC || !FEltC)
4409         break;
4410 
4411       // If the elements match (undef or not), that value is the result. If only
4412       // one element is undef, choose the defined element as the safe result.
4413       if (TEltC == FEltC)
4414         NewC.push_back(TEltC);
4415       else if (isa<PoisonValue>(TEltC) ||
4416                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4417         NewC.push_back(FEltC);
4418       else if (isa<PoisonValue>(FEltC) ||
4419                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4420         NewC.push_back(TEltC);
4421       else
4422         break;
4423     }
4424     if (NewC.size() == NumElts)
4425       return ConstantVector::get(NewC);
4426   }
4427 
4428   if (Value *V =
4429           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4430     return V;
4431 
4432   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4433     return V;
4434 
4435   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4436     return V;
4437 
4438   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4439   if (Imp)
4440     return *Imp ? TrueVal : FalseVal;
4441 
4442   return nullptr;
4443 }
4444 
4445 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4446                                 const SimplifyQuery &Q) {
4447   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4448 }
4449 
4450 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4451 /// If not, this returns null.
4452 static Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr,
4453                               ArrayRef<Value *> Indices, bool InBounds,
4454                               const SimplifyQuery &Q, unsigned) {
4455   // The type of the GEP pointer operand.
4456   unsigned AS =
4457       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4458 
4459   // getelementptr P -> P.
4460   if (Indices.empty())
4461     return Ptr;
4462 
4463   // Compute the (pointer) type returned by the GEP instruction.
4464   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4465   Type *GEPTy = PointerType::get(LastType, AS);
4466   if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4467     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4468   else {
4469     for (Value *Op : Indices) {
4470       // If one of the operands is a vector, the result type is a vector of
4471       // pointers. All vector operands must have the same number of elements.
4472       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4473         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4474         break;
4475       }
4476     }
4477   }
4478 
4479   // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
4480   // it may be equivalent to a bitcast.
4481   if (Ptr->getType()->isOpaquePointerTy() &&
4482       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4483     return Ptr;
4484 
4485   // getelementptr poison, idx -> poison
4486   // getelementptr baseptr, poison -> poison
4487   if (isa<PoisonValue>(Ptr) ||
4488       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4489     return PoisonValue::get(GEPTy);
4490 
4491   if (Q.isUndefValue(Ptr))
4492     // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
4493     return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
4494 
4495   bool IsScalableVec =
4496       isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
4497         return isa<ScalableVectorType>(V->getType());
4498       });
4499 
4500   if (Indices.size() == 1) {
4501     // getelementptr P, 0 -> P.
4502     if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4503       return Ptr;
4504 
4505     Type *Ty = SrcTy;
4506     if (!IsScalableVec && Ty->isSized()) {
4507       Value *P;
4508       uint64_t C;
4509       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4510       // getelementptr P, N -> P if P points to a type of zero size.
4511       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
4512         return Ptr;
4513 
4514       // The following transforms are only safe if the ptrtoint cast
4515       // doesn't truncate the pointers.
4516       if (Indices[0]->getType()->getScalarSizeInBits() ==
4517           Q.DL.getPointerSizeInBits(AS)) {
4518         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
4519           return P->getType() == GEPTy &&
4520                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
4521         };
4522         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4523         if (TyAllocSize == 1 &&
4524             match(Indices[0],
4525                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
4526             CanSimplify())
4527           return P;
4528 
4529         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
4530         // size 1 << C.
4531         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4532                                            m_PtrToInt(m_Specific(Ptr))),
4533                                      m_ConstantInt(C))) &&
4534             TyAllocSize == 1ULL << C && CanSimplify())
4535           return P;
4536 
4537         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
4538         // size C.
4539         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4540                                            m_PtrToInt(m_Specific(Ptr))),
4541                                      m_SpecificInt(TyAllocSize))) &&
4542             CanSimplify())
4543           return P;
4544       }
4545     }
4546   }
4547 
4548   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4549       all_of(Indices.drop_back(1),
4550              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4551     unsigned IdxWidth =
4552         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
4553     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
4554       APInt BasePtrOffset(IdxWidth, 0);
4555       Value *StrippedBasePtr =
4556           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
4557 
4558       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4559       // inttoptr is generally conservative, this particular case is folded to
4560       // a null pointer, which will have incorrect provenance.
4561 
4562       // gep (gep V, C), (sub 0, V) -> C
4563       if (match(Indices.back(),
4564                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4565           !BasePtrOffset.isZero()) {
4566         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4567         return ConstantExpr::getIntToPtr(CI, GEPTy);
4568       }
4569       // gep (gep V, C), (xor V, -1) -> C-1
4570       if (match(Indices.back(),
4571                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4572           !BasePtrOffset.isOne()) {
4573         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4574         return ConstantExpr::getIntToPtr(CI, GEPTy);
4575       }
4576     }
4577   }
4578 
4579   // Check to see if this is constant foldable.
4580   if (!isa<Constant>(Ptr) ||
4581       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
4582     return nullptr;
4583 
4584   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
4585                                             InBounds);
4586   return ConstantFoldConstant(CE, Q.DL);
4587 }
4588 
4589 Value *llvm::SimplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
4590                              bool InBounds, const SimplifyQuery &Q) {
4591   return ::SimplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
4592 }
4593 
4594 /// Given operands for an InsertValueInst, see if we can fold the result.
4595 /// If not, this returns null.
4596 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4597                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4598                                       unsigned) {
4599   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4600     if (Constant *CVal = dyn_cast<Constant>(Val))
4601       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4602 
4603   // insertvalue x, undef, n -> x
4604   if (Q.isUndefValue(Val))
4605     return Agg;
4606 
4607   // insertvalue x, (extractvalue y, n), n
4608   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4609     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4610         EV->getIndices() == Idxs) {
4611       // insertvalue undef, (extractvalue y, n), n -> y
4612       if (Q.isUndefValue(Agg))
4613         return EV->getAggregateOperand();
4614 
4615       // insertvalue y, (extractvalue y, n), n -> y
4616       if (Agg == EV->getAggregateOperand())
4617         return Agg;
4618     }
4619 
4620   return nullptr;
4621 }
4622 
4623 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4624                                      ArrayRef<unsigned> Idxs,
4625                                      const SimplifyQuery &Q) {
4626   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4627 }
4628 
4629 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4630                                        const SimplifyQuery &Q) {
4631   // Try to constant fold.
4632   auto *VecC = dyn_cast<Constant>(Vec);
4633   auto *ValC = dyn_cast<Constant>(Val);
4634   auto *IdxC = dyn_cast<Constant>(Idx);
4635   if (VecC && ValC && IdxC)
4636     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4637 
4638   // For fixed-length vector, fold into poison if index is out of bounds.
4639   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4640     if (isa<FixedVectorType>(Vec->getType()) &&
4641         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4642       return PoisonValue::get(Vec->getType());
4643   }
4644 
4645   // If index is undef, it might be out of bounds (see above case)
4646   if (Q.isUndefValue(Idx))
4647     return PoisonValue::get(Vec->getType());
4648 
4649   // If the scalar is poison, or it is undef and there is no risk of
4650   // propagating poison from the vector value, simplify to the vector value.
4651   if (isa<PoisonValue>(Val) ||
4652       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4653     return Vec;
4654 
4655   // If we are extracting a value from a vector, then inserting it into the same
4656   // place, that's the input vector:
4657   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4658   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4659     return Vec;
4660 
4661   return nullptr;
4662 }
4663 
4664 /// Given operands for an ExtractValueInst, see if we can fold the result.
4665 /// If not, this returns null.
4666 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4667                                        const SimplifyQuery &, unsigned) {
4668   if (auto *CAgg = dyn_cast<Constant>(Agg))
4669     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4670 
4671   // extractvalue x, (insertvalue y, elt, n), n -> elt
4672   unsigned NumIdxs = Idxs.size();
4673   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4674        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4675     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4676     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4677     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4678     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4679         Idxs.slice(0, NumCommonIdxs)) {
4680       if (NumIdxs == NumInsertValueIdxs)
4681         return IVI->getInsertedValueOperand();
4682       break;
4683     }
4684   }
4685 
4686   return nullptr;
4687 }
4688 
4689 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4690                                       const SimplifyQuery &Q) {
4691   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4692 }
4693 
4694 /// Given operands for an ExtractElementInst, see if we can fold the result.
4695 /// If not, this returns null.
4696 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
4697                                          const SimplifyQuery &Q, unsigned) {
4698   auto *VecVTy = cast<VectorType>(Vec->getType());
4699   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4700     if (auto *CIdx = dyn_cast<Constant>(Idx))
4701       return ConstantExpr::getExtractElement(CVec, CIdx);
4702 
4703     if (Q.isUndefValue(Vec))
4704       return UndefValue::get(VecVTy->getElementType());
4705   }
4706 
4707   // An undef extract index can be arbitrarily chosen to be an out-of-range
4708   // index value, which would result in the instruction being poison.
4709   if (Q.isUndefValue(Idx))
4710     return PoisonValue::get(VecVTy->getElementType());
4711 
4712   // If extracting a specified index from the vector, see if we can recursively
4713   // find a previously computed scalar that was inserted into the vector.
4714   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4715     // For fixed-length vector, fold into undef if index is out of bounds.
4716     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
4717     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
4718       return PoisonValue::get(VecVTy->getElementType());
4719     // Handle case where an element is extracted from a splat.
4720     if (IdxC->getValue().ult(MinNumElts))
4721       if (auto *Splat = getSplatValue(Vec))
4722         return Splat;
4723     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4724       return Elt;
4725   } else {
4726     // The index is not relevant if our vector is a splat.
4727     if (Value *Splat = getSplatValue(Vec))
4728       return Splat;
4729   }
4730   return nullptr;
4731 }
4732 
4733 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4734                                         const SimplifyQuery &Q) {
4735   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4736 }
4737 
4738 /// See if we can fold the given phi. If not, returns null.
4739 static Value *SimplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
4740                               const SimplifyQuery &Q) {
4741   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4742   //          here, because the PHI we may succeed simplifying to was not
4743   //          def-reachable from the original PHI!
4744 
4745   // If all of the PHI's incoming values are the same then replace the PHI node
4746   // with the common value.
4747   Value *CommonValue = nullptr;
4748   bool HasUndefInput = false;
4749   for (Value *Incoming : IncomingValues) {
4750     // If the incoming value is the phi node itself, it can safely be skipped.
4751     if (Incoming == PN) continue;
4752     if (Q.isUndefValue(Incoming)) {
4753       // Remember that we saw an undef value, but otherwise ignore them.
4754       HasUndefInput = true;
4755       continue;
4756     }
4757     if (CommonValue && Incoming != CommonValue)
4758       return nullptr;  // Not the same, bail out.
4759     CommonValue = Incoming;
4760   }
4761 
4762   // If CommonValue is null then all of the incoming values were either undef or
4763   // equal to the phi node itself.
4764   if (!CommonValue)
4765     return UndefValue::get(PN->getType());
4766 
4767   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4768   // instruction, we cannot return X as the result of the PHI node unless it
4769   // dominates the PHI block.
4770   if (HasUndefInput)
4771     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4772 
4773   return CommonValue;
4774 }
4775 
4776 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4777                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4778   if (auto *C = dyn_cast<Constant>(Op))
4779     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4780 
4781   if (auto *CI = dyn_cast<CastInst>(Op)) {
4782     auto *Src = CI->getOperand(0);
4783     Type *SrcTy = Src->getType();
4784     Type *MidTy = CI->getType();
4785     Type *DstTy = Ty;
4786     if (Src->getType() == Ty) {
4787       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4788       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4789       Type *SrcIntPtrTy =
4790           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4791       Type *MidIntPtrTy =
4792           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4793       Type *DstIntPtrTy =
4794           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4795       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4796                                          SrcIntPtrTy, MidIntPtrTy,
4797                                          DstIntPtrTy) == Instruction::BitCast)
4798         return Src;
4799     }
4800   }
4801 
4802   // bitcast x -> x
4803   if (CastOpc == Instruction::BitCast)
4804     if (Op->getType() == Ty)
4805       return Op;
4806 
4807   return nullptr;
4808 }
4809 
4810 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4811                               const SimplifyQuery &Q) {
4812   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4813 }
4814 
4815 /// For the given destination element of a shuffle, peek through shuffles to
4816 /// match a root vector source operand that contains that element in the same
4817 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4818 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4819                                    int MaskVal, Value *RootVec,
4820                                    unsigned MaxRecurse) {
4821   if (!MaxRecurse--)
4822     return nullptr;
4823 
4824   // Bail out if any mask value is undefined. That kind of shuffle may be
4825   // simplified further based on demanded bits or other folds.
4826   if (MaskVal == -1)
4827     return nullptr;
4828 
4829   // The mask value chooses which source operand we need to look at next.
4830   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4831   int RootElt = MaskVal;
4832   Value *SourceOp = Op0;
4833   if (MaskVal >= InVecNumElts) {
4834     RootElt = MaskVal - InVecNumElts;
4835     SourceOp = Op1;
4836   }
4837 
4838   // If the source operand is a shuffle itself, look through it to find the
4839   // matching root vector.
4840   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4841     return foldIdentityShuffles(
4842         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4843         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4844   }
4845 
4846   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4847   // size?
4848 
4849   // The source operand is not a shuffle. Initialize the root vector value for
4850   // this shuffle if that has not been done yet.
4851   if (!RootVec)
4852     RootVec = SourceOp;
4853 
4854   // Give up as soon as a source operand does not match the existing root value.
4855   if (RootVec != SourceOp)
4856     return nullptr;
4857 
4858   // The element must be coming from the same lane in the source vector
4859   // (although it may have crossed lanes in intermediate shuffles).
4860   if (RootElt != DestElt)
4861     return nullptr;
4862 
4863   return RootVec;
4864 }
4865 
4866 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4867                                         ArrayRef<int> Mask, Type *RetTy,
4868                                         const SimplifyQuery &Q,
4869                                         unsigned MaxRecurse) {
4870   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4871     return UndefValue::get(RetTy);
4872 
4873   auto *InVecTy = cast<VectorType>(Op0->getType());
4874   unsigned MaskNumElts = Mask.size();
4875   ElementCount InVecEltCount = InVecTy->getElementCount();
4876 
4877   bool Scalable = InVecEltCount.isScalable();
4878 
4879   SmallVector<int, 32> Indices;
4880   Indices.assign(Mask.begin(), Mask.end());
4881 
4882   // Canonicalization: If mask does not select elements from an input vector,
4883   // replace that input vector with poison.
4884   if (!Scalable) {
4885     bool MaskSelects0 = false, MaskSelects1 = false;
4886     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4887     for (unsigned i = 0; i != MaskNumElts; ++i) {
4888       if (Indices[i] == -1)
4889         continue;
4890       if ((unsigned)Indices[i] < InVecNumElts)
4891         MaskSelects0 = true;
4892       else
4893         MaskSelects1 = true;
4894     }
4895     if (!MaskSelects0)
4896       Op0 = PoisonValue::get(InVecTy);
4897     if (!MaskSelects1)
4898       Op1 = PoisonValue::get(InVecTy);
4899   }
4900 
4901   auto *Op0Const = dyn_cast<Constant>(Op0);
4902   auto *Op1Const = dyn_cast<Constant>(Op1);
4903 
4904   // If all operands are constant, constant fold the shuffle. This
4905   // transformation depends on the value of the mask which is not known at
4906   // compile time for scalable vectors
4907   if (Op0Const && Op1Const)
4908     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4909 
4910   // Canonicalization: if only one input vector is constant, it shall be the
4911   // second one. This transformation depends on the value of the mask which
4912   // is not known at compile time for scalable vectors
4913   if (!Scalable && Op0Const && !Op1Const) {
4914     std::swap(Op0, Op1);
4915     ShuffleVectorInst::commuteShuffleMask(Indices,
4916                                           InVecEltCount.getKnownMinValue());
4917   }
4918 
4919   // A splat of an inserted scalar constant becomes a vector constant:
4920   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4921   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4922   //       original mask constant.
4923   // NOTE: This transformation depends on the value of the mask which is not
4924   // known at compile time for scalable vectors
4925   Constant *C;
4926   ConstantInt *IndexC;
4927   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4928                                           m_ConstantInt(IndexC)))) {
4929     // Match a splat shuffle mask of the insert index allowing undef elements.
4930     int InsertIndex = IndexC->getZExtValue();
4931     if (all_of(Indices, [InsertIndex](int MaskElt) {
4932           return MaskElt == InsertIndex || MaskElt == -1;
4933         })) {
4934       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4935 
4936       // Shuffle mask undefs become undefined constant result elements.
4937       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4938       for (unsigned i = 0; i != MaskNumElts; ++i)
4939         if (Indices[i] == -1)
4940           VecC[i] = UndefValue::get(C->getType());
4941       return ConstantVector::get(VecC);
4942     }
4943   }
4944 
4945   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4946   // value type is same as the input vectors' type.
4947   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4948     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
4949         is_splat(OpShuf->getShuffleMask()))
4950       return Op0;
4951 
4952   // All remaining transformation depend on the value of the mask, which is
4953   // not known at compile time for scalable vectors.
4954   if (Scalable)
4955     return nullptr;
4956 
4957   // Don't fold a shuffle with undef mask elements. This may get folded in a
4958   // better way using demanded bits or other analysis.
4959   // TODO: Should we allow this?
4960   if (is_contained(Indices, -1))
4961     return nullptr;
4962 
4963   // Check if every element of this shuffle can be mapped back to the
4964   // corresponding element of a single root vector. If so, we don't need this
4965   // shuffle. This handles simple identity shuffles as well as chains of
4966   // shuffles that may widen/narrow and/or move elements across lanes and back.
4967   Value *RootVec = nullptr;
4968   for (unsigned i = 0; i != MaskNumElts; ++i) {
4969     // Note that recursion is limited for each vector element, so if any element
4970     // exceeds the limit, this will fail to simplify.
4971     RootVec =
4972         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4973 
4974     // We can't replace a widening/narrowing shuffle with one of its operands.
4975     if (!RootVec || RootVec->getType() != RetTy)
4976       return nullptr;
4977   }
4978   return RootVec;
4979 }
4980 
4981 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4982 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4983                                        ArrayRef<int> Mask, Type *RetTy,
4984                                        const SimplifyQuery &Q) {
4985   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4986 }
4987 
4988 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4989                               Value *&Op, const SimplifyQuery &Q) {
4990   if (auto *C = dyn_cast<Constant>(Op))
4991     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4992   return nullptr;
4993 }
4994 
4995 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
4996 /// returns null.
4997 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4998                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4999   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5000     return C;
5001 
5002   Value *X;
5003   // fneg (fneg X) ==> X
5004   if (match(Op, m_FNeg(m_Value(X))))
5005     return X;
5006 
5007   return nullptr;
5008 }
5009 
5010 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
5011                               const SimplifyQuery &Q) {
5012   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5013 }
5014 
5015 static Constant *propagateNaN(Constant *In) {
5016   // If the input is a vector with undef elements, just return a default NaN.
5017   if (!In->isNaN())
5018     return ConstantFP::getNaN(In->getType());
5019 
5020   // Propagate the existing NaN constant when possible.
5021   // TODO: Should we quiet a signaling NaN?
5022   return In;
5023 }
5024 
5025 /// Perform folds that are common to any floating-point operation. This implies
5026 /// transforms based on poison/undef/NaN because the operation itself makes no
5027 /// difference to the result.
5028 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5029                               const SimplifyQuery &Q,
5030                               fp::ExceptionBehavior ExBehavior,
5031                               RoundingMode Rounding) {
5032   // Poison is independent of anything else. It always propagates from an
5033   // operand to a math result.
5034   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5035     return PoisonValue::get(Ops[0]->getType());
5036 
5037   for (Value *V : Ops) {
5038     bool IsNan = match(V, m_NaN());
5039     bool IsInf = match(V, m_Inf());
5040     bool IsUndef = Q.isUndefValue(V);
5041 
5042     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5043     // (an undef operand can be chosen to be Nan/Inf), then the result of
5044     // this operation is poison.
5045     if (FMF.noNaNs() && (IsNan || IsUndef))
5046       return PoisonValue::get(V->getType());
5047     if (FMF.noInfs() && (IsInf || IsUndef))
5048       return PoisonValue::get(V->getType());
5049 
5050     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5051       if (IsUndef || IsNan)
5052         return propagateNaN(cast<Constant>(V));
5053     } else if (ExBehavior != fp::ebStrict) {
5054       if (IsNan)
5055         return propagateNaN(cast<Constant>(V));
5056     }
5057   }
5058   return nullptr;
5059 }
5060 
5061 /// Given operands for an FAdd, see if we can fold the result.  If not, this
5062 /// returns null.
5063 static Value *
5064 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5065                  const SimplifyQuery &Q, unsigned MaxRecurse,
5066                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5067                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5068   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5069     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5070       return C;
5071 
5072   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5073     return C;
5074 
5075   // fadd X, -0 ==> X
5076   // With strict/constrained FP, we have these possible edge cases that do
5077   // not simplify to Op0:
5078   // fadd SNaN, -0.0 --> QNaN
5079   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5080   if (canIgnoreSNaN(ExBehavior, FMF) &&
5081       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5082        FMF.noSignedZeros()))
5083     if (match(Op1, m_NegZeroFP()))
5084       return Op0;
5085 
5086   // fadd X, 0 ==> X, when we know X is not -0
5087   if (canIgnoreSNaN(ExBehavior, FMF))
5088     if (match(Op1, m_PosZeroFP()) &&
5089         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5090       return Op0;
5091 
5092   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5093     return nullptr;
5094 
5095   // With nnan: -X + X --> 0.0 (and commuted variant)
5096   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5097   // Negative zeros are allowed because we always end up with positive zero:
5098   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5099   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5100   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5101   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5102   if (FMF.noNaNs()) {
5103     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5104         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5105       return ConstantFP::getNullValue(Op0->getType());
5106 
5107     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5108         match(Op1, m_FNeg(m_Specific(Op0))))
5109       return ConstantFP::getNullValue(Op0->getType());
5110   }
5111 
5112   // (X - Y) + Y --> X
5113   // Y + (X - Y) --> X
5114   Value *X;
5115   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5116       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5117        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5118     return X;
5119 
5120   return nullptr;
5121 }
5122 
5123 /// Given operands for an FSub, see if we can fold the result.  If not, this
5124 /// returns null.
5125 static Value *
5126 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5127                  const SimplifyQuery &Q, unsigned MaxRecurse,
5128                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5129                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5130   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5131     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5132       return C;
5133 
5134   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5135     return C;
5136 
5137   // fsub X, +0 ==> X
5138   if (canIgnoreSNaN(ExBehavior, FMF) &&
5139       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5140        FMF.noSignedZeros()))
5141     if (match(Op1, m_PosZeroFP()))
5142       return Op0;
5143 
5144   // fsub X, -0 ==> X, when we know X is not -0
5145   if (canIgnoreSNaN(ExBehavior, FMF))
5146     if (match(Op1, m_NegZeroFP()) &&
5147         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5148       return Op0;
5149 
5150   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5151     return nullptr;
5152 
5153   // fsub -0.0, (fsub -0.0, X) ==> X
5154   // fsub -0.0, (fneg X) ==> X
5155   Value *X;
5156   if (match(Op0, m_NegZeroFP()) &&
5157       match(Op1, m_FNeg(m_Value(X))))
5158     return X;
5159 
5160   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5161   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5162   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5163       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5164        match(Op1, m_FNeg(m_Value(X)))))
5165     return X;
5166 
5167   // fsub nnan x, x ==> 0.0
5168   if (FMF.noNaNs() && Op0 == Op1)
5169     return Constant::getNullValue(Op0->getType());
5170 
5171   // Y - (Y - X) --> X
5172   // (X + Y) - Y --> X
5173   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5174       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5175        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5176     return X;
5177 
5178   return nullptr;
5179 }
5180 
5181 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5182                               const SimplifyQuery &Q, unsigned MaxRecurse,
5183                               fp::ExceptionBehavior ExBehavior,
5184                               RoundingMode Rounding) {
5185   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5186     return C;
5187 
5188   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5189     return nullptr;
5190 
5191   // fmul X, 1.0 ==> X
5192   if (match(Op1, m_FPOne()))
5193     return Op0;
5194 
5195   // fmul 1.0, X ==> X
5196   if (match(Op0, m_FPOne()))
5197     return Op1;
5198 
5199   // fmul nnan nsz X, 0 ==> 0
5200   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
5201     return ConstantFP::getNullValue(Op0->getType());
5202 
5203   // fmul nnan nsz 0, X ==> 0
5204   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5205     return ConstantFP::getNullValue(Op1->getType());
5206 
5207   // sqrt(X) * sqrt(X) --> X, if we can:
5208   // 1. Remove the intermediate rounding (reassociate).
5209   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5210   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5211   Value *X;
5212   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
5213       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
5214     return X;
5215 
5216   return nullptr;
5217 }
5218 
5219 /// Given the operands for an FMul, see if we can fold the result
5220 static Value *
5221 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5222                  const SimplifyQuery &Q, unsigned MaxRecurse,
5223                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5224                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5225   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5226     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5227       return C;
5228 
5229   // Now apply simplifications that do not require rounding.
5230   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5231 }
5232 
5233 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5234                               const SimplifyQuery &Q,
5235                               fp::ExceptionBehavior ExBehavior,
5236                               RoundingMode Rounding) {
5237   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5238                             Rounding);
5239 }
5240 
5241 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5242                               const SimplifyQuery &Q,
5243                               fp::ExceptionBehavior ExBehavior,
5244                               RoundingMode Rounding) {
5245   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5246                             Rounding);
5247 }
5248 
5249 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5250                               const SimplifyQuery &Q,
5251                               fp::ExceptionBehavior ExBehavior,
5252                               RoundingMode Rounding) {
5253   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5254                             Rounding);
5255 }
5256 
5257 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5258                              const SimplifyQuery &Q,
5259                              fp::ExceptionBehavior ExBehavior,
5260                              RoundingMode Rounding) {
5261   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5262                            Rounding);
5263 }
5264 
5265 static Value *
5266 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5267                  const SimplifyQuery &Q, unsigned,
5268                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5269                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5270   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5271     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5272       return C;
5273 
5274   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5275     return C;
5276 
5277   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5278     return nullptr;
5279 
5280   // X / 1.0 -> X
5281   if (match(Op1, m_FPOne()))
5282     return Op0;
5283 
5284   // 0 / X -> 0
5285   // Requires that NaNs are off (X could be zero) and signed zeroes are
5286   // ignored (X could be positive or negative, so the output sign is unknown).
5287   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5288     return ConstantFP::getNullValue(Op0->getType());
5289 
5290   if (FMF.noNaNs()) {
5291     // X / X -> 1.0 is legal when NaNs are ignored.
5292     // We can ignore infinities because INF/INF is NaN.
5293     if (Op0 == Op1)
5294       return ConstantFP::get(Op0->getType(), 1.0);
5295 
5296     // (X * Y) / Y --> X if we can reassociate to the above form.
5297     Value *X;
5298     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5299       return X;
5300 
5301     // -X /  X -> -1.0 and
5302     //  X / -X -> -1.0 are legal when NaNs are ignored.
5303     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5304     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5305         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5306       return ConstantFP::get(Op0->getType(), -1.0);
5307   }
5308 
5309   return nullptr;
5310 }
5311 
5312 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5313                               const SimplifyQuery &Q,
5314                               fp::ExceptionBehavior ExBehavior,
5315                               RoundingMode Rounding) {
5316   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5317                             Rounding);
5318 }
5319 
5320 static Value *
5321 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5322                  const SimplifyQuery &Q, unsigned,
5323                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5324                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5325   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5326     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5327       return C;
5328 
5329   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5330     return C;
5331 
5332   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5333     return nullptr;
5334 
5335   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5336   // The constant match may include undef elements in a vector, so return a full
5337   // zero constant as the result.
5338   if (FMF.noNaNs()) {
5339     // +0 % X -> 0
5340     if (match(Op0, m_PosZeroFP()))
5341       return ConstantFP::getNullValue(Op0->getType());
5342     // -0 % X -> -0
5343     if (match(Op0, m_NegZeroFP()))
5344       return ConstantFP::getNegativeZero(Op0->getType());
5345   }
5346 
5347   return nullptr;
5348 }
5349 
5350 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5351                               const SimplifyQuery &Q,
5352                               fp::ExceptionBehavior ExBehavior,
5353                               RoundingMode Rounding) {
5354   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5355                             Rounding);
5356 }
5357 
5358 //=== Helper functions for higher up the class hierarchy.
5359 
5360 /// Given the operand for a UnaryOperator, see if we can fold the result.
5361 /// If not, this returns null.
5362 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5363                            unsigned MaxRecurse) {
5364   switch (Opcode) {
5365   case Instruction::FNeg:
5366     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5367   default:
5368     llvm_unreachable("Unexpected opcode");
5369   }
5370 }
5371 
5372 /// Given the operand for a UnaryOperator, see if we can fold the result.
5373 /// If not, this returns null.
5374 /// Try to use FastMathFlags when folding the result.
5375 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5376                              const FastMathFlags &FMF,
5377                              const SimplifyQuery &Q, unsigned MaxRecurse) {
5378   switch (Opcode) {
5379   case Instruction::FNeg:
5380     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5381   default:
5382     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5383   }
5384 }
5385 
5386 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5387   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5388 }
5389 
5390 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5391                           const SimplifyQuery &Q) {
5392   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5393 }
5394 
5395 /// Given operands for a BinaryOperator, see if we can fold the result.
5396 /// If not, this returns null.
5397 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5398                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5399   switch (Opcode) {
5400   case Instruction::Add:
5401     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5402   case Instruction::Sub:
5403     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5404   case Instruction::Mul:
5405     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
5406   case Instruction::SDiv:
5407     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
5408   case Instruction::UDiv:
5409     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5410   case Instruction::SRem:
5411     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
5412   case Instruction::URem:
5413     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
5414   case Instruction::Shl:
5415     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5416   case Instruction::LShr:
5417     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5418   case Instruction::AShr:
5419     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5420   case Instruction::And:
5421     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
5422   case Instruction::Or:
5423     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
5424   case Instruction::Xor:
5425     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
5426   case Instruction::FAdd:
5427     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5428   case Instruction::FSub:
5429     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5430   case Instruction::FMul:
5431     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5432   case Instruction::FDiv:
5433     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5434   case Instruction::FRem:
5435     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5436   default:
5437     llvm_unreachable("Unexpected opcode");
5438   }
5439 }
5440 
5441 /// Given operands for a BinaryOperator, see if we can fold the result.
5442 /// If not, this returns null.
5443 /// Try to use FastMathFlags when folding the result.
5444 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5445                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5446                             unsigned MaxRecurse) {
5447   switch (Opcode) {
5448   case Instruction::FAdd:
5449     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5450   case Instruction::FSub:
5451     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5452   case Instruction::FMul:
5453     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5454   case Instruction::FDiv:
5455     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5456   default:
5457     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5458   }
5459 }
5460 
5461 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5462                            const SimplifyQuery &Q) {
5463   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5464 }
5465 
5466 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5467                            FastMathFlags FMF, const SimplifyQuery &Q) {
5468   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5469 }
5470 
5471 /// Given operands for a CmpInst, see if we can fold the result.
5472 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5473                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5474   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5475     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5476   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5477 }
5478 
5479 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5480                              const SimplifyQuery &Q) {
5481   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5482 }
5483 
5484 static bool IsIdempotent(Intrinsic::ID ID) {
5485   switch (ID) {
5486   default: return false;
5487 
5488   // Unary idempotent: f(f(x)) = f(x)
5489   case Intrinsic::fabs:
5490   case Intrinsic::floor:
5491   case Intrinsic::ceil:
5492   case Intrinsic::trunc:
5493   case Intrinsic::rint:
5494   case Intrinsic::nearbyint:
5495   case Intrinsic::round:
5496   case Intrinsic::roundeven:
5497   case Intrinsic::canonicalize:
5498     return true;
5499   }
5500 }
5501 
5502 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5503                                    const DataLayout &DL) {
5504   GlobalValue *PtrSym;
5505   APInt PtrOffset;
5506   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5507     return nullptr;
5508 
5509   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5510   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5511   Type *Int32PtrTy = Int32Ty->getPointerTo();
5512   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5513 
5514   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5515   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5516     return nullptr;
5517 
5518   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5519   if (OffsetInt % 4 != 0)
5520     return nullptr;
5521 
5522   Constant *C = ConstantExpr::getGetElementPtr(
5523       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5524       ConstantInt::get(Int64Ty, OffsetInt / 4));
5525   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5526   if (!Loaded)
5527     return nullptr;
5528 
5529   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5530   if (!LoadedCE)
5531     return nullptr;
5532 
5533   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5534     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5535     if (!LoadedCE)
5536       return nullptr;
5537   }
5538 
5539   if (LoadedCE->getOpcode() != Instruction::Sub)
5540     return nullptr;
5541 
5542   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5543   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5544     return nullptr;
5545   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5546 
5547   Constant *LoadedRHS = LoadedCE->getOperand(1);
5548   GlobalValue *LoadedRHSSym;
5549   APInt LoadedRHSOffset;
5550   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5551                                   DL) ||
5552       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5553     return nullptr;
5554 
5555   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5556 }
5557 
5558 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5559                                      const SimplifyQuery &Q) {
5560   // Idempotent functions return the same result when called repeatedly.
5561   Intrinsic::ID IID = F->getIntrinsicID();
5562   if (IsIdempotent(IID))
5563     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5564       if (II->getIntrinsicID() == IID)
5565         return II;
5566 
5567   Value *X;
5568   switch (IID) {
5569   case Intrinsic::fabs:
5570     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5571     break;
5572   case Intrinsic::bswap:
5573     // bswap(bswap(x)) -> x
5574     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5575     break;
5576   case Intrinsic::bitreverse:
5577     // bitreverse(bitreverse(x)) -> x
5578     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5579     break;
5580   case Intrinsic::ctpop: {
5581     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5582     // ctpop(and X, 1) --> and X, 1
5583     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5584     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5585                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5586       return Op0;
5587     break;
5588   }
5589   case Intrinsic::exp:
5590     // exp(log(x)) -> x
5591     if (Q.CxtI->hasAllowReassoc() &&
5592         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5593     break;
5594   case Intrinsic::exp2:
5595     // exp2(log2(x)) -> x
5596     if (Q.CxtI->hasAllowReassoc() &&
5597         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5598     break;
5599   case Intrinsic::log:
5600     // log(exp(x)) -> x
5601     if (Q.CxtI->hasAllowReassoc() &&
5602         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5603     break;
5604   case Intrinsic::log2:
5605     // log2(exp2(x)) -> x
5606     if (Q.CxtI->hasAllowReassoc() &&
5607         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5608          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5609                                                 m_Value(X))))) return X;
5610     break;
5611   case Intrinsic::log10:
5612     // log10(pow(10.0, x)) -> x
5613     if (Q.CxtI->hasAllowReassoc() &&
5614         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5615                                                m_Value(X)))) return X;
5616     break;
5617   case Intrinsic::floor:
5618   case Intrinsic::trunc:
5619   case Intrinsic::ceil:
5620   case Intrinsic::round:
5621   case Intrinsic::roundeven:
5622   case Intrinsic::nearbyint:
5623   case Intrinsic::rint: {
5624     // floor (sitofp x) -> sitofp x
5625     // floor (uitofp x) -> uitofp x
5626     //
5627     // Converting from int always results in a finite integral number or
5628     // infinity. For either of those inputs, these rounding functions always
5629     // return the same value, so the rounding can be eliminated.
5630     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5631       return Op0;
5632     break;
5633   }
5634   case Intrinsic::experimental_vector_reverse:
5635     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5636     if (match(Op0,
5637               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5638       return X;
5639     // experimental.vector.reverse(splat(X)) -> splat(X)
5640     if (isSplatValue(Op0))
5641       return Op0;
5642     break;
5643   default:
5644     break;
5645   }
5646 
5647   return nullptr;
5648 }
5649 
5650 /// Given a min/max intrinsic, see if it can be removed based on having an
5651 /// operand that is another min/max intrinsic with shared operand(s). The caller
5652 /// is expected to swap the operand arguments to handle commutation.
5653 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5654   Value *X, *Y;
5655   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5656     return nullptr;
5657 
5658   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5659   if (!MM0)
5660     return nullptr;
5661   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5662 
5663   if (Op1 == X || Op1 == Y ||
5664       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5665     // max (max X, Y), X --> max X, Y
5666     if (IID0 == IID)
5667       return MM0;
5668     // max (min X, Y), X --> X
5669     if (IID0 == getInverseMinMaxIntrinsic(IID))
5670       return Op1;
5671   }
5672   return nullptr;
5673 }
5674 
5675 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5676                                       const SimplifyQuery &Q) {
5677   Intrinsic::ID IID = F->getIntrinsicID();
5678   Type *ReturnType = F->getReturnType();
5679   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5680   switch (IID) {
5681   case Intrinsic::abs:
5682     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5683     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5684     // on the outer abs.
5685     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5686       return Op0;
5687     break;
5688 
5689   case Intrinsic::cttz: {
5690     Value *X;
5691     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5692       return X;
5693     break;
5694   }
5695   case Intrinsic::ctlz: {
5696     Value *X;
5697     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
5698       return X;
5699     if (match(Op0, m_AShr(m_Negative(), m_Value())))
5700       return Constant::getNullValue(ReturnType);
5701     break;
5702   }
5703   case Intrinsic::smax:
5704   case Intrinsic::smin:
5705   case Intrinsic::umax:
5706   case Intrinsic::umin: {
5707     // If the arguments are the same, this is a no-op.
5708     if (Op0 == Op1)
5709       return Op0;
5710 
5711     // Canonicalize constant operand as Op1.
5712     if (isa<Constant>(Op0))
5713       std::swap(Op0, Op1);
5714 
5715     // Assume undef is the limit value.
5716     if (Q.isUndefValue(Op1))
5717       return ConstantInt::get(
5718           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
5719 
5720     const APInt *C;
5721     if (match(Op1, m_APIntAllowUndef(C))) {
5722       // Clamp to limit value. For example:
5723       // umax(i8 %x, i8 255) --> 255
5724       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
5725         return ConstantInt::get(ReturnType, *C);
5726 
5727       // If the constant op is the opposite of the limit value, the other must
5728       // be larger/smaller or equal. For example:
5729       // umin(i8 %x, i8 255) --> %x
5730       if (*C == MinMaxIntrinsic::getSaturationPoint(
5731                     getInverseMinMaxIntrinsic(IID), BitWidth))
5732         return Op0;
5733 
5734       // Remove nested call if constant operands allow it. Example:
5735       // max (max X, 7), 5 -> max X, 7
5736       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5737       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5738         // TODO: loosen undef/splat restrictions for vector constants.
5739         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5740         const APInt *InnerC;
5741         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5742             ICmpInst::compare(*InnerC, *C,
5743                               ICmpInst::getNonStrictPredicate(
5744                                   MinMaxIntrinsic::getPredicate(IID))))
5745           return Op0;
5746       }
5747     }
5748 
5749     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5750       return V;
5751     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5752       return V;
5753 
5754     ICmpInst::Predicate Pred =
5755         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
5756     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5757       return Op0;
5758     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5759       return Op1;
5760 
5761     if (Optional<bool> Imp =
5762             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5763       return *Imp ? Op0 : Op1;
5764     if (Optional<bool> Imp =
5765             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5766       return *Imp ? Op1 : Op0;
5767 
5768     break;
5769   }
5770   case Intrinsic::usub_with_overflow:
5771   case Intrinsic::ssub_with_overflow:
5772     // X - X -> { 0, false }
5773     // X - undef -> { 0, false }
5774     // undef - X -> { 0, false }
5775     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5776       return Constant::getNullValue(ReturnType);
5777     break;
5778   case Intrinsic::uadd_with_overflow:
5779   case Intrinsic::sadd_with_overflow:
5780     // X + undef -> { -1, false }
5781     // undef + x -> { -1, false }
5782     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5783       return ConstantStruct::get(
5784           cast<StructType>(ReturnType),
5785           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5786            Constant::getNullValue(ReturnType->getStructElementType(1))});
5787     }
5788     break;
5789   case Intrinsic::umul_with_overflow:
5790   case Intrinsic::smul_with_overflow:
5791     // 0 * X -> { 0, false }
5792     // X * 0 -> { 0, false }
5793     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5794       return Constant::getNullValue(ReturnType);
5795     // undef * X -> { 0, false }
5796     // X * undef -> { 0, false }
5797     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5798       return Constant::getNullValue(ReturnType);
5799     break;
5800   case Intrinsic::uadd_sat:
5801     // sat(MAX + X) -> MAX
5802     // sat(X + MAX) -> MAX
5803     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5804       return Constant::getAllOnesValue(ReturnType);
5805     LLVM_FALLTHROUGH;
5806   case Intrinsic::sadd_sat:
5807     // sat(X + undef) -> -1
5808     // sat(undef + X) -> -1
5809     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5810     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5811     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5812       return Constant::getAllOnesValue(ReturnType);
5813 
5814     // X + 0 -> X
5815     if (match(Op1, m_Zero()))
5816       return Op0;
5817     // 0 + X -> X
5818     if (match(Op0, m_Zero()))
5819       return Op1;
5820     break;
5821   case Intrinsic::usub_sat:
5822     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5823     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5824       return Constant::getNullValue(ReturnType);
5825     LLVM_FALLTHROUGH;
5826   case Intrinsic::ssub_sat:
5827     // X - X -> 0, X - undef -> 0, undef - X -> 0
5828     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5829       return Constant::getNullValue(ReturnType);
5830     // X - 0 -> X
5831     if (match(Op1, m_Zero()))
5832       return Op0;
5833     break;
5834   case Intrinsic::load_relative:
5835     if (auto *C0 = dyn_cast<Constant>(Op0))
5836       if (auto *C1 = dyn_cast<Constant>(Op1))
5837         return SimplifyRelativeLoad(C0, C1, Q.DL);
5838     break;
5839   case Intrinsic::powi:
5840     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5841       // powi(x, 0) -> 1.0
5842       if (Power->isZero())
5843         return ConstantFP::get(Op0->getType(), 1.0);
5844       // powi(x, 1) -> x
5845       if (Power->isOne())
5846         return Op0;
5847     }
5848     break;
5849   case Intrinsic::copysign:
5850     // copysign X, X --> X
5851     if (Op0 == Op1)
5852       return Op0;
5853     // copysign -X, X --> X
5854     // copysign X, -X --> -X
5855     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5856         match(Op1, m_FNeg(m_Specific(Op0))))
5857       return Op1;
5858     break;
5859   case Intrinsic::maxnum:
5860   case Intrinsic::minnum:
5861   case Intrinsic::maximum:
5862   case Intrinsic::minimum: {
5863     // If the arguments are the same, this is a no-op.
5864     if (Op0 == Op1) return Op0;
5865 
5866     // Canonicalize constant operand as Op1.
5867     if (isa<Constant>(Op0))
5868       std::swap(Op0, Op1);
5869 
5870     // If an argument is undef, return the other argument.
5871     if (Q.isUndefValue(Op1))
5872       return Op0;
5873 
5874     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5875     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5876 
5877     // minnum(X, nan) -> X
5878     // maxnum(X, nan) -> X
5879     // minimum(X, nan) -> nan
5880     // maximum(X, nan) -> nan
5881     if (match(Op1, m_NaN()))
5882       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5883 
5884     // In the following folds, inf can be replaced with the largest finite
5885     // float, if the ninf flag is set.
5886     const APFloat *C;
5887     if (match(Op1, m_APFloat(C)) &&
5888         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5889       // minnum(X, -inf) -> -inf
5890       // maxnum(X, +inf) -> +inf
5891       // minimum(X, -inf) -> -inf if nnan
5892       // maximum(X, +inf) -> +inf if nnan
5893       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5894         return ConstantFP::get(ReturnType, *C);
5895 
5896       // minnum(X, +inf) -> X if nnan
5897       // maxnum(X, -inf) -> X if nnan
5898       // minimum(X, +inf) -> X
5899       // maximum(X, -inf) -> X
5900       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5901         return Op0;
5902     }
5903 
5904     // Min/max of the same operation with common operand:
5905     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5906     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5907       if (M0->getIntrinsicID() == IID &&
5908           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5909         return Op0;
5910     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5911       if (M1->getIntrinsicID() == IID &&
5912           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5913         return Op1;
5914 
5915     break;
5916   }
5917   case Intrinsic::experimental_vector_extract: {
5918     Type *ReturnType = F->getReturnType();
5919 
5920     // (extract_vector (insert_vector _, X, 0), 0) -> X
5921     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
5922     Value *X = nullptr;
5923     if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>(
5924                        m_Value(), m_Value(X), m_Zero())) &&
5925         IdxN == 0 && X->getType() == ReturnType)
5926       return X;
5927 
5928     break;
5929   }
5930   default:
5931     break;
5932   }
5933 
5934   return nullptr;
5935 }
5936 
5937 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5938 
5939   unsigned NumOperands = Call->arg_size();
5940   Function *F = cast<Function>(Call->getCalledFunction());
5941   Intrinsic::ID IID = F->getIntrinsicID();
5942 
5943   // Most of the intrinsics with no operands have some kind of side effect.
5944   // Don't simplify.
5945   if (!NumOperands) {
5946     switch (IID) {
5947     case Intrinsic::vscale: {
5948       // Call may not be inserted into the IR yet at point of calling simplify.
5949       if (!Call->getParent() || !Call->getParent()->getParent())
5950         return nullptr;
5951       auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
5952       if (!Attr.isValid())
5953         return nullptr;
5954       unsigned VScaleMin = Attr.getVScaleRangeMin();
5955       Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
5956       if (VScaleMax && VScaleMin == VScaleMax)
5957         return ConstantInt::get(F->getReturnType(), VScaleMin);
5958       return nullptr;
5959     }
5960     default:
5961       return nullptr;
5962     }
5963   }
5964 
5965   if (NumOperands == 1)
5966     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5967 
5968   if (NumOperands == 2)
5969     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5970                                    Call->getArgOperand(1), Q);
5971 
5972   // Handle intrinsics with 3 or more arguments.
5973   switch (IID) {
5974   case Intrinsic::masked_load:
5975   case Intrinsic::masked_gather: {
5976     Value *MaskArg = Call->getArgOperand(2);
5977     Value *PassthruArg = Call->getArgOperand(3);
5978     // If the mask is all zeros or undef, the "passthru" argument is the result.
5979     if (maskIsAllZeroOrUndef(MaskArg))
5980       return PassthruArg;
5981     return nullptr;
5982   }
5983   case Intrinsic::fshl:
5984   case Intrinsic::fshr: {
5985     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5986           *ShAmtArg = Call->getArgOperand(2);
5987 
5988     // If both operands are undef, the result is undef.
5989     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
5990       return UndefValue::get(F->getReturnType());
5991 
5992     // If shift amount is undef, assume it is zero.
5993     if (Q.isUndefValue(ShAmtArg))
5994       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5995 
5996     const APInt *ShAmtC;
5997     if (match(ShAmtArg, m_APInt(ShAmtC))) {
5998       // If there's effectively no shift, return the 1st arg or 2nd arg.
5999       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6000       if (ShAmtC->urem(BitWidth).isZero())
6001         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6002     }
6003 
6004     // Rotating zero by anything is zero.
6005     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6006       return ConstantInt::getNullValue(F->getReturnType());
6007 
6008     // Rotating -1 by anything is -1.
6009     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6010       return ConstantInt::getAllOnesValue(F->getReturnType());
6011 
6012     return nullptr;
6013   }
6014   case Intrinsic::experimental_constrained_fma: {
6015     Value *Op0 = Call->getArgOperand(0);
6016     Value *Op1 = Call->getArgOperand(1);
6017     Value *Op2 = Call->getArgOperand(2);
6018     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6019     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
6020                                 FPI->getExceptionBehavior().getValue(),
6021                                 FPI->getRoundingMode().getValue()))
6022       return V;
6023     return nullptr;
6024   }
6025   case Intrinsic::fma:
6026   case Intrinsic::fmuladd: {
6027     Value *Op0 = Call->getArgOperand(0);
6028     Value *Op1 = Call->getArgOperand(1);
6029     Value *Op2 = Call->getArgOperand(2);
6030     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
6031                                 RoundingMode::NearestTiesToEven))
6032       return V;
6033     return nullptr;
6034   }
6035   case Intrinsic::smul_fix:
6036   case Intrinsic::smul_fix_sat: {
6037     Value *Op0 = Call->getArgOperand(0);
6038     Value *Op1 = Call->getArgOperand(1);
6039     Value *Op2 = Call->getArgOperand(2);
6040     Type *ReturnType = F->getReturnType();
6041 
6042     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6043     // when both Op0 and Op1 are constant so we do not care about that special
6044     // case here).
6045     if (isa<Constant>(Op0))
6046       std::swap(Op0, Op1);
6047 
6048     // X * 0 -> 0
6049     if (match(Op1, m_Zero()))
6050       return Constant::getNullValue(ReturnType);
6051 
6052     // X * undef -> 0
6053     if (Q.isUndefValue(Op1))
6054       return Constant::getNullValue(ReturnType);
6055 
6056     // X * (1 << Scale) -> X
6057     APInt ScaledOne =
6058         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6059                             cast<ConstantInt>(Op2)->getZExtValue());
6060     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6061       return Op0;
6062 
6063     return nullptr;
6064   }
6065   case Intrinsic::experimental_vector_insert: {
6066     Value *Vec = Call->getArgOperand(0);
6067     Value *SubVec = Call->getArgOperand(1);
6068     Value *Idx = Call->getArgOperand(2);
6069     Type *ReturnType = F->getReturnType();
6070 
6071     // (insert_vector Y, (extract_vector X, 0), 0) -> X
6072     // where: Y is X, or Y is undef
6073     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6074     Value *X = nullptr;
6075     if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>(
6076                           m_Value(X), m_Zero())) &&
6077         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6078         X->getType() == ReturnType)
6079       return X;
6080 
6081     return nullptr;
6082   }
6083   case Intrinsic::experimental_constrained_fadd: {
6084     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6085     return SimplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6086                             FPI->getFastMathFlags(), Q,
6087                             FPI->getExceptionBehavior().getValue(),
6088                             FPI->getRoundingMode().getValue());
6089     break;
6090   }
6091   case Intrinsic::experimental_constrained_fsub: {
6092     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6093     return SimplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6094                             FPI->getFastMathFlags(), Q,
6095                             FPI->getExceptionBehavior().getValue(),
6096                             FPI->getRoundingMode().getValue());
6097     break;
6098   }
6099   case Intrinsic::experimental_constrained_fmul: {
6100     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6101     return SimplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6102                             FPI->getFastMathFlags(), Q,
6103                             FPI->getExceptionBehavior().getValue(),
6104                             FPI->getRoundingMode().getValue());
6105     break;
6106   }
6107   case Intrinsic::experimental_constrained_fdiv: {
6108     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6109     return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6110                             FPI->getFastMathFlags(), Q,
6111                             FPI->getExceptionBehavior().getValue(),
6112                             FPI->getRoundingMode().getValue());
6113     break;
6114   }
6115   case Intrinsic::experimental_constrained_frem: {
6116     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6117     return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6118                             FPI->getFastMathFlags(), Q,
6119                             FPI->getExceptionBehavior().getValue(),
6120                             FPI->getRoundingMode().getValue());
6121     break;
6122   }
6123   default:
6124     return nullptr;
6125   }
6126 }
6127 
6128 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
6129   auto *F = dyn_cast<Function>(Call->getCalledOperand());
6130   if (!F || !canConstantFoldCallTo(Call, F))
6131     return nullptr;
6132 
6133   SmallVector<Constant *, 4> ConstantArgs;
6134   unsigned NumArgs = Call->arg_size();
6135   ConstantArgs.reserve(NumArgs);
6136   for (auto &Arg : Call->args()) {
6137     Constant *C = dyn_cast<Constant>(&Arg);
6138     if (!C) {
6139       if (isa<MetadataAsValue>(Arg.get()))
6140         continue;
6141       return nullptr;
6142     }
6143     ConstantArgs.push_back(C);
6144   }
6145 
6146   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6147 }
6148 
6149 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
6150   // musttail calls can only be simplified if they are also DCEd.
6151   // As we can't guarantee this here, don't simplify them.
6152   if (Call->isMustTailCall())
6153     return nullptr;
6154 
6155   // call undef -> poison
6156   // call null -> poison
6157   Value *Callee = Call->getCalledOperand();
6158   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6159     return PoisonValue::get(Call->getType());
6160 
6161   if (Value *V = tryConstantFoldCall(Call, Q))
6162     return V;
6163 
6164   auto *F = dyn_cast<Function>(Callee);
6165   if (F && F->isIntrinsic())
6166     if (Value *Ret = simplifyIntrinsic(Call, Q))
6167       return Ret;
6168 
6169   return nullptr;
6170 }
6171 
6172 /// Given operands for a Freeze, see if we can fold the result.
6173 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6174   // Use a utility function defined in ValueTracking.
6175   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6176     return Op0;
6177   // We have room for improvement.
6178   return nullptr;
6179 }
6180 
6181 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6182   return ::SimplifyFreezeInst(Op0, Q);
6183 }
6184 
6185 static Value *SimplifyLoadInst(LoadInst *LI, Value *PtrOp,
6186                                const SimplifyQuery &Q) {
6187   if (LI->isVolatile())
6188     return nullptr;
6189 
6190   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
6191   auto *PtrOpC = dyn_cast<Constant>(PtrOp);
6192   // Try to convert operand into a constant by stripping offsets while looking
6193   // through invariant.group intrinsics. Don't bother if the underlying object
6194   // is not constant, as calculating GEP offsets is expensive.
6195   if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
6196     PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6197         Q.DL, Offset, /* AllowNonInbounts */ true,
6198         /* AllowInvariantGroup */ true);
6199     // Index size may have changed due to address space casts.
6200     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6201     PtrOpC = dyn_cast<Constant>(PtrOp);
6202   }
6203 
6204   if (PtrOpC)
6205     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
6206   return nullptr;
6207 }
6208 
6209 /// See if we can compute a simplified version of this instruction.
6210 /// If not, this returns null.
6211 
6212 static Value *simplifyInstructionWithOperands(Instruction *I,
6213                                               ArrayRef<Value *> NewOps,
6214                                               const SimplifyQuery &SQ,
6215                                               OptimizationRemarkEmitter *ORE) {
6216   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
6217   Value *Result = nullptr;
6218 
6219   switch (I->getOpcode()) {
6220   default:
6221     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
6222       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
6223       transform(NewOps, NewConstOps.begin(),
6224                 [](Value *V) { return cast<Constant>(V); });
6225       Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
6226     }
6227     break;
6228   case Instruction::FNeg:
6229     Result = SimplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
6230     break;
6231   case Instruction::FAdd:
6232     Result = SimplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6233     break;
6234   case Instruction::Add:
6235     Result = SimplifyAddInst(
6236         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6237         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6238     break;
6239   case Instruction::FSub:
6240     Result = SimplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6241     break;
6242   case Instruction::Sub:
6243     Result = SimplifySubInst(
6244         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6245         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6246     break;
6247   case Instruction::FMul:
6248     Result = SimplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6249     break;
6250   case Instruction::Mul:
6251     Result = SimplifyMulInst(NewOps[0], NewOps[1], Q);
6252     break;
6253   case Instruction::SDiv:
6254     Result = SimplifySDivInst(NewOps[0], NewOps[1], Q);
6255     break;
6256   case Instruction::UDiv:
6257     Result = SimplifyUDivInst(NewOps[0], NewOps[1], Q);
6258     break;
6259   case Instruction::FDiv:
6260     Result = SimplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6261     break;
6262   case Instruction::SRem:
6263     Result = SimplifySRemInst(NewOps[0], NewOps[1], Q);
6264     break;
6265   case Instruction::URem:
6266     Result = SimplifyURemInst(NewOps[0], NewOps[1], Q);
6267     break;
6268   case Instruction::FRem:
6269     Result = SimplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6270     break;
6271   case Instruction::Shl:
6272     Result = SimplifyShlInst(
6273         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6274         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6275     break;
6276   case Instruction::LShr:
6277     Result = SimplifyLShrInst(NewOps[0], NewOps[1],
6278                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6279     break;
6280   case Instruction::AShr:
6281     Result = SimplifyAShrInst(NewOps[0], NewOps[1],
6282                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6283     break;
6284   case Instruction::And:
6285     Result = SimplifyAndInst(NewOps[0], NewOps[1], Q);
6286     break;
6287   case Instruction::Or:
6288     Result = SimplifyOrInst(NewOps[0], NewOps[1], Q);
6289     break;
6290   case Instruction::Xor:
6291     Result = SimplifyXorInst(NewOps[0], NewOps[1], Q);
6292     break;
6293   case Instruction::ICmp:
6294     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
6295                               NewOps[1], Q);
6296     break;
6297   case Instruction::FCmp:
6298     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
6299                               NewOps[1], I->getFastMathFlags(), Q);
6300     break;
6301   case Instruction::Select:
6302     Result = SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
6303     break;
6304   case Instruction::GetElementPtr: {
6305     auto *GEPI = cast<GetElementPtrInst>(I);
6306     Result =
6307         SimplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
6308                         makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
6309     break;
6310   }
6311   case Instruction::InsertValue: {
6312     InsertValueInst *IV = cast<InsertValueInst>(I);
6313     Result = SimplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
6314     break;
6315   }
6316   case Instruction::InsertElement: {
6317     Result = SimplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
6318     break;
6319   }
6320   case Instruction::ExtractValue: {
6321     auto *EVI = cast<ExtractValueInst>(I);
6322     Result = SimplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
6323     break;
6324   }
6325   case Instruction::ExtractElement: {
6326     Result = SimplifyExtractElementInst(NewOps[0], NewOps[1], Q);
6327     break;
6328   }
6329   case Instruction::ShuffleVector: {
6330     auto *SVI = cast<ShuffleVectorInst>(I);
6331     Result = SimplifyShuffleVectorInst(
6332         NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q);
6333     break;
6334   }
6335   case Instruction::PHI:
6336     Result = SimplifyPHINode(cast<PHINode>(I), NewOps, Q);
6337     break;
6338   case Instruction::Call: {
6339     // TODO: Use NewOps
6340     Result = SimplifyCall(cast<CallInst>(I), Q);
6341     break;
6342   }
6343   case Instruction::Freeze:
6344     Result = llvm::SimplifyFreezeInst(NewOps[0], Q);
6345     break;
6346 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
6347 #include "llvm/IR/Instruction.def"
6348 #undef HANDLE_CAST_INST
6349     Result = SimplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
6350     break;
6351   case Instruction::Alloca:
6352     // No simplifications for Alloca and it can't be constant folded.
6353     Result = nullptr;
6354     break;
6355   case Instruction::Load:
6356     Result = SimplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
6357     break;
6358   }
6359 
6360   /// If called on unreachable code, the above logic may report that the
6361   /// instruction simplified to itself.  Make life easier for users by
6362   /// detecting that case here, returning a safe value instead.
6363   return Result == I ? UndefValue::get(I->getType()) : Result;
6364 }
6365 
6366 Value *llvm::SimplifyInstructionWithOperands(Instruction *I,
6367                                              ArrayRef<Value *> NewOps,
6368                                              const SimplifyQuery &SQ,
6369                                              OptimizationRemarkEmitter *ORE) {
6370   assert(NewOps.size() == I->getNumOperands() &&
6371          "Number of operands should match the instruction!");
6372   return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
6373 }
6374 
6375 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
6376                                  OptimizationRemarkEmitter *ORE) {
6377   SmallVector<Value *, 8> Ops(I->operands());
6378   return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
6379 }
6380 
6381 /// Implementation of recursive simplification through an instruction's
6382 /// uses.
6383 ///
6384 /// This is the common implementation of the recursive simplification routines.
6385 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
6386 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
6387 /// instructions to process and attempt to simplify it using
6388 /// InstructionSimplify. Recursively visited users which could not be
6389 /// simplified themselves are to the optional UnsimplifiedUsers set for
6390 /// further processing by the caller.
6391 ///
6392 /// This routine returns 'true' only when *it* simplifies something. The passed
6393 /// in simplified value does not count toward this.
6394 static bool replaceAndRecursivelySimplifyImpl(
6395     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6396     const DominatorTree *DT, AssumptionCache *AC,
6397     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
6398   bool Simplified = false;
6399   SmallSetVector<Instruction *, 8> Worklist;
6400   const DataLayout &DL = I->getModule()->getDataLayout();
6401 
6402   // If we have an explicit value to collapse to, do that round of the
6403   // simplification loop by hand initially.
6404   if (SimpleV) {
6405     for (User *U : I->users())
6406       if (U != I)
6407         Worklist.insert(cast<Instruction>(U));
6408 
6409     // Replace the instruction with its simplified value.
6410     I->replaceAllUsesWith(SimpleV);
6411 
6412     // Gracefully handle edge cases where the instruction is not wired into any
6413     // parent block.
6414     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6415         !I->mayHaveSideEffects())
6416       I->eraseFromParent();
6417   } else {
6418     Worklist.insert(I);
6419   }
6420 
6421   // Note that we must test the size on each iteration, the worklist can grow.
6422   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6423     I = Worklist[Idx];
6424 
6425     // See if this instruction simplifies.
6426     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
6427     if (!SimpleV) {
6428       if (UnsimplifiedUsers)
6429         UnsimplifiedUsers->insert(I);
6430       continue;
6431     }
6432 
6433     Simplified = true;
6434 
6435     // Stash away all the uses of the old instruction so we can check them for
6436     // recursive simplifications after a RAUW. This is cheaper than checking all
6437     // uses of To on the recursive step in most cases.
6438     for (User *U : I->users())
6439       Worklist.insert(cast<Instruction>(U));
6440 
6441     // Replace the instruction with its simplified value.
6442     I->replaceAllUsesWith(SimpleV);
6443 
6444     // Gracefully handle edge cases where the instruction is not wired into any
6445     // parent block.
6446     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6447         !I->mayHaveSideEffects())
6448       I->eraseFromParent();
6449   }
6450   return Simplified;
6451 }
6452 
6453 bool llvm::replaceAndRecursivelySimplify(
6454     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6455     const DominatorTree *DT, AssumptionCache *AC,
6456     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6457   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6458   assert(SimpleV && "Must provide a simplified value.");
6459   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6460                                            UnsimplifiedUsers);
6461 }
6462 
6463 namespace llvm {
6464 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6465   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6466   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6467   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6468   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6469   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6470   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6471   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6472 }
6473 
6474 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6475                                          const DataLayout &DL) {
6476   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6477 }
6478 
6479 template <class T, class... TArgs>
6480 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6481                                          Function &F) {
6482   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6483   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6484   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6485   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6486 }
6487 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6488                                                   Function &);
6489 }
6490 
6491 void InstSimplifyFolder::anchor() {}
6492