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