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