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