InstSimplify: Fold a hasNoUnsignedWrap() call into a match() expression
[oota-llvm.git] / lib / Analysis / InstructionSimplify.cpp
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/ConstantFolding.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
34 using namespace llvm;
35 using namespace llvm::PatternMatch;
36
37 #define DEBUG_TYPE "instsimplify"
38
39 enum { RecursionLimit = 3 };
40
41 STATISTIC(NumExpand,  "Number of expansions");
42 STATISTIC(NumReassoc, "Number of reassociations");
43
44 namespace {
45 struct Query {
46   const DataLayout *DL;
47   const TargetLibraryInfo *TLI;
48   const DominatorTree *DT;
49   AssumptionTracker *AT;
50   const Instruction *CxtI;
51
52   Query(const DataLayout *DL, const TargetLibraryInfo *tli,
53         const DominatorTree *dt, AssumptionTracker *at = nullptr,
54         const Instruction *cxti = nullptr)
55     : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
56 };
57 } // end anonymous namespace
58
59 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
60 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
61                             unsigned);
62 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
63                               unsigned);
64 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
65 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
66 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
67
68 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
69 /// a vector with every element false, as appropriate for the type.
70 static Constant *getFalse(Type *Ty) {
71   assert(Ty->getScalarType()->isIntegerTy(1) &&
72          "Expected i1 type or a vector of i1!");
73   return Constant::getNullValue(Ty);
74 }
75
76 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
77 /// a vector with every element true, as appropriate for the type.
78 static Constant *getTrue(Type *Ty) {
79   assert(Ty->getScalarType()->isIntegerTy(1) &&
80          "Expected i1 type or a vector of i1!");
81   return Constant::getAllOnesValue(Ty);
82 }
83
84 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
85 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
86                           Value *RHS) {
87   CmpInst *Cmp = dyn_cast<CmpInst>(V);
88   if (!Cmp)
89     return false;
90   CmpInst::Predicate CPred = Cmp->getPredicate();
91   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
92   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
93     return true;
94   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
95     CRHS == LHS;
96 }
97
98 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
99 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
100   Instruction *I = dyn_cast<Instruction>(V);
101   if (!I)
102     // Arguments and constants dominate all instructions.
103     return true;
104
105   // If we are processing instructions (and/or basic blocks) that have not been
106   // fully added to a function, the parent nodes may still be null. Simply
107   // return the conservative answer in these cases.
108   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
109     return false;
110
111   // If we have a DominatorTree then do a precise test.
112   if (DT) {
113     if (!DT->isReachableFromEntry(P->getParent()))
114       return true;
115     if (!DT->isReachableFromEntry(I->getParent()))
116       return false;
117     return DT->dominates(I, P);
118   }
119
120   // Otherwise, if the instruction is in the entry block, and is not an invoke,
121   // then it obviously dominates all phi nodes.
122   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
123       !isa<InvokeInst>(I))
124     return true;
125
126   return false;
127 }
128
129 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
130 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
131 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
132 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
133 /// Returns the simplified value, or null if no simplification was performed.
134 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
135                           unsigned OpcToExpand, const Query &Q,
136                           unsigned MaxRecurse) {
137   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
138   // Recursion is always used, so bail out at once if we already hit the limit.
139   if (!MaxRecurse--)
140     return nullptr;
141
142   // Check whether the expression has the form "(A op' B) op C".
143   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
144     if (Op0->getOpcode() == OpcodeToExpand) {
145       // It does!  Try turning it into "(A op C) op' (B op C)".
146       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
147       // Do "A op C" and "B op C" both simplify?
148       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
149         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
150           // They do! Return "L op' R" if it simplifies or is already available.
151           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
152           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
153                                      && L == B && R == A)) {
154             ++NumExpand;
155             return LHS;
156           }
157           // Otherwise return "L op' R" if it simplifies.
158           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
159             ++NumExpand;
160             return V;
161           }
162         }
163     }
164
165   // Check whether the expression has the form "A op (B op' C)".
166   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
167     if (Op1->getOpcode() == OpcodeToExpand) {
168       // It does!  Try turning it into "(A op B) op' (A op C)".
169       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
170       // Do "A op B" and "A op C" both simplify?
171       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
172         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
173           // They do! Return "L op' R" if it simplifies or is already available.
174           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
175           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
176                                      && L == C && R == B)) {
177             ++NumExpand;
178             return RHS;
179           }
180           // Otherwise return "L op' R" if it simplifies.
181           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
182             ++NumExpand;
183             return V;
184           }
185         }
186     }
187
188   return nullptr;
189 }
190
191 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
192 /// operations.  Returns the simpler value, or null if none was found.
193 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
194                                        const Query &Q, unsigned MaxRecurse) {
195   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
196   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
197
198   // Recursion is always used, so bail out at once if we already hit the limit.
199   if (!MaxRecurse--)
200     return nullptr;
201
202   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
203   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
204
205   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
206   if (Op0 && Op0->getOpcode() == Opcode) {
207     Value *A = Op0->getOperand(0);
208     Value *B = Op0->getOperand(1);
209     Value *C = RHS;
210
211     // Does "B op C" simplify?
212     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
213       // It does!  Return "A op V" if it simplifies or is already available.
214       // If V equals B then "A op V" is just the LHS.
215       if (V == B) return LHS;
216       // Otherwise return "A op V" if it simplifies.
217       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
218         ++NumReassoc;
219         return W;
220       }
221     }
222   }
223
224   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
225   if (Op1 && Op1->getOpcode() == Opcode) {
226     Value *A = LHS;
227     Value *B = Op1->getOperand(0);
228     Value *C = Op1->getOperand(1);
229
230     // Does "A op B" simplify?
231     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
232       // It does!  Return "V op C" if it simplifies or is already available.
233       // If V equals B then "V op C" is just the RHS.
234       if (V == B) return RHS;
235       // Otherwise return "V op C" if it simplifies.
236       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
237         ++NumReassoc;
238         return W;
239       }
240     }
241   }
242
243   // The remaining transforms require commutativity as well as associativity.
244   if (!Instruction::isCommutative(Opcode))
245     return nullptr;
246
247   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
248   if (Op0 && Op0->getOpcode() == Opcode) {
249     Value *A = Op0->getOperand(0);
250     Value *B = Op0->getOperand(1);
251     Value *C = RHS;
252
253     // Does "C op A" simplify?
254     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
255       // It does!  Return "V op B" if it simplifies or is already available.
256       // If V equals A then "V op B" is just the LHS.
257       if (V == A) return LHS;
258       // Otherwise return "V op B" if it simplifies.
259       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
260         ++NumReassoc;
261         return W;
262       }
263     }
264   }
265
266   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
267   if (Op1 && Op1->getOpcode() == Opcode) {
268     Value *A = LHS;
269     Value *B = Op1->getOperand(0);
270     Value *C = Op1->getOperand(1);
271
272     // Does "C op A" simplify?
273     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
274       // It does!  Return "B op V" if it simplifies or is already available.
275       // If V equals C then "B op V" is just the RHS.
276       if (V == C) return RHS;
277       // Otherwise return "B op V" if it simplifies.
278       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
279         ++NumReassoc;
280         return W;
281       }
282     }
283   }
284
285   return nullptr;
286 }
287
288 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
289 /// instruction as an operand, try to simplify the binop by seeing whether
290 /// evaluating it on both branches of the select results in the same value.
291 /// Returns the common value if so, otherwise returns null.
292 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
293                                     const Query &Q, unsigned MaxRecurse) {
294   // Recursion is always used, so bail out at once if we already hit the limit.
295   if (!MaxRecurse--)
296     return nullptr;
297
298   SelectInst *SI;
299   if (isa<SelectInst>(LHS)) {
300     SI = cast<SelectInst>(LHS);
301   } else {
302     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
303     SI = cast<SelectInst>(RHS);
304   }
305
306   // Evaluate the BinOp on the true and false branches of the select.
307   Value *TV;
308   Value *FV;
309   if (SI == LHS) {
310     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
311     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
312   } else {
313     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
314     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
315   }
316
317   // If they simplified to the same value, then return the common value.
318   // If they both failed to simplify then return null.
319   if (TV == FV)
320     return TV;
321
322   // If one branch simplified to undef, return the other one.
323   if (TV && isa<UndefValue>(TV))
324     return FV;
325   if (FV && isa<UndefValue>(FV))
326     return TV;
327
328   // If applying the operation did not change the true and false select values,
329   // then the result of the binop is the select itself.
330   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
331     return SI;
332
333   // If one branch simplified and the other did not, and the simplified
334   // value is equal to the unsimplified one, return the simplified value.
335   // For example, select (cond, X, X & Z) & Z -> X & Z.
336   if ((FV && !TV) || (TV && !FV)) {
337     // Check that the simplified value has the form "X op Y" where "op" is the
338     // same as the original operation.
339     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
340     if (Simplified && Simplified->getOpcode() == Opcode) {
341       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
342       // We already know that "op" is the same as for the simplified value.  See
343       // if the operands match too.  If so, return the simplified value.
344       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
345       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
346       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
347       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
348           Simplified->getOperand(1) == UnsimplifiedRHS)
349         return Simplified;
350       if (Simplified->isCommutative() &&
351           Simplified->getOperand(1) == UnsimplifiedLHS &&
352           Simplified->getOperand(0) == UnsimplifiedRHS)
353         return Simplified;
354     }
355   }
356
357   return nullptr;
358 }
359
360 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
361 /// try to simplify the comparison by seeing whether both branches of the select
362 /// result in the same value.  Returns the common value if so, otherwise returns
363 /// null.
364 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
365                                   Value *RHS, const Query &Q,
366                                   unsigned MaxRecurse) {
367   // Recursion is always used, so bail out at once if we already hit the limit.
368   if (!MaxRecurse--)
369     return nullptr;
370
371   // Make sure the select is on the LHS.
372   if (!isa<SelectInst>(LHS)) {
373     std::swap(LHS, RHS);
374     Pred = CmpInst::getSwappedPredicate(Pred);
375   }
376   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
377   SelectInst *SI = cast<SelectInst>(LHS);
378   Value *Cond = SI->getCondition();
379   Value *TV = SI->getTrueValue();
380   Value *FV = SI->getFalseValue();
381
382   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
383   // Does "cmp TV, RHS" simplify?
384   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
385   if (TCmp == Cond) {
386     // It not only simplified, it simplified to the select condition.  Replace
387     // it with 'true'.
388     TCmp = getTrue(Cond->getType());
389   } else if (!TCmp) {
390     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
391     // condition then we can replace it with 'true'.  Otherwise give up.
392     if (!isSameCompare(Cond, Pred, TV, RHS))
393       return nullptr;
394     TCmp = getTrue(Cond->getType());
395   }
396
397   // Does "cmp FV, RHS" simplify?
398   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
399   if (FCmp == Cond) {
400     // It not only simplified, it simplified to the select condition.  Replace
401     // it with 'false'.
402     FCmp = getFalse(Cond->getType());
403   } else if (!FCmp) {
404     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
405     // condition then we can replace it with 'false'.  Otherwise give up.
406     if (!isSameCompare(Cond, Pred, FV, RHS))
407       return nullptr;
408     FCmp = getFalse(Cond->getType());
409   }
410
411   // If both sides simplified to the same value, then use it as the result of
412   // the original comparison.
413   if (TCmp == FCmp)
414     return TCmp;
415
416   // The remaining cases only make sense if the select condition has the same
417   // type as the result of the comparison, so bail out if this is not so.
418   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
419     return nullptr;
420   // If the false value simplified to false, then the result of the compare
421   // is equal to "Cond && TCmp".  This also catches the case when the false
422   // value simplified to false and the true value to true, returning "Cond".
423   if (match(FCmp, m_Zero()))
424     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
425       return V;
426   // If the true value simplified to true, then the result of the compare
427   // is equal to "Cond || FCmp".
428   if (match(TCmp, m_One()))
429     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
430       return V;
431   // Finally, if the false value simplified to true and the true value to
432   // false, then the result of the compare is equal to "!Cond".
433   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
434     if (Value *V =
435         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
436                         Q, MaxRecurse))
437       return V;
438
439   return nullptr;
440 }
441
442 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
443 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
444 /// it on the incoming phi values yields the same result for every value.  If so
445 /// returns the common value, otherwise returns null.
446 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
447                                  const Query &Q, unsigned MaxRecurse) {
448   // Recursion is always used, so bail out at once if we already hit the limit.
449   if (!MaxRecurse--)
450     return nullptr;
451
452   PHINode *PI;
453   if (isa<PHINode>(LHS)) {
454     PI = cast<PHINode>(LHS);
455     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
456     if (!ValueDominatesPHI(RHS, PI, Q.DT))
457       return nullptr;
458   } else {
459     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
460     PI = cast<PHINode>(RHS);
461     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
462     if (!ValueDominatesPHI(LHS, PI, Q.DT))
463       return nullptr;
464   }
465
466   // Evaluate the BinOp on the incoming phi values.
467   Value *CommonValue = nullptr;
468   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
469     Value *Incoming = PI->getIncomingValue(i);
470     // If the incoming value is the phi node itself, it can safely be skipped.
471     if (Incoming == PI) continue;
472     Value *V = PI == LHS ?
473       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
474       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
475     // If the operation failed to simplify, or simplified to a different value
476     // to previously, then give up.
477     if (!V || (CommonValue && V != CommonValue))
478       return nullptr;
479     CommonValue = V;
480   }
481
482   return CommonValue;
483 }
484
485 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
486 /// try to simplify the comparison by seeing whether comparing with all of the
487 /// incoming phi values yields the same result every time.  If so returns the
488 /// common result, otherwise returns null.
489 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
490                                const Query &Q, unsigned MaxRecurse) {
491   // Recursion is always used, so bail out at once if we already hit the limit.
492   if (!MaxRecurse--)
493     return nullptr;
494
495   // Make sure the phi is on the LHS.
496   if (!isa<PHINode>(LHS)) {
497     std::swap(LHS, RHS);
498     Pred = CmpInst::getSwappedPredicate(Pred);
499   }
500   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
501   PHINode *PI = cast<PHINode>(LHS);
502
503   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
504   if (!ValueDominatesPHI(RHS, PI, Q.DT))
505     return nullptr;
506
507   // Evaluate the BinOp on the incoming phi values.
508   Value *CommonValue = nullptr;
509   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
510     Value *Incoming = PI->getIncomingValue(i);
511     // If the incoming value is the phi node itself, it can safely be skipped.
512     if (Incoming == PI) continue;
513     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
514     // If the operation failed to simplify, or simplified to a different value
515     // to previously, then give up.
516     if (!V || (CommonValue && V != CommonValue))
517       return nullptr;
518     CommonValue = V;
519   }
520
521   return CommonValue;
522 }
523
524 /// SimplifyAddInst - Given operands for an Add, see if we can
525 /// fold the result.  If not, this returns null.
526 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
527                               const Query &Q, unsigned MaxRecurse) {
528   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
529     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
530       Constant *Ops[] = { CLHS, CRHS };
531       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
532                                       Q.DL, Q.TLI);
533     }
534
535     // Canonicalize the constant to the RHS.
536     std::swap(Op0, Op1);
537   }
538
539   // X + undef -> undef
540   if (match(Op1, m_Undef()))
541     return Op1;
542
543   // X + 0 -> X
544   if (match(Op1, m_Zero()))
545     return Op0;
546
547   // X + (Y - X) -> Y
548   // (Y - X) + X -> Y
549   // Eg: X + -X -> 0
550   Value *Y = nullptr;
551   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
553     return Y;
554
555   // X + ~X -> -1   since   ~X = -X-1
556   if (match(Op0, m_Not(m_Specific(Op1))) ||
557       match(Op1, m_Not(m_Specific(Op0))))
558     return Constant::getAllOnesValue(Op0->getType());
559
560   /// i1 add -> xor.
561   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
562     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
563       return V;
564
565   // Try some generic simplifications for associative operations.
566   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
567                                           MaxRecurse))
568     return V;
569
570   // Threading Add over selects and phi nodes is pointless, so don't bother.
571   // Threading over the select in "A + select(cond, B, C)" means evaluating
572   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573   // only if B and C are equal.  If B and C are equal then (since we assume
574   // that operands have already been simplified) "select(cond, B, C)" should
575   // have been simplified to the common value of B and C already.  Analysing
576   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
577   // for threading over phi nodes.
578
579   return nullptr;
580 }
581
582 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
583                              const DataLayout *DL, const TargetLibraryInfo *TLI,
584                              const DominatorTree *DT, AssumptionTracker *AT,
585                              const Instruction *CxtI) {
586   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
587                            Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
588 }
589
590 /// \brief Compute the base pointer and cumulative constant offsets for V.
591 ///
592 /// This strips all constant offsets off of V, leaving it the base pointer, and
593 /// accumulates the total constant offset applied in the returned constant. It
594 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
595 /// no constant offsets applied.
596 ///
597 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599 /// folding.
600 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
601                                                 Value *&V,
602                                                 bool AllowNonInbounds = false) {
603   assert(V->getType()->getScalarType()->isPointerTy());
604
605   // Without DataLayout, just be conservative for now. Theoretically, more could
606   // be done in this case.
607   if (!DL)
608     return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
609
610   Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
611   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
612
613   // Even though we don't look through PHI nodes, we could be called on an
614   // instruction in an unreachable block, which may be on a cycle.
615   SmallPtrSet<Value *, 4> Visited;
616   Visited.insert(V);
617   do {
618     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
619       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
620           !GEP->accumulateConstantOffset(*DL, Offset))
621         break;
622       V = GEP->getPointerOperand();
623     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
624       V = cast<Operator>(V)->getOperand(0);
625     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
626       if (GA->mayBeOverridden())
627         break;
628       V = GA->getAliasee();
629     } else {
630       break;
631     }
632     assert(V->getType()->getScalarType()->isPointerTy() &&
633            "Unexpected operand type!");
634   } while (Visited.insert(V));
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,
646                                           Value *LHS, 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 /// SimplifySubInst - Given operands for a Sub, see if we can
663 /// fold the result.  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       Constant *Ops[] = { CLHS, CRHS };
669       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
670                                       Ops, Q.DL, Q.TLI);
671     }
672
673   // X - undef -> undef
674   // undef - X -> undef
675   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
676     return UndefValue::get(Op0->getType());
677
678   // X - 0 -> X
679   if (match(Op1, m_Zero()))
680     return Op0;
681
682   // X - X -> 0
683   if (Op0 == Op1)
684     return Constant::getNullValue(Op0->getType());
685
686   // X - (0 - Y) -> X if the second sub is NUW.
687   // If Y != 0, 0 - Y is a poison value.
688   // If Y == 0, 0 - Y simplifies to 0.
689   if (BinaryOperator::isNeg(Op1)) {
690     if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
691       assert(BO->getOpcode() == Instruction::Sub &&
692              "Expected a subtraction operator!");
693       if (BO->hasNoUnsignedWrap())
694         return Op0;
695     }
696   }
697
698   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
699   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
700   Value *X = nullptr, *Y = nullptr, *Z = Op1;
701   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
702     // See if "V === Y - Z" simplifies.
703     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
704       // It does!  Now see if "X + V" simplifies.
705       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
706         // It does, we successfully reassociated!
707         ++NumReassoc;
708         return W;
709       }
710     // See if "V === X - Z" simplifies.
711     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
712       // It does!  Now see if "Y + V" simplifies.
713       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
714         // It does, we successfully reassociated!
715         ++NumReassoc;
716         return W;
717       }
718   }
719
720   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
721   // For example, X - (X + 1) -> -1
722   X = Op0;
723   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
724     // See if "V === X - Y" simplifies.
725     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
726       // It does!  Now see if "V - Z" simplifies.
727       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
728         // It does, we successfully reassociated!
729         ++NumReassoc;
730         return W;
731       }
732     // See if "V === X - Z" simplifies.
733     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
734       // It does!  Now see if "V - Y" simplifies.
735       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
736         // It does, we successfully reassociated!
737         ++NumReassoc;
738         return W;
739       }
740   }
741
742   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
743   // For example, X - (X - Y) -> Y.
744   Z = Op0;
745   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
746     // See if "V === Z - X" simplifies.
747     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
748       // It does!  Now see if "V + Y" simplifies.
749       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
750         // It does, we successfully reassociated!
751         ++NumReassoc;
752         return W;
753       }
754
755   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
756   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
757       match(Op1, m_Trunc(m_Value(Y))))
758     if (X->getType() == Y->getType())
759       // See if "V === X - Y" simplifies.
760       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
761         // It does!  Now see if "trunc V" simplifies.
762         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
763           // It does, return the simplified "trunc V".
764           return W;
765
766   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
767   if (match(Op0, m_PtrToInt(m_Value(X))) &&
768       match(Op1, m_PtrToInt(m_Value(Y))))
769     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
770       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
771
772   // i1 sub -> xor.
773   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
774     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
775       return V;
776
777   // Threading Sub over selects and phi nodes is pointless, so don't bother.
778   // Threading over the select in "A - select(cond, B, C)" means evaluating
779   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
780   // only if B and C are equal.  If B and C are equal then (since we assume
781   // that operands have already been simplified) "select(cond, B, C)" should
782   // have been simplified to the common value of B and C already.  Analysing
783   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
784   // for threading over phi nodes.
785
786   return nullptr;
787 }
788
789 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
790                              const DataLayout *DL, const TargetLibraryInfo *TLI,
791                              const DominatorTree *DT, AssumptionTracker *AT,
792                              const Instruction *CxtI) {
793   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
794                            Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
795 }
796
797 /// Given operands for an FAdd, see if we can fold the result.  If not, this
798 /// returns null.
799 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
800                               const Query &Q, unsigned MaxRecurse) {
801   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
802     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
803       Constant *Ops[] = { CLHS, CRHS };
804       return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
805                                       Ops, Q.DL, Q.TLI);
806     }
807
808     // Canonicalize the constant to the RHS.
809     std::swap(Op0, Op1);
810   }
811
812   // fadd X, -0 ==> X
813   if (match(Op1, m_NegZero()))
814     return Op0;
815
816   // fadd X, 0 ==> X, when we know X is not -0
817   if (match(Op1, m_Zero()) &&
818       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
819     return Op0;
820
821   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
822   //   where nnan and ninf have to occur at least once somewhere in this
823   //   expression
824   Value *SubOp = nullptr;
825   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
826     SubOp = Op1;
827   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
828     SubOp = Op0;
829   if (SubOp) {
830     Instruction *FSub = cast<Instruction>(SubOp);
831     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
832         (FMF.noInfs() || FSub->hasNoInfs()))
833       return Constant::getNullValue(Op0->getType());
834   }
835
836   return nullptr;
837 }
838
839 /// Given operands for an FSub, see if we can fold the result.  If not, this
840 /// returns null.
841 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
842                               const Query &Q, unsigned MaxRecurse) {
843   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
844     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
845       Constant *Ops[] = { CLHS, CRHS };
846       return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
847                                       Ops, Q.DL, Q.TLI);
848     }
849   }
850
851   // fsub X, 0 ==> X
852   if (match(Op1, m_Zero()))
853     return Op0;
854
855   // fsub X, -0 ==> X, when we know X is not -0
856   if (match(Op1, m_NegZero()) &&
857       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
858     return Op0;
859
860   // fsub 0, (fsub -0.0, X) ==> X
861   Value *X;
862   if (match(Op0, m_AnyZero())) {
863     if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
864       return X;
865     if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
866       return X;
867   }
868
869   // fsub nnan ninf x, x ==> 0.0
870   if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
871     return Constant::getNullValue(Op0->getType());
872
873   return nullptr;
874 }
875
876 /// Given the operands for an FMul, see if we can fold the result
877 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
878                                FastMathFlags FMF,
879                                const Query &Q,
880                                unsigned MaxRecurse) {
881  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
882     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
883       Constant *Ops[] = { CLHS, CRHS };
884       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
885                                       Ops, Q.DL, Q.TLI);
886     }
887
888     // Canonicalize the constant to the RHS.
889     std::swap(Op0, Op1);
890  }
891
892  // fmul X, 1.0 ==> X
893  if (match(Op1, m_FPOne()))
894    return Op0;
895
896  // fmul nnan nsz X, 0 ==> 0
897  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
898    return Op1;
899
900  return nullptr;
901 }
902
903 /// SimplifyMulInst - Given operands for a Mul, see if we can
904 /// fold the result.  If not, this returns null.
905 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
906                               unsigned MaxRecurse) {
907   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
908     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
909       Constant *Ops[] = { CLHS, CRHS };
910       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
911                                       Ops, Q.DL, Q.TLI);
912     }
913
914     // Canonicalize the constant to the RHS.
915     std::swap(Op0, Op1);
916   }
917
918   // X * undef -> 0
919   if (match(Op1, m_Undef()))
920     return Constant::getNullValue(Op0->getType());
921
922   // X * 0 -> 0
923   if (match(Op1, m_Zero()))
924     return Op1;
925
926   // X * 1 -> X
927   if (match(Op1, m_One()))
928     return Op0;
929
930   // (X / Y) * Y -> X if the division is exact.
931   Value *X = nullptr;
932   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
933       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
934     return X;
935
936   // i1 mul -> and.
937   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
938     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
939       return V;
940
941   // Try some generic simplifications for associative operations.
942   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
943                                           MaxRecurse))
944     return V;
945
946   // Mul distributes over Add.  Try some generic simplifications based on this.
947   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
948                              Q, MaxRecurse))
949     return V;
950
951   // If the operation is with the result of a select instruction, check whether
952   // operating on either branch of the select always yields the same value.
953   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
954     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
955                                          MaxRecurse))
956       return V;
957
958   // If the operation is with the result of a phi instruction, check whether
959   // operating on all incoming values of the phi always yields the same value.
960   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
961     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
962                                       MaxRecurse))
963       return V;
964
965   return nullptr;
966 }
967
968 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
969                              const DataLayout *DL, const TargetLibraryInfo *TLI,
970                              const DominatorTree *DT, AssumptionTracker *AT,
971                              const Instruction *CxtI) {
972   return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
973                             RecursionLimit);
974 }
975
976 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
977                              const DataLayout *DL, const TargetLibraryInfo *TLI,
978                              const DominatorTree *DT, AssumptionTracker *AT,
979                              const Instruction *CxtI) {
980   return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
981                             RecursionLimit);
982 }
983
984 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
985                               FastMathFlags FMF,
986                               const DataLayout *DL,
987                               const TargetLibraryInfo *TLI,
988                               const DominatorTree *DT,
989                               AssumptionTracker *AT,
990                               const Instruction *CxtI) {
991   return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
992                             RecursionLimit);
993 }
994
995 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
996                              const TargetLibraryInfo *TLI,
997                              const DominatorTree *DT, AssumptionTracker *AT,
998                              const Instruction *CxtI) {
999   return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1000                            RecursionLimit);
1001 }
1002
1003 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1004 /// fold the result.  If not, this returns null.
1005 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1006                           const Query &Q, unsigned MaxRecurse) {
1007   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1008     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1009       Constant *Ops[] = { C0, C1 };
1010       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1011     }
1012   }
1013
1014   bool isSigned = Opcode == Instruction::SDiv;
1015
1016   // X / undef -> undef
1017   if (match(Op1, m_Undef()))
1018     return Op1;
1019
1020   // undef / X -> 0
1021   if (match(Op0, m_Undef()))
1022     return Constant::getNullValue(Op0->getType());
1023
1024   // 0 / X -> 0, we don't need to preserve faults!
1025   if (match(Op0, m_Zero()))
1026     return Op0;
1027
1028   // X / 1 -> X
1029   if (match(Op1, m_One()))
1030     return Op0;
1031
1032   if (Op0->getType()->isIntegerTy(1))
1033     // It can't be division by zero, hence it must be division by one.
1034     return Op0;
1035
1036   // X / X -> 1
1037   if (Op0 == Op1)
1038     return ConstantInt::get(Op0->getType(), 1);
1039
1040   // (X * Y) / Y -> X if the multiplication does not overflow.
1041   Value *X = nullptr, *Y = nullptr;
1042   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1043     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1044     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1045     // If the Mul knows it does not overflow, then we are good to go.
1046     if ((isSigned && Mul->hasNoSignedWrap()) ||
1047         (!isSigned && Mul->hasNoUnsignedWrap()))
1048       return X;
1049     // If X has the form X = A / Y then X * Y cannot overflow.
1050     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1051       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1052         return X;
1053   }
1054
1055   // (X rem Y) / Y -> 0
1056   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1057       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1058     return Constant::getNullValue(Op0->getType());
1059
1060   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1061   ConstantInt *C1, *C2;
1062   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1063       match(Op1, m_ConstantInt(C2))) {
1064     bool Overflow;
1065     C1->getValue().umul_ov(C2->getValue(), Overflow);
1066     if (Overflow)
1067       return Constant::getNullValue(Op0->getType());
1068   }
1069
1070   // If the operation is with the result of a select instruction, check whether
1071   // operating on either branch of the select always yields the same value.
1072   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1073     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1074       return V;
1075
1076   // If the operation is with the result of a phi instruction, check whether
1077   // operating on all incoming values of the phi always yields the same value.
1078   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1079     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1080       return V;
1081
1082   return nullptr;
1083 }
1084
1085 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1086 /// fold the result.  If not, this returns null.
1087 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1088                                unsigned MaxRecurse) {
1089   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1090     return V;
1091
1092   return nullptr;
1093 }
1094
1095 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1096                               const TargetLibraryInfo *TLI,
1097                               const DominatorTree *DT,
1098                               AssumptionTracker *AT,
1099                               const Instruction *CxtI) {
1100   return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1101                             RecursionLimit);
1102 }
1103
1104 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1105 /// fold the result.  If not, this returns null.
1106 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1107                                unsigned MaxRecurse) {
1108   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1109     return V;
1110
1111   return nullptr;
1112 }
1113
1114 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1115                               const TargetLibraryInfo *TLI,
1116                               const DominatorTree *DT,
1117                               AssumptionTracker *AT,
1118                               const Instruction *CxtI) {
1119   return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1120                             RecursionLimit);
1121 }
1122
1123 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1124                                unsigned) {
1125   // undef / X -> undef    (the undef could be a snan).
1126   if (match(Op0, m_Undef()))
1127     return Op0;
1128
1129   // X / undef -> undef
1130   if (match(Op1, m_Undef()))
1131     return Op1;
1132
1133   return nullptr;
1134 }
1135
1136 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1137                               const TargetLibraryInfo *TLI,
1138                               const DominatorTree *DT,
1139                               AssumptionTracker *AT,
1140                               const Instruction *CxtI) {
1141   return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1142                             RecursionLimit);
1143 }
1144
1145 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1146 /// fold the result.  If not, this returns null.
1147 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1148                           const Query &Q, unsigned MaxRecurse) {
1149   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1150     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1151       Constant *Ops[] = { C0, C1 };
1152       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1153     }
1154   }
1155
1156   // X % undef -> undef
1157   if (match(Op1, m_Undef()))
1158     return Op1;
1159
1160   // undef % X -> 0
1161   if (match(Op0, m_Undef()))
1162     return Constant::getNullValue(Op0->getType());
1163
1164   // 0 % X -> 0, we don't need to preserve faults!
1165   if (match(Op0, m_Zero()))
1166     return Op0;
1167
1168   // X % 0 -> undef, we don't need to preserve faults!
1169   if (match(Op1, m_Zero()))
1170     return UndefValue::get(Op0->getType());
1171
1172   // X % 1 -> 0
1173   if (match(Op1, m_One()))
1174     return Constant::getNullValue(Op0->getType());
1175
1176   if (Op0->getType()->isIntegerTy(1))
1177     // It can't be remainder by zero, hence it must be remainder by one.
1178     return Constant::getNullValue(Op0->getType());
1179
1180   // X % X -> 0
1181   if (Op0 == Op1)
1182     return Constant::getNullValue(Op0->getType());
1183
1184   // (X % Y) % Y -> X % Y
1185   if ((Opcode == Instruction::SRem &&
1186        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1187       (Opcode == Instruction::URem &&
1188        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1189     return Op0;
1190
1191   // If the operation is with the result of a select instruction, check whether
1192   // operating on either branch of the select always yields the same value.
1193   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1194     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1195       return V;
1196
1197   // If the operation is with the result of a phi instruction, check whether
1198   // operating on all incoming values of the phi always yields the same value.
1199   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1200     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1201       return V;
1202
1203   return nullptr;
1204 }
1205
1206 /// SimplifySRemInst - Given operands for an SRem, see if we can
1207 /// fold the result.  If not, this returns null.
1208 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1209                                unsigned MaxRecurse) {
1210   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1211     return V;
1212
1213   return nullptr;
1214 }
1215
1216 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1217                               const TargetLibraryInfo *TLI,
1218                               const DominatorTree *DT,
1219                               AssumptionTracker *AT,
1220                               const Instruction *CxtI) {
1221   return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1222                             RecursionLimit);
1223 }
1224
1225 /// SimplifyURemInst - Given operands for a URem, see if we can
1226 /// fold the result.  If not, this returns null.
1227 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1228                                unsigned MaxRecurse) {
1229   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1230     return V;
1231
1232   return nullptr;
1233 }
1234
1235 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1236                               const TargetLibraryInfo *TLI,
1237                               const DominatorTree *DT,
1238                               AssumptionTracker *AT,
1239                               const Instruction *CxtI) {
1240   return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1241                             RecursionLimit);
1242 }
1243
1244 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1245                                unsigned) {
1246   // undef % X -> undef    (the undef could be a snan).
1247   if (match(Op0, m_Undef()))
1248     return Op0;
1249
1250   // X % undef -> undef
1251   if (match(Op1, m_Undef()))
1252     return Op1;
1253
1254   return nullptr;
1255 }
1256
1257 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1258                               const TargetLibraryInfo *TLI,
1259                               const DominatorTree *DT,
1260                               AssumptionTracker *AT,
1261                               const Instruction *CxtI) {
1262   return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1263                             RecursionLimit);
1264 }
1265
1266 /// isUndefShift - 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 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1294 /// fold the result.  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       Constant *Ops[] = { C0, C1 };
1300       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1301     }
1302   }
1303
1304   // 0 shift by X -> 0
1305   if (match(Op0, m_Zero()))
1306     return Op0;
1307
1308   // X shift by 0 -> X
1309   if (match(Op1, m_Zero()))
1310     return Op0;
1311
1312   // Fold undefined shifts.
1313   if (isUndefShift(Op1))
1314     return UndefValue::get(Op0->getType());
1315
1316   // If the operation is with the result of a select instruction, check whether
1317   // operating on either branch of the select always yields the same value.
1318   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1319     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1320       return V;
1321
1322   // If the operation is with the result of a phi instruction, check whether
1323   // operating on all incoming values of the phi always yields the same value.
1324   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1325     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1326       return V;
1327
1328   return nullptr;
1329 }
1330
1331 /// SimplifyShlInst - Given operands for an Shl, see if we can
1332 /// fold the result.  If not, this returns null.
1333 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1334                               const Query &Q, unsigned MaxRecurse) {
1335   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1336     return V;
1337
1338   // undef << X -> 0
1339   if (match(Op0, m_Undef()))
1340     return Constant::getNullValue(Op0->getType());
1341
1342   // (X >> A) << A -> X
1343   Value *X;
1344   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1345     return X;
1346   return nullptr;
1347 }
1348
1349 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1350                              const DataLayout *DL, const TargetLibraryInfo *TLI,
1351                              const DominatorTree *DT, AssumptionTracker *AT,
1352                              const Instruction *CxtI) {
1353   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
1354                            RecursionLimit);
1355 }
1356
1357 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1358 /// fold the result.  If not, this returns null.
1359 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1360                                const Query &Q, unsigned MaxRecurse) {
1361   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1362     return V;
1363
1364   // X >> X -> 0
1365   if (Op0 == Op1)
1366     return Constant::getNullValue(Op0->getType());
1367
1368   // undef >>l X -> 0
1369   if (match(Op0, m_Undef()))
1370     return Constant::getNullValue(Op0->getType());
1371
1372   // (X << A) >> A -> X
1373   Value *X;
1374   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1375     return X;
1376
1377   return nullptr;
1378 }
1379
1380 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1381                               const DataLayout *DL,
1382                               const TargetLibraryInfo *TLI,
1383                               const DominatorTree *DT,
1384                               AssumptionTracker *AT,
1385                               const Instruction *CxtI) {
1386   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1387                             RecursionLimit);
1388 }
1389
1390 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1391 /// fold the result.  If not, this returns null.
1392 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1393                                const Query &Q, unsigned MaxRecurse) {
1394   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1395     return V;
1396
1397   // X >> X -> 0
1398   if (Op0 == Op1)
1399     return Constant::getNullValue(Op0->getType());
1400
1401   // all ones >>a X -> all ones
1402   if (match(Op0, m_AllOnes()))
1403     return Op0;
1404
1405   // undef >>a X -> all ones
1406   if (match(Op0, m_Undef()))
1407     return Constant::getAllOnesValue(Op0->getType());
1408
1409   // (X << A) >> A -> X
1410   Value *X;
1411   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1412       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1413     return X;
1414
1415   // Arithmetic shifting an all-sign-bit value is a no-op.
1416   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
1417   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1418     return Op0;
1419
1420   return nullptr;
1421 }
1422
1423 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1424                               const DataLayout *DL,
1425                               const TargetLibraryInfo *TLI,
1426                               const DominatorTree *DT,
1427                               AssumptionTracker *AT,
1428                               const Instruction *CxtI) {
1429   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1430                             RecursionLimit);
1431 }
1432
1433 // Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1434 // of possible values cannot be satisfied.
1435 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1436   ICmpInst::Predicate Pred0, Pred1;
1437   ConstantInt *CI1, *CI2;
1438   Value *V;
1439   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1440                          m_ConstantInt(CI2))))
1441    return nullptr;
1442
1443   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1444     return nullptr;
1445
1446   Type *ITy = Op0->getType();
1447
1448   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1449   bool isNSW = AddInst->hasNoSignedWrap();
1450   bool isNUW = AddInst->hasNoUnsignedWrap();
1451
1452   const APInt &CI1V = CI1->getValue();
1453   const APInt &CI2V = CI2->getValue();
1454   const APInt Delta = CI2V - CI1V;
1455   if (CI1V.isStrictlyPositive()) {
1456     if (Delta == 2) {
1457       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1458         return getFalse(ITy);
1459       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1460         return getFalse(ITy);
1461     }
1462     if (Delta == 1) {
1463       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1464         return getFalse(ITy);
1465       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1466         return getFalse(ITy);
1467     }
1468   }
1469   if (CI1V.getBoolValue() && isNUW) {
1470     if (Delta == 2)
1471       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1472         return getFalse(ITy);
1473     if (Delta == 1)
1474       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1475         return getFalse(ITy);
1476   }
1477
1478   return nullptr;
1479 }
1480
1481 /// SimplifyAndInst - Given operands for an And, see if we can
1482 /// fold the result.  If not, this returns null.
1483 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1484                               unsigned MaxRecurse) {
1485   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1486     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1487       Constant *Ops[] = { CLHS, CRHS };
1488       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1489                                       Ops, Q.DL, Q.TLI);
1490     }
1491
1492     // Canonicalize the constant to the RHS.
1493     std::swap(Op0, Op1);
1494   }
1495
1496   // X & undef -> 0
1497   if (match(Op1, m_Undef()))
1498     return Constant::getNullValue(Op0->getType());
1499
1500   // X & X = X
1501   if (Op0 == Op1)
1502     return Op0;
1503
1504   // X & 0 = 0
1505   if (match(Op1, m_Zero()))
1506     return Op1;
1507
1508   // X & -1 = X
1509   if (match(Op1, m_AllOnes()))
1510     return Op0;
1511
1512   // A & ~A  =  ~A & A  =  0
1513   if (match(Op0, m_Not(m_Specific(Op1))) ||
1514       match(Op1, m_Not(m_Specific(Op0))))
1515     return Constant::getNullValue(Op0->getType());
1516
1517   // (A | ?) & A = A
1518   Value *A = nullptr, *B = nullptr;
1519   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1520       (A == Op1 || B == Op1))
1521     return Op1;
1522
1523   // A & (A | ?) = A
1524   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1525       (A == Op0 || B == Op0))
1526     return Op0;
1527
1528   // A & (-A) = A if A is a power of two or zero.
1529   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1530       match(Op1, m_Neg(m_Specific(Op0)))) {
1531     if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1532       return Op0;
1533     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1534       return Op1;
1535   }
1536
1537   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1538     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1539       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1540         return V;
1541       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1542         return V;
1543     }
1544   }
1545
1546   // Try some generic simplifications for associative operations.
1547   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1548                                           MaxRecurse))
1549     return V;
1550
1551   // And distributes over Or.  Try some generic simplifications based on this.
1552   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1553                              Q, MaxRecurse))
1554     return V;
1555
1556   // And distributes over Xor.  Try some generic simplifications based on this.
1557   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1558                              Q, MaxRecurse))
1559     return V;
1560
1561   // If the operation is with the result of a select instruction, check whether
1562   // operating on either branch of the select always yields the same value.
1563   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1564     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1565                                          MaxRecurse))
1566       return V;
1567
1568   // If the operation is with the result of a phi instruction, check whether
1569   // operating on all incoming values of the phi always yields the same value.
1570   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1571     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1572                                       MaxRecurse))
1573       return V;
1574
1575   return nullptr;
1576 }
1577
1578 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
1579                              const TargetLibraryInfo *TLI,
1580                              const DominatorTree *DT, AssumptionTracker *AT,
1581                              const Instruction *CxtI) {
1582   return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1583                            RecursionLimit);
1584 }
1585
1586 // Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1587 // contains all possible values.
1588 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1589   ICmpInst::Predicate Pred0, Pred1;
1590   ConstantInt *CI1, *CI2;
1591   Value *V;
1592   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1593                          m_ConstantInt(CI2))))
1594    return nullptr;
1595
1596   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1597     return nullptr;
1598
1599   Type *ITy = Op0->getType();
1600
1601   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1602   bool isNSW = AddInst->hasNoSignedWrap();
1603   bool isNUW = AddInst->hasNoUnsignedWrap();
1604
1605   const APInt &CI1V = CI1->getValue();
1606   const APInt &CI2V = CI2->getValue();
1607   const APInt Delta = CI2V - CI1V;
1608   if (CI1V.isStrictlyPositive()) {
1609     if (Delta == 2) {
1610       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1611         return getTrue(ITy);
1612       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1613         return getTrue(ITy);
1614     }
1615     if (Delta == 1) {
1616       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1617         return getTrue(ITy);
1618       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1619         return getTrue(ITy);
1620     }
1621   }
1622   if (CI1V.getBoolValue() && isNUW) {
1623     if (Delta == 2)
1624       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1625         return getTrue(ITy);
1626     if (Delta == 1)
1627       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1628         return getTrue(ITy);
1629   }
1630
1631   return nullptr;
1632 }
1633
1634 /// SimplifyOrInst - Given operands for an Or, see if we can
1635 /// fold the result.  If not, this returns null.
1636 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1637                              unsigned MaxRecurse) {
1638   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1639     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1640       Constant *Ops[] = { CLHS, CRHS };
1641       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1642                                       Ops, Q.DL, Q.TLI);
1643     }
1644
1645     // Canonicalize the constant to the RHS.
1646     std::swap(Op0, Op1);
1647   }
1648
1649   // X | undef -> -1
1650   if (match(Op1, m_Undef()))
1651     return Constant::getAllOnesValue(Op0->getType());
1652
1653   // X | X = X
1654   if (Op0 == Op1)
1655     return Op0;
1656
1657   // X | 0 = X
1658   if (match(Op1, m_Zero()))
1659     return Op0;
1660
1661   // X | -1 = -1
1662   if (match(Op1, m_AllOnes()))
1663     return Op1;
1664
1665   // A | ~A  =  ~A | A  =  -1
1666   if (match(Op0, m_Not(m_Specific(Op1))) ||
1667       match(Op1, m_Not(m_Specific(Op0))))
1668     return Constant::getAllOnesValue(Op0->getType());
1669
1670   // (A & ?) | A = A
1671   Value *A = nullptr, *B = nullptr;
1672   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1673       (A == Op1 || B == Op1))
1674     return Op1;
1675
1676   // A | (A & ?) = A
1677   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1678       (A == Op0 || B == Op0))
1679     return Op0;
1680
1681   // ~(A & ?) | A = -1
1682   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1683       (A == Op1 || B == Op1))
1684     return Constant::getAllOnesValue(Op1->getType());
1685
1686   // A | ~(A & ?) = -1
1687   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1688       (A == Op0 || B == Op0))
1689     return Constant::getAllOnesValue(Op0->getType());
1690
1691   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1692     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1693       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1694         return V;
1695       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1696         return V;
1697     }
1698   }
1699
1700   // Try some generic simplifications for associative operations.
1701   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1702                                           MaxRecurse))
1703     return V;
1704
1705   // Or distributes over And.  Try some generic simplifications based on this.
1706   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1707                              MaxRecurse))
1708     return V;
1709
1710   // If the operation is with the result of a select instruction, check whether
1711   // operating on either branch of the select always yields the same value.
1712   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1713     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1714                                          MaxRecurse))
1715       return V;
1716
1717   // (A & C)|(B & D)
1718   Value *C = nullptr, *D = nullptr;
1719   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1720       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1721     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1722     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1723     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1724       // (A & C1)|(B & C2)
1725       // If we have: ((V + N) & C1) | (V & C2)
1726       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1727       // replace with V+N.
1728       Value *V1, *V2;
1729       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1730           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1731         // Add commutes, try both ways.
1732         if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
1733                                          0, Q.AT, Q.CxtI, Q.DT))
1734           return A;
1735         if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
1736                                          0, Q.AT, Q.CxtI, Q.DT))
1737           return A;
1738       }
1739       // Or commutes, try both ways.
1740       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1741           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1742         // Add commutes, try both ways.
1743         if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
1744                                          0, Q.AT, Q.CxtI, Q.DT))
1745           return B;
1746         if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
1747                                          0, Q.AT, Q.CxtI, Q.DT))
1748           return B;
1749       }
1750     }
1751   }
1752
1753   // If the operation is with the result of a phi instruction, check whether
1754   // operating on all incoming values of the phi always yields the same value.
1755   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1756     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1757       return V;
1758
1759   return nullptr;
1760 }
1761
1762 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
1763                             const TargetLibraryInfo *TLI,
1764                             const DominatorTree *DT, AssumptionTracker *AT,
1765                             const Instruction *CxtI) {
1766   return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1767                           RecursionLimit);
1768 }
1769
1770 /// SimplifyXorInst - Given operands for a Xor, see if we can
1771 /// fold the result.  If not, this returns null.
1772 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1773                               unsigned MaxRecurse) {
1774   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1775     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1776       Constant *Ops[] = { CLHS, CRHS };
1777       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1778                                       Ops, Q.DL, Q.TLI);
1779     }
1780
1781     // Canonicalize the constant to the RHS.
1782     std::swap(Op0, Op1);
1783   }
1784
1785   // A ^ undef -> undef
1786   if (match(Op1, m_Undef()))
1787     return Op1;
1788
1789   // A ^ 0 = A
1790   if (match(Op1, m_Zero()))
1791     return Op0;
1792
1793   // A ^ A = 0
1794   if (Op0 == Op1)
1795     return Constant::getNullValue(Op0->getType());
1796
1797   // A ^ ~A  =  ~A ^ A  =  -1
1798   if (match(Op0, m_Not(m_Specific(Op1))) ||
1799       match(Op1, m_Not(m_Specific(Op0))))
1800     return Constant::getAllOnesValue(Op0->getType());
1801
1802   // Try some generic simplifications for associative operations.
1803   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1804                                           MaxRecurse))
1805     return V;
1806
1807   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1808   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1809   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1810   // only if B and C are equal.  If B and C are equal then (since we assume
1811   // that operands have already been simplified) "select(cond, B, C)" should
1812   // have been simplified to the common value of B and C already.  Analysing
1813   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1814   // for threading over phi nodes.
1815
1816   return nullptr;
1817 }
1818
1819 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
1820                              const TargetLibraryInfo *TLI,
1821                              const DominatorTree *DT, AssumptionTracker *AT,
1822                              const Instruction *CxtI) {
1823   return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1824                            RecursionLimit);
1825 }
1826
1827 static Type *GetCompareTy(Value *Op) {
1828   return CmpInst::makeCmpResultType(Op->getType());
1829 }
1830
1831 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1832 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1833 /// otherwise return null.  Helper function for analyzing max/min idioms.
1834 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1835                                          Value *LHS, Value *RHS) {
1836   SelectInst *SI = dyn_cast<SelectInst>(V);
1837   if (!SI)
1838     return nullptr;
1839   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1840   if (!Cmp)
1841     return nullptr;
1842   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1843   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1844     return Cmp;
1845   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1846       LHS == CmpRHS && RHS == CmpLHS)
1847     return Cmp;
1848   return nullptr;
1849 }
1850
1851 // A significant optimization not implemented here is assuming that alloca
1852 // addresses are not equal to incoming argument values. They don't *alias*,
1853 // as we say, but that doesn't mean they aren't equal, so we take a
1854 // conservative approach.
1855 //
1856 // This is inspired in part by C++11 5.10p1:
1857 //   "Two pointers of the same type compare equal if and only if they are both
1858 //    null, both point to the same function, or both represent the same
1859 //    address."
1860 //
1861 // This is pretty permissive.
1862 //
1863 // It's also partly due to C11 6.5.9p6:
1864 //   "Two pointers compare equal if and only if both are null pointers, both are
1865 //    pointers to the same object (including a pointer to an object and a
1866 //    subobject at its beginning) or function, both are pointers to one past the
1867 //    last element of the same array object, or one is a pointer to one past the
1868 //    end of one array object and the other is a pointer to the start of a
1869 //    different array object that happens to immediately follow the first array
1870 //    object in the address space.)
1871 //
1872 // C11's version is more restrictive, however there's no reason why an argument
1873 // couldn't be a one-past-the-end value for a stack object in the caller and be
1874 // equal to the beginning of a stack object in the callee.
1875 //
1876 // If the C and C++ standards are ever made sufficiently restrictive in this
1877 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1878 // this optimization.
1879 static Constant *computePointerICmp(const DataLayout *DL,
1880                                     const TargetLibraryInfo *TLI,
1881                                     CmpInst::Predicate Pred,
1882                                     Value *LHS, Value *RHS) {
1883   // First, skip past any trivial no-ops.
1884   LHS = LHS->stripPointerCasts();
1885   RHS = RHS->stripPointerCasts();
1886
1887   // A non-null pointer is not equal to a null pointer.
1888   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1889       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1890     return ConstantInt::get(GetCompareTy(LHS),
1891                             !CmpInst::isTrueWhenEqual(Pred));
1892
1893   // We can only fold certain predicates on pointer comparisons.
1894   switch (Pred) {
1895   default:
1896     return nullptr;
1897
1898     // Equality comaprisons are easy to fold.
1899   case CmpInst::ICMP_EQ:
1900   case CmpInst::ICMP_NE:
1901     break;
1902
1903     // We can only handle unsigned relational comparisons because 'inbounds' on
1904     // a GEP only protects against unsigned wrapping.
1905   case CmpInst::ICMP_UGT:
1906   case CmpInst::ICMP_UGE:
1907   case CmpInst::ICMP_ULT:
1908   case CmpInst::ICMP_ULE:
1909     // However, we have to switch them to their signed variants to handle
1910     // negative indices from the base pointer.
1911     Pred = ICmpInst::getSignedPredicate(Pred);
1912     break;
1913   }
1914
1915   // Strip off any constant offsets so that we can reason about them.
1916   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1917   // here and compare base addresses like AliasAnalysis does, however there are
1918   // numerous hazards. AliasAnalysis and its utilities rely on special rules
1919   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1920   // doesn't need to guarantee pointer inequality when it says NoAlias.
1921   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1922   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1923
1924   // If LHS and RHS are related via constant offsets to the same base
1925   // value, we can replace it with an icmp which just compares the offsets.
1926   if (LHS == RHS)
1927     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1928
1929   // Various optimizations for (in)equality comparisons.
1930   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1931     // Different non-empty allocations that exist at the same time have
1932     // different addresses (if the program can tell). Global variables always
1933     // exist, so they always exist during the lifetime of each other and all
1934     // allocas. Two different allocas usually have different addresses...
1935     //
1936     // However, if there's an @llvm.stackrestore dynamically in between two
1937     // allocas, they may have the same address. It's tempting to reduce the
1938     // scope of the problem by only looking at *static* allocas here. That would
1939     // cover the majority of allocas while significantly reducing the likelihood
1940     // of having an @llvm.stackrestore pop up in the middle. However, it's not
1941     // actually impossible for an @llvm.stackrestore to pop up in the middle of
1942     // an entry block. Also, if we have a block that's not attached to a
1943     // function, we can't tell if it's "static" under the current definition.
1944     // Theoretically, this problem could be fixed by creating a new kind of
1945     // instruction kind specifically for static allocas. Such a new instruction
1946     // could be required to be at the top of the entry block, thus preventing it
1947     // from being subject to a @llvm.stackrestore. Instcombine could even
1948     // convert regular allocas into these special allocas. It'd be nifty.
1949     // However, until then, this problem remains open.
1950     //
1951     // So, we'll assume that two non-empty allocas have different addresses
1952     // for now.
1953     //
1954     // With all that, if the offsets are within the bounds of their allocations
1955     // (and not one-past-the-end! so we can't use inbounds!), and their
1956     // allocations aren't the same, the pointers are not equal.
1957     //
1958     // Note that it's not necessary to check for LHS being a global variable
1959     // address, due to canonicalization and constant folding.
1960     if (isa<AllocaInst>(LHS) &&
1961         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1962       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1963       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1964       uint64_t LHSSize, RHSSize;
1965       if (LHSOffsetCI && RHSOffsetCI &&
1966           getObjectSize(LHS, LHSSize, DL, TLI) &&
1967           getObjectSize(RHS, RHSSize, DL, TLI)) {
1968         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1969         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1970         if (!LHSOffsetValue.isNegative() &&
1971             !RHSOffsetValue.isNegative() &&
1972             LHSOffsetValue.ult(LHSSize) &&
1973             RHSOffsetValue.ult(RHSSize)) {
1974           return ConstantInt::get(GetCompareTy(LHS),
1975                                   !CmpInst::isTrueWhenEqual(Pred));
1976         }
1977       }
1978
1979       // Repeat the above check but this time without depending on DataLayout
1980       // or being able to compute a precise size.
1981       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1982           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1983           LHSOffset->isNullValue() &&
1984           RHSOffset->isNullValue())
1985         return ConstantInt::get(GetCompareTy(LHS),
1986                                 !CmpInst::isTrueWhenEqual(Pred));
1987     }
1988
1989     // Even if an non-inbounds GEP occurs along the path we can still optimize
1990     // equality comparisons concerning the result. We avoid walking the whole
1991     // chain again by starting where the last calls to
1992     // stripAndComputeConstantOffsets left off and accumulate the offsets.
1993     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1994     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
1995     if (LHS == RHS)
1996       return ConstantExpr::getICmp(Pred,
1997                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1998                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
1999   }
2000
2001   // Otherwise, fail.
2002   return nullptr;
2003 }
2004
2005 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
2006 /// fold the result.  If not, this returns null.
2007 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2008                                const Query &Q, unsigned MaxRecurse) {
2009   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2010   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2011
2012   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2013     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2014       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2015
2016     // If we have a constant, make sure it is on the RHS.
2017     std::swap(LHS, RHS);
2018     Pred = CmpInst::getSwappedPredicate(Pred);
2019   }
2020
2021   Type *ITy = GetCompareTy(LHS); // The return type.
2022   Type *OpTy = LHS->getType();   // The operand type.
2023
2024   // icmp X, X -> true/false
2025   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2026   // because X could be 0.
2027   if (LHS == RHS || isa<UndefValue>(RHS))
2028     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2029
2030   // Special case logic when the operands have i1 type.
2031   if (OpTy->getScalarType()->isIntegerTy(1)) {
2032     switch (Pred) {
2033     default: break;
2034     case ICmpInst::ICMP_EQ:
2035       // X == 1 -> X
2036       if (match(RHS, m_One()))
2037         return LHS;
2038       break;
2039     case ICmpInst::ICMP_NE:
2040       // X != 0 -> X
2041       if (match(RHS, m_Zero()))
2042         return LHS;
2043       break;
2044     case ICmpInst::ICMP_UGT:
2045       // X >u 0 -> X
2046       if (match(RHS, m_Zero()))
2047         return LHS;
2048       break;
2049     case ICmpInst::ICMP_UGE:
2050       // X >=u 1 -> X
2051       if (match(RHS, m_One()))
2052         return LHS;
2053       break;
2054     case ICmpInst::ICMP_SLT:
2055       // X <s 0 -> X
2056       if (match(RHS, m_Zero()))
2057         return LHS;
2058       break;
2059     case ICmpInst::ICMP_SLE:
2060       // X <=s -1 -> X
2061       if (match(RHS, m_One()))
2062         return LHS;
2063       break;
2064     }
2065   }
2066
2067   // If we are comparing with zero then try hard since this is a common case.
2068   if (match(RHS, m_Zero())) {
2069     bool LHSKnownNonNegative, LHSKnownNegative;
2070     switch (Pred) {
2071     default: llvm_unreachable("Unknown ICmp predicate!");
2072     case ICmpInst::ICMP_ULT:
2073       return getFalse(ITy);
2074     case ICmpInst::ICMP_UGE:
2075       return getTrue(ITy);
2076     case ICmpInst::ICMP_EQ:
2077     case ICmpInst::ICMP_ULE:
2078       if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
2079         return getFalse(ITy);
2080       break;
2081     case ICmpInst::ICMP_NE:
2082     case ICmpInst::ICMP_UGT:
2083       if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
2084         return getTrue(ITy);
2085       break;
2086     case ICmpInst::ICMP_SLT:
2087       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2088                      0, Q.AT, Q.CxtI, Q.DT);
2089       if (LHSKnownNegative)
2090         return getTrue(ITy);
2091       if (LHSKnownNonNegative)
2092         return getFalse(ITy);
2093       break;
2094     case ICmpInst::ICMP_SLE:
2095       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2096                      0, Q.AT, Q.CxtI, Q.DT);
2097       if (LHSKnownNegative)
2098         return getTrue(ITy);
2099       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
2100                                                 0, Q.AT, Q.CxtI, Q.DT))
2101         return getFalse(ITy);
2102       break;
2103     case ICmpInst::ICMP_SGE:
2104       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2105                      0, Q.AT, Q.CxtI, Q.DT);
2106       if (LHSKnownNegative)
2107         return getFalse(ITy);
2108       if (LHSKnownNonNegative)
2109         return getTrue(ITy);
2110       break;
2111     case ICmpInst::ICMP_SGT:
2112       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2113                      0, Q.AT, Q.CxtI, Q.DT);
2114       if (LHSKnownNegative)
2115         return getFalse(ITy);
2116       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 
2117                                                 0, Q.AT, Q.CxtI, Q.DT))
2118         return getTrue(ITy);
2119       break;
2120     }
2121   }
2122
2123   // See if we are doing a comparison with a constant integer.
2124   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2125     // Rule out tautological comparisons (eg., ult 0 or uge 0).
2126     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2127     if (RHS_CR.isEmptySet())
2128       return ConstantInt::getFalse(CI->getContext());
2129     if (RHS_CR.isFullSet())
2130       return ConstantInt::getTrue(CI->getContext());
2131
2132     // Many binary operators with constant RHS have easy to compute constant
2133     // range.  Use them to check whether the comparison is a tautology.
2134     unsigned Width = CI->getBitWidth();
2135     APInt Lower = APInt(Width, 0);
2136     APInt Upper = APInt(Width, 0);
2137     ConstantInt *CI2;
2138     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2139       // 'urem x, CI2' produces [0, CI2).
2140       Upper = CI2->getValue();
2141     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2142       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2143       Upper = CI2->getValue().abs();
2144       Lower = (-Upper) + 1;
2145     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2146       // 'udiv CI2, x' produces [0, CI2].
2147       Upper = CI2->getValue() + 1;
2148     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2149       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2150       APInt NegOne = APInt::getAllOnesValue(Width);
2151       if (!CI2->isZero())
2152         Upper = NegOne.udiv(CI2->getValue()) + 1;
2153     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2154       if (CI2->isMinSignedValue()) {
2155         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2156         Lower = CI2->getValue();
2157         Upper = Lower.lshr(1) + 1;
2158       } else {
2159         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2160         Upper = CI2->getValue().abs() + 1;
2161         Lower = (-Upper) + 1;
2162       }
2163     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2164       APInt IntMin = APInt::getSignedMinValue(Width);
2165       APInt IntMax = APInt::getSignedMaxValue(Width);
2166       APInt Val = CI2->getValue();
2167       if (Val.isAllOnesValue()) {
2168         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2169         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2170         Lower = IntMin + 1;
2171         Upper = IntMax + 1;
2172       } else if (Val.countLeadingZeros() < Width - 1) {
2173         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2174         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2175         Lower = IntMin.sdiv(Val);
2176         Upper = IntMax.sdiv(Val);
2177         if (Lower.sgt(Upper))
2178           std::swap(Lower, Upper);
2179         Upper = Upper + 1;
2180         assert(Upper != Lower && "Upper part of range has wrapped!");
2181       }
2182     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2183       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2184       Lower = CI2->getValue();
2185       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2186     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2187       if (CI2->isNegative()) {
2188         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2189         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2190         Lower = CI2->getValue().shl(ShiftAmount);
2191         Upper = CI2->getValue() + 1;
2192       } else {
2193         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2194         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2195         Lower = CI2->getValue();
2196         Upper = CI2->getValue().shl(ShiftAmount) + 1;
2197       }
2198     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2199       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2200       APInt NegOne = APInt::getAllOnesValue(Width);
2201       if (CI2->getValue().ult(Width))
2202         Upper = NegOne.lshr(CI2->getValue()) + 1;
2203     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2204       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2205       unsigned ShiftAmount = Width - 1;
2206       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2207         ShiftAmount = CI2->getValue().countTrailingZeros();
2208       Lower = CI2->getValue().lshr(ShiftAmount);
2209       Upper = CI2->getValue() + 1;
2210     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2211       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2212       APInt IntMin = APInt::getSignedMinValue(Width);
2213       APInt IntMax = APInt::getSignedMaxValue(Width);
2214       if (CI2->getValue().ult(Width)) {
2215         Lower = IntMin.ashr(CI2->getValue());
2216         Upper = IntMax.ashr(CI2->getValue()) + 1;
2217       }
2218     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2219       unsigned ShiftAmount = Width - 1;
2220       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2221         ShiftAmount = CI2->getValue().countTrailingZeros();
2222       if (CI2->isNegative()) {
2223         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2224         Lower = CI2->getValue();
2225         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2226       } else {
2227         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2228         Lower = CI2->getValue().ashr(ShiftAmount);
2229         Upper = CI2->getValue() + 1;
2230       }
2231     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2232       // 'or x, CI2' produces [CI2, UINT_MAX].
2233       Lower = CI2->getValue();
2234     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2235       // 'and x, CI2' produces [0, CI2].
2236       Upper = CI2->getValue() + 1;
2237     }
2238     if (Lower != Upper) {
2239       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2240       if (RHS_CR.contains(LHS_CR))
2241         return ConstantInt::getTrue(RHS->getContext());
2242       if (RHS_CR.inverse().contains(LHS_CR))
2243         return ConstantInt::getFalse(RHS->getContext());
2244     }
2245   }
2246
2247   // Compare of cast, for example (zext X) != 0 -> X != 0
2248   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2249     Instruction *LI = cast<CastInst>(LHS);
2250     Value *SrcOp = LI->getOperand(0);
2251     Type *SrcTy = SrcOp->getType();
2252     Type *DstTy = LI->getType();
2253
2254     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2255     // if the integer type is the same size as the pointer type.
2256     if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2257         Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2258       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2259         // Transfer the cast to the constant.
2260         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2261                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2262                                         Q, MaxRecurse-1))
2263           return V;
2264       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2265         if (RI->getOperand(0)->getType() == SrcTy)
2266           // Compare without the cast.
2267           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2268                                           Q, MaxRecurse-1))
2269             return V;
2270       }
2271     }
2272
2273     if (isa<ZExtInst>(LHS)) {
2274       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2275       // same type.
2276       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2277         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2278           // Compare X and Y.  Note that signed predicates become unsigned.
2279           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2280                                           SrcOp, RI->getOperand(0), Q,
2281                                           MaxRecurse-1))
2282             return V;
2283       }
2284       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2285       // too.  If not, then try to deduce the result of the comparison.
2286       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2287         // Compute the constant that would happen if we truncated to SrcTy then
2288         // reextended to DstTy.
2289         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2290         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2291
2292         // If the re-extended constant didn't change then this is effectively
2293         // also a case of comparing two zero-extended values.
2294         if (RExt == CI && MaxRecurse)
2295           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2296                                         SrcOp, Trunc, Q, MaxRecurse-1))
2297             return V;
2298
2299         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2300         // there.  Use this to work out the result of the comparison.
2301         if (RExt != CI) {
2302           switch (Pred) {
2303           default: llvm_unreachable("Unknown ICmp predicate!");
2304           // LHS <u RHS.
2305           case ICmpInst::ICMP_EQ:
2306           case ICmpInst::ICMP_UGT:
2307           case ICmpInst::ICMP_UGE:
2308             return ConstantInt::getFalse(CI->getContext());
2309
2310           case ICmpInst::ICMP_NE:
2311           case ICmpInst::ICMP_ULT:
2312           case ICmpInst::ICMP_ULE:
2313             return ConstantInt::getTrue(CI->getContext());
2314
2315           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2316           // is non-negative then LHS <s RHS.
2317           case ICmpInst::ICMP_SGT:
2318           case ICmpInst::ICMP_SGE:
2319             return CI->getValue().isNegative() ?
2320               ConstantInt::getTrue(CI->getContext()) :
2321               ConstantInt::getFalse(CI->getContext());
2322
2323           case ICmpInst::ICMP_SLT:
2324           case ICmpInst::ICMP_SLE:
2325             return CI->getValue().isNegative() ?
2326               ConstantInt::getFalse(CI->getContext()) :
2327               ConstantInt::getTrue(CI->getContext());
2328           }
2329         }
2330       }
2331     }
2332
2333     if (isa<SExtInst>(LHS)) {
2334       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2335       // same type.
2336       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2337         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2338           // Compare X and Y.  Note that the predicate does not change.
2339           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2340                                           Q, MaxRecurse-1))
2341             return V;
2342       }
2343       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2344       // too.  If not, then try to deduce the result of the comparison.
2345       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2346         // Compute the constant that would happen if we truncated to SrcTy then
2347         // reextended to DstTy.
2348         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2349         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2350
2351         // If the re-extended constant didn't change then this is effectively
2352         // also a case of comparing two sign-extended values.
2353         if (RExt == CI && MaxRecurse)
2354           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2355             return V;
2356
2357         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2358         // bits there.  Use this to work out the result of the comparison.
2359         if (RExt != CI) {
2360           switch (Pred) {
2361           default: llvm_unreachable("Unknown ICmp predicate!");
2362           case ICmpInst::ICMP_EQ:
2363             return ConstantInt::getFalse(CI->getContext());
2364           case ICmpInst::ICMP_NE:
2365             return ConstantInt::getTrue(CI->getContext());
2366
2367           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2368           // LHS >s RHS.
2369           case ICmpInst::ICMP_SGT:
2370           case ICmpInst::ICMP_SGE:
2371             return CI->getValue().isNegative() ?
2372               ConstantInt::getTrue(CI->getContext()) :
2373               ConstantInt::getFalse(CI->getContext());
2374           case ICmpInst::ICMP_SLT:
2375           case ICmpInst::ICMP_SLE:
2376             return CI->getValue().isNegative() ?
2377               ConstantInt::getFalse(CI->getContext()) :
2378               ConstantInt::getTrue(CI->getContext());
2379
2380           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2381           // LHS >u RHS.
2382           case ICmpInst::ICMP_UGT:
2383           case ICmpInst::ICMP_UGE:
2384             // Comparison is true iff the LHS <s 0.
2385             if (MaxRecurse)
2386               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2387                                               Constant::getNullValue(SrcTy),
2388                                               Q, MaxRecurse-1))
2389                 return V;
2390             break;
2391           case ICmpInst::ICMP_ULT:
2392           case ICmpInst::ICMP_ULE:
2393             // Comparison is true iff the LHS >=s 0.
2394             if (MaxRecurse)
2395               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2396                                               Constant::getNullValue(SrcTy),
2397                                               Q, MaxRecurse-1))
2398                 return V;
2399             break;
2400           }
2401         }
2402       }
2403     }
2404   }
2405
2406   // If a bit is known to be zero for A and known to be one for B,
2407   // then A and B cannot be equal.
2408   if (ICmpInst::isEquality(Pred)) {
2409     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2410       uint32_t BitWidth = CI->getBitWidth();
2411       APInt LHSKnownZero(BitWidth, 0);
2412       APInt LHSKnownOne(BitWidth, 0);
2413       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
2414                        0, Q.AT, Q.CxtI, Q.DT);
2415       APInt RHSKnownZero(BitWidth, 0);
2416       APInt RHSKnownOne(BitWidth, 0);
2417       computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
2418                        0, Q.AT, Q.CxtI, Q.DT);
2419       if (((LHSKnownOne & RHSKnownZero) != 0) ||
2420           ((LHSKnownZero & RHSKnownOne) != 0))
2421         return (Pred == ICmpInst::ICMP_EQ)
2422                    ? ConstantInt::getFalse(CI->getContext())
2423                    : ConstantInt::getTrue(CI->getContext());
2424     }
2425   }
2426
2427   // Special logic for binary operators.
2428   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2429   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2430   if (MaxRecurse && (LBO || RBO)) {
2431     // Analyze the case when either LHS or RHS is an add instruction.
2432     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2433     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2434     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2435     if (LBO && LBO->getOpcode() == Instruction::Add) {
2436       A = LBO->getOperand(0); B = LBO->getOperand(1);
2437       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2438         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2439         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2440     }
2441     if (RBO && RBO->getOpcode() == Instruction::Add) {
2442       C = RBO->getOperand(0); D = RBO->getOperand(1);
2443       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2444         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2445         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2446     }
2447
2448     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2449     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2450       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2451                                       Constant::getNullValue(RHS->getType()),
2452                                       Q, MaxRecurse-1))
2453         return V;
2454
2455     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2456     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2457       if (Value *V = SimplifyICmpInst(Pred,
2458                                       Constant::getNullValue(LHS->getType()),
2459                                       C == LHS ? D : C, Q, MaxRecurse-1))
2460         return V;
2461
2462     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2463     if (A && C && (A == C || A == D || B == C || B == D) &&
2464         NoLHSWrapProblem && NoRHSWrapProblem) {
2465       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2466       Value *Y, *Z;
2467       if (A == C) {
2468         // C + B == C + D  ->  B == D
2469         Y = B;
2470         Z = D;
2471       } else if (A == D) {
2472         // D + B == C + D  ->  B == C
2473         Y = B;
2474         Z = C;
2475       } else if (B == C) {
2476         // A + C == C + D  ->  A == D
2477         Y = A;
2478         Z = D;
2479       } else {
2480         assert(B == D);
2481         // A + D == C + D  ->  A == C
2482         Y = A;
2483         Z = C;
2484       }
2485       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2486         return V;
2487     }
2488   }
2489
2490   // 0 - (zext X) pred C
2491   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2492     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2493       if (RHSC->getValue().isStrictlyPositive()) {
2494         if (Pred == ICmpInst::ICMP_SLT)
2495           return ConstantInt::getTrue(RHSC->getContext());
2496         if (Pred == ICmpInst::ICMP_SGE)
2497           return ConstantInt::getFalse(RHSC->getContext());
2498         if (Pred == ICmpInst::ICMP_EQ)
2499           return ConstantInt::getFalse(RHSC->getContext());
2500         if (Pred == ICmpInst::ICMP_NE)
2501           return ConstantInt::getTrue(RHSC->getContext());
2502       }
2503       if (RHSC->getValue().isNonNegative()) {
2504         if (Pred == ICmpInst::ICMP_SLE)
2505           return ConstantInt::getTrue(RHSC->getContext());
2506         if (Pred == ICmpInst::ICMP_SGT)
2507           return ConstantInt::getFalse(RHSC->getContext());
2508       }
2509     }
2510   }
2511
2512   // icmp pred (urem X, Y), Y
2513   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2514     bool KnownNonNegative, KnownNegative;
2515     switch (Pred) {
2516     default:
2517       break;
2518     case ICmpInst::ICMP_SGT:
2519     case ICmpInst::ICMP_SGE:
2520       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2521                      0, Q.AT, Q.CxtI, Q.DT);
2522       if (!KnownNonNegative)
2523         break;
2524       // fall-through
2525     case ICmpInst::ICMP_EQ:
2526     case ICmpInst::ICMP_UGT:
2527     case ICmpInst::ICMP_UGE:
2528       return getFalse(ITy);
2529     case ICmpInst::ICMP_SLT:
2530     case ICmpInst::ICMP_SLE:
2531       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2532                      0, Q.AT, Q.CxtI, Q.DT);
2533       if (!KnownNonNegative)
2534         break;
2535       // fall-through
2536     case ICmpInst::ICMP_NE:
2537     case ICmpInst::ICMP_ULT:
2538     case ICmpInst::ICMP_ULE:
2539       return getTrue(ITy);
2540     }
2541   }
2542
2543   // icmp pred X, (urem Y, X)
2544   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2545     bool KnownNonNegative, KnownNegative;
2546     switch (Pred) {
2547     default:
2548       break;
2549     case ICmpInst::ICMP_SGT:
2550     case ICmpInst::ICMP_SGE:
2551       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2552                      0, Q.AT, Q.CxtI, Q.DT);
2553       if (!KnownNonNegative)
2554         break;
2555       // fall-through
2556     case ICmpInst::ICMP_NE:
2557     case ICmpInst::ICMP_UGT:
2558     case ICmpInst::ICMP_UGE:
2559       return getTrue(ITy);
2560     case ICmpInst::ICMP_SLT:
2561     case ICmpInst::ICMP_SLE:
2562       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2563                      0, Q.AT, Q.CxtI, Q.DT);
2564       if (!KnownNonNegative)
2565         break;
2566       // fall-through
2567     case ICmpInst::ICMP_EQ:
2568     case ICmpInst::ICMP_ULT:
2569     case ICmpInst::ICMP_ULE:
2570       return getFalse(ITy);
2571     }
2572   }
2573
2574   // x udiv y <=u x.
2575   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2576     // icmp pred (X /u Y), X
2577     if (Pred == ICmpInst::ICMP_UGT)
2578       return getFalse(ITy);
2579     if (Pred == ICmpInst::ICMP_ULE)
2580       return getTrue(ITy);
2581   }
2582
2583   // handle:
2584   //   CI2 << X == CI
2585   //   CI2 << X != CI
2586   //
2587   //   where CI2 is a power of 2 and CI isn't
2588   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2589     const APInt *CI2Val, *CIVal = &CI->getValue();
2590     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2591         CI2Val->isPowerOf2()) {
2592       if (!CIVal->isPowerOf2()) {
2593         // CI2 << X can equal zero in some circumstances,
2594         // this simplification is unsafe if CI is zero.
2595         //
2596         // We know it is safe if:
2597         // - The shift is nsw, we can't shift out the one bit.
2598         // - The shift is nuw, we can't shift out the one bit.
2599         // - CI2 is one
2600         // - CI isn't zero
2601         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2602             *CI2Val == 1 || !CI->isZero()) {
2603           if (Pred == ICmpInst::ICMP_EQ)
2604             return ConstantInt::getFalse(RHS->getContext());
2605           if (Pred == ICmpInst::ICMP_NE)
2606             return ConstantInt::getTrue(RHS->getContext());
2607         }
2608       }
2609       if (CIVal->isSignBit() && *CI2Val == 1) {
2610         if (Pred == ICmpInst::ICMP_UGT)
2611           return ConstantInt::getFalse(RHS->getContext());
2612         if (Pred == ICmpInst::ICMP_ULE)
2613           return ConstantInt::getTrue(RHS->getContext());
2614       }
2615     }
2616   }
2617
2618   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2619       LBO->getOperand(1) == RBO->getOperand(1)) {
2620     switch (LBO->getOpcode()) {
2621     default: break;
2622     case Instruction::UDiv:
2623     case Instruction::LShr:
2624       if (ICmpInst::isSigned(Pred))
2625         break;
2626       // fall-through
2627     case Instruction::SDiv:
2628     case Instruction::AShr:
2629       if (!LBO->isExact() || !RBO->isExact())
2630         break;
2631       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2632                                       RBO->getOperand(0), Q, MaxRecurse-1))
2633         return V;
2634       break;
2635     case Instruction::Shl: {
2636       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2637       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2638       if (!NUW && !NSW)
2639         break;
2640       if (!NSW && ICmpInst::isSigned(Pred))
2641         break;
2642       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2643                                       RBO->getOperand(0), Q, MaxRecurse-1))
2644         return V;
2645       break;
2646     }
2647     }
2648   }
2649
2650   // Simplify comparisons involving max/min.
2651   Value *A, *B;
2652   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2653   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2654
2655   // Signed variants on "max(a,b)>=a -> true".
2656   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2657     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2658     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2659     // We analyze this as smax(A, B) pred A.
2660     P = Pred;
2661   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2662              (A == LHS || B == LHS)) {
2663     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2664     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2665     // We analyze this as smax(A, B) swapped-pred A.
2666     P = CmpInst::getSwappedPredicate(Pred);
2667   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2668              (A == RHS || B == RHS)) {
2669     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2670     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2671     // We analyze this as smax(-A, -B) swapped-pred -A.
2672     // Note that we do not need to actually form -A or -B thanks to EqP.
2673     P = CmpInst::getSwappedPredicate(Pred);
2674   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2675              (A == LHS || B == LHS)) {
2676     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2677     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2678     // We analyze this as smax(-A, -B) pred -A.
2679     // Note that we do not need to actually form -A or -B thanks to EqP.
2680     P = Pred;
2681   }
2682   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2683     // Cases correspond to "max(A, B) p A".
2684     switch (P) {
2685     default:
2686       break;
2687     case CmpInst::ICMP_EQ:
2688     case CmpInst::ICMP_SLE:
2689       // Equivalent to "A EqP B".  This may be the same as the condition tested
2690       // in the max/min; if so, we can just return that.
2691       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2692         return V;
2693       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2694         return V;
2695       // Otherwise, see if "A EqP B" simplifies.
2696       if (MaxRecurse)
2697         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2698           return V;
2699       break;
2700     case CmpInst::ICMP_NE:
2701     case CmpInst::ICMP_SGT: {
2702       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2703       // Equivalent to "A InvEqP B".  This may be the same as the condition
2704       // tested in the max/min; if so, we can just return that.
2705       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2706         return V;
2707       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2708         return V;
2709       // Otherwise, see if "A InvEqP B" simplifies.
2710       if (MaxRecurse)
2711         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2712           return V;
2713       break;
2714     }
2715     case CmpInst::ICMP_SGE:
2716       // Always true.
2717       return getTrue(ITy);
2718     case CmpInst::ICMP_SLT:
2719       // Always false.
2720       return getFalse(ITy);
2721     }
2722   }
2723
2724   // Unsigned variants on "max(a,b)>=a -> true".
2725   P = CmpInst::BAD_ICMP_PREDICATE;
2726   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2727     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2728     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2729     // We analyze this as umax(A, B) pred A.
2730     P = Pred;
2731   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2732              (A == LHS || B == LHS)) {
2733     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2734     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2735     // We analyze this as umax(A, B) swapped-pred A.
2736     P = CmpInst::getSwappedPredicate(Pred);
2737   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2738              (A == RHS || B == RHS)) {
2739     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2740     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2741     // We analyze this as umax(-A, -B) swapped-pred -A.
2742     // Note that we do not need to actually form -A or -B thanks to EqP.
2743     P = CmpInst::getSwappedPredicate(Pred);
2744   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2745              (A == LHS || B == LHS)) {
2746     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2747     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2748     // We analyze this as umax(-A, -B) pred -A.
2749     // Note that we do not need to actually form -A or -B thanks to EqP.
2750     P = Pred;
2751   }
2752   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2753     // Cases correspond to "max(A, B) p A".
2754     switch (P) {
2755     default:
2756       break;
2757     case CmpInst::ICMP_EQ:
2758     case CmpInst::ICMP_ULE:
2759       // Equivalent to "A EqP B".  This may be the same as the condition tested
2760       // in the max/min; if so, we can just return that.
2761       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2762         return V;
2763       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2764         return V;
2765       // Otherwise, see if "A EqP B" simplifies.
2766       if (MaxRecurse)
2767         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2768           return V;
2769       break;
2770     case CmpInst::ICMP_NE:
2771     case CmpInst::ICMP_UGT: {
2772       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2773       // Equivalent to "A InvEqP B".  This may be the same as the condition
2774       // tested in the max/min; if so, we can just return that.
2775       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2776         return V;
2777       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2778         return V;
2779       // Otherwise, see if "A InvEqP B" simplifies.
2780       if (MaxRecurse)
2781         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2782           return V;
2783       break;
2784     }
2785     case CmpInst::ICMP_UGE:
2786       // Always true.
2787       return getTrue(ITy);
2788     case CmpInst::ICMP_ULT:
2789       // Always false.
2790       return getFalse(ITy);
2791     }
2792   }
2793
2794   // Variants on "max(x,y) >= min(x,z)".
2795   Value *C, *D;
2796   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2797       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2798       (A == C || A == D || B == C || B == D)) {
2799     // max(x, ?) pred min(x, ?).
2800     if (Pred == CmpInst::ICMP_SGE)
2801       // Always true.
2802       return getTrue(ITy);
2803     if (Pred == CmpInst::ICMP_SLT)
2804       // Always false.
2805       return getFalse(ITy);
2806   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2807              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2808              (A == C || A == D || B == C || B == D)) {
2809     // min(x, ?) pred max(x, ?).
2810     if (Pred == CmpInst::ICMP_SLE)
2811       // Always true.
2812       return getTrue(ITy);
2813     if (Pred == CmpInst::ICMP_SGT)
2814       // Always false.
2815       return getFalse(ITy);
2816   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2817              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2818              (A == C || A == D || B == C || B == D)) {
2819     // max(x, ?) pred min(x, ?).
2820     if (Pred == CmpInst::ICMP_UGE)
2821       // Always true.
2822       return getTrue(ITy);
2823     if (Pred == CmpInst::ICMP_ULT)
2824       // Always false.
2825       return getFalse(ITy);
2826   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2827              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2828              (A == C || A == D || B == C || B == D)) {
2829     // min(x, ?) pred max(x, ?).
2830     if (Pred == CmpInst::ICMP_ULE)
2831       // Always true.
2832       return getTrue(ITy);
2833     if (Pred == CmpInst::ICMP_UGT)
2834       // Always false.
2835       return getFalse(ITy);
2836   }
2837
2838   // Simplify comparisons of related pointers using a powerful, recursive
2839   // GEP-walk when we have target data available..
2840   if (LHS->getType()->isPointerTy())
2841     if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
2842       return C;
2843
2844   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2845     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2846       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2847           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2848           (ICmpInst::isEquality(Pred) ||
2849            (GLHS->isInBounds() && GRHS->isInBounds() &&
2850             Pred == ICmpInst::getSignedPredicate(Pred)))) {
2851         // The bases are equal and the indices are constant.  Build a constant
2852         // expression GEP with the same indices and a null base pointer to see
2853         // what constant folding can make out of it.
2854         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2855         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2856         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2857
2858         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2859         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2860         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2861       }
2862     }
2863   }
2864
2865   // If the comparison is with the result of a select instruction, check whether
2866   // comparing with either branch of the select always yields the same value.
2867   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2868     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2869       return V;
2870
2871   // If the comparison is with the result of a phi instruction, check whether
2872   // doing the compare with each incoming phi value yields a common result.
2873   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2874     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2875       return V;
2876
2877   return nullptr;
2878 }
2879
2880 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2881                               const DataLayout *DL,
2882                               const TargetLibraryInfo *TLI,
2883                               const DominatorTree *DT,
2884                               AssumptionTracker *AT,
2885                               Instruction *CxtI) {
2886   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2887                             RecursionLimit);
2888 }
2889
2890 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2891 /// fold the result.  If not, this returns null.
2892 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2893                                const Query &Q, unsigned MaxRecurse) {
2894   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2895   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2896
2897   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2898     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2899       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2900
2901     // If we have a constant, make sure it is on the RHS.
2902     std::swap(LHS, RHS);
2903     Pred = CmpInst::getSwappedPredicate(Pred);
2904   }
2905
2906   // Fold trivial predicates.
2907   if (Pred == FCmpInst::FCMP_FALSE)
2908     return ConstantInt::get(GetCompareTy(LHS), 0);
2909   if (Pred == FCmpInst::FCMP_TRUE)
2910     return ConstantInt::get(GetCompareTy(LHS), 1);
2911
2912   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2913     return UndefValue::get(GetCompareTy(LHS));
2914
2915   // fcmp x,x -> true/false.  Not all compares are foldable.
2916   if (LHS == RHS) {
2917     if (CmpInst::isTrueWhenEqual(Pred))
2918       return ConstantInt::get(GetCompareTy(LHS), 1);
2919     if (CmpInst::isFalseWhenEqual(Pred))
2920       return ConstantInt::get(GetCompareTy(LHS), 0);
2921   }
2922
2923   // Handle fcmp with constant RHS
2924   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2925     // If the constant is a nan, see if we can fold the comparison based on it.
2926     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2927       if (CFP->getValueAPF().isNaN()) {
2928         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2929           return ConstantInt::getFalse(CFP->getContext());
2930         assert(FCmpInst::isUnordered(Pred) &&
2931                "Comparison must be either ordered or unordered!");
2932         // True if unordered.
2933         return ConstantInt::getTrue(CFP->getContext());
2934       }
2935       // Check whether the constant is an infinity.
2936       if (CFP->getValueAPF().isInfinity()) {
2937         if (CFP->getValueAPF().isNegative()) {
2938           switch (Pred) {
2939           case FCmpInst::FCMP_OLT:
2940             // No value is ordered and less than negative infinity.
2941             return ConstantInt::getFalse(CFP->getContext());
2942           case FCmpInst::FCMP_UGE:
2943             // All values are unordered with or at least negative infinity.
2944             return ConstantInt::getTrue(CFP->getContext());
2945           default:
2946             break;
2947           }
2948         } else {
2949           switch (Pred) {
2950           case FCmpInst::FCMP_OGT:
2951             // No value is ordered and greater than infinity.
2952             return ConstantInt::getFalse(CFP->getContext());
2953           case FCmpInst::FCMP_ULE:
2954             // All values are unordered with and at most infinity.
2955             return ConstantInt::getTrue(CFP->getContext());
2956           default:
2957             break;
2958           }
2959         }
2960       }
2961     }
2962   }
2963
2964   // If the comparison is with the result of a select instruction, check whether
2965   // comparing with either branch of the select always yields the same value.
2966   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2967     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2968       return V;
2969
2970   // If the comparison is with the result of a phi instruction, check whether
2971   // doing the compare with each incoming phi value yields a common result.
2972   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2973     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2974       return V;
2975
2976   return nullptr;
2977 }
2978
2979 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2980                               const DataLayout *DL,
2981                               const TargetLibraryInfo *TLI,
2982                               const DominatorTree *DT,
2983                               AssumptionTracker *AT,
2984                               const Instruction *CxtI) {
2985   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2986                             RecursionLimit);
2987 }
2988
2989 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2990 /// the result.  If not, this returns null.
2991 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2992                                  Value *FalseVal, const Query &Q,
2993                                  unsigned MaxRecurse) {
2994   // select true, X, Y  -> X
2995   // select false, X, Y -> Y
2996   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2997     if (CB->isAllOnesValue())
2998       return TrueVal;
2999     if (CB->isNullValue())
3000       return FalseVal;
3001   }
3002
3003   // select C, X, X -> X
3004   if (TrueVal == FalseVal)
3005     return TrueVal;
3006
3007   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3008     if (isa<Constant>(TrueVal))
3009       return TrueVal;
3010     return FalseVal;
3011   }
3012   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3013     return FalseVal;
3014   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3015     return TrueVal;
3016
3017   return nullptr;
3018 }
3019
3020 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3021                                 const DataLayout *DL,
3022                                 const TargetLibraryInfo *TLI,
3023                                 const DominatorTree *DT,
3024                                 AssumptionTracker *AT,
3025                                 const Instruction *CxtI) {
3026   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3027                               Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
3028 }
3029
3030 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
3031 /// fold the result.  If not, this returns null.
3032 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
3033   // The type of the GEP pointer operand.
3034   PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
3035   unsigned AS = PtrTy->getAddressSpace();
3036
3037   // getelementptr P -> P.
3038   if (Ops.size() == 1)
3039     return Ops[0];
3040
3041   // Compute the (pointer) type returned by the GEP instruction.
3042   Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
3043   Type *GEPTy = PointerType::get(LastType, AS);
3044   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3045     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3046
3047   if (isa<UndefValue>(Ops[0]))
3048     return UndefValue::get(GEPTy);
3049
3050   if (Ops.size() == 2) {
3051     // getelementptr P, 0 -> P.
3052     if (match(Ops[1], m_Zero()))
3053       return Ops[0];
3054
3055     Type *Ty = PtrTy->getElementType();
3056     if (Q.DL && Ty->isSized()) {
3057       Value *P;
3058       uint64_t C;
3059       uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
3060       // getelementptr P, N -> P if P points to a type of zero size.
3061       if (TyAllocSize == 0)
3062         return Ops[0];
3063
3064       // The following transforms are only safe if the ptrtoint cast
3065       // doesn't truncate the pointers.
3066       if (Ops[1]->getType()->getScalarSizeInBits() ==
3067           Q.DL->getPointerSizeInBits(AS)) {
3068         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3069           if (match(P, m_Zero()))
3070             return Constant::getNullValue(GEPTy);
3071           Value *Temp;
3072           if (match(P, m_PtrToInt(m_Value(Temp))))
3073             if (Temp->getType() == GEPTy)
3074               return Temp;
3075           return nullptr;
3076         };
3077
3078         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3079         if (TyAllocSize == 1 &&
3080             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3081           if (Value *R = PtrToIntOrZero(P))
3082             return R;
3083
3084         // getelementptr V, (ashr (sub P, V), C) -> Q
3085         // if P points to a type of size 1 << C.
3086         if (match(Ops[1],
3087                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3088                          m_ConstantInt(C))) &&
3089             TyAllocSize == 1ULL << C)
3090           if (Value *R = PtrToIntOrZero(P))
3091             return R;
3092
3093         // getelementptr V, (sdiv (sub P, V), C) -> Q
3094         // if P points to a type of size C.
3095         if (match(Ops[1],
3096                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3097                          m_SpecificInt(TyAllocSize))))
3098           if (Value *R = PtrToIntOrZero(P))
3099             return R;
3100       }
3101     }
3102   }
3103
3104   // Check to see if this is constant foldable.
3105   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3106     if (!isa<Constant>(Ops[i]))
3107       return nullptr;
3108
3109   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
3110 }
3111
3112 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
3113                              const TargetLibraryInfo *TLI,
3114                              const DominatorTree *DT, AssumptionTracker *AT,
3115                              const Instruction *CxtI) {
3116   return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
3117 }
3118
3119 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
3120 /// can fold the result.  If not, this returns null.
3121 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3122                                       ArrayRef<unsigned> Idxs, const Query &Q,
3123                                       unsigned) {
3124   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3125     if (Constant *CVal = dyn_cast<Constant>(Val))
3126       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3127
3128   // insertvalue x, undef, n -> x
3129   if (match(Val, m_Undef()))
3130     return Agg;
3131
3132   // insertvalue x, (extractvalue y, n), n
3133   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3134     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3135         EV->getIndices() == Idxs) {
3136       // insertvalue undef, (extractvalue y, n), n -> y
3137       if (match(Agg, m_Undef()))
3138         return EV->getAggregateOperand();
3139
3140       // insertvalue y, (extractvalue y, n), n -> y
3141       if (Agg == EV->getAggregateOperand())
3142         return Agg;
3143     }
3144
3145   return nullptr;
3146 }
3147
3148 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3149                                      ArrayRef<unsigned> Idxs,
3150                                      const DataLayout *DL,
3151                                      const TargetLibraryInfo *TLI,
3152                                      const DominatorTree *DT,
3153                                      AssumptionTracker *AT,
3154                                      const Instruction *CxtI) {
3155   return ::SimplifyInsertValueInst(Agg, Val, Idxs,
3156                                    Query (DL, TLI, DT, AT, CxtI),
3157                                    RecursionLimit);
3158 }
3159
3160 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
3161 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3162   // If all of the PHI's incoming values are the same then replace the PHI node
3163   // with the common value.
3164   Value *CommonValue = nullptr;
3165   bool HasUndefInput = false;
3166   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3167     Value *Incoming = PN->getIncomingValue(i);
3168     // If the incoming value is the phi node itself, it can safely be skipped.
3169     if (Incoming == PN) continue;
3170     if (isa<UndefValue>(Incoming)) {
3171       // Remember that we saw an undef value, but otherwise ignore them.
3172       HasUndefInput = true;
3173       continue;
3174     }
3175     if (CommonValue && Incoming != CommonValue)
3176       return nullptr;  // Not the same, bail out.
3177     CommonValue = Incoming;
3178   }
3179
3180   // If CommonValue is null then all of the incoming values were either undef or
3181   // equal to the phi node itself.
3182   if (!CommonValue)
3183     return UndefValue::get(PN->getType());
3184
3185   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3186   // instruction, we cannot return X as the result of the PHI node unless it
3187   // dominates the PHI block.
3188   if (HasUndefInput)
3189     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3190
3191   return CommonValue;
3192 }
3193
3194 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3195   if (Constant *C = dyn_cast<Constant>(Op))
3196     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
3197
3198   return nullptr;
3199 }
3200
3201 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
3202                                const TargetLibraryInfo *TLI,
3203                                const DominatorTree *DT,
3204                                AssumptionTracker *AT,
3205                                const Instruction *CxtI) {
3206   return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
3207                              RecursionLimit);
3208 }
3209
3210 //=== Helper functions for higher up the class hierarchy.
3211
3212 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
3213 /// fold the result.  If not, this returns null.
3214 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3215                             const Query &Q, unsigned MaxRecurse) {
3216   switch (Opcode) {
3217   case Instruction::Add:
3218     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3219                            Q, MaxRecurse);
3220   case Instruction::FAdd:
3221     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3222
3223   case Instruction::Sub:
3224     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3225                            Q, MaxRecurse);
3226   case Instruction::FSub:
3227     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3228
3229   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3230   case Instruction::FMul:
3231     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3232   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3233   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3234   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
3235   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3236   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3237   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
3238   case Instruction::Shl:
3239     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3240                            Q, MaxRecurse);
3241   case Instruction::LShr:
3242     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3243   case Instruction::AShr:
3244     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3245   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3246   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3247   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3248   default:
3249     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3250       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3251         Constant *COps[] = {CLHS, CRHS};
3252         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
3253                                         Q.TLI);
3254       }
3255
3256     // If the operation is associative, try some generic simplifications.
3257     if (Instruction::isAssociative(Opcode))
3258       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3259         return V;
3260
3261     // If the operation is with the result of a select instruction check whether
3262     // operating on either branch of the select always yields the same value.
3263     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3264       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3265         return V;
3266
3267     // If the operation is with the result of a phi instruction, check whether
3268     // operating on all incoming values of the phi always yields the same value.
3269     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3270       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3271         return V;
3272
3273     return nullptr;
3274   }
3275 }
3276
3277 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3278                            const DataLayout *DL, const TargetLibraryInfo *TLI,
3279                            const DominatorTree *DT, AssumptionTracker *AT,
3280                            const Instruction *CxtI) {
3281   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3282                          RecursionLimit);
3283 }
3284
3285 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3286 /// fold the result.
3287 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3288                               const Query &Q, unsigned MaxRecurse) {
3289   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3290     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3291   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3292 }
3293
3294 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3295                              const DataLayout *DL, const TargetLibraryInfo *TLI,
3296                              const DominatorTree *DT, AssumptionTracker *AT,
3297                              const Instruction *CxtI) {
3298   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3299                            RecursionLimit);
3300 }
3301
3302 static bool IsIdempotent(Intrinsic::ID ID) {
3303   switch (ID) {
3304   default: return false;
3305
3306   // Unary idempotent: f(f(x)) = f(x)
3307   case Intrinsic::fabs:
3308   case Intrinsic::floor:
3309   case Intrinsic::ceil:
3310   case Intrinsic::trunc:
3311   case Intrinsic::rint:
3312   case Intrinsic::nearbyint:
3313   case Intrinsic::round:
3314     return true;
3315   }
3316 }
3317
3318 template <typename IterTy>
3319 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3320                                 const Query &Q, unsigned MaxRecurse) {
3321   // Perform idempotent optimizations
3322   if (!IsIdempotent(IID))
3323     return nullptr;
3324
3325   // Unary Ops
3326   if (std::distance(ArgBegin, ArgEnd) == 1)
3327     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3328       if (II->getIntrinsicID() == IID)
3329         return II;
3330
3331   return nullptr;
3332 }
3333
3334 template <typename IterTy>
3335 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3336                            const Query &Q, unsigned MaxRecurse) {
3337   Type *Ty = V->getType();
3338   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3339     Ty = PTy->getElementType();
3340   FunctionType *FTy = cast<FunctionType>(Ty);
3341
3342   // call undef -> undef
3343   if (isa<UndefValue>(V))
3344     return UndefValue::get(FTy->getReturnType());
3345
3346   Function *F = dyn_cast<Function>(V);
3347   if (!F)
3348     return nullptr;
3349
3350   if (unsigned IID = F->getIntrinsicID())
3351     if (Value *Ret =
3352         SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3353       return Ret;
3354
3355   if (!canConstantFoldCallTo(F))
3356     return nullptr;
3357
3358   SmallVector<Constant *, 4> ConstantArgs;
3359   ConstantArgs.reserve(ArgEnd - ArgBegin);
3360   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3361     Constant *C = dyn_cast<Constant>(*I);
3362     if (!C)
3363       return nullptr;
3364     ConstantArgs.push_back(C);
3365   }
3366
3367   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3368 }
3369
3370 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3371                           User::op_iterator ArgEnd, const DataLayout *DL,
3372                           const TargetLibraryInfo *TLI,
3373                           const DominatorTree *DT, AssumptionTracker *AT,
3374                           const Instruction *CxtI) {
3375   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
3376                         RecursionLimit);
3377 }
3378
3379 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3380                           const DataLayout *DL, const TargetLibraryInfo *TLI,
3381                           const DominatorTree *DT, AssumptionTracker *AT,
3382                           const Instruction *CxtI) {
3383   return ::SimplifyCall(V, Args.begin(), Args.end(),
3384                         Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
3385 }
3386
3387 /// SimplifyInstruction - See if we can compute a simplified version of this
3388 /// instruction.  If not, this returns null.
3389 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
3390                                  const TargetLibraryInfo *TLI,
3391                                  const DominatorTree *DT,
3392                                  AssumptionTracker *AT) {
3393   Value *Result;
3394
3395   switch (I->getOpcode()) {
3396   default:
3397     Result = ConstantFoldInstruction(I, DL, TLI);
3398     break;
3399   case Instruction::FAdd:
3400     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3401                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
3402     break;
3403   case Instruction::Add:
3404     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3405                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3406                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3407                              DL, TLI, DT, AT, I);
3408     break;
3409   case Instruction::FSub:
3410     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3411                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
3412     break;
3413   case Instruction::Sub:
3414     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3415                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3416                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3417                              DL, TLI, DT, AT, I);
3418     break;
3419   case Instruction::FMul:
3420     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3421                               I->getFastMathFlags(), DL, TLI, DT, AT, I);
3422     break;
3423   case Instruction::Mul:
3424     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
3425                              DL, TLI, DT, AT, I);
3426     break;
3427   case Instruction::SDiv:
3428     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
3429                               DL, TLI, DT, AT, I);
3430     break;
3431   case Instruction::UDiv:
3432     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
3433                               DL, TLI, DT, AT, I);
3434     break;
3435   case Instruction::FDiv:
3436     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3437                               DL, TLI, DT, AT, I);
3438     break;
3439   case Instruction::SRem:
3440     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
3441                               DL, TLI, DT, AT, I);
3442     break;
3443   case Instruction::URem:
3444     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
3445                               DL, TLI, DT, AT, I);
3446     break;
3447   case Instruction::FRem:
3448     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3449                               DL, TLI, DT, AT, I);
3450     break;
3451   case Instruction::Shl:
3452     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3453                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3454                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3455                              DL, TLI, DT, AT, I);
3456     break;
3457   case Instruction::LShr:
3458     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3459                               cast<BinaryOperator>(I)->isExact(),
3460                               DL, TLI, DT, AT, I);
3461     break;
3462   case Instruction::AShr:
3463     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3464                               cast<BinaryOperator>(I)->isExact(),
3465                               DL, TLI, DT, AT, I);
3466     break;
3467   case Instruction::And:
3468     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
3469                              DL, TLI, DT, AT, I);
3470     break;
3471   case Instruction::Or:
3472     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3473                             AT, I);
3474     break;
3475   case Instruction::Xor:
3476     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
3477                              DL, TLI, DT, AT, I);
3478     break;
3479   case Instruction::ICmp:
3480     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3481                               I->getOperand(0), I->getOperand(1),
3482                               DL, TLI, DT, AT, I);
3483     break;
3484   case Instruction::FCmp:
3485     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3486                               I->getOperand(0), I->getOperand(1),
3487                               DL, TLI, DT, AT, I);
3488     break;
3489   case Instruction::Select:
3490     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3491                                 I->getOperand(2), DL, TLI, DT, AT, I);
3492     break;
3493   case Instruction::GetElementPtr: {
3494     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3495     Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
3496     break;
3497   }
3498   case Instruction::InsertValue: {
3499     InsertValueInst *IV = cast<InsertValueInst>(I);
3500     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3501                                      IV->getInsertedValueOperand(),
3502                                      IV->getIndices(), DL, TLI, DT, AT, I);
3503     break;
3504   }
3505   case Instruction::PHI:
3506     Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
3507     break;
3508   case Instruction::Call: {
3509     CallSite CS(cast<CallInst>(I));
3510     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3511                           DL, TLI, DT, AT, I);
3512     break;
3513   }
3514   case Instruction::Trunc:
3515     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
3516                                AT, I);
3517     break;
3518   }
3519
3520   /// If called on unreachable code, the above logic may report that the
3521   /// instruction simplified to itself.  Make life easier for users by
3522   /// detecting that case here, returning a safe value instead.
3523   return Result == I ? UndefValue::get(I->getType()) : Result;
3524 }
3525
3526 /// \brief Implementation of recursive simplification through an instructions
3527 /// uses.
3528 ///
3529 /// This is the common implementation of the recursive simplification routines.
3530 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3531 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3532 /// instructions to process and attempt to simplify it using
3533 /// InstructionSimplify.
3534 ///
3535 /// This routine returns 'true' only when *it* simplifies something. The passed
3536 /// in simplified value does not count toward this.
3537 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3538                                               const DataLayout *DL,
3539                                               const TargetLibraryInfo *TLI,
3540                                               const DominatorTree *DT,
3541                                               AssumptionTracker *AT) {
3542   bool Simplified = false;
3543   SmallSetVector<Instruction *, 8> Worklist;
3544
3545   // If we have an explicit value to collapse to, do that round of the
3546   // simplification loop by hand initially.
3547   if (SimpleV) {
3548     for (User *U : I->users())
3549       if (U != I)
3550         Worklist.insert(cast<Instruction>(U));
3551
3552     // Replace the instruction with its simplified value.
3553     I->replaceAllUsesWith(SimpleV);
3554
3555     // Gracefully handle edge cases where the instruction is not wired into any
3556     // parent block.
3557     if (I->getParent())
3558       I->eraseFromParent();
3559   } else {
3560     Worklist.insert(I);
3561   }
3562
3563   // Note that we must test the size on each iteration, the worklist can grow.
3564   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3565     I = Worklist[Idx];
3566
3567     // See if this instruction simplifies.
3568     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
3569     if (!SimpleV)
3570       continue;
3571
3572     Simplified = true;
3573
3574     // Stash away all the uses of the old instruction so we can check them for
3575     // recursive simplifications after a RAUW. This is cheaper than checking all
3576     // uses of To on the recursive step in most cases.
3577     for (User *U : I->users())
3578       Worklist.insert(cast<Instruction>(U));
3579
3580     // Replace the instruction with its simplified value.
3581     I->replaceAllUsesWith(SimpleV);
3582
3583     // Gracefully handle edge cases where the instruction is not wired into any
3584     // parent block.
3585     if (I->getParent())
3586       I->eraseFromParent();
3587   }
3588   return Simplified;
3589 }
3590
3591 bool llvm::recursivelySimplifyInstruction(Instruction *I,
3592                                           const DataLayout *DL,
3593                                           const TargetLibraryInfo *TLI,
3594                                           const DominatorTree *DT,
3595                                           AssumptionTracker *AT) {
3596   return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
3597 }
3598
3599 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3600                                          const DataLayout *DL,
3601                                          const TargetLibraryInfo *TLI,
3602                                          const DominatorTree *DT,
3603                                          AssumptionTracker *AT) {
3604   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3605   assert(SimpleV && "Must provide a simplified value.");
3606   return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);
3607 }