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