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