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