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