83881deccf4069253c9e6454d22708db16195ebd
[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 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Support/ConstantRange.h"
28 #include "llvm/Support/PatternMatch.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Target/TargetData.h"
31 using namespace llvm;
32 using namespace llvm::PatternMatch;
33
34 enum { RecursionLimit = 3 };
35
36 STATISTIC(NumExpand,  "Number of expansions");
37 STATISTIC(NumFactor , "Number of factorizations");
38 STATISTIC(NumReassoc, "Number of reassociations");
39
40 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41                               const DominatorTree *, unsigned);
42 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
43                             const DominatorTree *, unsigned);
44 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
45                               const DominatorTree *, unsigned);
46 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47                              const DominatorTree *, unsigned);
48 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49                               const DominatorTree *, unsigned);
50
51 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
52 /// a vector with every element false, as appropriate for the type.
53 static Constant *getFalse(Type *Ty) {
54   assert((Ty->isIntegerTy(1) ||
55           (Ty->isVectorTy() &&
56            cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
57          "Expected i1 type or a vector of i1!");
58   return Constant::getNullValue(Ty);
59 }
60
61 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
62 /// a vector with every element true, as appropriate for the type.
63 static Constant *getTrue(Type *Ty) {
64   assert((Ty->isIntegerTy(1) ||
65           (Ty->isVectorTy() &&
66            cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
67          "Expected i1 type or a vector of i1!");
68   return Constant::getAllOnesValue(Ty);
69 }
70
71 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
72 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
73   Instruction *I = dyn_cast<Instruction>(V);
74   if (!I)
75     // Arguments and constants dominate all instructions.
76     return true;
77
78   // If we have a DominatorTree then do a precise test.
79   if (DT)
80     return DT->dominates(I, P);
81
82   // Otherwise, if the instruction is in the entry block, and is not an invoke,
83   // then it obviously dominates all phi nodes.
84   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
85       !isa<InvokeInst>(I))
86     return true;
87
88   return false;
89 }
90
91 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
92 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
93 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
94 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
95 /// Returns the simplified value, or null if no simplification was performed.
96 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
97                           unsigned OpcToExpand, const TargetData *TD,
98                           const DominatorTree *DT, unsigned MaxRecurse) {
99   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
100   // Recursion is always used, so bail out at once if we already hit the limit.
101   if (!MaxRecurse--)
102     return 0;
103
104   // Check whether the expression has the form "(A op' B) op C".
105   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
106     if (Op0->getOpcode() == OpcodeToExpand) {
107       // It does!  Try turning it into "(A op C) op' (B op C)".
108       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
109       // Do "A op C" and "B op C" both simplify?
110       if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
111         if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
112           // They do! Return "L op' R" if it simplifies or is already available.
113           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
114           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
115                                      && L == B && R == A)) {
116             ++NumExpand;
117             return LHS;
118           }
119           // Otherwise return "L op' R" if it simplifies.
120           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
121                                        MaxRecurse)) {
122             ++NumExpand;
123             return V;
124           }
125         }
126     }
127
128   // Check whether the expression has the form "A op (B op' C)".
129   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
130     if (Op1->getOpcode() == OpcodeToExpand) {
131       // It does!  Try turning it into "(A op B) op' (A op C)".
132       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
133       // Do "A op B" and "A op C" both simplify?
134       if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
135         if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
136           // They do! Return "L op' R" if it simplifies or is already available.
137           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
138           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
139                                      && L == C && R == B)) {
140             ++NumExpand;
141             return RHS;
142           }
143           // Otherwise return "L op' R" if it simplifies.
144           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
145                                        MaxRecurse)) {
146             ++NumExpand;
147             return V;
148           }
149         }
150     }
151
152   return 0;
153 }
154
155 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
156 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
157 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
158 /// Returns the simplified value, or null if no simplification was performed.
159 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
160                              unsigned OpcToExtract, const TargetData *TD,
161                              const DominatorTree *DT, unsigned MaxRecurse) {
162   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
163   // Recursion is always used, so bail out at once if we already hit the limit.
164   if (!MaxRecurse--)
165     return 0;
166
167   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
168   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
169
170   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
171       !Op1 || Op1->getOpcode() != OpcodeToExtract)
172     return 0;
173
174   // The expression has the form "(A op' B) op (C op' D)".
175   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
176   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
177
178   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
179   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
180   // commutative case, "(A op' B) op (C op' A)"?
181   if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
182     Value *DD = A == C ? D : C;
183     // Form "A op' (B op DD)" if it simplifies completely.
184     // Does "B op DD" simplify?
185     if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
186       // It does!  Return "A op' V" if it simplifies or is already available.
187       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
188       // "A op' V" is just the RHS.
189       if (V == B || V == DD) {
190         ++NumFactor;
191         return V == B ? LHS : RHS;
192       }
193       // Otherwise return "A op' V" if it simplifies.
194       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
195         ++NumFactor;
196         return W;
197       }
198     }
199   }
200
201   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
202   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
203   // commutative case, "(A op' B) op (B op' D)"?
204   if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
205     Value *CC = B == D ? C : D;
206     // Form "(A op CC) op' B" if it simplifies completely..
207     // Does "A op CC" simplify?
208     if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
209       // It does!  Return "V op' B" if it simplifies or is already available.
210       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
211       // "V op' B" is just the RHS.
212       if (V == A || V == CC) {
213         ++NumFactor;
214         return V == A ? LHS : RHS;
215       }
216       // Otherwise return "V op' B" if it simplifies.
217       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
218         ++NumFactor;
219         return W;
220       }
221     }
222   }
223
224   return 0;
225 }
226
227 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
228 /// operations.  Returns the simpler value, or null if none was found.
229 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
230                                        const TargetData *TD,
231                                        const DominatorTree *DT,
232                                        unsigned MaxRecurse) {
233   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
234   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
235
236   // Recursion is always used, so bail out at once if we already hit the limit.
237   if (!MaxRecurse--)
238     return 0;
239
240   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
241   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
242
243   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
244   if (Op0 && Op0->getOpcode() == Opcode) {
245     Value *A = Op0->getOperand(0);
246     Value *B = Op0->getOperand(1);
247     Value *C = RHS;
248
249     // Does "B op C" simplify?
250     if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
251       // It does!  Return "A op V" if it simplifies or is already available.
252       // If V equals B then "A op V" is just the LHS.
253       if (V == B) return LHS;
254       // Otherwise return "A op V" if it simplifies.
255       if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
256         ++NumReassoc;
257         return W;
258       }
259     }
260   }
261
262   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
263   if (Op1 && Op1->getOpcode() == Opcode) {
264     Value *A = LHS;
265     Value *B = Op1->getOperand(0);
266     Value *C = Op1->getOperand(1);
267
268     // Does "A op B" simplify?
269     if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
270       // It does!  Return "V op C" if it simplifies or is already available.
271       // If V equals B then "V op C" is just the RHS.
272       if (V == B) return RHS;
273       // Otherwise return "V op C" if it simplifies.
274       if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
275         ++NumReassoc;
276         return W;
277       }
278     }
279   }
280
281   // The remaining transforms require commutativity as well as associativity.
282   if (!Instruction::isCommutative(Opcode))
283     return 0;
284
285   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
286   if (Op0 && Op0->getOpcode() == Opcode) {
287     Value *A = Op0->getOperand(0);
288     Value *B = Op0->getOperand(1);
289     Value *C = RHS;
290
291     // Does "C op A" simplify?
292     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
293       // It does!  Return "V op B" if it simplifies or is already available.
294       // If V equals A then "V op B" is just the LHS.
295       if (V == A) return LHS;
296       // Otherwise return "V op B" if it simplifies.
297       if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
298         ++NumReassoc;
299         return W;
300       }
301     }
302   }
303
304   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
305   if (Op1 && Op1->getOpcode() == Opcode) {
306     Value *A = LHS;
307     Value *B = Op1->getOperand(0);
308     Value *C = Op1->getOperand(1);
309
310     // Does "C op A" simplify?
311     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
312       // It does!  Return "B op V" if it simplifies or is already available.
313       // If V equals C then "B op V" is just the RHS.
314       if (V == C) return RHS;
315       // Otherwise return "B op V" if it simplifies.
316       if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
317         ++NumReassoc;
318         return W;
319       }
320     }
321   }
322
323   return 0;
324 }
325
326 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
327 /// instruction as an operand, try to simplify the binop by seeing whether
328 /// evaluating it on both branches of the select results in the same value.
329 /// Returns the common value if so, otherwise returns null.
330 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
331                                     const TargetData *TD,
332                                     const DominatorTree *DT,
333                                     unsigned MaxRecurse) {
334   // Recursion is always used, so bail out at once if we already hit the limit.
335   if (!MaxRecurse--)
336     return 0;
337
338   SelectInst *SI;
339   if (isa<SelectInst>(LHS)) {
340     SI = cast<SelectInst>(LHS);
341   } else {
342     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
343     SI = cast<SelectInst>(RHS);
344   }
345
346   // Evaluate the BinOp on the true and false branches of the select.
347   Value *TV;
348   Value *FV;
349   if (SI == LHS) {
350     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
351     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
352   } else {
353     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
354     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
355   }
356
357   // If they simplified to the same value, then return the common value.
358   // If they both failed to simplify then return null.
359   if (TV == FV)
360     return TV;
361
362   // If one branch simplified to undef, return the other one.
363   if (TV && isa<UndefValue>(TV))
364     return FV;
365   if (FV && isa<UndefValue>(FV))
366     return TV;
367
368   // If applying the operation did not change the true and false select values,
369   // then the result of the binop is the select itself.
370   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
371     return SI;
372
373   // If one branch simplified and the other did not, and the simplified
374   // value is equal to the unsimplified one, return the simplified value.
375   // For example, select (cond, X, X & Z) & Z -> X & Z.
376   if ((FV && !TV) || (TV && !FV)) {
377     // Check that the simplified value has the form "X op Y" where "op" is the
378     // same as the original operation.
379     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
380     if (Simplified && Simplified->getOpcode() == Opcode) {
381       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
382       // We already know that "op" is the same as for the simplified value.  See
383       // if the operands match too.  If so, return the simplified value.
384       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
385       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
386       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
387       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
388           Simplified->getOperand(1) == UnsimplifiedRHS)
389         return Simplified;
390       if (Simplified->isCommutative() &&
391           Simplified->getOperand(1) == UnsimplifiedLHS &&
392           Simplified->getOperand(0) == UnsimplifiedRHS)
393         return Simplified;
394     }
395   }
396
397   return 0;
398 }
399
400 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
401 /// try to simplify the comparison by seeing whether both branches of the select
402 /// result in the same value.  Returns the common value if so, otherwise returns
403 /// null.
404 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
405                                   Value *RHS, const TargetData *TD,
406                                   const DominatorTree *DT,
407                                   unsigned MaxRecurse) {
408   // Recursion is always used, so bail out at once if we already hit the limit.
409   if (!MaxRecurse--)
410     return 0;
411
412   // Make sure the select is on the LHS.
413   if (!isa<SelectInst>(LHS)) {
414     std::swap(LHS, RHS);
415     Pred = CmpInst::getSwappedPredicate(Pred);
416   }
417   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
418   SelectInst *SI = cast<SelectInst>(LHS);
419   Value *Cond = SI->getCondition();
420   Value *TV = SI->getTrueValue();
421   Value *FV = SI->getFalseValue();
422
423   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
424   // Does "cmp TV, RHS" simplify?
425   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, DT, MaxRecurse);
426   if (!TCmp) {
427     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
428     // condition itself then we can replace it with 'true'.
429     if (match(Cond, m_ICmp(Pred, m_Specific(TV), m_Specific(RHS))))
430       TCmp = getTrue(Cond->getType());
431   }
432   if (!TCmp)
433     return 0;
434
435   // Does "cmp FV, RHS" simplify?
436   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, DT, MaxRecurse);
437   if (!FCmp) {
438     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
439     // condition itself then we can replace it with 'false'.
440     if (match(Cond, m_ICmp(Pred, m_Specific(FV), m_Specific(RHS))))
441       FCmp = getFalse(Cond->getType());
442   }
443   if (!FCmp)
444     return 0;
445
446   // If both sides simplified to the same value, then use it as the result of
447   // the original comparison.
448   if (TCmp == FCmp)
449     return TCmp;
450   // If the false value simplified to false, then the result of the compare
451   // is equal to "Cond && TCmp".  This also catches the case when the false
452   // value simplified to false and the true value to true, returning "Cond".
453   if (match(FCmp, m_Zero()))
454     if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
455       return V;
456   // If the true value simplified to true, then the result of the compare
457   // is equal to "Cond || FCmp".
458   if (match(TCmp, m_One()))
459     if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
460       return V;
461   // Finally, if the false value simplified to true and the true value to
462   // false, then the result of the compare is equal to "!Cond".
463   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
464     if (Value *V =
465         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
466                         TD, DT, MaxRecurse))
467       return V;
468
469   return 0;
470 }
471
472 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
473 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
474 /// it on the incoming phi values yields the same result for every value.  If so
475 /// returns the common value, otherwise returns null.
476 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
477                                  const TargetData *TD, const DominatorTree *DT,
478                                  unsigned MaxRecurse) {
479   // Recursion is always used, so bail out at once if we already hit the limit.
480   if (!MaxRecurse--)
481     return 0;
482
483   PHINode *PI;
484   if (isa<PHINode>(LHS)) {
485     PI = cast<PHINode>(LHS);
486     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
487     if (!ValueDominatesPHI(RHS, PI, DT))
488       return 0;
489   } else {
490     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
491     PI = cast<PHINode>(RHS);
492     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
493     if (!ValueDominatesPHI(LHS, PI, DT))
494       return 0;
495   }
496
497   // Evaluate the BinOp on the incoming phi values.
498   Value *CommonValue = 0;
499   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
500     Value *Incoming = PI->getIncomingValue(i);
501     // If the incoming value is the phi node itself, it can safely be skipped.
502     if (Incoming == PI) continue;
503     Value *V = PI == LHS ?
504       SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
505       SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
506     // If the operation failed to simplify, or simplified to a different value
507     // to previously, then give up.
508     if (!V || (CommonValue && V != CommonValue))
509       return 0;
510     CommonValue = V;
511   }
512
513   return CommonValue;
514 }
515
516 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
517 /// try to simplify the comparison by seeing whether comparing with all of the
518 /// incoming phi values yields the same result every time.  If so returns the
519 /// common result, otherwise returns null.
520 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
521                                const TargetData *TD, const DominatorTree *DT,
522                                unsigned MaxRecurse) {
523   // Recursion is always used, so bail out at once if we already hit the limit.
524   if (!MaxRecurse--)
525     return 0;
526
527   // Make sure the phi is on the LHS.
528   if (!isa<PHINode>(LHS)) {
529     std::swap(LHS, RHS);
530     Pred = CmpInst::getSwappedPredicate(Pred);
531   }
532   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
533   PHINode *PI = cast<PHINode>(LHS);
534
535   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
536   if (!ValueDominatesPHI(RHS, PI, DT))
537     return 0;
538
539   // Evaluate the BinOp on the incoming phi values.
540   Value *CommonValue = 0;
541   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
542     Value *Incoming = PI->getIncomingValue(i);
543     // If the incoming value is the phi node itself, it can safely be skipped.
544     if (Incoming == PI) continue;
545     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
546     // If the operation failed to simplify, or simplified to a different value
547     // to previously, then give up.
548     if (!V || (CommonValue && V != CommonValue))
549       return 0;
550     CommonValue = V;
551   }
552
553   return CommonValue;
554 }
555
556 /// SimplifyAddInst - Given operands for an Add, see if we can
557 /// fold the result.  If not, this returns null.
558 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
559                               const TargetData *TD, const DominatorTree *DT,
560                               unsigned MaxRecurse) {
561   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
562     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
563       Constant *Ops[] = { CLHS, CRHS };
564       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
565                                       Ops, TD);
566     }
567
568     // Canonicalize the constant to the RHS.
569     std::swap(Op0, Op1);
570   }
571
572   // X + undef -> undef
573   if (match(Op1, m_Undef()))
574     return Op1;
575
576   // X + 0 -> X
577   if (match(Op1, m_Zero()))
578     return Op0;
579
580   // X + (Y - X) -> Y
581   // (Y - X) + X -> Y
582   // Eg: X + -X -> 0
583   Value *Y = 0;
584   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
585       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
586     return Y;
587
588   // X + ~X -> -1   since   ~X = -X-1
589   if (match(Op0, m_Not(m_Specific(Op1))) ||
590       match(Op1, m_Not(m_Specific(Op0))))
591     return Constant::getAllOnesValue(Op0->getType());
592
593   /// i1 add -> xor.
594   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
595     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
596       return V;
597
598   // Try some generic simplifications for associative operations.
599   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
600                                           MaxRecurse))
601     return V;
602
603   // Mul distributes over Add.  Try some generic simplifications based on this.
604   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
605                                 TD, DT, MaxRecurse))
606     return V;
607
608   // Threading Add over selects and phi nodes is pointless, so don't bother.
609   // Threading over the select in "A + select(cond, B, C)" means evaluating
610   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
611   // only if B and C are equal.  If B and C are equal then (since we assume
612   // that operands have already been simplified) "select(cond, B, C)" should
613   // have been simplified to the common value of B and C already.  Analysing
614   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
615   // for threading over phi nodes.
616
617   return 0;
618 }
619
620 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
621                              const TargetData *TD, const DominatorTree *DT) {
622   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
623 }
624
625 /// SimplifySubInst - Given operands for a Sub, see if we can
626 /// fold the result.  If not, this returns null.
627 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
628                               const TargetData *TD, const DominatorTree *DT,
629                               unsigned MaxRecurse) {
630   if (Constant *CLHS = dyn_cast<Constant>(Op0))
631     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
632       Constant *Ops[] = { CLHS, CRHS };
633       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
634                                       Ops, TD);
635     }
636
637   // X - undef -> undef
638   // undef - X -> undef
639   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
640     return UndefValue::get(Op0->getType());
641
642   // X - 0 -> X
643   if (match(Op1, m_Zero()))
644     return Op0;
645
646   // X - X -> 0
647   if (Op0 == Op1)
648     return Constant::getNullValue(Op0->getType());
649
650   // (X*2) - X -> X
651   // (X<<1) - X -> X
652   Value *X = 0;
653   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
654       match(Op0, m_Shl(m_Specific(Op1), m_One())))
655     return Op1;
656
657   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
658   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
659   Value *Y = 0, *Z = Op1;
660   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
661     // See if "V === Y - Z" simplifies.
662     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
663       // It does!  Now see if "X + V" simplifies.
664       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
665                                    MaxRecurse-1)) {
666         // It does, we successfully reassociated!
667         ++NumReassoc;
668         return W;
669       }
670     // See if "V === X - Z" simplifies.
671     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
672       // It does!  Now see if "Y + V" simplifies.
673       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
674                                    MaxRecurse-1)) {
675         // It does, we successfully reassociated!
676         ++NumReassoc;
677         return W;
678       }
679   }
680
681   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
682   // For example, X - (X + 1) -> -1
683   X = Op0;
684   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
685     // See if "V === X - Y" simplifies.
686     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
687       // It does!  Now see if "V - Z" simplifies.
688       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
689                                    MaxRecurse-1)) {
690         // It does, we successfully reassociated!
691         ++NumReassoc;
692         return W;
693       }
694     // See if "V === X - Z" simplifies.
695     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
696       // It does!  Now see if "V - Y" simplifies.
697       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
698                                    MaxRecurse-1)) {
699         // It does, we successfully reassociated!
700         ++NumReassoc;
701         return W;
702       }
703   }
704
705   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
706   // For example, X - (X - Y) -> Y.
707   Z = Op0;
708   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
709     // See if "V === Z - X" simplifies.
710     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
711       // It does!  Now see if "V + Y" simplifies.
712       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
713                                    MaxRecurse-1)) {
714         // It does, we successfully reassociated!
715         ++NumReassoc;
716         return W;
717       }
718
719   // Mul distributes over Sub.  Try some generic simplifications based on this.
720   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
721                                 TD, DT, MaxRecurse))
722     return V;
723
724   // i1 sub -> xor.
725   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
726     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
727       return V;
728
729   // Threading Sub over selects and phi nodes is pointless, so don't bother.
730   // Threading over the select in "A - select(cond, B, C)" means evaluating
731   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
732   // only if B and C are equal.  If B and C are equal then (since we assume
733   // that operands have already been simplified) "select(cond, B, C)" should
734   // have been simplified to the common value of B and C already.  Analysing
735   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
736   // for threading over phi nodes.
737
738   return 0;
739 }
740
741 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
742                              const TargetData *TD, const DominatorTree *DT) {
743   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
744 }
745
746 /// SimplifyMulInst - Given operands for a Mul, see if we can
747 /// fold the result.  If not, this returns null.
748 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
749                               const DominatorTree *DT, unsigned MaxRecurse) {
750   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
751     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
752       Constant *Ops[] = { CLHS, CRHS };
753       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
754                                       Ops, TD);
755     }
756
757     // Canonicalize the constant to the RHS.
758     std::swap(Op0, Op1);
759   }
760
761   // X * undef -> 0
762   if (match(Op1, m_Undef()))
763     return Constant::getNullValue(Op0->getType());
764
765   // X * 0 -> 0
766   if (match(Op1, m_Zero()))
767     return Op1;
768
769   // X * 1 -> X
770   if (match(Op1, m_One()))
771     return Op0;
772
773   // (X / Y) * Y -> X if the division is exact.
774   Value *X = 0, *Y = 0;
775   if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
776       (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
777     PossiblyExactOperator *Div =
778       cast<PossiblyExactOperator>(Y == Op1 ? Op0 : Op1);
779     if (Div->isExact())
780       return X;
781   }
782
783   // i1 mul -> and.
784   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
785     if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
786       return V;
787
788   // Try some generic simplifications for associative operations.
789   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
790                                           MaxRecurse))
791     return V;
792
793   // Mul distributes over Add.  Try some generic simplifications based on this.
794   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
795                              TD, DT, MaxRecurse))
796     return V;
797
798   // If the operation is with the result of a select instruction, check whether
799   // operating on either branch of the select always yields the same value.
800   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
801     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
802                                          MaxRecurse))
803       return V;
804
805   // If the operation is with the result of a phi instruction, check whether
806   // operating on all incoming values of the phi always yields the same value.
807   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
808     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
809                                       MaxRecurse))
810       return V;
811
812   return 0;
813 }
814
815 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
816                              const DominatorTree *DT) {
817   return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
818 }
819
820 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
821 /// fold the result.  If not, this returns null.
822 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
823                           const TargetData *TD, const DominatorTree *DT,
824                           unsigned MaxRecurse) {
825   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
826     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
827       Constant *Ops[] = { C0, C1 };
828       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
829     }
830   }
831
832   bool isSigned = Opcode == Instruction::SDiv;
833
834   // X / undef -> undef
835   if (match(Op1, m_Undef()))
836     return Op1;
837
838   // undef / X -> 0
839   if (match(Op0, m_Undef()))
840     return Constant::getNullValue(Op0->getType());
841
842   // 0 / X -> 0, we don't need to preserve faults!
843   if (match(Op0, m_Zero()))
844     return Op0;
845
846   // X / 1 -> X
847   if (match(Op1, m_One()))
848     return Op0;
849
850   if (Op0->getType()->isIntegerTy(1))
851     // It can't be division by zero, hence it must be division by one.
852     return Op0;
853
854   // X / X -> 1
855   if (Op0 == Op1)
856     return ConstantInt::get(Op0->getType(), 1);
857
858   // (X * Y) / Y -> X if the multiplication does not overflow.
859   Value *X = 0, *Y = 0;
860   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
861     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
862     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
863     // If the Mul knows it does not overflow, then we are good to go.
864     if ((isSigned && Mul->hasNoSignedWrap()) ||
865         (!isSigned && Mul->hasNoUnsignedWrap()))
866       return X;
867     // If X has the form X = A / Y then X * Y cannot overflow.
868     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
869       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
870         return X;
871   }
872
873   // (X rem Y) / Y -> 0
874   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
875       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
876     return Constant::getNullValue(Op0->getType());
877
878   // If the operation is with the result of a select instruction, check whether
879   // operating on either branch of the select always yields the same value.
880   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
881     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
882       return V;
883
884   // If the operation is with the result of a phi instruction, check whether
885   // operating on all incoming values of the phi always yields the same value.
886   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
887     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
888       return V;
889
890   return 0;
891 }
892
893 /// SimplifySDivInst - Given operands for an SDiv, see if we can
894 /// fold the result.  If not, this returns null.
895 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
896                                const DominatorTree *DT, unsigned MaxRecurse) {
897   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
898     return V;
899
900   return 0;
901 }
902
903 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
904                               const DominatorTree *DT) {
905   return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
906 }
907
908 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
909 /// fold the result.  If not, this returns null.
910 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
911                                const DominatorTree *DT, unsigned MaxRecurse) {
912   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
913     return V;
914
915   return 0;
916 }
917
918 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
919                               const DominatorTree *DT) {
920   return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
921 }
922
923 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
924                                const DominatorTree *, unsigned) {
925   // undef / X -> undef    (the undef could be a snan).
926   if (match(Op0, m_Undef()))
927     return Op0;
928
929   // X / undef -> undef
930   if (match(Op1, m_Undef()))
931     return Op1;
932
933   return 0;
934 }
935
936 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
937                               const DominatorTree *DT) {
938   return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
939 }
940
941 /// SimplifyRem - Given operands for an SRem or URem, see if we can
942 /// fold the result.  If not, this returns null.
943 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
944                           const TargetData *TD, const DominatorTree *DT,
945                           unsigned MaxRecurse) {
946   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
947     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
948       Constant *Ops[] = { C0, C1 };
949       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
950     }
951   }
952
953   // X % undef -> undef
954   if (match(Op1, m_Undef()))
955     return Op1;
956
957   // undef % X -> 0
958   if (match(Op0, m_Undef()))
959     return Constant::getNullValue(Op0->getType());
960
961   // 0 % X -> 0, we don't need to preserve faults!
962   if (match(Op0, m_Zero()))
963     return Op0;
964
965   // X % 0 -> undef, we don't need to preserve faults!
966   if (match(Op1, m_Zero()))
967     return UndefValue::get(Op0->getType());
968
969   // X % 1 -> 0
970   if (match(Op1, m_One()))
971     return Constant::getNullValue(Op0->getType());
972
973   if (Op0->getType()->isIntegerTy(1))
974     // It can't be remainder by zero, hence it must be remainder by one.
975     return Constant::getNullValue(Op0->getType());
976
977   // X % X -> 0
978   if (Op0 == Op1)
979     return Constant::getNullValue(Op0->getType());
980
981   // If the operation is with the result of a select instruction, check whether
982   // operating on either branch of the select always yields the same value.
983   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
984     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
985       return V;
986
987   // If the operation is with the result of a phi instruction, check whether
988   // operating on all incoming values of the phi always yields the same value.
989   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
990     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
991       return V;
992
993   return 0;
994 }
995
996 /// SimplifySRemInst - Given operands for an SRem, see if we can
997 /// fold the result.  If not, this returns null.
998 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
999                                const DominatorTree *DT, unsigned MaxRecurse) {
1000   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
1001     return V;
1002
1003   return 0;
1004 }
1005
1006 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1007                               const DominatorTree *DT) {
1008   return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
1009 }
1010
1011 /// SimplifyURemInst - Given operands for a URem, see if we can
1012 /// fold the result.  If not, this returns null.
1013 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1014                                const DominatorTree *DT, unsigned MaxRecurse) {
1015   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
1016     return V;
1017
1018   return 0;
1019 }
1020
1021 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1022                               const DominatorTree *DT) {
1023   return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1024 }
1025
1026 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1027                                const DominatorTree *, unsigned) {
1028   // undef % X -> undef    (the undef could be a snan).
1029   if (match(Op0, m_Undef()))
1030     return Op0;
1031
1032   // X % undef -> undef
1033   if (match(Op1, m_Undef()))
1034     return Op1;
1035
1036   return 0;
1037 }
1038
1039 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1040                               const DominatorTree *DT) {
1041   return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1042 }
1043
1044 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1045 /// fold the result.  If not, this returns null.
1046 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1047                             const TargetData *TD, const DominatorTree *DT,
1048                             unsigned MaxRecurse) {
1049   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1050     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1051       Constant *Ops[] = { C0, C1 };
1052       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
1053     }
1054   }
1055
1056   // 0 shift by X -> 0
1057   if (match(Op0, m_Zero()))
1058     return Op0;
1059
1060   // X shift by 0 -> X
1061   if (match(Op1, m_Zero()))
1062     return Op0;
1063
1064   // X shift by undef -> undef because it may shift by the bitwidth.
1065   if (match(Op1, m_Undef()))
1066     return Op1;
1067
1068   // Shifting by the bitwidth or more is undefined.
1069   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1070     if (CI->getValue().getLimitedValue() >=
1071         Op0->getType()->getScalarSizeInBits())
1072       return UndefValue::get(Op0->getType());
1073
1074   // If the operation is with the result of a select instruction, check whether
1075   // operating on either branch of the select always yields the same value.
1076   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1077     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1078       return V;
1079
1080   // If the operation is with the result of a phi instruction, check whether
1081   // operating on all incoming values of the phi always yields the same value.
1082   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1083     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1084       return V;
1085
1086   return 0;
1087 }
1088
1089 /// SimplifyShlInst - Given operands for an Shl, see if we can
1090 /// fold the result.  If not, this returns null.
1091 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1092                               const TargetData *TD, const DominatorTree *DT,
1093                               unsigned MaxRecurse) {
1094   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1095     return V;
1096
1097   // undef << X -> 0
1098   if (match(Op0, m_Undef()))
1099     return Constant::getNullValue(Op0->getType());
1100
1101   // (X >> A) << A -> X
1102   Value *X;
1103   if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1104       cast<PossiblyExactOperator>(Op0)->isExact())
1105     return X;
1106   return 0;
1107 }
1108
1109 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1110                              const TargetData *TD, const DominatorTree *DT) {
1111   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1112 }
1113
1114 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1115 /// fold the result.  If not, this returns null.
1116 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1117                                const TargetData *TD, const DominatorTree *DT,
1118                                unsigned MaxRecurse) {
1119   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1120     return V;
1121
1122   // undef >>l X -> 0
1123   if (match(Op0, m_Undef()))
1124     return Constant::getNullValue(Op0->getType());
1125
1126   // (X << A) >> A -> X
1127   Value *X;
1128   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1129       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1130     return X;
1131
1132   return 0;
1133 }
1134
1135 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1136                               const TargetData *TD, const DominatorTree *DT) {
1137   return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1138 }
1139
1140 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1141 /// fold the result.  If not, this returns null.
1142 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1143                                const TargetData *TD, const DominatorTree *DT,
1144                                unsigned MaxRecurse) {
1145   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1146     return V;
1147
1148   // all ones >>a X -> all ones
1149   if (match(Op0, m_AllOnes()))
1150     return Op0;
1151
1152   // undef >>a X -> all ones
1153   if (match(Op0, m_Undef()))
1154     return Constant::getAllOnesValue(Op0->getType());
1155
1156   // (X << A) >> A -> X
1157   Value *X;
1158   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1159       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1160     return X;
1161
1162   return 0;
1163 }
1164
1165 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1166                               const TargetData *TD, const DominatorTree *DT) {
1167   return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1168 }
1169
1170 /// SimplifyAndInst - Given operands for an And, see if we can
1171 /// fold the result.  If not, this returns null.
1172 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1173                               const DominatorTree *DT, unsigned MaxRecurse) {
1174   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1175     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1176       Constant *Ops[] = { CLHS, CRHS };
1177       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1178                                       Ops, TD);
1179     }
1180
1181     // Canonicalize the constant to the RHS.
1182     std::swap(Op0, Op1);
1183   }
1184
1185   // X & undef -> 0
1186   if (match(Op1, m_Undef()))
1187     return Constant::getNullValue(Op0->getType());
1188
1189   // X & X = X
1190   if (Op0 == Op1)
1191     return Op0;
1192
1193   // X & 0 = 0
1194   if (match(Op1, m_Zero()))
1195     return Op1;
1196
1197   // X & -1 = X
1198   if (match(Op1, m_AllOnes()))
1199     return Op0;
1200
1201   // A & ~A  =  ~A & A  =  0
1202   if (match(Op0, m_Not(m_Specific(Op1))) ||
1203       match(Op1, m_Not(m_Specific(Op0))))
1204     return Constant::getNullValue(Op0->getType());
1205
1206   // (A | ?) & A = A
1207   Value *A = 0, *B = 0;
1208   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1209       (A == Op1 || B == Op1))
1210     return Op1;
1211
1212   // A & (A | ?) = A
1213   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1214       (A == Op0 || B == Op0))
1215     return Op0;
1216
1217   // A & (-A) = A if A is a power of two or zero.
1218   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1219       match(Op1, m_Neg(m_Specific(Op0)))) {
1220     if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1221       return Op0;
1222     if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1223       return Op1;
1224   }
1225
1226   // Try some generic simplifications for associative operations.
1227   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1228                                           MaxRecurse))
1229     return V;
1230
1231   // And distributes over Or.  Try some generic simplifications based on this.
1232   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1233                              TD, DT, MaxRecurse))
1234     return V;
1235
1236   // And distributes over Xor.  Try some generic simplifications based on this.
1237   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1238                              TD, DT, MaxRecurse))
1239     return V;
1240
1241   // Or distributes over And.  Try some generic simplifications based on this.
1242   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1243                                 TD, DT, MaxRecurse))
1244     return V;
1245
1246   // If the operation is with the result of a select instruction, check whether
1247   // operating on either branch of the select always yields the same value.
1248   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1249     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1250                                          MaxRecurse))
1251       return V;
1252
1253   // If the operation is with the result of a phi instruction, check whether
1254   // operating on all incoming values of the phi always yields the same value.
1255   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1256     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1257                                       MaxRecurse))
1258       return V;
1259
1260   return 0;
1261 }
1262
1263 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1264                              const DominatorTree *DT) {
1265   return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1266 }
1267
1268 /// SimplifyOrInst - Given operands for an Or, see if we can
1269 /// fold the result.  If not, this returns null.
1270 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1271                              const DominatorTree *DT, unsigned MaxRecurse) {
1272   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1273     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1274       Constant *Ops[] = { CLHS, CRHS };
1275       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1276                                       Ops, TD);
1277     }
1278
1279     // Canonicalize the constant to the RHS.
1280     std::swap(Op0, Op1);
1281   }
1282
1283   // X | undef -> -1
1284   if (match(Op1, m_Undef()))
1285     return Constant::getAllOnesValue(Op0->getType());
1286
1287   // X | X = X
1288   if (Op0 == Op1)
1289     return Op0;
1290
1291   // X | 0 = X
1292   if (match(Op1, m_Zero()))
1293     return Op0;
1294
1295   // X | -1 = -1
1296   if (match(Op1, m_AllOnes()))
1297     return Op1;
1298
1299   // A | ~A  =  ~A | A  =  -1
1300   if (match(Op0, m_Not(m_Specific(Op1))) ||
1301       match(Op1, m_Not(m_Specific(Op0))))
1302     return Constant::getAllOnesValue(Op0->getType());
1303
1304   // (A & ?) | A = A
1305   Value *A = 0, *B = 0;
1306   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1307       (A == Op1 || B == Op1))
1308     return Op1;
1309
1310   // A | (A & ?) = A
1311   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1312       (A == Op0 || B == Op0))
1313     return Op0;
1314
1315   // ~(A & ?) | A = -1
1316   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1317       (A == Op1 || B == Op1))
1318     return Constant::getAllOnesValue(Op1->getType());
1319
1320   // A | ~(A & ?) = -1
1321   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1322       (A == Op0 || B == Op0))
1323     return Constant::getAllOnesValue(Op0->getType());
1324
1325   // Try some generic simplifications for associative operations.
1326   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1327                                           MaxRecurse))
1328     return V;
1329
1330   // Or distributes over And.  Try some generic simplifications based on this.
1331   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1332                              TD, DT, MaxRecurse))
1333     return V;
1334
1335   // And distributes over Or.  Try some generic simplifications based on this.
1336   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1337                                 TD, DT, MaxRecurse))
1338     return V;
1339
1340   // If the operation is with the result of a select instruction, check whether
1341   // operating on either branch of the select always yields the same value.
1342   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1343     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1344                                          MaxRecurse))
1345       return V;
1346
1347   // If the operation is with the result of a phi instruction, check whether
1348   // operating on all incoming values of the phi always yields the same value.
1349   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1350     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1351                                       MaxRecurse))
1352       return V;
1353
1354   return 0;
1355 }
1356
1357 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1358                             const DominatorTree *DT) {
1359   return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1360 }
1361
1362 /// SimplifyXorInst - Given operands for a Xor, see if we can
1363 /// fold the result.  If not, this returns null.
1364 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1365                               const DominatorTree *DT, unsigned MaxRecurse) {
1366   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1367     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1368       Constant *Ops[] = { CLHS, CRHS };
1369       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1370                                       Ops, TD);
1371     }
1372
1373     // Canonicalize the constant to the RHS.
1374     std::swap(Op0, Op1);
1375   }
1376
1377   // A ^ undef -> undef
1378   if (match(Op1, m_Undef()))
1379     return Op1;
1380
1381   // A ^ 0 = A
1382   if (match(Op1, m_Zero()))
1383     return Op0;
1384
1385   // A ^ A = 0
1386   if (Op0 == Op1)
1387     return Constant::getNullValue(Op0->getType());
1388
1389   // A ^ ~A  =  ~A ^ A  =  -1
1390   if (match(Op0, m_Not(m_Specific(Op1))) ||
1391       match(Op1, m_Not(m_Specific(Op0))))
1392     return Constant::getAllOnesValue(Op0->getType());
1393
1394   // Try some generic simplifications for associative operations.
1395   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1396                                           MaxRecurse))
1397     return V;
1398
1399   // And distributes over Xor.  Try some generic simplifications based on this.
1400   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1401                                 TD, DT, MaxRecurse))
1402     return V;
1403
1404   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1405   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1406   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1407   // only if B and C are equal.  If B and C are equal then (since we assume
1408   // that operands have already been simplified) "select(cond, B, C)" should
1409   // have been simplified to the common value of B and C already.  Analysing
1410   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1411   // for threading over phi nodes.
1412
1413   return 0;
1414 }
1415
1416 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1417                              const DominatorTree *DT) {
1418   return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1419 }
1420
1421 static Type *GetCompareTy(Value *Op) {
1422   return CmpInst::makeCmpResultType(Op->getType());
1423 }
1424
1425 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1426 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1427 /// otherwise return null.  Helper function for analyzing max/min idioms.
1428 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1429                                          Value *LHS, Value *RHS) {
1430   SelectInst *SI = dyn_cast<SelectInst>(V);
1431   if (!SI)
1432     return 0;
1433   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1434   if (!Cmp)
1435     return 0;
1436   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1437   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1438     return Cmp;
1439   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1440       LHS == CmpRHS && RHS == CmpLHS)
1441     return Cmp;
1442   return 0;
1443 }
1444
1445 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1446 /// fold the result.  If not, this returns null.
1447 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1448                                const TargetData *TD, const DominatorTree *DT,
1449                                unsigned MaxRecurse) {
1450   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1451   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1452
1453   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1454     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1455       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1456
1457     // If we have a constant, make sure it is on the RHS.
1458     std::swap(LHS, RHS);
1459     Pred = CmpInst::getSwappedPredicate(Pred);
1460   }
1461
1462   Type *ITy = GetCompareTy(LHS); // The return type.
1463   Type *OpTy = LHS->getType();   // The operand type.
1464
1465   // icmp X, X -> true/false
1466   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1467   // because X could be 0.
1468   if (LHS == RHS || isa<UndefValue>(RHS))
1469     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1470
1471   // Special case logic when the operands have i1 type.
1472   if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1473        cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1474     switch (Pred) {
1475     default: break;
1476     case ICmpInst::ICMP_EQ:
1477       // X == 1 -> X
1478       if (match(RHS, m_One()))
1479         return LHS;
1480       break;
1481     case ICmpInst::ICMP_NE:
1482       // X != 0 -> X
1483       if (match(RHS, m_Zero()))
1484         return LHS;
1485       break;
1486     case ICmpInst::ICMP_UGT:
1487       // X >u 0 -> X
1488       if (match(RHS, m_Zero()))
1489         return LHS;
1490       break;
1491     case ICmpInst::ICMP_UGE:
1492       // X >=u 1 -> X
1493       if (match(RHS, m_One()))
1494         return LHS;
1495       break;
1496     case ICmpInst::ICMP_SLT:
1497       // X <s 0 -> X
1498       if (match(RHS, m_Zero()))
1499         return LHS;
1500       break;
1501     case ICmpInst::ICMP_SLE:
1502       // X <=s -1 -> X
1503       if (match(RHS, m_One()))
1504         return LHS;
1505       break;
1506     }
1507   }
1508
1509   // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1510   // different addresses, and what's more the address of a stack variable is
1511   // never null or equal to the address of a global.  Note that generalizing
1512   // to the case where LHS is a global variable address or null is pointless,
1513   // since if both LHS and RHS are constants then we already constant folded
1514   // the compare, and if only one of them is then we moved it to RHS already.
1515   if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1516                                isa<ConstantPointerNull>(RHS)))
1517     // We already know that LHS != RHS.
1518     return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1519
1520   // If we are comparing with zero then try hard since this is a common case.
1521   if (match(RHS, m_Zero())) {
1522     bool LHSKnownNonNegative, LHSKnownNegative;
1523     switch (Pred) {
1524     default:
1525       assert(false && "Unknown ICmp predicate!");
1526     case ICmpInst::ICMP_ULT:
1527       return getFalse(ITy);
1528     case ICmpInst::ICMP_UGE:
1529       return getTrue(ITy);
1530     case ICmpInst::ICMP_EQ:
1531     case ICmpInst::ICMP_ULE:
1532       if (isKnownNonZero(LHS, TD))
1533         return getFalse(ITy);
1534       break;
1535     case ICmpInst::ICMP_NE:
1536     case ICmpInst::ICMP_UGT:
1537       if (isKnownNonZero(LHS, TD))
1538         return getTrue(ITy);
1539       break;
1540     case ICmpInst::ICMP_SLT:
1541       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1542       if (LHSKnownNegative)
1543         return getTrue(ITy);
1544       if (LHSKnownNonNegative)
1545         return getFalse(ITy);
1546       break;
1547     case ICmpInst::ICMP_SLE:
1548       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1549       if (LHSKnownNegative)
1550         return getTrue(ITy);
1551       if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1552         return getFalse(ITy);
1553       break;
1554     case ICmpInst::ICMP_SGE:
1555       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1556       if (LHSKnownNegative)
1557         return getFalse(ITy);
1558       if (LHSKnownNonNegative)
1559         return getTrue(ITy);
1560       break;
1561     case ICmpInst::ICMP_SGT:
1562       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1563       if (LHSKnownNegative)
1564         return getFalse(ITy);
1565       if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1566         return getTrue(ITy);
1567       break;
1568     }
1569   }
1570
1571   // See if we are doing a comparison with a constant integer.
1572   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1573     // Rule out tautological comparisons (eg., ult 0 or uge 0).
1574     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1575     if (RHS_CR.isEmptySet())
1576       return ConstantInt::getFalse(CI->getContext());
1577     if (RHS_CR.isFullSet())
1578       return ConstantInt::getTrue(CI->getContext());
1579
1580     // Many binary operators with constant RHS have easy to compute constant
1581     // range.  Use them to check whether the comparison is a tautology.
1582     uint32_t Width = CI->getBitWidth();
1583     APInt Lower = APInt(Width, 0);
1584     APInt Upper = APInt(Width, 0);
1585     ConstantInt *CI2;
1586     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1587       // 'urem x, CI2' produces [0, CI2).
1588       Upper = CI2->getValue();
1589     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1590       // 'srem x, CI2' produces (-|CI2|, |CI2|).
1591       Upper = CI2->getValue().abs();
1592       Lower = (-Upper) + 1;
1593     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1594       // 'udiv CI2, x' produces [0, CI2].
1595       Upper = CI2->getValue();
1596     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1597       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1598       APInt NegOne = APInt::getAllOnesValue(Width);
1599       if (!CI2->isZero())
1600         Upper = NegOne.udiv(CI2->getValue()) + 1;
1601     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1602       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1603       APInt IntMin = APInt::getSignedMinValue(Width);
1604       APInt IntMax = APInt::getSignedMaxValue(Width);
1605       APInt Val = CI2->getValue().abs();
1606       if (!Val.isMinValue()) {
1607         Lower = IntMin.sdiv(Val);
1608         Upper = IntMax.sdiv(Val) + 1;
1609       }
1610     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1611       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1612       APInt NegOne = APInt::getAllOnesValue(Width);
1613       if (CI2->getValue().ult(Width))
1614         Upper = NegOne.lshr(CI2->getValue()) + 1;
1615     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1616       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1617       APInt IntMin = APInt::getSignedMinValue(Width);
1618       APInt IntMax = APInt::getSignedMaxValue(Width);
1619       if (CI2->getValue().ult(Width)) {
1620         Lower = IntMin.ashr(CI2->getValue());
1621         Upper = IntMax.ashr(CI2->getValue()) + 1;
1622       }
1623     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1624       // 'or x, CI2' produces [CI2, UINT_MAX].
1625       Lower = CI2->getValue();
1626     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1627       // 'and x, CI2' produces [0, CI2].
1628       Upper = CI2->getValue() + 1;
1629     }
1630     if (Lower != Upper) {
1631       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1632       if (RHS_CR.contains(LHS_CR))
1633         return ConstantInt::getTrue(RHS->getContext());
1634       if (RHS_CR.inverse().contains(LHS_CR))
1635         return ConstantInt::getFalse(RHS->getContext());
1636     }
1637   }
1638
1639   // Compare of cast, for example (zext X) != 0 -> X != 0
1640   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1641     Instruction *LI = cast<CastInst>(LHS);
1642     Value *SrcOp = LI->getOperand(0);
1643     Type *SrcTy = SrcOp->getType();
1644     Type *DstTy = LI->getType();
1645
1646     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1647     // if the integer type is the same size as the pointer type.
1648     if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1649         TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1650       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1651         // Transfer the cast to the constant.
1652         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1653                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
1654                                         TD, DT, MaxRecurse-1))
1655           return V;
1656       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1657         if (RI->getOperand(0)->getType() == SrcTy)
1658           // Compare without the cast.
1659           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1660                                           TD, DT, MaxRecurse-1))
1661             return V;
1662       }
1663     }
1664
1665     if (isa<ZExtInst>(LHS)) {
1666       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1667       // same type.
1668       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1669         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1670           // Compare X and Y.  Note that signed predicates become unsigned.
1671           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1672                                           SrcOp, RI->getOperand(0), TD, DT,
1673                                           MaxRecurse-1))
1674             return V;
1675       }
1676       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1677       // too.  If not, then try to deduce the result of the comparison.
1678       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1679         // Compute the constant that would happen if we truncated to SrcTy then
1680         // reextended to DstTy.
1681         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1682         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1683
1684         // If the re-extended constant didn't change then this is effectively
1685         // also a case of comparing two zero-extended values.
1686         if (RExt == CI && MaxRecurse)
1687           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1688                                           SrcOp, Trunc, TD, DT, MaxRecurse-1))
1689             return V;
1690
1691         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1692         // there.  Use this to work out the result of the comparison.
1693         if (RExt != CI) {
1694           switch (Pred) {
1695           default:
1696             assert(false && "Unknown ICmp predicate!");
1697           // LHS <u RHS.
1698           case ICmpInst::ICMP_EQ:
1699           case ICmpInst::ICMP_UGT:
1700           case ICmpInst::ICMP_UGE:
1701             return ConstantInt::getFalse(CI->getContext());
1702
1703           case ICmpInst::ICMP_NE:
1704           case ICmpInst::ICMP_ULT:
1705           case ICmpInst::ICMP_ULE:
1706             return ConstantInt::getTrue(CI->getContext());
1707
1708           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1709           // is non-negative then LHS <s RHS.
1710           case ICmpInst::ICMP_SGT:
1711           case ICmpInst::ICMP_SGE:
1712             return CI->getValue().isNegative() ?
1713               ConstantInt::getTrue(CI->getContext()) :
1714               ConstantInt::getFalse(CI->getContext());
1715
1716           case ICmpInst::ICMP_SLT:
1717           case ICmpInst::ICMP_SLE:
1718             return CI->getValue().isNegative() ?
1719               ConstantInt::getFalse(CI->getContext()) :
1720               ConstantInt::getTrue(CI->getContext());
1721           }
1722         }
1723       }
1724     }
1725
1726     if (isa<SExtInst>(LHS)) {
1727       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1728       // same type.
1729       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1730         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1731           // Compare X and Y.  Note that the predicate does not change.
1732           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1733                                           TD, DT, MaxRecurse-1))
1734             return V;
1735       }
1736       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1737       // too.  If not, then try to deduce the result of the comparison.
1738       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1739         // Compute the constant that would happen if we truncated to SrcTy then
1740         // reextended to DstTy.
1741         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1742         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1743
1744         // If the re-extended constant didn't change then this is effectively
1745         // also a case of comparing two sign-extended values.
1746         if (RExt == CI && MaxRecurse)
1747           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1748                                           MaxRecurse-1))
1749             return V;
1750
1751         // Otherwise the upper bits of LHS are all equal, while RHS has varying
1752         // bits there.  Use this to work out the result of the comparison.
1753         if (RExt != CI) {
1754           switch (Pred) {
1755           default:
1756             assert(false && "Unknown ICmp predicate!");
1757           case ICmpInst::ICMP_EQ:
1758             return ConstantInt::getFalse(CI->getContext());
1759           case ICmpInst::ICMP_NE:
1760             return ConstantInt::getTrue(CI->getContext());
1761
1762           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
1763           // LHS >s RHS.
1764           case ICmpInst::ICMP_SGT:
1765           case ICmpInst::ICMP_SGE:
1766             return CI->getValue().isNegative() ?
1767               ConstantInt::getTrue(CI->getContext()) :
1768               ConstantInt::getFalse(CI->getContext());
1769           case ICmpInst::ICMP_SLT:
1770           case ICmpInst::ICMP_SLE:
1771             return CI->getValue().isNegative() ?
1772               ConstantInt::getFalse(CI->getContext()) :
1773               ConstantInt::getTrue(CI->getContext());
1774
1775           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
1776           // LHS >u RHS.
1777           case ICmpInst::ICMP_UGT:
1778           case ICmpInst::ICMP_UGE:
1779             // Comparison is true iff the LHS <s 0.
1780             if (MaxRecurse)
1781               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1782                                               Constant::getNullValue(SrcTy),
1783                                               TD, DT, MaxRecurse-1))
1784                 return V;
1785             break;
1786           case ICmpInst::ICMP_ULT:
1787           case ICmpInst::ICMP_ULE:
1788             // Comparison is true iff the LHS >=s 0.
1789             if (MaxRecurse)
1790               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1791                                               Constant::getNullValue(SrcTy),
1792                                               TD, DT, MaxRecurse-1))
1793                 return V;
1794             break;
1795           }
1796         }
1797       }
1798     }
1799   }
1800
1801   // Special logic for binary operators.
1802   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1803   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1804   if (MaxRecurse && (LBO || RBO)) {
1805     // Analyze the case when either LHS or RHS is an add instruction.
1806     Value *A = 0, *B = 0, *C = 0, *D = 0;
1807     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1808     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1809     if (LBO && LBO->getOpcode() == Instruction::Add) {
1810       A = LBO->getOperand(0); B = LBO->getOperand(1);
1811       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1812         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1813         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1814     }
1815     if (RBO && RBO->getOpcode() == Instruction::Add) {
1816       C = RBO->getOperand(0); D = RBO->getOperand(1);
1817       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1818         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1819         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1820     }
1821
1822     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1823     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1824       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1825                                       Constant::getNullValue(RHS->getType()),
1826                                       TD, DT, MaxRecurse-1))
1827         return V;
1828
1829     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1830     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1831       if (Value *V = SimplifyICmpInst(Pred,
1832                                       Constant::getNullValue(LHS->getType()),
1833                                       C == LHS ? D : C, TD, DT, MaxRecurse-1))
1834         return V;
1835
1836     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1837     if (A && C && (A == C || A == D || B == C || B == D) &&
1838         NoLHSWrapProblem && NoRHSWrapProblem) {
1839       // Determine Y and Z in the form icmp (X+Y), (X+Z).
1840       Value *Y = (A == C || A == D) ? B : A;
1841       Value *Z = (C == A || C == B) ? D : C;
1842       if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1843         return V;
1844     }
1845   }
1846
1847   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1848     bool KnownNonNegative, KnownNegative;
1849     switch (Pred) {
1850     default:
1851       break;
1852     case ICmpInst::ICMP_SGT:
1853     case ICmpInst::ICMP_SGE:
1854       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1855       if (!KnownNonNegative)
1856         break;
1857       // fall-through
1858     case ICmpInst::ICMP_EQ:
1859     case ICmpInst::ICMP_UGT:
1860     case ICmpInst::ICMP_UGE:
1861       return getFalse(ITy);
1862     case ICmpInst::ICMP_SLT:
1863     case ICmpInst::ICMP_SLE:
1864       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1865       if (!KnownNonNegative)
1866         break;
1867       // fall-through
1868     case ICmpInst::ICMP_NE:
1869     case ICmpInst::ICMP_ULT:
1870     case ICmpInst::ICMP_ULE:
1871       return getTrue(ITy);
1872     }
1873   }
1874   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1875     bool KnownNonNegative, KnownNegative;
1876     switch (Pred) {
1877     default:
1878       break;
1879     case ICmpInst::ICMP_SGT:
1880     case ICmpInst::ICMP_SGE:
1881       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1882       if (!KnownNonNegative)
1883         break;
1884       // fall-through
1885     case ICmpInst::ICMP_NE:
1886     case ICmpInst::ICMP_UGT:
1887     case ICmpInst::ICMP_UGE:
1888       return getTrue(ITy);
1889     case ICmpInst::ICMP_SLT:
1890     case ICmpInst::ICMP_SLE:
1891       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1892       if (!KnownNonNegative)
1893         break;
1894       // fall-through
1895     case ICmpInst::ICMP_EQ:
1896     case ICmpInst::ICMP_ULT:
1897     case ICmpInst::ICMP_ULE:
1898       return getFalse(ITy);
1899     }
1900   }
1901
1902   // x udiv y <=u x.
1903   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1904     // icmp pred (X /u Y), X
1905     if (Pred == ICmpInst::ICMP_UGT)
1906       return getFalse(ITy);
1907     if (Pred == ICmpInst::ICMP_ULE)
1908       return getTrue(ITy);
1909   }
1910
1911   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1912       LBO->getOperand(1) == RBO->getOperand(1)) {
1913     switch (LBO->getOpcode()) {
1914     default: break;
1915     case Instruction::UDiv:
1916     case Instruction::LShr:
1917       if (ICmpInst::isSigned(Pred))
1918         break;
1919       // fall-through
1920     case Instruction::SDiv:
1921     case Instruction::AShr:
1922       if (!LBO->isExact() || !RBO->isExact())
1923         break;
1924       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1925                                       RBO->getOperand(0), TD, DT, MaxRecurse-1))
1926         return V;
1927       break;
1928     case Instruction::Shl: {
1929       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
1930       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1931       if (!NUW && !NSW)
1932         break;
1933       if (!NSW && ICmpInst::isSigned(Pred))
1934         break;
1935       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1936                                       RBO->getOperand(0), TD, DT, MaxRecurse-1))
1937         return V;
1938       break;
1939     }
1940     }
1941   }
1942
1943   // Simplify comparisons involving max/min.
1944   Value *A, *B;
1945   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1946   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1947
1948   // Signed variants on "max(a,b)>=a -> true".
1949   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1950     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1951     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1952     // We analyze this as smax(A, B) pred A.
1953     P = Pred;
1954   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1955              (A == LHS || B == LHS)) {
1956     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1957     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1958     // We analyze this as smax(A, B) swapped-pred A.
1959     P = CmpInst::getSwappedPredicate(Pred);
1960   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1961              (A == RHS || B == RHS)) {
1962     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1963     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1964     // We analyze this as smax(-A, -B) swapped-pred -A.
1965     // Note that we do not need to actually form -A or -B thanks to EqP.
1966     P = CmpInst::getSwappedPredicate(Pred);
1967   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1968              (A == LHS || B == LHS)) {
1969     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1970     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1971     // We analyze this as smax(-A, -B) pred -A.
1972     // Note that we do not need to actually form -A or -B thanks to EqP.
1973     P = Pred;
1974   }
1975   if (P != CmpInst::BAD_ICMP_PREDICATE) {
1976     // Cases correspond to "max(A, B) p A".
1977     switch (P) {
1978     default:
1979       break;
1980     case CmpInst::ICMP_EQ:
1981     case CmpInst::ICMP_SLE:
1982       // Equivalent to "A EqP B".  This may be the same as the condition tested
1983       // in the max/min; if so, we can just return that.
1984       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1985         return V;
1986       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1987         return V;
1988       // Otherwise, see if "A EqP B" simplifies.
1989       if (MaxRecurse)
1990         if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1991           return V;
1992       break;
1993     case CmpInst::ICMP_NE:
1994     case CmpInst::ICMP_SGT: {
1995       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1996       // Equivalent to "A InvEqP B".  This may be the same as the condition
1997       // tested in the max/min; if so, we can just return that.
1998       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1999         return V;
2000       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2001         return V;
2002       // Otherwise, see if "A InvEqP B" simplifies.
2003       if (MaxRecurse)
2004         if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2005           return V;
2006       break;
2007     }
2008     case CmpInst::ICMP_SGE:
2009       // Always true.
2010       return getTrue(ITy);
2011     case CmpInst::ICMP_SLT:
2012       // Always false.
2013       return getFalse(ITy);
2014     }
2015   }
2016
2017   // Unsigned variants on "max(a,b)>=a -> true".
2018   P = CmpInst::BAD_ICMP_PREDICATE;
2019   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2020     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2021     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2022     // We analyze this as umax(A, B) pred A.
2023     P = Pred;
2024   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2025              (A == LHS || B == LHS)) {
2026     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2027     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2028     // We analyze this as umax(A, B) swapped-pred A.
2029     P = CmpInst::getSwappedPredicate(Pred);
2030   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2031              (A == RHS || B == RHS)) {
2032     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2033     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2034     // We analyze this as umax(-A, -B) swapped-pred -A.
2035     // Note that we do not need to actually form -A or -B thanks to EqP.
2036     P = CmpInst::getSwappedPredicate(Pred);
2037   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2038              (A == LHS || B == LHS)) {
2039     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2040     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2041     // We analyze this as umax(-A, -B) pred -A.
2042     // Note that we do not need to actually form -A or -B thanks to EqP.
2043     P = Pred;
2044   }
2045   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2046     // Cases correspond to "max(A, B) p A".
2047     switch (P) {
2048     default:
2049       break;
2050     case CmpInst::ICMP_EQ:
2051     case CmpInst::ICMP_ULE:
2052       // Equivalent to "A EqP B".  This may be the same as the condition tested
2053       // in the max/min; if so, we can just return that.
2054       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2055         return V;
2056       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2057         return V;
2058       // Otherwise, see if "A EqP B" simplifies.
2059       if (MaxRecurse)
2060         if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2061           return V;
2062       break;
2063     case CmpInst::ICMP_NE:
2064     case CmpInst::ICMP_UGT: {
2065       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2066       // Equivalent to "A InvEqP B".  This may be the same as the condition
2067       // tested in the max/min; if so, we can just return that.
2068       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2069         return V;
2070       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2071         return V;
2072       // Otherwise, see if "A InvEqP B" simplifies.
2073       if (MaxRecurse)
2074         if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2075           return V;
2076       break;
2077     }
2078     case CmpInst::ICMP_UGE:
2079       // Always true.
2080       return getTrue(ITy);
2081     case CmpInst::ICMP_ULT:
2082       // Always false.
2083       return getFalse(ITy);
2084     }
2085   }
2086
2087   // Variants on "max(x,y) >= min(x,z)".
2088   Value *C, *D;
2089   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2090       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2091       (A == C || A == D || B == C || B == D)) {
2092     // max(x, ?) pred min(x, ?).
2093     if (Pred == CmpInst::ICMP_SGE)
2094       // Always true.
2095       return getTrue(ITy);
2096     if (Pred == CmpInst::ICMP_SLT)
2097       // Always false.
2098       return getFalse(ITy);
2099   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2100              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2101              (A == C || A == D || B == C || B == D)) {
2102     // min(x, ?) pred max(x, ?).
2103     if (Pred == CmpInst::ICMP_SLE)
2104       // Always true.
2105       return getTrue(ITy);
2106     if (Pred == CmpInst::ICMP_SGT)
2107       // Always false.
2108       return getFalse(ITy);
2109   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2110              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2111              (A == C || A == D || B == C || B == D)) {
2112     // max(x, ?) pred min(x, ?).
2113     if (Pred == CmpInst::ICMP_UGE)
2114       // Always true.
2115       return getTrue(ITy);
2116     if (Pred == CmpInst::ICMP_ULT)
2117       // Always false.
2118       return getFalse(ITy);
2119   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2120              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2121              (A == C || A == D || B == C || B == D)) {
2122     // min(x, ?) pred max(x, ?).
2123     if (Pred == CmpInst::ICMP_ULE)
2124       // Always true.
2125       return getTrue(ITy);
2126     if (Pred == CmpInst::ICMP_UGT)
2127       // Always false.
2128       return getFalse(ITy);
2129   }
2130
2131   // If the comparison is with the result of a select instruction, check whether
2132   // comparing with either branch of the select always yields the same value.
2133   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2134     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2135       return V;
2136
2137   // If the comparison is with the result of a phi instruction, check whether
2138   // doing the compare with each incoming phi value yields a common result.
2139   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2140     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2141       return V;
2142
2143   return 0;
2144 }
2145
2146 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2147                               const TargetData *TD, const DominatorTree *DT) {
2148   return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2149 }
2150
2151 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2152 /// fold the result.  If not, this returns null.
2153 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2154                                const TargetData *TD, const DominatorTree *DT,
2155                                unsigned MaxRecurse) {
2156   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2157   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2158
2159   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2160     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2161       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2162
2163     // If we have a constant, make sure it is on the RHS.
2164     std::swap(LHS, RHS);
2165     Pred = CmpInst::getSwappedPredicate(Pred);
2166   }
2167
2168   // Fold trivial predicates.
2169   if (Pred == FCmpInst::FCMP_FALSE)
2170     return ConstantInt::get(GetCompareTy(LHS), 0);
2171   if (Pred == FCmpInst::FCMP_TRUE)
2172     return ConstantInt::get(GetCompareTy(LHS), 1);
2173
2174   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2175     return UndefValue::get(GetCompareTy(LHS));
2176
2177   // fcmp x,x -> true/false.  Not all compares are foldable.
2178   if (LHS == RHS) {
2179     if (CmpInst::isTrueWhenEqual(Pred))
2180       return ConstantInt::get(GetCompareTy(LHS), 1);
2181     if (CmpInst::isFalseWhenEqual(Pred))
2182       return ConstantInt::get(GetCompareTy(LHS), 0);
2183   }
2184
2185   // Handle fcmp with constant RHS
2186   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2187     // If the constant is a nan, see if we can fold the comparison based on it.
2188     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2189       if (CFP->getValueAPF().isNaN()) {
2190         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2191           return ConstantInt::getFalse(CFP->getContext());
2192         assert(FCmpInst::isUnordered(Pred) &&
2193                "Comparison must be either ordered or unordered!");
2194         // True if unordered.
2195         return ConstantInt::getTrue(CFP->getContext());
2196       }
2197       // Check whether the constant is an infinity.
2198       if (CFP->getValueAPF().isInfinity()) {
2199         if (CFP->getValueAPF().isNegative()) {
2200           switch (Pred) {
2201           case FCmpInst::FCMP_OLT:
2202             // No value is ordered and less than negative infinity.
2203             return ConstantInt::getFalse(CFP->getContext());
2204           case FCmpInst::FCMP_UGE:
2205             // All values are unordered with or at least negative infinity.
2206             return ConstantInt::getTrue(CFP->getContext());
2207           default:
2208             break;
2209           }
2210         } else {
2211           switch (Pred) {
2212           case FCmpInst::FCMP_OGT:
2213             // No value is ordered and greater than infinity.
2214             return ConstantInt::getFalse(CFP->getContext());
2215           case FCmpInst::FCMP_ULE:
2216             // All values are unordered with and at most infinity.
2217             return ConstantInt::getTrue(CFP->getContext());
2218           default:
2219             break;
2220           }
2221         }
2222       }
2223     }
2224   }
2225
2226   // If the comparison is with the result of a select instruction, check whether
2227   // comparing with either branch of the select always yields the same value.
2228   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2229     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2230       return V;
2231
2232   // If the comparison is with the result of a phi instruction, check whether
2233   // doing the compare with each incoming phi value yields a common result.
2234   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2235     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2236       return V;
2237
2238   return 0;
2239 }
2240
2241 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2242                               const TargetData *TD, const DominatorTree *DT) {
2243   return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2244 }
2245
2246 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2247 /// the result.  If not, this returns null.
2248 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2249                                 const TargetData *TD, const DominatorTree *) {
2250   // select true, X, Y  -> X
2251   // select false, X, Y -> Y
2252   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2253     return CB->getZExtValue() ? TrueVal : FalseVal;
2254
2255   // select C, X, X -> X
2256   if (TrueVal == FalseVal)
2257     return TrueVal;
2258
2259   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2260     if (isa<Constant>(TrueVal))
2261       return TrueVal;
2262     return FalseVal;
2263   }
2264   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2265     return FalseVal;
2266   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2267     return TrueVal;
2268
2269   return 0;
2270 }
2271
2272 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2273 /// fold the result.  If not, this returns null.
2274 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
2275                              const TargetData *TD, const DominatorTree *) {
2276   // The type of the GEP pointer operand.
2277   PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2278
2279   // getelementptr P -> P.
2280   if (Ops.size() == 1)
2281     return Ops[0];
2282
2283   if (isa<UndefValue>(Ops[0])) {
2284     // Compute the (pointer) type returned by the GEP instruction.
2285     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2286     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2287     return UndefValue::get(GEPTy);
2288   }
2289
2290   if (Ops.size() == 2) {
2291     // getelementptr P, 0 -> P.
2292     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2293       if (C->isZero())
2294         return Ops[0];
2295     // getelementptr P, N -> P if P points to a type of zero size.
2296     if (TD) {
2297       Type *Ty = PtrTy->getElementType();
2298       if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2299         return Ops[0];
2300     }
2301   }
2302
2303   // Check to see if this is constant foldable.
2304   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2305     if (!isa<Constant>(Ops[i]))
2306       return 0;
2307
2308   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2309 }
2310
2311 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2312 /// can fold the result.  If not, this returns null.
2313 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2314                                      ArrayRef<unsigned> Idxs,
2315                                      const TargetData *,
2316                                      const DominatorTree *) {
2317   if (Constant *CAgg = dyn_cast<Constant>(Agg))
2318     if (Constant *CVal = dyn_cast<Constant>(Val))
2319       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2320
2321   // insertvalue x, undef, n -> x
2322   if (match(Val, m_Undef()))
2323     return Agg;
2324
2325   // insertvalue x, (extractvalue y, n), n
2326   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2327     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2328         EV->getIndices() == Idxs) {
2329       // insertvalue undef, (extractvalue y, n), n -> y
2330       if (match(Agg, m_Undef()))
2331         return EV->getAggregateOperand();
2332
2333       // insertvalue y, (extractvalue y, n), n -> y
2334       if (Agg == EV->getAggregateOperand())
2335         return Agg;
2336     }
2337
2338   return 0;
2339 }
2340
2341 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2342 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2343   // If all of the PHI's incoming values are the same then replace the PHI node
2344   // with the common value.
2345   Value *CommonValue = 0;
2346   bool HasUndefInput = false;
2347   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2348     Value *Incoming = PN->getIncomingValue(i);
2349     // If the incoming value is the phi node itself, it can safely be skipped.
2350     if (Incoming == PN) continue;
2351     if (isa<UndefValue>(Incoming)) {
2352       // Remember that we saw an undef value, but otherwise ignore them.
2353       HasUndefInput = true;
2354       continue;
2355     }
2356     if (CommonValue && Incoming != CommonValue)
2357       return 0;  // Not the same, bail out.
2358     CommonValue = Incoming;
2359   }
2360
2361   // If CommonValue is null then all of the incoming values were either undef or
2362   // equal to the phi node itself.
2363   if (!CommonValue)
2364     return UndefValue::get(PN->getType());
2365
2366   // If we have a PHI node like phi(X, undef, X), where X is defined by some
2367   // instruction, we cannot return X as the result of the PHI node unless it
2368   // dominates the PHI block.
2369   if (HasUndefInput)
2370     return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2371
2372   return CommonValue;
2373 }
2374
2375
2376 //=== Helper functions for higher up the class hierarchy.
2377
2378 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2379 /// fold the result.  If not, this returns null.
2380 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2381                             const TargetData *TD, const DominatorTree *DT,
2382                             unsigned MaxRecurse) {
2383   switch (Opcode) {
2384   case Instruction::Add:
2385     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2386                            TD, DT, MaxRecurse);
2387   case Instruction::Sub:
2388     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2389                            TD, DT, MaxRecurse);
2390   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2391   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2392   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2393   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2394   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2395   case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2396   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2397   case Instruction::Shl:
2398     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2399                            TD, DT, MaxRecurse);
2400   case Instruction::LShr:
2401     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2402   case Instruction::AShr:
2403     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2404   case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2405   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2406   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2407   default:
2408     if (Constant *CLHS = dyn_cast<Constant>(LHS))
2409       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2410         Constant *COps[] = {CLHS, CRHS};
2411         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
2412       }
2413
2414     // If the operation is associative, try some generic simplifications.
2415     if (Instruction::isAssociative(Opcode))
2416       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2417                                               MaxRecurse))
2418         return V;
2419
2420     // If the operation is with the result of a select instruction, check whether
2421     // operating on either branch of the select always yields the same value.
2422     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2423       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2424                                            MaxRecurse))
2425         return V;
2426
2427     // If the operation is with the result of a phi instruction, check whether
2428     // operating on all incoming values of the phi always yields the same value.
2429     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2430       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2431         return V;
2432
2433     return 0;
2434   }
2435 }
2436
2437 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2438                            const TargetData *TD, const DominatorTree *DT) {
2439   return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2440 }
2441
2442 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2443 /// fold the result.
2444 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2445                               const TargetData *TD, const DominatorTree *DT,
2446                               unsigned MaxRecurse) {
2447   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2448     return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2449   return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2450 }
2451
2452 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2453                              const TargetData *TD, const DominatorTree *DT) {
2454   return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2455 }
2456
2457 /// SimplifyInstruction - See if we can compute a simplified version of this
2458 /// instruction.  If not, this returns null.
2459 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2460                                  const DominatorTree *DT) {
2461   Value *Result;
2462
2463   switch (I->getOpcode()) {
2464   default:
2465     Result = ConstantFoldInstruction(I, TD);
2466     break;
2467   case Instruction::Add:
2468     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2469                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2470                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2471                              TD, DT);
2472     break;
2473   case Instruction::Sub:
2474     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2475                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2476                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2477                              TD, DT);
2478     break;
2479   case Instruction::Mul:
2480     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2481     break;
2482   case Instruction::SDiv:
2483     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2484     break;
2485   case Instruction::UDiv:
2486     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2487     break;
2488   case Instruction::FDiv:
2489     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2490     break;
2491   case Instruction::SRem:
2492     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2493     break;
2494   case Instruction::URem:
2495     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2496     break;
2497   case Instruction::FRem:
2498     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2499     break;
2500   case Instruction::Shl:
2501     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2502                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2503                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2504                              TD, DT);
2505     break;
2506   case Instruction::LShr:
2507     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2508                               cast<BinaryOperator>(I)->isExact(),
2509                               TD, DT);
2510     break;
2511   case Instruction::AShr:
2512     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2513                               cast<BinaryOperator>(I)->isExact(),
2514                               TD, DT);
2515     break;
2516   case Instruction::And:
2517     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2518     break;
2519   case Instruction::Or:
2520     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2521     break;
2522   case Instruction::Xor:
2523     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2524     break;
2525   case Instruction::ICmp:
2526     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2527                               I->getOperand(0), I->getOperand(1), TD, DT);
2528     break;
2529   case Instruction::FCmp:
2530     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2531                               I->getOperand(0), I->getOperand(1), TD, DT);
2532     break;
2533   case Instruction::Select:
2534     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2535                                 I->getOperand(2), TD, DT);
2536     break;
2537   case Instruction::GetElementPtr: {
2538     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2539     Result = SimplifyGEPInst(Ops, TD, DT);
2540     break;
2541   }
2542   case Instruction::InsertValue: {
2543     InsertValueInst *IV = cast<InsertValueInst>(I);
2544     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2545                                      IV->getInsertedValueOperand(),
2546                                      IV->getIndices(), TD, DT);
2547     break;
2548   }
2549   case Instruction::PHI:
2550     Result = SimplifyPHINode(cast<PHINode>(I), DT);
2551     break;
2552   }
2553
2554   /// If called on unreachable code, the above logic may report that the
2555   /// instruction simplified to itself.  Make life easier for users by
2556   /// detecting that case here, returning a safe value instead.
2557   return Result == I ? UndefValue::get(I->getType()) : Result;
2558 }
2559
2560 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2561 /// delete the From instruction.  In addition to a basic RAUW, this does a
2562 /// recursive simplification of the newly formed instructions.  This catches
2563 /// things where one simplification exposes other opportunities.  This only
2564 /// simplifies and deletes scalar operations, it does not change the CFG.
2565 ///
2566 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2567                                      const TargetData *TD,
2568                                      const DominatorTree *DT) {
2569   assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2570
2571   // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2572   // we can know if it gets deleted out from under us or replaced in a
2573   // recursive simplification.
2574   WeakVH FromHandle(From);
2575   WeakVH ToHandle(To);
2576
2577   while (!From->use_empty()) {
2578     // Update the instruction to use the new value.
2579     Use &TheUse = From->use_begin().getUse();
2580     Instruction *User = cast<Instruction>(TheUse.getUser());
2581     TheUse = To;
2582
2583     // Check to see if the instruction can be folded due to the operand
2584     // replacement.  For example changing (or X, Y) into (or X, -1) can replace
2585     // the 'or' with -1.
2586     Value *SimplifiedVal;
2587     {
2588       // Sanity check to make sure 'User' doesn't dangle across
2589       // SimplifyInstruction.
2590       AssertingVH<> UserHandle(User);
2591
2592       SimplifiedVal = SimplifyInstruction(User, TD, DT);
2593       if (SimplifiedVal == 0) continue;
2594     }
2595
2596     // Recursively simplify this user to the new value.
2597     ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2598     From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2599     To = ToHandle;
2600
2601     assert(ToHandle && "To value deleted by recursive simplification?");
2602
2603     // If the recursive simplification ended up revisiting and deleting
2604     // 'From' then we're done.
2605     if (From == 0)
2606       return;
2607   }
2608
2609   // If 'From' has value handles referring to it, do a real RAUW to update them.
2610   From->replaceAllUsesWith(To);
2611
2612   From->eraseFromParent();
2613 }