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