]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Analysis/InstructionSimplify.cpp
Merge ^/vendor/clang/dist up to its last change, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Analysis / InstructionSimplify.cpp
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions.  This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/CmpInstAnalysis.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/LoopAnalysisManager.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/IR/ConstantRange.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/KnownBits.h"
42 #include <algorithm>
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
45
46 #define DEBUG_TYPE "instsimplify"
47
48 enum { RecursionLimit = 3 };
49
50 STATISTIC(NumExpand,  "Number of expansions");
51 STATISTIC(NumReassoc, "Number of reassociations");
52
53 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
54 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
55 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
56                              const SimplifyQuery &, unsigned);
57 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
58                             unsigned);
59 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
60                             const SimplifyQuery &, unsigned);
61 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
62                               unsigned);
63 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
64                                const SimplifyQuery &Q, unsigned MaxRecurse);
65 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
66 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
67 static Value *SimplifyCastInst(unsigned, Value *, Type *,
68                                const SimplifyQuery &, unsigned);
69 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
70                               unsigned);
71
72 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
73                                      Value *FalseVal) {
74   BinaryOperator::BinaryOps BinOpCode;
75   if (auto *BO = dyn_cast<BinaryOperator>(Cond))
76     BinOpCode = BO->getOpcode();
77   else
78     return nullptr;
79
80   CmpInst::Predicate ExpectedPred, Pred1, Pred2;
81   if (BinOpCode == BinaryOperator::Or) {
82     ExpectedPred = ICmpInst::ICMP_NE;
83   } else if (BinOpCode == BinaryOperator::And) {
84     ExpectedPred = ICmpInst::ICMP_EQ;
85   } else
86     return nullptr;
87
88   // %A = icmp eq %TV, %FV
89   // %B = icmp eq %X, %Y (and one of these is a select operand)
90   // %C = and %A, %B
91   // %D = select %C, %TV, %FV
92   // -->
93   // %FV
94
95   // %A = icmp ne %TV, %FV
96   // %B = icmp ne %X, %Y (and one of these is a select operand)
97   // %C = or %A, %B
98   // %D = select %C, %TV, %FV
99   // -->
100   // %TV
101   Value *X, *Y;
102   if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
103                                       m_Specific(FalseVal)),
104                              m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
105       Pred1 != Pred2 || Pred1 != ExpectedPred)
106     return nullptr;
107
108   if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
109     return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
110
111   return nullptr;
112 }
113
114 /// For a boolean type or a vector of boolean type, return false or a vector
115 /// with every element false.
116 static Constant *getFalse(Type *Ty) {
117   return ConstantInt::getFalse(Ty);
118 }
119
120 /// For a boolean type or a vector of boolean type, return true or a vector
121 /// with every element true.
122 static Constant *getTrue(Type *Ty) {
123   return ConstantInt::getTrue(Ty);
124 }
125
126 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
127 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
128                           Value *RHS) {
129   CmpInst *Cmp = dyn_cast<CmpInst>(V);
130   if (!Cmp)
131     return false;
132   CmpInst::Predicate CPred = Cmp->getPredicate();
133   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
134   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
135     return true;
136   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
137     CRHS == LHS;
138 }
139
140 /// Does the given value dominate the specified phi node?
141 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
142   Instruction *I = dyn_cast<Instruction>(V);
143   if (!I)
144     // Arguments and constants dominate all instructions.
145     return true;
146
147   // If we are processing instructions (and/or basic blocks) that have not been
148   // fully added to a function, the parent nodes may still be null. Simply
149   // return the conservative answer in these cases.
150   if (!I->getParent() || !P->getParent() || !I->getFunction())
151     return false;
152
153   // If we have a DominatorTree then do a precise test.
154   if (DT)
155     return DT->dominates(I, P);
156
157   // Otherwise, if the instruction is in the entry block and is not an invoke,
158   // then it obviously dominates all phi nodes.
159   if (I->getParent() == &I->getFunction()->getEntryBlock() &&
160       !isa<InvokeInst>(I))
161     return true;
162
163   return false;
164 }
165
166 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
167 /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
168 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
169 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
170 /// Returns the simplified value, or null if no simplification was performed.
171 static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
172                           Instruction::BinaryOps OpcodeToExpand,
173                           const SimplifyQuery &Q, unsigned MaxRecurse) {
174   // Recursion is always used, so bail out at once if we already hit the limit.
175   if (!MaxRecurse--)
176     return nullptr;
177
178   // Check whether the expression has the form "(A op' B) op C".
179   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
180     if (Op0->getOpcode() == OpcodeToExpand) {
181       // It does!  Try turning it into "(A op C) op' (B op C)".
182       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
183       // Do "A op C" and "B op C" both simplify?
184       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
185         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
186           // They do! Return "L op' R" if it simplifies or is already available.
187           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
188           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
189                                      && L == B && R == A)) {
190             ++NumExpand;
191             return LHS;
192           }
193           // Otherwise return "L op' R" if it simplifies.
194           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
195             ++NumExpand;
196             return V;
197           }
198         }
199     }
200
201   // Check whether the expression has the form "A op (B op' C)".
202   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
203     if (Op1->getOpcode() == OpcodeToExpand) {
204       // It does!  Try turning it into "(A op B) op' (A op C)".
205       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
206       // Do "A op B" and "A op C" both simplify?
207       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
208         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
209           // They do! Return "L op' R" if it simplifies or is already available.
210           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
211           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
212                                      && L == C && R == B)) {
213             ++NumExpand;
214             return RHS;
215           }
216           // Otherwise return "L op' R" if it simplifies.
217           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
218             ++NumExpand;
219             return V;
220           }
221         }
222     }
223
224   return nullptr;
225 }
226
227 /// Generic simplifications for associative binary operations.
228 /// Returns the simpler value, or null if none was found.
229 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
230                                        Value *LHS, Value *RHS,
231                                        const SimplifyQuery &Q,
232                                        unsigned MaxRecurse) {
233   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
234
235   // Recursion is always used, so bail out at once if we already hit the limit.
236   if (!MaxRecurse--)
237     return nullptr;
238
239   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
240   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
241
242   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
243   if (Op0 && Op0->getOpcode() == Opcode) {
244     Value *A = Op0->getOperand(0);
245     Value *B = Op0->getOperand(1);
246     Value *C = RHS;
247
248     // Does "B op C" simplify?
249     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
250       // It does!  Return "A op V" if it simplifies or is already available.
251       // If V equals B then "A op V" is just the LHS.
252       if (V == B) return LHS;
253       // Otherwise return "A op V" if it simplifies.
254       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
255         ++NumReassoc;
256         return W;
257       }
258     }
259   }
260
261   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
262   if (Op1 && Op1->getOpcode() == Opcode) {
263     Value *A = LHS;
264     Value *B = Op1->getOperand(0);
265     Value *C = Op1->getOperand(1);
266
267     // Does "A op B" simplify?
268     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
269       // It does!  Return "V op C" if it simplifies or is already available.
270       // If V equals B then "V op C" is just the RHS.
271       if (V == B) return RHS;
272       // Otherwise return "V op C" if it simplifies.
273       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
274         ++NumReassoc;
275         return W;
276       }
277     }
278   }
279
280   // The remaining transforms require commutativity as well as associativity.
281   if (!Instruction::isCommutative(Opcode))
282     return nullptr;
283
284   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
285   if (Op0 && Op0->getOpcode() == Opcode) {
286     Value *A = Op0->getOperand(0);
287     Value *B = Op0->getOperand(1);
288     Value *C = RHS;
289
290     // Does "C op A" simplify?
291     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
292       // It does!  Return "V op B" if it simplifies or is already available.
293       // If V equals A then "V op B" is just the LHS.
294       if (V == A) return LHS;
295       // Otherwise return "V op B" if it simplifies.
296       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
297         ++NumReassoc;
298         return W;
299       }
300     }
301   }
302
303   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
304   if (Op1 && Op1->getOpcode() == Opcode) {
305     Value *A = LHS;
306     Value *B = Op1->getOperand(0);
307     Value *C = Op1->getOperand(1);
308
309     // Does "C op A" simplify?
310     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
311       // It does!  Return "B op V" if it simplifies or is already available.
312       // If V equals C then "B op V" is just the RHS.
313       if (V == C) return RHS;
314       // Otherwise return "B op V" if it simplifies.
315       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
316         ++NumReassoc;
317         return W;
318       }
319     }
320   }
321
322   return nullptr;
323 }
324
325 /// In the case of a binary operation with a select instruction as an operand,
326 /// try to simplify the binop by seeing whether evaluating it on both branches
327 /// of the select results in the same value. Returns the common value if so,
328 /// otherwise returns null.
329 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
330                                     Value *RHS, const SimplifyQuery &Q,
331                                     unsigned MaxRecurse) {
332   // Recursion is always used, so bail out at once if we already hit the limit.
333   if (!MaxRecurse--)
334     return nullptr;
335
336   SelectInst *SI;
337   if (isa<SelectInst>(LHS)) {
338     SI = cast<SelectInst>(LHS);
339   } else {
340     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
341     SI = cast<SelectInst>(RHS);
342   }
343
344   // Evaluate the BinOp on the true and false branches of the select.
345   Value *TV;
346   Value *FV;
347   if (SI == LHS) {
348     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
349     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
350   } else {
351     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
352     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
353   }
354
355   // If they simplified to the same value, then return the common value.
356   // If they both failed to simplify then return null.
357   if (TV == FV)
358     return TV;
359
360   // If one branch simplified to undef, return the other one.
361   if (TV && isa<UndefValue>(TV))
362     return FV;
363   if (FV && isa<UndefValue>(FV))
364     return TV;
365
366   // If applying the operation did not change the true and false select values,
367   // then the result of the binop is the select itself.
368   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
369     return SI;
370
371   // If one branch simplified and the other did not, and the simplified
372   // value is equal to the unsimplified one, return the simplified value.
373   // For example, select (cond, X, X & Z) & Z -> X & Z.
374   if ((FV && !TV) || (TV && !FV)) {
375     // Check that the simplified value has the form "X op Y" where "op" is the
376     // same as the original operation.
377     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
378     if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
379       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
380       // We already know that "op" is the same as for the simplified value.  See
381       // if the operands match too.  If so, return the simplified value.
382       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
383       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
384       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
385       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
386           Simplified->getOperand(1) == UnsimplifiedRHS)
387         return Simplified;
388       if (Simplified->isCommutative() &&
389           Simplified->getOperand(1) == UnsimplifiedLHS &&
390           Simplified->getOperand(0) == UnsimplifiedRHS)
391         return Simplified;
392     }
393   }
394
395   return nullptr;
396 }
397
398 /// In the case of a comparison with a select instruction, try to simplify the
399 /// comparison by seeing whether both branches of the select result in the same
400 /// value. Returns the common value if so, otherwise returns null.
401 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
402                                   Value *RHS, const SimplifyQuery &Q,
403                                   unsigned MaxRecurse) {
404   // Recursion is always used, so bail out at once if we already hit the limit.
405   if (!MaxRecurse--)
406     return nullptr;
407
408   // Make sure the select is on the LHS.
409   if (!isa<SelectInst>(LHS)) {
410     std::swap(LHS, RHS);
411     Pred = CmpInst::getSwappedPredicate(Pred);
412   }
413   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
414   SelectInst *SI = cast<SelectInst>(LHS);
415   Value *Cond = SI->getCondition();
416   Value *TV = SI->getTrueValue();
417   Value *FV = SI->getFalseValue();
418
419   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
420   // Does "cmp TV, RHS" simplify?
421   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
422   if (TCmp == Cond) {
423     // It not only simplified, it simplified to the select condition.  Replace
424     // it with 'true'.
425     TCmp = getTrue(Cond->getType());
426   } else if (!TCmp) {
427     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
428     // condition then we can replace it with 'true'.  Otherwise give up.
429     if (!isSameCompare(Cond, Pred, TV, RHS))
430       return nullptr;
431     TCmp = getTrue(Cond->getType());
432   }
433
434   // Does "cmp FV, RHS" simplify?
435   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
436   if (FCmp == Cond) {
437     // It not only simplified, it simplified to the select condition.  Replace
438     // it with 'false'.
439     FCmp = getFalse(Cond->getType());
440   } else if (!FCmp) {
441     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
442     // condition then we can replace it with 'false'.  Otherwise give up.
443     if (!isSameCompare(Cond, Pred, FV, RHS))
444       return nullptr;
445     FCmp = getFalse(Cond->getType());
446   }
447
448   // If both sides simplified to the same value, then use it as the result of
449   // the original comparison.
450   if (TCmp == FCmp)
451     return TCmp;
452
453   // The remaining cases only make sense if the select condition has the same
454   // type as the result of the comparison, so bail out if this is not so.
455   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
456     return nullptr;
457   // If the false value simplified to false, then the result of the compare
458   // is equal to "Cond && TCmp".  This also catches the case when the false
459   // value simplified to false and the true value to true, returning "Cond".
460   if (match(FCmp, m_Zero()))
461     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
462       return V;
463   // If the true value simplified to true, then the result of the compare
464   // is equal to "Cond || FCmp".
465   if (match(TCmp, m_One()))
466     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
467       return V;
468   // Finally, if the false value simplified to true and the true value to
469   // false, then the result of the compare is equal to "!Cond".
470   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
471     if (Value *V =
472         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
473                         Q, MaxRecurse))
474       return V;
475
476   return nullptr;
477 }
478
479 /// In the case of a binary operation with an operand that is a PHI instruction,
480 /// try to simplify the binop by seeing whether evaluating it on the incoming
481 /// phi values yields the same result for every value. If so returns the common
482 /// value, otherwise returns null.
483 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
484                                  Value *RHS, const SimplifyQuery &Q,
485                                  unsigned MaxRecurse) {
486   // Recursion is always used, so bail out at once if we already hit the limit.
487   if (!MaxRecurse--)
488     return nullptr;
489
490   PHINode *PI;
491   if (isa<PHINode>(LHS)) {
492     PI = cast<PHINode>(LHS);
493     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
494     if (!valueDominatesPHI(RHS, PI, Q.DT))
495       return nullptr;
496   } else {
497     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
498     PI = cast<PHINode>(RHS);
499     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
500     if (!valueDominatesPHI(LHS, PI, Q.DT))
501       return nullptr;
502   }
503
504   // Evaluate the BinOp on the incoming phi values.
505   Value *CommonValue = nullptr;
506   for (Value *Incoming : PI->incoming_values()) {
507     // If the incoming value is the phi node itself, it can safely be skipped.
508     if (Incoming == PI) continue;
509     Value *V = PI == LHS ?
510       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
511       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
512     // If the operation failed to simplify, or simplified to a different value
513     // to previously, then give up.
514     if (!V || (CommonValue && V != CommonValue))
515       return nullptr;
516     CommonValue = V;
517   }
518
519   return CommonValue;
520 }
521
522 /// In the case of a comparison with a PHI instruction, try to simplify the
523 /// comparison by seeing whether comparing with all of the incoming phi values
524 /// yields the same result every time. If so returns the common result,
525 /// otherwise returns null.
526 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
527                                const SimplifyQuery &Q, unsigned MaxRecurse) {
528   // Recursion is always used, so bail out at once if we already hit the limit.
529   if (!MaxRecurse--)
530     return nullptr;
531
532   // Make sure the phi is on the LHS.
533   if (!isa<PHINode>(LHS)) {
534     std::swap(LHS, RHS);
535     Pred = CmpInst::getSwappedPredicate(Pred);
536   }
537   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
538   PHINode *PI = cast<PHINode>(LHS);
539
540   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
541   if (!valueDominatesPHI(RHS, PI, Q.DT))
542     return nullptr;
543
544   // Evaluate the BinOp on the incoming phi values.
545   Value *CommonValue = nullptr;
546   for (Value *Incoming : PI->incoming_values()) {
547     // If the incoming value is the phi node itself, it can safely be skipped.
548     if (Incoming == PI) continue;
549     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
550     // If the operation failed to simplify, or simplified to a different value
551     // to previously, then give up.
552     if (!V || (CommonValue && V != CommonValue))
553       return nullptr;
554     CommonValue = V;
555   }
556
557   return CommonValue;
558 }
559
560 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
561                                        Value *&Op0, Value *&Op1,
562                                        const SimplifyQuery &Q) {
563   if (auto *CLHS = dyn_cast<Constant>(Op0)) {
564     if (auto *CRHS = dyn_cast<Constant>(Op1))
565       return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
566
567     // Canonicalize the constant to the RHS if this is a commutative operation.
568     if (Instruction::isCommutative(Opcode))
569       std::swap(Op0, Op1);
570   }
571   return nullptr;
572 }
573
574 /// Given operands for an Add, see if we can fold the result.
575 /// If not, this returns null.
576 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
577                               const SimplifyQuery &Q, unsigned MaxRecurse) {
578   if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
579     return C;
580
581   // X + undef -> undef
582   if (match(Op1, m_Undef()))
583     return Op1;
584
585   // X + 0 -> X
586   if (match(Op1, m_Zero()))
587     return Op0;
588
589   // If two operands are negative, return 0.
590   if (isKnownNegation(Op0, Op1))
591     return Constant::getNullValue(Op0->getType());
592
593   // X + (Y - X) -> Y
594   // (Y - X) + X -> Y
595   // Eg: X + -X -> 0
596   Value *Y = nullptr;
597   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
598       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
599     return Y;
600
601   // X + ~X -> -1   since   ~X = -X-1
602   Type *Ty = Op0->getType();
603   if (match(Op0, m_Not(m_Specific(Op1))) ||
604       match(Op1, m_Not(m_Specific(Op0))))
605     return Constant::getAllOnesValue(Ty);
606
607   // add nsw/nuw (xor Y, signmask), signmask --> Y
608   // The no-wrapping add guarantees that the top bit will be set by the add.
609   // Therefore, the xor must be clearing the already set sign bit of Y.
610   if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
611       match(Op0, m_Xor(m_Value(Y), m_SignMask())))
612     return Y;
613
614   // add nuw %x, -1  ->  -1, because %x can only be 0.
615   if (IsNUW && match(Op1, m_AllOnes()))
616     return Op1; // Which is -1.
617
618   /// i1 add -> xor.
619   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
620     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
621       return V;
622
623   // Try some generic simplifications for associative operations.
624   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
625                                           MaxRecurse))
626     return V;
627
628   // Threading Add over selects and phi nodes is pointless, so don't bother.
629   // Threading over the select in "A + select(cond, B, C)" means evaluating
630   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
631   // only if B and C are equal.  If B and C are equal then (since we assume
632   // that operands have already been simplified) "select(cond, B, C)" should
633   // have been simplified to the common value of B and C already.  Analysing
634   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
635   // for threading over phi nodes.
636
637   return nullptr;
638 }
639
640 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
641                              const SimplifyQuery &Query) {
642   return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
643 }
644
645 /// Compute the base pointer and cumulative constant offsets for V.
646 ///
647 /// This strips all constant offsets off of V, leaving it the base pointer, and
648 /// accumulates the total constant offset applied in the returned constant. It
649 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
650 /// no constant offsets applied.
651 ///
652 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
653 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
654 /// folding.
655 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
656                                                 bool AllowNonInbounds = false) {
657   assert(V->getType()->isPtrOrPtrVectorTy());
658
659   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
660   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
661
662   V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
663   // As that strip may trace through `addrspacecast`, need to sext or trunc
664   // the offset calculated.
665   IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
666   Offset = Offset.sextOrTrunc(IntPtrTy->getIntegerBitWidth());
667
668   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
669   if (V->getType()->isVectorTy())
670     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
671                                     OffsetIntPtr);
672   return OffsetIntPtr;
673 }
674
675 /// Compute the constant difference between two pointer values.
676 /// If the difference is not a constant, returns zero.
677 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
678                                           Value *RHS) {
679   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
680   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
681
682   // If LHS and RHS are not related via constant offsets to the same base
683   // value, there is nothing we can do here.
684   if (LHS != RHS)
685     return nullptr;
686
687   // Otherwise, the difference of LHS - RHS can be computed as:
688   //    LHS - RHS
689   //  = (LHSOffset + Base) - (RHSOffset + Base)
690   //  = LHSOffset - RHSOffset
691   return ConstantExpr::getSub(LHSOffset, RHSOffset);
692 }
693
694 /// Given operands for a Sub, see if we can fold the result.
695 /// If not, this returns null.
696 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
697                               const SimplifyQuery &Q, unsigned MaxRecurse) {
698   if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
699     return C;
700
701   // X - undef -> undef
702   // undef - X -> undef
703   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
704     return UndefValue::get(Op0->getType());
705
706   // X - 0 -> X
707   if (match(Op1, m_Zero()))
708     return Op0;
709
710   // X - X -> 0
711   if (Op0 == Op1)
712     return Constant::getNullValue(Op0->getType());
713
714   // Is this a negation?
715   if (match(Op0, m_Zero())) {
716     // 0 - X -> 0 if the sub is NUW.
717     if (isNUW)
718       return Constant::getNullValue(Op0->getType());
719
720     KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
721     if (Known.Zero.isMaxSignedValue()) {
722       // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
723       // Op1 must be 0 because negating the minimum signed value is undefined.
724       if (isNSW)
725         return Constant::getNullValue(Op0->getType());
726
727       // 0 - X -> X if X is 0 or the minimum signed value.
728       return Op1;
729     }
730   }
731
732   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
733   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
734   Value *X = nullptr, *Y = nullptr, *Z = Op1;
735   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
736     // See if "V === Y - Z" simplifies.
737     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
738       // It does!  Now see if "X + V" simplifies.
739       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
740         // It does, we successfully reassociated!
741         ++NumReassoc;
742         return W;
743       }
744     // See if "V === X - Z" simplifies.
745     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
746       // It does!  Now see if "Y + V" simplifies.
747       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
748         // It does, we successfully reassociated!
749         ++NumReassoc;
750         return W;
751       }
752   }
753
754   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
755   // For example, X - (X + 1) -> -1
756   X = Op0;
757   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
758     // See if "V === X - Y" simplifies.
759     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
760       // It does!  Now see if "V - Z" simplifies.
761       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
762         // It does, we successfully reassociated!
763         ++NumReassoc;
764         return W;
765       }
766     // See if "V === X - Z" simplifies.
767     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
768       // It does!  Now see if "V - Y" simplifies.
769       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
770         // It does, we successfully reassociated!
771         ++NumReassoc;
772         return W;
773       }
774   }
775
776   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
777   // For example, X - (X - Y) -> Y.
778   Z = Op0;
779   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
780     // See if "V === Z - X" simplifies.
781     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
782       // It does!  Now see if "V + Y" simplifies.
783       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
784         // It does, we successfully reassociated!
785         ++NumReassoc;
786         return W;
787       }
788
789   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
790   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
791       match(Op1, m_Trunc(m_Value(Y))))
792     if (X->getType() == Y->getType())
793       // See if "V === X - Y" simplifies.
794       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
795         // It does!  Now see if "trunc V" simplifies.
796         if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
797                                         Q, MaxRecurse - 1))
798           // It does, return the simplified "trunc V".
799           return W;
800
801   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
802   if (match(Op0, m_PtrToInt(m_Value(X))) &&
803       match(Op1, m_PtrToInt(m_Value(Y))))
804     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
805       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
806
807   // i1 sub -> xor.
808   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
809     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
810       return V;
811
812   // Threading Sub over selects and phi nodes is pointless, so don't bother.
813   // Threading over the select in "A - select(cond, B, C)" means evaluating
814   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
815   // only if B and C are equal.  If B and C are equal then (since we assume
816   // that operands have already been simplified) "select(cond, B, C)" should
817   // have been simplified to the common value of B and C already.  Analysing
818   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
819   // for threading over phi nodes.
820
821   return nullptr;
822 }
823
824 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
825                              const SimplifyQuery &Q) {
826   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
827 }
828
829 /// Given operands for a Mul, see if we can fold the result.
830 /// If not, this returns null.
831 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
832                               unsigned MaxRecurse) {
833   if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
834     return C;
835
836   // X * undef -> 0
837   // X * 0 -> 0
838   if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
839     return Constant::getNullValue(Op0->getType());
840
841   // X * 1 -> X
842   if (match(Op1, m_One()))
843     return Op0;
844
845   // (X / Y) * Y -> X if the division is exact.
846   Value *X = nullptr;
847   if (Q.IIQ.UseInstrInfo &&
848       (match(Op0,
849              m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) ||     // (X / Y) * Y
850        match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
851     return X;
852
853   // i1 mul -> and.
854   if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
855     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
856       return V;
857
858   // Try some generic simplifications for associative operations.
859   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
860                                           MaxRecurse))
861     return V;
862
863   // Mul distributes over Add. Try some generic simplifications based on this.
864   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
865                              Q, MaxRecurse))
866     return V;
867
868   // If the operation is with the result of a select instruction, check whether
869   // operating on either branch of the select always yields the same value.
870   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
871     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
872                                          MaxRecurse))
873       return V;
874
875   // If the operation is with the result of a phi instruction, check whether
876   // operating on all incoming values of the phi always yields the same value.
877   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
878     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
879                                       MaxRecurse))
880       return V;
881
882   return nullptr;
883 }
884
885 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
886   return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
887 }
888
889 /// Check for common or similar folds of integer division or integer remainder.
890 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
891 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
892   Type *Ty = Op0->getType();
893
894   // X / undef -> undef
895   // X % undef -> undef
896   if (match(Op1, m_Undef()))
897     return Op1;
898
899   // X / 0 -> undef
900   // X % 0 -> undef
901   // We don't need to preserve faults!
902   if (match(Op1, m_Zero()))
903     return UndefValue::get(Ty);
904
905   // If any element of a constant divisor vector is zero or undef, the whole op
906   // is undef.
907   auto *Op1C = dyn_cast<Constant>(Op1);
908   if (Op1C && Ty->isVectorTy()) {
909     unsigned NumElts = Ty->getVectorNumElements();
910     for (unsigned i = 0; i != NumElts; ++i) {
911       Constant *Elt = Op1C->getAggregateElement(i);
912       if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
913         return UndefValue::get(Ty);
914     }
915   }
916
917   // undef / X -> 0
918   // undef % X -> 0
919   if (match(Op0, m_Undef()))
920     return Constant::getNullValue(Ty);
921
922   // 0 / X -> 0
923   // 0 % X -> 0
924   if (match(Op0, m_Zero()))
925     return Constant::getNullValue(Op0->getType());
926
927   // X / X -> 1
928   // X % X -> 0
929   if (Op0 == Op1)
930     return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
931
932   // X / 1 -> X
933   // X % 1 -> 0
934   // If this is a boolean op (single-bit element type), we can't have
935   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
936   // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
937   Value *X;
938   if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
939       (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
940     return IsDiv ? Op0 : Constant::getNullValue(Ty);
941
942   return nullptr;
943 }
944
945 /// Given a predicate and two operands, return true if the comparison is true.
946 /// This is a helper for div/rem simplification where we return some other value
947 /// when we can prove a relationship between the operands.
948 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
949                        const SimplifyQuery &Q, unsigned MaxRecurse) {
950   Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
951   Constant *C = dyn_cast_or_null<Constant>(V);
952   return (C && C->isAllOnesValue());
953 }
954
955 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
956 /// to simplify X % Y to X.
957 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
958                       unsigned MaxRecurse, bool IsSigned) {
959   // Recursion is always used, so bail out at once if we already hit the limit.
960   if (!MaxRecurse--)
961     return false;
962
963   if (IsSigned) {
964     // |X| / |Y| --> 0
965     //
966     // We require that 1 operand is a simple constant. That could be extended to
967     // 2 variables if we computed the sign bit for each.
968     //
969     // Make sure that a constant is not the minimum signed value because taking
970     // the abs() of that is undefined.
971     Type *Ty = X->getType();
972     const APInt *C;
973     if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
974       // Is the variable divisor magnitude always greater than the constant
975       // dividend magnitude?
976       // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
977       Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
978       Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
979       if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
980           isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
981         return true;
982     }
983     if (match(Y, m_APInt(C))) {
984       // Special-case: we can't take the abs() of a minimum signed value. If
985       // that's the divisor, then all we have to do is prove that the dividend
986       // is also not the minimum signed value.
987       if (C->isMinSignedValue())
988         return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
989
990       // Is the variable dividend magnitude always less than the constant
991       // divisor magnitude?
992       // |X| < |C| --> X > -abs(C) and X < abs(C)
993       Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
994       Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
995       if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
996           isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
997         return true;
998     }
999     return false;
1000   }
1001
1002   // IsSigned == false.
1003   // Is the dividend unsigned less than the divisor?
1004   return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1005 }
1006
1007 /// These are simplifications common to SDiv and UDiv.
1008 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1009                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1010   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1011     return C;
1012
1013   if (Value *V = simplifyDivRem(Op0, Op1, true))
1014     return V;
1015
1016   bool IsSigned = Opcode == Instruction::SDiv;
1017
1018   // (X * Y) / Y -> X if the multiplication does not overflow.
1019   Value *X;
1020   if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1021     auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1022     // If the Mul does not overflow, then we are good to go.
1023     if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1024         (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
1025       return X;
1026     // If X has the form X = A / Y, then X * Y cannot overflow.
1027     if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1028         (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1029       return X;
1030   }
1031
1032   // (X rem Y) / Y -> 0
1033   if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1034       (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1035     return Constant::getNullValue(Op0->getType());
1036
1037   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1038   ConstantInt *C1, *C2;
1039   if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1040       match(Op1, m_ConstantInt(C2))) {
1041     bool Overflow;
1042     (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1043     if (Overflow)
1044       return Constant::getNullValue(Op0->getType());
1045   }
1046
1047   // If the operation is with the result of a select instruction, check whether
1048   // operating on either branch of the select always yields the same value.
1049   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1050     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1051       return V;
1052
1053   // If the operation is with the result of a phi instruction, check whether
1054   // operating on all incoming values of the phi always yields the same value.
1055   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1056     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1057       return V;
1058
1059   if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1060     return Constant::getNullValue(Op0->getType());
1061
1062   return nullptr;
1063 }
1064
1065 /// These are simplifications common to SRem and URem.
1066 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1067                           const SimplifyQuery &Q, unsigned MaxRecurse) {
1068   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1069     return C;
1070
1071   if (Value *V = simplifyDivRem(Op0, Op1, false))
1072     return V;
1073
1074   // (X % Y) % Y -> X % Y
1075   if ((Opcode == Instruction::SRem &&
1076        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1077       (Opcode == Instruction::URem &&
1078        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1079     return Op0;
1080
1081   // (X << Y) % X -> 0
1082   if (Q.IIQ.UseInstrInfo &&
1083       ((Opcode == Instruction::SRem &&
1084         match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1085        (Opcode == Instruction::URem &&
1086         match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1087     return Constant::getNullValue(Op0->getType());
1088
1089   // If the operation is with the result of a select instruction, check whether
1090   // operating on either branch of the select always yields the same value.
1091   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1092     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1093       return V;
1094
1095   // If the operation is with the result of a phi instruction, check whether
1096   // operating on all incoming values of the phi always yields the same value.
1097   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1098     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1099       return V;
1100
1101   // If X / Y == 0, then X % Y == X.
1102   if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1103     return Op0;
1104
1105   return nullptr;
1106 }
1107
1108 /// Given operands for an SDiv, see if we can fold the result.
1109 /// If not, this returns null.
1110 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1111                                unsigned MaxRecurse) {
1112   // If two operands are negated and no signed overflow, return -1.
1113   if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1114     return Constant::getAllOnesValue(Op0->getType());
1115
1116   return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1117 }
1118
1119 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1120   return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1121 }
1122
1123 /// Given operands for a UDiv, see if we can fold the result.
1124 /// If not, this returns null.
1125 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1126                                unsigned MaxRecurse) {
1127   return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1128 }
1129
1130 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1131   return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1132 }
1133
1134 /// Given operands for an SRem, see if we can fold the result.
1135 /// If not, this returns null.
1136 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1137                                unsigned MaxRecurse) {
1138   // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1139   // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1140   Value *X;
1141   if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1142     return ConstantInt::getNullValue(Op0->getType());
1143
1144   // If the two operands are negated, return 0.
1145   if (isKnownNegation(Op0, Op1))
1146     return ConstantInt::getNullValue(Op0->getType());
1147
1148   return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1149 }
1150
1151 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1152   return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1153 }
1154
1155 /// Given operands for a URem, see if we can fold the result.
1156 /// If not, this returns null.
1157 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1158                                unsigned MaxRecurse) {
1159   return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1160 }
1161
1162 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1163   return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1164 }
1165
1166 /// Returns true if a shift by \c Amount always yields undef.
1167 static bool isUndefShift(Value *Amount) {
1168   Constant *C = dyn_cast<Constant>(Amount);
1169   if (!C)
1170     return false;
1171
1172   // X shift by undef -> undef because it may shift by the bitwidth.
1173   if (isa<UndefValue>(C))
1174     return true;
1175
1176   // Shifting by the bitwidth or more is undefined.
1177   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1178     if (CI->getValue().getLimitedValue() >=
1179         CI->getType()->getScalarSizeInBits())
1180       return true;
1181
1182   // If all lanes of a vector shift are undefined the whole shift is.
1183   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1184     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1185       if (!isUndefShift(C->getAggregateElement(I)))
1186         return false;
1187     return true;
1188   }
1189
1190   return false;
1191 }
1192
1193 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1194 /// If not, this returns null.
1195 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1196                             Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
1197   if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1198     return C;
1199
1200   // 0 shift by X -> 0
1201   if (match(Op0, m_Zero()))
1202     return Constant::getNullValue(Op0->getType());
1203
1204   // X shift by 0 -> X
1205   // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1206   // would be poison.
1207   Value *X;
1208   if (match(Op1, m_Zero()) ||
1209       (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1210     return Op0;
1211
1212   // Fold undefined shifts.
1213   if (isUndefShift(Op1))
1214     return UndefValue::get(Op0->getType());
1215
1216   // If the operation is with the result of a select instruction, check whether
1217   // operating on either branch of the select always yields the same value.
1218   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1219     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1220       return V;
1221
1222   // If the operation is with the result of a phi instruction, check whether
1223   // operating on all incoming values of the phi always yields the same value.
1224   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1225     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1226       return V;
1227
1228   // If any bits in the shift amount make that value greater than or equal to
1229   // the number of bits in the type, the shift is undefined.
1230   KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1231   if (Known.One.getLimitedValue() >= Known.getBitWidth())
1232     return UndefValue::get(Op0->getType());
1233
1234   // If all valid bits in the shift amount are known zero, the first operand is
1235   // unchanged.
1236   unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
1237   if (Known.countMinTrailingZeros() >= NumValidShiftBits)
1238     return Op0;
1239
1240   return nullptr;
1241 }
1242
1243 /// Given operands for an Shl, LShr or AShr, see if we can
1244 /// fold the result.  If not, this returns null.
1245 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1246                                  Value *Op1, bool isExact, const SimplifyQuery &Q,
1247                                  unsigned MaxRecurse) {
1248   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1249     return V;
1250
1251   // X >> X -> 0
1252   if (Op0 == Op1)
1253     return Constant::getNullValue(Op0->getType());
1254
1255   // undef >> X -> 0
1256   // undef >> X -> undef (if it's exact)
1257   if (match(Op0, m_Undef()))
1258     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1259
1260   // The low bit cannot be shifted out of an exact shift if it is set.
1261   if (isExact) {
1262     KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1263     if (Op0Known.One[0])
1264       return Op0;
1265   }
1266
1267   return nullptr;
1268 }
1269
1270 /// Given operands for an Shl, see if we can fold the result.
1271 /// If not, this returns null.
1272 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1273                               const SimplifyQuery &Q, unsigned MaxRecurse) {
1274   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1275     return V;
1276
1277   // undef << X -> 0
1278   // undef << X -> undef if (if it's NSW/NUW)
1279   if (match(Op0, m_Undef()))
1280     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1281
1282   // (X >> A) << A -> X
1283   Value *X;
1284   if (Q.IIQ.UseInstrInfo &&
1285       match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1286     return X;
1287
1288   // shl nuw i8 C, %x  ->  C  iff C has sign bit set.
1289   if (isNUW && match(Op0, m_Negative()))
1290     return Op0;
1291   // NOTE: could use computeKnownBits() / LazyValueInfo,
1292   // but the cost-benefit analysis suggests it isn't worth it.
1293
1294   return nullptr;
1295 }
1296
1297 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1298                              const SimplifyQuery &Q) {
1299   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1300 }
1301
1302 /// Given operands for an LShr, see if we can fold the result.
1303 /// If not, this returns null.
1304 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1305                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1306   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1307                                     MaxRecurse))
1308       return V;
1309
1310   // (X << A) >> A -> X
1311   Value *X;
1312   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1313     return X;
1314
1315   // ((X << A) | Y) >> A -> X  if effective width of Y is not larger than A.
1316   // We can return X as we do in the above case since OR alters no bits in X.
1317   // SimplifyDemandedBits in InstCombine can do more general optimization for
1318   // bit manipulation. This pattern aims to provide opportunities for other
1319   // optimizers by supporting a simple but common case in InstSimplify.
1320   Value *Y;
1321   const APInt *ShRAmt, *ShLAmt;
1322   if (match(Op1, m_APInt(ShRAmt)) &&
1323       match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1324       *ShRAmt == *ShLAmt) {
1325     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1326     const unsigned Width = Op0->getType()->getScalarSizeInBits();
1327     const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1328     if (ShRAmt->uge(EffWidthY))
1329       return X;
1330   }
1331
1332   return nullptr;
1333 }
1334
1335 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1336                               const SimplifyQuery &Q) {
1337   return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1338 }
1339
1340 /// Given operands for an AShr, see if we can fold the result.
1341 /// If not, this returns null.
1342 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1343                                const SimplifyQuery &Q, unsigned MaxRecurse) {
1344   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1345                                     MaxRecurse))
1346     return V;
1347
1348   // all ones >>a X -> -1
1349   // Do not return Op0 because it may contain undef elements if it's a vector.
1350   if (match(Op0, m_AllOnes()))
1351     return Constant::getAllOnesValue(Op0->getType());
1352
1353   // (X << A) >> A -> X
1354   Value *X;
1355   if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1356     return X;
1357
1358   // Arithmetic shifting an all-sign-bit value is a no-op.
1359   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1360   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1361     return Op0;
1362
1363   return nullptr;
1364 }
1365
1366 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1367                               const SimplifyQuery &Q) {
1368   return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1369 }
1370
1371 /// Commuted variants are assumed to be handled by calling this function again
1372 /// with the parameters swapped.
1373 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1374                                          ICmpInst *UnsignedICmp, bool IsAnd,
1375                                          const SimplifyQuery &Q) {
1376   Value *X, *Y;
1377
1378   ICmpInst::Predicate EqPred;
1379   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1380       !ICmpInst::isEquality(EqPred))
1381     return nullptr;
1382
1383   ICmpInst::Predicate UnsignedPred;
1384
1385   Value *A, *B;
1386   // Y = (A - B);
1387   if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1388     if (match(UnsignedICmp,
1389               m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1390         ICmpInst::isUnsigned(UnsignedPred)) {
1391       if (UnsignedICmp->getOperand(0) != A)
1392         UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1393
1394       // A >=/<= B || (A - B) != 0  <-->  true
1395       if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1396            UnsignedPred == ICmpInst::ICMP_ULE) &&
1397           EqPred == ICmpInst::ICMP_NE && !IsAnd)
1398         return ConstantInt::getTrue(UnsignedICmp->getType());
1399       // A </> B && (A - B) == 0  <-->  false
1400       if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1401            UnsignedPred == ICmpInst::ICMP_UGT) &&
1402           EqPred == ICmpInst::ICMP_EQ && IsAnd)
1403         return ConstantInt::getFalse(UnsignedICmp->getType());
1404
1405       // A </> B && (A - B) != 0  <-->  A </> B
1406       // A </> B || (A - B) != 0  <-->  (A - B) != 0
1407       if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1408                                           UnsignedPred == ICmpInst::ICMP_UGT))
1409         return IsAnd ? UnsignedICmp : ZeroICmp;
1410
1411       // A <=/>= B && (A - B) == 0  <-->  (A - B) == 0
1412       // A <=/>= B || (A - B) == 0  <-->  A <=/>= B
1413       if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1414                                           UnsignedPred == ICmpInst::ICMP_UGE))
1415         return IsAnd ? ZeroICmp : UnsignedICmp;
1416     }
1417
1418     // Given  Y = (A - B)
1419     //   Y >= A && Y != 0  --> Y >= A  iff B != 0
1420     //   Y <  A || Y == 0  --> Y <  A  iff B != 0
1421     if (match(UnsignedICmp,
1422               m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1423       if (UnsignedICmp->getOperand(0) != Y)
1424         UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1425
1426       if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1427           EqPred == ICmpInst::ICMP_NE &&
1428           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1429         return UnsignedICmp;
1430       if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1431           EqPred == ICmpInst::ICMP_EQ &&
1432           isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1433         return UnsignedICmp;
1434     }
1435   }
1436
1437   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1438       ICmpInst::isUnsigned(UnsignedPred))
1439     ;
1440   else if (match(UnsignedICmp,
1441                  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1442            ICmpInst::isUnsigned(UnsignedPred))
1443     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1444   else
1445     return nullptr;
1446
1447   // X < Y && Y != 0  -->  X < Y
1448   // X < Y || Y != 0  -->  Y != 0
1449   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1450     return IsAnd ? UnsignedICmp : ZeroICmp;
1451
1452   // X <= Y && Y != 0  -->  X <= Y  iff X != 0
1453   // X <= Y || Y != 0  -->  Y != 0  iff X != 0
1454   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1455       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1456     return IsAnd ? UnsignedICmp : ZeroICmp;
1457
1458   // X >= Y && Y == 0  -->  Y == 0
1459   // X >= Y || Y == 0  -->  X >= Y
1460   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1461     return IsAnd ? ZeroICmp : UnsignedICmp;
1462
1463   // X > Y && Y == 0  -->  Y == 0  iff X != 0
1464   // X > Y || Y == 0  -->  X > Y   iff X != 0
1465   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1466       isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1467     return IsAnd ? ZeroICmp : UnsignedICmp;
1468
1469   // X < Y && Y == 0  -->  false
1470   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1471       IsAnd)
1472     return getFalse(UnsignedICmp->getType());
1473
1474   // X >= Y || Y != 0  -->  true
1475   if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1476       !IsAnd)
1477     return getTrue(UnsignedICmp->getType());
1478
1479   return nullptr;
1480 }
1481
1482 /// Commuted variants are assumed to be handled by calling this function again
1483 /// with the parameters swapped.
1484 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1485   ICmpInst::Predicate Pred0, Pred1;
1486   Value *A ,*B;
1487   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1488       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1489     return nullptr;
1490
1491   // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1492   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1493   // can eliminate Op1 from this 'and'.
1494   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1495     return Op0;
1496
1497   // Check for any combination of predicates that are guaranteed to be disjoint.
1498   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1499       (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1500       (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1501       (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1502     return getFalse(Op0->getType());
1503
1504   return nullptr;
1505 }
1506
1507 /// Commuted variants are assumed to be handled by calling this function again
1508 /// with the parameters swapped.
1509 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1510   ICmpInst::Predicate Pred0, Pred1;
1511   Value *A ,*B;
1512   if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1513       !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1514     return nullptr;
1515
1516   // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1517   // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1518   // can eliminate Op0 from this 'or'.
1519   if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1520     return Op1;
1521
1522   // Check for any combination of predicates that cover the entire range of
1523   // possibilities.
1524   if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1525       (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1526       (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1527       (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1528     return getTrue(Op0->getType());
1529
1530   return nullptr;
1531 }
1532
1533 /// Test if a pair of compares with a shared operand and 2 constants has an
1534 /// empty set intersection, full set union, or if one compare is a superset of
1535 /// the other.
1536 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1537                                                 bool IsAnd) {
1538   // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1539   if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1540     return nullptr;
1541
1542   const APInt *C0, *C1;
1543   if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1544       !match(Cmp1->getOperand(1), m_APInt(C1)))
1545     return nullptr;
1546
1547   auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1548   auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1549
1550   // For and-of-compares, check if the intersection is empty:
1551   // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1552   if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1553     return getFalse(Cmp0->getType());
1554
1555   // For or-of-compares, check if the union is full:
1556   // (icmp X, C0) || (icmp X, C1) --> full set --> true
1557   if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1558     return getTrue(Cmp0->getType());
1559
1560   // Is one range a superset of the other?
1561   // If this is and-of-compares, take the smaller set:
1562   // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1563   // If this is or-of-compares, take the larger set:
1564   // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1565   if (Range0.contains(Range1))
1566     return IsAnd ? Cmp1 : Cmp0;
1567   if (Range1.contains(Range0))
1568     return IsAnd ? Cmp0 : Cmp1;
1569
1570   return nullptr;
1571 }
1572
1573 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1574                                            bool IsAnd) {
1575   ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1576   if (!match(Cmp0->getOperand(1), m_Zero()) ||
1577       !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1578     return nullptr;
1579
1580   if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1581     return nullptr;
1582
1583   // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1584   Value *X = Cmp0->getOperand(0);
1585   Value *Y = Cmp1->getOperand(0);
1586
1587   // If one of the compares is a masked version of a (not) null check, then
1588   // that compare implies the other, so we eliminate the other. Optionally, look
1589   // through a pointer-to-int cast to match a null check of a pointer type.
1590
1591   // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1592   // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1593   // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1594   // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1595   if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1596       match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1597     return Cmp1;
1598
1599   // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1600   // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1601   // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1602   // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1603   if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1604       match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1605     return Cmp0;
1606
1607   return nullptr;
1608 }
1609
1610 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1611                                         const InstrInfoQuery &IIQ) {
1612   // (icmp (add V, C0), C1) & (icmp V, C0)
1613   ICmpInst::Predicate Pred0, Pred1;
1614   const APInt *C0, *C1;
1615   Value *V;
1616   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1617     return nullptr;
1618
1619   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1620     return nullptr;
1621
1622   auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1623   if (AddInst->getOperand(1) != Op1->getOperand(1))
1624     return nullptr;
1625
1626   Type *ITy = Op0->getType();
1627   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1628   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1629
1630   const APInt Delta = *C1 - *C0;
1631   if (C0->isStrictlyPositive()) {
1632     if (Delta == 2) {
1633       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1634         return getFalse(ITy);
1635       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1636         return getFalse(ITy);
1637     }
1638     if (Delta == 1) {
1639       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1640         return getFalse(ITy);
1641       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1642         return getFalse(ITy);
1643     }
1644   }
1645   if (C0->getBoolValue() && isNUW) {
1646     if (Delta == 2)
1647       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1648         return getFalse(ITy);
1649     if (Delta == 1)
1650       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1651         return getFalse(ITy);
1652   }
1653
1654   return nullptr;
1655 }
1656
1657 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1658                                  const SimplifyQuery &Q) {
1659   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1660     return X;
1661   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1662     return X;
1663
1664   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1665     return X;
1666   if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1667     return X;
1668
1669   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1670     return X;
1671
1672   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1673     return X;
1674
1675   if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1676     return X;
1677   if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1678     return X;
1679
1680   return nullptr;
1681 }
1682
1683 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1684                                        const InstrInfoQuery &IIQ) {
1685   // (icmp (add V, C0), C1) | (icmp V, C0)
1686   ICmpInst::Predicate Pred0, Pred1;
1687   const APInt *C0, *C1;
1688   Value *V;
1689   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1690     return nullptr;
1691
1692   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1693     return nullptr;
1694
1695   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1696   if (AddInst->getOperand(1) != Op1->getOperand(1))
1697     return nullptr;
1698
1699   Type *ITy = Op0->getType();
1700   bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1701   bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1702
1703   const APInt Delta = *C1 - *C0;
1704   if (C0->isStrictlyPositive()) {
1705     if (Delta == 2) {
1706       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1707         return getTrue(ITy);
1708       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1709         return getTrue(ITy);
1710     }
1711     if (Delta == 1) {
1712       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1713         return getTrue(ITy);
1714       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1715         return getTrue(ITy);
1716     }
1717   }
1718   if (C0->getBoolValue() && isNUW) {
1719     if (Delta == 2)
1720       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1721         return getTrue(ITy);
1722     if (Delta == 1)
1723       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1724         return getTrue(ITy);
1725   }
1726
1727   return nullptr;
1728 }
1729
1730 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1731                                 const SimplifyQuery &Q) {
1732   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1733     return X;
1734   if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1735     return X;
1736
1737   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1738     return X;
1739   if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1740     return X;
1741
1742   if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1743     return X;
1744
1745   if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1746     return X;
1747
1748   if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1749     return X;
1750   if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1751     return X;
1752
1753   return nullptr;
1754 }
1755
1756 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1757                                    FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1758   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1759   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1760   if (LHS0->getType() != RHS0->getType())
1761     return nullptr;
1762
1763   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1764   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1765       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1766     // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1767     // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1768     // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1769     // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1770     // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1771     // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1772     // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1773     // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1774     if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1775         (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1776       return RHS;
1777
1778     // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1779     // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1780     // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1781     // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1782     // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1783     // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1784     // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1785     // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1786     if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1787         (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1788       return LHS;
1789   }
1790
1791   return nullptr;
1792 }
1793
1794 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
1795                                   Value *Op0, Value *Op1, bool IsAnd) {
1796   // Look through casts of the 'and' operands to find compares.
1797   auto *Cast0 = dyn_cast<CastInst>(Op0);
1798   auto *Cast1 = dyn_cast<CastInst>(Op1);
1799   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1800       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1801     Op0 = Cast0->getOperand(0);
1802     Op1 = Cast1->getOperand(0);
1803   }
1804
1805   Value *V = nullptr;
1806   auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1807   auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1808   if (ICmp0 && ICmp1)
1809     V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1810               : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1811
1812   auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1813   auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1814   if (FCmp0 && FCmp1)
1815     V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
1816
1817   if (!V)
1818     return nullptr;
1819   if (!Cast0)
1820     return V;
1821
1822   // If we looked through casts, we can only handle a constant simplification
1823   // because we are not allowed to create a cast instruction here.
1824   if (auto *C = dyn_cast<Constant>(V))
1825     return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1826
1827   return nullptr;
1828 }
1829
1830 /// Check that the Op1 is in expected form, i.e.:
1831 ///   %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1832 ///   %Op1 = extractvalue { i4, i1 } %Agg, 1
1833 static bool omitCheckForZeroBeforeMulWithOverflowInternal(Value *Op1,
1834                                                           Value *X) {
1835   auto *Extract = dyn_cast<ExtractValueInst>(Op1);
1836   // We should only be extracting the overflow bit.
1837   if (!Extract || !Extract->getIndices().equals(1))
1838     return false;
1839   Value *Agg = Extract->getAggregateOperand();
1840   // This should be a multiplication-with-overflow intrinsic.
1841   if (!match(Agg, m_CombineOr(m_Intrinsic<Intrinsic::umul_with_overflow>(),
1842                               m_Intrinsic<Intrinsic::smul_with_overflow>())))
1843     return false;
1844   // One of its multipliers should be the value we checked for zero before.
1845   if (!match(Agg, m_CombineOr(m_Argument<0>(m_Specific(X)),
1846                               m_Argument<1>(m_Specific(X)))))
1847     return false;
1848   return true;
1849 }
1850
1851 /// The @llvm.[us]mul.with.overflow intrinsic could have been folded from some
1852 /// other form of check, e.g. one that was using division; it may have been
1853 /// guarded against division-by-zero. We can drop that check now.
1854 /// Look for:
1855 ///   %Op0 = icmp ne i4 %X, 0
1856 ///   %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1857 ///   %Op1 = extractvalue { i4, i1 } %Agg, 1
1858 ///   %??? = and i1 %Op0, %Op1
1859 /// We can just return  %Op1
1860 static Value *omitCheckForZeroBeforeMulWithOverflow(Value *Op0, Value *Op1) {
1861   ICmpInst::Predicate Pred;
1862   Value *X;
1863   if (!match(Op0, m_ICmp(Pred, m_Value(X), m_Zero())) ||
1864       Pred != ICmpInst::Predicate::ICMP_NE)
1865     return nullptr;
1866   // Is Op1 in expected form?
1867   if (!omitCheckForZeroBeforeMulWithOverflowInternal(Op1, X))
1868     return nullptr;
1869   // Can omit 'and', and just return the overflow bit.
1870   return Op1;
1871 }
1872
1873 /// The @llvm.[us]mul.with.overflow intrinsic could have been folded from some
1874 /// other form of check, e.g. one that was using division; it may have been
1875 /// guarded against division-by-zero. We can drop that check now.
1876 /// Look for:
1877 ///   %Op0 = icmp eq i4 %X, 0
1878 ///   %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1879 ///   %Op1 = extractvalue { i4, i1 } %Agg, 1
1880 ///   %NotOp1 = xor i1 %Op1, true
1881 ///   %or = or i1 %Op0, %NotOp1
1882 /// We can just return  %NotOp1
1883 static Value *omitCheckForZeroBeforeInvertedMulWithOverflow(Value *Op0,
1884                                                             Value *NotOp1) {
1885   ICmpInst::Predicate Pred;
1886   Value *X;
1887   if (!match(Op0, m_ICmp(Pred, m_Value(X), m_Zero())) ||
1888       Pred != ICmpInst::Predicate::ICMP_EQ)
1889     return nullptr;
1890   // We expect the other hand of an 'or' to be a 'not'.
1891   Value *Op1;
1892   if (!match(NotOp1, m_Not(m_Value(Op1))))
1893     return nullptr;
1894   // Is Op1 in expected form?
1895   if (!omitCheckForZeroBeforeMulWithOverflowInternal(Op1, X))
1896     return nullptr;
1897   // Can omit 'and', and just return the inverted overflow bit.
1898   return NotOp1;
1899 }
1900
1901 /// Given operands for an And, see if we can fold the result.
1902 /// If not, this returns null.
1903 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1904                               unsigned MaxRecurse) {
1905   if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1906     return C;
1907
1908   // X & undef -> 0
1909   if (match(Op1, m_Undef()))
1910     return Constant::getNullValue(Op0->getType());
1911
1912   // X & X = X
1913   if (Op0 == Op1)
1914     return Op0;
1915
1916   // X & 0 = 0
1917   if (match(Op1, m_Zero()))
1918     return Constant::getNullValue(Op0->getType());
1919
1920   // X & -1 = X
1921   if (match(Op1, m_AllOnes()))
1922     return Op0;
1923
1924   // A & ~A  =  ~A & A  =  0
1925   if (match(Op0, m_Not(m_Specific(Op1))) ||
1926       match(Op1, m_Not(m_Specific(Op0))))
1927     return Constant::getNullValue(Op0->getType());
1928
1929   // (A | ?) & A = A
1930   if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1931     return Op1;
1932
1933   // A & (A | ?) = A
1934   if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
1935     return Op0;
1936
1937   // A mask that only clears known zeros of a shifted value is a no-op.
1938   Value *X;
1939   const APInt *Mask;
1940   const APInt *ShAmt;
1941   if (match(Op1, m_APInt(Mask))) {
1942     // If all bits in the inverted and shifted mask are clear:
1943     // and (shl X, ShAmt), Mask --> shl X, ShAmt
1944     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1945         (~(*Mask)).lshr(*ShAmt).isNullValue())
1946       return Op0;
1947
1948     // If all bits in the inverted and shifted mask are clear:
1949     // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1950     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1951         (~(*Mask)).shl(*ShAmt).isNullValue())
1952       return Op0;
1953   }
1954
1955   // If we have a multiplication overflow check that is being 'and'ed with a
1956   // check that one of the multipliers is not zero, we can omit the 'and', and
1957   // only keep the overflow check.
1958   if (Value *V = omitCheckForZeroBeforeMulWithOverflow(Op0, Op1))
1959     return V;
1960   if (Value *V = omitCheckForZeroBeforeMulWithOverflow(Op1, Op0))
1961     return V;
1962
1963   // A & (-A) = A if A is a power of two or zero.
1964   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1965       match(Op1, m_Neg(m_Specific(Op0)))) {
1966     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1967                                Q.DT))
1968       return Op0;
1969     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1970                                Q.DT))
1971       return Op1;
1972   }
1973
1974   // This is a similar pattern used for checking if a value is a power-of-2:
1975   // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
1976   // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
1977   if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
1978       isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1979     return Constant::getNullValue(Op1->getType());
1980   if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
1981       isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1982     return Constant::getNullValue(Op0->getType());
1983
1984   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
1985     return V;
1986
1987   // Try some generic simplifications for associative operations.
1988   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1989                                           MaxRecurse))
1990     return V;
1991
1992   // And distributes over Or.  Try some generic simplifications based on this.
1993   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1994                              Q, MaxRecurse))
1995     return V;
1996
1997   // And distributes over Xor.  Try some generic simplifications based on this.
1998   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1999                              Q, MaxRecurse))
2000     return V;
2001
2002   // If the operation is with the result of a select instruction, check whether
2003   // operating on either branch of the select always yields the same value.
2004   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
2005     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
2006                                          MaxRecurse))
2007       return V;
2008
2009   // If the operation is with the result of a phi instruction, check whether
2010   // operating on all incoming values of the phi always yields the same value.
2011   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2012     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
2013                                       MaxRecurse))
2014       return V;
2015
2016   // Assuming the effective width of Y is not larger than A, i.e. all bits
2017   // from X and Y are disjoint in (X << A) | Y,
2018   // if the mask of this AND op covers all bits of X or Y, while it covers
2019   // no bits from the other, we can bypass this AND op. E.g.,
2020   // ((X << A) | Y) & Mask -> Y,
2021   //     if Mask = ((1 << effective_width_of(Y)) - 1)
2022   // ((X << A) | Y) & Mask -> X << A,
2023   //     if Mask = ((1 << effective_width_of(X)) - 1) << A
2024   // SimplifyDemandedBits in InstCombine can optimize the general case.
2025   // This pattern aims to help other passes for a common case.
2026   Value *Y, *XShifted;
2027   if (match(Op1, m_APInt(Mask)) &&
2028       match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2029                                      m_Value(XShifted)),
2030                         m_Value(Y)))) {
2031     const unsigned Width = Op0->getType()->getScalarSizeInBits();
2032     const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2033     const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2034     const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
2035     if (EffWidthY <= ShftCnt) {
2036       const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
2037                                                 Q.DT);
2038       const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
2039       const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2040       const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2041       // If the mask is extracting all bits from X or Y as is, we can skip
2042       // this AND op.
2043       if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2044         return Y;
2045       if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2046         return XShifted;
2047     }
2048   }
2049
2050   return nullptr;
2051 }
2052
2053 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2054   return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
2055 }
2056
2057 /// Given operands for an Or, see if we can fold the result.
2058 /// If not, this returns null.
2059 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2060                              unsigned MaxRecurse) {
2061   if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2062     return C;
2063
2064   // X | undef -> -1
2065   // X | -1 = -1
2066   // Do not return Op1 because it may contain undef elements if it's a vector.
2067   if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
2068     return Constant::getAllOnesValue(Op0->getType());
2069
2070   // X | X = X
2071   // X | 0 = X
2072   if (Op0 == Op1 || match(Op1, m_Zero()))
2073     return Op0;
2074
2075   // A | ~A  =  ~A | A  =  -1
2076   if (match(Op0, m_Not(m_Specific(Op1))) ||
2077       match(Op1, m_Not(m_Specific(Op0))))
2078     return Constant::getAllOnesValue(Op0->getType());
2079
2080   // (A & ?) | A = A
2081   if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
2082     return Op1;
2083
2084   // A | (A & ?) = A
2085   if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
2086     return Op0;
2087
2088   // ~(A & ?) | A = -1
2089   if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
2090     return Constant::getAllOnesValue(Op1->getType());
2091
2092   // A | ~(A & ?) = -1
2093   if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
2094     return Constant::getAllOnesValue(Op0->getType());
2095
2096   Value *A, *B;
2097   // (A & ~B) | (A ^ B) -> (A ^ B)
2098   // (~B & A) | (A ^ B) -> (A ^ B)
2099   // (A & ~B) | (B ^ A) -> (B ^ A)
2100   // (~B & A) | (B ^ A) -> (B ^ A)
2101   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2102       (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
2103        match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
2104     return Op1;
2105
2106   // Commute the 'or' operands.
2107   // (A ^ B) | (A & ~B) -> (A ^ B)
2108   // (A ^ B) | (~B & A) -> (A ^ B)
2109   // (B ^ A) | (A & ~B) -> (B ^ A)
2110   // (B ^ A) | (~B & A) -> (B ^ A)
2111   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2112       (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
2113        match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
2114     return Op0;
2115
2116   // (A & B) | (~A ^ B) -> (~A ^ B)
2117   // (B & A) | (~A ^ B) -> (~A ^ B)
2118   // (A & B) | (B ^ ~A) -> (B ^ ~A)
2119   // (B & A) | (B ^ ~A) -> (B ^ ~A)
2120   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2121       (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
2122        match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
2123     return Op1;
2124
2125   // (~A ^ B) | (A & B) -> (~A ^ B)
2126   // (~A ^ B) | (B & A) -> (~A ^ B)
2127   // (B ^ ~A) | (A & B) -> (B ^ ~A)
2128   // (B ^ ~A) | (B & A) -> (B ^ ~A)
2129   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2130       (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
2131        match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
2132     return Op0;
2133
2134   if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2135     return V;
2136
2137   // If we have a multiplication overflow check that is being 'and'ed with a
2138   // check that one of the multipliers is not zero, we can omit the 'and', and
2139   // only keep the overflow check.
2140   if (Value *V = omitCheckForZeroBeforeInvertedMulWithOverflow(Op0, Op1))
2141     return V;
2142   if (Value *V = omitCheckForZeroBeforeInvertedMulWithOverflow(Op1, Op0))
2143     return V;
2144
2145   // Try some generic simplifications for associative operations.
2146   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2147                                           MaxRecurse))
2148     return V;
2149
2150   // Or distributes over And.  Try some generic simplifications based on this.
2151   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
2152                              MaxRecurse))
2153     return V;
2154
2155   // If the operation is with the result of a select instruction, check whether
2156   // operating on either branch of the select always yields the same value.
2157   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
2158     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2159                                          MaxRecurse))
2160       return V;
2161
2162   // (A & C1)|(B & C2)
2163   const APInt *C1, *C2;
2164   if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2165       match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2166     if (*C1 == ~*C2) {
2167       // (A & C1)|(B & C2)
2168       // If we have: ((V + N) & C1) | (V & C2)
2169       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2170       // replace with V+N.
2171       Value *N;
2172       if (C2->isMask() && // C2 == 0+1+
2173           match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2174         // Add commutes, try both ways.
2175         if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2176           return A;
2177       }
2178       // Or commutes, try both ways.
2179       if (C1->isMask() &&
2180           match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2181         // Add commutes, try both ways.
2182         if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2183           return B;
2184       }
2185     }
2186   }
2187
2188   // If the operation is with the result of a phi instruction, check whether
2189   // operating on all incoming values of the phi always yields the same value.
2190   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2191     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2192       return V;
2193
2194   return nullptr;
2195 }
2196
2197 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2198   return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2199 }
2200
2201 /// Given operands for a Xor, see if we can fold the result.
2202 /// If not, this returns null.
2203 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2204                               unsigned MaxRecurse) {
2205   if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2206     return C;
2207
2208   // A ^ undef -> undef
2209   if (match(Op1, m_Undef()))
2210     return Op1;
2211
2212   // A ^ 0 = A
2213   if (match(Op1, m_Zero()))
2214     return Op0;
2215
2216   // A ^ A = 0
2217   if (Op0 == Op1)
2218     return Constant::getNullValue(Op0->getType());
2219
2220   // A ^ ~A  =  ~A ^ A  =  -1
2221   if (match(Op0, m_Not(m_Specific(Op1))) ||
2222       match(Op1, m_Not(m_Specific(Op0))))
2223     return Constant::getAllOnesValue(Op0->getType());
2224
2225   // Try some generic simplifications for associative operations.
2226   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2227                                           MaxRecurse))
2228     return V;
2229
2230   // Threading Xor over selects and phi nodes is pointless, so don't bother.
2231   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2232   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2233   // only if B and C are equal.  If B and C are equal then (since we assume
2234   // that operands have already been simplified) "select(cond, B, C)" should
2235   // have been simplified to the common value of B and C already.  Analysing
2236   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
2237   // for threading over phi nodes.
2238
2239   return nullptr;
2240 }
2241
2242 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2243   return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2244 }
2245
2246
2247 static Type *GetCompareTy(Value *Op) {
2248   return CmpInst::makeCmpResultType(Op->getType());
2249 }
2250
2251 /// Rummage around inside V looking for something equivalent to the comparison
2252 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2253 /// Helper function for analyzing max/min idioms.
2254 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2255                                          Value *LHS, Value *RHS) {
2256   SelectInst *SI = dyn_cast<SelectInst>(V);
2257   if (!SI)
2258     return nullptr;
2259   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2260   if (!Cmp)
2261     return nullptr;
2262   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2263   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2264     return Cmp;
2265   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2266       LHS == CmpRHS && RHS == CmpLHS)
2267     return Cmp;
2268   return nullptr;
2269 }
2270
2271 // A significant optimization not implemented here is assuming that alloca
2272 // addresses are not equal to incoming argument values. They don't *alias*,
2273 // as we say, but that doesn't mean they aren't equal, so we take a
2274 // conservative approach.
2275 //
2276 // This is inspired in part by C++11 5.10p1:
2277 //   "Two pointers of the same type compare equal if and only if they are both
2278 //    null, both point to the same function, or both represent the same
2279 //    address."
2280 //
2281 // This is pretty permissive.
2282 //
2283 // It's also partly due to C11 6.5.9p6:
2284 //   "Two pointers compare equal if and only if both are null pointers, both are
2285 //    pointers to the same object (including a pointer to an object and a
2286 //    subobject at its beginning) or function, both are pointers to one past the
2287 //    last element of the same array object, or one is a pointer to one past the
2288 //    end of one array object and the other is a pointer to the start of a
2289 //    different array object that happens to immediately follow the first array
2290 //    object in the address space.)
2291 //
2292 // C11's version is more restrictive, however there's no reason why an argument
2293 // couldn't be a one-past-the-end value for a stack object in the caller and be
2294 // equal to the beginning of a stack object in the callee.
2295 //
2296 // If the C and C++ standards are ever made sufficiently restrictive in this
2297 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2298 // this optimization.
2299 static Constant *
2300 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2301                    const DominatorTree *DT, CmpInst::Predicate Pred,
2302                    AssumptionCache *AC, const Instruction *CxtI,
2303                    const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
2304   // First, skip past any trivial no-ops.
2305   LHS = LHS->stripPointerCasts();
2306   RHS = RHS->stripPointerCasts();
2307
2308   // A non-null pointer is not equal to a null pointer.
2309   if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2310                            IIQ.UseInstrInfo) &&
2311       isa<ConstantPointerNull>(RHS) &&
2312       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2313     return ConstantInt::get(GetCompareTy(LHS),
2314                             !CmpInst::isTrueWhenEqual(Pred));
2315
2316   // We can only fold certain predicates on pointer comparisons.
2317   switch (Pred) {
2318   default:
2319     return nullptr;
2320
2321     // Equality comaprisons are easy to fold.
2322   case CmpInst::ICMP_EQ:
2323   case CmpInst::ICMP_NE:
2324     break;
2325
2326     // We can only handle unsigned relational comparisons because 'inbounds' on
2327     // a GEP only protects against unsigned wrapping.
2328   case CmpInst::ICMP_UGT:
2329   case CmpInst::ICMP_UGE:
2330   case CmpInst::ICMP_ULT:
2331   case CmpInst::ICMP_ULE:
2332     // However, we have to switch them to their signed variants to handle
2333     // negative indices from the base pointer.
2334     Pred = ICmpInst::getSignedPredicate(Pred);
2335     break;
2336   }
2337
2338   // Strip off any constant offsets so that we can reason about them.
2339   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2340   // here and compare base addresses like AliasAnalysis does, however there are
2341   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2342   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2343   // doesn't need to guarantee pointer inequality when it says NoAlias.
2344   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2345   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2346
2347   // If LHS and RHS are related via constant offsets to the same base
2348   // value, we can replace it with an icmp which just compares the offsets.
2349   if (LHS == RHS)
2350     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2351
2352   // Various optimizations for (in)equality comparisons.
2353   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2354     // Different non-empty allocations that exist at the same time have
2355     // different addresses (if the program can tell). Global variables always
2356     // exist, so they always exist during the lifetime of each other and all
2357     // allocas. Two different allocas usually have different addresses...
2358     //
2359     // However, if there's an @llvm.stackrestore dynamically in between two
2360     // allocas, they may have the same address. It's tempting to reduce the
2361     // scope of the problem by only looking at *static* allocas here. That would
2362     // cover the majority of allocas while significantly reducing the likelihood
2363     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2364     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2365     // an entry block. Also, if we have a block that's not attached to a
2366     // function, we can't tell if it's "static" under the current definition.
2367     // Theoretically, this problem could be fixed by creating a new kind of
2368     // instruction kind specifically for static allocas. Such a new instruction
2369     // could be required to be at the top of the entry block, thus preventing it
2370     // from being subject to a @llvm.stackrestore. Instcombine could even
2371     // convert regular allocas into these special allocas. It'd be nifty.
2372     // However, until then, this problem remains open.
2373     //
2374     // So, we'll assume that two non-empty allocas have different addresses
2375     // for now.
2376     //
2377     // With all that, if the offsets are within the bounds of their allocations
2378     // (and not one-past-the-end! so we can't use inbounds!), and their
2379     // allocations aren't the same, the pointers are not equal.
2380     //
2381     // Note that it's not necessary to check for LHS being a global variable
2382     // address, due to canonicalization and constant folding.
2383     if (isa<AllocaInst>(LHS) &&
2384         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2385       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2386       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2387       uint64_t LHSSize, RHSSize;
2388       ObjectSizeOpts Opts;
2389       Opts.NullIsUnknownSize =
2390           NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
2391       if (LHSOffsetCI && RHSOffsetCI &&
2392           getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2393           getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2394         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2395         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2396         if (!LHSOffsetValue.isNegative() &&
2397             !RHSOffsetValue.isNegative() &&
2398             LHSOffsetValue.ult(LHSSize) &&
2399             RHSOffsetValue.ult(RHSSize)) {
2400           return ConstantInt::get(GetCompareTy(LHS),
2401                                   !CmpInst::isTrueWhenEqual(Pred));
2402         }
2403       }
2404
2405       // Repeat the above check but this time without depending on DataLayout
2406       // or being able to compute a precise size.
2407       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2408           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2409           LHSOffset->isNullValue() &&
2410           RHSOffset->isNullValue())
2411         return ConstantInt::get(GetCompareTy(LHS),
2412                                 !CmpInst::isTrueWhenEqual(Pred));
2413     }
2414
2415     // Even if an non-inbounds GEP occurs along the path we can still optimize
2416     // equality comparisons concerning the result. We avoid walking the whole
2417     // chain again by starting where the last calls to
2418     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2419     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2420     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2421     if (LHS == RHS)
2422       return ConstantExpr::getICmp(Pred,
2423                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2424                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2425
2426     // If one side of the equality comparison must come from a noalias call
2427     // (meaning a system memory allocation function), and the other side must
2428     // come from a pointer that cannot overlap with dynamically-allocated
2429     // memory within the lifetime of the current function (allocas, byval
2430     // arguments, globals), then determine the comparison result here.
2431     SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2432     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2433     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2434
2435     // Is the set of underlying objects all noalias calls?
2436     auto IsNAC = [](ArrayRef<const Value *> Objects) {
2437       return all_of(Objects, isNoAliasCall);
2438     };
2439
2440     // Is the set of underlying objects all things which must be disjoint from
2441     // noalias calls. For allocas, we consider only static ones (dynamic
2442     // allocas might be transformed into calls to malloc not simultaneously
2443     // live with the compared-to allocation). For globals, we exclude symbols
2444     // that might be resolve lazily to symbols in another dynamically-loaded
2445     // library (and, thus, could be malloc'ed by the implementation).
2446     auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2447       return all_of(Objects, [](const Value *V) {
2448         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2449           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2450         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2451           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2452                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2453                  !GV->isThreadLocal();
2454         if (const Argument *A = dyn_cast<Argument>(V))
2455           return A->hasByValAttr();
2456         return false;
2457       });
2458     };
2459
2460     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2461         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2462         return ConstantInt::get(GetCompareTy(LHS),
2463                                 !CmpInst::isTrueWhenEqual(Pred));
2464
2465     // Fold comparisons for non-escaping pointer even if the allocation call
2466     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2467     // dynamic allocation call could be either of the operands.
2468     Value *MI = nullptr;
2469     if (isAllocLikeFn(LHS, TLI) &&
2470         llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2471       MI = LHS;
2472     else if (isAllocLikeFn(RHS, TLI) &&
2473              llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2474       MI = RHS;
2475     // FIXME: We should also fold the compare when the pointer escapes, but the
2476     // compare dominates the pointer escape
2477     if (MI && !PointerMayBeCaptured(MI, true, true))
2478       return ConstantInt::get(GetCompareTy(LHS),
2479                               CmpInst::isFalseWhenEqual(Pred));
2480   }
2481
2482   // Otherwise, fail.
2483   return nullptr;
2484 }
2485
2486 /// Fold an icmp when its operands have i1 scalar type.
2487 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2488                                   Value *RHS, const SimplifyQuery &Q) {
2489   Type *ITy = GetCompareTy(LHS); // The return type.
2490   Type *OpTy = LHS->getType();   // The operand type.
2491   if (!OpTy->isIntOrIntVectorTy(1))
2492     return nullptr;
2493
2494   // A boolean compared to true/false can be simplified in 14 out of the 20
2495   // (10 predicates * 2 constants) possible combinations. Cases not handled here
2496   // require a 'not' of the LHS, so those must be transformed in InstCombine.
2497   if (match(RHS, m_Zero())) {
2498     switch (Pred) {
2499     case CmpInst::ICMP_NE:  // X !=  0 -> X
2500     case CmpInst::ICMP_UGT: // X >u  0 -> X
2501     case CmpInst::ICMP_SLT: // X <s  0 -> X
2502       return LHS;
2503
2504     case CmpInst::ICMP_ULT: // X <u  0 -> false
2505     case CmpInst::ICMP_SGT: // X >s  0 -> false
2506       return getFalse(ITy);
2507
2508     case CmpInst::ICMP_UGE: // X >=u 0 -> true
2509     case CmpInst::ICMP_SLE: // X <=s 0 -> true
2510       return getTrue(ITy);
2511
2512     default: break;
2513     }
2514   } else if (match(RHS, m_One())) {
2515     switch (Pred) {
2516     case CmpInst::ICMP_EQ:  // X ==   1 -> X
2517     case CmpInst::ICMP_UGE: // X >=u  1 -> X
2518     case CmpInst::ICMP_SLE: // X <=s -1 -> X
2519       return LHS;
2520
2521     case CmpInst::ICMP_UGT: // X >u   1 -> false
2522     case CmpInst::ICMP_SLT: // X <s  -1 -> false
2523       return getFalse(ITy);
2524
2525     case CmpInst::ICMP_ULE: // X <=u  1 -> true
2526     case CmpInst::ICMP_SGE: // X >=s -1 -> true
2527       return getTrue(ITy);
2528
2529     default: break;
2530     }
2531   }
2532
2533   switch (Pred) {
2534   default:
2535     break;
2536   case ICmpInst::ICMP_UGE:
2537     if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2538       return getTrue(ITy);
2539     break;
2540   case ICmpInst::ICMP_SGE:
2541     /// For signed comparison, the values for an i1 are 0 and -1
2542     /// respectively. This maps into a truth table of:
2543     /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2544     ///  0  |  0  |  1 (0 >= 0)   |  1
2545     ///  0  |  1  |  1 (0 >= -1)  |  1
2546     ///  1  |  0  |  0 (-1 >= 0)  |  0
2547     ///  1  |  1  |  1 (-1 >= -1) |  1
2548     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2549       return getTrue(ITy);
2550     break;
2551   case ICmpInst::ICMP_ULE:
2552     if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2553       return getTrue(ITy);
2554     break;
2555   }
2556
2557   return nullptr;
2558 }
2559
2560 /// Try hard to fold icmp with zero RHS because this is a common case.
2561 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2562                                    Value *RHS, const SimplifyQuery &Q) {
2563   if (!match(RHS, m_Zero()))
2564     return nullptr;
2565
2566   Type *ITy = GetCompareTy(LHS); // The return type.
2567   switch (Pred) {
2568   default:
2569     llvm_unreachable("Unknown ICmp predicate!");
2570   case ICmpInst::ICMP_ULT:
2571     return getFalse(ITy);
2572   case ICmpInst::ICMP_UGE:
2573     return getTrue(ITy);
2574   case ICmpInst::ICMP_EQ:
2575   case ICmpInst::ICMP_ULE:
2576     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2577       return getFalse(ITy);
2578     break;
2579   case ICmpInst::ICMP_NE:
2580   case ICmpInst::ICMP_UGT:
2581     if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2582       return getTrue(ITy);
2583     break;
2584   case ICmpInst::ICMP_SLT: {
2585     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2586     if (LHSKnown.isNegative())
2587       return getTrue(ITy);
2588     if (LHSKnown.isNonNegative())
2589       return getFalse(ITy);
2590     break;
2591   }
2592   case ICmpInst::ICMP_SLE: {
2593     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2594     if (LHSKnown.isNegative())
2595       return getTrue(ITy);
2596     if (LHSKnown.isNonNegative() &&
2597         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2598       return getFalse(ITy);
2599     break;
2600   }
2601   case ICmpInst::ICMP_SGE: {
2602     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2603     if (LHSKnown.isNegative())
2604       return getFalse(ITy);
2605     if (LHSKnown.isNonNegative())
2606       return getTrue(ITy);
2607     break;
2608   }
2609   case ICmpInst::ICMP_SGT: {
2610     KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2611     if (LHSKnown.isNegative())
2612       return getFalse(ITy);
2613     if (LHSKnown.isNonNegative() &&
2614         isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2615       return getTrue(ITy);
2616     break;
2617   }
2618   }
2619
2620   return nullptr;
2621 }
2622
2623 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2624                                        Value *RHS, const InstrInfoQuery &IIQ) {
2625   Type *ITy = GetCompareTy(RHS); // The return type.
2626
2627   Value *X;
2628   // Sign-bit checks can be optimized to true/false after unsigned
2629   // floating-point casts:
2630   // icmp slt (bitcast (uitofp X)),  0 --> false
2631   // icmp sgt (bitcast (uitofp X)), -1 --> true
2632   if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2633     if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2634       return ConstantInt::getFalse(ITy);
2635     if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2636       return ConstantInt::getTrue(ITy);
2637   }
2638
2639   const APInt *C;
2640   if (!match(RHS, m_APInt(C)))
2641     return nullptr;
2642
2643   // Rule out tautological comparisons (eg., ult 0 or uge 0).
2644   ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2645   if (RHS_CR.isEmptySet())
2646     return ConstantInt::getFalse(ITy);
2647   if (RHS_CR.isFullSet())
2648     return ConstantInt::getTrue(ITy);
2649
2650   ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo);
2651   if (!LHS_CR.isFullSet()) {
2652     if (RHS_CR.contains(LHS_CR))
2653       return ConstantInt::getTrue(ITy);
2654     if (RHS_CR.inverse().contains(LHS_CR))
2655       return ConstantInt::getFalse(ITy);
2656   }
2657
2658   return nullptr;
2659 }
2660
2661 /// TODO: A large part of this logic is duplicated in InstCombine's
2662 /// foldICmpBinOp(). We should be able to share that and avoid the code
2663 /// duplication.
2664 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2665                                     Value *RHS, const SimplifyQuery &Q,
2666                                     unsigned MaxRecurse) {
2667   Type *ITy = GetCompareTy(LHS); // The return type.
2668
2669   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2670   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2671   if (MaxRecurse && (LBO || RBO)) {
2672     // Analyze the case when either LHS or RHS is an add instruction.
2673     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2674     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2675     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2676     if (LBO && LBO->getOpcode() == Instruction::Add) {
2677       A = LBO->getOperand(0);
2678       B = LBO->getOperand(1);
2679       NoLHSWrapProblem =
2680           ICmpInst::isEquality(Pred) ||
2681           (CmpInst::isUnsigned(Pred) &&
2682            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2683           (CmpInst::isSigned(Pred) &&
2684            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2685     }
2686     if (RBO && RBO->getOpcode() == Instruction::Add) {
2687       C = RBO->getOperand(0);
2688       D = RBO->getOperand(1);
2689       NoRHSWrapProblem =
2690           ICmpInst::isEquality(Pred) ||
2691           (CmpInst::isUnsigned(Pred) &&
2692            Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2693           (CmpInst::isSigned(Pred) &&
2694            Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2695     }
2696
2697     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2698     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2699       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2700                                       Constant::getNullValue(RHS->getType()), Q,
2701                                       MaxRecurse - 1))
2702         return V;
2703
2704     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2705     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2706       if (Value *V =
2707               SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2708                                C == LHS ? D : C, Q, MaxRecurse - 1))
2709         return V;
2710
2711     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2712     if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2713         NoRHSWrapProblem) {
2714       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2715       Value *Y, *Z;
2716       if (A == C) {
2717         // C + B == C + D  ->  B == D
2718         Y = B;
2719         Z = D;
2720       } else if (A == D) {
2721         // D + B == C + D  ->  B == C
2722         Y = B;
2723         Z = C;
2724       } else if (B == C) {
2725         // A + C == C + D  ->  A == D
2726         Y = A;
2727         Z = D;
2728       } else {
2729         assert(B == D);
2730         // A + D == C + D  ->  A == C
2731         Y = A;
2732         Z = C;
2733       }
2734       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2735         return V;
2736     }
2737   }
2738
2739   {
2740     Value *Y = nullptr;
2741     // icmp pred (or X, Y), X
2742     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2743       if (Pred == ICmpInst::ICMP_ULT)
2744         return getFalse(ITy);
2745       if (Pred == ICmpInst::ICMP_UGE)
2746         return getTrue(ITy);
2747
2748       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2749         KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2750         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2751         if (RHSKnown.isNonNegative() && YKnown.isNegative())
2752           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2753         if (RHSKnown.isNegative() || YKnown.isNonNegative())
2754           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2755       }
2756     }
2757     // icmp pred X, (or X, Y)
2758     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2759       if (Pred == ICmpInst::ICMP_ULE)
2760         return getTrue(ITy);
2761       if (Pred == ICmpInst::ICMP_UGT)
2762         return getFalse(ITy);
2763
2764       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2765         KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2766         KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2767         if (LHSKnown.isNonNegative() && YKnown.isNegative())
2768           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2769         if (LHSKnown.isNegative() || YKnown.isNonNegative())
2770           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2771       }
2772     }
2773   }
2774
2775   // icmp pred (and X, Y), X
2776   if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2777     if (Pred == ICmpInst::ICMP_UGT)
2778       return getFalse(ITy);
2779     if (Pred == ICmpInst::ICMP_ULE)
2780       return getTrue(ITy);
2781   }
2782   // icmp pred X, (and X, Y)
2783   if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2784     if (Pred == ICmpInst::ICMP_UGE)
2785       return getTrue(ITy);
2786     if (Pred == ICmpInst::ICMP_ULT)
2787       return getFalse(ITy);
2788   }
2789
2790   // 0 - (zext X) pred C
2791   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2792     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2793       if (RHSC->getValue().isStrictlyPositive()) {
2794         if (Pred == ICmpInst::ICMP_SLT)
2795           return ConstantInt::getTrue(RHSC->getContext());
2796         if (Pred == ICmpInst::ICMP_SGE)
2797           return ConstantInt::getFalse(RHSC->getContext());
2798         if (Pred == ICmpInst::ICMP_EQ)
2799           return ConstantInt::getFalse(RHSC->getContext());
2800         if (Pred == ICmpInst::ICMP_NE)
2801           return ConstantInt::getTrue(RHSC->getContext());
2802       }
2803       if (RHSC->getValue().isNonNegative()) {
2804         if (Pred == ICmpInst::ICMP_SLE)
2805           return ConstantInt::getTrue(RHSC->getContext());
2806         if (Pred == ICmpInst::ICMP_SGT)
2807           return ConstantInt::getFalse(RHSC->getContext());
2808       }
2809     }
2810   }
2811
2812   // icmp pred (urem X, Y), Y
2813   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2814     switch (Pred) {
2815     default:
2816       break;
2817     case ICmpInst::ICMP_SGT:
2818     case ICmpInst::ICMP_SGE: {
2819       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2820       if (!Known.isNonNegative())
2821         break;
2822       LLVM_FALLTHROUGH;
2823     }
2824     case ICmpInst::ICMP_EQ:
2825     case ICmpInst::ICMP_UGT:
2826     case ICmpInst::ICMP_UGE:
2827       return getFalse(ITy);
2828     case ICmpInst::ICMP_SLT:
2829     case ICmpInst::ICMP_SLE: {
2830       KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2831       if (!Known.isNonNegative())
2832         break;
2833       LLVM_FALLTHROUGH;
2834     }
2835     case ICmpInst::ICMP_NE:
2836     case ICmpInst::ICMP_ULT:
2837     case ICmpInst::ICMP_ULE:
2838       return getTrue(ITy);
2839     }
2840   }
2841
2842   // icmp pred X, (urem Y, X)
2843   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2844     switch (Pred) {
2845     default:
2846       break;
2847     case ICmpInst::ICMP_SGT:
2848     case ICmpInst::ICMP_SGE: {
2849       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2850       if (!Known.isNonNegative())
2851         break;
2852       LLVM_FALLTHROUGH;
2853     }
2854     case ICmpInst::ICMP_NE:
2855     case ICmpInst::ICMP_UGT:
2856     case ICmpInst::ICMP_UGE:
2857       return getTrue(ITy);
2858     case ICmpInst::ICMP_SLT:
2859     case ICmpInst::ICMP_SLE: {
2860       KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2861       if (!Known.isNonNegative())
2862         break;
2863       LLVM_FALLTHROUGH;
2864     }
2865     case ICmpInst::ICMP_EQ:
2866     case ICmpInst::ICMP_ULT:
2867     case ICmpInst::ICMP_ULE:
2868       return getFalse(ITy);
2869     }
2870   }
2871
2872   // x >> y <=u x
2873   // x udiv y <=u x.
2874   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2875               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2876     // icmp pred (X op Y), X
2877     if (Pred == ICmpInst::ICMP_UGT)
2878       return getFalse(ITy);
2879     if (Pred == ICmpInst::ICMP_ULE)
2880       return getTrue(ITy);
2881   }
2882
2883   // x >=u x >> y
2884   // x >=u x udiv y.
2885   if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2886               match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2887     // icmp pred X, (X op Y)
2888     if (Pred == ICmpInst::ICMP_ULT)
2889       return getFalse(ITy);
2890     if (Pred == ICmpInst::ICMP_UGE)
2891       return getTrue(ITy);
2892   }
2893
2894   // handle:
2895   //   CI2 << X == CI
2896   //   CI2 << X != CI
2897   //
2898   //   where CI2 is a power of 2 and CI isn't
2899   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2900     const APInt *CI2Val, *CIVal = &CI->getValue();
2901     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2902         CI2Val->isPowerOf2()) {
2903       if (!CIVal->isPowerOf2()) {
2904         // CI2 << X can equal zero in some circumstances,
2905         // this simplification is unsafe if CI is zero.
2906         //
2907         // We know it is safe if:
2908         // - The shift is nsw, we can't shift out the one bit.
2909         // - The shift is nuw, we can't shift out the one bit.
2910         // - CI2 is one
2911         // - CI isn't zero
2912         if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2913             Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2914             CI2Val->isOneValue() || !CI->isZero()) {
2915           if (Pred == ICmpInst::ICMP_EQ)
2916             return ConstantInt::getFalse(RHS->getContext());
2917           if (Pred == ICmpInst::ICMP_NE)
2918             return ConstantInt::getTrue(RHS->getContext());
2919         }
2920       }
2921       if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2922         if (Pred == ICmpInst::ICMP_UGT)
2923           return ConstantInt::getFalse(RHS->getContext());
2924         if (Pred == ICmpInst::ICMP_ULE)
2925           return ConstantInt::getTrue(RHS->getContext());
2926       }
2927     }
2928   }
2929
2930   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2931       LBO->getOperand(1) == RBO->getOperand(1)) {
2932     switch (LBO->getOpcode()) {
2933     default:
2934       break;
2935     case Instruction::UDiv:
2936     case Instruction::LShr:
2937       if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
2938           !Q.IIQ.isExact(RBO))
2939         break;
2940       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2941                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2942           return V;
2943       break;
2944     case Instruction::SDiv:
2945       if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
2946           !Q.IIQ.isExact(RBO))
2947         break;
2948       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2949                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2950         return V;
2951       break;
2952     case Instruction::AShr:
2953       if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
2954         break;
2955       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2956                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2957         return V;
2958       break;
2959     case Instruction::Shl: {
2960       bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
2961       bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
2962       if (!NUW && !NSW)
2963         break;
2964       if (!NSW && ICmpInst::isSigned(Pred))
2965         break;
2966       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2967                                       RBO->getOperand(0), Q, MaxRecurse - 1))
2968         return V;
2969       break;
2970     }
2971     }
2972   }
2973   return nullptr;
2974 }
2975
2976 /// Simplify integer comparisons where at least one operand of the compare
2977 /// matches an integer min/max idiom.
2978 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2979                                      Value *RHS, const SimplifyQuery &Q,
2980                                      unsigned MaxRecurse) {
2981   Type *ITy = GetCompareTy(LHS); // The return type.
2982   Value *A, *B;
2983   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2984   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2985
2986   // Signed variants on "max(a,b)>=a -> true".
2987   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2988     if (A != RHS)
2989       std::swap(A, B);       // smax(A, B) pred A.
2990     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2991     // We analyze this as smax(A, B) pred A.
2992     P = Pred;
2993   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2994              (A == LHS || B == LHS)) {
2995     if (A != LHS)
2996       std::swap(A, B);       // A pred smax(A, B).
2997     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2998     // We analyze this as smax(A, B) swapped-pred A.
2999     P = CmpInst::getSwappedPredicate(Pred);
3000   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3001              (A == RHS || B == RHS)) {
3002     if (A != RHS)
3003       std::swap(A, B);       // smin(A, B) pred A.
3004     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3005     // We analyze this as smax(-A, -B) swapped-pred -A.
3006     // Note that we do not need to actually form -A or -B thanks to EqP.
3007     P = CmpInst::getSwappedPredicate(Pred);
3008   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3009              (A == LHS || B == LHS)) {
3010     if (A != LHS)
3011       std::swap(A, B);       // A pred smin(A, B).
3012     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3013     // We analyze this as smax(-A, -B) pred -A.
3014     // Note that we do not need to actually form -A or -B thanks to EqP.
3015     P = Pred;
3016   }
3017   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3018     // Cases correspond to "max(A, B) p A".
3019     switch (P) {
3020     default:
3021       break;
3022     case CmpInst::ICMP_EQ:
3023     case CmpInst::ICMP_SLE:
3024       // Equivalent to "A EqP B".  This may be the same as the condition tested
3025       // in the max/min; if so, we can just return that.
3026       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3027         return V;
3028       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3029         return V;
3030       // Otherwise, see if "A EqP B" simplifies.
3031       if (MaxRecurse)
3032         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3033           return V;
3034       break;
3035     case CmpInst::ICMP_NE:
3036     case CmpInst::ICMP_SGT: {
3037       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3038       // Equivalent to "A InvEqP B".  This may be the same as the condition
3039       // tested in the max/min; if so, we can just return that.
3040       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3041         return V;
3042       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3043         return V;
3044       // Otherwise, see if "A InvEqP B" simplifies.
3045       if (MaxRecurse)
3046         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3047           return V;
3048       break;
3049     }
3050     case CmpInst::ICMP_SGE:
3051       // Always true.
3052       return getTrue(ITy);
3053     case CmpInst::ICMP_SLT:
3054       // Always false.
3055       return getFalse(ITy);
3056     }
3057   }
3058
3059   // Unsigned variants on "max(a,b)>=a -> true".
3060   P = CmpInst::BAD_ICMP_PREDICATE;
3061   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3062     if (A != RHS)
3063       std::swap(A, B);       // umax(A, B) pred A.
3064     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3065     // We analyze this as umax(A, B) pred A.
3066     P = Pred;
3067   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3068              (A == LHS || B == LHS)) {
3069     if (A != LHS)
3070       std::swap(A, B);       // A pred umax(A, B).
3071     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3072     // We analyze this as umax(A, B) swapped-pred A.
3073     P = CmpInst::getSwappedPredicate(Pred);
3074   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3075              (A == RHS || B == RHS)) {
3076     if (A != RHS)
3077       std::swap(A, B);       // umin(A, B) pred A.
3078     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3079     // We analyze this as umax(-A, -B) swapped-pred -A.
3080     // Note that we do not need to actually form -A or -B thanks to EqP.
3081     P = CmpInst::getSwappedPredicate(Pred);
3082   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3083              (A == LHS || B == LHS)) {
3084     if (A != LHS)
3085       std::swap(A, B);       // A pred umin(A, B).
3086     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3087     // We analyze this as umax(-A, -B) pred -A.
3088     // Note that we do not need to actually form -A or -B thanks to EqP.
3089     P = Pred;
3090   }
3091   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3092     // Cases correspond to "max(A, B) p A".
3093     switch (P) {
3094     default:
3095       break;
3096     case CmpInst::ICMP_EQ:
3097     case CmpInst::ICMP_ULE:
3098       // Equivalent to "A EqP B".  This may be the same as the condition tested
3099       // in the max/min; if so, we can just return that.
3100       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3101         return V;
3102       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3103         return V;
3104       // Otherwise, see if "A EqP B" simplifies.
3105       if (MaxRecurse)
3106         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3107           return V;
3108       break;
3109     case CmpInst::ICMP_NE:
3110     case CmpInst::ICMP_UGT: {
3111       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3112       // Equivalent to "A InvEqP B".  This may be the same as the condition
3113       // tested in the max/min; if so, we can just return that.
3114       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3115         return V;
3116       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3117         return V;
3118       // Otherwise, see if "A InvEqP B" simplifies.
3119       if (MaxRecurse)
3120         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3121           return V;
3122       break;
3123     }
3124     case CmpInst::ICMP_UGE:
3125       // Always true.
3126       return getTrue(ITy);
3127     case CmpInst::ICMP_ULT:
3128       // Always false.
3129       return getFalse(ITy);
3130     }
3131   }
3132
3133   // Variants on "max(x,y) >= min(x,z)".
3134   Value *C, *D;
3135   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3136       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3137       (A == C || A == D || B == C || B == D)) {
3138     // max(x, ?) pred min(x, ?).
3139     if (Pred == CmpInst::ICMP_SGE)
3140       // Always true.
3141       return getTrue(ITy);
3142     if (Pred == CmpInst::ICMP_SLT)
3143       // Always false.
3144       return getFalse(ITy);
3145   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3146              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3147              (A == C || A == D || B == C || B == D)) {
3148     // min(x, ?) pred max(x, ?).
3149     if (Pred == CmpInst::ICMP_SLE)
3150       // Always true.
3151       return getTrue(ITy);
3152     if (Pred == CmpInst::ICMP_SGT)
3153       // Always false.
3154       return getFalse(ITy);
3155   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3156              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3157              (A == C || A == D || B == C || B == D)) {
3158     // max(x, ?) pred min(x, ?).
3159     if (Pred == CmpInst::ICMP_UGE)
3160       // Always true.
3161       return getTrue(ITy);
3162     if (Pred == CmpInst::ICMP_ULT)
3163       // Always false.
3164       return getFalse(ITy);
3165   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3166              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3167              (A == C || A == D || B == C || B == D)) {
3168     // min(x, ?) pred max(x, ?).
3169     if (Pred == CmpInst::ICMP_ULE)
3170       // Always true.
3171       return getTrue(ITy);
3172     if (Pred == CmpInst::ICMP_UGT)
3173       // Always false.
3174       return getFalse(ITy);
3175   }
3176
3177   return nullptr;
3178 }
3179
3180 /// Given operands for an ICmpInst, see if we can fold the result.
3181 /// If not, this returns null.
3182 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3183                                const SimplifyQuery &Q, unsigned MaxRecurse) {
3184   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3185   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3186
3187   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3188     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3189       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3190
3191     // If we have a constant, make sure it is on the RHS.
3192     std::swap(LHS, RHS);
3193     Pred = CmpInst::getSwappedPredicate(Pred);
3194   }
3195   assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3196
3197   Type *ITy = GetCompareTy(LHS); // The return type.
3198
3199   // For EQ and NE, we can always pick a value for the undef to make the
3200   // predicate pass or fail, so we can return undef.
3201   // Matches behavior in llvm::ConstantFoldCompareInstruction.
3202   if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3203     return UndefValue::get(ITy);
3204
3205   // icmp X, X -> true/false
3206   // icmp X, undef -> true/false because undef could be X.
3207   if (LHS == RHS || isa<UndefValue>(RHS))
3208     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3209
3210   if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3211     return V;
3212
3213   if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3214     return V;
3215
3216   if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3217     return V;
3218
3219   // If both operands have range metadata, use the metadata
3220   // to simplify the comparison.
3221   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3222     auto RHS_Instr = cast<Instruction>(RHS);
3223     auto LHS_Instr = cast<Instruction>(LHS);
3224
3225     if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3226         Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3227       auto RHS_CR = getConstantRangeFromMetadata(
3228           *RHS_Instr->getMetadata(LLVMContext::MD_range));
3229       auto LHS_CR = getConstantRangeFromMetadata(
3230           *LHS_Instr->getMetadata(LLVMContext::MD_range));
3231
3232       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3233       if (Satisfied_CR.contains(LHS_CR))
3234         return ConstantInt::getTrue(RHS->getContext());
3235
3236       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3237                 CmpInst::getInversePredicate(Pred), RHS_CR);
3238       if (InversedSatisfied_CR.contains(LHS_CR))
3239         return ConstantInt::getFalse(RHS->getContext());
3240     }
3241   }
3242
3243   // Compare of cast, for example (zext X) != 0 -> X != 0
3244   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3245     Instruction *LI = cast<CastInst>(LHS);
3246     Value *SrcOp = LI->getOperand(0);
3247     Type *SrcTy = SrcOp->getType();
3248     Type *DstTy = LI->getType();
3249
3250     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3251     // if the integer type is the same size as the pointer type.
3252     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3253         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3254       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3255         // Transfer the cast to the constant.
3256         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3257                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
3258                                         Q, MaxRecurse-1))
3259           return V;
3260       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3261         if (RI->getOperand(0)->getType() == SrcTy)
3262           // Compare without the cast.
3263           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3264                                           Q, MaxRecurse-1))
3265             return V;
3266       }
3267     }
3268
3269     if (isa<ZExtInst>(LHS)) {
3270       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3271       // same type.
3272       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3273         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3274           // Compare X and Y.  Note that signed predicates become unsigned.
3275           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3276                                           SrcOp, RI->getOperand(0), Q,
3277                                           MaxRecurse-1))
3278             return V;
3279       }
3280       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3281       // too.  If not, then try to deduce the result of the comparison.
3282       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3283         // Compute the constant that would happen if we truncated to SrcTy then
3284         // reextended to DstTy.
3285         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3286         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3287
3288         // If the re-extended constant didn't change then this is effectively
3289         // also a case of comparing two zero-extended values.
3290         if (RExt == CI && MaxRecurse)
3291           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3292                                         SrcOp, Trunc, Q, MaxRecurse-1))
3293             return V;
3294
3295         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3296         // there.  Use this to work out the result of the comparison.
3297         if (RExt != CI) {
3298           switch (Pred) {
3299           default: llvm_unreachable("Unknown ICmp predicate!");
3300           // LHS <u RHS.
3301           case ICmpInst::ICMP_EQ:
3302           case ICmpInst::ICMP_UGT:
3303           case ICmpInst::ICMP_UGE:
3304             return ConstantInt::getFalse(CI->getContext());
3305
3306           case ICmpInst::ICMP_NE:
3307           case ICmpInst::ICMP_ULT:
3308           case ICmpInst::ICMP_ULE:
3309             return ConstantInt::getTrue(CI->getContext());
3310
3311           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
3312           // is non-negative then LHS <s RHS.
3313           case ICmpInst::ICMP_SGT:
3314           case ICmpInst::ICMP_SGE:
3315             return CI->getValue().isNegative() ?
3316               ConstantInt::getTrue(CI->getContext()) :
3317               ConstantInt::getFalse(CI->getContext());
3318
3319           case ICmpInst::ICMP_SLT:
3320           case ICmpInst::ICMP_SLE:
3321             return CI->getValue().isNegative() ?
3322               ConstantInt::getFalse(CI->getContext()) :
3323               ConstantInt::getTrue(CI->getContext());
3324           }
3325         }
3326       }
3327     }
3328
3329     if (isa<SExtInst>(LHS)) {
3330       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3331       // same type.
3332       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3333         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3334           // Compare X and Y.  Note that the predicate does not change.
3335           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3336                                           Q, MaxRecurse-1))
3337             return V;
3338       }
3339       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3340       // too.  If not, then try to deduce the result of the comparison.
3341       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3342         // Compute the constant that would happen if we truncated to SrcTy then
3343         // reextended to DstTy.
3344         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3345         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3346
3347         // If the re-extended constant didn't change then this is effectively
3348         // also a case of comparing two sign-extended values.
3349         if (RExt == CI && MaxRecurse)
3350           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3351             return V;
3352
3353         // Otherwise the upper bits of LHS are all equal, while RHS has varying
3354         // bits there.  Use this to work out the result of the comparison.
3355         if (RExt != CI) {
3356           switch (Pred) {
3357           default: llvm_unreachable("Unknown ICmp predicate!");
3358           case ICmpInst::ICMP_EQ:
3359             return ConstantInt::getFalse(CI->getContext());
3360           case ICmpInst::ICMP_NE:
3361             return ConstantInt::getTrue(CI->getContext());
3362
3363           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
3364           // LHS >s RHS.
3365           case ICmpInst::ICMP_SGT:
3366           case ICmpInst::ICMP_SGE:
3367             return CI->getValue().isNegative() ?
3368               ConstantInt::getTrue(CI->getContext()) :
3369               ConstantInt::getFalse(CI->getContext());
3370           case ICmpInst::ICMP_SLT:
3371           case ICmpInst::ICMP_SLE:
3372             return CI->getValue().isNegative() ?
3373               ConstantInt::getFalse(CI->getContext()) :
3374               ConstantInt::getTrue(CI->getContext());
3375
3376           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
3377           // LHS >u RHS.
3378           case ICmpInst::ICMP_UGT:
3379           case ICmpInst::ICMP_UGE:
3380             // Comparison is true iff the LHS <s 0.
3381             if (MaxRecurse)
3382               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3383                                               Constant::getNullValue(SrcTy),
3384                                               Q, MaxRecurse-1))
3385                 return V;
3386             break;
3387           case ICmpInst::ICMP_ULT:
3388           case ICmpInst::ICMP_ULE:
3389             // Comparison is true iff the LHS >=s 0.
3390             if (MaxRecurse)
3391               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3392                                               Constant::getNullValue(SrcTy),
3393                                               Q, MaxRecurse-1))
3394                 return V;
3395             break;
3396           }
3397         }
3398       }
3399     }
3400   }
3401
3402   // icmp eq|ne X, Y -> false|true if X != Y
3403   if (ICmpInst::isEquality(Pred) &&
3404       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3405     return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3406   }
3407
3408   if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3409     return V;
3410
3411   if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3412     return V;
3413
3414   // Simplify comparisons of related pointers using a powerful, recursive
3415   // GEP-walk when we have target data available..
3416   if (LHS->getType()->isPointerTy())
3417     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3418                                      Q.IIQ, LHS, RHS))
3419       return C;
3420   if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3421     if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3422       if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3423               Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3424           Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3425               Q.DL.getTypeSizeInBits(CRHS->getType()))
3426         if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3427                                          Q.IIQ, CLHS->getPointerOperand(),
3428                                          CRHS->getPointerOperand()))
3429           return C;
3430
3431   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3432     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3433       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3434           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3435           (ICmpInst::isEquality(Pred) ||
3436            (GLHS->isInBounds() && GRHS->isInBounds() &&
3437             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3438         // The bases are equal and the indices are constant.  Build a constant
3439         // expression GEP with the same indices and a null base pointer to see
3440         // what constant folding can make out of it.
3441         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3442         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3443         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3444             GLHS->getSourceElementType(), Null, IndicesLHS);
3445
3446         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3447         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3448             GLHS->getSourceElementType(), Null, IndicesRHS);
3449         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3450       }
3451     }
3452   }
3453
3454   // If the comparison is with the result of a select instruction, check whether
3455   // comparing with either branch of the select always yields the same value.
3456   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3457     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3458       return V;
3459
3460   // If the comparison is with the result of a phi instruction, check whether
3461   // doing the compare with each incoming phi value yields a common result.
3462   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3463     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3464       return V;
3465
3466   return nullptr;
3467 }
3468
3469 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3470                               const SimplifyQuery &Q) {
3471   return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3472 }
3473
3474 /// Given operands for an FCmpInst, see if we can fold the result.
3475 /// If not, this returns null.
3476 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3477                                FastMathFlags FMF, const SimplifyQuery &Q,
3478                                unsigned MaxRecurse) {
3479   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3480   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3481
3482   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3483     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3484       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3485
3486     // If we have a constant, make sure it is on the RHS.
3487     std::swap(LHS, RHS);
3488     Pred = CmpInst::getSwappedPredicate(Pred);
3489   }
3490
3491   // Fold trivial predicates.
3492   Type *RetTy = GetCompareTy(LHS);
3493   if (Pred == FCmpInst::FCMP_FALSE)
3494     return getFalse(RetTy);
3495   if (Pred == FCmpInst::FCMP_TRUE)
3496     return getTrue(RetTy);
3497
3498   // Fold (un)ordered comparison if we can determine there are no NaNs.
3499   if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3500     if (FMF.noNaNs() ||
3501         (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3502       return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3503
3504   // NaN is unordered; NaN is not ordered.
3505   assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3506          "Comparison must be either ordered or unordered");
3507   if (match(RHS, m_NaN()))
3508     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3509
3510   // fcmp pred x, undef  and  fcmp pred undef, x
3511   // fold to true if unordered, false if ordered
3512   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3513     // Choosing NaN for the undef will always make unordered comparison succeed
3514     // and ordered comparison fail.
3515     return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3516   }
3517
3518   // fcmp x,x -> true/false.  Not all compares are foldable.
3519   if (LHS == RHS) {
3520     if (CmpInst::isTrueWhenEqual(Pred))
3521       return getTrue(RetTy);
3522     if (CmpInst::isFalseWhenEqual(Pred))
3523       return getFalse(RetTy);
3524   }
3525
3526   // Handle fcmp with constant RHS.
3527   // TODO: Use match with a specific FP value, so these work with vectors with
3528   // undef lanes.
3529   const APFloat *C;
3530   if (match(RHS, m_APFloat(C))) {
3531     // Check whether the constant is an infinity.
3532     if (C->isInfinity()) {
3533       if (C->isNegative()) {
3534         switch (Pred) {
3535         case FCmpInst::FCMP_OLT:
3536           // No value is ordered and less than negative infinity.
3537           return getFalse(RetTy);
3538         case FCmpInst::FCMP_UGE:
3539           // All values are unordered with or at least negative infinity.
3540           return getTrue(RetTy);
3541         default:
3542           break;
3543         }
3544       } else {
3545         switch (Pred) {
3546         case FCmpInst::FCMP_OGT:
3547           // No value is ordered and greater than infinity.
3548           return getFalse(RetTy);
3549         case FCmpInst::FCMP_ULE:
3550           // All values are unordered with and at most infinity.
3551           return getTrue(RetTy);
3552         default:
3553           break;
3554         }
3555       }
3556     }
3557     if (C->isNegative() && !C->isNegZero()) {
3558       assert(!C->isNaN() && "Unexpected NaN constant!");
3559       // TODO: We can catch more cases by using a range check rather than
3560       //       relying on CannotBeOrderedLessThanZero.
3561       switch (Pred) {
3562       case FCmpInst::FCMP_UGE:
3563       case FCmpInst::FCMP_UGT:
3564       case FCmpInst::FCMP_UNE:
3565         // (X >= 0) implies (X > C) when (C < 0)
3566         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3567           return getTrue(RetTy);
3568         break;
3569       case FCmpInst::FCMP_OEQ:
3570       case FCmpInst::FCMP_OLE:
3571       case FCmpInst::FCMP_OLT:
3572         // (X >= 0) implies !(X < C) when (C < 0)
3573         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3574           return getFalse(RetTy);
3575         break;
3576       default:
3577         break;
3578       }
3579     }
3580
3581     // Check comparison of [minnum/maxnum with constant] with other constant.
3582     const APFloat *C2;
3583     if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3584          C2->compare(*C) == APFloat::cmpLessThan) ||
3585         (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3586          C2->compare(*C) == APFloat::cmpGreaterThan)) {
3587       bool IsMaxNum =
3588           cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3589       // The ordered relationship and minnum/maxnum guarantee that we do not
3590       // have NaN constants, so ordered/unordered preds are handled the same.
3591       switch (Pred) {
3592       case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
3593         // minnum(X, LesserC)  == C --> false
3594         // maxnum(X, GreaterC) == C --> false
3595         return getFalse(RetTy);
3596       case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
3597         // minnum(X, LesserC)  != C --> true
3598         // maxnum(X, GreaterC) != C --> true
3599         return getTrue(RetTy);
3600       case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3601       case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3602         // minnum(X, LesserC)  >= C --> false
3603         // minnum(X, LesserC)  >  C --> false
3604         // maxnum(X, GreaterC) >= C --> true
3605         // maxnum(X, GreaterC) >  C --> true
3606         return ConstantInt::get(RetTy, IsMaxNum);
3607       case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3608       case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
3609         // minnum(X, LesserC)  <= C --> true
3610         // minnum(X, LesserC)  <  C --> true
3611         // maxnum(X, GreaterC) <= C --> false
3612         // maxnum(X, GreaterC) <  C --> false
3613         return ConstantInt::get(RetTy, !IsMaxNum);
3614       default:
3615         // TRUE/FALSE/ORD/UNO should be handled before this.
3616         llvm_unreachable("Unexpected fcmp predicate");
3617       }
3618     }
3619   }
3620
3621   if (match(RHS, m_AnyZeroFP())) {
3622     switch (Pred) {
3623     case FCmpInst::FCMP_OGE:
3624     case FCmpInst::FCMP_ULT:
3625       // Positive or zero X >= 0.0 --> true
3626       // Positive or zero X <  0.0 --> false
3627       if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3628           CannotBeOrderedLessThanZero(LHS, Q.TLI))
3629         return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3630       break;
3631     case FCmpInst::FCMP_UGE:
3632     case FCmpInst::FCMP_OLT:
3633       // Positive or zero or nan X >= 0.0 --> true
3634       // Positive or zero or nan X <  0.0 --> false
3635       if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3636         return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3637       break;
3638     default:
3639       break;
3640     }
3641   }
3642
3643   // If the comparison is with the result of a select instruction, check whether
3644   // comparing with either branch of the select always yields the same value.
3645   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3646     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3647       return V;
3648
3649   // If the comparison is with the result of a phi instruction, check whether
3650   // doing the compare with each incoming phi value yields a common result.
3651   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3652     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3653       return V;
3654
3655   return nullptr;
3656 }
3657
3658 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3659                               FastMathFlags FMF, const SimplifyQuery &Q) {
3660   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3661 }
3662
3663 /// See if V simplifies when its operand Op is replaced with RepOp.
3664 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3665                                            const SimplifyQuery &Q,
3666                                            unsigned MaxRecurse) {
3667   // Trivial replacement.
3668   if (V == Op)
3669     return RepOp;
3670
3671   // We cannot replace a constant, and shouldn't even try.
3672   if (isa<Constant>(Op))
3673     return nullptr;
3674
3675   auto *I = dyn_cast<Instruction>(V);
3676   if (!I)
3677     return nullptr;
3678
3679   // If this is a binary operator, try to simplify it with the replaced op.
3680   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3681     // Consider:
3682     //   %cmp = icmp eq i32 %x, 2147483647
3683     //   %add = add nsw i32 %x, 1
3684     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3685     //
3686     // We can't replace %sel with %add unless we strip away the flags.
3687     // TODO: This is an unusual limitation because better analysis results in
3688     //       worse simplification. InstCombine can do this fold more generally
3689     //       by dropping the flags. Remove this fold to save compile-time?
3690     if (isa<OverflowingBinaryOperator>(B))
3691       if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3692         return nullptr;
3693     if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3694       return nullptr;
3695
3696     if (MaxRecurse) {
3697       if (B->getOperand(0) == Op)
3698         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3699                              MaxRecurse - 1);
3700       if (B->getOperand(1) == Op)
3701         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3702                              MaxRecurse - 1);
3703     }
3704   }
3705
3706   // Same for CmpInsts.
3707   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3708     if (MaxRecurse) {
3709       if (C->getOperand(0) == Op)
3710         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3711                                MaxRecurse - 1);
3712       if (C->getOperand(1) == Op)
3713         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3714                                MaxRecurse - 1);
3715     }
3716   }
3717
3718   // Same for GEPs.
3719   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3720     if (MaxRecurse) {
3721       SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3722       transform(GEP->operands(), NewOps.begin(),
3723                 [&](Value *V) { return V == Op ? RepOp : V; });
3724       return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3725                              MaxRecurse - 1);
3726     }
3727   }
3728
3729   // TODO: We could hand off more cases to instsimplify here.
3730
3731   // If all operands are constant after substituting Op for RepOp then we can
3732   // constant fold the instruction.
3733   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3734     // Build a list of all constant operands.
3735     SmallVector<Constant *, 8> ConstOps;
3736     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3737       if (I->getOperand(i) == Op)
3738         ConstOps.push_back(CRepOp);
3739       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3740         ConstOps.push_back(COp);
3741       else
3742         break;
3743     }
3744
3745     // All operands were constants, fold it.
3746     if (ConstOps.size() == I->getNumOperands()) {
3747       if (CmpInst *C = dyn_cast<CmpInst>(I))
3748         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3749                                                ConstOps[1], Q.DL, Q.TLI);
3750
3751       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3752         if (!LI->isVolatile())
3753           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3754
3755       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3756     }
3757   }
3758
3759   return nullptr;
3760 }
3761
3762 /// Try to simplify a select instruction when its condition operand is an
3763 /// integer comparison where one operand of the compare is a constant.
3764 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3765                                     const APInt *Y, bool TrueWhenUnset) {
3766   const APInt *C;
3767
3768   // (X & Y) == 0 ? X & ~Y : X  --> X
3769   // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3770   if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3771       *Y == ~*C)
3772     return TrueWhenUnset ? FalseVal : TrueVal;
3773
3774   // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3775   // (X & Y) != 0 ? X : X & ~Y  --> X
3776   if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3777       *Y == ~*C)
3778     return TrueWhenUnset ? FalseVal : TrueVal;
3779
3780   if (Y->isPowerOf2()) {
3781     // (X & Y) == 0 ? X | Y : X  --> X | Y
3782     // (X & Y) != 0 ? X | Y : X  --> X
3783     if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3784         *Y == *C)
3785       return TrueWhenUnset ? TrueVal : FalseVal;
3786
3787     // (X & Y) == 0 ? X : X | Y  --> X
3788     // (X & Y) != 0 ? X : X | Y  --> X | Y
3789     if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3790         *Y == *C)
3791       return TrueWhenUnset ? TrueVal : FalseVal;
3792   }
3793
3794   return nullptr;
3795 }
3796
3797 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3798 /// eq/ne.
3799 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3800                                            ICmpInst::Predicate Pred,
3801                                            Value *TrueVal, Value *FalseVal) {
3802   Value *X;
3803   APInt Mask;
3804   if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3805     return nullptr;
3806
3807   return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3808                                Pred == ICmpInst::ICMP_EQ);
3809 }
3810
3811 /// Try to simplify a select instruction when its condition operand is an
3812 /// integer comparison.
3813 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3814                                          Value *FalseVal, const SimplifyQuery &Q,
3815                                          unsigned MaxRecurse) {
3816   ICmpInst::Predicate Pred;
3817   Value *CmpLHS, *CmpRHS;
3818   if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3819     return nullptr;
3820
3821   if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3822     Value *X;
3823     const APInt *Y;
3824     if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3825       if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3826                                            Pred == ICmpInst::ICMP_EQ))
3827         return V;
3828
3829     // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
3830     Value *ShAmt;
3831     auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3832                                                           m_Value(ShAmt)),
3833                              m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3834                                                           m_Value(ShAmt)));
3835     // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3836     // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3837     if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3838         Pred == ICmpInst::ICMP_EQ)
3839       return X;
3840     // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3841     // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3842     if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3843         Pred == ICmpInst::ICMP_NE)
3844       return X;
3845
3846     // Test for a zero-shift-guard-op around rotates. These are used to
3847     // avoid UB from oversized shifts in raw IR rotate patterns, but the
3848     // intrinsics do not have that problem.
3849     // We do not allow this transform for the general funnel shift case because
3850     // that would not preserve the poison safety of the original code.
3851     auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3852                                                              m_Deferred(X),
3853                                                              m_Value(ShAmt)),
3854                                 m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3855                                                              m_Deferred(X),
3856                                                              m_Value(ShAmt)));
3857     // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3858     // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3859     if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3860         Pred == ICmpInst::ICMP_NE)
3861       return TrueVal;
3862     // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3863     // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3864     if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3865         Pred == ICmpInst::ICMP_EQ)
3866       return FalseVal;
3867   }
3868
3869   // Check for other compares that behave like bit test.
3870   if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3871                                               TrueVal, FalseVal))
3872     return V;
3873
3874   // If we have an equality comparison, then we know the value in one of the
3875   // arms of the select. See if substituting this value into the arm and
3876   // simplifying the result yields the same value as the other arm.
3877   if (Pred == ICmpInst::ICMP_EQ) {
3878     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3879             TrueVal ||
3880         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3881             TrueVal)
3882       return FalseVal;
3883     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3884             FalseVal ||
3885         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3886             FalseVal)
3887       return FalseVal;
3888   } else if (Pred == ICmpInst::ICMP_NE) {
3889     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3890             FalseVal ||
3891         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3892             FalseVal)
3893       return TrueVal;
3894     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3895             TrueVal ||
3896         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3897             TrueVal)
3898       return TrueVal;
3899   }
3900
3901   return nullptr;
3902 }
3903
3904 /// Try to simplify a select instruction when its condition operand is a
3905 /// floating-point comparison.
3906 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3907   FCmpInst::Predicate Pred;
3908   if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3909       !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3910     return nullptr;
3911
3912   // TODO: The transform may not be valid with -0.0. An incomplete way of
3913   // testing for that possibility is to check if at least one operand is a
3914   // non-zero constant.
3915   const APFloat *C;
3916   if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3917       (match(F, m_APFloat(C)) && C->isNonZero())) {
3918     // (T == F) ? T : F --> F
3919     // (F == T) ? T : F --> F
3920     if (Pred == FCmpInst::FCMP_OEQ)
3921       return F;
3922
3923     // (T != F) ? T : F --> T
3924     // (F != T) ? T : F --> T
3925     if (Pred == FCmpInst::FCMP_UNE)
3926       return T;
3927   }
3928
3929   return nullptr;
3930 }
3931
3932 /// Given operands for a SelectInst, see if we can fold the result.
3933 /// If not, this returns null.
3934 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3935                                  const SimplifyQuery &Q, unsigned MaxRecurse) {
3936   if (auto *CondC = dyn_cast<Constant>(Cond)) {
3937     if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3938       if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3939         return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3940
3941     // select undef, X, Y -> X or Y
3942     if (isa<UndefValue>(CondC))
3943       return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3944
3945     // TODO: Vector constants with undef elements don't simplify.
3946
3947     // select true, X, Y  -> X
3948     if (CondC->isAllOnesValue())
3949       return TrueVal;
3950     // select false, X, Y -> Y
3951     if (CondC->isNullValue())
3952       return FalseVal;
3953   }
3954
3955   // select ?, X, X -> X
3956   if (TrueVal == FalseVal)
3957     return TrueVal;
3958
3959   if (isa<UndefValue>(TrueVal))   // select ?, undef, X -> X
3960     return FalseVal;
3961   if (isa<UndefValue>(FalseVal))   // select ?, X, undef -> X
3962     return TrueVal;
3963
3964   if (Value *V =
3965           simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
3966     return V;
3967
3968   if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
3969     return V;
3970
3971   if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
3972     return V;
3973
3974   Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
3975   if (Imp)
3976     return *Imp ? TrueVal : FalseVal;
3977
3978   return nullptr;
3979 }
3980
3981 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3982                                 const SimplifyQuery &Q) {
3983   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
3984 }
3985
3986 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3987 /// If not, this returns null.
3988 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3989                               const SimplifyQuery &Q, unsigned) {
3990   // The type of the GEP pointer operand.
3991   unsigned AS =
3992       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3993
3994   // getelementptr P -> P.
3995   if (Ops.size() == 1)
3996     return Ops[0];
3997
3998   // Compute the (pointer) type returned by the GEP instruction.
3999   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
4000   Type *GEPTy = PointerType::get(LastType, AS);
4001   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
4002     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
4003   else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
4004     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
4005
4006   if (isa<UndefValue>(Ops[0]))
4007     return UndefValue::get(GEPTy);
4008
4009   if (Ops.size() == 2) {
4010     // getelementptr P, 0 -> P.
4011     if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
4012       return Ops[0];
4013
4014     Type *Ty = SrcTy;
4015     if (Ty->isSized()) {
4016       Value *P;
4017       uint64_t C;
4018       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4019       // getelementptr P, N -> P if P points to a type of zero size.
4020       if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4021         return Ops[0];
4022
4023       // The following transforms are only safe if the ptrtoint cast
4024       // doesn't truncate the pointers.
4025       if (Ops[1]->getType()->getScalarSizeInBits() ==
4026           Q.DL.getIndexSizeInBits(AS)) {
4027         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
4028           if (match(P, m_Zero()))
4029             return Constant::getNullValue(GEPTy);
4030           Value *Temp;
4031           if (match(P, m_PtrToInt(m_Value(Temp))))
4032             if (Temp->getType() == GEPTy)
4033               return Temp;
4034           return nullptr;
4035         };
4036
4037         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4038         if (TyAllocSize == 1 &&
4039             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4040           if (Value *R = PtrToIntOrZero(P))
4041             return R;
4042
4043         // getelementptr V, (ashr (sub P, V), C) -> Q
4044         // if P points to a type of size 1 << C.
4045         if (match(Ops[1],
4046                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4047                          m_ConstantInt(C))) &&
4048             TyAllocSize == 1ULL << C)
4049           if (Value *R = PtrToIntOrZero(P))
4050             return R;
4051
4052         // getelementptr V, (sdiv (sub P, V), C) -> Q
4053         // if P points to a type of size C.
4054         if (match(Ops[1],
4055                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4056                          m_SpecificInt(TyAllocSize))))
4057           if (Value *R = PtrToIntOrZero(P))
4058             return R;
4059       }
4060     }
4061   }
4062
4063   if (Q.DL.getTypeAllocSize(LastType) == 1 &&
4064       all_of(Ops.slice(1).drop_back(1),
4065              [](Value *Idx) { return match(Idx, m_Zero()); })) {
4066     unsigned IdxWidth =
4067         Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4068     if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4069       APInt BasePtrOffset(IdxWidth, 0);
4070       Value *StrippedBasePtr =
4071           Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4072                                                             BasePtrOffset);
4073
4074       // gep (gep V, C), (sub 0, V) -> C
4075       if (match(Ops.back(),
4076                 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
4077         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4078         return ConstantExpr::getIntToPtr(CI, GEPTy);
4079       }
4080       // gep (gep V, C), (xor V, -1) -> C-1
4081       if (match(Ops.back(),
4082                 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
4083         auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4084         return ConstantExpr::getIntToPtr(CI, GEPTy);
4085       }
4086     }
4087   }
4088
4089   // Check to see if this is constant foldable.
4090   if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4091     return nullptr;
4092
4093   auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4094                                             Ops.slice(1));
4095   if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
4096     return CEFolded;
4097   return CE;
4098 }
4099
4100 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4101                              const SimplifyQuery &Q) {
4102   return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4103 }
4104
4105 /// Given operands for an InsertValueInst, see if we can fold the result.
4106 /// If not, this returns null.
4107 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4108                                       ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4109                                       unsigned) {
4110   if (Constant *CAgg = dyn_cast<Constant>(Agg))
4111     if (Constant *CVal = dyn_cast<Constant>(Val))
4112       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4113
4114   // insertvalue x, undef, n -> x
4115   if (match(Val, m_Undef()))
4116     return Agg;
4117
4118   // insertvalue x, (extractvalue y, n), n
4119   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4120     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4121         EV->getIndices() == Idxs) {
4122       // insertvalue undef, (extractvalue y, n), n -> y
4123       if (match(Agg, m_Undef()))
4124         return EV->getAggregateOperand();
4125
4126       // insertvalue y, (extractvalue y, n), n -> y
4127       if (Agg == EV->getAggregateOperand())
4128         return Agg;
4129     }
4130
4131   return nullptr;
4132 }
4133
4134 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4135                                      ArrayRef<unsigned> Idxs,
4136                                      const SimplifyQuery &Q) {
4137   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4138 }
4139
4140 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4141                                        const SimplifyQuery &Q) {
4142   // Try to constant fold.
4143   auto *VecC = dyn_cast<Constant>(Vec);
4144   auto *ValC = dyn_cast<Constant>(Val);
4145   auto *IdxC = dyn_cast<Constant>(Idx);
4146   if (VecC && ValC && IdxC)
4147     return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4148
4149   // Fold into undef if index is out of bounds.
4150   if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4151     uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
4152     if (CI->uge(NumElements))
4153       return UndefValue::get(Vec->getType());
4154   }
4155
4156   // If index is undef, it might be out of bounds (see above case)
4157   if (isa<UndefValue>(Idx))
4158     return UndefValue::get(Vec->getType());
4159
4160   // Inserting an undef scalar? Assume it is the same value as the existing
4161   // vector element.
4162   if (isa<UndefValue>(Val))
4163     return Vec;
4164
4165   // If we are extracting a value from a vector, then inserting it into the same
4166   // place, that's the input vector:
4167   // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4168   if (match(Val, m_ExtractElement(m_Specific(Vec), m_Specific(Idx))))
4169     return Vec;
4170
4171   return nullptr;
4172 }
4173
4174 /// Given operands for an ExtractValueInst, see if we can fold the result.
4175 /// If not, this returns null.
4176 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4177                                        const SimplifyQuery &, unsigned) {
4178   if (auto *CAgg = dyn_cast<Constant>(Agg))
4179     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4180
4181   // extractvalue x, (insertvalue y, elt, n), n -> elt
4182   unsigned NumIdxs = Idxs.size();
4183   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4184        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4185     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4186     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4187     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4188     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4189         Idxs.slice(0, NumCommonIdxs)) {
4190       if (NumIdxs == NumInsertValueIdxs)
4191         return IVI->getInsertedValueOperand();
4192       break;
4193     }
4194   }
4195
4196   return nullptr;
4197 }
4198
4199 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4200                                       const SimplifyQuery &Q) {
4201   return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4202 }
4203
4204 /// Given operands for an ExtractElementInst, see if we can fold the result.
4205 /// If not, this returns null.
4206 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
4207                                          unsigned) {
4208   if (auto *CVec = dyn_cast<Constant>(Vec)) {
4209     if (auto *CIdx = dyn_cast<Constant>(Idx))
4210       return ConstantFoldExtractElementInstruction(CVec, CIdx);
4211
4212     // The index is not relevant if our vector is a splat.
4213     if (auto *Splat = CVec->getSplatValue())
4214       return Splat;
4215
4216     if (isa<UndefValue>(Vec))
4217       return UndefValue::get(Vec->getType()->getVectorElementType());
4218   }
4219
4220   // If extracting a specified index from the vector, see if we can recursively
4221   // find a previously computed scalar that was inserted into the vector.
4222   if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4223     if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4224       // definitely out of bounds, thus undefined result
4225       return UndefValue::get(Vec->getType()->getVectorElementType());
4226     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4227       return Elt;
4228   }
4229
4230   // An undef extract index can be arbitrarily chosen to be an out-of-range
4231   // index value, which would result in the instruction being undef.
4232   if (isa<UndefValue>(Idx))
4233     return UndefValue::get(Vec->getType()->getVectorElementType());
4234
4235   return nullptr;
4236 }
4237
4238 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4239                                         const SimplifyQuery &Q) {
4240   return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4241 }
4242
4243 /// See if we can fold the given phi. If not, returns null.
4244 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4245   // If all of the PHI's incoming values are the same then replace the PHI node
4246   // with the common value.
4247   Value *CommonValue = nullptr;
4248   bool HasUndefInput = false;
4249   for (Value *Incoming : PN->incoming_values()) {
4250     // If the incoming value is the phi node itself, it can safely be skipped.
4251     if (Incoming == PN) continue;
4252     if (isa<UndefValue>(Incoming)) {
4253       // Remember that we saw an undef value, but otherwise ignore them.
4254       HasUndefInput = true;
4255       continue;
4256     }
4257     if (CommonValue && Incoming != CommonValue)
4258       return nullptr;  // Not the same, bail out.
4259     CommonValue = Incoming;
4260   }
4261
4262   // If CommonValue is null then all of the incoming values were either undef or
4263   // equal to the phi node itself.
4264   if (!CommonValue)
4265     return UndefValue::get(PN->getType());
4266
4267   // If we have a PHI node like phi(X, undef, X), where X is defined by some
4268   // instruction, we cannot return X as the result of the PHI node unless it
4269   // dominates the PHI block.
4270   if (HasUndefInput)
4271     return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4272
4273   return CommonValue;
4274 }
4275
4276 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4277                                Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4278   if (auto *C = dyn_cast<Constant>(Op))
4279     return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4280
4281   if (auto *CI = dyn_cast<CastInst>(Op)) {
4282     auto *Src = CI->getOperand(0);
4283     Type *SrcTy = Src->getType();
4284     Type *MidTy = CI->getType();
4285     Type *DstTy = Ty;
4286     if (Src->getType() == Ty) {
4287       auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4288       auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4289       Type *SrcIntPtrTy =
4290           SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4291       Type *MidIntPtrTy =
4292           MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4293       Type *DstIntPtrTy =
4294           DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4295       if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4296                                          SrcIntPtrTy, MidIntPtrTy,
4297                                          DstIntPtrTy) == Instruction::BitCast)
4298         return Src;
4299     }
4300   }
4301
4302   // bitcast x -> x
4303   if (CastOpc == Instruction::BitCast)
4304     if (Op->getType() == Ty)
4305       return Op;
4306
4307   return nullptr;
4308 }
4309
4310 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4311                               const SimplifyQuery &Q) {
4312   return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4313 }
4314
4315 /// For the given destination element of a shuffle, peek through shuffles to
4316 /// match a root vector source operand that contains that element in the same
4317 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4318 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4319                                    int MaskVal, Value *RootVec,
4320                                    unsigned MaxRecurse) {
4321   if (!MaxRecurse--)
4322     return nullptr;
4323
4324   // Bail out if any mask value is undefined. That kind of shuffle may be
4325   // simplified further based on demanded bits or other folds.
4326   if (MaskVal == -1)
4327     return nullptr;
4328
4329   // The mask value chooses which source operand we need to look at next.
4330   int InVecNumElts = Op0->getType()->getVectorNumElements();
4331   int RootElt = MaskVal;
4332   Value *SourceOp = Op0;
4333   if (MaskVal >= InVecNumElts) {
4334     RootElt = MaskVal - InVecNumElts;
4335     SourceOp = Op1;
4336   }
4337
4338   // If the source operand is a shuffle itself, look through it to find the
4339   // matching root vector.
4340   if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4341     return foldIdentityShuffles(
4342         DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4343         SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4344   }
4345
4346   // TODO: Look through bitcasts? What if the bitcast changes the vector element
4347   // size?
4348
4349   // The source operand is not a shuffle. Initialize the root vector value for
4350   // this shuffle if that has not been done yet.
4351   if (!RootVec)
4352     RootVec = SourceOp;
4353
4354   // Give up as soon as a source operand does not match the existing root value.
4355   if (RootVec != SourceOp)
4356     return nullptr;
4357
4358   // The element must be coming from the same lane in the source vector
4359   // (although it may have crossed lanes in intermediate shuffles).
4360   if (RootElt != DestElt)
4361     return nullptr;
4362
4363   return RootVec;
4364 }
4365
4366 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4367                                         Type *RetTy, const SimplifyQuery &Q,
4368                                         unsigned MaxRecurse) {
4369   if (isa<UndefValue>(Mask))
4370     return UndefValue::get(RetTy);
4371
4372   Type *InVecTy = Op0->getType();
4373   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4374   unsigned InVecNumElts = InVecTy->getVectorNumElements();
4375
4376   SmallVector<int, 32> Indices;
4377   ShuffleVectorInst::getShuffleMask(Mask, Indices);
4378   assert(MaskNumElts == Indices.size() &&
4379          "Size of Indices not same as number of mask elements?");
4380
4381   // Canonicalization: If mask does not select elements from an input vector,
4382   // replace that input vector with undef.
4383   bool MaskSelects0 = false, MaskSelects1 = false;
4384   for (unsigned i = 0; i != MaskNumElts; ++i) {
4385     if (Indices[i] == -1)
4386       continue;
4387     if ((unsigned)Indices[i] < InVecNumElts)
4388       MaskSelects0 = true;
4389     else
4390       MaskSelects1 = true;
4391   }
4392   if (!MaskSelects0)
4393     Op0 = UndefValue::get(InVecTy);
4394   if (!MaskSelects1)
4395     Op1 = UndefValue::get(InVecTy);
4396
4397   auto *Op0Const = dyn_cast<Constant>(Op0);
4398   auto *Op1Const = dyn_cast<Constant>(Op1);
4399
4400   // If all operands are constant, constant fold the shuffle.
4401   if (Op0Const && Op1Const)
4402     return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4403
4404   // Canonicalization: if only one input vector is constant, it shall be the
4405   // second one.
4406   if (Op0Const && !Op1Const) {
4407     std::swap(Op0, Op1);
4408     ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4409   }
4410
4411   // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4412   // value type is same as the input vectors' type.
4413   if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4414     if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4415         OpShuf->getMask()->getSplatValue())
4416       return Op0;
4417
4418   // Don't fold a shuffle with undef mask elements. This may get folded in a
4419   // better way using demanded bits or other analysis.
4420   // TODO: Should we allow this?
4421   if (find(Indices, -1) != Indices.end())
4422     return nullptr;
4423
4424   // Check if every element of this shuffle can be mapped back to the
4425   // corresponding element of a single root vector. If so, we don't need this
4426   // shuffle. This handles simple identity shuffles as well as chains of
4427   // shuffles that may widen/narrow and/or move elements across lanes and back.
4428   Value *RootVec = nullptr;
4429   for (unsigned i = 0; i != MaskNumElts; ++i) {
4430     // Note that recursion is limited for each vector element, so if any element
4431     // exceeds the limit, this will fail to simplify.
4432     RootVec =
4433         foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4434
4435     // We can't replace a widening/narrowing shuffle with one of its operands.
4436     if (!RootVec || RootVec->getType() != RetTy)
4437       return nullptr;
4438   }
4439   return RootVec;
4440 }
4441
4442 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4443 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4444                                        Type *RetTy, const SimplifyQuery &Q) {
4445   return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4446 }
4447
4448 static Constant *foldConstant(Instruction::UnaryOps Opcode,
4449                               Value *&Op, const SimplifyQuery &Q) {
4450   if (auto *C = dyn_cast<Constant>(Op))
4451     return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4452   return nullptr;
4453 }
4454
4455 /// Given the operand for an FNeg, see if we can fold the result.  If not, this
4456 /// returns null.
4457 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4458                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4459   if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4460     return C;
4461
4462   Value *X;
4463   // fneg (fneg X) ==> X
4464   if (match(Op, m_FNeg(m_Value(X))))
4465     return X;
4466
4467   return nullptr;
4468 }
4469
4470 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4471                               const SimplifyQuery &Q) {
4472   return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4473 }
4474
4475 static Constant *propagateNaN(Constant *In) {
4476   // If the input is a vector with undef elements, just return a default NaN.
4477   if (!In->isNaN())
4478     return ConstantFP::getNaN(In->getType());
4479
4480   // Propagate the existing NaN constant when possible.
4481   // TODO: Should we quiet a signaling NaN?
4482   return In;
4483 }
4484
4485 /// Perform folds that are common to any floating-point operation. This implies
4486 /// transforms based on undef/NaN because the operation itself makes no
4487 /// difference to the result.
4488 static Constant *simplifyFPOp(ArrayRef<Value *> Ops) {
4489   if (any_of(Ops, [](Value *V) { return isa<UndefValue>(V); }))
4490     return ConstantFP::getNaN(Ops[0]->getType());
4491
4492   for (Value *V : Ops)
4493     if (match(V, m_NaN()))
4494       return propagateNaN(cast<Constant>(V));
4495
4496   return nullptr;
4497 }
4498
4499 /// Given operands for an FAdd, see if we can fold the result.  If not, this
4500 /// returns null.
4501 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4502                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4503   if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4504     return C;
4505
4506   if (Constant *C = simplifyFPOp({Op0, Op1}))
4507     return C;
4508
4509   // fadd X, -0 ==> X
4510   if (match(Op1, m_NegZeroFP()))
4511     return Op0;
4512
4513   // fadd X, 0 ==> X, when we know X is not -0
4514   if (match(Op1, m_PosZeroFP()) &&
4515       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4516     return Op0;
4517
4518   // With nnan: -X + X --> 0.0 (and commuted variant)
4519   // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4520   // Negative zeros are allowed because we always end up with positive zero:
4521   // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4522   // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4523   // X =  0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4524   // X =  0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4525   if (FMF.noNaNs()) {
4526     if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4527         match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4528       return ConstantFP::getNullValue(Op0->getType());
4529
4530     if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4531         match(Op1, m_FNeg(m_Specific(Op0))))
4532       return ConstantFP::getNullValue(Op0->getType());
4533   }
4534
4535   // (X - Y) + Y --> X
4536   // Y + (X - Y) --> X
4537   Value *X;
4538   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4539       (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4540        match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4541     return X;
4542
4543   return nullptr;
4544 }
4545
4546 /// Given operands for an FSub, see if we can fold the result.  If not, this
4547 /// returns null.
4548 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4549                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4550   if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4551     return C;
4552
4553   if (Constant *C = simplifyFPOp({Op0, Op1}))
4554     return C;
4555
4556   // fsub X, +0 ==> X
4557   if (match(Op1, m_PosZeroFP()))
4558     return Op0;
4559
4560   // fsub X, -0 ==> X, when we know X is not -0
4561   if (match(Op1, m_NegZeroFP()) &&
4562       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4563     return Op0;
4564
4565   // fsub -0.0, (fsub -0.0, X) ==> X
4566   // fsub -0.0, (fneg X) ==> X
4567   Value *X;
4568   if (match(Op0, m_NegZeroFP()) &&
4569       match(Op1, m_FNeg(m_Value(X))))
4570     return X;
4571
4572   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4573   // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4574   if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4575       (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4576        match(Op1, m_FNeg(m_Value(X)))))
4577     return X;
4578
4579   // fsub nnan x, x ==> 0.0
4580   if (FMF.noNaNs() && Op0 == Op1)
4581     return Constant::getNullValue(Op0->getType());
4582
4583   // Y - (Y - X) --> X
4584   // (X + Y) - Y --> X
4585   if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4586       (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4587        match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4588     return X;
4589
4590   return nullptr;
4591 }
4592
4593 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4594                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4595   if (Constant *C = simplifyFPOp({Op0, Op1}))
4596     return C;
4597
4598   // fmul X, 1.0 ==> X
4599   if (match(Op1, m_FPOne()))
4600     return Op0;
4601
4602   // fmul 1.0, X ==> X
4603   if (match(Op0, m_FPOne()))
4604     return Op1;
4605
4606   // fmul nnan nsz X, 0 ==> 0
4607   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4608     return ConstantFP::getNullValue(Op0->getType());
4609
4610   // fmul nnan nsz 0, X ==> 0
4611   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4612     return ConstantFP::getNullValue(Op1->getType());
4613
4614   // sqrt(X) * sqrt(X) --> X, if we can:
4615   // 1. Remove the intermediate rounding (reassociate).
4616   // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4617   // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4618   Value *X;
4619   if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4620       FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4621     return X;
4622
4623   return nullptr;
4624 }
4625
4626 /// Given the operands for an FMul, see if we can fold the result
4627 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4628                                const SimplifyQuery &Q, unsigned MaxRecurse) {
4629   if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4630     return C;
4631
4632   // Now apply simplifications that do not require rounding.
4633   return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse);
4634 }
4635
4636 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4637                               const SimplifyQuery &Q) {
4638   return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4639 }
4640
4641
4642 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4643                               const SimplifyQuery &Q) {
4644   return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4645 }
4646
4647 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4648                               const SimplifyQuery &Q) {
4649   return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4650 }
4651
4652 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
4653                              const SimplifyQuery &Q) {
4654   return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit);
4655 }
4656
4657 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4658                                const SimplifyQuery &Q, unsigned) {
4659   if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4660     return C;
4661
4662   if (Constant *C = simplifyFPOp({Op0, Op1}))
4663     return C;
4664
4665   // X / 1.0 -> X
4666   if (match(Op1, m_FPOne()))
4667     return Op0;
4668
4669   // 0 / X -> 0
4670   // Requires that NaNs are off (X could be zero) and signed zeroes are
4671   // ignored (X could be positive or negative, so the output sign is unknown).
4672   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4673     return ConstantFP::getNullValue(Op0->getType());
4674
4675   if (FMF.noNaNs()) {
4676     // X / X -> 1.0 is legal when NaNs are ignored.
4677     // We can ignore infinities because INF/INF is NaN.
4678     if (Op0 == Op1)
4679       return ConstantFP::get(Op0->getType(), 1.0);
4680
4681     // (X * Y) / Y --> X if we can reassociate to the above form.
4682     Value *X;
4683     if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4684       return X;
4685
4686     // -X /  X -> -1.0 and
4687     //  X / -X -> -1.0 are legal when NaNs are ignored.
4688     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4689     if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4690         match(Op1, m_FNegNSZ(m_Specific(Op0))))
4691       return ConstantFP::get(Op0->getType(), -1.0);
4692   }
4693
4694   return nullptr;
4695 }
4696
4697 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4698                               const SimplifyQuery &Q) {
4699   return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4700 }
4701
4702 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4703                                const SimplifyQuery &Q, unsigned) {
4704   if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4705     return C;
4706
4707   if (Constant *C = simplifyFPOp({Op0, Op1}))
4708     return C;
4709
4710   // Unlike fdiv, the result of frem always matches the sign of the dividend.
4711   // The constant match may include undef elements in a vector, so return a full
4712   // zero constant as the result.
4713   if (FMF.noNaNs()) {
4714     // +0 % X -> 0
4715     if (match(Op0, m_PosZeroFP()))
4716       return ConstantFP::getNullValue(Op0->getType());
4717     // -0 % X -> -0
4718     if (match(Op0, m_NegZeroFP()))
4719       return ConstantFP::getNegativeZero(Op0->getType());
4720   }
4721
4722   return nullptr;
4723 }
4724
4725 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4726                               const SimplifyQuery &Q) {
4727   return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4728 }
4729
4730 //=== Helper functions for higher up the class hierarchy.
4731
4732 /// Given the operand for a UnaryOperator, see if we can fold the result.
4733 /// If not, this returns null.
4734 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
4735                            unsigned MaxRecurse) {
4736   switch (Opcode) {
4737   case Instruction::FNeg:
4738     return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
4739   default:
4740     llvm_unreachable("Unexpected opcode");
4741   }
4742 }
4743
4744 /// Given the operand for a UnaryOperator, see if we can fold the result.
4745 /// If not, this returns null.
4746 /// Try to use FastMathFlags when folding the result.
4747 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
4748                              const FastMathFlags &FMF,
4749                              const SimplifyQuery &Q, unsigned MaxRecurse) {
4750   switch (Opcode) {
4751   case Instruction::FNeg:
4752     return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
4753   default:
4754     return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
4755   }
4756 }
4757
4758 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
4759   return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
4760 }
4761
4762 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
4763                           const SimplifyQuery &Q) {
4764   return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
4765 }
4766
4767 /// Given operands for a BinaryOperator, see if we can fold the result.
4768 /// If not, this returns null.
4769 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4770                             const SimplifyQuery &Q, unsigned MaxRecurse) {
4771   switch (Opcode) {
4772   case Instruction::Add:
4773     return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4774   case Instruction::Sub:
4775     return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4776   case Instruction::Mul:
4777     return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4778   case Instruction::SDiv:
4779     return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4780   case Instruction::UDiv:
4781     return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4782   case Instruction::SRem:
4783     return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4784   case Instruction::URem:
4785     return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4786   case Instruction::Shl:
4787     return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4788   case Instruction::LShr:
4789     return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4790   case Instruction::AShr:
4791     return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4792   case Instruction::And:
4793     return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4794   case Instruction::Or:
4795     return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4796   case Instruction::Xor:
4797     return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4798   case Instruction::FAdd:
4799     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4800   case Instruction::FSub:
4801     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4802   case Instruction::FMul:
4803     return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4804   case Instruction::FDiv:
4805     return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4806   case Instruction::FRem:
4807     return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4808   default:
4809     llvm_unreachable("Unexpected opcode");
4810   }
4811 }
4812
4813 /// Given operands for a BinaryOperator, see if we can fold the result.
4814 /// If not, this returns null.
4815 /// Try to use FastMathFlags when folding the result.
4816 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4817                             const FastMathFlags &FMF, const SimplifyQuery &Q,
4818                             unsigned MaxRecurse) {
4819   switch (Opcode) {
4820   case Instruction::FAdd:
4821     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4822   case Instruction::FSub:
4823     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4824   case Instruction::FMul:
4825     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4826   case Instruction::FDiv:
4827     return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
4828   default:
4829     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4830   }
4831 }
4832
4833 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4834                            const SimplifyQuery &Q) {
4835   return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4836 }
4837
4838 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4839                            FastMathFlags FMF, const SimplifyQuery &Q) {
4840   return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4841 }
4842
4843 /// Given operands for a CmpInst, see if we can fold the result.
4844 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4845                               const SimplifyQuery &Q, unsigned MaxRecurse) {
4846   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4847     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4848   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4849 }
4850
4851 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4852                              const SimplifyQuery &Q) {
4853   return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4854 }
4855
4856 static bool IsIdempotent(Intrinsic::ID ID) {
4857   switch (ID) {
4858   default: return false;
4859
4860   // Unary idempotent: f(f(x)) = f(x)
4861   case Intrinsic::fabs:
4862   case Intrinsic::floor:
4863   case Intrinsic::ceil:
4864   case Intrinsic::trunc:
4865   case Intrinsic::rint:
4866   case Intrinsic::nearbyint:
4867   case Intrinsic::round:
4868   case Intrinsic::canonicalize:
4869     return true;
4870   }
4871 }
4872
4873 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4874                                    const DataLayout &DL) {
4875   GlobalValue *PtrSym;
4876   APInt PtrOffset;
4877   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4878     return nullptr;
4879
4880   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4881   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4882   Type *Int32PtrTy = Int32Ty->getPointerTo();
4883   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4884
4885   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4886   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4887     return nullptr;
4888
4889   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4890   if (OffsetInt % 4 != 0)
4891     return nullptr;
4892
4893   Constant *C = ConstantExpr::getGetElementPtr(
4894       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4895       ConstantInt::get(Int64Ty, OffsetInt / 4));
4896   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4897   if (!Loaded)
4898     return nullptr;
4899
4900   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4901   if (!LoadedCE)
4902     return nullptr;
4903
4904   if (LoadedCE->getOpcode() == Instruction::Trunc) {
4905     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4906     if (!LoadedCE)
4907       return nullptr;
4908   }
4909
4910   if (LoadedCE->getOpcode() != Instruction::Sub)
4911     return nullptr;
4912
4913   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4914   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4915     return nullptr;
4916   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4917
4918   Constant *LoadedRHS = LoadedCE->getOperand(1);
4919   GlobalValue *LoadedRHSSym;
4920   APInt LoadedRHSOffset;
4921   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4922                                   DL) ||
4923       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4924     return nullptr;
4925
4926   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4927 }
4928
4929 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4930                                      const SimplifyQuery &Q) {
4931   // Idempotent functions return the same result when called repeatedly.
4932   Intrinsic::ID IID = F->getIntrinsicID();
4933   if (IsIdempotent(IID))
4934     if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4935       if (II->getIntrinsicID() == IID)
4936         return II;
4937
4938   Value *X;
4939   switch (IID) {
4940   case Intrinsic::fabs:
4941     if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4942     break;
4943   case Intrinsic::bswap:
4944     // bswap(bswap(x)) -> x
4945     if (match(Op0, m_BSwap(m_Value(X)))) return X;
4946     break;
4947   case Intrinsic::bitreverse:
4948     // bitreverse(bitreverse(x)) -> x
4949     if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4950     break;
4951   case Intrinsic::exp:
4952     // exp(log(x)) -> x
4953     if (Q.CxtI->hasAllowReassoc() &&
4954         match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4955     break;
4956   case Intrinsic::exp2:
4957     // exp2(log2(x)) -> x
4958     if (Q.CxtI->hasAllowReassoc() &&
4959         match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4960     break;
4961   case Intrinsic::log:
4962     // log(exp(x)) -> x
4963     if (Q.CxtI->hasAllowReassoc() &&
4964         match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4965     break;
4966   case Intrinsic::log2:
4967     // log2(exp2(x)) -> x
4968     if (Q.CxtI->hasAllowReassoc() &&
4969         (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4970          match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4971                                                 m_Value(X))))) return X;
4972     break;
4973   case Intrinsic::log10:
4974     // log10(pow(10.0, x)) -> x
4975     if (Q.CxtI->hasAllowReassoc() &&
4976         match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4977                                                m_Value(X)))) return X;
4978     break;
4979   case Intrinsic::floor:
4980   case Intrinsic::trunc:
4981   case Intrinsic::ceil:
4982   case Intrinsic::round:
4983   case Intrinsic::nearbyint:
4984   case Intrinsic::rint: {
4985     // floor (sitofp x) -> sitofp x
4986     // floor (uitofp x) -> uitofp x
4987     //
4988     // Converting from int always results in a finite integral number or
4989     // infinity. For either of those inputs, these rounding functions always
4990     // return the same value, so the rounding can be eliminated.
4991     if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
4992       return Op0;
4993     break;
4994   }
4995   default:
4996     break;
4997   }
4998
4999   return nullptr;
5000 }
5001
5002 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
5003                                       const SimplifyQuery &Q) {
5004   Intrinsic::ID IID = F->getIntrinsicID();
5005   Type *ReturnType = F->getReturnType();
5006   switch (IID) {
5007   case Intrinsic::usub_with_overflow:
5008   case Intrinsic::ssub_with_overflow:
5009     // X - X -> { 0, false }
5010     if (Op0 == Op1)
5011       return Constant::getNullValue(ReturnType);
5012     LLVM_FALLTHROUGH;
5013   case Intrinsic::uadd_with_overflow:
5014   case Intrinsic::sadd_with_overflow:
5015     // X - undef -> { undef, false }
5016     // undef - X -> { undef, false }
5017     // X + undef -> { undef, false }
5018     // undef + x -> { undef, false }
5019     if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) {
5020       return ConstantStruct::get(
5021           cast<StructType>(ReturnType),
5022           {UndefValue::get(ReturnType->getStructElementType(0)),
5023            Constant::getNullValue(ReturnType->getStructElementType(1))});
5024     }
5025     break;
5026   case Intrinsic::umul_with_overflow:
5027   case Intrinsic::smul_with_overflow:
5028     // 0 * X -> { 0, false }
5029     // X * 0 -> { 0, false }
5030     if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
5031       return Constant::getNullValue(ReturnType);
5032     // undef * X -> { 0, false }
5033     // X * undef -> { 0, false }
5034     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5035       return Constant::getNullValue(ReturnType);
5036     break;
5037   case Intrinsic::uadd_sat:
5038     // sat(MAX + X) -> MAX
5039     // sat(X + MAX) -> MAX
5040     if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5041       return Constant::getAllOnesValue(ReturnType);
5042     LLVM_FALLTHROUGH;
5043   case Intrinsic::sadd_sat:
5044     // sat(X + undef) -> -1
5045     // sat(undef + X) -> -1
5046     // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5047     // For signed: Assume undef is ~X, in which case X + ~X = -1.
5048     if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5049       return Constant::getAllOnesValue(ReturnType);
5050
5051     // X + 0 -> X
5052     if (match(Op1, m_Zero()))
5053       return Op0;
5054     // 0 + X -> X
5055     if (match(Op0, m_Zero()))
5056       return Op1;
5057     break;
5058   case Intrinsic::usub_sat:
5059     // sat(0 - X) -> 0, sat(X - MAX) -> 0
5060     if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5061       return Constant::getNullValue(ReturnType);
5062     LLVM_FALLTHROUGH;
5063   case Intrinsic::ssub_sat:
5064     // X - X -> 0, X - undef -> 0, undef - X -> 0
5065     if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
5066       return Constant::getNullValue(ReturnType);
5067     // X - 0 -> X
5068     if (match(Op1, m_Zero()))
5069       return Op0;
5070     break;
5071   case Intrinsic::load_relative:
5072     if (auto *C0 = dyn_cast<Constant>(Op0))
5073       if (auto *C1 = dyn_cast<Constant>(Op1))
5074         return SimplifyRelativeLoad(C0, C1, Q.DL);
5075     break;
5076   case Intrinsic::powi:
5077     if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5078       // powi(x, 0) -> 1.0
5079       if (Power->isZero())
5080         return ConstantFP::get(Op0->getType(), 1.0);
5081       // powi(x, 1) -> x
5082       if (Power->isOne())
5083         return Op0;
5084     }
5085     break;
5086   case Intrinsic::maxnum:
5087   case Intrinsic::minnum:
5088   case Intrinsic::maximum:
5089   case Intrinsic::minimum: {
5090     // If the arguments are the same, this is a no-op.
5091     if (Op0 == Op1) return Op0;
5092
5093     // If one argument is undef, return the other argument.
5094     if (match(Op0, m_Undef()))
5095       return Op1;
5096     if (match(Op1, m_Undef()))
5097       return Op0;
5098
5099     // If one argument is NaN, return other or NaN appropriately.
5100     bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5101     if (match(Op0, m_NaN()))
5102       return PropagateNaN ? Op0 : Op1;
5103     if (match(Op1, m_NaN()))
5104       return PropagateNaN ? Op1 : Op0;
5105
5106     // Min/max of the same operation with common operand:
5107     // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5108     if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5109       if (M0->getIntrinsicID() == IID &&
5110           (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5111         return Op0;
5112     if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5113       if (M1->getIntrinsicID() == IID &&
5114           (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5115         return Op1;
5116
5117     // min(X, -Inf) --> -Inf (and commuted variant)
5118     // max(X, +Inf) --> +Inf (and commuted variant)
5119     bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
5120     const APFloat *C;
5121     if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
5122          C->isNegative() == UseNegInf) ||
5123         (match(Op1, m_APFloat(C)) && C->isInfinity() &&
5124          C->isNegative() == UseNegInf))
5125       return ConstantFP::getInfinity(ReturnType, UseNegInf);
5126
5127     // TODO: minnum(nnan x, inf) -> x
5128     // TODO: minnum(nnan ninf x, flt_max) -> x
5129     // TODO: maxnum(nnan x, -inf) -> x
5130     // TODO: maxnum(nnan ninf x, -flt_max) -> x
5131     break;
5132   }
5133   default:
5134     break;
5135   }
5136
5137   return nullptr;
5138 }
5139
5140 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
5141
5142   // Intrinsics with no operands have some kind of side effect. Don't simplify.
5143   unsigned NumOperands = Call->getNumArgOperands();
5144   if (!NumOperands)
5145     return nullptr;
5146
5147   Function *F = cast<Function>(Call->getCalledFunction());
5148   Intrinsic::ID IID = F->getIntrinsicID();
5149   if (NumOperands == 1)
5150     return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
5151
5152   if (NumOperands == 2)
5153     return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
5154                                    Call->getArgOperand(1), Q);
5155
5156   // Handle intrinsics with 3 or more arguments.
5157   switch (IID) {
5158   case Intrinsic::masked_load:
5159   case Intrinsic::masked_gather: {
5160     Value *MaskArg = Call->getArgOperand(2);
5161     Value *PassthruArg = Call->getArgOperand(3);
5162     // If the mask is all zeros or undef, the "passthru" argument is the result.
5163     if (maskIsAllZeroOrUndef(MaskArg))
5164       return PassthruArg;
5165     return nullptr;
5166   }
5167   case Intrinsic::fshl:
5168   case Intrinsic::fshr: {
5169     Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
5170           *ShAmtArg = Call->getArgOperand(2);
5171
5172     // If both operands are undef, the result is undef.
5173     if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
5174       return UndefValue::get(F->getReturnType());
5175
5176     // If shift amount is undef, assume it is zero.
5177     if (match(ShAmtArg, m_Undef()))
5178       return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5179
5180     const APInt *ShAmtC;
5181     if (match(ShAmtArg, m_APInt(ShAmtC))) {
5182       // If there's effectively no shift, return the 1st arg or 2nd arg.
5183       APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5184       if (ShAmtC->urem(BitWidth).isNullValue())
5185         return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
5186     }
5187     return nullptr;
5188   }
5189   case Intrinsic::fma:
5190   case Intrinsic::fmuladd: {
5191     Value *Op0 = Call->getArgOperand(0);
5192     Value *Op1 = Call->getArgOperand(1);
5193     Value *Op2 = Call->getArgOperand(2);
5194     if (Value *V = simplifyFPOp({ Op0, Op1, Op2 }))
5195       return V;
5196     return nullptr;
5197   }
5198   default:
5199     return nullptr;
5200   }
5201 }
5202
5203 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5204   Value *Callee = Call->getCalledValue();
5205
5206   // call undef -> undef
5207   // call null -> undef
5208   if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
5209     return UndefValue::get(Call->getType());
5210
5211   Function *F = dyn_cast<Function>(Callee);
5212   if (!F)
5213     return nullptr;
5214
5215   if (F->isIntrinsic())
5216     if (Value *Ret = simplifyIntrinsic(Call, Q))
5217       return Ret;
5218
5219   if (!canConstantFoldCallTo(Call, F))
5220     return nullptr;
5221
5222   SmallVector<Constant *, 4> ConstantArgs;
5223   unsigned NumArgs = Call->getNumArgOperands();
5224   ConstantArgs.reserve(NumArgs);
5225   for (auto &Arg : Call->args()) {
5226     Constant *C = dyn_cast<Constant>(&Arg);
5227     if (!C)
5228       return nullptr;
5229     ConstantArgs.push_back(C);
5230   }
5231
5232   return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5233 }
5234
5235 /// See if we can compute a simplified version of this instruction.
5236 /// If not, this returns null.
5237
5238 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5239                                  OptimizationRemarkEmitter *ORE) {
5240   const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5241   Value *Result;
5242
5243   switch (I->getOpcode()) {
5244   default:
5245     Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5246     break;
5247   case Instruction::FNeg:
5248     Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5249     break;
5250   case Instruction::FAdd:
5251     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5252                               I->getFastMathFlags(), Q);
5253     break;
5254   case Instruction::Add:
5255     Result =
5256         SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5257                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5258                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5259     break;
5260   case Instruction::FSub:
5261     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5262                               I->getFastMathFlags(), Q);
5263     break;
5264   case Instruction::Sub:
5265     Result =
5266         SimplifySubInst(I->getOperand(0), I->getOperand(1),
5267                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5268                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5269     break;
5270   case Instruction::FMul:
5271     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5272                               I->getFastMathFlags(), Q);
5273     break;
5274   case Instruction::Mul:
5275     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5276     break;
5277   case Instruction::SDiv:
5278     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5279     break;
5280   case Instruction::UDiv:
5281     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5282     break;
5283   case Instruction::FDiv:
5284     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5285                               I->getFastMathFlags(), Q);
5286     break;
5287   case Instruction::SRem:
5288     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5289     break;
5290   case Instruction::URem:
5291     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5292     break;
5293   case Instruction::FRem:
5294     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5295                               I->getFastMathFlags(), Q);
5296     break;
5297   case Instruction::Shl:
5298     Result =
5299         SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5300                         Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5301                         Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5302     break;
5303   case Instruction::LShr:
5304     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5305                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5306     break;
5307   case Instruction::AShr:
5308     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5309                               Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5310     break;
5311   case Instruction::And:
5312     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5313     break;
5314   case Instruction::Or:
5315     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5316     break;
5317   case Instruction::Xor:
5318     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5319     break;
5320   case Instruction::ICmp:
5321     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5322                               I->getOperand(0), I->getOperand(1), Q);
5323     break;
5324   case Instruction::FCmp:
5325     Result =
5326         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5327                          I->getOperand(1), I->getFastMathFlags(), Q);
5328     break;
5329   case Instruction::Select:
5330     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5331                                 I->getOperand(2), Q);
5332     break;
5333   case Instruction::GetElementPtr: {
5334     SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
5335     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5336                              Ops, Q);
5337     break;
5338   }
5339   case Instruction::InsertValue: {
5340     InsertValueInst *IV = cast<InsertValueInst>(I);
5341     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5342                                      IV->getInsertedValueOperand(),
5343                                      IV->getIndices(), Q);
5344     break;
5345   }
5346   case Instruction::InsertElement: {
5347     auto *IE = cast<InsertElementInst>(I);
5348     Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5349                                        IE->getOperand(2), Q);
5350     break;
5351   }
5352   case Instruction::ExtractValue: {
5353     auto *EVI = cast<ExtractValueInst>(I);
5354     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5355                                       EVI->getIndices(), Q);
5356     break;
5357   }
5358   case Instruction::ExtractElement: {
5359     auto *EEI = cast<ExtractElementInst>(I);
5360     Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5361                                         EEI->getIndexOperand(), Q);
5362     break;
5363   }
5364   case Instruction::ShuffleVector: {
5365     auto *SVI = cast<ShuffleVectorInst>(I);
5366     Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5367                                        SVI->getMask(), SVI->getType(), Q);
5368     break;
5369   }
5370   case Instruction::PHI:
5371     Result = SimplifyPHINode(cast<PHINode>(I), Q);
5372     break;
5373   case Instruction::Call: {
5374     Result = SimplifyCall(cast<CallInst>(I), Q);
5375     break;
5376   }
5377 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5378 #include "llvm/IR/Instruction.def"
5379 #undef HANDLE_CAST_INST
5380     Result =
5381         SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5382     break;
5383   case Instruction::Alloca:
5384     // No simplifications for Alloca and it can't be constant folded.
5385     Result = nullptr;
5386     break;
5387   }
5388
5389   // In general, it is possible for computeKnownBits to determine all bits in a
5390   // value even when the operands are not all constants.
5391   if (!Result && I->getType()->isIntOrIntVectorTy()) {
5392     KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
5393     if (Known.isConstant())
5394       Result = ConstantInt::get(I->getType(), Known.getConstant());
5395   }
5396
5397   /// If called on unreachable code, the above logic may report that the
5398   /// instruction simplified to itself.  Make life easier for users by
5399   /// detecting that case here, returning a safe value instead.
5400   return Result == I ? UndefValue::get(I->getType()) : Result;
5401 }
5402
5403 /// Implementation of recursive simplification through an instruction's
5404 /// uses.
5405 ///
5406 /// This is the common implementation of the recursive simplification routines.
5407 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5408 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5409 /// instructions to process and attempt to simplify it using
5410 /// InstructionSimplify. Recursively visited users which could not be
5411 /// simplified themselves are to the optional UnsimplifiedUsers set for
5412 /// further processing by the caller.
5413 ///
5414 /// This routine returns 'true' only when *it* simplifies something. The passed
5415 /// in simplified value does not count toward this.
5416 static bool replaceAndRecursivelySimplifyImpl(
5417     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
5418     const DominatorTree *DT, AssumptionCache *AC,
5419     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
5420   bool Simplified = false;
5421   SmallSetVector<Instruction *, 8> Worklist;
5422   const DataLayout &DL = I->getModule()->getDataLayout();
5423
5424   // If we have an explicit value to collapse to, do that round of the
5425   // simplification loop by hand initially.
5426   if (SimpleV) {
5427     for (User *U : I->users())
5428       if (U != I)
5429         Worklist.insert(cast<Instruction>(U));
5430
5431     // Replace the instruction with its simplified value.
5432     I->replaceAllUsesWith(SimpleV);
5433
5434     // Gracefully handle edge cases where the instruction is not wired into any
5435     // parent block.
5436     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5437         !I->mayHaveSideEffects())
5438       I->eraseFromParent();
5439   } else {
5440     Worklist.insert(I);
5441   }
5442
5443   // Note that we must test the size on each iteration, the worklist can grow.
5444   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5445     I = Worklist[Idx];
5446
5447     // See if this instruction simplifies.
5448     SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
5449     if (!SimpleV) {
5450       if (UnsimplifiedUsers)
5451         UnsimplifiedUsers->insert(I);
5452       continue;
5453     }
5454
5455     Simplified = true;
5456
5457     // Stash away all the uses of the old instruction so we can check them for
5458     // recursive simplifications after a RAUW. This is cheaper than checking all
5459     // uses of To on the recursive step in most cases.
5460     for (User *U : I->users())
5461       Worklist.insert(cast<Instruction>(U));
5462
5463     // Replace the instruction with its simplified value.
5464     I->replaceAllUsesWith(SimpleV);
5465
5466     // Gracefully handle edge cases where the instruction is not wired into any
5467     // parent block.
5468     if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5469         !I->mayHaveSideEffects())
5470       I->eraseFromParent();
5471   }
5472   return Simplified;
5473 }
5474
5475 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5476                                           const TargetLibraryInfo *TLI,
5477                                           const DominatorTree *DT,
5478                                           AssumptionCache *AC) {
5479   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC, nullptr);
5480 }
5481
5482 bool llvm::replaceAndRecursivelySimplify(
5483     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
5484     const DominatorTree *DT, AssumptionCache *AC,
5485     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
5486   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5487   assert(SimpleV && "Must provide a simplified value.");
5488   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
5489                                            UnsimplifiedUsers);
5490 }
5491
5492 namespace llvm {
5493 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5494   auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5495   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5496   auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5497   auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
5498   auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5499   auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5500   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5501 }
5502
5503 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5504                                          const DataLayout &DL) {
5505   return {DL, &AR.TLI, &AR.DT, &AR.AC};
5506 }
5507
5508 template <class T, class... TArgs>
5509 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5510                                          Function &F) {
5511   auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5512   auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5513   auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5514   return {F.getParent()->getDataLayout(), TLI, DT, AC};
5515 }
5516 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5517                                                   Function &);
5518 }