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