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