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