]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/InstructionSimplify.cpp
Update llvm to release_39 branch r278877.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Analysis / InstructionSimplify.cpp
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/VectorUtils.h"
29 #include "llvm/IR/ConstantRange.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include <algorithm>
38 using namespace llvm;
39 using namespace llvm::PatternMatch;
40
41 #define DEBUG_TYPE "instsimplify"
42
43 enum { RecursionLimit = 3 };
44
45 STATISTIC(NumExpand,  "Number of expansions");
46 STATISTIC(NumReassoc, "Number of reassociations");
47
48 namespace {
49 struct Query {
50   const DataLayout &DL;
51   const TargetLibraryInfo *TLI;
52   const DominatorTree *DT;
53   AssumptionCache *AC;
54   const Instruction *CxtI;
55
56   Query(const DataLayout &DL, const TargetLibraryInfo *tli,
57         const DominatorTree *dt, AssumptionCache *ac = nullptr,
58         const Instruction *cxti = nullptr)
59       : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
60 };
61 } // end anonymous namespace
62
63 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
65                             unsigned);
66 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67                               const Query &, unsigned);
68 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
69                               unsigned);
70 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
72 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
73
74 /// For a boolean type, or a vector of boolean type, return false, or
75 /// a vector with every element false, as appropriate for the type.
76 static Constant *getFalse(Type *Ty) {
77   assert(Ty->getScalarType()->isIntegerTy(1) &&
78          "Expected i1 type or a vector of i1!");
79   return Constant::getNullValue(Ty);
80 }
81
82 /// For a boolean type, or a vector of boolean type, return true, or
83 /// a vector with every element true, as appropriate for the type.
84 static Constant *getTrue(Type *Ty) {
85   assert(Ty->getScalarType()->isIntegerTy(1) &&
86          "Expected i1 type or a vector of i1!");
87   return Constant::getAllOnesValue(Ty);
88 }
89
90 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
91 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
92                           Value *RHS) {
93   CmpInst *Cmp = dyn_cast<CmpInst>(V);
94   if (!Cmp)
95     return false;
96   CmpInst::Predicate CPred = Cmp->getPredicate();
97   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
99     return true;
100   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
101     CRHS == LHS;
102 }
103
104 /// Does the given value dominate the specified phi node?
105 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106   Instruction *I = dyn_cast<Instruction>(V);
107   if (!I)
108     // Arguments and constants dominate all instructions.
109     return true;
110
111   // If we are processing instructions (and/or basic blocks) that have not been
112   // fully added to a function, the parent nodes may still be null. Simply
113   // return the conservative answer in these cases.
114   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
115     return false;
116
117   // If we have a DominatorTree then do a precise test.
118   if (DT) {
119     if (!DT->isReachableFromEntry(P->getParent()))
120       return true;
121     if (!DT->isReachableFromEntry(I->getParent()))
122       return false;
123     return DT->dominates(I, P);
124   }
125
126   // Otherwise, if the instruction is in the entry block and is not an invoke,
127   // then it obviously dominates all phi nodes.
128   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
129       !isa<InvokeInst>(I))
130     return true;
131
132   return false;
133 }
134
135 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
136 /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
137 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139 /// Returns the simplified value, or null if no simplification was performed.
140 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
141                           unsigned OpcToExpand, const Query &Q,
142                           unsigned MaxRecurse) {
143   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
144   // Recursion is always used, so bail out at once if we already hit the limit.
145   if (!MaxRecurse--)
146     return nullptr;
147
148   // Check whether the expression has the form "(A op' B) op C".
149   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
150     if (Op0->getOpcode() == OpcodeToExpand) {
151       // It does!  Try turning it into "(A op C) op' (B op C)".
152       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
153       // Do "A op C" and "B op C" both simplify?
154       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
155         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
156           // They do! Return "L op' R" if it simplifies or is already available.
157           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
158           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
159                                      && L == B && R == A)) {
160             ++NumExpand;
161             return LHS;
162           }
163           // Otherwise return "L op' R" if it simplifies.
164           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
165             ++NumExpand;
166             return V;
167           }
168         }
169     }
170
171   // Check whether the expression has the form "A op (B op' C)".
172   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
173     if (Op1->getOpcode() == OpcodeToExpand) {
174       // It does!  Try turning it into "(A op B) op' (A op C)".
175       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
176       // Do "A op B" and "A op C" both simplify?
177       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
178         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
179           // They do! Return "L op' R" if it simplifies or is already available.
180           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
181           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
182                                      && L == C && R == B)) {
183             ++NumExpand;
184             return RHS;
185           }
186           // Otherwise return "L op' R" if it simplifies.
187           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
188             ++NumExpand;
189             return V;
190           }
191         }
192     }
193
194   return nullptr;
195 }
196
197 /// Generic simplifications for associative binary operations.
198 /// Returns the simpler value, or null if none was found.
199 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
200                                        const Query &Q, unsigned MaxRecurse) {
201   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
202   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
203
204   // Recursion is always used, so bail out at once if we already hit the limit.
205   if (!MaxRecurse--)
206     return nullptr;
207
208   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
209   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
210
211   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
212   if (Op0 && Op0->getOpcode() == Opcode) {
213     Value *A = Op0->getOperand(0);
214     Value *B = Op0->getOperand(1);
215     Value *C = RHS;
216
217     // Does "B op C" simplify?
218     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
219       // It does!  Return "A op V" if it simplifies or is already available.
220       // If V equals B then "A op V" is just the LHS.
221       if (V == B) return LHS;
222       // Otherwise return "A op V" if it simplifies.
223       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
224         ++NumReassoc;
225         return W;
226       }
227     }
228   }
229
230   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
231   if (Op1 && Op1->getOpcode() == Opcode) {
232     Value *A = LHS;
233     Value *B = Op1->getOperand(0);
234     Value *C = Op1->getOperand(1);
235
236     // Does "A op B" simplify?
237     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
238       // It does!  Return "V op C" if it simplifies or is already available.
239       // If V equals B then "V op C" is just the RHS.
240       if (V == B) return RHS;
241       // Otherwise return "V op C" if it simplifies.
242       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
243         ++NumReassoc;
244         return W;
245       }
246     }
247   }
248
249   // The remaining transforms require commutativity as well as associativity.
250   if (!Instruction::isCommutative(Opcode))
251     return nullptr;
252
253   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
254   if (Op0 && Op0->getOpcode() == Opcode) {
255     Value *A = Op0->getOperand(0);
256     Value *B = Op0->getOperand(1);
257     Value *C = RHS;
258
259     // Does "C op A" simplify?
260     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
261       // It does!  Return "V op B" if it simplifies or is already available.
262       // If V equals A then "V op B" is just the LHS.
263       if (V == A) return LHS;
264       // Otherwise return "V op B" if it simplifies.
265       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
266         ++NumReassoc;
267         return W;
268       }
269     }
270   }
271
272   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
273   if (Op1 && Op1->getOpcode() == Opcode) {
274     Value *A = LHS;
275     Value *B = Op1->getOperand(0);
276     Value *C = Op1->getOperand(1);
277
278     // Does "C op A" simplify?
279     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
280       // It does!  Return "B op V" if it simplifies or is already available.
281       // If V equals C then "B op V" is just the RHS.
282       if (V == C) return RHS;
283       // Otherwise return "B op V" if it simplifies.
284       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
285         ++NumReassoc;
286         return W;
287       }
288     }
289   }
290
291   return nullptr;
292 }
293
294 /// In the case of a binary operation with a select instruction as an operand,
295 /// try to simplify the binop by seeing whether evaluating it on both branches
296 /// of the select results in the same value. Returns the common value if so,
297 /// otherwise returns null.
298 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
299                                     const Query &Q, unsigned MaxRecurse) {
300   // Recursion is always used, so bail out at once if we already hit the limit.
301   if (!MaxRecurse--)
302     return nullptr;
303
304   SelectInst *SI;
305   if (isa<SelectInst>(LHS)) {
306     SI = cast<SelectInst>(LHS);
307   } else {
308     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309     SI = cast<SelectInst>(RHS);
310   }
311
312   // Evaluate the BinOp on the true and false branches of the select.
313   Value *TV;
314   Value *FV;
315   if (SI == LHS) {
316     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
318   } else {
319     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
321   }
322
323   // If they simplified to the same value, then return the common value.
324   // If they both failed to simplify then return null.
325   if (TV == FV)
326     return TV;
327
328   // If one branch simplified to undef, return the other one.
329   if (TV && isa<UndefValue>(TV))
330     return FV;
331   if (FV && isa<UndefValue>(FV))
332     return TV;
333
334   // If applying the operation did not change the true and false select values,
335   // then the result of the binop is the select itself.
336   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
337     return SI;
338
339   // If one branch simplified and the other did not, and the simplified
340   // value is equal to the unsimplified one, return the simplified value.
341   // For example, select (cond, X, X & Z) & Z -> X & Z.
342   if ((FV && !TV) || (TV && !FV)) {
343     // Check that the simplified value has the form "X op Y" where "op" is the
344     // same as the original operation.
345     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346     if (Simplified && Simplified->getOpcode() == Opcode) {
347       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348       // We already know that "op" is the same as for the simplified value.  See
349       // if the operands match too.  If so, return the simplified value.
350       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
353       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354           Simplified->getOperand(1) == UnsimplifiedRHS)
355         return Simplified;
356       if (Simplified->isCommutative() &&
357           Simplified->getOperand(1) == UnsimplifiedLHS &&
358           Simplified->getOperand(0) == UnsimplifiedRHS)
359         return Simplified;
360     }
361   }
362
363   return nullptr;
364 }
365
366 /// In the case of a comparison with a select instruction, try to simplify the
367 /// comparison by seeing whether both branches of the select result in the same
368 /// value. Returns the common value if so, otherwise returns null.
369 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
370                                   Value *RHS, const Query &Q,
371                                   unsigned MaxRecurse) {
372   // Recursion is always used, so bail out at once if we already hit the limit.
373   if (!MaxRecurse--)
374     return nullptr;
375
376   // Make sure the select is on the LHS.
377   if (!isa<SelectInst>(LHS)) {
378     std::swap(LHS, RHS);
379     Pred = CmpInst::getSwappedPredicate(Pred);
380   }
381   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382   SelectInst *SI = cast<SelectInst>(LHS);
383   Value *Cond = SI->getCondition();
384   Value *TV = SI->getTrueValue();
385   Value *FV = SI->getFalseValue();
386
387   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
388   // Does "cmp TV, RHS" simplify?
389   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
390   if (TCmp == Cond) {
391     // It not only simplified, it simplified to the select condition.  Replace
392     // it with 'true'.
393     TCmp = getTrue(Cond->getType());
394   } else if (!TCmp) {
395     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
396     // condition then we can replace it with 'true'.  Otherwise give up.
397     if (!isSameCompare(Cond, Pred, TV, RHS))
398       return nullptr;
399     TCmp = getTrue(Cond->getType());
400   }
401
402   // Does "cmp FV, RHS" simplify?
403   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
404   if (FCmp == Cond) {
405     // It not only simplified, it simplified to the select condition.  Replace
406     // it with 'false'.
407     FCmp = getFalse(Cond->getType());
408   } else if (!FCmp) {
409     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
410     // condition then we can replace it with 'false'.  Otherwise give up.
411     if (!isSameCompare(Cond, Pred, FV, RHS))
412       return nullptr;
413     FCmp = getFalse(Cond->getType());
414   }
415
416   // If both sides simplified to the same value, then use it as the result of
417   // the original comparison.
418   if (TCmp == FCmp)
419     return TCmp;
420
421   // The remaining cases only make sense if the select condition has the same
422   // type as the result of the comparison, so bail out if this is not so.
423   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
424     return nullptr;
425   // If the false value simplified to false, then the result of the compare
426   // is equal to "Cond && TCmp".  This also catches the case when the false
427   // value simplified to false and the true value to true, returning "Cond".
428   if (match(FCmp, m_Zero()))
429     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
430       return V;
431   // If the true value simplified to true, then the result of the compare
432   // is equal to "Cond || FCmp".
433   if (match(TCmp, m_One()))
434     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
435       return V;
436   // Finally, if the false value simplified to true and the true value to
437   // false, then the result of the compare is equal to "!Cond".
438   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
439     if (Value *V =
440         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
441                         Q, MaxRecurse))
442       return V;
443
444   return nullptr;
445 }
446
447 /// In the case of a binary operation with an operand that is a PHI instruction,
448 /// try to simplify the binop by seeing whether evaluating it on the incoming
449 /// phi values yields the same result for every value. If so returns the common
450 /// value, otherwise returns null.
451 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
452                                  const Query &Q, unsigned MaxRecurse) {
453   // Recursion is always used, so bail out at once if we already hit the limit.
454   if (!MaxRecurse--)
455     return nullptr;
456
457   PHINode *PI;
458   if (isa<PHINode>(LHS)) {
459     PI = cast<PHINode>(LHS);
460     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
461     if (!ValueDominatesPHI(RHS, PI, Q.DT))
462       return nullptr;
463   } else {
464     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
465     PI = cast<PHINode>(RHS);
466     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
467     if (!ValueDominatesPHI(LHS, PI, Q.DT))
468       return nullptr;
469   }
470
471   // Evaluate the BinOp on the incoming phi values.
472   Value *CommonValue = nullptr;
473   for (Value *Incoming : PI->incoming_values()) {
474     // If the incoming value is the phi node itself, it can safely be skipped.
475     if (Incoming == PI) continue;
476     Value *V = PI == LHS ?
477       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
478       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
479     // If the operation failed to simplify, or simplified to a different value
480     // to previously, then give up.
481     if (!V || (CommonValue && V != CommonValue))
482       return nullptr;
483     CommonValue = V;
484   }
485
486   return CommonValue;
487 }
488
489 /// In the case of a comparison with a PHI instruction, try to simplify the
490 /// comparison by seeing whether comparing with all of the incoming phi values
491 /// yields the same result every time. If so returns the common result,
492 /// otherwise returns null.
493 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
494                                const Query &Q, unsigned MaxRecurse) {
495   // Recursion is always used, so bail out at once if we already hit the limit.
496   if (!MaxRecurse--)
497     return nullptr;
498
499   // Make sure the phi is on the LHS.
500   if (!isa<PHINode>(LHS)) {
501     std::swap(LHS, RHS);
502     Pred = CmpInst::getSwappedPredicate(Pred);
503   }
504   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
505   PHINode *PI = cast<PHINode>(LHS);
506
507   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
508   if (!ValueDominatesPHI(RHS, PI, Q.DT))
509     return nullptr;
510
511   // Evaluate the BinOp on the incoming phi values.
512   Value *CommonValue = nullptr;
513   for (Value *Incoming : PI->incoming_values()) {
514     // If the incoming value is the phi node itself, it can safely be skipped.
515     if (Incoming == PI) continue;
516     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
517     // If the operation failed to simplify, or simplified to a different value
518     // to previously, then give up.
519     if (!V || (CommonValue && V != CommonValue))
520       return nullptr;
521     CommonValue = V;
522   }
523
524   return CommonValue;
525 }
526
527 /// Given operands for an Add, see if we can fold the result.
528 /// If not, this returns null.
529 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
530                               const Query &Q, unsigned MaxRecurse) {
531   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
532     if (Constant *CRHS = dyn_cast<Constant>(Op1))
533       return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
534
535     // Canonicalize the constant to the RHS.
536     std::swap(Op0, Op1);
537   }
538
539   // X + undef -> undef
540   if (match(Op1, m_Undef()))
541     return Op1;
542
543   // X + 0 -> X
544   if (match(Op1, m_Zero()))
545     return Op0;
546
547   // X + (Y - X) -> Y
548   // (Y - X) + X -> Y
549   // Eg: X + -X -> 0
550   Value *Y = nullptr;
551   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
553     return Y;
554
555   // X + ~X -> -1   since   ~X = -X-1
556   if (match(Op0, m_Not(m_Specific(Op1))) ||
557       match(Op1, m_Not(m_Specific(Op0))))
558     return Constant::getAllOnesValue(Op0->getType());
559
560   /// i1 add -> xor.
561   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
562     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
563       return V;
564
565   // Try some generic simplifications for associative operations.
566   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
567                                           MaxRecurse))
568     return V;
569
570   // Threading Add over selects and phi nodes is pointless, so don't bother.
571   // Threading over the select in "A + select(cond, B, C)" means evaluating
572   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573   // only if B and C are equal.  If B and C are equal then (since we assume
574   // that operands have already been simplified) "select(cond, B, C)" should
575   // have been simplified to the common value of B and C already.  Analysing
576   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
577   // for threading over phi nodes.
578
579   return nullptr;
580 }
581
582 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
583                              const DataLayout &DL, const TargetLibraryInfo *TLI,
584                              const DominatorTree *DT, AssumptionCache *AC,
585                              const Instruction *CxtI) {
586   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
587                            RecursionLimit);
588 }
589
590 /// \brief Compute the base pointer and cumulative constant offsets for V.
591 ///
592 /// This strips all constant offsets off of V, leaving it the base pointer, and
593 /// accumulates the total constant offset applied in the returned constant. It
594 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
595 /// no constant offsets applied.
596 ///
597 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599 /// folding.
600 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
601                                                 bool AllowNonInbounds = false) {
602   assert(V->getType()->getScalarType()->isPointerTy());
603
604   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
605   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
606
607   // Even though we don't look through PHI nodes, we could be called on an
608   // instruction in an unreachable block, which may be on a cycle.
609   SmallPtrSet<Value *, 4> Visited;
610   Visited.insert(V);
611   do {
612     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
613       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
614           !GEP->accumulateConstantOffset(DL, Offset))
615         break;
616       V = GEP->getPointerOperand();
617     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
618       V = cast<Operator>(V)->getOperand(0);
619     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
620       if (GA->isInterposable())
621         break;
622       V = GA->getAliasee();
623     } else {
624       if (auto CS = CallSite(V))
625         if (Value *RV = CS.getReturnedArgOperand()) {
626           V = RV;
627           continue;
628         }
629       break;
630     }
631     assert(V->getType()->getScalarType()->isPointerTy() &&
632            "Unexpected operand type!");
633   } while (Visited.insert(V).second);
634
635   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636   if (V->getType()->isVectorTy())
637     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
638                                     OffsetIntPtr);
639   return OffsetIntPtr;
640 }
641
642 /// \brief Compute the constant difference between two pointer values.
643 /// If the difference is not a constant, returns zero.
644 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
645                                           Value *RHS) {
646   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
648
649   // If LHS and RHS are not related via constant offsets to the same base
650   // value, there is nothing we can do here.
651   if (LHS != RHS)
652     return nullptr;
653
654   // Otherwise, the difference of LHS - RHS can be computed as:
655   //    LHS - RHS
656   //  = (LHSOffset + Base) - (RHSOffset + Base)
657   //  = LHSOffset - RHSOffset
658   return ConstantExpr::getSub(LHSOffset, RHSOffset);
659 }
660
661 /// Given operands for a Sub, see if we can fold the result.
662 /// If not, this returns null.
663 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
664                               const Query &Q, unsigned MaxRecurse) {
665   if (Constant *CLHS = dyn_cast<Constant>(Op0))
666     if (Constant *CRHS = dyn_cast<Constant>(Op1))
667       return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
668
669   // X - undef -> undef
670   // undef - X -> undef
671   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
672     return UndefValue::get(Op0->getType());
673
674   // X - 0 -> X
675   if (match(Op1, m_Zero()))
676     return Op0;
677
678   // X - X -> 0
679   if (Op0 == Op1)
680     return Constant::getNullValue(Op0->getType());
681
682   // 0 - X -> 0 if the sub is NUW.
683   if (isNUW && match(Op0, m_Zero()))
684     return Op0;
685
686   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
687   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
688   Value *X = nullptr, *Y = nullptr, *Z = Op1;
689   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
690     // See if "V === Y - Z" simplifies.
691     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
692       // It does!  Now see if "X + V" simplifies.
693       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
694         // It does, we successfully reassociated!
695         ++NumReassoc;
696         return W;
697       }
698     // See if "V === X - Z" simplifies.
699     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
700       // It does!  Now see if "Y + V" simplifies.
701       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
702         // It does, we successfully reassociated!
703         ++NumReassoc;
704         return W;
705       }
706   }
707
708   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
709   // For example, X - (X + 1) -> -1
710   X = Op0;
711   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
712     // See if "V === X - Y" simplifies.
713     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
714       // It does!  Now see if "V - Z" simplifies.
715       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
716         // It does, we successfully reassociated!
717         ++NumReassoc;
718         return W;
719       }
720     // See if "V === X - Z" simplifies.
721     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
722       // It does!  Now see if "V - Y" simplifies.
723       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
724         // It does, we successfully reassociated!
725         ++NumReassoc;
726         return W;
727       }
728   }
729
730   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
731   // For example, X - (X - Y) -> Y.
732   Z = Op0;
733   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
734     // See if "V === Z - X" simplifies.
735     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
736       // It does!  Now see if "V + Y" simplifies.
737       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
738         // It does, we successfully reassociated!
739         ++NumReassoc;
740         return W;
741       }
742
743   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
744   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
745       match(Op1, m_Trunc(m_Value(Y))))
746     if (X->getType() == Y->getType())
747       // See if "V === X - Y" simplifies.
748       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
749         // It does!  Now see if "trunc V" simplifies.
750         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
751           // It does, return the simplified "trunc V".
752           return W;
753
754   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
755   if (match(Op0, m_PtrToInt(m_Value(X))) &&
756       match(Op1, m_PtrToInt(m_Value(Y))))
757     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
758       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
759
760   // i1 sub -> xor.
761   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
762     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
763       return V;
764
765   // Threading Sub over selects and phi nodes is pointless, so don't bother.
766   // Threading over the select in "A - select(cond, B, C)" means evaluating
767   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
768   // only if B and C are equal.  If B and C are equal then (since we assume
769   // that operands have already been simplified) "select(cond, B, C)" should
770   // have been simplified to the common value of B and C already.  Analysing
771   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
772   // for threading over phi nodes.
773
774   return nullptr;
775 }
776
777 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
778                              const DataLayout &DL, const TargetLibraryInfo *TLI,
779                              const DominatorTree *DT, AssumptionCache *AC,
780                              const Instruction *CxtI) {
781   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
782                            RecursionLimit);
783 }
784
785 /// Given operands for an FAdd, see if we can fold the result.  If not, this
786 /// returns null.
787 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
788                               const Query &Q, unsigned MaxRecurse) {
789   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
790     if (Constant *CRHS = dyn_cast<Constant>(Op1))
791       return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
792
793     // Canonicalize the constant to the RHS.
794     std::swap(Op0, Op1);
795   }
796
797   // fadd X, -0 ==> X
798   if (match(Op1, m_NegZero()))
799     return Op0;
800
801   // fadd X, 0 ==> X, when we know X is not -0
802   if (match(Op1, m_Zero()) &&
803       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
804     return Op0;
805
806   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
807   //   where nnan and ninf have to occur at least once somewhere in this
808   //   expression
809   Value *SubOp = nullptr;
810   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
811     SubOp = Op1;
812   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
813     SubOp = Op0;
814   if (SubOp) {
815     Instruction *FSub = cast<Instruction>(SubOp);
816     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
817         (FMF.noInfs() || FSub->hasNoInfs()))
818       return Constant::getNullValue(Op0->getType());
819   }
820
821   return nullptr;
822 }
823
824 /// Given operands for an FSub, see if we can fold the result.  If not, this
825 /// returns null.
826 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
827                               const Query &Q, unsigned MaxRecurse) {
828   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
829     if (Constant *CRHS = dyn_cast<Constant>(Op1))
830       return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
831   }
832
833   // fsub X, 0 ==> X
834   if (match(Op1, m_Zero()))
835     return Op0;
836
837   // fsub X, -0 ==> X, when we know X is not -0
838   if (match(Op1, m_NegZero()) &&
839       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
840     return Op0;
841
842   // fsub -0.0, (fsub -0.0, X) ==> X
843   Value *X;
844   if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
845     return X;
846
847   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
848   if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
849       match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
850     return X;
851
852   // fsub nnan x, x ==> 0.0
853   if (FMF.noNaNs() && Op0 == Op1)
854     return Constant::getNullValue(Op0->getType());
855
856   return nullptr;
857 }
858
859 /// Given the operands for an FMul, see if we can fold the result
860 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
861                                FastMathFlags FMF,
862                                const Query &Q,
863                                unsigned MaxRecurse) {
864  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
865     if (Constant *CRHS = dyn_cast<Constant>(Op1))
866       return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
867
868     // Canonicalize the constant to the RHS.
869     std::swap(Op0, Op1);
870  }
871
872  // fmul X, 1.0 ==> X
873  if (match(Op1, m_FPOne()))
874    return Op0;
875
876  // fmul nnan nsz X, 0 ==> 0
877  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
878    return Op1;
879
880  return nullptr;
881 }
882
883 /// Given operands for a Mul, see if we can fold the result.
884 /// If not, this returns null.
885 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886                               unsigned MaxRecurse) {
887   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
888     if (Constant *CRHS = dyn_cast<Constant>(Op1))
889       return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
890
891     // Canonicalize the constant to the RHS.
892     std::swap(Op0, Op1);
893   }
894
895   // X * undef -> 0
896   if (match(Op1, m_Undef()))
897     return Constant::getNullValue(Op0->getType());
898
899   // X * 0 -> 0
900   if (match(Op1, m_Zero()))
901     return Op1;
902
903   // X * 1 -> X
904   if (match(Op1, m_One()))
905     return Op0;
906
907   // (X / Y) * Y -> X if the division is exact.
908   Value *X = nullptr;
909   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
910       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
911     return X;
912
913   // i1 mul -> and.
914   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
915     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
916       return V;
917
918   // Try some generic simplifications for associative operations.
919   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
920                                           MaxRecurse))
921     return V;
922
923   // Mul distributes over Add.  Try some generic simplifications based on this.
924   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
925                              Q, MaxRecurse))
926     return V;
927
928   // If the operation is with the result of a select instruction, check whether
929   // operating on either branch of the select always yields the same value.
930   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
931     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
932                                          MaxRecurse))
933       return V;
934
935   // If the operation is with the result of a phi instruction, check whether
936   // operating on all incoming values of the phi always yields the same value.
937   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
938     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
939                                       MaxRecurse))
940       return V;
941
942   return nullptr;
943 }
944
945 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
946                               const DataLayout &DL,
947                               const TargetLibraryInfo *TLI,
948                               const DominatorTree *DT, AssumptionCache *AC,
949                               const Instruction *CxtI) {
950   return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
951                             RecursionLimit);
952 }
953
954 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
955                               const DataLayout &DL,
956                               const TargetLibraryInfo *TLI,
957                               const DominatorTree *DT, AssumptionCache *AC,
958                               const Instruction *CxtI) {
959   return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
960                             RecursionLimit);
961 }
962
963 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
964                               const DataLayout &DL,
965                               const TargetLibraryInfo *TLI,
966                               const DominatorTree *DT, AssumptionCache *AC,
967                               const Instruction *CxtI) {
968   return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
969                             RecursionLimit);
970 }
971
972 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
973                              const TargetLibraryInfo *TLI,
974                              const DominatorTree *DT, AssumptionCache *AC,
975                              const Instruction *CxtI) {
976   return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
977                            RecursionLimit);
978 }
979
980 /// Given operands for an SDiv or UDiv, see if we can fold the result.
981 /// If not, this returns null.
982 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
983                           const Query &Q, unsigned MaxRecurse) {
984   if (Constant *C0 = dyn_cast<Constant>(Op0))
985     if (Constant *C1 = dyn_cast<Constant>(Op1))
986       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
987
988   bool isSigned = Opcode == Instruction::SDiv;
989
990   // X / undef -> undef
991   if (match(Op1, m_Undef()))
992     return Op1;
993
994   // X / 0 -> undef, we don't need to preserve faults!
995   if (match(Op1, m_Zero()))
996     return UndefValue::get(Op1->getType());
997
998   // undef / X -> 0
999   if (match(Op0, m_Undef()))
1000     return Constant::getNullValue(Op0->getType());
1001
1002   // 0 / X -> 0, we don't need to preserve faults!
1003   if (match(Op0, m_Zero()))
1004     return Op0;
1005
1006   // X / 1 -> X
1007   if (match(Op1, m_One()))
1008     return Op0;
1009
1010   if (Op0->getType()->isIntegerTy(1))
1011     // It can't be division by zero, hence it must be division by one.
1012     return Op0;
1013
1014   // X / X -> 1
1015   if (Op0 == Op1)
1016     return ConstantInt::get(Op0->getType(), 1);
1017
1018   // (X * Y) / Y -> X if the multiplication does not overflow.
1019   Value *X = nullptr, *Y = nullptr;
1020   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1021     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1022     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1023     // If the Mul knows it does not overflow, then we are good to go.
1024     if ((isSigned && Mul->hasNoSignedWrap()) ||
1025         (!isSigned && Mul->hasNoUnsignedWrap()))
1026       return X;
1027     // If X has the form X = A / Y then X * Y cannot overflow.
1028     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1029       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1030         return X;
1031   }
1032
1033   // (X rem Y) / Y -> 0
1034   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1035       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1036     return Constant::getNullValue(Op0->getType());
1037
1038   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1039   ConstantInt *C1, *C2;
1040   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1041       match(Op1, m_ConstantInt(C2))) {
1042     bool Overflow;
1043     C1->getValue().umul_ov(C2->getValue(), Overflow);
1044     if (Overflow)
1045       return Constant::getNullValue(Op0->getType());
1046   }
1047
1048   // If the operation is with the result of a select instruction, check whether
1049   // operating on either branch of the select always yields the same value.
1050   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1051     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1052       return V;
1053
1054   // If the operation is with the result of a phi instruction, check whether
1055   // operating on all incoming values of the phi always yields the same value.
1056   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1057     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1058       return V;
1059
1060   return nullptr;
1061 }
1062
1063 /// Given operands for an SDiv, see if we can fold the result.
1064 /// If not, this returns null.
1065 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1066                                unsigned MaxRecurse) {
1067   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1068     return V;
1069
1070   return nullptr;
1071 }
1072
1073 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1074                               const TargetLibraryInfo *TLI,
1075                               const DominatorTree *DT, AssumptionCache *AC,
1076                               const Instruction *CxtI) {
1077   return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1078                             RecursionLimit);
1079 }
1080
1081 /// Given operands for a UDiv, see if we can fold the result.
1082 /// If not, this returns null.
1083 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1084                                unsigned MaxRecurse) {
1085   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1086     return V;
1087
1088   return nullptr;
1089 }
1090
1091 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1092                               const TargetLibraryInfo *TLI,
1093                               const DominatorTree *DT, AssumptionCache *AC,
1094                               const Instruction *CxtI) {
1095   return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1096                             RecursionLimit);
1097 }
1098
1099 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1100                                const Query &Q, unsigned) {
1101   // undef / X -> undef    (the undef could be a snan).
1102   if (match(Op0, m_Undef()))
1103     return Op0;
1104
1105   // X / undef -> undef
1106   if (match(Op1, m_Undef()))
1107     return Op1;
1108
1109   // 0 / X -> 0
1110   // Requires that NaNs are off (X could be zero) and signed zeroes are
1111   // ignored (X could be positive or negative, so the output sign is unknown).
1112   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1113     return Op0;
1114
1115   if (FMF.noNaNs()) {
1116     // X / X -> 1.0 is legal when NaNs are ignored.
1117     if (Op0 == Op1)
1118       return ConstantFP::get(Op0->getType(), 1.0);
1119
1120     // -X /  X -> -1.0 and
1121     //  X / -X -> -1.0 are legal when NaNs are ignored.
1122     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1123     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1124          BinaryOperator::getFNegArgument(Op0) == Op1) ||
1125         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1126          BinaryOperator::getFNegArgument(Op1) == Op0))
1127       return ConstantFP::get(Op0->getType(), -1.0);
1128   }
1129
1130   return nullptr;
1131 }
1132
1133 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1134                               const DataLayout &DL,
1135                               const TargetLibraryInfo *TLI,
1136                               const DominatorTree *DT, AssumptionCache *AC,
1137                               const Instruction *CxtI) {
1138   return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1139                             RecursionLimit);
1140 }
1141
1142 /// Given operands for an SRem or URem, see if we can fold the result.
1143 /// If not, this returns null.
1144 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1145                           const Query &Q, unsigned MaxRecurse) {
1146   if (Constant *C0 = dyn_cast<Constant>(Op0))
1147     if (Constant *C1 = dyn_cast<Constant>(Op1))
1148       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1149
1150   // X % undef -> undef
1151   if (match(Op1, m_Undef()))
1152     return Op1;
1153
1154   // undef % X -> 0
1155   if (match(Op0, m_Undef()))
1156     return Constant::getNullValue(Op0->getType());
1157
1158   // 0 % X -> 0, we don't need to preserve faults!
1159   if (match(Op0, m_Zero()))
1160     return Op0;
1161
1162   // X % 0 -> undef, we don't need to preserve faults!
1163   if (match(Op1, m_Zero()))
1164     return UndefValue::get(Op0->getType());
1165
1166   // X % 1 -> 0
1167   if (match(Op1, m_One()))
1168     return Constant::getNullValue(Op0->getType());
1169
1170   if (Op0->getType()->isIntegerTy(1))
1171     // It can't be remainder by zero, hence it must be remainder by one.
1172     return Constant::getNullValue(Op0->getType());
1173
1174   // X % X -> 0
1175   if (Op0 == Op1)
1176     return Constant::getNullValue(Op0->getType());
1177
1178   // (X % Y) % Y -> X % Y
1179   if ((Opcode == Instruction::SRem &&
1180        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1181       (Opcode == Instruction::URem &&
1182        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1183     return Op0;
1184
1185   // If the operation is with the result of a select instruction, check whether
1186   // operating on either branch of the select always yields the same value.
1187   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1188     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1189       return V;
1190
1191   // If the operation is with the result of a phi instruction, check whether
1192   // operating on all incoming values of the phi always yields the same value.
1193   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1194     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1195       return V;
1196
1197   return nullptr;
1198 }
1199
1200 /// Given operands for an SRem, see if we can fold the result.
1201 /// If not, this returns null.
1202 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1203                                unsigned MaxRecurse) {
1204   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1205     return V;
1206
1207   return nullptr;
1208 }
1209
1210 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1211                               const TargetLibraryInfo *TLI,
1212                               const DominatorTree *DT, AssumptionCache *AC,
1213                               const Instruction *CxtI) {
1214   return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1215                             RecursionLimit);
1216 }
1217
1218 /// Given operands for a URem, see if we can fold the result.
1219 /// If not, this returns null.
1220 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1221                                unsigned MaxRecurse) {
1222   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1223     return V;
1224
1225   return nullptr;
1226 }
1227
1228 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1229                               const TargetLibraryInfo *TLI,
1230                               const DominatorTree *DT, AssumptionCache *AC,
1231                               const Instruction *CxtI) {
1232   return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1233                             RecursionLimit);
1234 }
1235
1236 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1237                                const Query &, unsigned) {
1238   // undef % X -> undef    (the undef could be a snan).
1239   if (match(Op0, m_Undef()))
1240     return Op0;
1241
1242   // X % undef -> undef
1243   if (match(Op1, m_Undef()))
1244     return Op1;
1245
1246   // 0 % X -> 0
1247   // Requires that NaNs are off (X could be zero) and signed zeroes are
1248   // ignored (X could be positive or negative, so the output sign is unknown).
1249   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1250     return Op0;
1251
1252   return nullptr;
1253 }
1254
1255 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1256                               const DataLayout &DL,
1257                               const TargetLibraryInfo *TLI,
1258                               const DominatorTree *DT, AssumptionCache *AC,
1259                               const Instruction *CxtI) {
1260   return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1261                             RecursionLimit);
1262 }
1263
1264 /// Returns true if a shift by \c Amount always yields undef.
1265 static bool isUndefShift(Value *Amount) {
1266   Constant *C = dyn_cast<Constant>(Amount);
1267   if (!C)
1268     return false;
1269
1270   // X shift by undef -> undef because it may shift by the bitwidth.
1271   if (isa<UndefValue>(C))
1272     return true;
1273
1274   // Shifting by the bitwidth or more is undefined.
1275   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1276     if (CI->getValue().getLimitedValue() >=
1277         CI->getType()->getScalarSizeInBits())
1278       return true;
1279
1280   // If all lanes of a vector shift are undefined the whole shift is.
1281   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1282     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1283       if (!isUndefShift(C->getAggregateElement(I)))
1284         return false;
1285     return true;
1286   }
1287
1288   return false;
1289 }
1290
1291 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1292 /// If not, this returns null.
1293 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1294                             const Query &Q, unsigned MaxRecurse) {
1295   if (Constant *C0 = dyn_cast<Constant>(Op0))
1296     if (Constant *C1 = dyn_cast<Constant>(Op1))
1297       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1298
1299   // 0 shift by X -> 0
1300   if (match(Op0, m_Zero()))
1301     return Op0;
1302
1303   // X shift by 0 -> X
1304   if (match(Op1, m_Zero()))
1305     return Op0;
1306
1307   // Fold undefined shifts.
1308   if (isUndefShift(Op1))
1309     return UndefValue::get(Op0->getType());
1310
1311   // If the operation is with the result of a select instruction, check whether
1312   // operating on either branch of the select always yields the same value.
1313   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1314     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1315       return V;
1316
1317   // If the operation is with the result of a phi instruction, check whether
1318   // operating on all incoming values of the phi always yields the same value.
1319   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1320     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1321       return V;
1322
1323   // If any bits in the shift amount make that value greater than or equal to
1324   // the number of bits in the type, the shift is undefined.
1325   unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1326   APInt KnownZero(BitWidth, 0);
1327   APInt KnownOne(BitWidth, 0);
1328   computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1329   if (KnownOne.getLimitedValue() >= BitWidth)
1330     return UndefValue::get(Op0->getType());
1331
1332   // If all valid bits in the shift amount are known zero, the first operand is
1333   // unchanged.
1334   unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1335   APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1336   if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1337     return Op0;
1338
1339   return nullptr;
1340 }
1341
1342 /// \brief Given operands for an Shl, LShr or AShr, see if we can
1343 /// fold the result.  If not, this returns null.
1344 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1345                                  bool isExact, const Query &Q,
1346                                  unsigned MaxRecurse) {
1347   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1348     return V;
1349
1350   // X >> X -> 0
1351   if (Op0 == Op1)
1352     return Constant::getNullValue(Op0->getType());
1353
1354   // undef >> X -> 0
1355   // undef >> X -> undef (if it's exact)
1356   if (match(Op0, m_Undef()))
1357     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1358
1359   // The low bit cannot be shifted out of an exact shift if it is set.
1360   if (isExact) {
1361     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1362     APInt Op0KnownZero(BitWidth, 0);
1363     APInt Op0KnownOne(BitWidth, 0);
1364     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1365                      Q.CxtI, Q.DT);
1366     if (Op0KnownOne[0])
1367       return Op0;
1368   }
1369
1370   return nullptr;
1371 }
1372
1373 /// Given operands for an Shl, see if we can fold the result.
1374 /// If not, this returns null.
1375 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1376                               const Query &Q, unsigned MaxRecurse) {
1377   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1378     return V;
1379
1380   // undef << X -> 0
1381   // undef << X -> undef if (if it's NSW/NUW)
1382   if (match(Op0, m_Undef()))
1383     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1384
1385   // (X >> A) << A -> X
1386   Value *X;
1387   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1388     return X;
1389   return nullptr;
1390 }
1391
1392 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1393                              const DataLayout &DL, const TargetLibraryInfo *TLI,
1394                              const DominatorTree *DT, AssumptionCache *AC,
1395                              const Instruction *CxtI) {
1396   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1397                            RecursionLimit);
1398 }
1399
1400 /// Given operands for an LShr, see if we can fold the result.
1401 /// If not, this returns null.
1402 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1403                                const Query &Q, unsigned MaxRecurse) {
1404   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1405                                     MaxRecurse))
1406       return V;
1407
1408   // (X << A) >> A -> X
1409   Value *X;
1410   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1411     return X;
1412
1413   return nullptr;
1414 }
1415
1416 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1417                               const DataLayout &DL,
1418                               const TargetLibraryInfo *TLI,
1419                               const DominatorTree *DT, AssumptionCache *AC,
1420                               const Instruction *CxtI) {
1421   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1422                             RecursionLimit);
1423 }
1424
1425 /// Given operands for an AShr, see if we can fold the result.
1426 /// If not, this returns null.
1427 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1428                                const Query &Q, unsigned MaxRecurse) {
1429   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1430                                     MaxRecurse))
1431     return V;
1432
1433   // all ones >>a X -> all ones
1434   if (match(Op0, m_AllOnes()))
1435     return Op0;
1436
1437   // (X << A) >> A -> X
1438   Value *X;
1439   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1440     return X;
1441
1442   // Arithmetic shifting an all-sign-bit value is a no-op.
1443   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1444   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1445     return Op0;
1446
1447   return nullptr;
1448 }
1449
1450 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1451                               const DataLayout &DL,
1452                               const TargetLibraryInfo *TLI,
1453                               const DominatorTree *DT, AssumptionCache *AC,
1454                               const Instruction *CxtI) {
1455   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1456                             RecursionLimit);
1457 }
1458
1459 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1460                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1461   Value *X, *Y;
1462
1463   ICmpInst::Predicate EqPred;
1464   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1465       !ICmpInst::isEquality(EqPred))
1466     return nullptr;
1467
1468   ICmpInst::Predicate UnsignedPred;
1469   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1470       ICmpInst::isUnsigned(UnsignedPred))
1471     ;
1472   else if (match(UnsignedICmp,
1473                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1474            ICmpInst::isUnsigned(UnsignedPred))
1475     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1476   else
1477     return nullptr;
1478
1479   // X < Y && Y != 0  -->  X < Y
1480   // X < Y || Y != 0  -->  Y != 0
1481   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1482     return IsAnd ? UnsignedICmp : ZeroICmp;
1483
1484   // X >= Y || Y != 0  -->  true
1485   // X >= Y || Y == 0  -->  X >= Y
1486   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1487     if (EqPred == ICmpInst::ICMP_NE)
1488       return getTrue(UnsignedICmp->getType());
1489     return UnsignedICmp;
1490   }
1491
1492   // X < Y && Y == 0  -->  false
1493   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1494       IsAnd)
1495     return getFalse(UnsignedICmp->getType());
1496
1497   return nullptr;
1498 }
1499
1500 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1501   Type *ITy = Op0->getType();
1502   ICmpInst::Predicate Pred0, Pred1;
1503   ConstantInt *CI1, *CI2;
1504   Value *V;
1505
1506   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1507     return X;
1508
1509   // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1510   const APInt *C0, *C1;
1511   if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1512       match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1513     // Make a constant range that's the intersection of the two icmp ranges.
1514     // If the intersection is empty, we know that the result is false.
1515     auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1516     auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1517     if (Range0.intersectWith(Range1).isEmptySet())
1518       return getFalse(ITy);
1519   }
1520
1521   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1522                          m_ConstantInt(CI2))))
1523     return nullptr;
1524
1525   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1526     return nullptr;
1527
1528   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1529   bool isNSW = AddInst->hasNoSignedWrap();
1530   bool isNUW = AddInst->hasNoUnsignedWrap();
1531
1532   const APInt &CI1V = CI1->getValue();
1533   const APInt &CI2V = CI2->getValue();
1534   const APInt Delta = CI2V - CI1V;
1535   if (CI1V.isStrictlyPositive()) {
1536     if (Delta == 2) {
1537       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1538         return getFalse(ITy);
1539       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1540         return getFalse(ITy);
1541     }
1542     if (Delta == 1) {
1543       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1544         return getFalse(ITy);
1545       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1546         return getFalse(ITy);
1547     }
1548   }
1549   if (CI1V.getBoolValue() && isNUW) {
1550     if (Delta == 2)
1551       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1552         return getFalse(ITy);
1553     if (Delta == 1)
1554       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1555         return getFalse(ITy);
1556   }
1557
1558   return nullptr;
1559 }
1560
1561 /// Given operands for an And, see if we can fold the result.
1562 /// If not, this returns null.
1563 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1564                               unsigned MaxRecurse) {
1565   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1566     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1567       return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1568
1569     // Canonicalize the constant to the RHS.
1570     std::swap(Op0, Op1);
1571   }
1572
1573   // X & undef -> 0
1574   if (match(Op1, m_Undef()))
1575     return Constant::getNullValue(Op0->getType());
1576
1577   // X & X = X
1578   if (Op0 == Op1)
1579     return Op0;
1580
1581   // X & 0 = 0
1582   if (match(Op1, m_Zero()))
1583     return Op1;
1584
1585   // X & -1 = X
1586   if (match(Op1, m_AllOnes()))
1587     return Op0;
1588
1589   // A & ~A  =  ~A & A  =  0
1590   if (match(Op0, m_Not(m_Specific(Op1))) ||
1591       match(Op1, m_Not(m_Specific(Op0))))
1592     return Constant::getNullValue(Op0->getType());
1593
1594   // (A | ?) & A = A
1595   Value *A = nullptr, *B = nullptr;
1596   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1597       (A == Op1 || B == Op1))
1598     return Op1;
1599
1600   // A & (A | ?) = A
1601   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1602       (A == Op0 || B == Op0))
1603     return Op0;
1604
1605   // A & (-A) = A if A is a power of two or zero.
1606   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1607       match(Op1, m_Neg(m_Specific(Op0)))) {
1608     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1609                                Q.DT))
1610       return Op0;
1611     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1612                                Q.DT))
1613       return Op1;
1614   }
1615
1616   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1617     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1618       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1619         return V;
1620       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1621         return V;
1622     }
1623   }
1624
1625   // The compares may be hidden behind casts. Look through those and try the
1626   // same folds as above.
1627   auto *Cast0 = dyn_cast<CastInst>(Op0);
1628   auto *Cast1 = dyn_cast<CastInst>(Op1);
1629   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1630       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1631     auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1632     auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1633     if (Cmp0 && Cmp1) {
1634       Instruction::CastOps CastOpc = Cast0->getOpcode();
1635       Type *ResultType = Cast0->getType();
1636       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1637         return ConstantExpr::getCast(CastOpc, V, ResultType);
1638       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1639         return ConstantExpr::getCast(CastOpc, V, ResultType);
1640     }
1641   }
1642
1643   // Try some generic simplifications for associative operations.
1644   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1645                                           MaxRecurse))
1646     return V;
1647
1648   // And distributes over Or.  Try some generic simplifications based on this.
1649   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1650                              Q, MaxRecurse))
1651     return V;
1652
1653   // And distributes over Xor.  Try some generic simplifications based on this.
1654   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1655                              Q, MaxRecurse))
1656     return V;
1657
1658   // If the operation is with the result of a select instruction, check whether
1659   // operating on either branch of the select always yields the same value.
1660   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1661     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1662                                          MaxRecurse))
1663       return V;
1664
1665   // If the operation is with the result of a phi instruction, check whether
1666   // operating on all incoming values of the phi always yields the same value.
1667   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1668     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1669                                       MaxRecurse))
1670       return V;
1671
1672   return nullptr;
1673 }
1674
1675 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1676                              const TargetLibraryInfo *TLI,
1677                              const DominatorTree *DT, AssumptionCache *AC,
1678                              const Instruction *CxtI) {
1679   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1680                            RecursionLimit);
1681 }
1682
1683 /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1684 /// contains all possible values.
1685 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1686   ICmpInst::Predicate Pred0, Pred1;
1687   ConstantInt *CI1, *CI2;
1688   Value *V;
1689
1690   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1691     return X;
1692
1693   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1694                          m_ConstantInt(CI2))))
1695    return nullptr;
1696
1697   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1698     return nullptr;
1699
1700   Type *ITy = Op0->getType();
1701
1702   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1703   bool isNSW = AddInst->hasNoSignedWrap();
1704   bool isNUW = AddInst->hasNoUnsignedWrap();
1705
1706   const APInt &CI1V = CI1->getValue();
1707   const APInt &CI2V = CI2->getValue();
1708   const APInt Delta = CI2V - CI1V;
1709   if (CI1V.isStrictlyPositive()) {
1710     if (Delta == 2) {
1711       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1712         return getTrue(ITy);
1713       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1714         return getTrue(ITy);
1715     }
1716     if (Delta == 1) {
1717       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1718         return getTrue(ITy);
1719       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1720         return getTrue(ITy);
1721     }
1722   }
1723   if (CI1V.getBoolValue() && isNUW) {
1724     if (Delta == 2)
1725       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1726         return getTrue(ITy);
1727     if (Delta == 1)
1728       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1729         return getTrue(ITy);
1730   }
1731
1732   return nullptr;
1733 }
1734
1735 /// Given operands for an Or, see if we can fold the result.
1736 /// If not, this returns null.
1737 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1738                              unsigned MaxRecurse) {
1739   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1740     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1741       return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1742
1743     // Canonicalize the constant to the RHS.
1744     std::swap(Op0, Op1);
1745   }
1746
1747   // X | undef -> -1
1748   if (match(Op1, m_Undef()))
1749     return Constant::getAllOnesValue(Op0->getType());
1750
1751   // X | X = X
1752   if (Op0 == Op1)
1753     return Op0;
1754
1755   // X | 0 = X
1756   if (match(Op1, m_Zero()))
1757     return Op0;
1758
1759   // X | -1 = -1
1760   if (match(Op1, m_AllOnes()))
1761     return Op1;
1762
1763   // A | ~A  =  ~A | A  =  -1
1764   if (match(Op0, m_Not(m_Specific(Op1))) ||
1765       match(Op1, m_Not(m_Specific(Op0))))
1766     return Constant::getAllOnesValue(Op0->getType());
1767
1768   // (A & ?) | A = A
1769   Value *A = nullptr, *B = nullptr;
1770   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1771       (A == Op1 || B == Op1))
1772     return Op1;
1773
1774   // A | (A & ?) = A
1775   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1776       (A == Op0 || B == Op0))
1777     return Op0;
1778
1779   // ~(A & ?) | A = -1
1780   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781       (A == Op1 || B == Op1))
1782     return Constant::getAllOnesValue(Op1->getType());
1783
1784   // A | ~(A & ?) = -1
1785   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1786       (A == Op0 || B == Op0))
1787     return Constant::getAllOnesValue(Op0->getType());
1788
1789   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1790     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1791       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1792         return V;
1793       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1794         return V;
1795     }
1796   }
1797
1798   // Try some generic simplifications for associative operations.
1799   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1800                                           MaxRecurse))
1801     return V;
1802
1803   // Or distributes over And.  Try some generic simplifications based on this.
1804   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1805                              MaxRecurse))
1806     return V;
1807
1808   // If the operation is with the result of a select instruction, check whether
1809   // operating on either branch of the select always yields the same value.
1810   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1811     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1812                                          MaxRecurse))
1813       return V;
1814
1815   // (A & C)|(B & D)
1816   Value *C = nullptr, *D = nullptr;
1817   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1819     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1821     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1822       // (A & C1)|(B & C2)
1823       // If we have: ((V + N) & C1) | (V & C2)
1824       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1825       // replace with V+N.
1826       Value *V1, *V2;
1827       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1828           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1829         // Add commutes, try both ways.
1830         if (V1 == B &&
1831             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1832           return A;
1833         if (V2 == B &&
1834             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1835           return A;
1836       }
1837       // Or commutes, try both ways.
1838       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1839           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1840         // Add commutes, try both ways.
1841         if (V1 == A &&
1842             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1843           return B;
1844         if (V2 == A &&
1845             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1846           return B;
1847       }
1848     }
1849   }
1850
1851   // If the operation is with the result of a phi instruction, check whether
1852   // operating on all incoming values of the phi always yields the same value.
1853   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1854     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1855       return V;
1856
1857   return nullptr;
1858 }
1859
1860 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1861                             const TargetLibraryInfo *TLI,
1862                             const DominatorTree *DT, AssumptionCache *AC,
1863                             const Instruction *CxtI) {
1864   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1865                           RecursionLimit);
1866 }
1867
1868 /// Given operands for a Xor, see if we can fold the result.
1869 /// If not, this returns null.
1870 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1871                               unsigned MaxRecurse) {
1872   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1873     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1874       return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1875
1876     // Canonicalize the constant to the RHS.
1877     std::swap(Op0, Op1);
1878   }
1879
1880   // A ^ undef -> undef
1881   if (match(Op1, m_Undef()))
1882     return Op1;
1883
1884   // A ^ 0 = A
1885   if (match(Op1, m_Zero()))
1886     return Op0;
1887
1888   // A ^ A = 0
1889   if (Op0 == Op1)
1890     return Constant::getNullValue(Op0->getType());
1891
1892   // A ^ ~A  =  ~A ^ A  =  -1
1893   if (match(Op0, m_Not(m_Specific(Op1))) ||
1894       match(Op1, m_Not(m_Specific(Op0))))
1895     return Constant::getAllOnesValue(Op0->getType());
1896
1897   // Try some generic simplifications for associative operations.
1898   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1899                                           MaxRecurse))
1900     return V;
1901
1902   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1903   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1904   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1905   // only if B and C are equal.  If B and C are equal then (since we assume
1906   // that operands have already been simplified) "select(cond, B, C)" should
1907   // have been simplified to the common value of B and C already.  Analysing
1908   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1909   // for threading over phi nodes.
1910
1911   return nullptr;
1912 }
1913
1914 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1915                              const TargetLibraryInfo *TLI,
1916                              const DominatorTree *DT, AssumptionCache *AC,
1917                              const Instruction *CxtI) {
1918   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1919                            RecursionLimit);
1920 }
1921
1922 static Type *GetCompareTy(Value *Op) {
1923   return CmpInst::makeCmpResultType(Op->getType());
1924 }
1925
1926 /// Rummage around inside V looking for something equivalent to the comparison
1927 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1928 /// Helper function for analyzing max/min idioms.
1929 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1930                                          Value *LHS, Value *RHS) {
1931   SelectInst *SI = dyn_cast<SelectInst>(V);
1932   if (!SI)
1933     return nullptr;
1934   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1935   if (!Cmp)
1936     return nullptr;
1937   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1938   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1939     return Cmp;
1940   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1941       LHS == CmpRHS && RHS == CmpLHS)
1942     return Cmp;
1943   return nullptr;
1944 }
1945
1946 // A significant optimization not implemented here is assuming that alloca
1947 // addresses are not equal to incoming argument values. They don't *alias*,
1948 // as we say, but that doesn't mean they aren't equal, so we take a
1949 // conservative approach.
1950 //
1951 // This is inspired in part by C++11 5.10p1:
1952 //   "Two pointers of the same type compare equal if and only if they are both
1953 //    null, both point to the same function, or both represent the same
1954 //    address."
1955 //
1956 // This is pretty permissive.
1957 //
1958 // It's also partly due to C11 6.5.9p6:
1959 //   "Two pointers compare equal if and only if both are null pointers, both are
1960 //    pointers to the same object (including a pointer to an object and a
1961 //    subobject at its beginning) or function, both are pointers to one past the
1962 //    last element of the same array object, or one is a pointer to one past the
1963 //    end of one array object and the other is a pointer to the start of a
1964 //    different array object that happens to immediately follow the first array
1965 //    object in the address space.)
1966 //
1967 // C11's version is more restrictive, however there's no reason why an argument
1968 // couldn't be a one-past-the-end value for a stack object in the caller and be
1969 // equal to the beginning of a stack object in the callee.
1970 //
1971 // If the C and C++ standards are ever made sufficiently restrictive in this
1972 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1973 // this optimization.
1974 static Constant *
1975 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1976                    const DominatorTree *DT, CmpInst::Predicate Pred,
1977                    const Instruction *CxtI, Value *LHS, Value *RHS) {
1978   // First, skip past any trivial no-ops.
1979   LHS = LHS->stripPointerCasts();
1980   RHS = RHS->stripPointerCasts();
1981
1982   // A non-null pointer is not equal to a null pointer.
1983   if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
1984       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1985     return ConstantInt::get(GetCompareTy(LHS),
1986                             !CmpInst::isTrueWhenEqual(Pred));
1987
1988   // We can only fold certain predicates on pointer comparisons.
1989   switch (Pred) {
1990   default:
1991     return nullptr;
1992
1993     // Equality comaprisons are easy to fold.
1994   case CmpInst::ICMP_EQ:
1995   case CmpInst::ICMP_NE:
1996     break;
1997
1998     // We can only handle unsigned relational comparisons because 'inbounds' on
1999     // a GEP only protects against unsigned wrapping.
2000   case CmpInst::ICMP_UGT:
2001   case CmpInst::ICMP_UGE:
2002   case CmpInst::ICMP_ULT:
2003   case CmpInst::ICMP_ULE:
2004     // However, we have to switch them to their signed variants to handle
2005     // negative indices from the base pointer.
2006     Pred = ICmpInst::getSignedPredicate(Pred);
2007     break;
2008   }
2009
2010   // Strip off any constant offsets so that we can reason about them.
2011   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2012   // here and compare base addresses like AliasAnalysis does, however there are
2013   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2014   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2015   // doesn't need to guarantee pointer inequality when it says NoAlias.
2016   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2017   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2018
2019   // If LHS and RHS are related via constant offsets to the same base
2020   // value, we can replace it with an icmp which just compares the offsets.
2021   if (LHS == RHS)
2022     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2023
2024   // Various optimizations for (in)equality comparisons.
2025   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2026     // Different non-empty allocations that exist at the same time have
2027     // different addresses (if the program can tell). Global variables always
2028     // exist, so they always exist during the lifetime of each other and all
2029     // allocas. Two different allocas usually have different addresses...
2030     //
2031     // However, if there's an @llvm.stackrestore dynamically in between two
2032     // allocas, they may have the same address. It's tempting to reduce the
2033     // scope of the problem by only looking at *static* allocas here. That would
2034     // cover the majority of allocas while significantly reducing the likelihood
2035     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2036     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2037     // an entry block. Also, if we have a block that's not attached to a
2038     // function, we can't tell if it's "static" under the current definition.
2039     // Theoretically, this problem could be fixed by creating a new kind of
2040     // instruction kind specifically for static allocas. Such a new instruction
2041     // could be required to be at the top of the entry block, thus preventing it
2042     // from being subject to a @llvm.stackrestore. Instcombine could even
2043     // convert regular allocas into these special allocas. It'd be nifty.
2044     // However, until then, this problem remains open.
2045     //
2046     // So, we'll assume that two non-empty allocas have different addresses
2047     // for now.
2048     //
2049     // With all that, if the offsets are within the bounds of their allocations
2050     // (and not one-past-the-end! so we can't use inbounds!), and their
2051     // allocations aren't the same, the pointers are not equal.
2052     //
2053     // Note that it's not necessary to check for LHS being a global variable
2054     // address, due to canonicalization and constant folding.
2055     if (isa<AllocaInst>(LHS) &&
2056         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2057       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2058       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2059       uint64_t LHSSize, RHSSize;
2060       if (LHSOffsetCI && RHSOffsetCI &&
2061           getObjectSize(LHS, LHSSize, DL, TLI) &&
2062           getObjectSize(RHS, RHSSize, DL, TLI)) {
2063         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2064         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2065         if (!LHSOffsetValue.isNegative() &&
2066             !RHSOffsetValue.isNegative() &&
2067             LHSOffsetValue.ult(LHSSize) &&
2068             RHSOffsetValue.ult(RHSSize)) {
2069           return ConstantInt::get(GetCompareTy(LHS),
2070                                   !CmpInst::isTrueWhenEqual(Pred));
2071         }
2072       }
2073
2074       // Repeat the above check but this time without depending on DataLayout
2075       // or being able to compute a precise size.
2076       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2077           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2078           LHSOffset->isNullValue() &&
2079           RHSOffset->isNullValue())
2080         return ConstantInt::get(GetCompareTy(LHS),
2081                                 !CmpInst::isTrueWhenEqual(Pred));
2082     }
2083
2084     // Even if an non-inbounds GEP occurs along the path we can still optimize
2085     // equality comparisons concerning the result. We avoid walking the whole
2086     // chain again by starting where the last calls to
2087     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2088     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2089     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2090     if (LHS == RHS)
2091       return ConstantExpr::getICmp(Pred,
2092                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2093                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2094
2095     // If one side of the equality comparison must come from a noalias call
2096     // (meaning a system memory allocation function), and the other side must
2097     // come from a pointer that cannot overlap with dynamically-allocated
2098     // memory within the lifetime of the current function (allocas, byval
2099     // arguments, globals), then determine the comparison result here.
2100     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2101     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2102     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2103
2104     // Is the set of underlying objects all noalias calls?
2105     auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
2106       return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
2107     };
2108
2109     // Is the set of underlying objects all things which must be disjoint from
2110     // noalias calls. For allocas, we consider only static ones (dynamic
2111     // allocas might be transformed into calls to malloc not simultaneously
2112     // live with the compared-to allocation). For globals, we exclude symbols
2113     // that might be resolve lazily to symbols in another dynamically-loaded
2114     // library (and, thus, could be malloc'ed by the implementation).
2115     auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
2116       return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2117         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2118           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2119         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2120           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2121                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2122                  !GV->isThreadLocal();
2123         if (const Argument *A = dyn_cast<Argument>(V))
2124           return A->hasByValAttr();
2125         return false;
2126       });
2127     };
2128
2129     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2130         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2131         return ConstantInt::get(GetCompareTy(LHS),
2132                                 !CmpInst::isTrueWhenEqual(Pred));
2133
2134     // Fold comparisons for non-escaping pointer even if the allocation call
2135     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2136     // dynamic allocation call could be either of the operands.
2137     Value *MI = nullptr;
2138     if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
2139       MI = LHS;
2140     else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
2141       MI = RHS;
2142     // FIXME: We should also fold the compare when the pointer escapes, but the
2143     // compare dominates the pointer escape
2144     if (MI && !PointerMayBeCaptured(MI, true, true))
2145       return ConstantInt::get(GetCompareTy(LHS),
2146                               CmpInst::isFalseWhenEqual(Pred));
2147   }
2148
2149   // Otherwise, fail.
2150   return nullptr;
2151 }
2152
2153 /// Given operands for an ICmpInst, see if we can fold the result.
2154 /// If not, this returns null.
2155 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2156                                const Query &Q, unsigned MaxRecurse) {
2157   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2158   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2159
2160   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2161     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2162       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2163
2164     // If we have a constant, make sure it is on the RHS.
2165     std::swap(LHS, RHS);
2166     Pred = CmpInst::getSwappedPredicate(Pred);
2167   }
2168
2169   Type *ITy = GetCompareTy(LHS); // The return type.
2170   Type *OpTy = LHS->getType();   // The operand type.
2171
2172   // icmp X, X -> true/false
2173   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2174   // because X could be 0.
2175   if (LHS == RHS || isa<UndefValue>(RHS))
2176     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2177
2178   // Special case logic when the operands have i1 type.
2179   if (OpTy->getScalarType()->isIntegerTy(1)) {
2180     switch (Pred) {
2181     default: break;
2182     case ICmpInst::ICMP_EQ:
2183       // X == 1 -> X
2184       if (match(RHS, m_One()))
2185         return LHS;
2186       break;
2187     case ICmpInst::ICMP_NE:
2188       // X != 0 -> X
2189       if (match(RHS, m_Zero()))
2190         return LHS;
2191       break;
2192     case ICmpInst::ICMP_UGT:
2193       // X >u 0 -> X
2194       if (match(RHS, m_Zero()))
2195         return LHS;
2196       break;
2197     case ICmpInst::ICMP_UGE: {
2198       // X >=u 1 -> X
2199       if (match(RHS, m_One()))
2200         return LHS;
2201       if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2202         return getTrue(ITy);
2203       break;
2204     }
2205     case ICmpInst::ICMP_SGE: {
2206       /// For signed comparison, the values for an i1 are 0 and -1
2207       /// respectively. This maps into a truth table of:
2208       /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2209       ///  0  |  0  |  1 (0 >= 0)   |  1
2210       ///  0  |  1  |  1 (0 >= -1)  |  1
2211       ///  1  |  0  |  0 (-1 >= 0)  |  0
2212       ///  1  |  1  |  1 (-1 >= -1) |  1
2213       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2214         return getTrue(ITy);
2215       break;
2216     }
2217     case ICmpInst::ICMP_SLT:
2218       // X <s 0 -> X
2219       if (match(RHS, m_Zero()))
2220         return LHS;
2221       break;
2222     case ICmpInst::ICMP_SLE:
2223       // X <=s -1 -> X
2224       if (match(RHS, m_One()))
2225         return LHS;
2226       break;
2227     case ICmpInst::ICMP_ULE: {
2228       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2229         return getTrue(ITy);
2230       break;
2231     }
2232     }
2233   }
2234
2235   // If we are comparing with zero then try hard since this is a common case.
2236   if (match(RHS, m_Zero())) {
2237     bool LHSKnownNonNegative, LHSKnownNegative;
2238     switch (Pred) {
2239     default: llvm_unreachable("Unknown ICmp predicate!");
2240     case ICmpInst::ICMP_ULT:
2241       return getFalse(ITy);
2242     case ICmpInst::ICMP_UGE:
2243       return getTrue(ITy);
2244     case ICmpInst::ICMP_EQ:
2245     case ICmpInst::ICMP_ULE:
2246       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2247         return getFalse(ITy);
2248       break;
2249     case ICmpInst::ICMP_NE:
2250     case ICmpInst::ICMP_UGT:
2251       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2252         return getTrue(ITy);
2253       break;
2254     case ICmpInst::ICMP_SLT:
2255       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2256                      Q.CxtI, Q.DT);
2257       if (LHSKnownNegative)
2258         return getTrue(ITy);
2259       if (LHSKnownNonNegative)
2260         return getFalse(ITy);
2261       break;
2262     case ICmpInst::ICMP_SLE:
2263       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2264                      Q.CxtI, Q.DT);
2265       if (LHSKnownNegative)
2266         return getTrue(ITy);
2267       if (LHSKnownNonNegative &&
2268           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2269         return getFalse(ITy);
2270       break;
2271     case ICmpInst::ICMP_SGE:
2272       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2273                      Q.CxtI, Q.DT);
2274       if (LHSKnownNegative)
2275         return getFalse(ITy);
2276       if (LHSKnownNonNegative)
2277         return getTrue(ITy);
2278       break;
2279     case ICmpInst::ICMP_SGT:
2280       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2281                      Q.CxtI, Q.DT);
2282       if (LHSKnownNegative)
2283         return getFalse(ITy);
2284       if (LHSKnownNonNegative &&
2285           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2286         return getTrue(ITy);
2287       break;
2288     }
2289   }
2290
2291   // See if we are doing a comparison with a constant integer.
2292   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2293     // Rule out tautological comparisons (eg., ult 0 or uge 0).
2294     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2295     if (RHS_CR.isEmptySet())
2296       return ConstantInt::getFalse(CI->getContext());
2297     if (RHS_CR.isFullSet())
2298       return ConstantInt::getTrue(CI->getContext());
2299
2300     // Many binary operators with constant RHS have easy to compute constant
2301     // range.  Use them to check whether the comparison is a tautology.
2302     unsigned Width = CI->getBitWidth();
2303     APInt Lower = APInt(Width, 0);
2304     APInt Upper = APInt(Width, 0);
2305     ConstantInt *CI2;
2306     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2307       // 'urem x, CI2' produces [0, CI2).
2308       Upper = CI2->getValue();
2309     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2310       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2311       Upper = CI2->getValue().abs();
2312       Lower = (-Upper) + 1;
2313     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2314       // 'udiv CI2, x' produces [0, CI2].
2315       Upper = CI2->getValue() + 1;
2316     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2317       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2318       APInt NegOne = APInt::getAllOnesValue(Width);
2319       if (!CI2->isZero())
2320         Upper = NegOne.udiv(CI2->getValue()) + 1;
2321     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2322       if (CI2->isMinSignedValue()) {
2323         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2324         Lower = CI2->getValue();
2325         Upper = Lower.lshr(1) + 1;
2326       } else {
2327         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2328         Upper = CI2->getValue().abs() + 1;
2329         Lower = (-Upper) + 1;
2330       }
2331     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2332       APInt IntMin = APInt::getSignedMinValue(Width);
2333       APInt IntMax = APInt::getSignedMaxValue(Width);
2334       const APInt &Val = CI2->getValue();
2335       if (Val.isAllOnesValue()) {
2336         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2337         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2338         Lower = IntMin + 1;
2339         Upper = IntMax + 1;
2340       } else if (Val.countLeadingZeros() < Width - 1) {
2341         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2342         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2343         Lower = IntMin.sdiv(Val);
2344         Upper = IntMax.sdiv(Val);
2345         if (Lower.sgt(Upper))
2346           std::swap(Lower, Upper);
2347         Upper = Upper + 1;
2348         assert(Upper != Lower && "Upper part of range has wrapped!");
2349       }
2350     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2351       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2352       Lower = CI2->getValue();
2353       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2354     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2355       if (CI2->isNegative()) {
2356         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2357         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2358         Lower = CI2->getValue().shl(ShiftAmount);
2359         Upper = CI2->getValue() + 1;
2360       } else {
2361         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2362         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2363         Lower = CI2->getValue();
2364         Upper = CI2->getValue().shl(ShiftAmount) + 1;
2365       }
2366     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2367       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2368       APInt NegOne = APInt::getAllOnesValue(Width);
2369       if (CI2->getValue().ult(Width))
2370         Upper = NegOne.lshr(CI2->getValue()) + 1;
2371     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2372       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2373       unsigned ShiftAmount = Width - 1;
2374       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2375         ShiftAmount = CI2->getValue().countTrailingZeros();
2376       Lower = CI2->getValue().lshr(ShiftAmount);
2377       Upper = CI2->getValue() + 1;
2378     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2379       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2380       APInt IntMin = APInt::getSignedMinValue(Width);
2381       APInt IntMax = APInt::getSignedMaxValue(Width);
2382       if (CI2->getValue().ult(Width)) {
2383         Lower = IntMin.ashr(CI2->getValue());
2384         Upper = IntMax.ashr(CI2->getValue()) + 1;
2385       }
2386     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2387       unsigned ShiftAmount = Width - 1;
2388       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2389         ShiftAmount = CI2->getValue().countTrailingZeros();
2390       if (CI2->isNegative()) {
2391         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2392         Lower = CI2->getValue();
2393         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2394       } else {
2395         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2396         Lower = CI2->getValue().ashr(ShiftAmount);
2397         Upper = CI2->getValue() + 1;
2398       }
2399     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2400       // 'or x, CI2' produces [CI2, UINT_MAX].
2401       Lower = CI2->getValue();
2402     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2403       // 'and x, CI2' produces [0, CI2].
2404       Upper = CI2->getValue() + 1;
2405     } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2406       // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2407       Lower = CI2->getValue();
2408     }
2409
2410     ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2411                                           : ConstantRange(Width, true);
2412
2413     if (auto *I = dyn_cast<Instruction>(LHS))
2414       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2415         LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2416
2417     if (!LHS_CR.isFullSet()) {
2418       if (RHS_CR.contains(LHS_CR))
2419         return ConstantInt::getTrue(RHS->getContext());
2420       if (RHS_CR.inverse().contains(LHS_CR))
2421         return ConstantInt::getFalse(RHS->getContext());
2422     }
2423   }
2424
2425   // If both operands have range metadata, use the metadata
2426   // to simplify the comparison.
2427   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2428     auto RHS_Instr = dyn_cast<Instruction>(RHS);
2429     auto LHS_Instr = dyn_cast<Instruction>(LHS);
2430
2431     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2432         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2433       auto RHS_CR = getConstantRangeFromMetadata(
2434           *RHS_Instr->getMetadata(LLVMContext::MD_range));
2435       auto LHS_CR = getConstantRangeFromMetadata(
2436           *LHS_Instr->getMetadata(LLVMContext::MD_range));
2437
2438       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2439       if (Satisfied_CR.contains(LHS_CR))
2440         return ConstantInt::getTrue(RHS->getContext());
2441
2442       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2443                 CmpInst::getInversePredicate(Pred), RHS_CR);
2444       if (InversedSatisfied_CR.contains(LHS_CR))
2445         return ConstantInt::getFalse(RHS->getContext());
2446     }
2447   }
2448
2449   // Compare of cast, for example (zext X) != 0 -> X != 0
2450   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2451     Instruction *LI = cast<CastInst>(LHS);
2452     Value *SrcOp = LI->getOperand(0);
2453     Type *SrcTy = SrcOp->getType();
2454     Type *DstTy = LI->getType();
2455
2456     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2457     // if the integer type is the same size as the pointer type.
2458     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2459         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2460       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2461         // Transfer the cast to the constant.
2462         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2463                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2464                                         Q, MaxRecurse-1))
2465           return V;
2466       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2467         if (RI->getOperand(0)->getType() == SrcTy)
2468           // Compare without the cast.
2469           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2470                                           Q, MaxRecurse-1))
2471             return V;
2472       }
2473     }
2474
2475     if (isa<ZExtInst>(LHS)) {
2476       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2477       // same type.
2478       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2479         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2480           // Compare X and Y.  Note that signed predicates become unsigned.
2481           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2482                                           SrcOp, RI->getOperand(0), Q,
2483                                           MaxRecurse-1))
2484             return V;
2485       }
2486       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2487       // too.  If not, then try to deduce the result of the comparison.
2488       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2489         // Compute the constant that would happen if we truncated to SrcTy then
2490         // reextended to DstTy.
2491         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2492         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2493
2494         // If the re-extended constant didn't change then this is effectively
2495         // also a case of comparing two zero-extended values.
2496         if (RExt == CI && MaxRecurse)
2497           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2498                                         SrcOp, Trunc, Q, MaxRecurse-1))
2499             return V;
2500
2501         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2502         // there.  Use this to work out the result of the comparison.
2503         if (RExt != CI) {
2504           switch (Pred) {
2505           default: llvm_unreachable("Unknown ICmp predicate!");
2506           // LHS <u RHS.
2507           case ICmpInst::ICMP_EQ:
2508           case ICmpInst::ICMP_UGT:
2509           case ICmpInst::ICMP_UGE:
2510             return ConstantInt::getFalse(CI->getContext());
2511
2512           case ICmpInst::ICMP_NE:
2513           case ICmpInst::ICMP_ULT:
2514           case ICmpInst::ICMP_ULE:
2515             return ConstantInt::getTrue(CI->getContext());
2516
2517           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2518           // is non-negative then LHS <s RHS.
2519           case ICmpInst::ICMP_SGT:
2520           case ICmpInst::ICMP_SGE:
2521             return CI->getValue().isNegative() ?
2522               ConstantInt::getTrue(CI->getContext()) :
2523               ConstantInt::getFalse(CI->getContext());
2524
2525           case ICmpInst::ICMP_SLT:
2526           case ICmpInst::ICMP_SLE:
2527             return CI->getValue().isNegative() ?
2528               ConstantInt::getFalse(CI->getContext()) :
2529               ConstantInt::getTrue(CI->getContext());
2530           }
2531         }
2532       }
2533     }
2534
2535     if (isa<SExtInst>(LHS)) {
2536       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2537       // same type.
2538       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2539         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2540           // Compare X and Y.  Note that the predicate does not change.
2541           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2542                                           Q, MaxRecurse-1))
2543             return V;
2544       }
2545       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2546       // too.  If not, then try to deduce the result of the comparison.
2547       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2548         // Compute the constant that would happen if we truncated to SrcTy then
2549         // reextended to DstTy.
2550         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2551         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2552
2553         // If the re-extended constant didn't change then this is effectively
2554         // also a case of comparing two sign-extended values.
2555         if (RExt == CI && MaxRecurse)
2556           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2557             return V;
2558
2559         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2560         // bits there.  Use this to work out the result of the comparison.
2561         if (RExt != CI) {
2562           switch (Pred) {
2563           default: llvm_unreachable("Unknown ICmp predicate!");
2564           case ICmpInst::ICMP_EQ:
2565             return ConstantInt::getFalse(CI->getContext());
2566           case ICmpInst::ICMP_NE:
2567             return ConstantInt::getTrue(CI->getContext());
2568
2569           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2570           // LHS >s RHS.
2571           case ICmpInst::ICMP_SGT:
2572           case ICmpInst::ICMP_SGE:
2573             return CI->getValue().isNegative() ?
2574               ConstantInt::getTrue(CI->getContext()) :
2575               ConstantInt::getFalse(CI->getContext());
2576           case ICmpInst::ICMP_SLT:
2577           case ICmpInst::ICMP_SLE:
2578             return CI->getValue().isNegative() ?
2579               ConstantInt::getFalse(CI->getContext()) :
2580               ConstantInt::getTrue(CI->getContext());
2581
2582           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2583           // LHS >u RHS.
2584           case ICmpInst::ICMP_UGT:
2585           case ICmpInst::ICMP_UGE:
2586             // Comparison is true iff the LHS <s 0.
2587             if (MaxRecurse)
2588               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2589                                               Constant::getNullValue(SrcTy),
2590                                               Q, MaxRecurse-1))
2591                 return V;
2592             break;
2593           case ICmpInst::ICMP_ULT:
2594           case ICmpInst::ICMP_ULE:
2595             // Comparison is true iff the LHS >=s 0.
2596             if (MaxRecurse)
2597               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2598                                               Constant::getNullValue(SrcTy),
2599                                               Q, MaxRecurse-1))
2600                 return V;
2601             break;
2602           }
2603         }
2604       }
2605     }
2606   }
2607
2608   // icmp eq|ne X, Y -> false|true if X != Y
2609   if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2610       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2611     LLVMContext &Ctx = LHS->getType()->getContext();
2612     return Pred == ICmpInst::ICMP_NE ?
2613       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2614   }
2615
2616   // Special logic for binary operators.
2617   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2618   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2619   if (MaxRecurse && (LBO || RBO)) {
2620     // Analyze the case when either LHS or RHS is an add instruction.
2621     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2622     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2623     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2624     if (LBO && LBO->getOpcode() == Instruction::Add) {
2625       A = LBO->getOperand(0); B = LBO->getOperand(1);
2626       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2627         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2628         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2629     }
2630     if (RBO && RBO->getOpcode() == Instruction::Add) {
2631       C = RBO->getOperand(0); D = RBO->getOperand(1);
2632       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2633         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2634         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2635     }
2636
2637     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2638     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2639       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2640                                       Constant::getNullValue(RHS->getType()),
2641                                       Q, MaxRecurse-1))
2642         return V;
2643
2644     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2645     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2646       if (Value *V = SimplifyICmpInst(Pred,
2647                                       Constant::getNullValue(LHS->getType()),
2648                                       C == LHS ? D : C, Q, MaxRecurse-1))
2649         return V;
2650
2651     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2652     if (A && C && (A == C || A == D || B == C || B == D) &&
2653         NoLHSWrapProblem && NoRHSWrapProblem) {
2654       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2655       Value *Y, *Z;
2656       if (A == C) {
2657         // C + B == C + D  ->  B == D
2658         Y = B;
2659         Z = D;
2660       } else if (A == D) {
2661         // D + B == C + D  ->  B == C
2662         Y = B;
2663         Z = C;
2664       } else if (B == C) {
2665         // A + C == C + D  ->  A == D
2666         Y = A;
2667         Z = D;
2668       } else {
2669         assert(B == D);
2670         // A + D == C + D  ->  A == C
2671         Y = A;
2672         Z = C;
2673       }
2674       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2675         return V;
2676     }
2677   }
2678
2679   {
2680     Value *Y = nullptr;
2681     // icmp pred (or X, Y), X
2682     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2683       if (Pred == ICmpInst::ICMP_ULT)
2684         return getFalse(ITy);
2685       if (Pred == ICmpInst::ICMP_UGE)
2686         return getTrue(ITy);
2687
2688       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2689         bool RHSKnownNonNegative, RHSKnownNegative;
2690         bool YKnownNonNegative, YKnownNegative;
2691         ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2692                        Q.AC, Q.CxtI, Q.DT);
2693         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2694                        Q.CxtI, Q.DT);
2695         if (RHSKnownNonNegative && YKnownNegative)
2696           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2697         if (RHSKnownNegative || YKnownNonNegative)
2698           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2699       }
2700     }
2701     // icmp pred X, (or X, Y)
2702     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2703       if (Pred == ICmpInst::ICMP_ULE)
2704         return getTrue(ITy);
2705       if (Pred == ICmpInst::ICMP_UGT)
2706         return getFalse(ITy);
2707
2708       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2709         bool LHSKnownNonNegative, LHSKnownNegative;
2710         bool YKnownNonNegative, YKnownNegative;
2711         ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2712                        Q.AC, Q.CxtI, Q.DT);
2713         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2714                        Q.CxtI, Q.DT);
2715         if (LHSKnownNonNegative && YKnownNegative)
2716           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2717         if (LHSKnownNegative || YKnownNonNegative)
2718           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2719       }
2720     }
2721   }
2722
2723   // icmp pred (and X, Y), X
2724   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2725                                     m_And(m_Specific(RHS), m_Value())))) {
2726     if (Pred == ICmpInst::ICMP_UGT)
2727       return getFalse(ITy);
2728     if (Pred == ICmpInst::ICMP_ULE)
2729       return getTrue(ITy);
2730   }
2731   // icmp pred X, (and X, Y)
2732   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2733                                     m_And(m_Specific(LHS), m_Value())))) {
2734     if (Pred == ICmpInst::ICMP_UGE)
2735       return getTrue(ITy);
2736     if (Pred == ICmpInst::ICMP_ULT)
2737       return getFalse(ITy);
2738   }
2739
2740   // 0 - (zext X) pred C
2741   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2742     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2743       if (RHSC->getValue().isStrictlyPositive()) {
2744         if (Pred == ICmpInst::ICMP_SLT)
2745           return ConstantInt::getTrue(RHSC->getContext());
2746         if (Pred == ICmpInst::ICMP_SGE)
2747           return ConstantInt::getFalse(RHSC->getContext());
2748         if (Pred == ICmpInst::ICMP_EQ)
2749           return ConstantInt::getFalse(RHSC->getContext());
2750         if (Pred == ICmpInst::ICMP_NE)
2751           return ConstantInt::getTrue(RHSC->getContext());
2752       }
2753       if (RHSC->getValue().isNonNegative()) {
2754         if (Pred == ICmpInst::ICMP_SLE)
2755           return ConstantInt::getTrue(RHSC->getContext());
2756         if (Pred == ICmpInst::ICMP_SGT)
2757           return ConstantInt::getFalse(RHSC->getContext());
2758       }
2759     }
2760   }
2761
2762   // icmp pred (urem X, Y), Y
2763   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2764     bool KnownNonNegative, KnownNegative;
2765     switch (Pred) {
2766     default:
2767       break;
2768     case ICmpInst::ICMP_SGT:
2769     case ICmpInst::ICMP_SGE:
2770       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2771                      Q.CxtI, Q.DT);
2772       if (!KnownNonNegative)
2773         break;
2774       // fall-through
2775     case ICmpInst::ICMP_EQ:
2776     case ICmpInst::ICMP_UGT:
2777     case ICmpInst::ICMP_UGE:
2778       return getFalse(ITy);
2779     case ICmpInst::ICMP_SLT:
2780     case ICmpInst::ICMP_SLE:
2781       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2782                      Q.CxtI, Q.DT);
2783       if (!KnownNonNegative)
2784         break;
2785       // fall-through
2786     case ICmpInst::ICMP_NE:
2787     case ICmpInst::ICMP_ULT:
2788     case ICmpInst::ICMP_ULE:
2789       return getTrue(ITy);
2790     }
2791   }
2792
2793   // icmp pred X, (urem Y, X)
2794   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2795     bool KnownNonNegative, KnownNegative;
2796     switch (Pred) {
2797     default:
2798       break;
2799     case ICmpInst::ICMP_SGT:
2800     case ICmpInst::ICMP_SGE:
2801       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2802                      Q.CxtI, Q.DT);
2803       if (!KnownNonNegative)
2804         break;
2805       // fall-through
2806     case ICmpInst::ICMP_NE:
2807     case ICmpInst::ICMP_UGT:
2808     case ICmpInst::ICMP_UGE:
2809       return getTrue(ITy);
2810     case ICmpInst::ICMP_SLT:
2811     case ICmpInst::ICMP_SLE:
2812       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2813                      Q.CxtI, Q.DT);
2814       if (!KnownNonNegative)
2815         break;
2816       // fall-through
2817     case ICmpInst::ICMP_EQ:
2818     case ICmpInst::ICMP_ULT:
2819     case ICmpInst::ICMP_ULE:
2820       return getFalse(ITy);
2821     }
2822   }
2823
2824   // x >> y <=u x
2825   // x udiv y <=u x.
2826   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2827               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2828     // icmp pred (X op Y), X
2829     if (Pred == ICmpInst::ICMP_UGT)
2830       return getFalse(ITy);
2831     if (Pred == ICmpInst::ICMP_ULE)
2832       return getTrue(ITy);
2833   }
2834
2835   // handle:
2836   //   CI2 << X == CI
2837   //   CI2 << X != CI
2838   //
2839   //   where CI2 is a power of 2 and CI isn't
2840   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2841     const APInt *CI2Val, *CIVal = &CI->getValue();
2842     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2843         CI2Val->isPowerOf2()) {
2844       if (!CIVal->isPowerOf2()) {
2845         // CI2 << X can equal zero in some circumstances,
2846         // this simplification is unsafe if CI is zero.
2847         //
2848         // We know it is safe if:
2849         // - The shift is nsw, we can't shift out the one bit.
2850         // - The shift is nuw, we can't shift out the one bit.
2851         // - CI2 is one
2852         // - CI isn't zero
2853         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2854             *CI2Val == 1 || !CI->isZero()) {
2855           if (Pred == ICmpInst::ICMP_EQ)
2856             return ConstantInt::getFalse(RHS->getContext());
2857           if (Pred == ICmpInst::ICMP_NE)
2858             return ConstantInt::getTrue(RHS->getContext());
2859         }
2860       }
2861       if (CIVal->isSignBit() && *CI2Val == 1) {
2862         if (Pred == ICmpInst::ICMP_UGT)
2863           return ConstantInt::getFalse(RHS->getContext());
2864         if (Pred == ICmpInst::ICMP_ULE)
2865           return ConstantInt::getTrue(RHS->getContext());
2866       }
2867     }
2868   }
2869
2870   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2871       LBO->getOperand(1) == RBO->getOperand(1)) {
2872     switch (LBO->getOpcode()) {
2873     default: break;
2874     case Instruction::UDiv:
2875     case Instruction::LShr:
2876       if (ICmpInst::isSigned(Pred))
2877         break;
2878       // fall-through
2879     case Instruction::SDiv:
2880     case Instruction::AShr:
2881       if (!LBO->isExact() || !RBO->isExact())
2882         break;
2883       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2884                                       RBO->getOperand(0), Q, MaxRecurse-1))
2885         return V;
2886       break;
2887     case Instruction::Shl: {
2888       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2889       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2890       if (!NUW && !NSW)
2891         break;
2892       if (!NSW && ICmpInst::isSigned(Pred))
2893         break;
2894       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2895                                       RBO->getOperand(0), Q, MaxRecurse-1))
2896         return V;
2897       break;
2898     }
2899     }
2900   }
2901
2902   // Simplify comparisons involving max/min.
2903   Value *A, *B;
2904   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2905   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2906
2907   // Signed variants on "max(a,b)>=a -> true".
2908   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2909     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2910     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2911     // We analyze this as smax(A, B) pred A.
2912     P = Pred;
2913   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2914              (A == LHS || B == LHS)) {
2915     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2916     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2917     // We analyze this as smax(A, B) swapped-pred A.
2918     P = CmpInst::getSwappedPredicate(Pred);
2919   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2920              (A == RHS || B == RHS)) {
2921     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2922     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2923     // We analyze this as smax(-A, -B) swapped-pred -A.
2924     // Note that we do not need to actually form -A or -B thanks to EqP.
2925     P = CmpInst::getSwappedPredicate(Pred);
2926   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2927              (A == LHS || B == LHS)) {
2928     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2929     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2930     // We analyze this as smax(-A, -B) pred -A.
2931     // Note that we do not need to actually form -A or -B thanks to EqP.
2932     P = Pred;
2933   }
2934   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2935     // Cases correspond to "max(A, B) p A".
2936     switch (P) {
2937     default:
2938       break;
2939     case CmpInst::ICMP_EQ:
2940     case CmpInst::ICMP_SLE:
2941       // Equivalent to "A EqP B".  This may be the same as the condition tested
2942       // in the max/min; if so, we can just return that.
2943       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2944         return V;
2945       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2946         return V;
2947       // Otherwise, see if "A EqP B" simplifies.
2948       if (MaxRecurse)
2949         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2950           return V;
2951       break;
2952     case CmpInst::ICMP_NE:
2953     case CmpInst::ICMP_SGT: {
2954       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2955       // Equivalent to "A InvEqP B".  This may be the same as the condition
2956       // tested in the max/min; if so, we can just return that.
2957       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2958         return V;
2959       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2960         return V;
2961       // Otherwise, see if "A InvEqP B" simplifies.
2962       if (MaxRecurse)
2963         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2964           return V;
2965       break;
2966     }
2967     case CmpInst::ICMP_SGE:
2968       // Always true.
2969       return getTrue(ITy);
2970     case CmpInst::ICMP_SLT:
2971       // Always false.
2972       return getFalse(ITy);
2973     }
2974   }
2975
2976   // Unsigned variants on "max(a,b)>=a -> true".
2977   P = CmpInst::BAD_ICMP_PREDICATE;
2978   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2979     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2980     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2981     // We analyze this as umax(A, B) pred A.
2982     P = Pred;
2983   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2984              (A == LHS || B == LHS)) {
2985     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2986     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2987     // We analyze this as umax(A, B) swapped-pred A.
2988     P = CmpInst::getSwappedPredicate(Pred);
2989   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2990              (A == RHS || B == RHS)) {
2991     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2992     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2993     // We analyze this as umax(-A, -B) swapped-pred -A.
2994     // Note that we do not need to actually form -A or -B thanks to EqP.
2995     P = CmpInst::getSwappedPredicate(Pred);
2996   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2997              (A == LHS || B == LHS)) {
2998     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2999     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3000     // We analyze this as umax(-A, -B) pred -A.
3001     // Note that we do not need to actually form -A or -B thanks to EqP.
3002     P = Pred;
3003   }
3004   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3005     // Cases correspond to "max(A, B) p A".
3006     switch (P) {
3007     default:
3008       break;
3009     case CmpInst::ICMP_EQ:
3010     case CmpInst::ICMP_ULE:
3011       // Equivalent to "A EqP B".  This may be the same as the condition tested
3012       // in the max/min; if so, we can just return that.
3013       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3014         return V;
3015       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3016         return V;
3017       // Otherwise, see if "A EqP B" simplifies.
3018       if (MaxRecurse)
3019         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
3020           return V;
3021       break;
3022     case CmpInst::ICMP_NE:
3023     case CmpInst::ICMP_UGT: {
3024       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3025       // Equivalent to "A InvEqP B".  This may be the same as the condition
3026       // tested in the max/min; if so, we can just return that.
3027       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3028         return V;
3029       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3030         return V;
3031       // Otherwise, see if "A InvEqP B" simplifies.
3032       if (MaxRecurse)
3033         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
3034           return V;
3035       break;
3036     }
3037     case CmpInst::ICMP_UGE:
3038       // Always true.
3039       return getTrue(ITy);
3040     case CmpInst::ICMP_ULT:
3041       // Always false.
3042       return getFalse(ITy);
3043     }
3044   }
3045
3046   // Variants on "max(x,y) >= min(x,z)".
3047   Value *C, *D;
3048   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3049       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3050       (A == C || A == D || B == C || B == D)) {
3051     // max(x, ?) pred min(x, ?).
3052     if (Pred == CmpInst::ICMP_SGE)
3053       // Always true.
3054       return getTrue(ITy);
3055     if (Pred == CmpInst::ICMP_SLT)
3056       // Always false.
3057       return getFalse(ITy);
3058   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3059              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3060              (A == C || A == D || B == C || B == D)) {
3061     // min(x, ?) pred max(x, ?).
3062     if (Pred == CmpInst::ICMP_SLE)
3063       // Always true.
3064       return getTrue(ITy);
3065     if (Pred == CmpInst::ICMP_SGT)
3066       // Always false.
3067       return getFalse(ITy);
3068   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3069              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3070              (A == C || A == D || B == C || B == D)) {
3071     // max(x, ?) pred min(x, ?).
3072     if (Pred == CmpInst::ICMP_UGE)
3073       // Always true.
3074       return getTrue(ITy);
3075     if (Pred == CmpInst::ICMP_ULT)
3076       // Always false.
3077       return getFalse(ITy);
3078   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3079              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3080              (A == C || A == D || B == C || B == D)) {
3081     // min(x, ?) pred max(x, ?).
3082     if (Pred == CmpInst::ICMP_ULE)
3083       // Always true.
3084       return getTrue(ITy);
3085     if (Pred == CmpInst::ICMP_UGT)
3086       // Always false.
3087       return getFalse(ITy);
3088   }
3089
3090   // Simplify comparisons of related pointers using a powerful, recursive
3091   // GEP-walk when we have target data available..
3092   if (LHS->getType()->isPointerTy())
3093     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
3094       return C;
3095
3096   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3097     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3098       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3099           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3100           (ICmpInst::isEquality(Pred) ||
3101            (GLHS->isInBounds() && GRHS->isInBounds() &&
3102             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3103         // The bases are equal and the indices are constant.  Build a constant
3104         // expression GEP with the same indices and a null base pointer to see
3105         // what constant folding can make out of it.
3106         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3107         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3108         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3109             GLHS->getSourceElementType(), Null, IndicesLHS);
3110
3111         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3112         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3113             GLHS->getSourceElementType(), Null, IndicesRHS);
3114         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3115       }
3116     }
3117   }
3118
3119   // If a bit is known to be zero for A and known to be one for B,
3120   // then A and B cannot be equal.
3121   if (ICmpInst::isEquality(Pred)) {
3122     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3123       uint32_t BitWidth = CI->getBitWidth();
3124       APInt LHSKnownZero(BitWidth, 0);
3125       APInt LHSKnownOne(BitWidth, 0);
3126       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3127                        Q.CxtI, Q.DT);
3128       const APInt &RHSVal = CI->getValue();
3129       if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3130         return Pred == ICmpInst::ICMP_EQ
3131                    ? ConstantInt::getFalse(CI->getContext())
3132                    : ConstantInt::getTrue(CI->getContext());
3133     }
3134   }
3135
3136   // If the comparison is with the result of a select instruction, check whether
3137   // comparing with either branch of the select always yields the same value.
3138   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3139     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3140       return V;
3141
3142   // If the comparison is with the result of a phi instruction, check whether
3143   // doing the compare with each incoming phi value yields a common result.
3144   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3145     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3146       return V;
3147
3148   return nullptr;
3149 }
3150
3151 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3152                               const DataLayout &DL,
3153                               const TargetLibraryInfo *TLI,
3154                               const DominatorTree *DT, AssumptionCache *AC,
3155                               const Instruction *CxtI) {
3156   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3157                             RecursionLimit);
3158 }
3159
3160 /// Given operands for an FCmpInst, see if we can fold the result.
3161 /// If not, this returns null.
3162 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3163                                FastMathFlags FMF, const Query &Q,
3164                                unsigned MaxRecurse) {
3165   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3166   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3167
3168   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3169     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3170       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3171
3172     // If we have a constant, make sure it is on the RHS.
3173     std::swap(LHS, RHS);
3174     Pred = CmpInst::getSwappedPredicate(Pred);
3175   }
3176
3177   // Fold trivial predicates.
3178   if (Pred == FCmpInst::FCMP_FALSE)
3179     return ConstantInt::get(GetCompareTy(LHS), 0);
3180   if (Pred == FCmpInst::FCMP_TRUE)
3181     return ConstantInt::get(GetCompareTy(LHS), 1);
3182
3183   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3184   if (FMF.noNaNs()) {
3185     if (Pred == FCmpInst::FCMP_UNO)
3186       return ConstantInt::get(GetCompareTy(LHS), 0);
3187     if (Pred == FCmpInst::FCMP_ORD)
3188       return ConstantInt::get(GetCompareTy(LHS), 1);
3189   }
3190
3191   // fcmp pred x, undef  and  fcmp pred undef, x
3192   // fold to true if unordered, false if ordered
3193   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3194     // Choosing NaN for the undef will always make unordered comparison succeed
3195     // and ordered comparison fail.
3196     return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3197   }
3198
3199   // fcmp x,x -> true/false.  Not all compares are foldable.
3200   if (LHS == RHS) {
3201     if (CmpInst::isTrueWhenEqual(Pred))
3202       return ConstantInt::get(GetCompareTy(LHS), 1);
3203     if (CmpInst::isFalseWhenEqual(Pred))
3204       return ConstantInt::get(GetCompareTy(LHS), 0);
3205   }
3206
3207   // Handle fcmp with constant RHS
3208   const ConstantFP *CFP = nullptr;
3209   if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3210     if (RHS->getType()->isVectorTy())
3211       CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3212     else
3213       CFP = dyn_cast<ConstantFP>(RHSC);
3214   }
3215   if (CFP) {
3216     // If the constant is a nan, see if we can fold the comparison based on it.
3217     if (CFP->getValueAPF().isNaN()) {
3218       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3219         return ConstantInt::getFalse(CFP->getContext());
3220       assert(FCmpInst::isUnordered(Pred) &&
3221              "Comparison must be either ordered or unordered!");
3222       // True if unordered.
3223       return ConstantInt::get(GetCompareTy(LHS), 1);
3224     }
3225     // Check whether the constant is an infinity.
3226     if (CFP->getValueAPF().isInfinity()) {
3227       if (CFP->getValueAPF().isNegative()) {
3228         switch (Pred) {
3229         case FCmpInst::FCMP_OLT:
3230           // No value is ordered and less than negative infinity.
3231           return ConstantInt::get(GetCompareTy(LHS), 0);
3232         case FCmpInst::FCMP_UGE:
3233           // All values are unordered with or at least negative infinity.
3234           return ConstantInt::get(GetCompareTy(LHS), 1);
3235         default:
3236           break;
3237         }
3238       } else {
3239         switch (Pred) {
3240         case FCmpInst::FCMP_OGT:
3241           // No value is ordered and greater than infinity.
3242           return ConstantInt::get(GetCompareTy(LHS), 0);
3243         case FCmpInst::FCMP_ULE:
3244           // All values are unordered with and at most infinity.
3245           return ConstantInt::get(GetCompareTy(LHS), 1);
3246         default:
3247           break;
3248         }
3249       }
3250     }
3251     if (CFP->getValueAPF().isZero()) {
3252       switch (Pred) {
3253       case FCmpInst::FCMP_UGE:
3254         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3255           return ConstantInt::get(GetCompareTy(LHS), 1);
3256         break;
3257       case FCmpInst::FCMP_OLT:
3258         // X < 0
3259         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3260           return ConstantInt::get(GetCompareTy(LHS), 0);
3261         break;
3262       default:
3263         break;
3264       }
3265     }
3266   }
3267
3268   // If the comparison is with the result of a select instruction, check whether
3269   // comparing with either branch of the select always yields the same value.
3270   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3271     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3272       return V;
3273
3274   // If the comparison is with the result of a phi instruction, check whether
3275   // doing the compare with each incoming phi value yields a common result.
3276   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3277     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3278       return V;
3279
3280   return nullptr;
3281 }
3282
3283 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3284                               FastMathFlags FMF, const DataLayout &DL,
3285                               const TargetLibraryInfo *TLI,
3286                               const DominatorTree *DT, AssumptionCache *AC,
3287                               const Instruction *CxtI) {
3288   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3289                             Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3290 }
3291
3292 /// See if V simplifies when its operand Op is replaced with RepOp.
3293 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3294                                            const Query &Q,
3295                                            unsigned MaxRecurse) {
3296   // Trivial replacement.
3297   if (V == Op)
3298     return RepOp;
3299
3300   auto *I = dyn_cast<Instruction>(V);
3301   if (!I)
3302     return nullptr;
3303
3304   // If this is a binary operator, try to simplify it with the replaced op.
3305   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3306     // Consider:
3307     //   %cmp = icmp eq i32 %x, 2147483647
3308     //   %add = add nsw i32 %x, 1
3309     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3310     //
3311     // We can't replace %sel with %add unless we strip away the flags.
3312     if (isa<OverflowingBinaryOperator>(B))
3313       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3314         return nullptr;
3315     if (isa<PossiblyExactOperator>(B))
3316       if (B->isExact())
3317         return nullptr;
3318
3319     if (MaxRecurse) {
3320       if (B->getOperand(0) == Op)
3321         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3322                              MaxRecurse - 1);
3323       if (B->getOperand(1) == Op)
3324         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3325                              MaxRecurse - 1);
3326     }
3327   }
3328
3329   // Same for CmpInsts.
3330   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3331     if (MaxRecurse) {
3332       if (C->getOperand(0) == Op)
3333         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3334                                MaxRecurse - 1);
3335       if (C->getOperand(1) == Op)
3336         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3337                                MaxRecurse - 1);
3338     }
3339   }
3340
3341   // TODO: We could hand off more cases to instsimplify here.
3342
3343   // If all operands are constant after substituting Op for RepOp then we can
3344   // constant fold the instruction.
3345   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3346     // Build a list of all constant operands.
3347     SmallVector<Constant *, 8> ConstOps;
3348     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3349       if (I->getOperand(i) == Op)
3350         ConstOps.push_back(CRepOp);
3351       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3352         ConstOps.push_back(COp);
3353       else
3354         break;
3355     }
3356
3357     // All operands were constants, fold it.
3358     if (ConstOps.size() == I->getNumOperands()) {
3359       if (CmpInst *C = dyn_cast<CmpInst>(I))
3360         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3361                                                ConstOps[1], Q.DL, Q.TLI);
3362
3363       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3364         if (!LI->isVolatile())
3365           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3366
3367       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3368     }
3369   }
3370
3371   return nullptr;
3372 }
3373
3374 /// Given operands for a SelectInst, see if we can fold the result.
3375 /// If not, this returns null.
3376 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3377                                  Value *FalseVal, const Query &Q,
3378                                  unsigned MaxRecurse) {
3379   // select true, X, Y  -> X
3380   // select false, X, Y -> Y
3381   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3382     if (CB->isAllOnesValue())
3383       return TrueVal;
3384     if (CB->isNullValue())
3385       return FalseVal;
3386   }
3387
3388   // select C, X, X -> X
3389   if (TrueVal == FalseVal)
3390     return TrueVal;
3391
3392   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3393     if (isa<Constant>(TrueVal))
3394       return TrueVal;
3395     return FalseVal;
3396   }
3397   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3398     return FalseVal;
3399   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3400     return TrueVal;
3401
3402   if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3403     // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3404     // decomposeBitTestICmp() might help.
3405     unsigned BitWidth =
3406         Q.DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
3407     ICmpInst::Predicate Pred = ICI->getPredicate();
3408     Value *CmpLHS = ICI->getOperand(0);
3409     Value *CmpRHS = ICI->getOperand(1);
3410     APInt MinSignedValue = APInt::getSignBit(BitWidth);
3411     Value *X;
3412     const APInt *Y;
3413     bool TrueWhenUnset;
3414     bool IsBitTest = false;
3415     if (ICmpInst::isEquality(Pred) &&
3416         match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3417         match(CmpRHS, m_Zero())) {
3418       IsBitTest = true;
3419       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
3420     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3421       X = CmpLHS;
3422       Y = &MinSignedValue;
3423       IsBitTest = true;
3424       TrueWhenUnset = false;
3425     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3426       X = CmpLHS;
3427       Y = &MinSignedValue;
3428       IsBitTest = true;
3429       TrueWhenUnset = true;
3430     }
3431     if (IsBitTest) {
3432       const APInt *C;
3433       // (X & Y) == 0 ? X & ~Y : X  --> X
3434       // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3435       if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3436           *Y == ~*C)
3437         return TrueWhenUnset ? FalseVal : TrueVal;
3438       // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3439       // (X & Y) != 0 ? X : X & ~Y  --> X
3440       if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3441           *Y == ~*C)
3442         return TrueWhenUnset ? FalseVal : TrueVal;
3443
3444       if (Y->isPowerOf2()) {
3445         // (X & Y) == 0 ? X | Y : X  --> X | Y
3446         // (X & Y) != 0 ? X | Y : X  --> X
3447         if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3448             *Y == *C)
3449           return TrueWhenUnset ? TrueVal : FalseVal;
3450         // (X & Y) == 0 ? X : X | Y  --> X
3451         // (X & Y) != 0 ? X : X | Y  --> X | Y
3452         if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3453             *Y == *C)
3454           return TrueWhenUnset ? TrueVal : FalseVal;
3455       }
3456     }
3457     if (ICI->hasOneUse()) {
3458       const APInt *C;
3459       if (match(CmpRHS, m_APInt(C))) {
3460         // X < MIN ? T : F  -->  F
3461         if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3462           return FalseVal;
3463         // X < MIN ? T : F  -->  F
3464         if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3465           return FalseVal;
3466         // X > MAX ? T : F  -->  F
3467         if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3468           return FalseVal;
3469         // X > MAX ? T : F  -->  F
3470         if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3471           return FalseVal;
3472       }
3473     }
3474
3475     // If we have an equality comparison then we know the value in one of the
3476     // arms of the select. See if substituting this value into the arm and
3477     // simplifying the result yields the same value as the other arm.
3478     if (Pred == ICmpInst::ICMP_EQ) {
3479       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3480               TrueVal ||
3481           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3482               TrueVal)
3483         return FalseVal;
3484       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3485               FalseVal ||
3486           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3487               FalseVal)
3488         return FalseVal;
3489     } else if (Pred == ICmpInst::ICMP_NE) {
3490       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3491               FalseVal ||
3492           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3493               FalseVal)
3494         return TrueVal;
3495       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3496               TrueVal ||
3497           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3498               TrueVal)
3499         return TrueVal;
3500     }
3501   }
3502
3503   return nullptr;
3504 }
3505
3506 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3507                                 const DataLayout &DL,
3508                                 const TargetLibraryInfo *TLI,
3509                                 const DominatorTree *DT, AssumptionCache *AC,
3510                                 const Instruction *CxtI) {
3511   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3512                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3513 }
3514
3515 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3516 /// If not, this returns null.
3517 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3518                               const Query &Q, unsigned) {
3519   // The type of the GEP pointer operand.
3520   unsigned AS =
3521       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3522
3523   // getelementptr P -> P.
3524   if (Ops.size() == 1)
3525     return Ops[0];
3526
3527   // Compute the (pointer) type returned by the GEP instruction.
3528   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3529   Type *GEPTy = PointerType::get(LastType, AS);
3530   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3531     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3532
3533   if (isa<UndefValue>(Ops[0]))
3534     return UndefValue::get(GEPTy);
3535
3536   if (Ops.size() == 2) {
3537     // getelementptr P, 0 -> P.
3538     if (match(Ops[1], m_Zero()))
3539       return Ops[0];
3540
3541     Type *Ty = SrcTy;
3542     if (Ty->isSized()) {
3543       Value *P;
3544       uint64_t C;
3545       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3546       // getelementptr P, N -> P if P points to a type of zero size.
3547       if (TyAllocSize == 0)
3548         return Ops[0];
3549
3550       // The following transforms are only safe if the ptrtoint cast
3551       // doesn't truncate the pointers.
3552       if (Ops[1]->getType()->getScalarSizeInBits() ==
3553           Q.DL.getPointerSizeInBits(AS)) {
3554         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3555           if (match(P, m_Zero()))
3556             return Constant::getNullValue(GEPTy);
3557           Value *Temp;
3558           if (match(P, m_PtrToInt(m_Value(Temp))))
3559             if (Temp->getType() == GEPTy)
3560               return Temp;
3561           return nullptr;
3562         };
3563
3564         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3565         if (TyAllocSize == 1 &&
3566             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3567           if (Value *R = PtrToIntOrZero(P))
3568             return R;
3569
3570         // getelementptr V, (ashr (sub P, V), C) -> Q
3571         // if P points to a type of size 1 << C.
3572         if (match(Ops[1],
3573                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3574                          m_ConstantInt(C))) &&
3575             TyAllocSize == 1ULL << C)
3576           if (Value *R = PtrToIntOrZero(P))
3577             return R;
3578
3579         // getelementptr V, (sdiv (sub P, V), C) -> Q
3580         // if P points to a type of size C.
3581         if (match(Ops[1],
3582                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3583                          m_SpecificInt(TyAllocSize))))
3584           if (Value *R = PtrToIntOrZero(P))
3585             return R;
3586       }
3587     }
3588   }
3589
3590   // Check to see if this is constant foldable.
3591   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3592     if (!isa<Constant>(Ops[i]))
3593       return nullptr;
3594
3595   return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3596                                         Ops.slice(1));
3597 }
3598
3599 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3600                              const DataLayout &DL,
3601                              const TargetLibraryInfo *TLI,
3602                              const DominatorTree *DT, AssumptionCache *AC,
3603                              const Instruction *CxtI) {
3604   return ::SimplifyGEPInst(SrcTy, Ops,
3605                            Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3606 }
3607
3608 /// Given operands for an InsertValueInst, see if we can fold the result.
3609 /// If not, this returns null.
3610 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3611                                       ArrayRef<unsigned> Idxs, const Query &Q,
3612                                       unsigned) {
3613   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3614     if (Constant *CVal = dyn_cast<Constant>(Val))
3615       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3616
3617   // insertvalue x, undef, n -> x
3618   if (match(Val, m_Undef()))
3619     return Agg;
3620
3621   // insertvalue x, (extractvalue y, n), n
3622   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3623     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3624         EV->getIndices() == Idxs) {
3625       // insertvalue undef, (extractvalue y, n), n -> y
3626       if (match(Agg, m_Undef()))
3627         return EV->getAggregateOperand();
3628
3629       // insertvalue y, (extractvalue y, n), n -> y
3630       if (Agg == EV->getAggregateOperand())
3631         return Agg;
3632     }
3633
3634   return nullptr;
3635 }
3636
3637 Value *llvm::SimplifyInsertValueInst(
3638     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3639     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3640     const Instruction *CxtI) {
3641   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3642                                    RecursionLimit);
3643 }
3644
3645 /// Given operands for an ExtractValueInst, see if we can fold the result.
3646 /// If not, this returns null.
3647 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3648                                        const Query &, unsigned) {
3649   if (auto *CAgg = dyn_cast<Constant>(Agg))
3650     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3651
3652   // extractvalue x, (insertvalue y, elt, n), n -> elt
3653   unsigned NumIdxs = Idxs.size();
3654   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3655        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3656     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3657     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3658     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3659     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3660         Idxs.slice(0, NumCommonIdxs)) {
3661       if (NumIdxs == NumInsertValueIdxs)
3662         return IVI->getInsertedValueOperand();
3663       break;
3664     }
3665   }
3666
3667   return nullptr;
3668 }
3669
3670 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3671                                       const DataLayout &DL,
3672                                       const TargetLibraryInfo *TLI,
3673                                       const DominatorTree *DT,
3674                                       AssumptionCache *AC,
3675                                       const Instruction *CxtI) {
3676   return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3677                                     RecursionLimit);
3678 }
3679
3680 /// Given operands for an ExtractElementInst, see if we can fold the result.
3681 /// If not, this returns null.
3682 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3683                                          unsigned) {
3684   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3685     if (auto *CIdx = dyn_cast<Constant>(Idx))
3686       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3687
3688     // The index is not relevant if our vector is a splat.
3689     if (auto *Splat = CVec->getSplatValue())
3690       return Splat;
3691
3692     if (isa<UndefValue>(Vec))
3693       return UndefValue::get(Vec->getType()->getVectorElementType());
3694   }
3695
3696   // If extracting a specified index from the vector, see if we can recursively
3697   // find a previously computed scalar that was inserted into the vector.
3698   if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3699     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3700       return Elt;
3701
3702   return nullptr;
3703 }
3704
3705 Value *llvm::SimplifyExtractElementInst(
3706     Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3707     const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3708   return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3709                                       RecursionLimit);
3710 }
3711
3712 /// See if we can fold the given phi. If not, returns null.
3713 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3714   // If all of the PHI's incoming values are the same then replace the PHI node
3715   // with the common value.
3716   Value *CommonValue = nullptr;
3717   bool HasUndefInput = false;
3718   for (Value *Incoming : PN->incoming_values()) {
3719     // If the incoming value is the phi node itself, it can safely be skipped.
3720     if (Incoming == PN) continue;
3721     if (isa<UndefValue>(Incoming)) {
3722       // Remember that we saw an undef value, but otherwise ignore them.
3723       HasUndefInput = true;
3724       continue;
3725     }
3726     if (CommonValue && Incoming != CommonValue)
3727       return nullptr;  // Not the same, bail out.
3728     CommonValue = Incoming;
3729   }
3730
3731   // If CommonValue is null then all of the incoming values were either undef or
3732   // equal to the phi node itself.
3733   if (!CommonValue)
3734     return UndefValue::get(PN->getType());
3735
3736   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3737   // instruction, we cannot return X as the result of the PHI node unless it
3738   // dominates the PHI block.
3739   if (HasUndefInput)
3740     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3741
3742   return CommonValue;
3743 }
3744
3745 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3746   if (Constant *C = dyn_cast<Constant>(Op))
3747     return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
3748
3749   return nullptr;
3750 }
3751
3752 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
3753                                const TargetLibraryInfo *TLI,
3754                                const DominatorTree *DT, AssumptionCache *AC,
3755                                const Instruction *CxtI) {
3756   return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3757                              RecursionLimit);
3758 }
3759
3760 //=== Helper functions for higher up the class hierarchy.
3761
3762 /// Given operands for a BinaryOperator, see if we can fold the result.
3763 /// If not, this returns null.
3764 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3765                             const Query &Q, unsigned MaxRecurse) {
3766   switch (Opcode) {
3767   case Instruction::Add:
3768     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3769                            Q, MaxRecurse);
3770   case Instruction::FAdd:
3771     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3772
3773   case Instruction::Sub:
3774     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3775                            Q, MaxRecurse);
3776   case Instruction::FSub:
3777     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3778
3779   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3780   case Instruction::FMul:
3781     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3782   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3783   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3784   case Instruction::FDiv:
3785       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3786   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3787   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3788   case Instruction::FRem:
3789       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3790   case Instruction::Shl:
3791     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3792                            Q, MaxRecurse);
3793   case Instruction::LShr:
3794     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3795   case Instruction::AShr:
3796     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3797   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3798   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3799   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3800   default:
3801     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3802       if (Constant *CRHS = dyn_cast<Constant>(RHS))
3803         return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3804
3805     // If the operation is associative, try some generic simplifications.
3806     if (Instruction::isAssociative(Opcode))
3807       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3808         return V;
3809
3810     // If the operation is with the result of a select instruction check whether
3811     // operating on either branch of the select always yields the same value.
3812     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3813       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3814         return V;
3815
3816     // If the operation is with the result of a phi instruction, check whether
3817     // operating on all incoming values of the phi always yields the same value.
3818     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3819       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3820         return V;
3821
3822     return nullptr;
3823   }
3824 }
3825
3826 /// Given operands for a BinaryOperator, see if we can fold the result.
3827 /// If not, this returns null.
3828 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3829 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3830 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3831                               const FastMathFlags &FMF, const Query &Q,
3832                               unsigned MaxRecurse) {
3833   switch (Opcode) {
3834   case Instruction::FAdd:
3835     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3836   case Instruction::FSub:
3837     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3838   case Instruction::FMul:
3839     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3840   default:
3841     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3842   }
3843 }
3844
3845 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3846                            const DataLayout &DL, const TargetLibraryInfo *TLI,
3847                            const DominatorTree *DT, AssumptionCache *AC,
3848                            const Instruction *CxtI) {
3849   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3850                          RecursionLimit);
3851 }
3852
3853 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3854                              const FastMathFlags &FMF, const DataLayout &DL,
3855                              const TargetLibraryInfo *TLI,
3856                              const DominatorTree *DT, AssumptionCache *AC,
3857                              const Instruction *CxtI) {
3858   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3859                            RecursionLimit);
3860 }
3861
3862 /// Given operands for a CmpInst, see if we can fold the result.
3863 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3864                               const Query &Q, unsigned MaxRecurse) {
3865   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3866     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3867   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3868 }
3869
3870 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3871                              const DataLayout &DL, const TargetLibraryInfo *TLI,
3872                              const DominatorTree *DT, AssumptionCache *AC,
3873                              const Instruction *CxtI) {
3874   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3875                            RecursionLimit);
3876 }
3877
3878 static bool IsIdempotent(Intrinsic::ID ID) {
3879   switch (ID) {
3880   default: return false;
3881
3882   // Unary idempotent: f(f(x)) = f(x)
3883   case Intrinsic::fabs:
3884   case Intrinsic::floor:
3885   case Intrinsic::ceil:
3886   case Intrinsic::trunc:
3887   case Intrinsic::rint:
3888   case Intrinsic::nearbyint:
3889   case Intrinsic::round:
3890     return true;
3891   }
3892 }
3893
3894 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3895                                    const DataLayout &DL) {
3896   GlobalValue *PtrSym;
3897   APInt PtrOffset;
3898   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3899     return nullptr;
3900
3901   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3902   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3903   Type *Int32PtrTy = Int32Ty->getPointerTo();
3904   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3905
3906   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3907   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3908     return nullptr;
3909
3910   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3911   if (OffsetInt % 4 != 0)
3912     return nullptr;
3913
3914   Constant *C = ConstantExpr::getGetElementPtr(
3915       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3916       ConstantInt::get(Int64Ty, OffsetInt / 4));
3917   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3918   if (!Loaded)
3919     return nullptr;
3920
3921   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3922   if (!LoadedCE)
3923     return nullptr;
3924
3925   if (LoadedCE->getOpcode() == Instruction::Trunc) {
3926     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3927     if (!LoadedCE)
3928       return nullptr;
3929   }
3930
3931   if (LoadedCE->getOpcode() != Instruction::Sub)
3932     return nullptr;
3933
3934   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3935   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3936     return nullptr;
3937   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3938
3939   Constant *LoadedRHS = LoadedCE->getOperand(1);
3940   GlobalValue *LoadedRHSSym;
3941   APInt LoadedRHSOffset;
3942   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3943                                   DL) ||
3944       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3945     return nullptr;
3946
3947   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3948 }
3949
3950 static bool maskIsAllZeroOrUndef(Value *Mask) {
3951   auto *ConstMask = dyn_cast<Constant>(Mask);
3952   if (!ConstMask)
3953     return false;
3954   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
3955     return true;
3956   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
3957        ++I) {
3958     if (auto *MaskElt = ConstMask->getAggregateElement(I))
3959       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
3960         continue;
3961     return false;
3962   }
3963   return true;
3964 }
3965
3966 template <typename IterTy>
3967 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
3968                                 const Query &Q, unsigned MaxRecurse) {
3969   Intrinsic::ID IID = F->getIntrinsicID();
3970   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3971   Type *ReturnType = F->getReturnType();
3972
3973   // Binary Ops
3974   if (NumOperands == 2) {
3975     Value *LHS = *ArgBegin;
3976     Value *RHS = *(ArgBegin + 1);
3977     if (IID == Intrinsic::usub_with_overflow ||
3978         IID == Intrinsic::ssub_with_overflow) {
3979       // X - X -> { 0, false }
3980       if (LHS == RHS)
3981         return Constant::getNullValue(ReturnType);
3982
3983       // X - undef -> undef
3984       // undef - X -> undef
3985       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3986         return UndefValue::get(ReturnType);
3987     }
3988
3989     if (IID == Intrinsic::uadd_with_overflow ||
3990         IID == Intrinsic::sadd_with_overflow) {
3991       // X + undef -> undef
3992       if (isa<UndefValue>(RHS))
3993         return UndefValue::get(ReturnType);
3994     }
3995
3996     if (IID == Intrinsic::umul_with_overflow ||
3997         IID == Intrinsic::smul_with_overflow) {
3998       // X * 0 -> { 0, false }
3999       if (match(RHS, m_Zero()))
4000         return Constant::getNullValue(ReturnType);
4001
4002       // X * undef -> { 0, false }
4003       if (match(RHS, m_Undef()))
4004         return Constant::getNullValue(ReturnType);
4005     }
4006
4007     if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4008         isa<Constant>(RHS))
4009       return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4010                                   Q.DL);
4011   }
4012
4013   // Simplify calls to llvm.masked.load.*
4014   if (IID == Intrinsic::masked_load) {
4015     Value *MaskArg = ArgBegin[2];
4016     Value *PassthruArg = ArgBegin[3];
4017     // If the mask is all zeros or undef, the "passthru" argument is the result.
4018     if (maskIsAllZeroOrUndef(MaskArg))
4019       return PassthruArg;
4020   }
4021
4022   // Perform idempotent optimizations
4023   if (!IsIdempotent(IID))
4024     return nullptr;
4025
4026   // Unary Ops
4027   if (NumOperands == 1)
4028     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4029       if (II->getIntrinsicID() == IID)
4030         return II;
4031
4032   return nullptr;
4033 }
4034
4035 template <typename IterTy>
4036 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
4037                            const Query &Q, unsigned MaxRecurse) {
4038   Type *Ty = V->getType();
4039   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4040     Ty = PTy->getElementType();
4041   FunctionType *FTy = cast<FunctionType>(Ty);
4042
4043   // call undef -> undef
4044   // call null -> undef
4045   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4046     return UndefValue::get(FTy->getReturnType());
4047
4048   Function *F = dyn_cast<Function>(V);
4049   if (!F)
4050     return nullptr;
4051
4052   if (F->isIntrinsic())
4053     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
4054       return Ret;
4055
4056   if (!canConstantFoldCallTo(F))
4057     return nullptr;
4058
4059   SmallVector<Constant *, 4> ConstantArgs;
4060   ConstantArgs.reserve(ArgEnd - ArgBegin);
4061   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4062     Constant *C = dyn_cast<Constant>(*I);
4063     if (!C)
4064       return nullptr;
4065     ConstantArgs.push_back(C);
4066   }
4067
4068   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
4069 }
4070
4071 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
4072                           User::op_iterator ArgEnd, const DataLayout &DL,
4073                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
4074                           AssumptionCache *AC, const Instruction *CxtI) {
4075   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
4076                         RecursionLimit);
4077 }
4078
4079 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
4080                           const DataLayout &DL, const TargetLibraryInfo *TLI,
4081                           const DominatorTree *DT, AssumptionCache *AC,
4082                           const Instruction *CxtI) {
4083   return ::SimplifyCall(V, Args.begin(), Args.end(),
4084                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4085 }
4086
4087 /// See if we can compute a simplified version of this instruction.
4088 /// If not, this returns null.
4089 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
4090                                  const TargetLibraryInfo *TLI,
4091                                  const DominatorTree *DT, AssumptionCache *AC) {
4092   Value *Result;
4093
4094   switch (I->getOpcode()) {
4095   default:
4096     Result = ConstantFoldInstruction(I, DL, TLI);
4097     break;
4098   case Instruction::FAdd:
4099     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4100                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4101     break;
4102   case Instruction::Add:
4103     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4104                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4105                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4106                              TLI, DT, AC, I);
4107     break;
4108   case Instruction::FSub:
4109     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4110                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4111     break;
4112   case Instruction::Sub:
4113     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4114                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4115                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4116                              TLI, DT, AC, I);
4117     break;
4118   case Instruction::FMul:
4119     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4120                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4121     break;
4122   case Instruction::Mul:
4123     Result =
4124         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4125     break;
4126   case Instruction::SDiv:
4127     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4128                               AC, I);
4129     break;
4130   case Instruction::UDiv:
4131     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4132                               AC, I);
4133     break;
4134   case Instruction::FDiv:
4135     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4136                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4137     break;
4138   case Instruction::SRem:
4139     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4140                               AC, I);
4141     break;
4142   case Instruction::URem:
4143     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4144                               AC, I);
4145     break;
4146   case Instruction::FRem:
4147     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4148                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4149     break;
4150   case Instruction::Shl:
4151     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4152                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4153                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4154                              TLI, DT, AC, I);
4155     break;
4156   case Instruction::LShr:
4157     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4158                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4159                               AC, I);
4160     break;
4161   case Instruction::AShr:
4162     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4163                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4164                               AC, I);
4165     break;
4166   case Instruction::And:
4167     Result =
4168         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4169     break;
4170   case Instruction::Or:
4171     Result =
4172         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4173     break;
4174   case Instruction::Xor:
4175     Result =
4176         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4177     break;
4178   case Instruction::ICmp:
4179     Result =
4180         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4181                          I->getOperand(1), DL, TLI, DT, AC, I);
4182     break;
4183   case Instruction::FCmp:
4184     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4185                               I->getOperand(0), I->getOperand(1),
4186                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4187     break;
4188   case Instruction::Select:
4189     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4190                                 I->getOperand(2), DL, TLI, DT, AC, I);
4191     break;
4192   case Instruction::GetElementPtr: {
4193     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4194     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4195                              Ops, DL, TLI, DT, AC, I);
4196     break;
4197   }
4198   case Instruction::InsertValue: {
4199     InsertValueInst *IV = cast<InsertValueInst>(I);
4200     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4201                                      IV->getInsertedValueOperand(),
4202                                      IV->getIndices(), DL, TLI, DT, AC, I);
4203     break;
4204   }
4205   case Instruction::ExtractValue: {
4206     auto *EVI = cast<ExtractValueInst>(I);
4207     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4208                                       EVI->getIndices(), DL, TLI, DT, AC, I);
4209     break;
4210   }
4211   case Instruction::ExtractElement: {
4212     auto *EEI = cast<ExtractElementInst>(I);
4213     Result = SimplifyExtractElementInst(
4214         EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4215     break;
4216   }
4217   case Instruction::PHI:
4218     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4219     break;
4220   case Instruction::Call: {
4221     CallSite CS(cast<CallInst>(I));
4222     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4223                           TLI, DT, AC, I);
4224     break;
4225   }
4226   case Instruction::Trunc:
4227     Result =
4228         SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
4229     break;
4230   }
4231
4232   // In general, it is possible for computeKnownBits to determine all bits in a
4233   // value even when the operands are not all constants.
4234   if (!Result && I->getType()->isIntegerTy()) {
4235     unsigned BitWidth = I->getType()->getScalarSizeInBits();
4236     APInt KnownZero(BitWidth, 0);
4237     APInt KnownOne(BitWidth, 0);
4238     computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4239     if ((KnownZero | KnownOne).isAllOnesValue())
4240       Result = ConstantInt::get(I->getContext(), KnownOne);
4241   }
4242
4243   /// If called on unreachable code, the above logic may report that the
4244   /// instruction simplified to itself.  Make life easier for users by
4245   /// detecting that case here, returning a safe value instead.
4246   return Result == I ? UndefValue::get(I->getType()) : Result;
4247 }
4248
4249 /// \brief Implementation of recursive simplification through an instruction's
4250 /// uses.
4251 ///
4252 /// This is the common implementation of the recursive simplification routines.
4253 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4254 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4255 /// instructions to process and attempt to simplify it using
4256 /// InstructionSimplify.
4257 ///
4258 /// This routine returns 'true' only when *it* simplifies something. The passed
4259 /// in simplified value does not count toward this.
4260 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4261                                               const TargetLibraryInfo *TLI,
4262                                               const DominatorTree *DT,
4263                                               AssumptionCache *AC) {
4264   bool Simplified = false;
4265   SmallSetVector<Instruction *, 8> Worklist;
4266   const DataLayout &DL = I->getModule()->getDataLayout();
4267
4268   // If we have an explicit value to collapse to, do that round of the
4269   // simplification loop by hand initially.
4270   if (SimpleV) {
4271     for (User *U : I->users())
4272       if (U != I)
4273         Worklist.insert(cast<Instruction>(U));
4274
4275     // Replace the instruction with its simplified value.
4276     I->replaceAllUsesWith(SimpleV);
4277
4278     // Gracefully handle edge cases where the instruction is not wired into any
4279     // parent block.
4280     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4281         !I->mayHaveSideEffects())
4282       I->eraseFromParent();
4283   } else {
4284     Worklist.insert(I);
4285   }
4286
4287   // Note that we must test the size on each iteration, the worklist can grow.
4288   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4289     I = Worklist[Idx];
4290
4291     // See if this instruction simplifies.
4292     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4293     if (!SimpleV)
4294       continue;
4295
4296     Simplified = true;
4297
4298     // Stash away all the uses of the old instruction so we can check them for
4299     // recursive simplifications after a RAUW. This is cheaper than checking all
4300     // uses of To on the recursive step in most cases.
4301     for (User *U : I->users())
4302       Worklist.insert(cast<Instruction>(U));
4303
4304     // Replace the instruction with its simplified value.
4305     I->replaceAllUsesWith(SimpleV);
4306
4307     // Gracefully handle edge cases where the instruction is not wired into any
4308     // parent block.
4309     if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4310         !I->mayHaveSideEffects())
4311       I->eraseFromParent();
4312   }
4313   return Simplified;
4314 }
4315
4316 bool llvm::recursivelySimplifyInstruction(Instruction *I,
4317                                           const TargetLibraryInfo *TLI,
4318                                           const DominatorTree *DT,
4319                                           AssumptionCache *AC) {
4320   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4321 }
4322
4323 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4324                                          const TargetLibraryInfo *TLI,
4325                                          const DominatorTree *DT,
4326                                          AssumptionCache *AC) {
4327   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4328   assert(SimpleV && "Must provide a simplified value.");
4329   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
4330 }