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