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