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       if (LHS_CR.icmp(Pred, RHS_CR))
3455         return ConstantInt::getTrue(RHS->getContext());
3456 
3457       if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3458         return ConstantInt::getFalse(RHS->getContext());
3459     }
3460   }
3461 
3462   // Compare of cast, for example (zext X) != 0 -> X != 0
3463   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3464     Instruction *LI = cast<CastInst>(LHS);
3465     Value *SrcOp = LI->getOperand(0);
3466     Type *SrcTy = SrcOp->getType();
3467     Type *DstTy = LI->getType();
3468 
3469     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3470     // if the integer type is the same size as the pointer type.
3471     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3472         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3473       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3474         // Transfer the cast to the constant.
3475         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3476                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3477                                         Q, MaxRecurse-1))
3478           return V;
3479       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3480         if (RI->getOperand(0)->getType() == SrcTy)
3481           // Compare without the cast.
3482           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3483                                           Q, MaxRecurse-1))
3484             return V;
3485       }
3486     }
3487 
3488     if (isa<ZExtInst>(LHS)) {
3489       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3490       // same type.
3491       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3492         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3493           // Compare X and Y.  Note that signed predicates become unsigned.
3494           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3495                                           SrcOp, RI->getOperand(0), Q,
3496                                           MaxRecurse-1))
3497             return V;
3498       }
3499       // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3500       else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3501         if (SrcOp == RI->getOperand(0)) {
3502           if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3503             return ConstantInt::getTrue(ITy);
3504           if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3505             return ConstantInt::getFalse(ITy);
3506         }
3507       }
3508       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3509       // too.  If not, then try to deduce the result of the comparison.
3510       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3511         // Compute the constant that would happen if we truncated to SrcTy then
3512         // reextended to DstTy.
3513         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3514         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3515 
3516         // If the re-extended constant didn't change then this is effectively
3517         // also a case of comparing two zero-extended values.
3518         if (RExt == CI && MaxRecurse)
3519           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3520                                         SrcOp, Trunc, Q, MaxRecurse-1))
3521             return V;
3522 
3523         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3524         // there.  Use this to work out the result of the comparison.
3525         if (RExt != CI) {
3526           switch (Pred) {
3527           default: llvm_unreachable("Unknown ICmp predicate!");
3528           // LHS <u RHS.
3529           case ICmpInst::ICMP_EQ:
3530           case ICmpInst::ICMP_UGT:
3531           case ICmpInst::ICMP_UGE:
3532             return ConstantInt::getFalse(CI->getContext());
3533 
3534           case ICmpInst::ICMP_NE:
3535           case ICmpInst::ICMP_ULT:
3536           case ICmpInst::ICMP_ULE:
3537             return ConstantInt::getTrue(CI->getContext());
3538 
3539           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3540           // is non-negative then LHS <s RHS.
3541           case ICmpInst::ICMP_SGT:
3542           case ICmpInst::ICMP_SGE:
3543             return CI->getValue().isNegative() ?
3544               ConstantInt::getTrue(CI->getContext()) :
3545               ConstantInt::getFalse(CI->getContext());
3546 
3547           case ICmpInst::ICMP_SLT:
3548           case ICmpInst::ICMP_SLE:
3549             return CI->getValue().isNegative() ?
3550               ConstantInt::getFalse(CI->getContext()) :
3551               ConstantInt::getTrue(CI->getContext());
3552           }
3553         }
3554       }
3555     }
3556 
3557     if (isa<SExtInst>(LHS)) {
3558       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3559       // same type.
3560       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3561         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3562           // Compare X and Y.  Note that the predicate does not change.
3563           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3564                                           Q, MaxRecurse-1))
3565             return V;
3566       }
3567       // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3568       else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3569         if (SrcOp == RI->getOperand(0)) {
3570           if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3571             return ConstantInt::getTrue(ITy);
3572           if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3573             return ConstantInt::getFalse(ITy);
3574         }
3575       }
3576       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3577       // too.  If not, then try to deduce the result of the comparison.
3578       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3579         // Compute the constant that would happen if we truncated to SrcTy then
3580         // reextended to DstTy.
3581         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3582         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3583 
3584         // If the re-extended constant didn't change then this is effectively
3585         // also a case of comparing two sign-extended values.
3586         if (RExt == CI && MaxRecurse)
3587           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3588             return V;
3589 
3590         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3591         // bits there.  Use this to work out the result of the comparison.
3592         if (RExt != CI) {
3593           switch (Pred) {
3594           default: llvm_unreachable("Unknown ICmp predicate!");
3595           case ICmpInst::ICMP_EQ:
3596             return ConstantInt::getFalse(CI->getContext());
3597           case ICmpInst::ICMP_NE:
3598             return ConstantInt::getTrue(CI->getContext());
3599 
3600           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3601           // LHS >s RHS.
3602           case ICmpInst::ICMP_SGT:
3603           case ICmpInst::ICMP_SGE:
3604             return CI->getValue().isNegative() ?
3605               ConstantInt::getTrue(CI->getContext()) :
3606               ConstantInt::getFalse(CI->getContext());
3607           case ICmpInst::ICMP_SLT:
3608           case ICmpInst::ICMP_SLE:
3609             return CI->getValue().isNegative() ?
3610               ConstantInt::getFalse(CI->getContext()) :
3611               ConstantInt::getTrue(CI->getContext());
3612 
3613           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3614           // LHS >u RHS.
3615           case ICmpInst::ICMP_UGT:
3616           case ICmpInst::ICMP_UGE:
3617             // Comparison is true iff the LHS <s 0.
3618             if (MaxRecurse)
3619               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3620                                               Constant::getNullValue(SrcTy),
3621                                               Q, MaxRecurse-1))
3622                 return V;
3623             break;
3624           case ICmpInst::ICMP_ULT:
3625           case ICmpInst::ICMP_ULE:
3626             // Comparison is true iff the LHS >=s 0.
3627             if (MaxRecurse)
3628               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3629                                               Constant::getNullValue(SrcTy),
3630                                               Q, MaxRecurse-1))
3631                 return V;
3632             break;
3633           }
3634         }
3635       }
3636     }
3637   }
3638 
3639   // icmp eq|ne X, Y -> false|true if X != Y
3640   if (ICmpInst::isEquality(Pred) &&
3641       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3642     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3643   }
3644 
3645   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3646     return V;
3647 
3648   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3649     return V;
3650 
3651   if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
3652     return V;
3653 
3654   // Simplify comparisons of related pointers using a powerful, recursive
3655   // GEP-walk when we have target data available..
3656   if (LHS->getType()->isPointerTy())
3657     if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
3658       return C;
3659   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3660     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3661       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3662               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3663           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3664               Q.DL.getTypeSizeInBits(CRHS->getType()))
3665         if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
3666                                          CRHS->getPointerOperand(), Q))
3667           return C;
3668 
3669   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3670     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3671       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3672           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3673           (ICmpInst::isEquality(Pred) ||
3674            (GLHS->isInBounds() && GRHS->isInBounds() &&
3675             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3676         // The bases are equal and the indices are constant.  Build a constant
3677         // expression GEP with the same indices and a null base pointer to see
3678         // what constant folding can make out of it.
3679         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3680         SmallVector<Value *, 4> IndicesLHS(GLHS->indices());
3681         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3682             GLHS->getSourceElementType(), Null, IndicesLHS);
3683 
3684         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3685         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3686             GLHS->getSourceElementType(), Null, IndicesRHS);
3687         Constant *NewICmp = ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3688         return ConstantFoldConstant(NewICmp, Q.DL);
3689       }
3690     }
3691   }
3692 
3693   // If the comparison is with the result of a select instruction, check whether
3694   // comparing with either branch of the select always yields the same value.
3695   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3696     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3697       return V;
3698 
3699   // If the comparison is with the result of a phi instruction, check whether
3700   // doing the compare with each incoming phi value yields a common result.
3701   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3702     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3703       return V;
3704 
3705   return nullptr;
3706 }
3707 
3708 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3709                               const SimplifyQuery &Q) {
3710   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3711 }
3712 
3713 /// Given operands for an FCmpInst, see if we can fold the result.
3714 /// If not, this returns null.
3715 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3716                                FastMathFlags FMF, const SimplifyQuery &Q,
3717                                unsigned MaxRecurse) {
3718   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3719   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3720 
3721   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3722     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3723       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3724 
3725     // If we have a constant, make sure it is on the RHS.
3726     std::swap(LHS, RHS);
3727     Pred = CmpInst::getSwappedPredicate(Pred);
3728   }
3729 
3730   // Fold trivial predicates.
3731   Type *RetTy = GetCompareTy(LHS);
3732   if (Pred == FCmpInst::FCMP_FALSE)
3733     return getFalse(RetTy);
3734   if (Pred == FCmpInst::FCMP_TRUE)
3735     return getTrue(RetTy);
3736 
3737   // Fold (un)ordered comparison if we can determine there are no NaNs.
3738   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3739     if (FMF.noNaNs() ||
3740         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3741       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3742 
3743   // NaN is unordered; NaN is not ordered.
3744   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3745          "Comparison must be either ordered or unordered");
3746   if (match(RHS, m_NaN()))
3747     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3748 
3749   // fcmp pred x, undef  and  fcmp pred undef, x
3750   // fold to true if unordered, false if ordered
3751   if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
3752     // Choosing NaN for the undef will always make unordered comparison succeed
3753     // and ordered comparison fail.
3754     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3755   }
3756 
3757   // fcmp x,x -> true/false.  Not all compares are foldable.
3758   if (LHS == RHS) {
3759     if (CmpInst::isTrueWhenEqual(Pred))
3760       return getTrue(RetTy);
3761     if (CmpInst::isFalseWhenEqual(Pred))
3762       return getFalse(RetTy);
3763   }
3764 
3765   // Handle fcmp with constant RHS.
3766   // TODO: Use match with a specific FP value, so these work with vectors with
3767   // undef lanes.
3768   const APFloat *C;
3769   if (match(RHS, m_APFloat(C))) {
3770     // Check whether the constant is an infinity.
3771     if (C->isInfinity()) {
3772       if (C->isNegative()) {
3773         switch (Pred) {
3774         case FCmpInst::FCMP_OLT:
3775           // No value is ordered and less than negative infinity.
3776           return getFalse(RetTy);
3777         case FCmpInst::FCMP_UGE:
3778           // All values are unordered with or at least negative infinity.
3779           return getTrue(RetTy);
3780         default:
3781           break;
3782         }
3783       } else {
3784         switch (Pred) {
3785         case FCmpInst::FCMP_OGT:
3786           // No value is ordered and greater than infinity.
3787           return getFalse(RetTy);
3788         case FCmpInst::FCMP_ULE:
3789           // All values are unordered with and at most infinity.
3790           return getTrue(RetTy);
3791         default:
3792           break;
3793         }
3794       }
3795 
3796       // LHS == Inf
3797       if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
3798         return getFalse(RetTy);
3799       // LHS != Inf
3800       if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
3801         return getTrue(RetTy);
3802       // LHS == Inf || LHS == NaN
3803       if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
3804           isKnownNeverNaN(LHS, Q.TLI))
3805         return getFalse(RetTy);
3806       // LHS != Inf && LHS != NaN
3807       if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
3808           isKnownNeverNaN(LHS, Q.TLI))
3809         return getTrue(RetTy);
3810     }
3811     if (C->isNegative() && !C->isNegZero()) {
3812       assert(!C->isNaN() && "Unexpected NaN constant!");
3813       // TODO: We can catch more cases by using a range check rather than
3814       //       relying on CannotBeOrderedLessThanZero.
3815       switch (Pred) {
3816       case FCmpInst::FCMP_UGE:
3817       case FCmpInst::FCMP_UGT:
3818       case FCmpInst::FCMP_UNE:
3819         // (X >= 0) implies (X > C) when (C < 0)
3820         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3821           return getTrue(RetTy);
3822         break;
3823       case FCmpInst::FCMP_OEQ:
3824       case FCmpInst::FCMP_OLE:
3825       case FCmpInst::FCMP_OLT:
3826         // (X >= 0) implies !(X < C) when (C < 0)
3827         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3828           return getFalse(RetTy);
3829         break;
3830       default:
3831         break;
3832       }
3833     }
3834 
3835     // Check comparison of [minnum/maxnum with constant] with other constant.
3836     const APFloat *C2;
3837     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3838          *C2 < *C) ||
3839         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3840          *C2 > *C)) {
3841       bool IsMaxNum =
3842           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3843       // The ordered relationship and minnum/maxnum guarantee that we do not
3844       // have NaN constants, so ordered/unordered preds are handled the same.
3845       switch (Pred) {
3846       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3847         // minnum(X, LesserC)  == C --> false
3848         // maxnum(X, GreaterC) == C --> false
3849         return getFalse(RetTy);
3850       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3851         // minnum(X, LesserC)  != C --> true
3852         // maxnum(X, GreaterC) != C --> true
3853         return getTrue(RetTy);
3854       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3855       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3856         // minnum(X, LesserC)  >= C --> false
3857         // minnum(X, LesserC)  >  C --> false
3858         // maxnum(X, GreaterC) >= C --> true
3859         // maxnum(X, GreaterC) >  C --> true
3860         return ConstantInt::get(RetTy, IsMaxNum);
3861       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3862       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3863         // minnum(X, LesserC)  <= C --> true
3864         // minnum(X, LesserC)  <  C --> true
3865         // maxnum(X, GreaterC) <= C --> false
3866         // maxnum(X, GreaterC) <  C --> false
3867         return ConstantInt::get(RetTy, !IsMaxNum);
3868       default:
3869         // TRUE/FALSE/ORD/UNO should be handled before this.
3870         llvm_unreachable("Unexpected fcmp predicate");
3871       }
3872     }
3873   }
3874 
3875   if (match(RHS, m_AnyZeroFP())) {
3876     switch (Pred) {
3877     case FCmpInst::FCMP_OGE:
3878     case FCmpInst::FCMP_ULT:
3879       // Positive or zero X >= 0.0 --> true
3880       // Positive or zero X <  0.0 --> false
3881       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3882           CannotBeOrderedLessThanZero(LHS, Q.TLI))
3883         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3884       break;
3885     case FCmpInst::FCMP_UGE:
3886     case FCmpInst::FCMP_OLT:
3887       // Positive or zero or nan X >= 0.0 --> true
3888       // Positive or zero or nan X <  0.0 --> false
3889       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3890         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3891       break;
3892     default:
3893       break;
3894     }
3895   }
3896 
3897   // If the comparison is with the result of a select instruction, check whether
3898   // comparing with either branch of the select always yields the same value.
3899   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3900     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3901       return V;
3902 
3903   // If the comparison is with the result of a phi instruction, check whether
3904   // doing the compare with each incoming phi value yields a common result.
3905   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3906     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3907       return V;
3908 
3909   return nullptr;
3910 }
3911 
3912 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3913                               FastMathFlags FMF, const SimplifyQuery &Q) {
3914   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3915 }
3916 
3917 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3918                                      const SimplifyQuery &Q,
3919                                      bool AllowRefinement,
3920                                      unsigned MaxRecurse) {
3921   // Trivial replacement.
3922   if (V == Op)
3923     return RepOp;
3924 
3925   // We cannot replace a constant, and shouldn't even try.
3926   if (isa<Constant>(Op))
3927     return nullptr;
3928 
3929   auto *I = dyn_cast<Instruction>(V);
3930   if (!I || !is_contained(I->operands(), Op))
3931     return nullptr;
3932 
3933   // Replace Op with RepOp in instruction operands.
3934   SmallVector<Value *, 8> NewOps(I->getNumOperands());
3935   transform(I->operands(), NewOps.begin(),
3936             [&](Value *V) { return V == Op ? RepOp : V; });
3937 
3938   if (!AllowRefinement) {
3939     // General InstSimplify functions may refine the result, e.g. by returning
3940     // a constant for a potentially poison value. To avoid this, implement only
3941     // a few non-refining but profitable transforms here.
3942 
3943     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3944       unsigned Opcode = BO->getOpcode();
3945       // id op x -> x, x op id -> x
3946       if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
3947         return NewOps[1];
3948       if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
3949                                                       /* RHS */ true))
3950         return NewOps[0];
3951 
3952       // x & x -> x, x | x -> x
3953       if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
3954           NewOps[0] == NewOps[1])
3955         return NewOps[0];
3956     }
3957 
3958     if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3959       // getelementptr x, 0 -> x
3960       if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
3961           !GEP->isInBounds())
3962         return NewOps[0];
3963     }
3964   } else if (MaxRecurse) {
3965     // The simplification queries below may return the original value. Consider:
3966     //   %div = udiv i32 %arg, %arg2
3967     //   %mul = mul nsw i32 %div, %arg2
3968     //   %cmp = icmp eq i32 %mul, %arg
3969     //   %sel = select i1 %cmp, i32 %div, i32 undef
3970     // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
3971     // simplifies back to %arg. This can only happen because %mul does not
3972     // dominate %div. To ensure a consistent return value contract, we make sure
3973     // that this case returns nullptr as well.
3974     auto PreventSelfSimplify = [V](Value *Simplified) {
3975       return Simplified != V ? Simplified : nullptr;
3976     };
3977 
3978     if (auto *B = dyn_cast<BinaryOperator>(I))
3979       return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0],
3980                                                NewOps[1], Q, MaxRecurse - 1));
3981 
3982     if (CmpInst *C = dyn_cast<CmpInst>(I))
3983       return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0],
3984                                                  NewOps[1], Q, MaxRecurse - 1));
3985 
3986     if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
3987       return PreventSelfSimplify(SimplifyGEPInst(GEP->getSourceElementType(),
3988                                                  NewOps, Q, MaxRecurse - 1));
3989 
3990     if (isa<SelectInst>(I))
3991       return PreventSelfSimplify(
3992           SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q,
3993                              MaxRecurse - 1));
3994     // TODO: We could hand off more cases to instsimplify here.
3995   }
3996 
3997   // If all operands are constant after substituting Op for RepOp then we can
3998   // constant fold the instruction.
3999   SmallVector<Constant *, 8> ConstOps;
4000   for (Value *NewOp : NewOps) {
4001     if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4002       ConstOps.push_back(ConstOp);
4003     else
4004       return nullptr;
4005   }
4006 
4007   // Consider:
4008   //   %cmp = icmp eq i32 %x, 2147483647
4009   //   %add = add nsw i32 %x, 1
4010   //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
4011   //
4012   // We can't replace %sel with %add unless we strip away the flags (which
4013   // will be done in InstCombine).
4014   // TODO: This may be unsound, because it only catches some forms of
4015   // refinement.
4016   if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
4017     return nullptr;
4018 
4019   if (CmpInst *C = dyn_cast<CmpInst>(I))
4020     return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
4021                                            ConstOps[1], Q.DL, Q.TLI);
4022 
4023   if (LoadInst *LI = dyn_cast<LoadInst>(I))
4024     if (!LI->isVolatile())
4025       return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
4026 
4027   return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4028 }
4029 
4030 Value *llvm::SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4031                                     const SimplifyQuery &Q,
4032                                     bool AllowRefinement) {
4033   return ::SimplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
4034                                   RecursionLimit);
4035 }
4036 
4037 /// Try to simplify a select instruction when its condition operand is an
4038 /// integer comparison where one operand of the compare is a constant.
4039 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4040                                     const APInt *Y, bool TrueWhenUnset) {
4041   const APInt *C;
4042 
4043   // (X & Y) == 0 ? X & ~Y : X  --> X
4044   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
4045   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4046       *Y == ~*C)
4047     return TrueWhenUnset ? FalseVal : TrueVal;
4048 
4049   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
4050   // (X & Y) != 0 ? X : X & ~Y  --> X
4051   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4052       *Y == ~*C)
4053     return TrueWhenUnset ? FalseVal : TrueVal;
4054 
4055   if (Y->isPowerOf2()) {
4056     // (X & Y) == 0 ? X | Y : X  --> X | Y
4057     // (X & Y) != 0 ? X | Y : X  --> X
4058     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4059         *Y == *C)
4060       return TrueWhenUnset ? TrueVal : FalseVal;
4061 
4062     // (X & Y) == 0 ? X : X | Y  --> X
4063     // (X & Y) != 0 ? X : X | Y  --> X | Y
4064     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4065         *Y == *C)
4066       return TrueWhenUnset ? TrueVal : FalseVal;
4067   }
4068 
4069   return nullptr;
4070 }
4071 
4072 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4073 /// eq/ne.
4074 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4075                                            ICmpInst::Predicate Pred,
4076                                            Value *TrueVal, Value *FalseVal) {
4077   Value *X;
4078   APInt Mask;
4079   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4080     return nullptr;
4081 
4082   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4083                                Pred == ICmpInst::ICMP_EQ);
4084 }
4085 
4086 /// Try to simplify a select instruction when its condition operand is an
4087 /// integer comparison.
4088 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4089                                          Value *FalseVal, const SimplifyQuery &Q,
4090                                          unsigned MaxRecurse) {
4091   ICmpInst::Predicate Pred;
4092   Value *CmpLHS, *CmpRHS;
4093   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4094     return nullptr;
4095 
4096   // Canonicalize ne to eq predicate.
4097   if (Pred == ICmpInst::ICMP_NE) {
4098     Pred = ICmpInst::ICMP_EQ;
4099     std::swap(TrueVal, FalseVal);
4100   }
4101 
4102   if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4103     Value *X;
4104     const APInt *Y;
4105     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4106       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4107                                            /*TrueWhenUnset=*/true))
4108         return V;
4109 
4110     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4111     Value *ShAmt;
4112     auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4113                              m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4114     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4115     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4116     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4117       return X;
4118 
4119     // Test for a zero-shift-guard-op around rotates. These are used to
4120     // avoid UB from oversized shifts in raw IR rotate patterns, but the
4121     // intrinsics do not have that problem.
4122     // We do not allow this transform for the general funnel shift case because
4123     // that would not preserve the poison safety of the original code.
4124     auto isRotate =
4125         m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4126                     m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4127     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4128     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4129     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4130         Pred == ICmpInst::ICMP_EQ)
4131       return FalseVal;
4132 
4133     // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4134     // X == 0 ? -abs(X) : abs(X) --> abs(X)
4135     if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4136         match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4137       return FalseVal;
4138     if (match(TrueVal,
4139               m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4140         match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4141       return FalseVal;
4142   }
4143 
4144   // Check for other compares that behave like bit test.
4145   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
4146                                               TrueVal, FalseVal))
4147     return V;
4148 
4149   // If we have a scalar equality comparison, then we know the value in one of
4150   // the arms of the select. See if substituting this value into the arm and
4151   // simplifying the result yields the same value as the other arm.
4152   // Note that the equivalence/replacement opportunity does not hold for vectors
4153   // because each element of a vector select is chosen independently.
4154   if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
4155     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4156                                /* AllowRefinement */ false, MaxRecurse) ==
4157             TrueVal ||
4158         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
4159                                /* AllowRefinement */ false, MaxRecurse) ==
4160             TrueVal)
4161       return FalseVal;
4162     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4163                                /* AllowRefinement */ true, MaxRecurse) ==
4164             FalseVal ||
4165         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
4166                                /* AllowRefinement */ true, MaxRecurse) ==
4167             FalseVal)
4168       return FalseVal;
4169   }
4170 
4171   return nullptr;
4172 }
4173 
4174 /// Try to simplify a select instruction when its condition operand is a
4175 /// floating-point comparison.
4176 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4177                                      const SimplifyQuery &Q) {
4178   FCmpInst::Predicate Pred;
4179   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4180       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4181     return nullptr;
4182 
4183   // This transform is safe if we do not have (do not care about) -0.0 or if
4184   // at least one operand is known to not be -0.0. Otherwise, the select can
4185   // change the sign of a zero operand.
4186   bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) &&
4187                           Q.CxtI->hasNoSignedZeros();
4188   const APFloat *C;
4189   if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4190                           (match(F, m_APFloat(C)) && C->isNonZero())) {
4191     // (T == F) ? T : F --> F
4192     // (F == T) ? T : F --> F
4193     if (Pred == FCmpInst::FCMP_OEQ)
4194       return F;
4195 
4196     // (T != F) ? T : F --> T
4197     // (F != T) ? T : F --> T
4198     if (Pred == FCmpInst::FCMP_UNE)
4199       return T;
4200   }
4201 
4202   return nullptr;
4203 }
4204 
4205 /// Given operands for a SelectInst, see if we can fold the result.
4206 /// If not, this returns null.
4207 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4208                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
4209   if (auto *CondC = dyn_cast<Constant>(Cond)) {
4210     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4211       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4212         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4213 
4214     // select undef, X, Y -> X or Y
4215     if (Q.isUndefValue(CondC))
4216       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4217 
4218     // TODO: Vector constants with undef elements don't simplify.
4219 
4220     // select true, X, Y  -> X
4221     if (CondC->isAllOnesValue())
4222       return TrueVal;
4223     // select false, X, Y -> Y
4224     if (CondC->isNullValue())
4225       return FalseVal;
4226   }
4227 
4228   // select i1 Cond, i1 true, i1 false --> i1 Cond
4229   assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4230          "Select must have bool or bool vector condition");
4231   assert(TrueVal->getType() == FalseVal->getType() &&
4232          "Select must have same types for true/false ops");
4233   if (Cond->getType() == TrueVal->getType() &&
4234       match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4235     return Cond;
4236 
4237   // select ?, X, X -> X
4238   if (TrueVal == FalseVal)
4239     return TrueVal;
4240 
4241   // If the true or false value is undef, we can fold to the other value as
4242   // long as the other value isn't poison.
4243   // select ?, undef, X -> X
4244   if (Q.isUndefValue(TrueVal) &&
4245       isGuaranteedNotToBeUndefOrPoison(FalseVal, Q.AC, Q.CxtI, Q.DT))
4246     return FalseVal;
4247   // select ?, X, undef -> X
4248   if (Q.isUndefValue(FalseVal) &&
4249       isGuaranteedNotToBeUndefOrPoison(TrueVal, Q.AC, Q.CxtI, Q.DT))
4250     return TrueVal;
4251 
4252   // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4253   Constant *TrueC, *FalseC;
4254   if (isa<FixedVectorType>(TrueVal->getType()) &&
4255       match(TrueVal, m_Constant(TrueC)) &&
4256       match(FalseVal, m_Constant(FalseC))) {
4257     unsigned NumElts =
4258         cast<FixedVectorType>(TrueC->getType())->getNumElements();
4259     SmallVector<Constant *, 16> NewC;
4260     for (unsigned i = 0; i != NumElts; ++i) {
4261       // Bail out on incomplete vector constants.
4262       Constant *TEltC = TrueC->getAggregateElement(i);
4263       Constant *FEltC = FalseC->getAggregateElement(i);
4264       if (!TEltC || !FEltC)
4265         break;
4266 
4267       // If the elements match (undef or not), that value is the result. If only
4268       // one element is undef, choose the defined element as the safe result.
4269       if (TEltC == FEltC)
4270         NewC.push_back(TEltC);
4271       else if (Q.isUndefValue(TEltC) &&
4272                isGuaranteedNotToBeUndefOrPoison(FEltC))
4273         NewC.push_back(FEltC);
4274       else if (Q.isUndefValue(FEltC) &&
4275                isGuaranteedNotToBeUndefOrPoison(TEltC))
4276         NewC.push_back(TEltC);
4277       else
4278         break;
4279     }
4280     if (NewC.size() == NumElts)
4281       return ConstantVector::get(NewC);
4282   }
4283 
4284   if (Value *V =
4285           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4286     return V;
4287 
4288   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4289     return V;
4290 
4291   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4292     return V;
4293 
4294   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4295   if (Imp)
4296     return *Imp ? TrueVal : FalseVal;
4297 
4298   return nullptr;
4299 }
4300 
4301 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4302                                 const SimplifyQuery &Q) {
4303   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4304 }
4305 
4306 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4307 /// If not, this returns null.
4308 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4309                               const SimplifyQuery &Q, unsigned) {
4310   // The type of the GEP pointer operand.
4311   unsigned AS =
4312       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
4313 
4314   // getelementptr P -> P.
4315   if (Ops.size() == 1)
4316     return Ops[0];
4317 
4318   // Compute the (pointer) type returned by the GEP instruction.
4319   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
4320   Type *GEPTy = PointerType::get(LastType, AS);
4321   for (Value *Op : Ops) {
4322     // If one of the operands is a vector, the result type is a vector of
4323     // pointers. All vector operands must have the same number of elements.
4324     if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4325       GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4326       break;
4327     }
4328   }
4329 
4330   // getelementptr poison, idx -> poison
4331   // getelementptr baseptr, poison -> poison
4332   if (any_of(Ops, [](const auto *V) { return isa<PoisonValue>(V); }))
4333     return PoisonValue::get(GEPTy);
4334 
4335   if (Q.isUndefValue(Ops[0]))
4336     return UndefValue::get(GEPTy);
4337 
4338   bool IsScalableVec =
4339       isa<ScalableVectorType>(SrcTy) || any_of(Ops, [](const Value *V) {
4340         return isa<ScalableVectorType>(V->getType());
4341       });
4342 
4343   if (Ops.size() == 2) {
4344     // getelementptr P, 0 -> P.
4345     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
4346       return Ops[0];
4347 
4348     Type *Ty = SrcTy;
4349     if (!IsScalableVec && Ty->isSized()) {
4350       Value *P;
4351       uint64_t C;
4352       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4353       // getelementptr P, N -> P if P points to a type of zero size.
4354       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4355         return Ops[0];
4356 
4357       // The following transforms are only safe if the ptrtoint cast
4358       // doesn't truncate the pointers.
4359       if (Ops[1]->getType()->getScalarSizeInBits() ==
4360           Q.DL.getPointerSizeInBits(AS)) {
4361         auto CanSimplify = [GEPTy, &P, V = Ops[0]]() -> bool {
4362           return P->getType() == GEPTy &&
4363                  getUnderlyingObject(P) == getUnderlyingObject(V);
4364         };
4365         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4366         if (TyAllocSize == 1 &&
4367             match(Ops[1], m_Sub(m_PtrToInt(m_Value(P)),
4368                                 m_PtrToInt(m_Specific(Ops[0])))) &&
4369             CanSimplify())
4370           return P;
4371 
4372         // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
4373         // size 1 << C.
4374         if (match(Ops[1], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
4375                                        m_PtrToInt(m_Specific(Ops[0]))),
4376                                  m_ConstantInt(C))) &&
4377             TyAllocSize == 1ULL << C && CanSimplify())
4378           return P;
4379 
4380         // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
4381         // size C.
4382         if (match(Ops[1], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
4383                                        m_PtrToInt(m_Specific(Ops[0]))),
4384                                  m_SpecificInt(TyAllocSize))) &&
4385             CanSimplify())
4386           return P;
4387       }
4388     }
4389   }
4390 
4391   if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
4392       all_of(Ops.slice(1).drop_back(1),
4393              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4394     unsigned IdxWidth =
4395         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4396     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4397       APInt BasePtrOffset(IdxWidth, 0);
4398       Value *StrippedBasePtr =
4399           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4400                                                             BasePtrOffset);
4401 
4402       // Avoid creating inttoptr of zero here: While LLVMs treatment of
4403       // inttoptr is generally conservative, this particular case is folded to
4404       // a null pointer, which will have incorrect provenance.
4405 
4406       // gep (gep V, C), (sub 0, V) -> C
4407       if (match(Ops.back(),
4408                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
4409           !BasePtrOffset.isNullValue()) {
4410         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4411         return ConstantExpr::getIntToPtr(CI, GEPTy);
4412       }
4413       // gep (gep V, C), (xor V, -1) -> C-1
4414       if (match(Ops.back(),
4415                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
4416           !BasePtrOffset.isOneValue()) {
4417         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4418         return ConstantExpr::getIntToPtr(CI, GEPTy);
4419       }
4420     }
4421   }
4422 
4423   // Check to see if this is constant foldable.
4424   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4425     return nullptr;
4426 
4427   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4428                                             Ops.slice(1));
4429   return ConstantFoldConstant(CE, Q.DL);
4430 }
4431 
4432 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4433                              const SimplifyQuery &Q) {
4434   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4435 }
4436 
4437 /// Given operands for an InsertValueInst, see if we can fold the result.
4438 /// If not, this returns null.
4439 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4440                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4441                                       unsigned) {
4442   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4443     if (Constant *CVal = dyn_cast<Constant>(Val))
4444       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4445 
4446   // insertvalue x, undef, n -> x
4447   if (Q.isUndefValue(Val))
4448     return Agg;
4449 
4450   // insertvalue x, (extractvalue y, n), n
4451   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4452     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4453         EV->getIndices() == Idxs) {
4454       // insertvalue undef, (extractvalue y, n), n -> y
4455       if (Q.isUndefValue(Agg))
4456         return EV->getAggregateOperand();
4457 
4458       // insertvalue y, (extractvalue y, n), n -> y
4459       if (Agg == EV->getAggregateOperand())
4460         return Agg;
4461     }
4462 
4463   return nullptr;
4464 }
4465 
4466 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4467                                      ArrayRef<unsigned> Idxs,
4468                                      const SimplifyQuery &Q) {
4469   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4470 }
4471 
4472 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4473                                        const SimplifyQuery &Q) {
4474   // Try to constant fold.
4475   auto *VecC = dyn_cast<Constant>(Vec);
4476   auto *ValC = dyn_cast<Constant>(Val);
4477   auto *IdxC = dyn_cast<Constant>(Idx);
4478   if (VecC && ValC && IdxC)
4479     return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
4480 
4481   // For fixed-length vector, fold into poison if index is out of bounds.
4482   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4483     if (isa<FixedVectorType>(Vec->getType()) &&
4484         CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
4485       return PoisonValue::get(Vec->getType());
4486   }
4487 
4488   // If index is undef, it might be out of bounds (see above case)
4489   if (Q.isUndefValue(Idx))
4490     return PoisonValue::get(Vec->getType());
4491 
4492   // If the scalar is poison, or it is undef and there is no risk of
4493   // propagating poison from the vector value, simplify to the vector value.
4494   if (isa<PoisonValue>(Val) ||
4495       (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
4496     return Vec;
4497 
4498   // If we are extracting a value from a vector, then inserting it into the same
4499   // place, that's the input vector:
4500   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4501   if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
4502     return Vec;
4503 
4504   return nullptr;
4505 }
4506 
4507 /// Given operands for an ExtractValueInst, see if we can fold the result.
4508 /// If not, this returns null.
4509 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4510                                        const SimplifyQuery &, unsigned) {
4511   if (auto *CAgg = dyn_cast<Constant>(Agg))
4512     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4513 
4514   // extractvalue x, (insertvalue y, elt, n), n -> elt
4515   unsigned NumIdxs = Idxs.size();
4516   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4517        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4518     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4519     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4520     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4521     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4522         Idxs.slice(0, NumCommonIdxs)) {
4523       if (NumIdxs == NumInsertValueIdxs)
4524         return IVI->getInsertedValueOperand();
4525       break;
4526     }
4527   }
4528 
4529   return nullptr;
4530 }
4531 
4532 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4533                                       const SimplifyQuery &Q) {
4534   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4535 }
4536 
4537 /// Given operands for an ExtractElementInst, see if we can fold the result.
4538 /// If not, this returns null.
4539 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
4540                                          const SimplifyQuery &Q, unsigned) {
4541   auto *VecVTy = cast<VectorType>(Vec->getType());
4542   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4543     if (auto *CIdx = dyn_cast<Constant>(Idx))
4544       return ConstantExpr::getExtractElement(CVec, CIdx);
4545 
4546     // The index is not relevant if our vector is a splat.
4547     if (auto *Splat = CVec->getSplatValue())
4548       return Splat;
4549 
4550     if (Q.isUndefValue(Vec))
4551       return UndefValue::get(VecVTy->getElementType());
4552   }
4553 
4554   // If extracting a specified index from the vector, see if we can recursively
4555   // find a previously computed scalar that was inserted into the vector.
4556   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4557     // For fixed-length vector, fold into undef if index is out of bounds.
4558     if (isa<FixedVectorType>(VecVTy) &&
4559         IdxC->getValue().uge(cast<FixedVectorType>(VecVTy)->getNumElements()))
4560       return PoisonValue::get(VecVTy->getElementType());
4561     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4562       return Elt;
4563   }
4564 
4565   // An undef extract index can be arbitrarily chosen to be an out-of-range
4566   // index value, which would result in the instruction being poison.
4567   if (Q.isUndefValue(Idx))
4568     return PoisonValue::get(VecVTy->getElementType());
4569 
4570   return nullptr;
4571 }
4572 
4573 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4574                                         const SimplifyQuery &Q) {
4575   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4576 }
4577 
4578 /// See if we can fold the given phi. If not, returns null.
4579 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4580   // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
4581   //          here, because the PHI we may succeed simplifying to was not
4582   //          def-reachable from the original PHI!
4583 
4584   // If all of the PHI's incoming values are the same then replace the PHI node
4585   // with the common value.
4586   Value *CommonValue = nullptr;
4587   bool HasUndefInput = false;
4588   for (Value *Incoming : PN->incoming_values()) {
4589     // If the incoming value is the phi node itself, it can safely be skipped.
4590     if (Incoming == PN) continue;
4591     if (Q.isUndefValue(Incoming)) {
4592       // Remember that we saw an undef value, but otherwise ignore them.
4593       HasUndefInput = true;
4594       continue;
4595     }
4596     if (CommonValue && Incoming != CommonValue)
4597       return nullptr;  // Not the same, bail out.
4598     CommonValue = Incoming;
4599   }
4600 
4601   // If CommonValue is null then all of the incoming values were either undef or
4602   // equal to the phi node itself.
4603   if (!CommonValue)
4604     return UndefValue::get(PN->getType());
4605 
4606   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4607   // instruction, we cannot return X as the result of the PHI node unless it
4608   // dominates the PHI block.
4609   if (HasUndefInput)
4610     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4611 
4612   return CommonValue;
4613 }
4614 
4615 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4616                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4617   if (auto *C = dyn_cast<Constant>(Op))
4618     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4619 
4620   if (auto *CI = dyn_cast<CastInst>(Op)) {
4621     auto *Src = CI->getOperand(0);
4622     Type *SrcTy = Src->getType();
4623     Type *MidTy = CI->getType();
4624     Type *DstTy = Ty;
4625     if (Src->getType() == Ty) {
4626       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4627       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4628       Type *SrcIntPtrTy =
4629           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4630       Type *MidIntPtrTy =
4631           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4632       Type *DstIntPtrTy =
4633           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4634       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4635                                          SrcIntPtrTy, MidIntPtrTy,
4636                                          DstIntPtrTy) == Instruction::BitCast)
4637         return Src;
4638     }
4639   }
4640 
4641   // bitcast x -> x
4642   if (CastOpc == Instruction::BitCast)
4643     if (Op->getType() == Ty)
4644       return Op;
4645 
4646   return nullptr;
4647 }
4648 
4649 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4650                               const SimplifyQuery &Q) {
4651   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4652 }
4653 
4654 /// For the given destination element of a shuffle, peek through shuffles to
4655 /// match a root vector source operand that contains that element in the same
4656 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4657 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4658                                    int MaskVal, Value *RootVec,
4659                                    unsigned MaxRecurse) {
4660   if (!MaxRecurse--)
4661     return nullptr;
4662 
4663   // Bail out if any mask value is undefined. That kind of shuffle may be
4664   // simplified further based on demanded bits or other folds.
4665   if (MaskVal == -1)
4666     return nullptr;
4667 
4668   // The mask value chooses which source operand we need to look at next.
4669   int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
4670   int RootElt = MaskVal;
4671   Value *SourceOp = Op0;
4672   if (MaskVal >= InVecNumElts) {
4673     RootElt = MaskVal - InVecNumElts;
4674     SourceOp = Op1;
4675   }
4676 
4677   // If the source operand is a shuffle itself, look through it to find the
4678   // matching root vector.
4679   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4680     return foldIdentityShuffles(
4681         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4682         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4683   }
4684 
4685   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4686   // size?
4687 
4688   // The source operand is not a shuffle. Initialize the root vector value for
4689   // this shuffle if that has not been done yet.
4690   if (!RootVec)
4691     RootVec = SourceOp;
4692 
4693   // Give up as soon as a source operand does not match the existing root value.
4694   if (RootVec != SourceOp)
4695     return nullptr;
4696 
4697   // The element must be coming from the same lane in the source vector
4698   // (although it may have crossed lanes in intermediate shuffles).
4699   if (RootElt != DestElt)
4700     return nullptr;
4701 
4702   return RootVec;
4703 }
4704 
4705 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4706                                         ArrayRef<int> Mask, Type *RetTy,
4707                                         const SimplifyQuery &Q,
4708                                         unsigned MaxRecurse) {
4709   if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
4710     return UndefValue::get(RetTy);
4711 
4712   auto *InVecTy = cast<VectorType>(Op0->getType());
4713   unsigned MaskNumElts = Mask.size();
4714   ElementCount InVecEltCount = InVecTy->getElementCount();
4715 
4716   bool Scalable = InVecEltCount.isScalable();
4717 
4718   SmallVector<int, 32> Indices;
4719   Indices.assign(Mask.begin(), Mask.end());
4720 
4721   // Canonicalization: If mask does not select elements from an input vector,
4722   // replace that input vector with poison.
4723   if (!Scalable) {
4724     bool MaskSelects0 = false, MaskSelects1 = false;
4725     unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
4726     for (unsigned i = 0; i != MaskNumElts; ++i) {
4727       if (Indices[i] == -1)
4728         continue;
4729       if ((unsigned)Indices[i] < InVecNumElts)
4730         MaskSelects0 = true;
4731       else
4732         MaskSelects1 = true;
4733     }
4734     if (!MaskSelects0)
4735       Op0 = PoisonValue::get(InVecTy);
4736     if (!MaskSelects1)
4737       Op1 = PoisonValue::get(InVecTy);
4738   }
4739 
4740   auto *Op0Const = dyn_cast<Constant>(Op0);
4741   auto *Op1Const = dyn_cast<Constant>(Op1);
4742 
4743   // If all operands are constant, constant fold the shuffle. This
4744   // transformation depends on the value of the mask which is not known at
4745   // compile time for scalable vectors
4746   if (Op0Const && Op1Const)
4747     return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
4748 
4749   // Canonicalization: if only one input vector is constant, it shall be the
4750   // second one. This transformation depends on the value of the mask which
4751   // is not known at compile time for scalable vectors
4752   if (!Scalable && Op0Const && !Op1Const) {
4753     std::swap(Op0, Op1);
4754     ShuffleVectorInst::commuteShuffleMask(Indices,
4755                                           InVecEltCount.getKnownMinValue());
4756   }
4757 
4758   // A splat of an inserted scalar constant becomes a vector constant:
4759   // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
4760   // NOTE: We may have commuted above, so analyze the updated Indices, not the
4761   //       original mask constant.
4762   // NOTE: This transformation depends on the value of the mask which is not
4763   // known at compile time for scalable vectors
4764   Constant *C;
4765   ConstantInt *IndexC;
4766   if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
4767                                           m_ConstantInt(IndexC)))) {
4768     // Match a splat shuffle mask of the insert index allowing undef elements.
4769     int InsertIndex = IndexC->getZExtValue();
4770     if (all_of(Indices, [InsertIndex](int MaskElt) {
4771           return MaskElt == InsertIndex || MaskElt == -1;
4772         })) {
4773       assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
4774 
4775       // Shuffle mask undefs become undefined constant result elements.
4776       SmallVector<Constant *, 16> VecC(MaskNumElts, C);
4777       for (unsigned i = 0; i != MaskNumElts; ++i)
4778         if (Indices[i] == -1)
4779           VecC[i] = UndefValue::get(C->getType());
4780       return ConstantVector::get(VecC);
4781     }
4782   }
4783 
4784   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4785   // value type is same as the input vectors' type.
4786   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4787     if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
4788         is_splat(OpShuf->getShuffleMask()))
4789       return Op0;
4790 
4791   // All remaining transformation depend on the value of the mask, which is
4792   // not known at compile time for scalable vectors.
4793   if (Scalable)
4794     return nullptr;
4795 
4796   // Don't fold a shuffle with undef mask elements. This may get folded in a
4797   // better way using demanded bits or other analysis.
4798   // TODO: Should we allow this?
4799   if (is_contained(Indices, -1))
4800     return nullptr;
4801 
4802   // Check if every element of this shuffle can be mapped back to the
4803   // corresponding element of a single root vector. If so, we don't need this
4804   // shuffle. This handles simple identity shuffles as well as chains of
4805   // shuffles that may widen/narrow and/or move elements across lanes and back.
4806   Value *RootVec = nullptr;
4807   for (unsigned i = 0; i != MaskNumElts; ++i) {
4808     // Note that recursion is limited for each vector element, so if any element
4809     // exceeds the limit, this will fail to simplify.
4810     RootVec =
4811         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4812 
4813     // We can't replace a widening/narrowing shuffle with one of its operands.
4814     if (!RootVec || RootVec->getType() != RetTy)
4815       return nullptr;
4816   }
4817   return RootVec;
4818 }
4819 
4820 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4821 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1,
4822                                        ArrayRef<int> Mask, Type *RetTy,
4823                                        const SimplifyQuery &Q) {
4824   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4825 }
4826 
4827 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4828                               Value *&Op, const SimplifyQuery &Q) {
4829   if (auto *C = dyn_cast<Constant>(Op))
4830     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4831   return nullptr;
4832 }
4833 
4834 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
4835 /// returns null.
4836 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4837                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4838   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4839     return C;
4840 
4841   Value *X;
4842   // fneg (fneg X) ==> X
4843   if (match(Op, m_FNeg(m_Value(X))))
4844     return X;
4845 
4846   return nullptr;
4847 }
4848 
4849 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4850                               const SimplifyQuery &Q) {
4851   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4852 }
4853 
4854 static Constant *propagateNaN(Constant *In) {
4855   // If the input is a vector with undef elements, just return a default NaN.
4856   if (!In->isNaN())
4857     return ConstantFP::getNaN(In->getType());
4858 
4859   // Propagate the existing NaN constant when possible.
4860   // TODO: Should we quiet a signaling NaN?
4861   return In;
4862 }
4863 
4864 /// Perform folds that are common to any floating-point operation. This implies
4865 /// transforms based on undef/NaN because the operation itself makes no
4866 /// difference to the result.
4867 static Constant *simplifyFPOp(ArrayRef<Value *> Ops,
4868                               FastMathFlags FMF,
4869                               const SimplifyQuery &Q) {
4870   for (Value *V : Ops) {
4871     bool IsNan = match(V, m_NaN());
4872     bool IsInf = match(V, m_Inf());
4873     bool IsUndef = Q.isUndefValue(V);
4874 
4875     // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
4876     // (an undef operand can be chosen to be Nan/Inf), then the result of
4877     // this operation is poison.
4878     if (FMF.noNaNs() && (IsNan || IsUndef))
4879       return PoisonValue::get(V->getType());
4880     if (FMF.noInfs() && (IsInf || IsUndef))
4881       return PoisonValue::get(V->getType());
4882 
4883     if (IsUndef || IsNan)
4884       return propagateNaN(cast<Constant>(V));
4885   }
4886   return nullptr;
4887 }
4888 
4889 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4890 /// returns null.
4891 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4892                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4893   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4894     return C;
4895 
4896   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4897     return C;
4898 
4899   // fadd X, -0 ==> X
4900   if (match(Op1, m_NegZeroFP()))
4901     return Op0;
4902 
4903   // fadd X, 0 ==> X, when we know X is not -0
4904   if (match(Op1, m_PosZeroFP()) &&
4905       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4906     return Op0;
4907 
4908   // With nnan: -X + X --> 0.0 (and commuted variant)
4909   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4910   // Negative zeros are allowed because we always end up with positive zero:
4911   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4912   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4913   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4914   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4915   if (FMF.noNaNs()) {
4916     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4917         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4918       return ConstantFP::getNullValue(Op0->getType());
4919 
4920     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4921         match(Op1, m_FNeg(m_Specific(Op0))))
4922       return ConstantFP::getNullValue(Op0->getType());
4923   }
4924 
4925   // (X - Y) + Y --> X
4926   // Y + (X - Y) --> X
4927   Value *X;
4928   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4929       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4930        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4931     return X;
4932 
4933   return nullptr;
4934 }
4935 
4936 /// Given operands for an FSub, see if we can fold the result.  If not, this
4937 /// returns null.
4938 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4939                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4940   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4941     return C;
4942 
4943   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4944     return C;
4945 
4946   // fsub X, +0 ==> X
4947   if (match(Op1, m_PosZeroFP()))
4948     return Op0;
4949 
4950   // fsub X, -0 ==> X, when we know X is not -0
4951   if (match(Op1, m_NegZeroFP()) &&
4952       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4953     return Op0;
4954 
4955   // fsub -0.0, (fsub -0.0, X) ==> X
4956   // fsub -0.0, (fneg X) ==> X
4957   Value *X;
4958   if (match(Op0, m_NegZeroFP()) &&
4959       match(Op1, m_FNeg(m_Value(X))))
4960     return X;
4961 
4962   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4963   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4964   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4965       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4966        match(Op1, m_FNeg(m_Value(X)))))
4967     return X;
4968 
4969   // fsub nnan x, x ==> 0.0
4970   if (FMF.noNaNs() && Op0 == Op1)
4971     return Constant::getNullValue(Op0->getType());
4972 
4973   // Y - (Y - X) --> X
4974   // (X + Y) - Y --> X
4975   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4976       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4977        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4978     return X;
4979 
4980   return nullptr;
4981 }
4982 
4983 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4984                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4985   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
4986     return C;
4987 
4988   // fmul X, 1.0 ==> X
4989   if (match(Op1, m_FPOne()))
4990     return Op0;
4991 
4992   // fmul 1.0, X ==> X
4993   if (match(Op0, m_FPOne()))
4994     return Op1;
4995 
4996   // fmul nnan nsz X, 0 ==> 0
4997   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4998     return ConstantFP::getNullValue(Op0->getType());
4999 
5000   // fmul nnan nsz 0, X ==> 0
5001   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5002     return ConstantFP::getNullValue(Op1->getType());
5003 
5004   // sqrt(X) * sqrt(X) --> X, if we can:
5005   // 1. Remove the intermediate rounding (reassociate).
5006   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5007   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5008   Value *X;
5009   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
5010       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
5011     return X;
5012 
5013   return nullptr;
5014 }
5015 
5016 /// Given the operands for an FMul, see if we can fold the result
5017 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5018                                const SimplifyQuery &Q, unsigned MaxRecurse) {
5019   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5020     return C;
5021 
5022   // Now apply simplifications that do not require rounding.
5023   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse);
5024 }
5025 
5026 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5027                               const SimplifyQuery &Q) {
5028   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
5029 }
5030 
5031 
5032 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5033                               const SimplifyQuery &Q) {
5034   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
5035 }
5036 
5037 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5038                               const SimplifyQuery &Q) {
5039   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
5040 }
5041 
5042 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5043                              const SimplifyQuery &Q) {
5044   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit);
5045 }
5046 
5047 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5048                                const SimplifyQuery &Q, unsigned) {
5049   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5050     return C;
5051 
5052   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
5053     return C;
5054 
5055   // X / 1.0 -> X
5056   if (match(Op1, m_FPOne()))
5057     return Op0;
5058 
5059   // 0 / X -> 0
5060   // Requires that NaNs are off (X could be zero) and signed zeroes are
5061   // ignored (X could be positive or negative, so the output sign is unknown).
5062   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5063     return ConstantFP::getNullValue(Op0->getType());
5064 
5065   if (FMF.noNaNs()) {
5066     // X / X -> 1.0 is legal when NaNs are ignored.
5067     // We can ignore infinities because INF/INF is NaN.
5068     if (Op0 == Op1)
5069       return ConstantFP::get(Op0->getType(), 1.0);
5070 
5071     // (X * Y) / Y --> X if we can reassociate to the above form.
5072     Value *X;
5073     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5074       return X;
5075 
5076     // -X /  X -> -1.0 and
5077     //  X / -X -> -1.0 are legal when NaNs are ignored.
5078     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5079     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5080         match(Op1, m_FNegNSZ(m_Specific(Op0))))
5081       return ConstantFP::get(Op0->getType(), -1.0);
5082   }
5083 
5084   return nullptr;
5085 }
5086 
5087 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5088                               const SimplifyQuery &Q) {
5089   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
5090 }
5091 
5092 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5093                                const SimplifyQuery &Q, unsigned) {
5094   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5095     return C;
5096 
5097   if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q))
5098     return C;
5099 
5100   // Unlike fdiv, the result of frem always matches the sign of the dividend.
5101   // The constant match may include undef elements in a vector, so return a full
5102   // zero constant as the result.
5103   if (FMF.noNaNs()) {
5104     // +0 % X -> 0
5105     if (match(Op0, m_PosZeroFP()))
5106       return ConstantFP::getNullValue(Op0->getType());
5107     // -0 % X -> -0
5108     if (match(Op0, m_NegZeroFP()))
5109       return ConstantFP::getNegativeZero(Op0->getType());
5110   }
5111 
5112   return nullptr;
5113 }
5114 
5115 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5116                               const SimplifyQuery &Q) {
5117   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
5118 }
5119 
5120 //=== Helper functions for higher up the class hierarchy.
5121 
5122 /// Given the operand for a UnaryOperator, see if we can fold the result.
5123 /// If not, this returns null.
5124 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5125                            unsigned MaxRecurse) {
5126   switch (Opcode) {
5127   case Instruction::FNeg:
5128     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5129   default:
5130     llvm_unreachable("Unexpected opcode");
5131   }
5132 }
5133 
5134 /// Given the operand for a UnaryOperator, see if we can fold the result.
5135 /// If not, this returns null.
5136 /// Try to use FastMathFlags when folding the result.
5137 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5138                              const FastMathFlags &FMF,
5139                              const SimplifyQuery &Q, unsigned MaxRecurse) {
5140   switch (Opcode) {
5141   case Instruction::FNeg:
5142     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5143   default:
5144     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5145   }
5146 }
5147 
5148 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5149   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5150 }
5151 
5152 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5153                           const SimplifyQuery &Q) {
5154   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5155 }
5156 
5157 /// Given operands for a BinaryOperator, see if we can fold the result.
5158 /// If not, this returns null.
5159 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5160                             const SimplifyQuery &Q, unsigned MaxRecurse) {
5161   switch (Opcode) {
5162   case Instruction::Add:
5163     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
5164   case Instruction::Sub:
5165     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
5166   case Instruction::Mul:
5167     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
5168   case Instruction::SDiv:
5169     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
5170   case Instruction::UDiv:
5171     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
5172   case Instruction::SRem:
5173     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
5174   case Instruction::URem:
5175     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
5176   case Instruction::Shl:
5177     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
5178   case Instruction::LShr:
5179     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
5180   case Instruction::AShr:
5181     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
5182   case Instruction::And:
5183     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
5184   case Instruction::Or:
5185     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
5186   case Instruction::Xor:
5187     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
5188   case Instruction::FAdd:
5189     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5190   case Instruction::FSub:
5191     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5192   case Instruction::FMul:
5193     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5194   case Instruction::FDiv:
5195     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5196   case Instruction::FRem:
5197     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5198   default:
5199     llvm_unreachable("Unexpected opcode");
5200   }
5201 }
5202 
5203 /// Given operands for a BinaryOperator, see if we can fold the result.
5204 /// If not, this returns null.
5205 /// Try to use FastMathFlags when folding the result.
5206 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5207                             const FastMathFlags &FMF, const SimplifyQuery &Q,
5208                             unsigned MaxRecurse) {
5209   switch (Opcode) {
5210   case Instruction::FAdd:
5211     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
5212   case Instruction::FSub:
5213     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
5214   case Instruction::FMul:
5215     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
5216   case Instruction::FDiv:
5217     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
5218   default:
5219     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
5220   }
5221 }
5222 
5223 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5224                            const SimplifyQuery &Q) {
5225   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
5226 }
5227 
5228 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5229                            FastMathFlags FMF, const SimplifyQuery &Q) {
5230   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
5231 }
5232 
5233 /// Given operands for a CmpInst, see if we can fold the result.
5234 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5235                               const SimplifyQuery &Q, unsigned MaxRecurse) {
5236   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
5237     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
5238   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
5239 }
5240 
5241 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
5242                              const SimplifyQuery &Q) {
5243   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
5244 }
5245 
5246 static bool IsIdempotent(Intrinsic::ID ID) {
5247   switch (ID) {
5248   default: return false;
5249 
5250   // Unary idempotent: f(f(x)) = f(x)
5251   case Intrinsic::fabs:
5252   case Intrinsic::floor:
5253   case Intrinsic::ceil:
5254   case Intrinsic::trunc:
5255   case Intrinsic::rint:
5256   case Intrinsic::nearbyint:
5257   case Intrinsic::round:
5258   case Intrinsic::roundeven:
5259   case Intrinsic::canonicalize:
5260     return true;
5261   }
5262 }
5263 
5264 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
5265                                    const DataLayout &DL) {
5266   GlobalValue *PtrSym;
5267   APInt PtrOffset;
5268   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
5269     return nullptr;
5270 
5271   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
5272   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
5273   Type *Int32PtrTy = Int32Ty->getPointerTo();
5274   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
5275 
5276   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
5277   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
5278     return nullptr;
5279 
5280   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
5281   if (OffsetInt % 4 != 0)
5282     return nullptr;
5283 
5284   Constant *C = ConstantExpr::getGetElementPtr(
5285       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
5286       ConstantInt::get(Int64Ty, OffsetInt / 4));
5287   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
5288   if (!Loaded)
5289     return nullptr;
5290 
5291   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
5292   if (!LoadedCE)
5293     return nullptr;
5294 
5295   if (LoadedCE->getOpcode() == Instruction::Trunc) {
5296     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5297     if (!LoadedCE)
5298       return nullptr;
5299   }
5300 
5301   if (LoadedCE->getOpcode() != Instruction::Sub)
5302     return nullptr;
5303 
5304   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
5305   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
5306     return nullptr;
5307   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
5308 
5309   Constant *LoadedRHS = LoadedCE->getOperand(1);
5310   GlobalValue *LoadedRHSSym;
5311   APInt LoadedRHSOffset;
5312   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
5313                                   DL) ||
5314       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
5315     return nullptr;
5316 
5317   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
5318 }
5319 
5320 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
5321                                      const SimplifyQuery &Q) {
5322   // Idempotent functions return the same result when called repeatedly.
5323   Intrinsic::ID IID = F->getIntrinsicID();
5324   if (IsIdempotent(IID))
5325     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
5326       if (II->getIntrinsicID() == IID)
5327         return II;
5328 
5329   Value *X;
5330   switch (IID) {
5331   case Intrinsic::fabs:
5332     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
5333     break;
5334   case Intrinsic::bswap:
5335     // bswap(bswap(x)) -> x
5336     if (match(Op0, m_BSwap(m_Value(X)))) return X;
5337     break;
5338   case Intrinsic::bitreverse:
5339     // bitreverse(bitreverse(x)) -> x
5340     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
5341     break;
5342   case Intrinsic::ctpop: {
5343     // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
5344     // ctpop(and X, 1) --> and X, 1
5345     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
5346     if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
5347                           Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
5348       return Op0;
5349     break;
5350   }
5351   case Intrinsic::exp:
5352     // exp(log(x)) -> x
5353     if (Q.CxtI->hasAllowReassoc() &&
5354         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
5355     break;
5356   case Intrinsic::exp2:
5357     // exp2(log2(x)) -> x
5358     if (Q.CxtI->hasAllowReassoc() &&
5359         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
5360     break;
5361   case Intrinsic::log:
5362     // log(exp(x)) -> x
5363     if (Q.CxtI->hasAllowReassoc() &&
5364         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
5365     break;
5366   case Intrinsic::log2:
5367     // log2(exp2(x)) -> x
5368     if (Q.CxtI->hasAllowReassoc() &&
5369         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
5370          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
5371                                                 m_Value(X))))) return X;
5372     break;
5373   case Intrinsic::log10:
5374     // log10(pow(10.0, x)) -> x
5375     if (Q.CxtI->hasAllowReassoc() &&
5376         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
5377                                                m_Value(X)))) return X;
5378     break;
5379   case Intrinsic::floor:
5380   case Intrinsic::trunc:
5381   case Intrinsic::ceil:
5382   case Intrinsic::round:
5383   case Intrinsic::roundeven:
5384   case Intrinsic::nearbyint:
5385   case Intrinsic::rint: {
5386     // floor (sitofp x) -> sitofp x
5387     // floor (uitofp x) -> uitofp x
5388     //
5389     // Converting from int always results in a finite integral number or
5390     // infinity. For either of those inputs, these rounding functions always
5391     // return the same value, so the rounding can be eliminated.
5392     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
5393       return Op0;
5394     break;
5395   }
5396   case Intrinsic::experimental_vector_reverse:
5397     // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
5398     if (match(Op0,
5399               m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
5400       return X;
5401     break;
5402   default:
5403     break;
5404   }
5405 
5406   return nullptr;
5407 }
5408 
5409 static APInt getMaxMinLimit(Intrinsic::ID IID, unsigned BitWidth) {
5410   switch (IID) {
5411   case Intrinsic::smax: return APInt::getSignedMaxValue(BitWidth);
5412   case Intrinsic::smin: return APInt::getSignedMinValue(BitWidth);
5413   case Intrinsic::umax: return APInt::getMaxValue(BitWidth);
5414   case Intrinsic::umin: return APInt::getMinValue(BitWidth);
5415   default: llvm_unreachable("Unexpected intrinsic");
5416   }
5417 }
5418 
5419 static ICmpInst::Predicate getMaxMinPredicate(Intrinsic::ID IID) {
5420   switch (IID) {
5421   case Intrinsic::smax: return ICmpInst::ICMP_SGE;
5422   case Intrinsic::smin: return ICmpInst::ICMP_SLE;
5423   case Intrinsic::umax: return ICmpInst::ICMP_UGE;
5424   case Intrinsic::umin: return ICmpInst::ICMP_ULE;
5425   default: llvm_unreachable("Unexpected intrinsic");
5426   }
5427 }
5428 
5429 /// Given a min/max intrinsic, see if it can be removed based on having an
5430 /// operand that is another min/max intrinsic with shared operand(s). The caller
5431 /// is expected to swap the operand arguments to handle commutation.
5432 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
5433   Value *X, *Y;
5434   if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
5435     return nullptr;
5436 
5437   auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
5438   if (!MM0)
5439     return nullptr;
5440   Intrinsic::ID IID0 = MM0->getIntrinsicID();
5441 
5442   if (Op1 == X || Op1 == Y ||
5443       match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
5444     // max (max X, Y), X --> max X, Y
5445     if (IID0 == IID)
5446       return MM0;
5447     // max (min X, Y), X --> X
5448     if (IID0 == getInverseMinMaxIntrinsic(IID))
5449       return Op1;
5450   }
5451   return nullptr;
5452 }
5453 
5454 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5455                                       const SimplifyQuery &Q) {
5456   Intrinsic::ID IID = F->getIntrinsicID();
5457   Type *ReturnType = F->getReturnType();
5458   unsigned BitWidth = ReturnType->getScalarSizeInBits();
5459   switch (IID) {
5460   case Intrinsic::abs:
5461     // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
5462     // It is always ok to pick the earlier abs. We'll just lose nsw if its only
5463     // on the outer abs.
5464     if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
5465       return Op0;
5466     break;
5467 
5468   case Intrinsic::cttz: {
5469     Value *X;
5470     if (match(Op0, m_Shl(m_One(), m_Value(X))))
5471       return X;
5472     break;
5473   }
5474   case Intrinsic::ctlz: {
5475     Value *X;
5476     if (match(Op0, m_LShr(m_SignMask(), m_Value(X))))
5477       return X;
5478     break;
5479   }
5480   case Intrinsic::smax:
5481   case Intrinsic::smin:
5482   case Intrinsic::umax:
5483   case Intrinsic::umin: {
5484     // If the arguments are the same, this is a no-op.
5485     if (Op0 == Op1)
5486       return Op0;
5487 
5488     // Canonicalize constant operand as Op1.
5489     if (isa<Constant>(Op0))
5490       std::swap(Op0, Op1);
5491 
5492     // Assume undef is the limit value.
5493     if (Q.isUndefValue(Op1))
5494       return ConstantInt::get(ReturnType, getMaxMinLimit(IID, BitWidth));
5495 
5496     const APInt *C;
5497     if (match(Op1, m_APIntAllowUndef(C))) {
5498       // Clamp to limit value. For example:
5499       // umax(i8 %x, i8 255) --> 255
5500       if (*C == getMaxMinLimit(IID, BitWidth))
5501         return ConstantInt::get(ReturnType, *C);
5502 
5503       // If the constant op is the opposite of the limit value, the other must
5504       // be larger/smaller or equal. For example:
5505       // umin(i8 %x, i8 255) --> %x
5506       if (*C == getMaxMinLimit(getInverseMinMaxIntrinsic(IID), BitWidth))
5507         return Op0;
5508 
5509       // Remove nested call if constant operands allow it. Example:
5510       // max (max X, 7), 5 -> max X, 7
5511       auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
5512       if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
5513         // TODO: loosen undef/splat restrictions for vector constants.
5514         Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
5515         const APInt *InnerC;
5516         if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
5517             ((IID == Intrinsic::smax && InnerC->sge(*C)) ||
5518              (IID == Intrinsic::smin && InnerC->sle(*C)) ||
5519              (IID == Intrinsic::umax && InnerC->uge(*C)) ||
5520              (IID == Intrinsic::umin && InnerC->ule(*C))))
5521           return Op0;
5522       }
5523     }
5524 
5525     if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
5526       return V;
5527     if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
5528       return V;
5529 
5530     ICmpInst::Predicate Pred = getMaxMinPredicate(IID);
5531     if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
5532       return Op0;
5533     if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
5534       return Op1;
5535 
5536     if (Optional<bool> Imp =
5537             isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
5538       return *Imp ? Op0 : Op1;
5539     if (Optional<bool> Imp =
5540             isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
5541       return *Imp ? Op1 : Op0;
5542 
5543     break;
5544   }
5545   case Intrinsic::usub_with_overflow:
5546   case Intrinsic::ssub_with_overflow:
5547     // X - X -> { 0, false }
5548     // X - undef -> { 0, false }
5549     // undef - X -> { 0, false }
5550     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5551       return Constant::getNullValue(ReturnType);
5552     break;
5553   case Intrinsic::uadd_with_overflow:
5554   case Intrinsic::sadd_with_overflow:
5555     // X + undef -> { -1, false }
5556     // undef + x -> { -1, false }
5557     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
5558       return ConstantStruct::get(
5559           cast<StructType>(ReturnType),
5560           {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
5561            Constant::getNullValue(ReturnType->getStructElementType(1))});
5562     }
5563     break;
5564   case Intrinsic::umul_with_overflow:
5565   case Intrinsic::smul_with_overflow:
5566     // 0 * X -> { 0, false }
5567     // X * 0 -> { 0, false }
5568     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5569       return Constant::getNullValue(ReturnType);
5570     // undef * X -> { 0, false }
5571     // X * undef -> { 0, false }
5572     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5573       return Constant::getNullValue(ReturnType);
5574     break;
5575   case Intrinsic::uadd_sat:
5576     // sat(MAX + X) -> MAX
5577     // sat(X + MAX) -> MAX
5578     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5579       return Constant::getAllOnesValue(ReturnType);
5580     LLVM_FALLTHROUGH;
5581   case Intrinsic::sadd_sat:
5582     // sat(X + undef) -> -1
5583     // sat(undef + X) -> -1
5584     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5585     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5586     if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5587       return Constant::getAllOnesValue(ReturnType);
5588 
5589     // X + 0 -> X
5590     if (match(Op1, m_Zero()))
5591       return Op0;
5592     // 0 + X -> X
5593     if (match(Op0, m_Zero()))
5594       return Op1;
5595     break;
5596   case Intrinsic::usub_sat:
5597     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5598     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5599       return Constant::getNullValue(ReturnType);
5600     LLVM_FALLTHROUGH;
5601   case Intrinsic::ssub_sat:
5602     // X - X -> 0, X - undef -> 0, undef - X -> 0
5603     if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
5604       return Constant::getNullValue(ReturnType);
5605     // X - 0 -> X
5606     if (match(Op1, m_Zero()))
5607       return Op0;
5608     break;
5609   case Intrinsic::load_relative:
5610     if (auto *C0 = dyn_cast<Constant>(Op0))
5611       if (auto *C1 = dyn_cast<Constant>(Op1))
5612         return SimplifyRelativeLoad(C0, C1, Q.DL);
5613     break;
5614   case Intrinsic::powi:
5615     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5616       // powi(x, 0) -> 1.0
5617       if (Power->isZero())
5618         return ConstantFP::get(Op0->getType(), 1.0);
5619       // powi(x, 1) -> x
5620       if (Power->isOne())
5621         return Op0;
5622     }
5623     break;
5624   case Intrinsic::copysign:
5625     // copysign X, X --> X
5626     if (Op0 == Op1)
5627       return Op0;
5628     // copysign -X, X --> X
5629     // copysign X, -X --> -X
5630     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5631         match(Op1, m_FNeg(m_Specific(Op0))))
5632       return Op1;
5633     break;
5634   case Intrinsic::maxnum:
5635   case Intrinsic::minnum:
5636   case Intrinsic::maximum:
5637   case Intrinsic::minimum: {
5638     // If the arguments are the same, this is a no-op.
5639     if (Op0 == Op1) return Op0;
5640 
5641     // Canonicalize constant operand as Op1.
5642     if (isa<Constant>(Op0))
5643       std::swap(Op0, Op1);
5644 
5645     // If an argument is undef, return the other argument.
5646     if (Q.isUndefValue(Op1))
5647       return Op0;
5648 
5649     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5650     bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
5651 
5652     // minnum(X, nan) -> X
5653     // maxnum(X, nan) -> X
5654     // minimum(X, nan) -> nan
5655     // maximum(X, nan) -> nan
5656     if (match(Op1, m_NaN()))
5657       return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
5658 
5659     // In the following folds, inf can be replaced with the largest finite
5660     // float, if the ninf flag is set.
5661     const APFloat *C;
5662     if (match(Op1, m_APFloat(C)) &&
5663         (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
5664       // minnum(X, -inf) -> -inf
5665       // maxnum(X, +inf) -> +inf
5666       // minimum(X, -inf) -> -inf if nnan
5667       // maximum(X, +inf) -> +inf if nnan
5668       if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
5669         return ConstantFP::get(ReturnType, *C);
5670 
5671       // minnum(X, +inf) -> X if nnan
5672       // maxnum(X, -inf) -> X if nnan
5673       // minimum(X, +inf) -> X
5674       // maximum(X, -inf) -> X
5675       if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
5676         return Op0;
5677     }
5678 
5679     // Min/max of the same operation with common operand:
5680     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5681     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5682       if (M0->getIntrinsicID() == IID &&
5683           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5684         return Op0;
5685     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5686       if (M1->getIntrinsicID() == IID &&
5687           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5688         return Op1;
5689 
5690     break;
5691   }
5692   default:
5693     break;
5694   }
5695 
5696   return nullptr;
5697 }
5698 
5699 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5700 
5701   // Intrinsics with no operands have some kind of side effect. Don't simplify.
5702   unsigned NumOperands = Call->getNumArgOperands();
5703   if (!NumOperands)
5704     return nullptr;
5705 
5706   Function *F = cast<Function>(Call->getCalledFunction());
5707   Intrinsic::ID IID = F->getIntrinsicID();
5708   if (NumOperands == 1)
5709     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5710 
5711   if (NumOperands == 2)
5712     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5713                                    Call->getArgOperand(1), Q);
5714 
5715   // Handle intrinsics with 3 or more arguments.
5716   switch (IID) {
5717   case Intrinsic::masked_load:
5718   case Intrinsic::masked_gather: {
5719     Value *MaskArg = Call->getArgOperand(2);
5720     Value *PassthruArg = Call->getArgOperand(3);
5721     // If the mask is all zeros or undef, the "passthru" argument is the result.
5722     if (maskIsAllZeroOrUndef(MaskArg))
5723       return PassthruArg;
5724     return nullptr;
5725   }
5726   case Intrinsic::fshl:
5727   case Intrinsic::fshr: {
5728     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5729           *ShAmtArg = Call->getArgOperand(2);
5730 
5731     // If both operands are undef, the result is undef.
5732     if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
5733       return UndefValue::get(F->getReturnType());
5734 
5735     // If shift amount is undef, assume it is zero.
5736     if (Q.isUndefValue(ShAmtArg))
5737       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5738 
5739     const APInt *ShAmtC;
5740     if (match(ShAmtArg, m_APInt(ShAmtC))) {
5741       // If there's effectively no shift, return the 1st arg or 2nd arg.
5742       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5743       if (ShAmtC->urem(BitWidth).isNullValue())
5744         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5745     }
5746     return nullptr;
5747   }
5748   case Intrinsic::fma:
5749   case Intrinsic::fmuladd: {
5750     Value *Op0 = Call->getArgOperand(0);
5751     Value *Op1 = Call->getArgOperand(1);
5752     Value *Op2 = Call->getArgOperand(2);
5753     if (Value *V = simplifyFPOp({ Op0, Op1, Op2 }, {}, Q))
5754       return V;
5755     return nullptr;
5756   }
5757   case Intrinsic::smul_fix:
5758   case Intrinsic::smul_fix_sat: {
5759     Value *Op0 = Call->getArgOperand(0);
5760     Value *Op1 = Call->getArgOperand(1);
5761     Value *Op2 = Call->getArgOperand(2);
5762     Type *ReturnType = F->getReturnType();
5763 
5764     // Canonicalize constant operand as Op1 (ConstantFolding handles the case
5765     // when both Op0 and Op1 are constant so we do not care about that special
5766     // case here).
5767     if (isa<Constant>(Op0))
5768       std::swap(Op0, Op1);
5769 
5770     // X * 0 -> 0
5771     if (match(Op1, m_Zero()))
5772       return Constant::getNullValue(ReturnType);
5773 
5774     // X * undef -> 0
5775     if (Q.isUndefValue(Op1))
5776       return Constant::getNullValue(ReturnType);
5777 
5778     // X * (1 << Scale) -> X
5779     APInt ScaledOne =
5780         APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
5781                             cast<ConstantInt>(Op2)->getZExtValue());
5782     if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
5783       return Op0;
5784 
5785     return nullptr;
5786   }
5787   default:
5788     return nullptr;
5789   }
5790 }
5791 
5792 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
5793   auto *F = dyn_cast<Function>(Call->getCalledOperand());
5794   if (!F || !canConstantFoldCallTo(Call, F))
5795     return nullptr;
5796 
5797   SmallVector<Constant *, 4> ConstantArgs;
5798   unsigned NumArgs = Call->getNumArgOperands();
5799   ConstantArgs.reserve(NumArgs);
5800   for (auto &Arg : Call->args()) {
5801     Constant *C = dyn_cast<Constant>(&Arg);
5802     if (!C) {
5803       if (isa<MetadataAsValue>(Arg.get()))
5804         continue;
5805       return nullptr;
5806     }
5807     ConstantArgs.push_back(C);
5808   }
5809 
5810   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5811 }
5812 
5813 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5814   // musttail calls can only be simplified if they are also DCEd.
5815   // As we can't guarantee this here, don't simplify them.
5816   if (Call->isMustTailCall())
5817     return nullptr;
5818 
5819   // call undef -> poison
5820   // call null -> poison
5821   Value *Callee = Call->getCalledOperand();
5822   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
5823     return PoisonValue::get(Call->getType());
5824 
5825   if (Value *V = tryConstantFoldCall(Call, Q))
5826     return V;
5827 
5828   auto *F = dyn_cast<Function>(Callee);
5829   if (F && F->isIntrinsic())
5830     if (Value *Ret = simplifyIntrinsic(Call, Q))
5831       return Ret;
5832 
5833   return nullptr;
5834 }
5835 
5836 /// Given operands for a Freeze, see if we can fold the result.
5837 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5838   // Use a utility function defined in ValueTracking.
5839   if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
5840     return Op0;
5841   // We have room for improvement.
5842   return nullptr;
5843 }
5844 
5845 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
5846   return ::SimplifyFreezeInst(Op0, Q);
5847 }
5848 
5849 /// See if we can compute a simplified version of this instruction.
5850 /// If not, this returns null.
5851 
5852 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5853                                  OptimizationRemarkEmitter *ORE) {
5854   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5855   Value *Result;
5856 
5857   switch (I->getOpcode()) {
5858   default:
5859     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5860     break;
5861   case Instruction::FNeg:
5862     Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5863     break;
5864   case Instruction::FAdd:
5865     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5866                               I->getFastMathFlags(), Q);
5867     break;
5868   case Instruction::Add:
5869     Result =
5870         SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5871                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5872                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5873     break;
5874   case Instruction::FSub:
5875     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5876                               I->getFastMathFlags(), Q);
5877     break;
5878   case Instruction::Sub:
5879     Result =
5880         SimplifySubInst(I->getOperand(0), I->getOperand(1),
5881                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5882                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5883     break;
5884   case Instruction::FMul:
5885     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5886                               I->getFastMathFlags(), Q);
5887     break;
5888   case Instruction::Mul:
5889     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5890     break;
5891   case Instruction::SDiv:
5892     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5893     break;
5894   case Instruction::UDiv:
5895     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5896     break;
5897   case Instruction::FDiv:
5898     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5899                               I->getFastMathFlags(), Q);
5900     break;
5901   case Instruction::SRem:
5902     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5903     break;
5904   case Instruction::URem:
5905     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5906     break;
5907   case Instruction::FRem:
5908     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5909                               I->getFastMathFlags(), Q);
5910     break;
5911   case Instruction::Shl:
5912     Result =
5913         SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5914                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5915                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5916     break;
5917   case Instruction::LShr:
5918     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5919                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5920     break;
5921   case Instruction::AShr:
5922     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5923                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5924     break;
5925   case Instruction::And:
5926     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5927     break;
5928   case Instruction::Or:
5929     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5930     break;
5931   case Instruction::Xor:
5932     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5933     break;
5934   case Instruction::ICmp:
5935     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5936                               I->getOperand(0), I->getOperand(1), Q);
5937     break;
5938   case Instruction::FCmp:
5939     Result =
5940         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5941                          I->getOperand(1), I->getFastMathFlags(), Q);
5942     break;
5943   case Instruction::Select:
5944     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5945                                 I->getOperand(2), Q);
5946     break;
5947   case Instruction::GetElementPtr: {
5948     SmallVector<Value *, 8> Ops(I->operands());
5949     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5950                              Ops, Q);
5951     break;
5952   }
5953   case Instruction::InsertValue: {
5954     InsertValueInst *IV = cast<InsertValueInst>(I);
5955     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5956                                      IV->getInsertedValueOperand(),
5957                                      IV->getIndices(), Q);
5958     break;
5959   }
5960   case Instruction::InsertElement: {
5961     auto *IE = cast<InsertElementInst>(I);
5962     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5963                                        IE->getOperand(2), Q);
5964     break;
5965   }
5966   case Instruction::ExtractValue: {
5967     auto *EVI = cast<ExtractValueInst>(I);
5968     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5969                                       EVI->getIndices(), Q);
5970     break;
5971   }
5972   case Instruction::ExtractElement: {
5973     auto *EEI = cast<ExtractElementInst>(I);
5974     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5975                                         EEI->getIndexOperand(), Q);
5976     break;
5977   }
5978   case Instruction::ShuffleVector: {
5979     auto *SVI = cast<ShuffleVectorInst>(I);
5980     Result =
5981         SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5982                                   SVI->getShuffleMask(), SVI->getType(), Q);
5983     break;
5984   }
5985   case Instruction::PHI:
5986     Result = SimplifyPHINode(cast<PHINode>(I), Q);
5987     break;
5988   case Instruction::Call: {
5989     Result = SimplifyCall(cast<CallInst>(I), Q);
5990     break;
5991   }
5992   case Instruction::Freeze:
5993     Result = SimplifyFreezeInst(I->getOperand(0), Q);
5994     break;
5995 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5996 #include "llvm/IR/Instruction.def"
5997 #undef HANDLE_CAST_INST
5998     Result =
5999         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
6000     break;
6001   case Instruction::Alloca:
6002     // No simplifications for Alloca and it can't be constant folded.
6003     Result = nullptr;
6004     break;
6005   }
6006 
6007   /// If called on unreachable code, the above logic may report that the
6008   /// instruction simplified to itself.  Make life easier for users by
6009   /// detecting that case here, returning a safe value instead.
6010   return Result == I ? UndefValue::get(I->getType()) : Result;
6011 }
6012 
6013 /// Implementation of recursive simplification through an instruction's
6014 /// uses.
6015 ///
6016 /// This is the common implementation of the recursive simplification routines.
6017 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
6018 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
6019 /// instructions to process and attempt to simplify it using
6020 /// InstructionSimplify. Recursively visited users which could not be
6021 /// simplified themselves are to the optional UnsimplifiedUsers set for
6022 /// further processing by the caller.
6023 ///
6024 /// This routine returns 'true' only when *it* simplifies something. The passed
6025 /// in simplified value does not count toward this.
6026 static bool replaceAndRecursivelySimplifyImpl(
6027     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6028     const DominatorTree *DT, AssumptionCache *AC,
6029     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
6030   bool Simplified = false;
6031   SmallSetVector<Instruction *, 8> Worklist;
6032   const DataLayout &DL = I->getModule()->getDataLayout();
6033 
6034   // If we have an explicit value to collapse to, do that round of the
6035   // simplification loop by hand initially.
6036   if (SimpleV) {
6037     for (User *U : I->users())
6038       if (U != I)
6039         Worklist.insert(cast<Instruction>(U));
6040 
6041     // Replace the instruction with its simplified value.
6042     I->replaceAllUsesWith(SimpleV);
6043 
6044     // Gracefully handle edge cases where the instruction is not wired into any
6045     // parent block.
6046     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6047         !I->mayHaveSideEffects())
6048       I->eraseFromParent();
6049   } else {
6050     Worklist.insert(I);
6051   }
6052 
6053   // Note that we must test the size on each iteration, the worklist can grow.
6054   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
6055     I = Worklist[Idx];
6056 
6057     // See if this instruction simplifies.
6058     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
6059     if (!SimpleV) {
6060       if (UnsimplifiedUsers)
6061         UnsimplifiedUsers->insert(I);
6062       continue;
6063     }
6064 
6065     Simplified = true;
6066 
6067     // Stash away all the uses of the old instruction so we can check them for
6068     // recursive simplifications after a RAUW. This is cheaper than checking all
6069     // uses of To on the recursive step in most cases.
6070     for (User *U : I->users())
6071       Worklist.insert(cast<Instruction>(U));
6072 
6073     // Replace the instruction with its simplified value.
6074     I->replaceAllUsesWith(SimpleV);
6075 
6076     // Gracefully handle edge cases where the instruction is not wired into any
6077     // parent block.
6078     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
6079         !I->mayHaveSideEffects())
6080       I->eraseFromParent();
6081   }
6082   return Simplified;
6083 }
6084 
6085 bool llvm::replaceAndRecursivelySimplify(
6086     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
6087     const DominatorTree *DT, AssumptionCache *AC,
6088     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
6089   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
6090   assert(SimpleV && "Must provide a simplified value.");
6091   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
6092                                            UnsimplifiedUsers);
6093 }
6094 
6095 namespace llvm {
6096 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
6097   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
6098   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
6099   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
6100   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
6101   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
6102   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
6103   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6104 }
6105 
6106 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
6107                                          const DataLayout &DL) {
6108   return {DL, &AR.TLI, &AR.DT, &AR.AC};
6109 }
6110 
6111 template <class T, class... TArgs>
6112 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
6113                                          Function &F) {
6114   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
6115   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
6116   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
6117   return {F.getParent()->getDataLayout(), TLI, DT, AC};
6118 }
6119 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
6120                                                   Function &);
6121 }
6122