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