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