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