8f59971e06f127c49d53373269b6f362b6f1cef3
[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/Support/PatternMatch.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Target/TargetData.h"
28 using namespace llvm;
29 using namespace llvm::PatternMatch;
30
31 #define RecursionLimit 4
32
33 STATISTIC(NumExpand,  "Number of expansions");
34 STATISTIC(NumFactor , "Number of factorizations");
35 STATISTIC(NumReassoc, "Number of reassociations");
36
37 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
38                               const DominatorTree *, unsigned);
39 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
40                             const DominatorTree *, unsigned);
41 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
42                               const DominatorTree *, unsigned);
43 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
44                              const DominatorTree *, unsigned);
45 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
46                               const DominatorTree *, unsigned);
47
48 /// equal - Return true if the given values are known to be equal, false if they
49 /// are not equal or it is not clear whether they are equal or not.
50 static bool equal(Value *A, Value *B, unsigned MaxRecurse) {
51   // If the pointers are equal then the values are!
52   if (A == B)
53     return true;
54   // From this point on either recursion is used or the result is false, so bail
55   // out at once if we already hit the recursion limit.
56   if (!MaxRecurse--)
57     return false;
58   // If these are instructions, see if they compute the same value.
59   Instruction *AI = dyn_cast<Instruction>(A), *BI = dyn_cast<Instruction>(B);
60   if (!AI || !BI)
61     return false;
62   // If one of the instructions has extra flags attached then be conservative
63   // and say that the instructions differ.
64   if (!AI->hasSameSubclassOptionalData(BI))
65     return false;
66   // For some reason alloca's are not considered to read or write memory, yet
67   // each one nonetheless manages to return a different value...
68   if (isa<AllocaInst>(AI))
69     return false;
70   // Do not consider instructions to be equal if they may access memory.
71   if (AI->mayReadFromMemory() || AI->mayWriteToMemory())
72     return false;
73   // If the instructions do not perform the same computation then bail out.
74   if (!BI->isSameOperationAs(AI))
75     return false;
76
77   // Check whether all operands are equal.  If they are then the instructions
78   // have the same value.
79   bool AllOperandsEqual = true;
80   for (unsigned i = 0, e = AI->getNumOperands(); i != e; ++i)
81     if (!equal(AI->getOperand(i), BI->getOperand(i), MaxRecurse)) {
82       AllOperandsEqual = false;
83       break;
84     }
85   if (AllOperandsEqual)
86     return true;
87
88   // If the instructions are commutative and their operands are equal when
89   // swapped then the instructions have the same value.
90   return AI->isCommutative() &&
91     equal(AI->getOperand(0), BI->getOperand(1), MaxRecurse) &&
92     equal(AI->getOperand(1), BI->getOperand(0), MaxRecurse);
93 }
94
95 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
96 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
97   Instruction *I = dyn_cast<Instruction>(V);
98   if (!I)
99     // Arguments and constants dominate all instructions.
100     return true;
101
102   // If we have a DominatorTree then do a precise test.
103   if (DT)
104     return DT->dominates(I, P);
105
106   // Otherwise, if the instruction is in the entry block, and is not an invoke,
107   // then it obviously dominates all phi nodes.
108   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
109       !isa<InvokeInst>(I))
110     return true;
111
112   return false;
113 }
114
115 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
116 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
117 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
118 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
119 /// Returns the simplified value, or null if no simplification was performed.
120 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
121                           unsigned OpcToExpand, const TargetData *TD,
122                           const DominatorTree *DT, unsigned MaxRecurse) {
123   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
124   // Recursion is always used, so bail out at once if we already hit the limit.
125   if (!MaxRecurse--)
126     return 0;
127
128   // Check whether the expression has the form "(A op' B) op C".
129   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
130     if (Op0->getOpcode() == OpcodeToExpand) {
131       // It does!  Try turning it into "(A op C) op' (B op C)".
132       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
133       // Do "A op C" and "B op C" both simplify?
134       if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
135         if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
136           // They do! Return "L op' R" if it simplifies or is already available.
137           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
138           if ((equal(L, A, MaxRecurse) && equal(R, B, MaxRecurse)) ||
139               (Instruction::isCommutative(OpcodeToExpand) &&
140                equal(L, B, MaxRecurse) && equal(R, A, MaxRecurse))) {
141             ++NumExpand;
142             return LHS;
143           }
144           // Otherwise return "L op' R" if it simplifies.
145           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
146                                        MaxRecurse)) {
147             ++NumExpand;
148             return V;
149           }
150         }
151     }
152
153   // Check whether the expression has the form "A op (B op' C)".
154   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
155     if (Op1->getOpcode() == OpcodeToExpand) {
156       // It does!  Try turning it into "(A op B) op' (A op C)".
157       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
158       // Do "A op B" and "A op C" both simplify?
159       if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
160         if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
161           // They do! Return "L op' R" if it simplifies or is already available.
162           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
163           if ((equal(L, B, MaxRecurse) && equal(R, C, MaxRecurse)) ||
164               (Instruction::isCommutative(OpcodeToExpand) &&
165                equal(L, C, MaxRecurse) && equal(R, B, MaxRecurse))) {
166             ++NumExpand;
167             return RHS;
168           }
169           // Otherwise return "L op' R" if it simplifies.
170           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
171                                        MaxRecurse)) {
172             ++NumExpand;
173             return V;
174           }
175         }
176     }
177
178   return 0;
179 }
180
181 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
182 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
183 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
184 /// Returns the simplified value, or null if no simplification was performed.
185 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
186                              unsigned OpcToExtract, const TargetData *TD,
187                              const DominatorTree *DT, unsigned MaxRecurse) {
188   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
189   // Recursion is always used, so bail out at once if we already hit the limit.
190   if (!MaxRecurse--)
191     return 0;
192
193   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
195
196   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
197       !Op1 || Op1->getOpcode() != OpcodeToExtract)
198     return 0;
199
200   // The expression has the form "(A op' B) op (C op' D)".
201   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
202   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
203
204   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
205   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
206   // commutative case, "(A op' B) op (C op' A)"?
207   bool AEqualsC = equal(A, C, MaxRecurse);
208   if (AEqualsC || (Instruction::isCommutative(OpcodeToExtract) &&
209                    equal(A, D, MaxRecurse))) {
210     Value *DD = AEqualsC ? D : C;
211     // Form "A op' (B op DD)" if it simplifies completely.
212     // Does "B op DD" simplify?
213     if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
214       // It does!  Return "A op' V" if it simplifies or is already available.
215       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
216       // "A op' V" is just the RHS.
217       if (equal(V, B, MaxRecurse)) {
218         ++NumFactor;
219         return LHS;
220       }
221       if (equal(V, DD, MaxRecurse)) {
222         ++NumFactor;
223         return RHS;
224       }
225       // Otherwise return "A op' V" if it simplifies.
226       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
227         ++NumFactor;
228         return W;
229       }
230     }
231   }
232
233   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
234   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
235   // commutative case, "(A op' B) op (B op' D)"?
236   bool BEqualsD = equal(B, D, MaxRecurse);
237   if (BEqualsD || (Instruction::isCommutative(OpcodeToExtract) &&
238                    equal(B, C, MaxRecurse))) {
239     Value *CC = BEqualsD ? C : D;
240     // Form "(A op CC) op' B" if it simplifies completely..
241     // Does "A op CC" simplify?
242     if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
243       // It does!  Return "V op' B" if it simplifies or is already available.
244       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
245       // "V op' B" is just the RHS.
246       if (equal(V, A, MaxRecurse)) {
247         ++NumFactor;
248         return LHS;
249       }
250       if (equal(V, CC, MaxRecurse)) {
251         ++NumFactor;
252         return RHS;
253       }
254       // Otherwise return "V op' B" if it simplifies.
255       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
256         ++NumFactor;
257         return W;
258       }
259     }
260   }
261
262   return 0;
263 }
264
265 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
266 /// operations.  Returns the simpler value, or null if none was found.
267 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
268                                        const TargetData *TD,
269                                        const DominatorTree *DT,
270                                        unsigned MaxRecurse) {
271   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
272   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
273
274   // Recursion is always used, so bail out at once if we already hit the limit.
275   if (!MaxRecurse--)
276     return 0;
277
278   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
279   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
280
281   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
282   if (Op0 && Op0->getOpcode() == Opcode) {
283     Value *A = Op0->getOperand(0);
284     Value *B = Op0->getOperand(1);
285     Value *C = RHS;
286
287     // Does "B op C" simplify?
288     if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
289       // It does!  Return "A op V" if it simplifies or is already available.
290       // If V equals B then "A op V" is just the LHS.
291       if (equal(V, B, MaxRecurse)) return LHS;
292       // Otherwise return "A op V" if it simplifies.
293       if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
294         ++NumReassoc;
295         return W;
296       }
297     }
298   }
299
300   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
301   if (Op1 && Op1->getOpcode() == Opcode) {
302     Value *A = LHS;
303     Value *B = Op1->getOperand(0);
304     Value *C = Op1->getOperand(1);
305
306     // Does "A op B" simplify?
307     if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
308       // It does!  Return "V op C" if it simplifies or is already available.
309       // If V equals B then "V op C" is just the RHS.
310       if (equal(V, B, MaxRecurse)) return RHS;
311       // Otherwise return "V op C" if it simplifies.
312       if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
313         ++NumReassoc;
314         return W;
315       }
316     }
317   }
318
319   // The remaining transforms require commutativity as well as associativity.
320   if (!Instruction::isCommutative(Opcode))
321     return 0;
322
323   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
324   if (Op0 && Op0->getOpcode() == Opcode) {
325     Value *A = Op0->getOperand(0);
326     Value *B = Op0->getOperand(1);
327     Value *C = RHS;
328
329     // Does "C op A" simplify?
330     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
331       // It does!  Return "V op B" if it simplifies or is already available.
332       // If V equals A then "V op B" is just the LHS.
333       if (equal(V, A, MaxRecurse)) return LHS;
334       // Otherwise return "V op B" if it simplifies.
335       if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
336         ++NumReassoc;
337         return W;
338       }
339     }
340   }
341
342   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
343   if (Op1 && Op1->getOpcode() == Opcode) {
344     Value *A = LHS;
345     Value *B = Op1->getOperand(0);
346     Value *C = Op1->getOperand(1);
347
348     // Does "C op A" simplify?
349     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
350       // It does!  Return "B op V" if it simplifies or is already available.
351       // If V equals C then "B op V" is just the RHS.
352       if (equal(V, C, MaxRecurse)) return RHS;
353       // Otherwise return "B op V" if it simplifies.
354       if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
355         ++NumReassoc;
356         return W;
357       }
358     }
359   }
360
361   return 0;
362 }
363
364 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
365 /// instruction as an operand, try to simplify the binop by seeing whether
366 /// evaluating it on both branches of the select results in the same value.
367 /// Returns the common value if so, otherwise returns null.
368 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
369                                     const TargetData *TD,
370                                     const DominatorTree *DT,
371                                     unsigned MaxRecurse) {
372   // Recursion is always used, so bail out at once if we already hit the limit.
373   if (!MaxRecurse--)
374     return 0;
375
376   SelectInst *SI;
377   if (isa<SelectInst>(LHS)) {
378     SI = cast<SelectInst>(LHS);
379   } else {
380     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
381     SI = cast<SelectInst>(RHS);
382   }
383
384   // Evaluate the BinOp on the true and false branches of the select.
385   Value *TV;
386   Value *FV;
387   if (SI == LHS) {
388     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
389     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
390   } else {
391     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
392     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
393   }
394
395   // If they both failed to simplify then return null.
396   if (!TV && !FV)
397     return 0;
398
399   // If they simplified to the same value, then return the common value.
400   if (TV && FV && equal(TV, FV, MaxRecurse))
401     return TV;
402
403   // If one branch simplified to undef, return the other one.
404   if (TV && isa<UndefValue>(TV))
405     return FV;
406   if (FV && isa<UndefValue>(FV))
407     return TV;
408
409   // If applying the operation did not change the true and false select values,
410   // then the result of the binop is the select itself.
411   if (TV && equal(TV, SI->getTrueValue(), MaxRecurse) &&
412       FV && equal(FV, SI->getFalseValue(), MaxRecurse))
413     return SI;
414
415   // If one branch simplified and the other did not, and the simplified
416   // value is equal to the unsimplified one, return the simplified value.
417   // For example, select (cond, X, X & Z) & Z -> X & Z.
418   if ((FV && !TV) || (TV && !FV)) {
419     // Check that the simplified value has the form "X op Y" where "op" is the
420     // same as the original operation.
421     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
422     if (Simplified && Simplified->getOpcode() == Opcode) {
423       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
424       // We already know that "op" is the same as for the simplified value.  See
425       // if the operands match too.  If so, return the simplified value.
426       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
427       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
428       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
429       if (equal(Simplified->getOperand(0), UnsimplifiedLHS, MaxRecurse) &&
430           equal(Simplified->getOperand(1), UnsimplifiedRHS, MaxRecurse))
431         return Simplified;
432       if (Simplified->isCommutative() &&
433           equal(Simplified->getOperand(1), UnsimplifiedLHS, MaxRecurse) &&
434           equal(Simplified->getOperand(0), UnsimplifiedRHS, MaxRecurse))
435         return Simplified;
436     }
437   }
438
439   return 0;
440 }
441
442 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
443 /// try to simplify the comparison by seeing whether both branches of the select
444 /// result in the same value.  Returns the common value if so, otherwise returns
445 /// null.
446 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
447                                   Value *RHS, const TargetData *TD,
448                                   const DominatorTree *DT,
449                                   unsigned MaxRecurse) {
450   // Recursion is always used, so bail out at once if we already hit the limit.
451   if (!MaxRecurse--)
452     return 0;
453
454   // Make sure the select is on the LHS.
455   if (!isa<SelectInst>(LHS)) {
456     std::swap(LHS, RHS);
457     Pred = CmpInst::getSwappedPredicate(Pred);
458   }
459   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
460   SelectInst *SI = cast<SelectInst>(LHS);
461
462   // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
463   // Does "cmp TV, RHS" simplify?
464   if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
465                                     MaxRecurse))
466     // It does!  Does "cmp FV, RHS" simplify?
467     if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
468                                       MaxRecurse))
469       // It does!  If they simplified to the same value, then use it as the
470       // result of the original comparison.
471       if (equal(TCmp, FCmp, MaxRecurse))
472         return TCmp;
473   return 0;
474 }
475
476 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
477 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
478 /// it on the incoming phi values yields the same result for every value.  If so
479 /// returns the common value, otherwise returns null.
480 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
481                                  const TargetData *TD, const DominatorTree *DT,
482                                  unsigned MaxRecurse) {
483   // Recursion is always used, so bail out at once if we already hit the limit.
484   if (!MaxRecurse--)
485     return 0;
486
487   PHINode *PI;
488   if (isa<PHINode>(LHS)) {
489     PI = cast<PHINode>(LHS);
490     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
491     if (!ValueDominatesPHI(RHS, PI, DT))
492       return 0;
493   } else {
494     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
495     PI = cast<PHINode>(RHS);
496     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
497     if (!ValueDominatesPHI(LHS, PI, DT))
498       return 0;
499   }
500
501   // Evaluate the BinOp on the incoming phi values.
502   Value *CommonValue = 0;
503   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
504     Value *Incoming = PI->getIncomingValue(i);
505     // If the incoming value is the phi node itself, it can safely be skipped.
506     if (Incoming == PI) continue;
507     Value *V = PI == LHS ?
508       SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
509       SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
510     // If the operation failed to simplify, or simplified to a different value
511     // to previously, then give up.
512     if (!V || (CommonValue && V != CommonValue))
513       return 0;
514     CommonValue = V;
515   }
516
517   return CommonValue;
518 }
519
520 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
521 /// try to simplify the comparison by seeing whether comparing with all of the
522 /// incoming phi values yields the same result every time.  If so returns the
523 /// common result, otherwise returns null.
524 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
525                                const TargetData *TD, const DominatorTree *DT,
526                                unsigned MaxRecurse) {
527   // Recursion is always used, so bail out at once if we already hit the limit.
528   if (!MaxRecurse--)
529     return 0;
530
531   // Make sure the phi is on the LHS.
532   if (!isa<PHINode>(LHS)) {
533     std::swap(LHS, RHS);
534     Pred = CmpInst::getSwappedPredicate(Pred);
535   }
536   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
537   PHINode *PI = cast<PHINode>(LHS);
538
539   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
540   if (!ValueDominatesPHI(RHS, PI, DT))
541     return 0;
542
543   // Evaluate the BinOp on the incoming phi values.
544   Value *CommonValue = 0;
545   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
546     Value *Incoming = PI->getIncomingValue(i);
547     // If the incoming value is the phi node itself, it can safely be skipped.
548     if (Incoming == PI) continue;
549     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
550     // If the operation failed to simplify, or simplified to a different value
551     // to previously, then give up.
552     if (!V || (CommonValue && V != CommonValue))
553       return 0;
554     CommonValue = V;
555   }
556
557   return CommonValue;
558 }
559
560 /// SimplifyAddInst - Given operands for an Add, see if we can
561 /// fold the result.  If not, this returns null.
562 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
563                               const TargetData *TD, const DominatorTree *DT,
564                               unsigned MaxRecurse) {
565   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
566     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
567       Constant *Ops[] = { CLHS, CRHS };
568       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
569                                       Ops, 2, TD);
570     }
571
572     // Canonicalize the constant to the RHS.
573     std::swap(Op0, Op1);
574   }
575
576   // X + undef -> undef
577   if (isa<UndefValue>(Op1))
578     return Op1;
579
580   // X + 0 -> X
581   if (match(Op1, m_Zero()))
582     return Op0;
583
584   // X + (Y - X) -> Y
585   // (Y - X) + X -> Y
586   // Eg: X + -X -> 0
587   Value *X = 0, *Y = 0;
588   if ((match(Op1, m_Sub(m_Value(Y), m_Value(X))) && equal(X, Op0, MaxRecurse))||
589       (match(Op0, m_Sub(m_Value(Y), m_Value(X))) && equal(X, Op1, MaxRecurse)))
590     return Y;
591
592   // X + ~X -> -1   since   ~X = -X-1
593   if ((match(Op0, m_Not(m_Value(X))) && equal(X, Op1, MaxRecurse)) ||
594       (match(Op1, m_Not(m_Value(X))) && equal(X, Op0, MaxRecurse)))
595     return Constant::getAllOnesValue(Op0->getType());
596
597   /// i1 add -> xor.
598   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
599     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
600       return V;
601
602   // Try some generic simplifications for associative operations.
603   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
604                                           MaxRecurse))
605     return V;
606
607   // Mul distributes over Add.  Try some generic simplifications based on this.
608   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
609                                 TD, DT, MaxRecurse))
610     return V;
611
612   // Threading Add over selects and phi nodes is pointless, so don't bother.
613   // Threading over the select in "A + select(cond, B, C)" means evaluating
614   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
615   // only if B and C are equal.  If B and C are equal then (since we assume
616   // that operands have already been simplified) "select(cond, B, C)" should
617   // have been simplified to the common value of B and C already.  Analysing
618   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
619   // for threading over phi nodes.
620
621   return 0;
622 }
623
624 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
625                              const TargetData *TD, const DominatorTree *DT) {
626   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
627 }
628
629 /// SimplifySubInst - Given operands for a Sub, see if we can
630 /// fold the result.  If not, this returns null.
631 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
632                               const TargetData *TD, const DominatorTree *DT,
633                               unsigned MaxRecurse) {
634   if (Constant *CLHS = dyn_cast<Constant>(Op0))
635     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
636       Constant *Ops[] = { CLHS, CRHS };
637       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
638                                       Ops, 2, TD);
639     }
640
641   // X - undef -> undef
642   // undef - X -> undef
643   if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
644     return UndefValue::get(Op0->getType());
645
646   // X - 0 -> X
647   if (match(Op1, m_Zero()))
648     return Op0;
649
650   // X - X -> 0
651   if (equal(Op0, Op1, MaxRecurse))
652     return Constant::getNullValue(Op0->getType());
653
654   // (X + Y) - Y -> X
655   // (Y + X) - Y -> X
656   Value *X = 0, *Y = 0;
657   if ((match(Op0, m_Add(m_Value(X), m_Value(Y))) && equal(Y, Op1, MaxRecurse))||
658       (match(Op0, m_Add(m_Value(Y), m_Value(X))) && equal(Y, Op1, MaxRecurse)))
659     return X;
660
661   /// i1 sub -> xor.
662   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
663     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
664       return V;
665
666   // Mul distributes over Sub.  Try some generic simplifications based on this.
667   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
668                                 TD, DT, MaxRecurse))
669     return V;
670
671   // Threading Sub over selects and phi nodes is pointless, so don't bother.
672   // Threading over the select in "A - select(cond, B, C)" means evaluating
673   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
674   // only if B and C are equal.  If B and C are equal then (since we assume
675   // that operands have already been simplified) "select(cond, B, C)" should
676   // have been simplified to the common value of B and C already.  Analysing
677   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
678   // for threading over phi nodes.
679
680   return 0;
681 }
682
683 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
684                              const TargetData *TD, const DominatorTree *DT) {
685   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
686 }
687
688 /// SimplifyMulInst - Given operands for a Mul, see if we can
689 /// fold the result.  If not, this returns null.
690 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
691                               const DominatorTree *DT, unsigned MaxRecurse) {
692   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
693     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
694       Constant *Ops[] = { CLHS, CRHS };
695       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
696                                       Ops, 2, TD);
697     }
698
699     // Canonicalize the constant to the RHS.
700     std::swap(Op0, Op1);
701   }
702
703   // X * undef -> 0
704   if (isa<UndefValue>(Op1))
705     return Constant::getNullValue(Op0->getType());
706
707   // X * 0 -> 0
708   if (match(Op1, m_Zero()))
709     return Op1;
710
711   // X * 1 -> X
712   if (match(Op1, m_One()))
713     return Op0;
714
715   /// i1 mul -> and.
716   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
717     if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
718       return V;
719
720   // Try some generic simplifications for associative operations.
721   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
722                                           MaxRecurse))
723     return V;
724
725   // Mul distributes over Add.  Try some generic simplifications based on this.
726   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
727                              TD, DT, MaxRecurse))
728     return V;
729
730   // If the operation is with the result of a select instruction, check whether
731   // operating on either branch of the select always yields the same value.
732   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
733     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
734                                          MaxRecurse))
735       return V;
736
737   // If the operation is with the result of a phi instruction, check whether
738   // operating on all incoming values of the phi always yields the same value.
739   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
740     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
741                                       MaxRecurse))
742       return V;
743
744   return 0;
745 }
746
747 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
748                              const DominatorTree *DT) {
749   return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
750 }
751
752 /// SimplifyAndInst - Given operands for an And, see if we can
753 /// fold the result.  If not, this returns null.
754 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
755                               const DominatorTree *DT, unsigned MaxRecurse) {
756   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
757     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
758       Constant *Ops[] = { CLHS, CRHS };
759       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
760                                       Ops, 2, TD);
761     }
762
763     // Canonicalize the constant to the RHS.
764     std::swap(Op0, Op1);
765   }
766
767   // X & undef -> 0
768   if (isa<UndefValue>(Op1))
769     return Constant::getNullValue(Op0->getType());
770
771   // X & X = X
772   if (equal(Op0, Op1, MaxRecurse))
773     return Op0;
774
775   // X & 0 = 0
776   if (match(Op1, m_Zero()))
777     return Op1;
778
779   // X & -1 = X
780   if (match(Op1, m_AllOnes()))
781     return Op0;
782
783   // A & ~A  =  ~A & A  =  0
784   Value *A = 0, *B = 0;
785   if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
786       (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
787     return Constant::getNullValue(Op0->getType());
788
789   // (A | ?) & A = A
790   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
791       (equal(A, Op1, MaxRecurse) || equal(B, Op1, MaxRecurse)))
792     return Op1;
793
794   // A & (A | ?) = A
795   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
796       (equal(A, Op0, MaxRecurse) || equal(B, Op0, MaxRecurse)))
797     return Op0;
798
799   // Try some generic simplifications for associative operations.
800   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
801                                           MaxRecurse))
802     return V;
803
804   // And distributes over Or.  Try some generic simplifications based on this.
805   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
806                              TD, DT, MaxRecurse))
807     return V;
808
809   // And distributes over Xor.  Try some generic simplifications based on this.
810   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
811                              TD, DT, MaxRecurse))
812     return V;
813
814   // Or distributes over And.  Try some generic simplifications based on this.
815   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
816                                 TD, DT, MaxRecurse))
817     return V;
818
819   // If the operation is with the result of a select instruction, check whether
820   // operating on either branch of the select always yields the same value.
821   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
822     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
823                                          MaxRecurse))
824       return V;
825
826   // If the operation is with the result of a phi instruction, check whether
827   // operating on all incoming values of the phi always yields the same value.
828   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
829     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
830                                       MaxRecurse))
831       return V;
832
833   return 0;
834 }
835
836 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
837                              const DominatorTree *DT) {
838   return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
839 }
840
841 /// SimplifyOrInst - Given operands for an Or, see if we can
842 /// fold the result.  If not, this returns null.
843 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
844                              const DominatorTree *DT, unsigned MaxRecurse) {
845   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
846     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
847       Constant *Ops[] = { CLHS, CRHS };
848       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
849                                       Ops, 2, TD);
850     }
851
852     // Canonicalize the constant to the RHS.
853     std::swap(Op0, Op1);
854   }
855
856   // X | undef -> -1
857   if (isa<UndefValue>(Op1))
858     return Constant::getAllOnesValue(Op0->getType());
859
860   // X | X = X
861   if (equal(Op0, Op1, MaxRecurse))
862     return Op0;
863
864   // X | 0 = X
865   if (match(Op1, m_Zero()))
866     return Op0;
867
868   // X | -1 = -1
869   if (match(Op1, m_AllOnes()))
870     return Op1;
871
872   // A | ~A  =  ~A | A  =  -1
873   Value *A = 0, *B = 0;
874   if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
875       (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
876     return Constant::getAllOnesValue(Op0->getType());
877
878   // (A & ?) | A = A
879   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
880       (equal(A, Op1, MaxRecurse) || equal(B, Op1, MaxRecurse)))
881     return Op1;
882
883   // A | (A & ?) = A
884   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
885       (equal(A, Op0, MaxRecurse) || equal(B, Op0, MaxRecurse)))
886     return Op0;
887
888   // Try some generic simplifications for associative operations.
889   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
890                                           MaxRecurse))
891     return V;
892
893   // Or distributes over And.  Try some generic simplifications based on this.
894   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
895                              TD, DT, MaxRecurse))
896     return V;
897
898   // And distributes over Or.  Try some generic simplifications based on this.
899   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
900                                 TD, DT, MaxRecurse))
901     return V;
902
903   // If the operation is with the result of a select instruction, check whether
904   // operating on either branch of the select always yields the same value.
905   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
906     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
907                                          MaxRecurse))
908       return V;
909
910   // If the operation is with the result of a phi instruction, check whether
911   // operating on all incoming values of the phi always yields the same value.
912   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
913     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
914                                       MaxRecurse))
915       return V;
916
917   return 0;
918 }
919
920 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
921                             const DominatorTree *DT) {
922   return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
923 }
924
925 /// SimplifyXorInst - Given operands for a Xor, see if we can
926 /// fold the result.  If not, this returns null.
927 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
928                               const DominatorTree *DT, unsigned MaxRecurse) {
929   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
930     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
931       Constant *Ops[] = { CLHS, CRHS };
932       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
933                                       Ops, 2, TD);
934     }
935
936     // Canonicalize the constant to the RHS.
937     std::swap(Op0, Op1);
938   }
939
940   // A ^ undef -> undef
941   if (isa<UndefValue>(Op1))
942     return Op1;
943
944   // A ^ 0 = A
945   if (match(Op1, m_Zero()))
946     return Op0;
947
948   // A ^ A = 0
949   if (equal(Op0, Op1, MaxRecurse))
950     return Constant::getNullValue(Op0->getType());
951
952   // A ^ ~A  =  ~A ^ A  =  -1
953   Value *A = 0;
954   if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
955       (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
956     return Constant::getAllOnesValue(Op0->getType());
957
958   // Try some generic simplifications for associative operations.
959   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
960                                           MaxRecurse))
961     return V;
962
963   // And distributes over Xor.  Try some generic simplifications based on this.
964   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
965                                 TD, DT, MaxRecurse))
966     return V;
967
968   // Threading Xor over selects and phi nodes is pointless, so don't bother.
969   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
970   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
971   // only if B and C are equal.  If B and C are equal then (since we assume
972   // that operands have already been simplified) "select(cond, B, C)" should
973   // have been simplified to the common value of B and C already.  Analysing
974   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
975   // for threading over phi nodes.
976
977   return 0;
978 }
979
980 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
981                              const DominatorTree *DT) {
982   return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
983 }
984
985 static const Type *GetCompareTy(Value *Op) {
986   return CmpInst::makeCmpResultType(Op->getType());
987 }
988
989 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
990 /// fold the result.  If not, this returns null.
991 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
992                                const TargetData *TD, const DominatorTree *DT,
993                                unsigned MaxRecurse) {
994   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
995   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
996
997   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
998     if (Constant *CRHS = dyn_cast<Constant>(RHS))
999       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1000
1001     // If we have a constant, make sure it is on the RHS.
1002     std::swap(LHS, RHS);
1003     Pred = CmpInst::getSwappedPredicate(Pred);
1004   }
1005
1006   // ITy - This is the return type of the compare we're considering.
1007   const Type *ITy = GetCompareTy(LHS);
1008
1009   // icmp X, X -> true/false
1010   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1011   // because X could be 0.
1012   if (isa<UndefValue>(RHS) || equal(LHS, RHS, MaxRecurse))
1013     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1014
1015   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1016   // addresses never equal each other!  We already know that Op0 != Op1.
1017   if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
1018        isa<ConstantPointerNull>(LHS)) &&
1019       (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1020        isa<ConstantPointerNull>(RHS)))
1021     return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1022
1023   // See if we are doing a comparison with a constant.
1024   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1025     // If we have an icmp le or icmp ge instruction, turn it into the
1026     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
1027     // them being folded in the code below.
1028     switch (Pred) {
1029     default: break;
1030     case ICmpInst::ICMP_ULE:
1031       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
1032         return ConstantInt::getTrue(CI->getContext());
1033       break;
1034     case ICmpInst::ICMP_SLE:
1035       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
1036         return ConstantInt::getTrue(CI->getContext());
1037       break;
1038     case ICmpInst::ICMP_UGE:
1039       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
1040         return ConstantInt::getTrue(CI->getContext());
1041       break;
1042     case ICmpInst::ICMP_SGE:
1043       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
1044         return ConstantInt::getTrue(CI->getContext());
1045       break;
1046     }
1047   }
1048
1049   // If the comparison is with the result of a select instruction, check whether
1050   // comparing with either branch of the select always yields the same value.
1051   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1052     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1053       return V;
1054
1055   // If the comparison is with the result of a phi instruction, check whether
1056   // doing the compare with each incoming phi value yields a common result.
1057   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1058     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1059       return V;
1060
1061   return 0;
1062 }
1063
1064 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1065                               const TargetData *TD, const DominatorTree *DT) {
1066   return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1067 }
1068
1069 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1070 /// fold the result.  If not, this returns null.
1071 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1072                                const TargetData *TD, const DominatorTree *DT,
1073                                unsigned MaxRecurse) {
1074   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1075   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1076
1077   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1078     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1079       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1080
1081     // If we have a constant, make sure it is on the RHS.
1082     std::swap(LHS, RHS);
1083     Pred = CmpInst::getSwappedPredicate(Pred);
1084   }
1085
1086   // Fold trivial predicates.
1087   if (Pred == FCmpInst::FCMP_FALSE)
1088     return ConstantInt::get(GetCompareTy(LHS), 0);
1089   if (Pred == FCmpInst::FCMP_TRUE)
1090     return ConstantInt::get(GetCompareTy(LHS), 1);
1091
1092   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
1093     return UndefValue::get(GetCompareTy(LHS));
1094
1095   // fcmp x,x -> true/false.  Not all compares are foldable.
1096   if (equal(LHS, RHS, MaxRecurse)) {
1097     if (CmpInst::isTrueWhenEqual(Pred))
1098       return ConstantInt::get(GetCompareTy(LHS), 1);
1099     if (CmpInst::isFalseWhenEqual(Pred))
1100       return ConstantInt::get(GetCompareTy(LHS), 0);
1101   }
1102
1103   // Handle fcmp with constant RHS
1104   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1105     // If the constant is a nan, see if we can fold the comparison based on it.
1106     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1107       if (CFP->getValueAPF().isNaN()) {
1108         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
1109           return ConstantInt::getFalse(CFP->getContext());
1110         assert(FCmpInst::isUnordered(Pred) &&
1111                "Comparison must be either ordered or unordered!");
1112         // True if unordered.
1113         return ConstantInt::getTrue(CFP->getContext());
1114       }
1115       // Check whether the constant is an infinity.
1116       if (CFP->getValueAPF().isInfinity()) {
1117         if (CFP->getValueAPF().isNegative()) {
1118           switch (Pred) {
1119           case FCmpInst::FCMP_OLT:
1120             // No value is ordered and less than negative infinity.
1121             return ConstantInt::getFalse(CFP->getContext());
1122           case FCmpInst::FCMP_UGE:
1123             // All values are unordered with or at least negative infinity.
1124             return ConstantInt::getTrue(CFP->getContext());
1125           default:
1126             break;
1127           }
1128         } else {
1129           switch (Pred) {
1130           case FCmpInst::FCMP_OGT:
1131             // No value is ordered and greater than infinity.
1132             return ConstantInt::getFalse(CFP->getContext());
1133           case FCmpInst::FCMP_ULE:
1134             // All values are unordered with and at most infinity.
1135             return ConstantInt::getTrue(CFP->getContext());
1136           default:
1137             break;
1138           }
1139         }
1140       }
1141     }
1142   }
1143
1144   // If the comparison is with the result of a select instruction, check whether
1145   // comparing with either branch of the select always yields the same value.
1146   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1147     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1148       return V;
1149
1150   // If the comparison is with the result of a phi instruction, check whether
1151   // doing the compare with each incoming phi value yields a common result.
1152   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1153     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1154       return V;
1155
1156   return 0;
1157 }
1158
1159 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1160                               const TargetData *TD, const DominatorTree *DT) {
1161   return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1162 }
1163
1164 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1165 /// the result.  If not, this returns null.
1166 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1167                                  const TargetData *TD, const DominatorTree *,
1168                                  unsigned MaxRecurse) {
1169   // select true, X, Y  -> X
1170   // select false, X, Y -> Y
1171   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1172     return CB->getZExtValue() ? TrueVal : FalseVal;
1173
1174   // select C, X, X -> X
1175   if (equal(TrueVal, FalseVal, MaxRecurse))
1176     return TrueVal;
1177
1178   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
1179     return FalseVal;
1180   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
1181     return TrueVal;
1182   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
1183     if (isa<Constant>(TrueVal))
1184       return TrueVal;
1185     return FalseVal;
1186   }
1187
1188   return 0;
1189 }
1190
1191 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1192                                 const TargetData *TD, const DominatorTree *DT) {
1193   return ::SimplifySelectInst(CondVal, TrueVal, FalseVal, TD, DT,
1194                               RecursionLimit);
1195 }
1196
1197 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1198 /// fold the result.  If not, this returns null.
1199 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
1200                              const TargetData *TD, const DominatorTree *) {
1201   // The type of the GEP pointer operand.
1202   const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1203
1204   // getelementptr P -> P.
1205   if (NumOps == 1)
1206     return Ops[0];
1207
1208   if (isa<UndefValue>(Ops[0])) {
1209     // Compute the (pointer) type returned by the GEP instruction.
1210     const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1211                                                              NumOps-1);
1212     const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1213     return UndefValue::get(GEPTy);
1214   }
1215
1216   if (NumOps == 2) {
1217     // getelementptr P, 0 -> P.
1218     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1219       if (C->isZero())
1220         return Ops[0];
1221     // getelementptr P, N -> P if P points to a type of zero size.
1222     if (TD) {
1223       const Type *Ty = PtrTy->getElementType();
1224       if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
1225         return Ops[0];
1226     }
1227   }
1228
1229   // Check to see if this is constant foldable.
1230   for (unsigned i = 0; i != NumOps; ++i)
1231     if (!isa<Constant>(Ops[i]))
1232       return 0;
1233
1234   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1235                                         (Constant *const*)Ops+1, NumOps-1);
1236 }
1237
1238 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
1239 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1240   // If all of the PHI's incoming values are the same then replace the PHI node
1241   // with the common value.
1242   Value *CommonValue = 0;
1243   bool HasUndefInput = false;
1244   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1245     Value *Incoming = PN->getIncomingValue(i);
1246     // If the incoming value is the phi node itself, it can safely be skipped.
1247     if (Incoming == PN) continue;
1248     if (isa<UndefValue>(Incoming)) {
1249       // Remember that we saw an undef value, but otherwise ignore them.
1250       HasUndefInput = true;
1251       continue;
1252     }
1253     if (CommonValue && Incoming != CommonValue)
1254       return 0;  // Not the same, bail out.
1255     CommonValue = Incoming;
1256   }
1257
1258   // If CommonValue is null then all of the incoming values were either undef or
1259   // equal to the phi node itself.
1260   if (!CommonValue)
1261     return UndefValue::get(PN->getType());
1262
1263   // If we have a PHI node like phi(X, undef, X), where X is defined by some
1264   // instruction, we cannot return X as the result of the PHI node unless it
1265   // dominates the PHI block.
1266   if (HasUndefInput)
1267     return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1268
1269   return CommonValue;
1270 }
1271
1272
1273 //=== Helper functions for higher up the class hierarchy.
1274
1275 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1276 /// fold the result.  If not, this returns null.
1277 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1278                             const TargetData *TD, const DominatorTree *DT,
1279                             unsigned MaxRecurse) {
1280   switch (Opcode) {
1281   case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1282                                                 /* isNUW */ false, TD, DT,
1283                                                 MaxRecurse);
1284   case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1285                                                 /* isNUW */ false, TD, DT,
1286                                                 MaxRecurse);
1287   case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1288   case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1289   case Instruction::Or:  return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1290   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
1291   default:
1292     if (Constant *CLHS = dyn_cast<Constant>(LHS))
1293       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1294         Constant *COps[] = {CLHS, CRHS};
1295         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1296       }
1297
1298     // If the operation is associative, try some generic simplifications.
1299     if (Instruction::isAssociative(Opcode))
1300       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1301                                               MaxRecurse))
1302         return V;
1303
1304     // If the operation is with the result of a select instruction, check whether
1305     // operating on either branch of the select always yields the same value.
1306     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1307       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
1308                                            MaxRecurse))
1309         return V;
1310
1311     // If the operation is with the result of a phi instruction, check whether
1312     // operating on all incoming values of the phi always yields the same value.
1313     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1314       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
1315         return V;
1316
1317     return 0;
1318   }
1319 }
1320
1321 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1322                            const TargetData *TD, const DominatorTree *DT) {
1323   return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
1324 }
1325
1326 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1327 /// fold the result.
1328 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1329                               const TargetData *TD, const DominatorTree *DT,
1330                               unsigned MaxRecurse) {
1331   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
1332     return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1333   return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1334 }
1335
1336 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1337                              const TargetData *TD, const DominatorTree *DT) {
1338   return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1339 }
1340
1341 /// SimplifyInstruction - See if we can compute a simplified version of this
1342 /// instruction.  If not, this returns null.
1343 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1344                                  const DominatorTree *DT) {
1345   Value *Result;
1346
1347   switch (I->getOpcode()) {
1348   default:
1349     Result = ConstantFoldInstruction(I, TD);
1350     break;
1351   case Instruction::Add:
1352     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1353                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
1354                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1355                              TD, DT);
1356     break;
1357   case Instruction::Sub:
1358     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1359                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
1360                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1361                              TD, DT);
1362     break;
1363   case Instruction::Mul:
1364     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1365     break;
1366   case Instruction::And:
1367     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1368     break;
1369   case Instruction::Or:
1370     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1371     break;
1372   case Instruction::Xor:
1373     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1374     break;
1375   case Instruction::ICmp:
1376     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1377                               I->getOperand(0), I->getOperand(1), TD, DT);
1378     break;
1379   case Instruction::FCmp:
1380     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1381                               I->getOperand(0), I->getOperand(1), TD, DT);
1382     break;
1383   case Instruction::Select:
1384     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1385                                 I->getOperand(2), TD, DT);
1386     break;
1387   case Instruction::GetElementPtr: {
1388     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1389     Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1390     break;
1391   }
1392   case Instruction::PHI:
1393     Result = SimplifyPHINode(cast<PHINode>(I), DT);
1394     break;
1395   }
1396
1397   /// If called on unreachable code, the above logic may report that the
1398   /// instruction simplified to itself.  Make life easier for users by
1399   /// detecting that case here, returning a safe value instead.
1400   return Result == I ? UndefValue::get(I->getType()) : Result;
1401 }
1402
1403 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1404 /// delete the From instruction.  In addition to a basic RAUW, this does a
1405 /// recursive simplification of the newly formed instructions.  This catches
1406 /// things where one simplification exposes other opportunities.  This only
1407 /// simplifies and deletes scalar operations, it does not change the CFG.
1408 ///
1409 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
1410                                      const TargetData *TD,
1411                                      const DominatorTree *DT) {
1412   assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
1413
1414   // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1415   // we can know if it gets deleted out from under us or replaced in a
1416   // recursive simplification.
1417   WeakVH FromHandle(From);
1418   WeakVH ToHandle(To);
1419
1420   while (!From->use_empty()) {
1421     // Update the instruction to use the new value.
1422     Use &TheUse = From->use_begin().getUse();
1423     Instruction *User = cast<Instruction>(TheUse.getUser());
1424     TheUse = To;
1425
1426     // Check to see if the instruction can be folded due to the operand
1427     // replacement.  For example changing (or X, Y) into (or X, -1) can replace
1428     // the 'or' with -1.
1429     Value *SimplifiedVal;
1430     {
1431       // Sanity check to make sure 'User' doesn't dangle across
1432       // SimplifyInstruction.
1433       AssertingVH<> UserHandle(User);
1434
1435       SimplifiedVal = SimplifyInstruction(User, TD, DT);
1436       if (SimplifiedVal == 0) continue;
1437     }
1438
1439     // Recursively simplify this user to the new value.
1440     ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
1441     From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1442     To = ToHandle;
1443
1444     assert(ToHandle && "To value deleted by recursive simplification?");
1445
1446     // If the recursive simplification ended up revisiting and deleting
1447     // 'From' then we're done.
1448     if (From == 0)
1449       return;
1450   }
1451
1452   // If 'From' has value handles referring to it, do a real RAUW to update them.
1453   From->replaceAllUsesWith(To);
1454
1455   From->eraseFromParent();
1456 }