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