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 
2559   auto isByValArgOrGlobalVarOrAlloca = [](const Value *V) {
2560     if (const Argument *A = dyn_cast<Argument>(V))
2561       return A->hasByValAttr();
2562     return isa<AllocaInst>(V) || isa<GlobalVariable>(V);
2563   };
2564 
2565   if (!isByValArgOrGlobalVarOrAlloca(V1) ||
2566       !isByValArgOrGlobalVarOrAlloca(V2))
2567     return false;
2568 
2569   // Both sides being globals shouldn't reach here - as the resulting compare
2570   // is a constantexpr - but we want to guard against it to be safe.  The
2571   // semantics of globals are complicated by e.g. unnamed_addr.  The assumption
2572   // in this code is that while two globals could end up overlapping, they'll
2573   // never overlap with any alloca or byval, and thus we can still reason about
2574   // *one* global and one *non* global as disjoint storage.
2575   return !isa<GlobalVariable>(V1) || !isa<GlobalVariable>(V2);
2576 }
2577 
2578 // A significant optimization not implemented here is assuming that alloca
2579 // addresses are not equal to incoming argument values. They don't *alias*,
2580 // as we say, but that doesn't mean they aren't equal, so we take a
2581 // conservative approach.
2582 //
2583 // This is inspired in part by C++11 5.10p1:
2584 //   "Two pointers of the same type compare equal if and only if they are both
2585 //    null, both point to the same function, or both represent the same
2586 //    address."
2587 //
2588 // This is pretty permissive.
2589 //
2590 // It's also partly due to C11 6.5.9p6:
2591 //   "Two pointers compare equal if and only if both are null pointers, both are
2592 //    pointers to the same object (including a pointer to an object and a
2593 //    subobject at its beginning) or function, both are pointers to one past the
2594 //    last element of the same array object, or one is a pointer to one past the
2595 //    end of one array object and the other is a pointer to the start of a
2596 //    different array object that happens to immediately follow the first array
2597 //    object in the address space.)
2598 //
2599 // C11's version is more restrictive, however there's no reason why an argument
2600 // couldn't be a one-past-the-end value for a stack object in the caller and be
2601 // equal to the beginning of a stack object in the callee.
2602 //
2603 // If the C and C++ standards are ever made sufficiently restrictive in this
2604 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2605 // this optimization.
2606 static Constant *
2607 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
2608                    const SimplifyQuery &Q) {
2609   const DataLayout &DL = Q.DL;
2610   const TargetLibraryInfo *TLI = Q.TLI;
2611   const DominatorTree *DT = Q.DT;
2612   const Instruction *CxtI = Q.CxtI;
2613   const InstrInfoQuery &IIQ = Q.IIQ;
2614 
2615   // First, skip past any trivial no-ops.
2616   LHS = LHS->stripPointerCasts();
2617   RHS = RHS->stripPointerCasts();
2618 
2619   // A non-null pointer is not equal to a null pointer.
2620   if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
2621       llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2622                            IIQ.UseInstrInfo))
2623     return ConstantInt::get(GetCompareTy(LHS),
2624                             !CmpInst::isTrueWhenEqual(Pred));
2625 
2626   // We can only fold certain predicates on pointer comparisons.
2627   switch (Pred) {
2628   default:
2629     return nullptr;
2630 
2631     // Equality comaprisons are easy to fold.
2632   case CmpInst::ICMP_EQ:
2633   case CmpInst::ICMP_NE:
2634     break;
2635 
2636     // We can only handle unsigned relational comparisons because 'inbounds' on
2637     // a GEP only protects against unsigned wrapping.
2638   case CmpInst::ICMP_UGT:
2639   case CmpInst::ICMP_UGE:
2640   case CmpInst::ICMP_ULT:
2641   case CmpInst::ICMP_ULE:
2642     // However, we have to switch them to their signed variants to handle
2643     // negative indices from the base pointer.
2644     Pred = ICmpInst::getSignedPredicate(Pred);
2645     break;
2646   }
2647 
2648   // Strip off any constant offsets so that we can reason about them.
2649   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2650   // here and compare base addresses like AliasAnalysis does, however there are
2651   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2652   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2653   // doesn't need to guarantee pointer inequality when it says NoAlias.
2654 
2655   // Even if an non-inbounds GEP occurs along the path we can still optimize
2656   // equality comparisons concerning the result.
2657   bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2658   APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
2659   APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
2660 
2661   // If LHS and RHS are related via constant offsets to the same base
2662   // value, we can replace it with an icmp which just compares the offsets.
2663   if (LHS == RHS)
2664     return ConstantInt::get(
2665         GetCompareTy(LHS), ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2666 
2667   // Various optimizations for (in)equality comparisons.
2668   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2669     // Different non-empty allocations that exist at the same time have
2670     // different addresses (if the program can tell). If the offsets are
2671     // within the bounds of their allocations (and not one-past-the-end!
2672     // so we can't use inbounds!), and their allocations aren't the same,
2673     // the pointers are not equal.
2674     if (HaveNonOverlappingStorage(LHS, RHS)) {
2675       uint64_t LHSSize, RHSSize;
2676       ObjectSizeOpts Opts;
2677       Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2678       auto *F = [](Value *V) {
2679         if (auto *I = dyn_cast<Instruction>(V))
2680           return I->getFunction();
2681         return cast<Argument>(V)->getParent();
2682       }(LHS);
2683       Opts.NullIsUnknownSize = NullPointerIsDefined(F);
2684       if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2685           getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
2686           !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
2687           LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
2688         return ConstantInt::get(GetCompareTy(LHS),
2689                                 !CmpInst::isTrueWhenEqual(Pred));
2690       }
2691     }
2692 
2693     // If one side of the equality comparison must come from a noalias call
2694     // (meaning a system memory allocation function), and the other side must
2695     // come from a pointer that cannot overlap with dynamically-allocated
2696     // memory within the lifetime of the current function (allocas, byval
2697     // arguments, globals), then determine the comparison result here.
2698     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2699     getUnderlyingObjects(LHS, LHSUObjs);
2700     getUnderlyingObjects(RHS, RHSUObjs);
2701 
2702     // Is the set of underlying objects all noalias calls?
2703     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2704       return all_of(Objects, isNoAliasCall);
2705     };
2706 
2707     // Is the set of underlying objects all things which must be disjoint from
2708     // noalias calls.  We assume that indexing from such disjoint storage
2709     // into the heap is undefined, and thus offsets can be safely ignored.
2710     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2711       return all_of(Objects, ::IsAllocDisjoint);
2712     };
2713 
2714     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2715         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2716         return ConstantInt::get(GetCompareTy(LHS),
2717                                 !CmpInst::isTrueWhenEqual(Pred));
2718 
2719     // Fold comparisons for non-escaping pointer even if the allocation call
2720     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2721     // dynamic allocation call could be either of the operands.  Note that
2722     // the other operand can not be based on the alloc - if it were, then
2723     // the cmp itself would be a capture.
2724     Value *MI = nullptr;
2725     if (isAllocLikeFn(LHS, TLI) &&
2726         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2727       MI = LHS;
2728     else if (isAllocLikeFn(RHS, TLI) &&
2729              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2730       MI = RHS;
2731     // FIXME: We should also fold the compare when the pointer escapes, but the
2732     // compare dominates the pointer escape
2733     if (MI && !PointerMayBeCaptured(MI, true, true))
2734       return ConstantInt::get(GetCompareTy(LHS),
2735                               CmpInst::isFalseWhenEqual(Pred));
2736   }
2737 
2738   // Otherwise, fail.
2739   return nullptr;
2740 }
2741 
2742 /// Fold an icmp when its operands have i1 scalar type.
2743 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2744                                   Value *RHS, const SimplifyQuery &Q) {
2745   Type *ITy = GetCompareTy(LHS); // The return type.
2746   Type *OpTy = LHS->getType();   // The operand type.
2747   if (!OpTy->isIntOrIntVectorTy(1))
2748     return nullptr;
2749 
2750   // A boolean compared to true/false can be reduced in 14 out of the 20
2751   // (10 predicates * 2 constants) possible combinations. The other
2752   // 6 cases require a 'not' of the LHS.
2753 
2754   auto ExtractNotLHS = [](Value *V) -> Value * {
2755     Value *X;
2756     if (match(V, m_Not(m_Value(X))))
2757       return X;
2758     return nullptr;
2759   };
2760 
2761   if (match(RHS, m_Zero())) {
2762     switch (Pred) {
2763     case CmpInst::ICMP_NE:  // X !=  0 -> X
2764     case CmpInst::ICMP_UGT: // X >u  0 -> X
2765     case CmpInst::ICMP_SLT: // X <s  0 -> X
2766       return LHS;
2767 
2768     case CmpInst::ICMP_EQ:  // not(X) ==  0 -> X != 0 -> X
2769     case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2770     case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2771       if (Value *X = ExtractNotLHS(LHS))
2772         return X;
2773       break;
2774 
2775     case CmpInst::ICMP_ULT: // X <u  0 -> false
2776     case CmpInst::ICMP_SGT: // X >s  0 -> false
2777       return getFalse(ITy);
2778 
2779     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2780     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2781       return getTrue(ITy);
2782 
2783     default: break;
2784     }
2785   } else if (match(RHS, m_One())) {
2786     switch (Pred) {
2787     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2788     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2789     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2790       return LHS;
2791 
2792     case CmpInst::ICMP_NE:  // not(X) !=  1 -> X ==   1 -> X
2793     case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u  1 -> X
2794     case CmpInst::ICMP_SGT: // not(X) >s  1 -> X <=s -1 -> X
2795       if (Value *X = ExtractNotLHS(LHS))
2796         return X;
2797       break;
2798 
2799     case CmpInst::ICMP_UGT: // X >u   1 -> false
2800     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2801       return getFalse(ITy);
2802 
2803     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2804     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2805       return getTrue(ITy);
2806 
2807     default: break;
2808     }
2809   }
2810 
2811   switch (Pred) {
2812   default:
2813     break;
2814   case ICmpInst::ICMP_UGE:
2815     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2816       return getTrue(ITy);
2817     break;
2818   case ICmpInst::ICMP_SGE:
2819     /// For signed comparison, the values for an i1 are 0 and -1
2820     /// respectively. This maps into a truth table of:
2821     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2822     ///  0  |  0  |  1 (0 >= 0)   |  1
2823     ///  0  |  1  |  1 (0 >= -1)  |  1
2824     ///  1  |  0  |  0 (-1 >= 0)  |  0
2825     ///  1  |  1  |  1 (-1 >= -1) |  1
2826     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2827       return getTrue(ITy);
2828     break;
2829   case ICmpInst::ICMP_ULE:
2830     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2831       return getTrue(ITy);
2832     break;
2833   }
2834 
2835   return nullptr;
2836 }
2837 
2838 /// Try hard to fold icmp with zero RHS because this is a common case.
2839 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2840                                    Value *RHS, const SimplifyQuery &Q) {
2841   if (!match(RHS, m_Zero()))
2842     return nullptr;
2843 
2844   Type *ITy = GetCompareTy(LHS); // The return type.
2845   switch (Pred) {
2846   default:
2847     llvm_unreachable("Unknown ICmp predicate!");
2848   case ICmpInst::ICMP_ULT:
2849     return getFalse(ITy);
2850   case ICmpInst::ICMP_UGE:
2851     return getTrue(ITy);
2852   case ICmpInst::ICMP_EQ:
2853   case ICmpInst::ICMP_ULE:
2854     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2855       return getFalse(ITy);
2856     break;
2857   case ICmpInst::ICMP_NE:
2858   case ICmpInst::ICMP_UGT:
2859     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2860       return getTrue(ITy);
2861     break;
2862   case ICmpInst::ICMP_SLT: {
2863     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2864     if (LHSKnown.isNegative())
2865       return getTrue(ITy);
2866     if (LHSKnown.isNonNegative())
2867       return getFalse(ITy);
2868     break;
2869   }
2870   case ICmpInst::ICMP_SLE: {
2871     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2872     if (LHSKnown.isNegative())
2873       return getTrue(ITy);
2874     if (LHSKnown.isNonNegative() &&
2875         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2876       return getFalse(ITy);
2877     break;
2878   }
2879   case ICmpInst::ICMP_SGE: {
2880     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2881     if (LHSKnown.isNegative())
2882       return getFalse(ITy);
2883     if (LHSKnown.isNonNegative())
2884       return getTrue(ITy);
2885     break;
2886   }
2887   case ICmpInst::ICMP_SGT: {
2888     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2889     if (LHSKnown.isNegative())
2890       return getFalse(ITy);
2891     if (LHSKnown.isNonNegative() &&
2892         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2893       return getTrue(ITy);
2894     break;
2895   }
2896   }
2897 
2898   return nullptr;
2899 }
2900 
2901 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2902                                        Value *RHS, const InstrInfoQuery &IIQ) {
2903   Type *ITy = GetCompareTy(RHS); // The return type.
2904 
2905   Value *X;
2906   // Sign-bit checks can be optimized to true/false after unsigned
2907   // floating-point casts:
2908   // icmp slt (bitcast (uitofp X)),  0 --> false
2909   // icmp sgt (bitcast (uitofp X)), -1 --> true
2910   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2911     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2912       return ConstantInt::getFalse(ITy);
2913     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2914       return ConstantInt::getTrue(ITy);
2915   }
2916 
2917   const APInt *C;
2918   if (!match(RHS, m_APIntAllowUndef(C)))
2919     return nullptr;
2920 
2921   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2922   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2923   if (RHS_CR.isEmptySet())
2924     return ConstantInt::getFalse(ITy);
2925   if (RHS_CR.isFullSet())
2926     return ConstantInt::getTrue(ITy);
2927 
2928   ConstantRange LHS_CR =
2929       computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
2930   if (!LHS_CR.isFullSet()) {
2931     if (RHS_CR.contains(LHS_CR))
2932       return ConstantInt::getTrue(ITy);
2933     if (RHS_CR.inverse().contains(LHS_CR))
2934       return ConstantInt::getFalse(ITy);
2935   }
2936 
2937   // (mul nuw/nsw X, MulC) != C --> true  (if C is not a multiple of MulC)
2938   // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
2939   const APInt *MulC;
2940   if (ICmpInst::isEquality(Pred) &&
2941       ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2942         *MulC != 0 && C->urem(*MulC) != 0) ||
2943        (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
2944         *MulC != 0 && C->srem(*MulC) != 0)))
2945     return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
2946 
2947   return nullptr;
2948 }
2949 
2950 static Value *simplifyICmpWithBinOpOnLHS(
2951     CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS,
2952     const SimplifyQuery &Q, unsigned MaxRecurse) {
2953   Type *ITy = GetCompareTy(RHS); // The return type.
2954 
2955   Value *Y = nullptr;
2956   // icmp pred (or X, Y), X
2957   if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2958     if (Pred == ICmpInst::ICMP_ULT)
2959       return getFalse(ITy);
2960     if (Pred == ICmpInst::ICMP_UGE)
2961       return getTrue(ITy);
2962 
2963     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2964       KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2965       KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2966       if (RHSKnown.isNonNegative() && YKnown.isNegative())
2967         return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2968       if (RHSKnown.isNegative() || YKnown.isNonNegative())
2969         return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2970     }
2971   }
2972 
2973   // icmp pred (and X, Y), X
2974   if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2975     if (Pred == ICmpInst::ICMP_UGT)
2976       return getFalse(ITy);
2977     if (Pred == ICmpInst::ICMP_ULE)
2978       return getTrue(ITy);
2979   }
2980 
2981   // icmp pred (urem X, Y), Y
2982   if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2983     switch (Pred) {
2984     default:
2985       break;
2986     case ICmpInst::ICMP_SGT:
2987     case ICmpInst::ICMP_SGE: {
2988       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2989       if (!Known.isNonNegative())
2990         break;
2991       LLVM_FALLTHROUGH;
2992     }
2993     case ICmpInst::ICMP_EQ:
2994     case ICmpInst::ICMP_UGT:
2995     case ICmpInst::ICMP_UGE:
2996       return getFalse(ITy);
2997     case ICmpInst::ICMP_SLT:
2998     case ICmpInst::ICMP_SLE: {
2999       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3000       if (!Known.isNonNegative())
3001         break;
3002       LLVM_FALLTHROUGH;
3003     }
3004     case ICmpInst::ICMP_NE:
3005     case ICmpInst::ICMP_ULT:
3006     case ICmpInst::ICMP_ULE:
3007       return getTrue(ITy);
3008     }
3009   }
3010 
3011   // icmp pred (urem X, Y), X
3012   if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3013     if (Pred == ICmpInst::ICMP_ULE)
3014       return getTrue(ITy);
3015     if (Pred == ICmpInst::ICMP_UGT)
3016       return getFalse(ITy);
3017   }
3018 
3019   // x >>u y <=u x --> true.
3020   // x >>u y >u  x --> false.
3021   // x udiv y <=u x --> true.
3022   // x udiv y >u  x --> false.
3023   if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3024       match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3025     // icmp pred (X op Y), X
3026     if (Pred == ICmpInst::ICMP_UGT)
3027       return getFalse(ITy);
3028     if (Pred == ICmpInst::ICMP_ULE)
3029       return getTrue(ITy);
3030   }
3031 
3032   // If x is nonzero:
3033   // x >>u C <u  x --> true  for C != 0.
3034   // x >>u C !=  x --> true  for C != 0.
3035   // x >>u C >=u x --> false for C != 0.
3036   // x >>u C ==  x --> false for C != 0.
3037   // x udiv C <u  x --> true  for C != 1.
3038   // x udiv C !=  x --> true  for C != 1.
3039   // x udiv C >=u x --> false for C != 1.
3040   // x udiv C ==  x --> false for C != 1.
3041   // TODO: allow non-constant shift amount/divisor
3042   const APInt *C;
3043   if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3044       (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3045     if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3046       switch (Pred) {
3047       default:
3048         break;
3049       case ICmpInst::ICMP_EQ:
3050       case ICmpInst::ICMP_UGE:
3051         return getFalse(ITy);
3052       case ICmpInst::ICMP_NE:
3053       case ICmpInst::ICMP_ULT:
3054         return getTrue(ITy);
3055       case ICmpInst::ICMP_UGT:
3056       case ICmpInst::ICMP_ULE:
3057         // UGT/ULE are handled by the more general case just above
3058         llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3059       }
3060     }
3061   }
3062 
3063   // (x*C1)/C2 <= x for C1 <= C2.
3064   // This holds even if the multiplication overflows: Assume that x != 0 and
3065   // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3066   // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3067   //
3068   // Additionally, either the multiplication and division might be represented
3069   // as shifts:
3070   // (x*C1)>>C2 <= x for C1 < 2**C2.
3071   // (x<<C1)/C2 <= x for 2**C1 < C2.
3072   const APInt *C1, *C2;
3073   if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3074        C1->ule(*C2)) ||
3075       (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3076        C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3077       (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3078        (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3079     if (Pred == ICmpInst::ICMP_UGT)
3080       return getFalse(ITy);
3081     if (Pred == ICmpInst::ICMP_ULE)
3082       return getTrue(ITy);
3083   }
3084 
3085   return nullptr;
3086 }
3087 
3088 
3089 // If only one of the icmp's operands has NSW flags, try to prove that:
3090 //
3091 //   icmp slt (x + C1), (x +nsw C2)
3092 //
3093 // is equivalent to:
3094 //
3095 //   icmp slt C1, C2
3096 //
3097 // which is true if x + C2 has the NSW flags set and:
3098 // *) C1 < C2 && C1 >= 0, or
3099 // *) C2 < C1 && C1 <= 0.
3100 //
3101 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3102                                     Value *RHS) {
3103   // TODO: only support icmp slt for now.
3104   if (Pred != CmpInst::ICMP_SLT)
3105     return false;
3106 
3107   // Canonicalize nsw add as RHS.
3108   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3109     std::swap(LHS, RHS);
3110   if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3111     return false;
3112 
3113   Value *X;
3114   const APInt *C1, *C2;
3115   if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3116       !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3117     return false;
3118 
3119   return (C1->slt(*C2) && C1->isNonNegative()) ||
3120          (C2->slt(*C1) && C1->isNonPositive());
3121 }
3122 
3123 
3124 /// TODO: A large part of this logic is duplicated in InstCombine's
3125 /// foldICmpBinOp(). We should be able to share that and avoid the code
3126 /// duplication.
3127 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3128                                     Value *RHS, const SimplifyQuery &Q,
3129                                     unsigned MaxRecurse) {
3130   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3131   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3132   if (MaxRecurse && (LBO || RBO)) {
3133     // Analyze the case when either LHS or RHS is an add instruction.
3134     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3135     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3136     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3137     if (LBO && LBO->getOpcode() == Instruction::Add) {
3138       A = LBO->getOperand(0);
3139       B = LBO->getOperand(1);
3140       NoLHSWrapProblem =
3141           ICmpInst::isEquality(Pred) ||
3142           (CmpInst::isUnsigned(Pred) &&
3143            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3144           (CmpInst::isSigned(Pred) &&
3145            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3146     }
3147     if (RBO && RBO->getOpcode() == Instruction::Add) {
3148       C = RBO->getOperand(0);
3149       D = RBO->getOperand(1);
3150       NoRHSWrapProblem =
3151           ICmpInst::isEquality(Pred) ||
3152           (CmpInst::isUnsigned(Pred) &&
3153            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3154           (CmpInst::isSigned(Pred) &&
3155            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3156     }
3157 
3158     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3159     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3160       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
3161                                       Constant::getNullValue(RHS->getType()), Q,
3162                                       MaxRecurse - 1))
3163         return V;
3164 
3165     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3166     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3167       if (Value *V =
3168               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3169                                C == LHS ? D : C, Q, MaxRecurse - 1))
3170         return V;
3171 
3172     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3173     bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3174                        trySimplifyICmpWithAdds(Pred, LHS, RHS);
3175     if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3176       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3177       Value *Y, *Z;
3178       if (A == C) {
3179         // C + B == C + D  ->  B == D
3180         Y = B;
3181         Z = D;
3182       } else if (A == D) {
3183         // D + B == C + D  ->  B == C
3184         Y = B;
3185         Z = C;
3186       } else if (B == C) {
3187         // A + C == C + D  ->  A == D
3188         Y = A;
3189         Z = D;
3190       } else {
3191         assert(B == D);
3192         // A + D == C + D  ->  A == C
3193         Y = A;
3194         Z = C;
3195       }
3196       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3197         return V;
3198     }
3199   }
3200 
3201   if (LBO)
3202     if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3203       return V;
3204 
3205   if (RBO)
3206     if (Value *V = simplifyICmpWithBinOpOnLHS(
3207             ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3208       return V;
3209 
3210   // 0 - (zext X) pred C
3211   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3212     const APInt *C;
3213     if (match(RHS, m_APInt(C))) {
3214       if (C->isStrictlyPositive()) {
3215         if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3216           return ConstantInt::getTrue(GetCompareTy(RHS));
3217         if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3218           return ConstantInt::getFalse(GetCompareTy(RHS));
3219       }
3220       if (C->isNonNegative()) {
3221         if (Pred == ICmpInst::ICMP_SLE)
3222           return ConstantInt::getTrue(GetCompareTy(RHS));
3223         if (Pred == ICmpInst::ICMP_SGT)
3224           return ConstantInt::getFalse(GetCompareTy(RHS));
3225       }
3226     }
3227   }
3228 
3229   //   If C2 is a power-of-2 and C is not:
3230   //   (C2 << X) == C --> false
3231   //   (C2 << X) != C --> true
3232   const APInt *C;
3233   if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3234       match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3235     // C2 << X can equal zero in some circumstances.
3236     // This simplification might be unsafe if C is zero.
3237     //
3238     // We know it is safe if:
3239     // - The shift is nsw. We can't shift out the one bit.
3240     // - The shift is nuw. We can't shift out the one bit.
3241     // - C2 is one.
3242     // - C isn't zero.
3243     if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3244         Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3245         match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3246       if (Pred == ICmpInst::ICMP_EQ)
3247         return ConstantInt::getFalse(GetCompareTy(RHS));
3248       if (Pred == ICmpInst::ICMP_NE)
3249         return ConstantInt::getTrue(GetCompareTy(RHS));
3250     }
3251   }
3252 
3253   // TODO: This is overly constrained. LHS can be any power-of-2.
3254   // (1 << X)  >u 0x8000 --> false
3255   // (1 << X) <=u 0x8000 --> true
3256   if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
3257     if (Pred == ICmpInst::ICMP_UGT)
3258       return ConstantInt::getFalse(GetCompareTy(RHS));
3259     if (Pred == ICmpInst::ICMP_ULE)
3260       return ConstantInt::getTrue(GetCompareTy(RHS));
3261   }
3262 
3263   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3264       LBO->getOperand(1) == RBO->getOperand(1)) {
3265     switch (LBO->getOpcode()) {
3266     default:
3267       break;
3268     case Instruction::UDiv:
3269     case Instruction::LShr:
3270       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3271           !Q.IIQ.isExact(RBO))
3272         break;
3273       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3274                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3275           return V;
3276       break;
3277     case Instruction::SDiv:
3278       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3279           !Q.IIQ.isExact(RBO))
3280         break;
3281       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3282                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3283         return V;
3284       break;
3285     case Instruction::AShr:
3286       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3287         break;
3288       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3289                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3290         return V;
3291       break;
3292     case Instruction::Shl: {
3293       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3294       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3295       if (!NUW && !NSW)
3296         break;
3297       if (!NSW && ICmpInst::isSigned(Pred))
3298         break;
3299       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3300                                       RBO->getOperand(0), Q, MaxRecurse - 1))
3301         return V;
3302       break;
3303     }
3304     }
3305   }
3306   return nullptr;
3307 }
3308 
3309 /// Simplify integer comparisons where at least one operand of the compare
3310 /// matches an integer min/max idiom.
3311 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3312                                      Value *RHS, const SimplifyQuery &Q,
3313                                      unsigned MaxRecurse) {
3314   Type *ITy = GetCompareTy(LHS); // The return type.
3315   Value *A, *B;
3316   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3317   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3318 
3319   // Signed variants on "max(a,b)>=a -> true".
3320   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3321     if (A != RHS)
3322       std::swap(A, B);       // smax(A, B) pred A.
3323     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3324     // We analyze this as smax(A, B) pred A.
3325     P = Pred;
3326   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3327              (A == LHS || B == LHS)) {
3328     if (A != LHS)
3329       std::swap(A, B);       // A pred smax(A, B).
3330     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3331     // We analyze this as smax(A, B) swapped-pred A.
3332     P = CmpInst::getSwappedPredicate(Pred);
3333   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3334              (A == RHS || B == RHS)) {
3335     if (A != RHS)
3336       std::swap(A, B);       // smin(A, B) pred A.
3337     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3338     // We analyze this as smax(-A, -B) swapped-pred -A.
3339     // Note that we do not need to actually form -A or -B thanks to EqP.
3340     P = CmpInst::getSwappedPredicate(Pred);
3341   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3342              (A == LHS || B == LHS)) {
3343     if (A != LHS)
3344       std::swap(A, B);       // A pred smin(A, B).
3345     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3346     // We analyze this as smax(-A, -B) pred -A.
3347     // Note that we do not need to actually form -A or -B thanks to EqP.
3348     P = Pred;
3349   }
3350   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3351     // Cases correspond to "max(A, B) p A".
3352     switch (P) {
3353     default:
3354       break;
3355     case CmpInst::ICMP_EQ:
3356     case CmpInst::ICMP_SLE:
3357       // Equivalent to "A EqP B".  This may be the same as the condition tested
3358       // in the max/min; if so, we can just return that.
3359       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3360         return V;
3361       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3362         return V;
3363       // Otherwise, see if "A EqP B" simplifies.
3364       if (MaxRecurse)
3365         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3366           return V;
3367       break;
3368     case CmpInst::ICMP_NE:
3369     case CmpInst::ICMP_SGT: {
3370       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3371       // Equivalent to "A InvEqP B".  This may be the same as the condition
3372       // tested in the max/min; if so, we can just return that.
3373       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3374         return V;
3375       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3376         return V;
3377       // Otherwise, see if "A InvEqP B" simplifies.
3378       if (MaxRecurse)
3379         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3380           return V;
3381       break;
3382     }
3383     case CmpInst::ICMP_SGE:
3384       // Always true.
3385       return getTrue(ITy);
3386     case CmpInst::ICMP_SLT:
3387       // Always false.
3388       return getFalse(ITy);
3389     }
3390   }
3391 
3392   // Unsigned variants on "max(a,b)>=a -> true".
3393   P = CmpInst::BAD_ICMP_PREDICATE;
3394   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3395     if (A != RHS)
3396       std::swap(A, B);       // umax(A, B) pred A.
3397     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3398     // We analyze this as umax(A, B) pred A.
3399     P = Pred;
3400   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3401              (A == LHS || B == LHS)) {
3402     if (A != LHS)
3403       std::swap(A, B);       // A pred umax(A, B).
3404     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3405     // We analyze this as umax(A, B) swapped-pred A.
3406     P = CmpInst::getSwappedPredicate(Pred);
3407   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3408              (A == RHS || B == RHS)) {
3409     if (A != RHS)
3410       std::swap(A, B);       // umin(A, B) pred A.
3411     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3412     // We analyze this as umax(-A, -B) swapped-pred -A.
3413     // Note that we do not need to actually form -A or -B thanks to EqP.
3414     P = CmpInst::getSwappedPredicate(Pred);
3415   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3416              (A == LHS || B == LHS)) {
3417     if (A != LHS)
3418       std::swap(A, B);       // A pred umin(A, B).
3419     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3420     // We analyze this as umax(-A, -B) pred -A.
3421     // Note that we do not need to actually form -A or -B thanks to EqP.
3422     P = Pred;
3423   }
3424   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3425     // Cases correspond to "max(A, B) p A".
3426     switch (P) {
3427     default:
3428       break;
3429     case CmpInst::ICMP_EQ:
3430     case CmpInst::ICMP_ULE:
3431       // Equivalent to "A EqP B".  This may be the same as the condition tested
3432       // in the max/min; if so, we can just return that.
3433       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3434         return V;
3435       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3436         return V;
3437       // Otherwise, see if "A EqP B" simplifies.
3438       if (MaxRecurse)
3439         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3440           return V;
3441       break;
3442     case CmpInst::ICMP_NE:
3443     case CmpInst::ICMP_UGT: {
3444       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3445       // Equivalent to "A InvEqP B".  This may be the same as the condition
3446       // tested in the max/min; if so, we can just return that.
3447       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3448         return V;
3449       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3450         return V;
3451       // Otherwise, see if "A InvEqP B" simplifies.
3452       if (MaxRecurse)
3453         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3454           return V;
3455       break;
3456     }
3457     case CmpInst::ICMP_UGE:
3458       return getTrue(ITy);
3459     case CmpInst::ICMP_ULT:
3460       return getFalse(ITy);
3461     }
3462   }
3463 
3464   // Comparing 1 each of min/max with a common operand?
3465   // Canonicalize min operand to RHS.
3466   if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3467       match(LHS, m_SMin(m_Value(), m_Value()))) {
3468     std::swap(LHS, RHS);
3469     Pred = ICmpInst::getSwappedPredicate(Pred);
3470   }
3471 
3472   Value *C, *D;
3473   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3474       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3475       (A == C || A == D || B == C || B == D)) {
3476     // smax(A, B) >=s smin(A, D) --> true
3477     if (Pred == CmpInst::ICMP_SGE)
3478       return getTrue(ITy);
3479     // smax(A, B) <s smin(A, D) --> false
3480     if (Pred == CmpInst::ICMP_SLT)
3481       return getFalse(ITy);
3482   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3483              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3484              (A == C || A == D || B == C || B == D)) {
3485     // umax(A, B) >=u umin(A, D) --> true
3486     if (Pred == CmpInst::ICMP_UGE)
3487       return getTrue(ITy);
3488     // umax(A, B) <u umin(A, D) --> false
3489     if (Pred == CmpInst::ICMP_ULT)
3490       return getFalse(ITy);
3491   }
3492 
3493   return nullptr;
3494 }
3495 
3496 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3497                                                Value *LHS, Value *RHS,
3498                                                const SimplifyQuery &Q) {
3499   // Gracefully handle instructions that have not been inserted yet.
3500   if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
3501     return nullptr;
3502 
3503   for (Value *AssumeBaseOp : {LHS, RHS}) {
3504     for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3505       if (!AssumeVH)
3506         continue;
3507 
3508       CallInst *Assume = cast<CallInst>(AssumeVH);
3509       if (Optional<bool> Imp =
3510               isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS,
3511                                  Q.DL))
3512         if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3513           return ConstantInt::get(GetCompareTy(LHS), *Imp);
3514     }
3515   }
3516 
3517   return nullptr;
3518 }
3519 
3520 /// Given operands for an ICmpInst, see if we can fold the result.
3521 /// If not, this returns null.
3522 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3523                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3524   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3525   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3526 
3527   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3528     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3529       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3530 
3531     // If we have a constant, make sure it is on the RHS.
3532     std::swap(LHS, RHS);
3533     Pred = CmpInst::getSwappedPredicate(Pred);
3534   }
3535   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3536 
3537   Type *ITy = GetCompareTy(LHS); // The return type.
3538 
3539   // icmp poison, X -> poison
3540   if (isa<PoisonValue>(RHS))
3541     return PoisonValue::get(ITy);
3542 
3543   // For EQ and NE, we can always pick a value for the undef to make the
3544   // predicate pass or fail, so we can return undef.
3545   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3546   if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3547     return UndefValue::get(ITy);
3548 
3549   // icmp X, X -> true/false
3550   // icmp X, undef -> true/false because undef could be X.
3551   if (LHS == RHS || Q.isUndefValue(RHS))
3552     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3553 
3554   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3555     return V;
3556 
3557   // TODO: Sink/common this with other potentially expensive calls that use
3558   //       ValueTracking? See comment below for isKnownNonEqual().
3559   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3560     return V;
3561 
3562   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3563     return V;
3564 
3565   // If both operands have range metadata, use the metadata
3566   // to simplify the comparison.
3567   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3568     auto RHS_Instr = cast<Instruction>(RHS);
3569     auto LHS_Instr = cast<Instruction>(LHS);
3570 
3571     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3572         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3573       auto RHS_CR = getConstantRangeFromMetadata(
3574           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3575       auto LHS_CR = getConstantRangeFromMetadata(
3576           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3577 
3578       if (LHS_CR.icmp(Pred, RHS_CR))
3579         return ConstantInt::getTrue(RHS->getContext());
3580 
3581       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3582         return ConstantInt::getFalse(RHS->getContext());
3583     }
3584   }
3585 
3586   // Compare of cast, for example (zext X) != 0 -> X != 0
3587   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3588     Instruction *LI = cast<CastInst>(LHS);
3589     Value *SrcOp = LI->getOperand(0);
3590     Type *SrcTy = SrcOp->getType();
3591     Type *DstTy = LI->getType();
3592 
3593     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3594     // if the integer type is the same size as the pointer type.
3595     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3596         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3597       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3598         // Transfer the cast to the constant.
3599         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3600                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3601                                         Q, MaxRecurse-1))
3602           return V;
3603       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3604         if (RI->getOperand(0)->getType() == SrcTy)
3605           // Compare without the cast.
3606           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3607                                           Q, MaxRecurse-1))
3608             return V;
3609       }
3610     }
3611 
3612     if (isa<ZExtInst>(LHS)) {
3613       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3614       // same type.
3615       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3616         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3617           // Compare X and Y.  Note that signed predicates become unsigned.
3618           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3619                                           SrcOp, RI->getOperand(0), Q,
3620                                           MaxRecurse-1))
3621             return V;
3622       }
3623       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3624       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3625         if (SrcOp == RI->getOperand(0)) {
3626           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3627             return ConstantInt::getTrue(ITy);
3628           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3629             return ConstantInt::getFalse(ITy);
3630         }
3631       }
3632       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3633       // too.  If not, then try to deduce the result of the comparison.
3634       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3635         // Compute the constant that would happen if we truncated to SrcTy then
3636         // reextended to DstTy.
3637         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3638         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3639 
3640         // If the re-extended constant didn't change then this is effectively
3641         // also a case of comparing two zero-extended values.
3642         if (RExt == CI && MaxRecurse)
3643           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3644                                         SrcOp, Trunc, Q, MaxRecurse-1))
3645             return V;
3646 
3647         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3648         // there.  Use this to work out the result of the comparison.
3649         if (RExt != CI) {
3650           switch (Pred) {
3651           default: llvm_unreachable("Unknown ICmp predicate!");
3652           // LHS <u RHS.
3653           case ICmpInst::ICMP_EQ:
3654           case ICmpInst::ICMP_UGT:
3655           case ICmpInst::ICMP_UGE:
3656             return ConstantInt::getFalse(CI->getContext());
3657 
3658           case ICmpInst::ICMP_NE:
3659           case ICmpInst::ICMP_ULT:
3660           case ICmpInst::ICMP_ULE:
3661             return ConstantInt::getTrue(CI->getContext());
3662 
3663           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3664           // is non-negative then LHS <s RHS.
3665           case ICmpInst::ICMP_SGT:
3666           case ICmpInst::ICMP_SGE:
3667             return CI->getValue().isNegative() ?
3668               ConstantInt::getTrue(CI->getContext()) :
3669               ConstantInt::getFalse(CI->getContext());
3670 
3671           case ICmpInst::ICMP_SLT:
3672           case ICmpInst::ICMP_SLE:
3673             return CI->getValue().isNegative() ?
3674               ConstantInt::getFalse(CI->getContext()) :
3675               ConstantInt::getTrue(CI->getContext());
3676           }
3677         }
3678       }
3679     }
3680 
3681     if (isa<SExtInst>(LHS)) {
3682       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3683       // same type.
3684       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3685         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3686           // Compare X and Y.  Note that the predicate does not change.
3687           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3688                                           Q, MaxRecurse-1))
3689             return V;
3690       }
3691       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3692       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3693         if (SrcOp == RI->getOperand(0)) {
3694           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3695             return ConstantInt::getTrue(ITy);
3696           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3697             return ConstantInt::getFalse(ITy);
3698         }
3699       }
3700       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3701       // too.  If not, then try to deduce the result of the comparison.
3702       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3703         // Compute the constant that would happen if we truncated to SrcTy then
3704         // reextended to DstTy.
3705         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3706         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3707 
3708         // If the re-extended constant didn't change then this is effectively
3709         // also a case of comparing two sign-extended values.
3710         if (RExt == CI && MaxRecurse)
3711           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3712             return V;
3713 
3714         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3715         // bits there.  Use this to work out the result of the comparison.
3716         if (RExt != CI) {
3717           switch (Pred) {
3718           default: llvm_unreachable("Unknown ICmp predicate!");
3719           case ICmpInst::ICMP_EQ:
3720             return ConstantInt::getFalse(CI->getContext());
3721           case ICmpInst::ICMP_NE:
3722             return ConstantInt::getTrue(CI->getContext());
3723 
3724           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3725           // LHS >s RHS.
3726           case ICmpInst::ICMP_SGT:
3727           case ICmpInst::ICMP_SGE:
3728             return CI->getValue().isNegative() ?
3729               ConstantInt::getTrue(CI->getContext()) :
3730               ConstantInt::getFalse(CI->getContext());
3731           case ICmpInst::ICMP_SLT:
3732           case ICmpInst::ICMP_SLE:
3733             return CI->getValue().isNegative() ?
3734               ConstantInt::getFalse(CI->getContext()) :
3735               ConstantInt::getTrue(CI->getContext());
3736 
3737           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3738           // LHS >u RHS.
3739           case ICmpInst::ICMP_UGT:
3740           case ICmpInst::ICMP_UGE:
3741             // Comparison is true iff the LHS <s 0.
3742             if (MaxRecurse)
3743               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3744                                               Constant::getNullValue(SrcTy),
3745                                               Q, MaxRecurse-1))
3746                 return V;
3747             break;
3748           case ICmpInst::ICMP_ULT:
3749           case ICmpInst::ICMP_ULE:
3750             // Comparison is true iff the LHS >=s 0.
3751             if (MaxRecurse)
3752               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3753                                               Constant::getNullValue(SrcTy),
3754                                               Q, MaxRecurse-1))
3755                 return V;
3756             break;
3757           }
3758         }
3759       }
3760     }
3761   }
3762 
3763   // icmp eq|ne X, Y -> false|true if X != Y
3764   // This is potentially expensive, and we have already computedKnownBits for
3765   // compares with 0 above here, so only try this for a non-zero compare.
3766   if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
3767       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3768     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3769   }
3770 
3771   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3772     return V;
3773 
3774   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3775     return V;
3776 
3777   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3778     return V;
3779 
3780   // Simplify comparisons of related pointers using a powerful, recursive
3781   // GEP-walk when we have target data available..
3782   if (LHS->getType()->isPointerTy())
3783     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3784       return C;
3785   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3786     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3787       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3788               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3789           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3790               Q.DL.getTypeSizeInBits(CRHS->getType()))
3791         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3792                                          CRHS->getPointerOperand(), Q))
3793           return C;
3794 
3795   // If the comparison is with the result of a select instruction, check whether
3796   // comparing with either branch of the select always yields the same value.
3797   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3798     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3799       return V;
3800 
3801   // If the comparison is with the result of a phi instruction, check whether
3802   // doing the compare with each incoming phi value yields a common result.
3803   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3804     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3805       return V;
3806 
3807   return nullptr;
3808 }
3809 
3810 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3811                               const SimplifyQuery &Q) {
3812   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3813 }
3814 
3815 /// Given operands for an FCmpInst, see if we can fold the result.
3816 /// If not, this returns null.
3817 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3818                                FastMathFlags FMF, const SimplifyQuery &Q,
3819                                unsigned MaxRecurse) {
3820   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3821   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3822 
3823   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3824     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3825       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3826 
3827     // If we have a constant, make sure it is on the RHS.
3828     std::swap(LHS, RHS);
3829     Pred = CmpInst::getSwappedPredicate(Pred);
3830   }
3831 
3832   // Fold trivial predicates.
3833   Type *RetTy = GetCompareTy(LHS);
3834   if (Pred == FCmpInst::FCMP_FALSE)
3835     return getFalse(RetTy);
3836   if (Pred == FCmpInst::FCMP_TRUE)
3837     return getTrue(RetTy);
3838 
3839   // Fold (un)ordered comparison if we can determine there are no NaNs.
3840   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3841     if (FMF.noNaNs() ||
3842         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3843       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3844 
3845   // NaN is unordered; NaN is not ordered.
3846   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3847          "Comparison must be either ordered or unordered");
3848   if (match(RHS, m_NaN()))
3849     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3850 
3851   // fcmp pred x, poison and  fcmp pred poison, x
3852   // fold to poison
3853   if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
3854     return PoisonValue::get(RetTy);
3855 
3856   // fcmp pred x, undef  and  fcmp pred undef, x
3857   // fold to true if unordered, false if ordered
3858   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3859     // Choosing NaN for the undef will always make unordered comparison succeed
3860     // and ordered comparison fail.
3861     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3862   }
3863 
3864   // fcmp x,x -> true/false.  Not all compares are foldable.
3865   if (LHS == RHS) {
3866     if (CmpInst::isTrueWhenEqual(Pred))
3867       return getTrue(RetTy);
3868     if (CmpInst::isFalseWhenEqual(Pred))
3869       return getFalse(RetTy);
3870   }
3871 
3872   // Handle fcmp with constant RHS.
3873   // TODO: Use match with a specific FP value, so these work with vectors with
3874   // undef lanes.
3875   const APFloat *C;
3876   if (match(RHS, m_APFloat(C))) {
3877     // Check whether the constant is an infinity.
3878     if (C->isInfinity()) {
3879       if (C->isNegative()) {
3880         switch (Pred) {
3881         case FCmpInst::FCMP_OLT:
3882           // No value is ordered and less than negative infinity.
3883           return getFalse(RetTy);
3884         case FCmpInst::FCMP_UGE:
3885           // All values are unordered with or at least negative infinity.
3886           return getTrue(RetTy);
3887         default:
3888           break;
3889         }
3890       } else {
3891         switch (Pred) {
3892         case FCmpInst::FCMP_OGT:
3893           // No value is ordered and greater than infinity.
3894           return getFalse(RetTy);
3895         case FCmpInst::FCMP_ULE:
3896           // All values are unordered with and at most infinity.
3897           return getTrue(RetTy);
3898         default:
3899           break;
3900         }
3901       }
3902 
3903       // LHS == Inf
3904       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3905         return getFalse(RetTy);
3906       // LHS != Inf
3907       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3908         return getTrue(RetTy);
3909       // LHS == Inf || LHS == NaN
3910       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3911           isKnownNeverNaN(LHS, Q.TLI))
3912         return getFalse(RetTy);
3913       // LHS != Inf && LHS != NaN
3914       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3915           isKnownNeverNaN(LHS, Q.TLI))
3916         return getTrue(RetTy);
3917     }
3918     if (C->isNegative() && !C->isNegZero()) {
3919       assert(!C->isNaN() && "Unexpected NaN constant!");
3920       // TODO: We can catch more cases by using a range check rather than
3921       //       relying on CannotBeOrderedLessThanZero.
3922       switch (Pred) {
3923       case FCmpInst::FCMP_UGE:
3924       case FCmpInst::FCMP_UGT:
3925       case FCmpInst::FCMP_UNE:
3926         // (X >= 0) implies (X > C) when (C < 0)
3927         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3928           return getTrue(RetTy);
3929         break;
3930       case FCmpInst::FCMP_OEQ:
3931       case FCmpInst::FCMP_OLE:
3932       case FCmpInst::FCMP_OLT:
3933         // (X >= 0) implies !(X < C) when (C < 0)
3934         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3935           return getFalse(RetTy);
3936         break;
3937       default:
3938         break;
3939       }
3940     }
3941 
3942     // Check comparison of [minnum/maxnum with constant] with other constant.
3943     const APFloat *C2;
3944     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3945          *C2 < *C) ||
3946         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3947          *C2 > *C)) {
3948       bool IsMaxNum =
3949           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3950       // The ordered relationship and minnum/maxnum guarantee that we do not
3951       // have NaN constants, so ordered/unordered preds are handled the same.
3952       switch (Pred) {
3953       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3954         // minnum(X, LesserC)  == C --> false
3955         // maxnum(X, GreaterC) == C --> false
3956         return getFalse(RetTy);
3957       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3958         // minnum(X, LesserC)  != C --> true
3959         // maxnum(X, GreaterC) != C --> true
3960         return getTrue(RetTy);
3961       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3962       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3963         // minnum(X, LesserC)  >= C --> false
3964         // minnum(X, LesserC)  >  C --> false
3965         // maxnum(X, GreaterC) >= C --> true
3966         // maxnum(X, GreaterC) >  C --> true
3967         return ConstantInt::get(RetTy, IsMaxNum);
3968       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3969       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3970         // minnum(X, LesserC)  <= C --> true
3971         // minnum(X, LesserC)  <  C --> true
3972         // maxnum(X, GreaterC) <= C --> false
3973         // maxnum(X, GreaterC) <  C --> false
3974         return ConstantInt::get(RetTy, !IsMaxNum);
3975       default:
3976         // TRUE/FALSE/ORD/UNO should be handled before this.
3977         llvm_unreachable("Unexpected fcmp predicate");
3978       }
3979     }
3980   }
3981 
3982   if (match(RHS, m_AnyZeroFP())) {
3983     switch (Pred) {
3984     case FCmpInst::FCMP_OGE:
3985     case FCmpInst::FCMP_ULT:
3986       // Positive or zero X >= 0.0 --> true
3987       // Positive or zero X <  0.0 --> false
3988       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3989           CannotBeOrderedLessThanZero(LHS, Q.TLI))
3990         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3991       break;
3992     case FCmpInst::FCMP_UGE:
3993     case FCmpInst::FCMP_OLT:
3994       // Positive or zero or nan X >= 0.0 --> true
3995       // Positive or zero or nan X <  0.0 --> false
3996       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3997         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3998       break;
3999     default:
4000       break;
4001     }
4002   }
4003 
4004   // If the comparison is with the result of a select instruction, check whether
4005   // comparing with either branch of the select always yields the same value.
4006   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4007     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4008       return V;
4009 
4010   // If the comparison is with the result of a phi instruction, check whether
4011   // doing the compare with each incoming phi value yields a common result.
4012   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4013     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4014       return V;
4015 
4016   return nullptr;
4017 }
4018 
4019 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4020                               FastMathFlags FMF, const SimplifyQuery &Q) {
4021   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4022 }
4023 
4024 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4025                                      const SimplifyQuery &Q,
4026                                      bool AllowRefinement,
4027                                      unsigned MaxRecurse) {
4028   assert(!Op->getType()->isVectorTy() && "This is not safe for vectors");
4029 
4030   // Trivial replacement.
4031   if (V == Op)
4032     return RepOp;
4033 
4034   // We cannot replace a constant, and shouldn't even try.
4035   if (isa<Constant>(Op))
4036     return nullptr;
4037 
4038   auto *I = dyn_cast<Instruction>(V);
4039   if (!I || !is_contained(I->operands(), Op))
4040     return nullptr;
4041 
4042   // Replace Op with RepOp in instruction operands.
4043   SmallVector<Value *, 8> NewOps(I->getNumOperands());
4044   transform(I->operands(), NewOps.begin(),
4045             [&](Value *V) { return V == Op ? RepOp : V; });
4046 
4047   if (!AllowRefinement) {
4048     // General InstSimplify functions may refine the result, e.g. by returning
4049     // a constant for a potentially poison value. To avoid this, implement only
4050     // a few non-refining but profitable transforms here.
4051 
4052     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4053       unsigned Opcode = BO->getOpcode();
4054       // id op x -> x, x op id -> x
4055       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4056         return NewOps[1];
4057       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4058                                                       /* RHS */ true))
4059         return NewOps[0];
4060 
4061       // x & x -> x, x | x -> x
4062       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4063           NewOps[0] == NewOps[1])
4064         return NewOps[0];
4065     }
4066 
4067     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4068       // getelementptr x, 0 -> x
4069       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
4070           !GEP->isInBounds())
4071         return NewOps[0];
4072     }
4073   } else if (MaxRecurse) {
4074     // The simplification queries below may return the original value. Consider:
4075     //   %div = udiv i32 %arg, %arg2
4076     //   %mul = mul nsw i32 %div, %arg2
4077     //   %cmp = icmp eq i32 %mul, %arg
4078     //   %sel = select i1 %cmp, i32 %div, i32 undef
4079     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4080     // simplifies back to %arg. This can only happen because %mul does not
4081     // dominate %div. To ensure a consistent return value contract, we make sure
4082     // that this case returns nullptr as well.
4083     auto PreventSelfSimplify = [V](Value *Simplified) {
4084       return Simplified != V ? Simplified : nullptr;
4085     };
4086 
4087     if (auto *B = dyn_cast<BinaryOperator>(I))
4088       return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0],
4089                                                NewOps[1], Q, MaxRecurse - 1));
4090 
4091     if (CmpInst *C = dyn_cast<CmpInst>(I))
4092       return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0],
4093                                                  NewOps[1], Q, MaxRecurse - 1));
4094 
4095     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4096       return PreventSelfSimplify(SimplifyGEPInst(
4097           GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
4098           GEP->isInBounds(), Q, MaxRecurse - 1));
4099 
4100     if (isa<SelectInst>(I))
4101       return PreventSelfSimplify(
4102           SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q,
4103                              MaxRecurse - 1));
4104     // TODO: We could hand off more cases to instsimplify here.
4105   }
4106 
4107   // If all operands are constant after substituting Op for RepOp then we can
4108   // constant fold the instruction.
4109   SmallVector<Constant *, 8> ConstOps;
4110   for (Value *NewOp : NewOps) {
4111     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4112       ConstOps.push_back(ConstOp);
4113     else
4114       return nullptr;
4115   }
4116 
4117   // Consider:
4118   //   %cmp = icmp eq i32 %x, 2147483647
4119   //   %add = add nsw i32 %x, 1
4120   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4121   //
4122   // We can't replace %sel with %add unless we strip away the flags (which
4123   // will be done in InstCombine).
4124   // TODO: This may be unsound, because it only catches some forms of
4125   // refinement.
4126   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4127     return nullptr;
4128 
4129   if (CmpInst *C = dyn_cast<CmpInst>(I))
4130     return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4131                                            ConstOps[1], Q.DL, Q.TLI);
4132 
4133   if (LoadInst *LI = dyn_cast<LoadInst>(I))
4134     if (!LI->isVolatile())
4135       return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4136 
4137   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4138 }
4139 
4140 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4141                                     const SimplifyQuery &Q,
4142                                     bool AllowRefinement) {
4143   return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4144                                   RecursionLimit);
4145 }
4146 
4147 /// Try to simplify a select instruction when its condition operand is an
4148 /// integer comparison where one operand of the compare is a constant.
4149 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4150                                     const APInt *Y, bool TrueWhenUnset) {
4151   const APInt *C;
4152 
4153   // (X & Y) == 0 ? X & ~Y : X  --> X
4154   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4155   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4156       *Y == ~*C)
4157     return TrueWhenUnset ? FalseVal : TrueVal;
4158 
4159   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4160   // (X & Y) != 0 ? X : X & ~Y  --> X
4161   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4162       *Y == ~*C)
4163     return TrueWhenUnset ? FalseVal : TrueVal;
4164 
4165   if (Y->isPowerOf2()) {
4166     // (X & Y) == 0 ? X | Y : X  --> X | Y
4167     // (X & Y) != 0 ? X | Y : X  --> X
4168     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4169         *Y == *C)
4170       return TrueWhenUnset ? TrueVal : FalseVal;
4171 
4172     // (X & Y) == 0 ? X : X | Y  --> X
4173     // (X & Y) != 0 ? X : X | Y  --> X | Y
4174     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4175         *Y == *C)
4176       return TrueWhenUnset ? TrueVal : FalseVal;
4177   }
4178 
4179   return nullptr;
4180 }
4181 
4182 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4183 /// eq/ne.
4184 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4185                                            ICmpInst::Predicate Pred,
4186                                            Value *TrueVal, Value *FalseVal) {
4187   Value *X;
4188   APInt Mask;
4189   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4190     return nullptr;
4191 
4192   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4193                                Pred == ICmpInst::ICMP_EQ);
4194 }
4195 
4196 /// Try to simplify a select instruction when its condition operand is an
4197 /// integer comparison.
4198 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4199                                          Value *FalseVal, const SimplifyQuery &Q,
4200                                          unsigned MaxRecurse) {
4201   ICmpInst::Predicate Pred;
4202   Value *CmpLHS, *CmpRHS;
4203   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4204     return nullptr;
4205 
4206   // Canonicalize ne to eq predicate.
4207   if (Pred == ICmpInst::ICMP_NE) {
4208     Pred = ICmpInst::ICMP_EQ;
4209     std::swap(TrueVal, FalseVal);
4210   }
4211 
4212   // Check for integer min/max with a limit constant:
4213   // X > MIN_INT ? X : MIN_INT --> X
4214   // X < MAX_INT ? X : MAX_INT --> X
4215   if (TrueVal->getType()->isIntOrIntVectorTy()) {
4216     Value *X, *Y;
4217     SelectPatternFlavor SPF =
4218         matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4219                                      X, Y).Flavor;
4220     if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4221       APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4222                                     X->getType()->getScalarSizeInBits());
4223       if (match(Y, m_SpecificInt(LimitC)))
4224         return X;
4225     }
4226   }
4227 
4228   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4229     Value *X;
4230     const APInt *Y;
4231     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4232       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4233                                            /*TrueWhenUnset=*/true))
4234         return V;
4235 
4236     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4237     Value *ShAmt;
4238     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4239                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4240     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4241     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4242     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4243       return X;
4244 
4245     // Test for a zero-shift-guard-op around rotates. These are used to
4246     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4247     // intrinsics do not have that problem.
4248     // We do not allow this transform for the general funnel shift case because
4249     // that would not preserve the poison safety of the original code.
4250     auto isRotate =
4251         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4252                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4253     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4254     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4255     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4256         Pred == ICmpInst::ICMP_EQ)
4257       return FalseVal;
4258 
4259     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4260     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4261     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4262         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4263       return FalseVal;
4264     if (match(TrueVal,
4265               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4266         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4267       return FalseVal;
4268   }
4269 
4270   // Check for other compares that behave like bit test.
4271   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
4272                                               TrueVal, FalseVal))
4273     return V;
4274 
4275   // If we have a scalar equality comparison, then we know the value in one of
4276   // the arms of the select. See if substituting this value into the arm and
4277   // simplifying the result yields the same value as the other arm.
4278   // Note that the equivalence/replacement opportunity does not hold for vectors
4279   // because each element of a vector select is chosen independently.
4280   if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
4281     if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4282                                /* AllowRefinement */ false, MaxRecurse) ==
4283             TrueVal ||
4284         simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4285                                /* AllowRefinement */ false, MaxRecurse) ==
4286             TrueVal)
4287       return FalseVal;
4288     if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4289                                /* AllowRefinement */ true, MaxRecurse) ==
4290             FalseVal ||
4291         simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4292                                /* AllowRefinement */ true, MaxRecurse) ==
4293             FalseVal)
4294       return FalseVal;
4295   }
4296 
4297   return nullptr;
4298 }
4299 
4300 /// Try to simplify a select instruction when its condition operand is a
4301 /// floating-point comparison.
4302 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4303                                      const SimplifyQuery &Q) {
4304   FCmpInst::Predicate Pred;
4305   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4306       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4307     return nullptr;
4308 
4309   // This transform is safe if we do not have (do not care about) -0.0 or if
4310   // at least one operand is known to not be -0.0. Otherwise, the select can
4311   // change the sign of a zero operand.
4312   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4313                           Q.CxtI->hasNoSignedZeros();
4314   const APFloat *C;
4315   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4316                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4317     // (T == F) ? T : F --> F
4318     // (F == T) ? T : F --> F
4319     if (Pred == FCmpInst::FCMP_OEQ)
4320       return F;
4321 
4322     // (T != F) ? T : F --> T
4323     // (F != T) ? T : F --> T
4324     if (Pred == FCmpInst::FCMP_UNE)
4325       return T;
4326   }
4327 
4328   return nullptr;
4329 }
4330 
4331 /// Given operands for a SelectInst, see if we can fold the result.
4332 /// If not, this returns null.
4333 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4334                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4335   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4336     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4337       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4338         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4339 
4340     // select poison, X, Y -> poison
4341     if (isa<PoisonValue>(CondC))
4342       return PoisonValue::get(TrueVal->getType());
4343 
4344     // select undef, X, Y -> X or Y
4345     if (Q.isUndefValue(CondC))
4346       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4347 
4348     // select true,  X, Y --> X
4349     // select false, X, Y --> Y
4350     // For vectors, allow undef/poison elements in the condition to match the
4351     // defined elements, so we can eliminate the select.
4352     if (match(CondC, m_One()))
4353       return TrueVal;
4354     if (match(CondC, m_Zero()))
4355       return FalseVal;
4356   }
4357 
4358   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4359          "Select must have bool or bool vector condition");
4360   assert(TrueVal->getType() == FalseVal->getType() &&
4361          "Select must have same types for true/false ops");
4362 
4363   if (Cond->getType() == TrueVal->getType()) {
4364     // select i1 Cond, i1 true, i1 false --> i1 Cond
4365     if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4366       return Cond;
4367 
4368     // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4369     Value *X, *Y;
4370     if (match(FalseVal, m_ZeroInt())) {
4371       if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4372           match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4373         return X;
4374       if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4375           match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4376         return X;
4377     }
4378   }
4379 
4380   // select ?, X, X -> X
4381   if (TrueVal == FalseVal)
4382     return TrueVal;
4383 
4384   // If the true or false value is poison, we can fold to the other value.
4385   // If the true or false value is undef, we can fold to the other value as
4386   // long as the other value isn't poison.
4387   // select ?, poison, X -> X
4388   // select ?, undef,  X -> X
4389   if (isa<PoisonValue>(TrueVal) ||
4390       (Q.isUndefValue(TrueVal) &&
4391        isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
4392     return FalseVal;
4393   // select ?, X, poison -> X
4394   // select ?, X, undef  -> X
4395   if (isa<PoisonValue>(FalseVal) ||
4396       (Q.isUndefValue(FalseVal) &&
4397        isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
4398     return TrueVal;
4399 
4400   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4401   Constant *TrueC, *FalseC;
4402   if (isa<FixedVectorType>(TrueVal->getType()) &&
4403       match(TrueVal, m_Constant(TrueC)) &&
4404       match(FalseVal, m_Constant(FalseC))) {
4405     unsigned NumElts =
4406         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4407     SmallVector<Constant *, 16> NewC;
4408     for (unsigned i = 0; i != NumElts; ++i) {
4409       // Bail out on incomplete vector constants.
4410       Constant *TEltC = TrueC->getAggregateElement(i);
4411       Constant *FEltC = FalseC->getAggregateElement(i);
4412       if (!TEltC || !FEltC)
4413         break;
4414 
4415       // If the elements match (undef or not), that value is the result. If only
4416       // one element is undef, choose the defined element as the safe result.
4417       if (TEltC == FEltC)
4418         NewC.push_back(TEltC);
4419       else if (isa<PoisonValue>(TEltC) ||
4420                (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4421         NewC.push_back(FEltC);
4422       else if (isa<PoisonValue>(FEltC) ||
4423                (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4424         NewC.push_back(TEltC);
4425       else
4426         break;
4427     }
4428     if (NewC.size() == NumElts)
4429       return ConstantVector::get(NewC);
4430   }
4431 
4432   if (Value *V =
4433           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4434     return V;
4435 
4436   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4437     return V;
4438 
4439   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4440     return V;
4441 
4442   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4443   if (Imp)
4444     return *Imp ? TrueVal : FalseVal;
4445 
4446   return nullptr;
4447 }
4448 
4449 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4450                                 const SimplifyQuery &Q) {
4451   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4452 }
4453 
4454 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4455 /// If not, this returns null.
4456 static Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr,
4457                               ArrayRef<Value *> Indices, bool InBounds,
4458                               const SimplifyQuery &Q, unsigned) {
4459   // The type of the GEP pointer operand.
4460   unsigned AS =
4461       cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4462 
4463   // getelementptr P -> P.
4464   if (Indices.empty())
4465     return Ptr;
4466 
4467   // Compute the (pointer) type returned by the GEP instruction.
4468   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4469   Type *GEPTy = PointerType::get(LastType, AS);
4470   if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4471     GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4472   else {
4473     for (Value *Op : Indices) {
4474       // If one of the operands is a vector, the result type is a vector of
4475       // pointers. All vector operands must have the same number of elements.
4476       if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4477         GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4478         break;
4479       }
4480     }
4481   }
4482 
4483   // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
4484   // it may be equivalent to a bitcast.
4485   if (Ptr->getType()->isOpaquePointerTy() &&
4486       all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4487     return Ptr;
4488 
4489   // getelementptr poison, idx -> poison
4490   // getelementptr baseptr, poison -> poison
4491   if (isa<PoisonValue>(Ptr) ||
4492       any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4493     return PoisonValue::get(GEPTy);
4494 
4495   if (Q.isUndefValue(Ptr))
4496     // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
4497     return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
4498 
4499   bool IsScalableVec =
4500       isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
4501         return isa<ScalableVectorType>(V->getType());
4502       });
4503 
4504   if (Indices.size() == 1) {
4505     // getelementptr P, 0 -> P.
4506     if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4507       return Ptr;
4508 
4509     Type *Ty = SrcTy;
4510     if (!IsScalableVec && Ty->isSized()) {
4511       Value *P;
4512       uint64_t C;
4513       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4514       // getelementptr P, N -> P if P points to a type of zero size.
4515       if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
4516         return Ptr;
4517 
4518       // The following transforms are only safe if the ptrtoint cast
4519       // doesn't truncate the pointers.
4520       if (Indices[0]->getType()->getScalarSizeInBits() ==
4521           Q.DL.getPointerSizeInBits(AS)) {
4522         auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
4523           return P->getType() == GEPTy &&
4524                  getUnderlyingObject(P) == getUnderlyingObject(Ptr);
4525         };
4526         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4527         if (TyAllocSize == 1 &&
4528             match(Indices[0],
4529                   m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
4530             CanSimplify())
4531           return P;
4532 
4533         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
4534         // size 1 << C.
4535         if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4536                                            m_PtrToInt(m_Specific(Ptr))),
4537                                      m_ConstantInt(C))) &&
4538             TyAllocSize == 1ULL << C && CanSimplify())
4539           return P;
4540 
4541         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
4542         // size C.
4543         if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4544                                            m_PtrToInt(m_Specific(Ptr))),
4545                                      m_SpecificInt(TyAllocSize))) &&
4546             CanSimplify())
4547           return P;
4548       }
4549     }
4550   }
4551 
4552   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4553       all_of(Indices.drop_back(1),
4554              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4555     unsigned IdxWidth =
4556         Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
4557     if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
4558       APInt BasePtrOffset(IdxWidth, 0);
4559       Value *StrippedBasePtr =
4560           Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
4561 
4562       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4563       // inttoptr is generally conservative, this particular case is folded to
4564       // a null pointer, which will have incorrect provenance.
4565 
4566       // gep (gep V, C), (sub 0, V) -> C
4567       if (match(Indices.back(),
4568                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4569           !BasePtrOffset.isZero()) {
4570         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4571         return ConstantExpr::getIntToPtr(CI, GEPTy);
4572       }
4573       // gep (gep V, C), (xor V, -1) -> C-1
4574       if (match(Indices.back(),
4575                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4576           !BasePtrOffset.isOne()) {
4577         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4578         return ConstantExpr::getIntToPtr(CI, GEPTy);
4579       }
4580     }
4581   }
4582 
4583   // Check to see if this is constant foldable.
4584   if (!isa<Constant>(Ptr) ||
4585       !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
4586     return nullptr;
4587 
4588   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
4589                                             InBounds);
4590   return ConstantFoldConstant(CE, Q.DL);
4591 }
4592 
4593 Value *llvm::SimplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
4594                              bool InBounds, const SimplifyQuery &Q) {
4595   return ::SimplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
4596 }
4597 
4598 /// Given operands for an InsertValueInst, see if we can fold the result.
4599 /// If not, this returns null.
4600 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4601                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4602                                       unsigned) {
4603   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4604     if (Constant *CVal = dyn_cast<Constant>(Val))
4605       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4606 
4607   // insertvalue x, undef, n -> x
4608   if (Q.isUndefValue(Val))
4609     return Agg;
4610 
4611   // insertvalue x, (extractvalue y, n), n
4612   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4613     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4614         EV->getIndices() == Idxs) {
4615       // insertvalue undef, (extractvalue y, n), n -> y
4616       if (Q.isUndefValue(Agg))
4617         return EV->getAggregateOperand();
4618 
4619       // insertvalue y, (extractvalue y, n), n -> y
4620       if (Agg == EV->getAggregateOperand())
4621         return Agg;
4622     }
4623 
4624   return nullptr;
4625 }
4626 
4627 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4628                                      ArrayRef<unsigned> Idxs,
4629                                      const SimplifyQuery &Q) {
4630   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4631 }
4632 
4633 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4634                                        const SimplifyQuery &Q) {
4635   // Try to constant fold.
4636   auto *VecC = dyn_cast<Constant>(Vec);
4637   auto *ValC = dyn_cast<Constant>(Val);
4638   auto *IdxC = dyn_cast<Constant>(Idx);
4639   if (VecC && ValC && IdxC)
4640     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4641 
4642   // For fixed-length vector, fold into poison if index is out of bounds.
4643   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4644     if (isa<FixedVectorType>(Vec->getType()) &&
4645         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4646       return PoisonValue::get(Vec->getType());
4647   }
4648 
4649   // If index is undef, it might be out of bounds (see above case)
4650   if (Q.isUndefValue(Idx))
4651     return PoisonValue::get(Vec->getType());
4652 
4653   // If the scalar is poison, or it is undef and there is no risk of
4654   // propagating poison from the vector value, simplify to the vector value.
4655   if (isa<PoisonValue>(Val) ||
4656       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4657     return Vec;
4658 
4659   // If we are extracting a value from a vector, then inserting it into the same
4660   // place, that's the input vector:
4661   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4662   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4663     return Vec;
4664 
4665   return nullptr;
4666 }
4667 
4668 /// Given operands for an ExtractValueInst, see if we can fold the result.
4669 /// If not, this returns null.
4670 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4671                                        const SimplifyQuery &, unsigned) {
4672   if (auto *CAgg = dyn_cast<Constant>(Agg))
4673     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4674 
4675   // extractvalue x, (insertvalue y, elt, n), n -> elt
4676   unsigned NumIdxs = Idxs.size();
4677   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4678        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4679     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4680     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4681     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4682     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4683         Idxs.slice(0, NumCommonIdxs)) {
4684       if (NumIdxs == NumInsertValueIdxs)
4685         return IVI->getInsertedValueOperand();
4686       break;
4687     }
4688   }
4689 
4690   return nullptr;
4691 }
4692 
4693 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4694                                       const SimplifyQuery &Q) {
4695   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4696 }
4697 
4698 /// Given operands for an ExtractElementInst, see if we can fold the result.
4699 /// If not, this returns null.
4700 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
4701                                          const SimplifyQuery &Q, unsigned) {
4702   auto *VecVTy = cast<VectorType>(Vec->getType());
4703   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4704     if (auto *CIdx = dyn_cast<Constant>(Idx))
4705       return ConstantExpr::getExtractElement(CVec, CIdx);
4706 
4707     if (Q.isUndefValue(Vec))
4708       return UndefValue::get(VecVTy->getElementType());
4709   }
4710 
4711   // An undef extract index can be arbitrarily chosen to be an out-of-range
4712   // index value, which would result in the instruction being poison.
4713   if (Q.isUndefValue(Idx))
4714     return PoisonValue::get(VecVTy->getElementType());
4715 
4716   // If extracting a specified index from the vector, see if we can recursively
4717   // find a previously computed scalar that was inserted into the vector.
4718   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4719     // For fixed-length vector, fold into undef if index is out of bounds.
4720     unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
4721     if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
4722       return PoisonValue::get(VecVTy->getElementType());
4723     // Handle case where an element is extracted from a splat.
4724     if (IdxC->getValue().ult(MinNumElts))
4725       if (auto *Splat = getSplatValue(Vec))
4726         return Splat;
4727     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4728       return Elt;
4729   } else {
4730     // The index is not relevant if our vector is a splat.
4731     if (Value *Splat = getSplatValue(Vec))
4732       return Splat;
4733   }
4734   return nullptr;
4735 }
4736 
4737 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4738                                         const SimplifyQuery &Q) {
4739   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4740 }
4741 
4742 /// See if we can fold the given phi. If not, returns null.
4743 static Value *SimplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
4744                               const SimplifyQuery &Q) {
4745   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4746   //          here, because the PHI we may succeed simplifying to was not
4747   //          def-reachable from the original PHI!
4748 
4749   // If all of the PHI's incoming values are the same then replace the PHI node
4750   // with the common value.
4751   Value *CommonValue = nullptr;
4752   bool HasUndefInput = false;
4753   for (Value *Incoming : IncomingValues) {
4754     // If the incoming value is the phi node itself, it can safely be skipped.
4755     if (Incoming == PN) continue;
4756     if (Q.isUndefValue(Incoming)) {
4757       // Remember that we saw an undef value, but otherwise ignore them.
4758       HasUndefInput = true;
4759       continue;
4760     }
4761     if (CommonValue && Incoming != CommonValue)
4762       return nullptr;  // Not the same, bail out.
4763     CommonValue = Incoming;
4764   }
4765 
4766   // If CommonValue is null then all of the incoming values were either undef or
4767   // equal to the phi node itself.
4768   if (!CommonValue)
4769     return UndefValue::get(PN->getType());
4770 
4771   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4772   // instruction, we cannot return X as the result of the PHI node unless it
4773   // dominates the PHI block.
4774   if (HasUndefInput)
4775     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4776 
4777   return CommonValue;
4778 }
4779 
4780 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4781                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4782   if (auto *C = dyn_cast<Constant>(Op))
4783     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4784 
4785   if (auto *CI = dyn_cast<CastInst>(Op)) {
4786     auto *Src = CI->getOperand(0);
4787     Type *SrcTy = Src->getType();
4788     Type *MidTy = CI->getType();
4789     Type *DstTy = Ty;
4790     if (Src->getType() == Ty) {
4791       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4792       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4793       Type *SrcIntPtrTy =
4794           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4795       Type *MidIntPtrTy =
4796           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4797       Type *DstIntPtrTy =
4798           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4799       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4800                                          SrcIntPtrTy, MidIntPtrTy,
4801                                          DstIntPtrTy) == Instruction::BitCast)
4802         return Src;
4803     }
4804   }
4805 
4806   // bitcast x -> x
4807   if (CastOpc == Instruction::BitCast)
4808     if (Op->getType() == Ty)
4809       return Op;
4810 
4811   return nullptr;
4812 }
4813 
4814 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4815                               const SimplifyQuery &Q) {
4816   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4817 }
4818 
4819 /// For the given destination element of a shuffle, peek through shuffles to
4820 /// match a root vector source operand that contains that element in the same
4821 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4822 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4823                                    int MaskVal, Value *RootVec,
4824                                    unsigned MaxRecurse) {
4825   if (!MaxRecurse--)
4826     return nullptr;
4827 
4828   // Bail out if any mask value is undefined. That kind of shuffle may be
4829   // simplified further based on demanded bits or other folds.
4830   if (MaskVal == -1)
4831     return nullptr;
4832 
4833   // The mask value chooses which source operand we need to look at next.
4834   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4835   int RootElt = MaskVal;
4836   Value *SourceOp = Op0;
4837   if (MaskVal >= InVecNumElts) {
4838     RootElt = MaskVal - InVecNumElts;
4839     SourceOp = Op1;
4840   }
4841 
4842   // If the source operand is a shuffle itself, look through it to find the
4843   // matching root vector.
4844   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4845     return foldIdentityShuffles(
4846         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4847         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4848   }
4849 
4850   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4851   // size?
4852 
4853   // The source operand is not a shuffle. Initialize the root vector value for
4854   // this shuffle if that has not been done yet.
4855   if (!RootVec)
4856     RootVec = SourceOp;
4857 
4858   // Give up as soon as a source operand does not match the existing root value.
4859   if (RootVec != SourceOp)
4860     return nullptr;
4861 
4862   // The element must be coming from the same lane in the source vector
4863   // (although it may have crossed lanes in intermediate shuffles).
4864   if (RootElt != DestElt)
4865     return nullptr;
4866 
4867   return RootVec;
4868 }
4869 
4870 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4871                                         ArrayRef<int> Mask, Type *RetTy,
4872                                         const SimplifyQuery &Q,
4873                                         unsigned MaxRecurse) {
4874   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4875     return UndefValue::get(RetTy);
4876 
4877   auto *InVecTy = cast<VectorType>(Op0->getType());
4878   unsigned MaskNumElts = Mask.size();
4879   ElementCount InVecEltCount = InVecTy->getElementCount();
4880 
4881   bool Scalable = InVecEltCount.isScalable();
4882 
4883   SmallVector<int, 32> Indices;
4884   Indices.assign(Mask.begin(), Mask.end());
4885 
4886   // Canonicalization: If mask does not select elements from an input vector,
4887   // replace that input vector with poison.
4888   if (!Scalable) {
4889     bool MaskSelects0 = false, MaskSelects1 = false;
4890     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4891     for (unsigned i = 0; i != MaskNumElts; ++i) {
4892       if (Indices[i] == -1)
4893         continue;
4894       if ((unsigned)Indices[i] < InVecNumElts)
4895         MaskSelects0 = true;
4896       else
4897         MaskSelects1 = true;
4898     }
4899     if (!MaskSelects0)
4900       Op0 = PoisonValue::get(InVecTy);
4901     if (!MaskSelects1)
4902       Op1 = PoisonValue::get(InVecTy);
4903   }
4904 
4905   auto *Op0Const = dyn_cast<Constant>(Op0);
4906   auto *Op1Const = dyn_cast<Constant>(Op1);
4907 
4908   // If all operands are constant, constant fold the shuffle. This
4909   // transformation depends on the value of the mask which is not known at
4910   // compile time for scalable vectors
4911   if (Op0Const && Op1Const)
4912     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4913 
4914   // Canonicalization: if only one input vector is constant, it shall be the
4915   // second one. This transformation depends on the value of the mask which
4916   // is not known at compile time for scalable vectors
4917   if (!Scalable && Op0Const && !Op1Const) {
4918     std::swap(Op0, Op1);
4919     ShuffleVectorInst::commuteShuffleMask(Indices,
4920                                           InVecEltCount.getKnownMinValue());
4921   }
4922 
4923   // A splat of an inserted scalar constant becomes a vector constant:
4924   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4925   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4926   //       original mask constant.
4927   // NOTE: This transformation depends on the value of the mask which is not
4928   // known at compile time for scalable vectors
4929   Constant *C;
4930   ConstantInt *IndexC;
4931   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4932                                           m_ConstantInt(IndexC)))) {
4933     // Match a splat shuffle mask of the insert index allowing undef elements.
4934     int InsertIndex = IndexC->getZExtValue();
4935     if (all_of(Indices, [InsertIndex](int MaskElt) {
4936           return MaskElt == InsertIndex || MaskElt == -1;
4937         })) {
4938       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4939 
4940       // Shuffle mask undefs become undefined constant result elements.
4941       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4942       for (unsigned i = 0; i != MaskNumElts; ++i)
4943         if (Indices[i] == -1)
4944           VecC[i] = UndefValue::get(C->getType());
4945       return ConstantVector::get(VecC);
4946     }
4947   }
4948 
4949   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4950   // value type is same as the input vectors' type.
4951   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4952     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
4953         is_splat(OpShuf->getShuffleMask()))
4954       return Op0;
4955 
4956   // All remaining transformation depend on the value of the mask, which is
4957   // not known at compile time for scalable vectors.
4958   if (Scalable)
4959     return nullptr;
4960 
4961   // Don't fold a shuffle with undef mask elements. This may get folded in a
4962   // better way using demanded bits or other analysis.
4963   // TODO: Should we allow this?
4964   if (is_contained(Indices, -1))
4965     return nullptr;
4966 
4967   // Check if every element of this shuffle can be mapped back to the
4968   // corresponding element of a single root vector. If so, we don't need this
4969   // shuffle. This handles simple identity shuffles as well as chains of
4970   // shuffles that may widen/narrow and/or move elements across lanes and back.
4971   Value *RootVec = nullptr;
4972   for (unsigned i = 0; i != MaskNumElts; ++i) {
4973     // Note that recursion is limited for each vector element, so if any element
4974     // exceeds the limit, this will fail to simplify.
4975     RootVec =
4976         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4977 
4978     // We can't replace a widening/narrowing shuffle with one of its operands.
4979     if (!RootVec || RootVec->getType() != RetTy)
4980       return nullptr;
4981   }
4982   return RootVec;
4983 }
4984 
4985 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4986 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4987                                        ArrayRef<int> Mask, Type *RetTy,
4988                                        const SimplifyQuery &Q) {
4989   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4990 }
4991 
4992 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4993                               Value *&Op, const SimplifyQuery &Q) {
4994   if (auto *C = dyn_cast<Constant>(Op))
4995     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4996   return nullptr;
4997 }
4998 
4999 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
5000 /// returns null.
5001 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5002                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5003   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5004     return C;
5005 
5006   Value *X;
5007   // fneg (fneg X) ==> X
5008   if (match(Op, m_FNeg(m_Value(X))))
5009     return X;
5010 
5011   return nullptr;
5012 }
5013 
5014 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
5015                               const SimplifyQuery &Q) {
5016   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5017 }
5018 
5019 static Constant *propagateNaN(Constant *In) {
5020   // If the input is a vector with undef elements, just return a default NaN.
5021   if (!In->isNaN())
5022     return ConstantFP::getNaN(In->getType());
5023 
5024   // Propagate the existing NaN constant when possible.
5025   // TODO: Should we quiet a signaling NaN?
5026   return In;
5027 }
5028 
5029 /// Perform folds that are common to any floating-point operation. This implies
5030 /// transforms based on poison/undef/NaN because the operation itself makes no
5031 /// difference to the result.
5032 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5033                               const SimplifyQuery &Q,
5034                               fp::ExceptionBehavior ExBehavior,
5035                               RoundingMode Rounding) {
5036   // Poison is independent of anything else. It always propagates from an
5037   // operand to a math result.
5038   if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5039     return PoisonValue::get(Ops[0]->getType());
5040 
5041   for (Value *V : Ops) {
5042     bool IsNan = match(V, m_NaN());
5043     bool IsInf = match(V, m_Inf());
5044     bool IsUndef = Q.isUndefValue(V);
5045 
5046     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5047     // (an undef operand can be chosen to be Nan/Inf), then the result of
5048     // this operation is poison.
5049     if (FMF.noNaNs() && (IsNan || IsUndef))
5050       return PoisonValue::get(V->getType());
5051     if (FMF.noInfs() && (IsInf || IsUndef))
5052       return PoisonValue::get(V->getType());
5053 
5054     if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5055       if (IsUndef || IsNan)
5056         return propagateNaN(cast<Constant>(V));
5057     } else if (ExBehavior != fp::ebStrict) {
5058       if (IsNan)
5059         return propagateNaN(cast<Constant>(V));
5060     }
5061   }
5062   return nullptr;
5063 }
5064 
5065 /// Given operands for an FAdd, see if we can fold the result.  If not, this
5066 /// returns null.
5067 static Value *
5068 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5069                  const SimplifyQuery &Q, unsigned MaxRecurse,
5070                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5071                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5072   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5073     if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5074       return C;
5075 
5076   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5077     return C;
5078 
5079   // fadd X, -0 ==> X
5080   // With strict/constrained FP, we have these possible edge cases that do
5081   // not simplify to Op0:
5082   // fadd SNaN, -0.0 --> QNaN
5083   // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5084   if (canIgnoreSNaN(ExBehavior, FMF) &&
5085       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5086        FMF.noSignedZeros()))
5087     if (match(Op1, m_NegZeroFP()))
5088       return Op0;
5089 
5090   // fadd X, 0 ==> X, when we know X is not -0
5091   if (canIgnoreSNaN(ExBehavior, FMF))
5092     if (match(Op1, m_PosZeroFP()) &&
5093         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5094       return Op0;
5095 
5096   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5097     return nullptr;
5098 
5099   // With nnan: -X + X --> 0.0 (and commuted variant)
5100   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5101   // Negative zeros are allowed because we always end up with positive zero:
5102   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5103   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5104   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5105   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5106   if (FMF.noNaNs()) {
5107     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5108         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5109       return ConstantFP::getNullValue(Op0->getType());
5110 
5111     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5112         match(Op1, m_FNeg(m_Specific(Op0))))
5113       return ConstantFP::getNullValue(Op0->getType());
5114   }
5115 
5116   // (X - Y) + Y --> X
5117   // Y + (X - Y) --> X
5118   Value *X;
5119   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5120       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5121        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5122     return X;
5123 
5124   return nullptr;
5125 }
5126 
5127 /// Given operands for an FSub, see if we can fold the result.  If not, this
5128 /// returns null.
5129 static Value *
5130 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5131                  const SimplifyQuery &Q, unsigned MaxRecurse,
5132                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5133                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5134   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5135     if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5136       return C;
5137 
5138   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5139     return C;
5140 
5141   // fsub X, +0 ==> X
5142   if (canIgnoreSNaN(ExBehavior, FMF) &&
5143       (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5144        FMF.noSignedZeros()))
5145     if (match(Op1, m_PosZeroFP()))
5146       return Op0;
5147 
5148   // fsub X, -0 ==> X, when we know X is not -0
5149   if (canIgnoreSNaN(ExBehavior, FMF))
5150     if (match(Op1, m_NegZeroFP()) &&
5151         (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
5152       return Op0;
5153 
5154   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5155     return nullptr;
5156 
5157   // fsub -0.0, (fsub -0.0, X) ==> X
5158   // fsub -0.0, (fneg X) ==> X
5159   Value *X;
5160   if (match(Op0, m_NegZeroFP()) &&
5161       match(Op1, m_FNeg(m_Value(X))))
5162     return X;
5163 
5164   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5165   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5166   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5167       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5168        match(Op1, m_FNeg(m_Value(X)))))
5169     return X;
5170 
5171   // fsub nnan x, x ==> 0.0
5172   if (FMF.noNaNs() && Op0 == Op1)
5173     return Constant::getNullValue(Op0->getType());
5174 
5175   // Y - (Y - X) --> X
5176   // (X + Y) - Y --> X
5177   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5178       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5179        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5180     return X;
5181 
5182   return nullptr;
5183 }
5184 
5185 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5186                               const SimplifyQuery &Q, unsigned MaxRecurse,
5187                               fp::ExceptionBehavior ExBehavior,
5188                               RoundingMode Rounding) {
5189   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5190     return C;
5191 
5192   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5193     return nullptr;
5194 
5195   // fmul X, 1.0 ==> X
5196   if (match(Op1, m_FPOne()))
5197     return Op0;
5198 
5199   // fmul 1.0, X ==> X
5200   if (match(Op0, m_FPOne()))
5201     return Op1;
5202 
5203   // fmul nnan nsz X, 0 ==> 0
5204   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
5205     return ConstantFP::getNullValue(Op0->getType());
5206 
5207   // fmul nnan nsz 0, X ==> 0
5208   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5209     return ConstantFP::getNullValue(Op1->getType());
5210 
5211   // sqrt(X) * sqrt(X) --> X, if we can:
5212   // 1. Remove the intermediate rounding (reassociate).
5213   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5214   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5215   Value *X;
5216   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
5217       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
5218     return X;
5219 
5220   return nullptr;
5221 }
5222 
5223 /// Given the operands for an FMul, see if we can fold the result
5224 static Value *
5225 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5226                  const SimplifyQuery &Q, unsigned MaxRecurse,
5227                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5228                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5229   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5230     if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5231       return C;
5232 
5233   // Now apply simplifications that do not require rounding.
5234   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5235 }
5236 
5237 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5238                               const SimplifyQuery &Q,
5239                               fp::ExceptionBehavior ExBehavior,
5240                               RoundingMode Rounding) {
5241   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5242                             Rounding);
5243 }
5244 
5245 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5246                               const SimplifyQuery &Q,
5247                               fp::ExceptionBehavior ExBehavior,
5248                               RoundingMode Rounding) {
5249   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5250                             Rounding);
5251 }
5252 
5253 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5254                               const SimplifyQuery &Q,
5255                               fp::ExceptionBehavior ExBehavior,
5256                               RoundingMode Rounding) {
5257   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5258                             Rounding);
5259 }
5260 
5261 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5262                              const SimplifyQuery &Q,
5263                              fp::ExceptionBehavior ExBehavior,
5264                              RoundingMode Rounding) {
5265   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5266                            Rounding);
5267 }
5268 
5269 static Value *
5270 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5271                  const SimplifyQuery &Q, unsigned,
5272                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5273                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5274   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5275     if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5276       return C;
5277 
5278   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5279     return C;
5280 
5281   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5282     return nullptr;
5283 
5284   // X / 1.0 -> X
5285   if (match(Op1, m_FPOne()))
5286     return Op0;
5287 
5288   // 0 / X -> 0
5289   // Requires that NaNs are off (X could be zero) and signed zeroes are
5290   // ignored (X could be positive or negative, so the output sign is unknown).
5291   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5292     return ConstantFP::getNullValue(Op0->getType());
5293 
5294   if (FMF.noNaNs()) {
5295     // X / X -> 1.0 is legal when NaNs are ignored.
5296     // We can ignore infinities because INF/INF is NaN.
5297     if (Op0 == Op1)
5298       return ConstantFP::get(Op0->getType(), 1.0);
5299 
5300     // (X * Y) / Y --> X if we can reassociate to the above form.
5301     Value *X;
5302     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5303       return X;
5304 
5305     // -X /  X -> -1.0 and
5306     //  X / -X -> -1.0 are legal when NaNs are ignored.
5307     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5308     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5309         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5310       return ConstantFP::get(Op0->getType(), -1.0);
5311   }
5312 
5313   return nullptr;
5314 }
5315 
5316 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5317                               const SimplifyQuery &Q,
5318                               fp::ExceptionBehavior ExBehavior,
5319                               RoundingMode Rounding) {
5320   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5321                             Rounding);
5322 }
5323 
5324 static Value *
5325 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5326                  const SimplifyQuery &Q, unsigned,
5327                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5328                  RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5329   if (isDefaultFPEnvironment(ExBehavior, Rounding))
5330     if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5331       return C;
5332 
5333   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5334     return C;
5335 
5336   if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5337     return nullptr;
5338 
5339   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5340   // The constant match may include undef elements in a vector, so return a full
5341   // zero constant as the result.
5342   if (FMF.noNaNs()) {
5343     // +0 % X -> 0
5344     if (match(Op0, m_PosZeroFP()))
5345       return ConstantFP::getNullValue(Op0->getType());
5346     // -0 % X -> -0
5347     if (match(Op0, m_NegZeroFP()))
5348       return ConstantFP::getNegativeZero(Op0->getType());
5349   }
5350 
5351   return nullptr;
5352 }
5353 
5354 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5355                               const SimplifyQuery &Q,
5356                               fp::ExceptionBehavior ExBehavior,
5357                               RoundingMode Rounding) {
5358   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5359                             Rounding);
5360 }
5361 
5362 //=== Helper functions for higher up the class hierarchy.
5363 
5364 /// Given the operand for a UnaryOperator, see if we can fold the result.
5365 /// If not, this returns null.
5366 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5367                            unsigned MaxRecurse) {
5368   switch (Opcode) {
5369   case Instruction::FNeg:
5370     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5371   default:
5372     llvm_unreachable("Unexpected opcode");
5373   }
5374 }
5375 
5376 /// Given the operand for a UnaryOperator, see if we can fold the result.
5377 /// If not, this returns null.
5378 /// Try to use FastMathFlags when folding the result.
5379 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5380                              const FastMathFlags &FMF,
5381                              const SimplifyQuery &Q, unsigned MaxRecurse) {
5382   switch (Opcode) {
5383   case Instruction::FNeg:
5384     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5385   default:
5386     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5387   }
5388 }
5389 
5390 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5391   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5392 }
5393 
5394 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5395                           const SimplifyQuery &Q) {
5396   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5397 }
5398 
5399 /// Given operands for a BinaryOperator, see if we can fold the result.
5400 /// If not, this returns null.
5401 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5402                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5403   switch (Opcode) {
5404   case Instruction::Add:
5405     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5406   case Instruction::Sub:
5407     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5408   case Instruction::Mul:
5409     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
5410   case Instruction::SDiv:
5411     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
5412   case Instruction::UDiv:
5413     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5414   case Instruction::SRem:
5415     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
5416   case Instruction::URem:
5417     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
5418   case Instruction::Shl:
5419     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5420   case Instruction::LShr:
5421     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5422   case Instruction::AShr:
5423     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5424   case Instruction::And:
5425     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
5426   case Instruction::Or:
5427     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
5428   case Instruction::Xor:
5429     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
5430   case Instruction::FAdd:
5431     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5432   case Instruction::FSub:
5433     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5434   case Instruction::FMul:
5435     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5436   case Instruction::FDiv:
5437     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5438   case Instruction::FRem:
5439     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5440   default:
5441     llvm_unreachable("Unexpected opcode");
5442   }
5443 }
5444 
5445 /// Given operands for a BinaryOperator, see if we can fold the result.
5446 /// If not, this returns null.
5447 /// Try to use FastMathFlags when folding the result.
5448 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5449                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5450                             unsigned MaxRecurse) {
5451   switch (Opcode) {
5452   case Instruction::FAdd:
5453     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5454   case Instruction::FSub:
5455     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5456   case Instruction::FMul:
5457     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5458   case Instruction::FDiv:
5459     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5460   default:
5461     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5462   }
5463 }
5464 
5465 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5466                            const SimplifyQuery &Q) {
5467   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5468 }
5469 
5470 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5471                            FastMathFlags FMF, const SimplifyQuery &Q) {
5472   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5473 }
5474 
5475 /// Given operands for a CmpInst, see if we can fold the result.
5476 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5477                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5478   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5479     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5480   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5481 }
5482 
5483 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5484                              const SimplifyQuery &Q) {
5485   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5486 }
5487 
5488 static bool IsIdempotent(Intrinsic::ID ID) {
5489   switch (ID) {
5490   default: return false;
5491 
5492   // Unary idempotent: f(f(x)) = f(x)
5493   case Intrinsic::fabs:
5494   case Intrinsic::floor:
5495   case Intrinsic::ceil:
5496   case Intrinsic::trunc:
5497   case Intrinsic::rint:
5498   case Intrinsic::nearbyint:
5499   case Intrinsic::round:
5500   case Intrinsic::roundeven:
5501   case Intrinsic::canonicalize:
5502     return true;
5503   }
5504 }
5505 
5506 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5507                                    const DataLayout &DL) {
5508   GlobalValue *PtrSym;
5509   APInt PtrOffset;
5510   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5511     return nullptr;
5512 
5513   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5514   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5515   Type *Int32PtrTy = Int32Ty->getPointerTo();
5516   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5517 
5518   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5519   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5520     return nullptr;
5521 
5522   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5523   if (OffsetInt % 4 != 0)
5524     return nullptr;
5525 
5526   Constant *C = ConstantExpr::getGetElementPtr(
5527       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5528       ConstantInt::get(Int64Ty, OffsetInt / 4));
5529   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5530   if (!Loaded)
5531     return nullptr;
5532 
5533   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5534   if (!LoadedCE)
5535     return nullptr;
5536 
5537   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5538     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5539     if (!LoadedCE)
5540       return nullptr;
5541   }
5542 
5543   if (LoadedCE->getOpcode() != Instruction::Sub)
5544     return nullptr;
5545 
5546   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5547   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5548     return nullptr;
5549   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5550 
5551   Constant *LoadedRHS = LoadedCE->getOperand(1);
5552   GlobalValue *LoadedRHSSym;
5553   APInt LoadedRHSOffset;
5554   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5555                                   DL) ||
5556       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5557     return nullptr;
5558 
5559   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5560 }
5561 
5562 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5563                                      const SimplifyQuery &Q) {
5564   // Idempotent functions return the same result when called repeatedly.
5565   Intrinsic::ID IID = F->getIntrinsicID();
5566   if (IsIdempotent(IID))
5567     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5568       if (II->getIntrinsicID() == IID)
5569         return II;
5570 
5571   Value *X;
5572   switch (IID) {
5573   case Intrinsic::fabs:
5574     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5575     break;
5576   case Intrinsic::bswap:
5577     // bswap(bswap(x)) -> x
5578     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5579     break;
5580   case Intrinsic::bitreverse:
5581     // bitreverse(bitreverse(x)) -> x
5582     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5583     break;
5584   case Intrinsic::ctpop: {
5585     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5586     // ctpop(and X, 1) --> and X, 1
5587     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5588     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5589                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5590       return Op0;
5591     break;
5592   }
5593   case Intrinsic::exp:
5594     // exp(log(x)) -> x
5595     if (Q.CxtI->hasAllowReassoc() &&
5596         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5597     break;
5598   case Intrinsic::exp2:
5599     // exp2(log2(x)) -> x
5600     if (Q.CxtI->hasAllowReassoc() &&
5601         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5602     break;
5603   case Intrinsic::log:
5604     // log(exp(x)) -> x
5605     if (Q.CxtI->hasAllowReassoc() &&
5606         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5607     break;
5608   case Intrinsic::log2:
5609     // log2(exp2(x)) -> x
5610     if (Q.CxtI->hasAllowReassoc() &&
5611         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5612          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5613                                                 m_Value(X))))) return X;
5614     break;
5615   case Intrinsic::log10:
5616     // log10(pow(10.0, x)) -> x
5617     if (Q.CxtI->hasAllowReassoc() &&
5618         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5619                                                m_Value(X)))) return X;
5620     break;
5621   case Intrinsic::floor:
5622   case Intrinsic::trunc:
5623   case Intrinsic::ceil:
5624   case Intrinsic::round:
5625   case Intrinsic::roundeven:
5626   case Intrinsic::nearbyint:
5627   case Intrinsic::rint: {
5628     // floor (sitofp x) -> sitofp x
5629     // floor (uitofp x) -> uitofp x
5630     //
5631     // Converting from int always results in a finite integral number or
5632     // infinity. For either of those inputs, these rounding functions always
5633     // return the same value, so the rounding can be eliminated.
5634     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5635       return Op0;
5636     break;
5637   }
5638   case Intrinsic::experimental_vector_reverse:
5639     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5640     if (match(Op0,
5641               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5642       return X;
5643     // experimental.vector.reverse(splat(X)) -> splat(X)
5644     if (isSplatValue(Op0))
5645       return Op0;
5646     break;
5647   default:
5648     break;
5649   }
5650 
5651   return nullptr;
5652 }
5653 
5654 /// Given a min/max intrinsic, see if it can be removed based on having an
5655 /// operand that is another min/max intrinsic with shared operand(s). The caller
5656 /// is expected to swap the operand arguments to handle commutation.
5657 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5658   Value *X, *Y;
5659   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5660     return nullptr;
5661 
5662   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5663   if (!MM0)
5664     return nullptr;
5665   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5666 
5667   if (Op1 == X || Op1 == Y ||
5668       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5669     // max (max X, Y), X --> max X, Y
5670     if (IID0 == IID)
5671       return MM0;
5672     // max (min X, Y), X --> X
5673     if (IID0 == getInverseMinMaxIntrinsic(IID))
5674       return Op1;
5675   }
5676   return nullptr;
5677 }
5678 
5679 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5680                                       const SimplifyQuery &Q) {
5681   Intrinsic::ID IID = F->getIntrinsicID();
5682   Type *ReturnType = F->getReturnType();
5683   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5684   switch (IID) {
5685   case Intrinsic::abs:
5686     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5687     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5688     // on the outer abs.
5689     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5690       return Op0;
5691     break;
5692 
5693   case Intrinsic::cttz: {
5694     Value *X;
5695     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5696       return X;
5697     break;
5698   }
5699   case Intrinsic::ctlz: {
5700     Value *X;
5701     if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
5702       return X;
5703     if (match(Op0, m_AShr(m_Negative(), m_Value())))
5704       return Constant::getNullValue(ReturnType);
5705     break;
5706   }
5707   case Intrinsic::smax:
5708   case Intrinsic::smin:
5709   case Intrinsic::umax:
5710   case Intrinsic::umin: {
5711     // If the arguments are the same, this is a no-op.
5712     if (Op0 == Op1)
5713       return Op0;
5714 
5715     // Canonicalize constant operand as Op1.
5716     if (isa<Constant>(Op0))
5717       std::swap(Op0, Op1);
5718 
5719     // Assume undef is the limit value.
5720     if (Q.isUndefValue(Op1))
5721       return ConstantInt::get(
5722           ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
5723 
5724     const APInt *C;
5725     if (match(Op1, m_APIntAllowUndef(C))) {
5726       // Clamp to limit value. For example:
5727       // umax(i8 %x, i8 255) --> 255
5728       if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
5729         return ConstantInt::get(ReturnType, *C);
5730 
5731       // If the constant op is the opposite of the limit value, the other must
5732       // be larger/smaller or equal. For example:
5733       // umin(i8 %x, i8 255) --> %x
5734       if (*C == MinMaxIntrinsic::getSaturationPoint(
5735                     getInverseMinMaxIntrinsic(IID), BitWidth))
5736         return Op0;
5737 
5738       // Remove nested call if constant operands allow it. Example:
5739       // max (max X, 7), 5 -> max X, 7
5740       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5741       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5742         // TODO: loosen undef/splat restrictions for vector constants.
5743         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5744         const APInt *InnerC;
5745         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5746             ICmpInst::compare(*InnerC, *C,
5747                               ICmpInst::getNonStrictPredicate(
5748                                   MinMaxIntrinsic::getPredicate(IID))))
5749           return Op0;
5750       }
5751     }
5752 
5753     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5754       return V;
5755     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5756       return V;
5757 
5758     ICmpInst::Predicate Pred =
5759         ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
5760     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5761       return Op0;
5762     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5763       return Op1;
5764 
5765     if (Optional<bool> Imp =
5766             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5767       return *Imp ? Op0 : Op1;
5768     if (Optional<bool> Imp =
5769             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5770       return *Imp ? Op1 : Op0;
5771 
5772     break;
5773   }
5774   case Intrinsic::usub_with_overflow:
5775   case Intrinsic::ssub_with_overflow:
5776     // X - X -> { 0, false }
5777     // X - undef -> { 0, false }
5778     // undef - X -> { 0, false }
5779     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5780       return Constant::getNullValue(ReturnType);
5781     break;
5782   case Intrinsic::uadd_with_overflow:
5783   case Intrinsic::sadd_with_overflow:
5784     // X + undef -> { -1, false }
5785     // undef + x -> { -1, false }
5786     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5787       return ConstantStruct::get(
5788           cast<StructType>(ReturnType),
5789           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5790            Constant::getNullValue(ReturnType->getStructElementType(1))});
5791     }
5792     break;
5793   case Intrinsic::umul_with_overflow:
5794   case Intrinsic::smul_with_overflow:
5795     // 0 * X -> { 0, false }
5796     // X * 0 -> { 0, false }
5797     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5798       return Constant::getNullValue(ReturnType);
5799     // undef * X -> { 0, false }
5800     // X * undef -> { 0, false }
5801     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5802       return Constant::getNullValue(ReturnType);
5803     break;
5804   case Intrinsic::uadd_sat:
5805     // sat(MAX + X) -> MAX
5806     // sat(X + MAX) -> MAX
5807     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5808       return Constant::getAllOnesValue(ReturnType);
5809     LLVM_FALLTHROUGH;
5810   case Intrinsic::sadd_sat:
5811     // sat(X + undef) -> -1
5812     // sat(undef + X) -> -1
5813     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5814     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5815     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5816       return Constant::getAllOnesValue(ReturnType);
5817 
5818     // X + 0 -> X
5819     if (match(Op1, m_Zero()))
5820       return Op0;
5821     // 0 + X -> X
5822     if (match(Op0, m_Zero()))
5823       return Op1;
5824     break;
5825   case Intrinsic::usub_sat:
5826     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5827     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5828       return Constant::getNullValue(ReturnType);
5829     LLVM_FALLTHROUGH;
5830   case Intrinsic::ssub_sat:
5831     // X - X -> 0, X - undef -> 0, undef - X -> 0
5832     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5833       return Constant::getNullValue(ReturnType);
5834     // X - 0 -> X
5835     if (match(Op1, m_Zero()))
5836       return Op0;
5837     break;
5838   case Intrinsic::load_relative:
5839     if (auto *C0 = dyn_cast<Constant>(Op0))
5840       if (auto *C1 = dyn_cast<Constant>(Op1))
5841         return SimplifyRelativeLoad(C0, C1, Q.DL);
5842     break;
5843   case Intrinsic::powi:
5844     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5845       // powi(x, 0) -> 1.0
5846       if (Power->isZero())
5847         return ConstantFP::get(Op0->getType(), 1.0);
5848       // powi(x, 1) -> x
5849       if (Power->isOne())
5850         return Op0;
5851     }
5852     break;
5853   case Intrinsic::copysign:
5854     // copysign X, X --> X
5855     if (Op0 == Op1)
5856       return Op0;
5857     // copysign -X, X --> X
5858     // copysign X, -X --> -X
5859     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5860         match(Op1, m_FNeg(m_Specific(Op0))))
5861       return Op1;
5862     break;
5863   case Intrinsic::maxnum:
5864   case Intrinsic::minnum:
5865   case Intrinsic::maximum:
5866   case Intrinsic::minimum: {
5867     // If the arguments are the same, this is a no-op.
5868     if (Op0 == Op1) return Op0;
5869 
5870     // Canonicalize constant operand as Op1.
5871     if (isa<Constant>(Op0))
5872       std::swap(Op0, Op1);
5873 
5874     // If an argument is undef, return the other argument.
5875     if (Q.isUndefValue(Op1))
5876       return Op0;
5877 
5878     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5879     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5880 
5881     // minnum(X, nan) -> X
5882     // maxnum(X, nan) -> X
5883     // minimum(X, nan) -> nan
5884     // maximum(X, nan) -> nan
5885     if (match(Op1, m_NaN()))
5886       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5887 
5888     // In the following folds, inf can be replaced with the largest finite
5889     // float, if the ninf flag is set.
5890     const APFloat *C;
5891     if (match(Op1, m_APFloat(C)) &&
5892         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5893       // minnum(X, -inf) -> -inf
5894       // maxnum(X, +inf) -> +inf
5895       // minimum(X, -inf) -> -inf if nnan
5896       // maximum(X, +inf) -> +inf if nnan
5897       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5898         return ConstantFP::get(ReturnType, *C);
5899 
5900       // minnum(X, +inf) -> X if nnan
5901       // maxnum(X, -inf) -> X if nnan
5902       // minimum(X, +inf) -> X
5903       // maximum(X, -inf) -> X
5904       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5905         return Op0;
5906     }
5907 
5908     // Min/max of the same operation with common operand:
5909     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5910     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5911       if (M0->getIntrinsicID() == IID &&
5912           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5913         return Op0;
5914     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5915       if (M1->getIntrinsicID() == IID &&
5916           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5917         return Op1;
5918 
5919     break;
5920   }
5921   case Intrinsic::experimental_vector_extract: {
5922     Type *ReturnType = F->getReturnType();
5923 
5924     // (extract_vector (insert_vector _, X, 0), 0) -> X
5925     unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
5926     Value *X = nullptr;
5927     if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>(
5928                        m_Value(), m_Value(X), m_Zero())) &&
5929         IdxN == 0 && X->getType() == ReturnType)
5930       return X;
5931 
5932     break;
5933   }
5934   default:
5935     break;
5936   }
5937 
5938   return nullptr;
5939 }
5940 
5941 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5942 
5943   unsigned NumOperands = Call->arg_size();
5944   Function *F = cast<Function>(Call->getCalledFunction());
5945   Intrinsic::ID IID = F->getIntrinsicID();
5946 
5947   // Most of the intrinsics with no operands have some kind of side effect.
5948   // Don't simplify.
5949   if (!NumOperands) {
5950     switch (IID) {
5951     case Intrinsic::vscale: {
5952       // Call may not be inserted into the IR yet at point of calling simplify.
5953       if (!Call->getParent() || !Call->getParent()->getParent())
5954         return nullptr;
5955       auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
5956       if (!Attr.isValid())
5957         return nullptr;
5958       unsigned VScaleMin = Attr.getVScaleRangeMin();
5959       Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
5960       if (VScaleMax && VScaleMin == VScaleMax)
5961         return ConstantInt::get(F->getReturnType(), VScaleMin);
5962       return nullptr;
5963     }
5964     default:
5965       return nullptr;
5966     }
5967   }
5968 
5969   if (NumOperands == 1)
5970     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5971 
5972   if (NumOperands == 2)
5973     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5974                                    Call->getArgOperand(1), Q);
5975 
5976   // Handle intrinsics with 3 or more arguments.
5977   switch (IID) {
5978   case Intrinsic::masked_load:
5979   case Intrinsic::masked_gather: {
5980     Value *MaskArg = Call->getArgOperand(2);
5981     Value *PassthruArg = Call->getArgOperand(3);
5982     // If the mask is all zeros or undef, the "passthru" argument is the result.
5983     if (maskIsAllZeroOrUndef(MaskArg))
5984       return PassthruArg;
5985     return nullptr;
5986   }
5987   case Intrinsic::fshl:
5988   case Intrinsic::fshr: {
5989     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5990           *ShAmtArg = Call->getArgOperand(2);
5991 
5992     // If both operands are undef, the result is undef.
5993     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
5994       return UndefValue::get(F->getReturnType());
5995 
5996     // If shift amount is undef, assume it is zero.
5997     if (Q.isUndefValue(ShAmtArg))
5998       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5999 
6000     const APInt *ShAmtC;
6001     if (match(ShAmtArg, m_APInt(ShAmtC))) {
6002       // If there's effectively no shift, return the 1st arg or 2nd arg.
6003       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6004       if (ShAmtC->urem(BitWidth).isZero())
6005         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
6006     }
6007 
6008     // Rotating zero by anything is zero.
6009     if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6010       return ConstantInt::getNullValue(F->getReturnType());
6011 
6012     // Rotating -1 by anything is -1.
6013     if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6014       return ConstantInt::getAllOnesValue(F->getReturnType());
6015 
6016     return nullptr;
6017   }
6018   case Intrinsic::experimental_constrained_fma: {
6019     Value *Op0 = Call->getArgOperand(0);
6020     Value *Op1 = Call->getArgOperand(1);
6021     Value *Op2 = Call->getArgOperand(2);
6022     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6023     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
6024                                 FPI->getExceptionBehavior().getValue(),
6025                                 FPI->getRoundingMode().getValue()))
6026       return V;
6027     return nullptr;
6028   }
6029   case Intrinsic::fma:
6030   case Intrinsic::fmuladd: {
6031     Value *Op0 = Call->getArgOperand(0);
6032     Value *Op1 = Call->getArgOperand(1);
6033     Value *Op2 = Call->getArgOperand(2);
6034     if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
6035                                 RoundingMode::NearestTiesToEven))
6036       return V;
6037     return nullptr;
6038   }
6039   case Intrinsic::smul_fix:
6040   case Intrinsic::smul_fix_sat: {
6041     Value *Op0 = Call->getArgOperand(0);
6042     Value *Op1 = Call->getArgOperand(1);
6043     Value *Op2 = Call->getArgOperand(2);
6044     Type *ReturnType = F->getReturnType();
6045 
6046     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6047     // when both Op0 and Op1 are constant so we do not care about that special
6048     // case here).
6049     if (isa<Constant>(Op0))
6050       std::swap(Op0, Op1);
6051 
6052     // X * 0 -> 0
6053     if (match(Op1, m_Zero()))
6054       return Constant::getNullValue(ReturnType);
6055 
6056     // X * undef -> 0
6057     if (Q.isUndefValue(Op1))
6058       return Constant::getNullValue(ReturnType);
6059 
6060     // X * (1 << Scale) -> X
6061     APInt ScaledOne =
6062         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6063                             cast<ConstantInt>(Op2)->getZExtValue());
6064     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6065       return Op0;
6066 
6067     return nullptr;
6068   }
6069   case Intrinsic::experimental_vector_insert: {
6070     Value *Vec = Call->getArgOperand(0);
6071     Value *SubVec = Call->getArgOperand(1);
6072     Value *Idx = Call->getArgOperand(2);
6073     Type *ReturnType = F->getReturnType();
6074 
6075     // (insert_vector Y, (extract_vector X, 0), 0) -> X
6076     // where: Y is X, or Y is undef
6077     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6078     Value *X = nullptr;
6079     if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>(
6080                           m_Value(X), m_Zero())) &&
6081         (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6082         X->getType() == ReturnType)
6083       return X;
6084 
6085     return nullptr;
6086   }
6087   case Intrinsic::experimental_constrained_fadd: {
6088     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6089     return SimplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6090                             FPI->getFastMathFlags(), Q,
6091                             FPI->getExceptionBehavior().getValue(),
6092                             FPI->getRoundingMode().getValue());
6093     break;
6094   }
6095   case Intrinsic::experimental_constrained_fsub: {
6096     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6097     return SimplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6098                             FPI->getFastMathFlags(), Q,
6099                             FPI->getExceptionBehavior().getValue(),
6100                             FPI->getRoundingMode().getValue());
6101     break;
6102   }
6103   case Intrinsic::experimental_constrained_fmul: {
6104     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6105     return SimplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6106                             FPI->getFastMathFlags(), Q,
6107                             FPI->getExceptionBehavior().getValue(),
6108                             FPI->getRoundingMode().getValue());
6109     break;
6110   }
6111   case Intrinsic::experimental_constrained_fdiv: {
6112     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6113     return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6114                             FPI->getFastMathFlags(), Q,
6115                             FPI->getExceptionBehavior().getValue(),
6116                             FPI->getRoundingMode().getValue());
6117     break;
6118   }
6119   case Intrinsic::experimental_constrained_frem: {
6120     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6121     return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
6122                             FPI->getFastMathFlags(), Q,
6123                             FPI->getExceptionBehavior().getValue(),
6124                             FPI->getRoundingMode().getValue());
6125     break;
6126   }
6127   default:
6128     return nullptr;
6129   }
6130 }
6131 
6132 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
6133   auto *F = dyn_cast<Function>(Call->getCalledOperand());
6134   if (!F || !canConstantFoldCallTo(Call, F))
6135     return nullptr;
6136 
6137   SmallVector<Constant *, 4> ConstantArgs;
6138   unsigned NumArgs = Call->arg_size();
6139   ConstantArgs.reserve(NumArgs);
6140   for (auto &Arg : Call->args()) {
6141     Constant *C = dyn_cast<Constant>(&Arg);
6142     if (!C) {
6143       if (isa<MetadataAsValue>(Arg.get()))
6144         continue;
6145       return nullptr;
6146     }
6147     ConstantArgs.push_back(C);
6148   }
6149 
6150   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6151 }
6152 
6153 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
6154   // musttail calls can only be simplified if they are also DCEd.
6155   // As we can't guarantee this here, don't simplify them.
6156   if (Call->isMustTailCall())
6157     return nullptr;
6158 
6159   // call undef -> poison
6160   // call null -> poison
6161   Value *Callee = Call->getCalledOperand();
6162   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6163     return PoisonValue::get(Call->getType());
6164 
6165   if (Value *V = tryConstantFoldCall(Call, Q))
6166     return V;
6167 
6168   auto *F = dyn_cast<Function>(Callee);
6169   if (F && F->isIntrinsic())
6170     if (Value *Ret = simplifyIntrinsic(Call, Q))
6171       return Ret;
6172 
6173   return nullptr;
6174 }
6175 
6176 /// Given operands for a Freeze, see if we can fold the result.
6177 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6178   // Use a utility function defined in ValueTracking.
6179   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6180     return Op0;
6181   // We have room for improvement.
6182   return nullptr;
6183 }
6184 
6185 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6186   return ::SimplifyFreezeInst(Op0, Q);
6187 }
6188 
6189 static Value *SimplifyLoadInst(LoadInst *LI, Value *PtrOp,
6190                                const SimplifyQuery &Q) {
6191   if (LI->isVolatile())
6192     return nullptr;
6193 
6194   APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
6195   auto *PtrOpC = dyn_cast<Constant>(PtrOp);
6196   // Try to convert operand into a constant by stripping offsets while looking
6197   // through invariant.group intrinsics. Don't bother if the underlying object
6198   // is not constant, as calculating GEP offsets is expensive.
6199   if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
6200     PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6201         Q.DL, Offset, /* AllowNonInbounts */ true,
6202         /* AllowInvariantGroup */ true);
6203     // Index size may have changed due to address space casts.
6204     Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6205     PtrOpC = dyn_cast<Constant>(PtrOp);
6206   }
6207 
6208   if (PtrOpC)
6209     return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
6210   return nullptr;
6211 }
6212 
6213 /// See if we can compute a simplified version of this instruction.
6214 /// If not, this returns null.
6215 
6216 static Value *simplifyInstructionWithOperands(Instruction *I,
6217                                               ArrayRef<Value *> NewOps,
6218                                               const SimplifyQuery &SQ,
6219                                               OptimizationRemarkEmitter *ORE) {
6220   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
6221   Value *Result = nullptr;
6222 
6223   switch (I->getOpcode()) {
6224   default:
6225     if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
6226       SmallVector<Constant *, 8> NewConstOps(NewOps.size());
6227       transform(NewOps, NewConstOps.begin(),
6228                 [](Value *V) { return cast<Constant>(V); });
6229       Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
6230     }
6231     break;
6232   case Instruction::FNeg:
6233     Result = SimplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
6234     break;
6235   case Instruction::FAdd:
6236     Result = SimplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6237     break;
6238   case Instruction::Add:
6239     Result = SimplifyAddInst(
6240         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6241         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6242     break;
6243   case Instruction::FSub:
6244     Result = SimplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6245     break;
6246   case Instruction::Sub:
6247     Result = SimplifySubInst(
6248         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6249         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6250     break;
6251   case Instruction::FMul:
6252     Result = SimplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6253     break;
6254   case Instruction::Mul:
6255     Result = SimplifyMulInst(NewOps[0], NewOps[1], Q);
6256     break;
6257   case Instruction::SDiv:
6258     Result = SimplifySDivInst(NewOps[0], NewOps[1], Q);
6259     break;
6260   case Instruction::UDiv:
6261     Result = SimplifyUDivInst(NewOps[0], NewOps[1], Q);
6262     break;
6263   case Instruction::FDiv:
6264     Result = SimplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6265     break;
6266   case Instruction::SRem:
6267     Result = SimplifySRemInst(NewOps[0], NewOps[1], Q);
6268     break;
6269   case Instruction::URem:
6270     Result = SimplifyURemInst(NewOps[0], NewOps[1], Q);
6271     break;
6272   case Instruction::FRem:
6273     Result = SimplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
6274     break;
6275   case Instruction::Shl:
6276     Result = SimplifyShlInst(
6277         NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6278         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
6279     break;
6280   case Instruction::LShr:
6281     Result = SimplifyLShrInst(NewOps[0], NewOps[1],
6282                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6283     break;
6284   case Instruction::AShr:
6285     Result = SimplifyAShrInst(NewOps[0], NewOps[1],
6286                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
6287     break;
6288   case Instruction::And:
6289     Result = SimplifyAndInst(NewOps[0], NewOps[1], Q);
6290     break;
6291   case Instruction::Or:
6292     Result = SimplifyOrInst(NewOps[0], NewOps[1], Q);
6293     break;
6294   case Instruction::Xor:
6295     Result = SimplifyXorInst(NewOps[0], NewOps[1], Q);
6296     break;
6297   case Instruction::ICmp:
6298     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
6299                               NewOps[1], Q);
6300     break;
6301   case Instruction::FCmp:
6302     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
6303                               NewOps[1], I->getFastMathFlags(), Q);
6304     break;
6305   case Instruction::Select:
6306     Result = SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
6307     break;
6308   case Instruction::GetElementPtr: {
6309     auto *GEPI = cast<GetElementPtrInst>(I);
6310     Result =
6311         SimplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
6312                         makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
6313     break;
6314   }
6315   case Instruction::InsertValue: {
6316     InsertValueInst *IV = cast<InsertValueInst>(I);
6317     Result = SimplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
6318     break;
6319   }
6320   case Instruction::InsertElement: {
6321     Result = SimplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
6322     break;
6323   }
6324   case Instruction::ExtractValue: {
6325     auto *EVI = cast<ExtractValueInst>(I);
6326     Result = SimplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
6327     break;
6328   }
6329   case Instruction::ExtractElement: {
6330     Result = SimplifyExtractElementInst(NewOps[0], NewOps[1], Q);
6331     break;
6332   }
6333   case Instruction::ShuffleVector: {
6334     auto *SVI = cast<ShuffleVectorInst>(I);
6335     Result = SimplifyShuffleVectorInst(
6336         NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q);
6337     break;
6338   }
6339   case Instruction::PHI:
6340     Result = SimplifyPHINode(cast<PHINode>(I), NewOps, Q);
6341     break;
6342   case Instruction::Call: {
6343     // TODO: Use NewOps
6344     Result = SimplifyCall(cast<CallInst>(I), Q);
6345     break;
6346   }
6347   case Instruction::Freeze:
6348     Result = llvm::SimplifyFreezeInst(NewOps[0], Q);
6349     break;
6350 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
6351 #include "llvm/IR/Instruction.def"
6352 #undef HANDLE_CAST_INST
6353     Result = SimplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
6354     break;
6355   case Instruction::Alloca:
6356     // No simplifications for Alloca and it can't be constant folded.
6357     Result = nullptr;
6358     break;
6359   case Instruction::Load:
6360     Result = SimplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
6361     break;
6362   }
6363 
6364   /// If called on unreachable code, the above logic may report that the
6365   /// instruction simplified to itself.  Make life easier for users by
6366   /// detecting that case here, returning a safe value instead.
6367   return Result == I ? UndefValue::get(I->getType()) : Result;
6368 }
6369 
6370 Value *llvm::SimplifyInstructionWithOperands(Instruction *I,
6371                                              ArrayRef<Value *> NewOps,
6372                                              const SimplifyQuery &SQ,
6373                                              OptimizationRemarkEmitter *ORE) {
6374   assert(NewOps.size() == I->getNumOperands() &&
6375          "Number of operands should match the instruction!");
6376   return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
6377 }
6378 
6379 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
6380                                  OptimizationRemarkEmitter *ORE) {
6381   SmallVector<Value *, 8> Ops(I->operands());
6382   return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
6383 }
6384 
6385 /// Implementation of recursive simplification through an instruction's
6386 /// uses.
6387 ///
6388 /// This is the common implementation of the recursive simplification routines.
6389 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
6390 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
6391 /// instructions to process and attempt to simplify it using
6392 /// InstructionSimplify. Recursively visited users which could not be
6393 /// simplified themselves are to the optional UnsimplifiedUsers set for
6394 /// further processing by the caller.
6395 ///
6396 /// This routine returns 'true' only when *it* simplifies something. The passed
6397 /// in simplified value does not count toward this.
6398 static bool replaceAndRecursivelySimplifyImpl(
6399     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6400     const DominatorTree *DT, AssumptionCache *AC,
6401     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
6402   bool Simplified = false;
6403   SmallSetVector<Instruction *, 8> Worklist;
6404   const DataLayout &DL = I->getModule()->getDataLayout();
6405 
6406   // If we have an explicit value to collapse to, do that round of the
6407   // simplification loop by hand initially.
6408   if (SimpleV) {
6409     for (User *U : I->users())
6410       if (U != I)
6411         Worklist.insert(cast<Instruction>(U));
6412 
6413     // Replace the instruction with its simplified value.
6414     I->replaceAllUsesWith(SimpleV);
6415 
6416     // Gracefully handle edge cases where the instruction is not wired into any
6417     // parent block.
6418     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6419         !I->mayHaveSideEffects())
6420       I->eraseFromParent();
6421   } else {
6422     Worklist.insert(I);
6423   }
6424 
6425   // Note that we must test the size on each iteration, the worklist can grow.
6426   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6427     I = Worklist[Idx];
6428 
6429     // See if this instruction simplifies.
6430     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
6431     if (!SimpleV) {
6432       if (UnsimplifiedUsers)
6433         UnsimplifiedUsers->insert(I);
6434       continue;
6435     }
6436 
6437     Simplified = true;
6438 
6439     // Stash away all the uses of the old instruction so we can check them for
6440     // recursive simplifications after a RAUW. This is cheaper than checking all
6441     // uses of To on the recursive step in most cases.
6442     for (User *U : I->users())
6443       Worklist.insert(cast<Instruction>(U));
6444 
6445     // Replace the instruction with its simplified value.
6446     I->replaceAllUsesWith(SimpleV);
6447 
6448     // Gracefully handle edge cases where the instruction is not wired into any
6449     // parent block.
6450     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6451         !I->mayHaveSideEffects())
6452       I->eraseFromParent();
6453   }
6454   return Simplified;
6455 }
6456 
6457 bool llvm::replaceAndRecursivelySimplify(
6458     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6459     const DominatorTree *DT, AssumptionCache *AC,
6460     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6461   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6462   assert(SimpleV && "Must provide a simplified value.");
6463   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6464                                            UnsimplifiedUsers);
6465 }
6466 
6467 namespace llvm {
6468 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6469   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6470   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6471   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6472   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6473   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6474   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6475   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6476 }
6477 
6478 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6479                                          const DataLayout &DL) {
6480   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6481 }
6482 
6483 template <class T, class... TArgs>
6484 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6485                                          Function &F) {
6486   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6487   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6488   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6489   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6490 }
6491 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6492                                                   Function &);
6493 }
6494 
6495 void InstSimplifyFolder::anchor() {}
6496