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