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