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