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