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