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