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