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