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