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