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