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