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