R600: Implement ComputeNumSignBitsForTargetNode for BFE
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
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 contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/GlobalAlias.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/MathExtras.h"
33 #include <cstring>
34 using namespace llvm;
35 using namespace llvm::PatternMatch;
36
37 const unsigned MaxDepth = 6;
38
39 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
40 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
41 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
42   if (unsigned BitWidth = Ty->getScalarSizeInBits())
43     return BitWidth;
44
45   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
46 }
47
48 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
49                                    APInt &KnownZero, APInt &KnownOne,
50                                    APInt &KnownZero2, APInt &KnownOne2,
51                                    const DataLayout *TD, unsigned Depth) {
52   if (!Add) {
53     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
54       // We know that the top bits of C-X are clear if X contains less bits
55       // than C (i.e. no wrap-around can happen).  For example, 20-X is
56       // positive if we can prove that X is >= 0 and < 16.
57       if (!CLHS->getValue().isNegative()) {
58         unsigned BitWidth = KnownZero.getBitWidth();
59         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
60         // NLZ can't be BitWidth with no sign bit
61         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
62         llvm::computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
63
64         // If all of the MaskV bits are known to be zero, then we know the
65         // output top bits are zero, because we now know that the output is
66         // from [0-C].
67         if ((KnownZero2 & MaskV) == MaskV) {
68           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
69           // Top bits known zero.
70           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
71         }
72       }
73     }
74   }
75
76   unsigned BitWidth = KnownZero.getBitWidth();
77
78   // If one of the operands has trailing zeros, then the bits that the
79   // other operand has in those bit positions will be preserved in the
80   // result. For an add, this works with either operand. For a subtract,
81   // this only works if the known zeros are in the right operand.
82   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
83   llvm::computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1);
84   unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
85
86   llvm::computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
87   unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
88
89   // Determine which operand has more trailing zeros, and use that
90   // many bits from the other operand.
91   if (LHSKnownZeroOut > RHSKnownZeroOut) {
92     if (Add) {
93       APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
94       KnownZero |= KnownZero2 & Mask;
95       KnownOne  |= KnownOne2 & Mask;
96     } else {
97       // If the known zeros are in the left operand for a subtract,
98       // fall back to the minimum known zeros in both operands.
99       KnownZero |= APInt::getLowBitsSet(BitWidth,
100                                         std::min(LHSKnownZeroOut,
101                                                  RHSKnownZeroOut));
102     }
103   } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
104     APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
105     KnownZero |= LHSKnownZero & Mask;
106     KnownOne  |= LHSKnownOne & Mask;
107   }
108
109   // Are we still trying to solve for the sign bit?
110   if (!KnownZero.isNegative() && !KnownOne.isNegative()) {
111     if (NSW) {
112       if (Add) {
113         // Adding two positive numbers can't wrap into negative
114         if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
115           KnownZero |= APInt::getSignBit(BitWidth);
116         // and adding two negative numbers can't wrap into positive.
117         else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
118           KnownOne |= APInt::getSignBit(BitWidth);
119       } else {
120         // Subtracting a negative number from a positive one can't wrap
121         if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
122           KnownZero |= APInt::getSignBit(BitWidth);
123         // neither can subtracting a positive number from a negative one.
124         else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
125           KnownOne |= APInt::getSignBit(BitWidth);
126       }
127     }
128   }
129 }
130
131 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
132                                 APInt &KnownZero, APInt &KnownOne,
133                                 APInt &KnownZero2, APInt &KnownOne2,
134                                 const DataLayout *TD, unsigned Depth) {
135   unsigned BitWidth = KnownZero.getBitWidth();
136   computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1);
137   computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1);
138
139   bool isKnownNegative = false;
140   bool isKnownNonNegative = false;
141   // If the multiplication is known not to overflow, compute the sign bit.
142   if (NSW) {
143     if (Op0 == Op1) {
144       // The product of a number with itself is non-negative.
145       isKnownNonNegative = true;
146     } else {
147       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
148       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
149       bool isKnownNegativeOp1 = KnownOne.isNegative();
150       bool isKnownNegativeOp0 = KnownOne2.isNegative();
151       // The product of two numbers with the same sign is non-negative.
152       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
153         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
154       // The product of a negative number and a non-negative number is either
155       // negative or zero.
156       if (!isKnownNonNegative)
157         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
158                            isKnownNonZero(Op0, TD, Depth)) ||
159                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
160                            isKnownNonZero(Op1, TD, Depth));
161     }
162   }
163
164   // If low bits are zero in either operand, output low known-0 bits.
165   // Also compute a conserative estimate for high known-0 bits.
166   // More trickiness is possible, but this is sufficient for the
167   // interesting case of alignment computation.
168   KnownOne.clearAllBits();
169   unsigned TrailZ = KnownZero.countTrailingOnes() +
170                     KnownZero2.countTrailingOnes();
171   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
172                              KnownZero2.countLeadingOnes(),
173                              BitWidth) - BitWidth;
174
175   TrailZ = std::min(TrailZ, BitWidth);
176   LeadZ = std::min(LeadZ, BitWidth);
177   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
178               APInt::getHighBitsSet(BitWidth, LeadZ);
179
180   // Only make use of no-wrap flags if we failed to compute the sign bit
181   // directly.  This matters if the multiplication always overflows, in
182   // which case we prefer to follow the result of the direct computation,
183   // though as the program is invoking undefined behaviour we can choose
184   // whatever we like here.
185   if (isKnownNonNegative && !KnownOne.isNegative())
186     KnownZero.setBit(BitWidth - 1);
187   else if (isKnownNegative && !KnownZero.isNegative())
188     KnownOne.setBit(BitWidth - 1);
189 }
190
191 void llvm::computeKnownBitsLoad(const MDNode &Ranges, APInt &KnownZero) {
192   unsigned BitWidth = KnownZero.getBitWidth();
193   unsigned NumRanges = Ranges.getNumOperands() / 2;
194   assert(NumRanges >= 1);
195
196   // Use the high end of the ranges to find leading zeros.
197   unsigned MinLeadingZeros = BitWidth;
198   for (unsigned i = 0; i < NumRanges; ++i) {
199     ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
200     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
201     ConstantRange Range(Lower->getValue(), Upper->getValue());
202     if (Range.isWrappedSet())
203       MinLeadingZeros = 0; // -1 has no zeros
204     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
205     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
206   }
207
208   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
209 }
210
211 /// Determine which bits of V are known to be either zero or one and return
212 /// them in the KnownZero/KnownOne bit sets.
213 ///
214 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
215 /// we cannot optimize based on the assumption that it is zero without changing
216 /// it to be an explicit zero.  If we don't change it to zero, other code could
217 /// optimized based on the contradictory assumption that it is non-zero.
218 /// Because instcombine aggressively folds operations with undef args anyway,
219 /// this won't lose us code quality.
220 ///
221 /// This function is defined on values with integer type, values with pointer
222 /// type (but only if TD is non-null), and vectors of integers.  In the case
223 /// where V is a vector, known zero, and known one values are the
224 /// same width as the vector element, and the bit is set only if it is true
225 /// for all of the elements in the vector.
226 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
227                             const DataLayout *TD, unsigned Depth) {
228   assert(V && "No Value?");
229   assert(Depth <= MaxDepth && "Limit Search Depth");
230   unsigned BitWidth = KnownZero.getBitWidth();
231
232   assert((V->getType()->isIntOrIntVectorTy() ||
233           V->getType()->getScalarType()->isPointerTy()) &&
234          "Not integer or pointer type!");
235   assert((!TD ||
236           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
237          (!V->getType()->isIntOrIntVectorTy() ||
238           V->getType()->getScalarSizeInBits() == BitWidth) &&
239          KnownZero.getBitWidth() == BitWidth &&
240          KnownOne.getBitWidth() == BitWidth &&
241          "V, KnownOne and KnownZero should have same BitWidth");
242
243   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
244     // We know all of the bits for a constant!
245     KnownOne = CI->getValue();
246     KnownZero = ~KnownOne;
247     return;
248   }
249   // Null and aggregate-zero are all-zeros.
250   if (isa<ConstantPointerNull>(V) ||
251       isa<ConstantAggregateZero>(V)) {
252     KnownOne.clearAllBits();
253     KnownZero = APInt::getAllOnesValue(BitWidth);
254     return;
255   }
256   // Handle a constant vector by taking the intersection of the known bits of
257   // each element.  There is no real need to handle ConstantVector here, because
258   // we don't handle undef in any particularly useful way.
259   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
260     // We know that CDS must be a vector of integers. Take the intersection of
261     // each element.
262     KnownZero.setAllBits(); KnownOne.setAllBits();
263     APInt Elt(KnownZero.getBitWidth(), 0);
264     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
265       Elt = CDS->getElementAsInteger(i);
266       KnownZero &= ~Elt;
267       KnownOne &= Elt;
268     }
269     return;
270   }
271
272   // The address of an aligned GlobalValue has trailing zeros.
273   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
274     unsigned Align = GV->getAlignment();
275     if (Align == 0 && TD) {
276       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
277         Type *ObjectType = GVar->getType()->getElementType();
278         if (ObjectType->isSized()) {
279           // If the object is defined in the current Module, we'll be giving
280           // it the preferred alignment. Otherwise, we have to assume that it
281           // may only have the minimum ABI alignment.
282           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
283             Align = TD->getPreferredAlignment(GVar);
284           else
285             Align = TD->getABITypeAlignment(ObjectType);
286         }
287       }
288     }
289     if (Align > 0)
290       KnownZero = APInt::getLowBitsSet(BitWidth,
291                                        countTrailingZeros(Align));
292     else
293       KnownZero.clearAllBits();
294     KnownOne.clearAllBits();
295     return;
296   }
297   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
298   // the bits of its aliasee.
299   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
300     if (GA->mayBeOverridden()) {
301       KnownZero.clearAllBits(); KnownOne.clearAllBits();
302     } else {
303       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1);
304     }
305     return;
306   }
307
308   if (Argument *A = dyn_cast<Argument>(V)) {
309     unsigned Align = 0;
310
311     if (A->hasByValOrInAllocaAttr()) {
312       // Get alignment information off byval/inalloca arguments if specified in
313       // the IR.
314       Align = A->getParamAlignment();
315     } else if (TD && A->hasStructRetAttr()) {
316       // An sret parameter has at least the ABI alignment of the return type.
317       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
318       if (EltTy->isSized())
319         Align = TD->getABITypeAlignment(EltTy);
320     }
321
322     if (Align)
323       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
324     return;
325   }
326
327   // Start out not knowing anything.
328   KnownZero.clearAllBits(); KnownOne.clearAllBits();
329
330   if (Depth == MaxDepth)
331     return;  // Limit search depth.
332
333   Operator *I = dyn_cast<Operator>(V);
334   if (!I) return;
335
336   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
337   switch (I->getOpcode()) {
338   default: break;
339   case Instruction::Load:
340     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
341       computeKnownBitsLoad(*MD, KnownZero);
342     break;
343   case Instruction::And: {
344     // If either the LHS or the RHS are Zero, the result is zero.
345     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
346     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
347
348     // Output known-1 bits are only known if set in both the LHS & RHS.
349     KnownOne &= KnownOne2;
350     // Output known-0 are known to be clear if zero in either the LHS | RHS.
351     KnownZero |= KnownZero2;
352     break;
353   }
354   case Instruction::Or: {
355     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
356     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
357
358     // Output known-0 bits are only known if clear in both the LHS & RHS.
359     KnownZero &= KnownZero2;
360     // Output known-1 are known to be set if set in either the LHS | RHS.
361     KnownOne |= KnownOne2;
362     break;
363   }
364   case Instruction::Xor: {
365     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
366     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
367
368     // Output known-0 bits are known if clear or set in both the LHS & RHS.
369     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
370     // Output known-1 are known to be set if set in only one of the LHS, RHS.
371     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
372     KnownZero = KnownZeroOut;
373     break;
374   }
375   case Instruction::Mul: {
376     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
377     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
378                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD, Depth);
379     break;
380   }
381   case Instruction::UDiv: {
382     // For the purposes of computing leading zeros we can conservatively
383     // treat a udiv as a logical right shift by the power of 2 known to
384     // be less than the denominator.
385     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
386     unsigned LeadZ = KnownZero2.countLeadingOnes();
387
388     KnownOne2.clearAllBits();
389     KnownZero2.clearAllBits();
390     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1);
391     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
392     if (RHSUnknownLeadingOnes != BitWidth)
393       LeadZ = std::min(BitWidth,
394                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
395
396     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
397     break;
398   }
399   case Instruction::Select:
400     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1);
401     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD,
402                       Depth+1);
403
404     // Only known if known in both the LHS and RHS.
405     KnownOne &= KnownOne2;
406     KnownZero &= KnownZero2;
407     break;
408   case Instruction::FPTrunc:
409   case Instruction::FPExt:
410   case Instruction::FPToUI:
411   case Instruction::FPToSI:
412   case Instruction::SIToFP:
413   case Instruction::UIToFP:
414     break; // Can't work with floating point.
415   case Instruction::PtrToInt:
416   case Instruction::IntToPtr:
417     // We can't handle these if we don't know the pointer size.
418     if (!TD) break;
419     // FALL THROUGH and handle them the same as zext/trunc.
420   case Instruction::ZExt:
421   case Instruction::Trunc: {
422     Type *SrcTy = I->getOperand(0)->getType();
423
424     unsigned SrcBitWidth;
425     // Note that we handle pointer operands here because of inttoptr/ptrtoint
426     // which fall through here.
427     if(TD) {
428       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
429     } else {
430       SrcBitWidth = SrcTy->getScalarSizeInBits();
431       if (!SrcBitWidth) break;
432     }
433
434     assert(SrcBitWidth && "SrcBitWidth can't be zero");
435     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
436     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
437     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
438     KnownZero = KnownZero.zextOrTrunc(BitWidth);
439     KnownOne = KnownOne.zextOrTrunc(BitWidth);
440     // Any top bits are known to be zero.
441     if (BitWidth > SrcBitWidth)
442       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
443     break;
444   }
445   case Instruction::BitCast: {
446     Type *SrcTy = I->getOperand(0)->getType();
447     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
448         // TODO: For now, not handling conversions like:
449         // (bitcast i64 %x to <2 x i32>)
450         !I->getType()->isVectorTy()) {
451       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
452       break;
453     }
454     break;
455   }
456   case Instruction::SExt: {
457     // Compute the bits in the result that are not present in the input.
458     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
459
460     KnownZero = KnownZero.trunc(SrcBitWidth);
461     KnownOne = KnownOne.trunc(SrcBitWidth);
462     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
463     KnownZero = KnownZero.zext(BitWidth);
464     KnownOne = KnownOne.zext(BitWidth);
465
466     // If the sign bit of the input is known set or clear, then we know the
467     // top bits of the result.
468     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
469       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
470     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
471       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
472     break;
473   }
474   case Instruction::Shl:
475     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
476     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
477       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
478       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
479       KnownZero <<= ShiftAmt;
480       KnownOne  <<= ShiftAmt;
481       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
482       break;
483     }
484     break;
485   case Instruction::LShr:
486     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
487     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
488       // Compute the new bits that are at the top now.
489       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
490
491       // Unsigned shift right.
492       computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1);
493       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
494       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
495       // high bits known zero.
496       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
497       break;
498     }
499     break;
500   case Instruction::AShr:
501     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
502     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
503       // Compute the new bits that are at the top now.
504       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
505
506       // Signed shift right.
507       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
508       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
509       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
510
511       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
512       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
513         KnownZero |= HighBits;
514       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
515         KnownOne |= HighBits;
516       break;
517     }
518     break;
519   case Instruction::Sub: {
520     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
521     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
522                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
523                             Depth);
524     break;
525   }
526   case Instruction::Add: {
527     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
528     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
529                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
530                             Depth);
531     break;
532   }
533   case Instruction::SRem:
534     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
535       APInt RA = Rem->getValue().abs();
536       if (RA.isPowerOf2()) {
537         APInt LowBits = RA - 1;
538         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
539
540         // The low bits of the first operand are unchanged by the srem.
541         KnownZero = KnownZero2 & LowBits;
542         KnownOne = KnownOne2 & LowBits;
543
544         // If the first operand is non-negative or has all low bits zero, then
545         // the upper bits are all zero.
546         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
547           KnownZero |= ~LowBits;
548
549         // If the first operand is negative and not all low bits are zero, then
550         // the upper bits are all one.
551         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
552           KnownOne |= ~LowBits;
553
554         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
555       }
556     }
557
558     // The sign bit is the LHS's sign bit, except when the result of the
559     // remainder is zero.
560     if (KnownZero.isNonNegative()) {
561       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
562       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
563                        Depth+1);
564       // If it's known zero, our sign bit is also zero.
565       if (LHSKnownZero.isNegative())
566         KnownZero.setBit(BitWidth - 1);
567     }
568
569     break;
570   case Instruction::URem: {
571     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
572       APInt RA = Rem->getValue();
573       if (RA.isPowerOf2()) {
574         APInt LowBits = (RA - 1);
575         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
576                          Depth+1);
577         KnownZero |= ~LowBits;
578         KnownOne &= LowBits;
579         break;
580       }
581     }
582
583     // Since the result is less than or equal to either operand, any leading
584     // zero bits in either operand must also exist in the result.
585     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
586     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1);
587
588     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
589                                 KnownZero2.countLeadingOnes());
590     KnownOne.clearAllBits();
591     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
592     break;
593   }
594
595   case Instruction::Alloca: {
596     AllocaInst *AI = cast<AllocaInst>(V);
597     unsigned Align = AI->getAlignment();
598     if (Align == 0 && TD)
599       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
600
601     if (Align > 0)
602       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
603     break;
604   }
605   case Instruction::GetElementPtr: {
606     // Analyze all of the subscripts of this getelementptr instruction
607     // to determine if we can prove known low zero bits.
608     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
609     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
610                      Depth+1);
611     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
612
613     gep_type_iterator GTI = gep_type_begin(I);
614     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
615       Value *Index = I->getOperand(i);
616       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
617         // Handle struct member offset arithmetic.
618         if (!TD) {
619           TrailZ = 0;
620           break;
621         }
622
623         // Handle case when index is vector zeroinitializer
624         Constant *CIndex = cast<Constant>(Index);
625         if (CIndex->isZeroValue())
626           continue;
627
628         if (CIndex->getType()->isVectorTy())
629           Index = CIndex->getSplatValue();
630
631         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
632         const StructLayout *SL = TD->getStructLayout(STy);
633         uint64_t Offset = SL->getElementOffset(Idx);
634         TrailZ = std::min<unsigned>(TrailZ,
635                                     countTrailingZeros(Offset));
636       } else {
637         // Handle array index arithmetic.
638         Type *IndexedTy = GTI.getIndexedType();
639         if (!IndexedTy->isSized()) {
640           TrailZ = 0;
641           break;
642         }
643         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
644         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
645         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
646         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1);
647         TrailZ = std::min(TrailZ,
648                           unsigned(countTrailingZeros(TypeSize) +
649                                    LocalKnownZero.countTrailingOnes()));
650       }
651     }
652
653     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
654     break;
655   }
656   case Instruction::PHI: {
657     PHINode *P = cast<PHINode>(I);
658     // Handle the case of a simple two-predecessor recurrence PHI.
659     // There's a lot more that could theoretically be done here, but
660     // this is sufficient to catch some interesting cases.
661     if (P->getNumIncomingValues() == 2) {
662       for (unsigned i = 0; i != 2; ++i) {
663         Value *L = P->getIncomingValue(i);
664         Value *R = P->getIncomingValue(!i);
665         Operator *LU = dyn_cast<Operator>(L);
666         if (!LU)
667           continue;
668         unsigned Opcode = LU->getOpcode();
669         // Check for operations that have the property that if
670         // both their operands have low zero bits, the result
671         // will have low zero bits.
672         if (Opcode == Instruction::Add ||
673             Opcode == Instruction::Sub ||
674             Opcode == Instruction::And ||
675             Opcode == Instruction::Or ||
676             Opcode == Instruction::Mul) {
677           Value *LL = LU->getOperand(0);
678           Value *LR = LU->getOperand(1);
679           // Find a recurrence.
680           if (LL == I)
681             L = LR;
682           else if (LR == I)
683             L = LL;
684           else
685             break;
686           // Ok, we have a PHI of the form L op= R. Check for low
687           // zero bits.
688           computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1);
689
690           // We need to take the minimum number of known bits
691           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
692           computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1);
693
694           KnownZero = APInt::getLowBitsSet(BitWidth,
695                                            std::min(KnownZero2.countTrailingOnes(),
696                                                     KnownZero3.countTrailingOnes()));
697           break;
698         }
699       }
700     }
701
702     // Unreachable blocks may have zero-operand PHI nodes.
703     if (P->getNumIncomingValues() == 0)
704       break;
705
706     // Otherwise take the unions of the known bit sets of the operands,
707     // taking conservative care to avoid excessive recursion.
708     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
709       // Skip if every incoming value references to ourself.
710       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
711         break;
712
713       KnownZero = APInt::getAllOnesValue(BitWidth);
714       KnownOne = APInt::getAllOnesValue(BitWidth);
715       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
716         // Skip direct self references.
717         if (P->getIncomingValue(i) == P) continue;
718
719         KnownZero2 = APInt(BitWidth, 0);
720         KnownOne2 = APInt(BitWidth, 0);
721         // Recurse, but cap the recursion to one level, because we don't
722         // want to waste time spinning around in loops.
723         computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
724                          MaxDepth-1);
725         KnownZero &= KnownZero2;
726         KnownOne &= KnownOne2;
727         // If all bits have been ruled out, there's no need to check
728         // more operands.
729         if (!KnownZero && !KnownOne)
730           break;
731       }
732     }
733     break;
734   }
735   case Instruction::Call:
736     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
737       switch (II->getIntrinsicID()) {
738       default: break;
739       case Intrinsic::ctlz:
740       case Intrinsic::cttz: {
741         unsigned LowBits = Log2_32(BitWidth)+1;
742         // If this call is undefined for 0, the result will be less than 2^n.
743         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
744           LowBits -= 1;
745         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
746         break;
747       }
748       case Intrinsic::ctpop: {
749         unsigned LowBits = Log2_32(BitWidth)+1;
750         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
751         break;
752       }
753       case Intrinsic::x86_sse42_crc32_64_64:
754         KnownZero = APInt::getHighBitsSet(64, 32);
755         break;
756       }
757     }
758     break;
759   case Instruction::ExtractValue:
760     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
761       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
762       if (EVI->getNumIndices() != 1) break;
763       if (EVI->getIndices()[0] == 0) {
764         switch (II->getIntrinsicID()) {
765         default: break;
766         case Intrinsic::uadd_with_overflow:
767         case Intrinsic::sadd_with_overflow:
768           computeKnownBitsAddSub(true, II->getArgOperand(0),
769                                  II->getArgOperand(1), false, KnownZero,
770                                  KnownOne, KnownZero2, KnownOne2, TD, Depth);
771           break;
772         case Intrinsic::usub_with_overflow:
773         case Intrinsic::ssub_with_overflow:
774           computeKnownBitsAddSub(false, II->getArgOperand(0),
775                                  II->getArgOperand(1), false, KnownZero,
776                                  KnownOne, KnownZero2, KnownOne2, TD, Depth);
777           break;
778         case Intrinsic::umul_with_overflow:
779         case Intrinsic::smul_with_overflow:
780           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
781                               false, KnownZero, KnownOne,
782                               KnownZero2, KnownOne2, TD, Depth);
783           break;
784         }
785       }
786     }
787   }
788
789   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
790 }
791
792 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
793 /// one.  Convenience wrapper around computeKnownBits.
794 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
795                           const DataLayout *TD, unsigned Depth) {
796   unsigned BitWidth = getBitWidth(V->getType(), TD);
797   if (!BitWidth) {
798     KnownZero = false;
799     KnownOne = false;
800     return;
801   }
802   APInt ZeroBits(BitWidth, 0);
803   APInt OneBits(BitWidth, 0);
804   computeKnownBits(V, ZeroBits, OneBits, TD, Depth);
805   KnownOne = OneBits[BitWidth - 1];
806   KnownZero = ZeroBits[BitWidth - 1];
807 }
808
809 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
810 /// bit set when defined. For vectors return true if every element is known to
811 /// be a power of two when defined.  Supports values with integer or pointer
812 /// types and vectors of integers.
813 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth) {
814   if (Constant *C = dyn_cast<Constant>(V)) {
815     if (C->isNullValue())
816       return OrZero;
817     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
818       return CI->getValue().isPowerOf2();
819     // TODO: Handle vector constants.
820   }
821
822   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
823   // it is shifted off the end then the result is undefined.
824   if (match(V, m_Shl(m_One(), m_Value())))
825     return true;
826
827   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
828   // bottom.  If it is shifted off the bottom then the result is undefined.
829   if (match(V, m_LShr(m_SignBit(), m_Value())))
830     return true;
831
832   // The remaining tests are all recursive, so bail out if we hit the limit.
833   if (Depth++ == MaxDepth)
834     return false;
835
836   Value *X = nullptr, *Y = nullptr;
837   // A shift of a power of two is a power of two or zero.
838   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
839                  match(V, m_Shr(m_Value(X), m_Value()))))
840     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth);
841
842   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
843     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth);
844
845   if (SelectInst *SI = dyn_cast<SelectInst>(V))
846     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth) &&
847       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth);
848
849   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
850     // A power of two and'd with anything is a power of two or zero.
851     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth) ||
852         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth))
853       return true;
854     // X & (-X) is always a power of two or zero.
855     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
856       return true;
857     return false;
858   }
859
860   // Adding a power-of-two or zero to the same power-of-two or zero yields
861   // either the original power-of-two, a larger power-of-two or zero.
862   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
863     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
864     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
865       if (match(X, m_And(m_Specific(Y), m_Value())) ||
866           match(X, m_And(m_Value(), m_Specific(Y))))
867         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth))
868           return true;
869       if (match(Y, m_And(m_Specific(X), m_Value())) ||
870           match(Y, m_And(m_Value(), m_Specific(X))))
871         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth))
872           return true;
873
874       unsigned BitWidth = V->getType()->getScalarSizeInBits();
875       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
876       computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth);
877
878       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
879       computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth);
880       // If i8 V is a power of two or zero:
881       //  ZeroBits: 1 1 1 0 1 1 1 1
882       // ~ZeroBits: 0 0 0 1 0 0 0 0
883       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
884         // If OrZero isn't set, we cannot give back a zero result.
885         // Make sure either the LHS or RHS has a bit set.
886         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
887           return true;
888     }
889   }
890
891   // An exact divide or right shift can only shift off zero bits, so the result
892   // is a power of two only if the first operand is a power of two and not
893   // copying a sign bit (sdiv int_min, 2).
894   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
895       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
896     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero, Depth);
897   }
898
899   return false;
900 }
901
902 /// \brief Test whether a GEP's result is known to be non-null.
903 ///
904 /// Uses properties inherent in a GEP to try to determine whether it is known
905 /// to be non-null.
906 ///
907 /// Currently this routine does not support vector GEPs.
908 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
909                               unsigned Depth) {
910   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
911     return false;
912
913   // FIXME: Support vector-GEPs.
914   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
915
916   // If the base pointer is non-null, we cannot walk to a null address with an
917   // inbounds GEP in address space zero.
918   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth))
919     return true;
920
921   // Past this, if we don't have DataLayout, we can't do much.
922   if (!DL)
923     return false;
924
925   // Walk the GEP operands and see if any operand introduces a non-zero offset.
926   // If so, then the GEP cannot produce a null pointer, as doing so would
927   // inherently violate the inbounds contract within address space zero.
928   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
929        GTI != GTE; ++GTI) {
930     // Struct types are easy -- they must always be indexed by a constant.
931     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
932       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
933       unsigned ElementIdx = OpC->getZExtValue();
934       const StructLayout *SL = DL->getStructLayout(STy);
935       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
936       if (ElementOffset > 0)
937         return true;
938       continue;
939     }
940
941     // If we have a zero-sized type, the index doesn't matter. Keep looping.
942     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
943       continue;
944
945     // Fast path the constant operand case both for efficiency and so we don't
946     // increment Depth when just zipping down an all-constant GEP.
947     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
948       if (!OpC->isZero())
949         return true;
950       continue;
951     }
952
953     // We post-increment Depth here because while isKnownNonZero increments it
954     // as well, when we pop back up that increment won't persist. We don't want
955     // to recurse 10k times just because we have 10k GEP operands. We don't
956     // bail completely out because we want to handle constant GEPs regardless
957     // of depth.
958     if (Depth++ >= MaxDepth)
959       continue;
960
961     if (isKnownNonZero(GTI.getOperand(), DL, Depth))
962       return true;
963   }
964
965   return false;
966 }
967
968 /// isKnownNonZero - Return true if the given value is known to be non-zero
969 /// when defined.  For vectors return true if every element is known to be
970 /// non-zero when defined.  Supports values with integer or pointer type and
971 /// vectors of integers.
972 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth) {
973   if (Constant *C = dyn_cast<Constant>(V)) {
974     if (C->isNullValue())
975       return false;
976     if (isa<ConstantInt>(C))
977       // Must be non-zero due to null test above.
978       return true;
979     // TODO: Handle vectors
980     return false;
981   }
982
983   // The remaining tests are all recursive, so bail out if we hit the limit.
984   if (Depth++ >= MaxDepth)
985     return false;
986
987   // Check for pointer simplifications.
988   if (V->getType()->isPointerTy()) {
989     if (isKnownNonNull(V))
990       return true; 
991     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
992       if (isGEPKnownNonNull(GEP, TD, Depth))
993         return true;
994   }
995
996   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
997
998   // X | Y != 0 if X != 0 or Y != 0.
999   Value *X = nullptr, *Y = nullptr;
1000   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1001     return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
1002
1003   // ext X != 0 if X != 0.
1004   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1005     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
1006
1007   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1008   // if the lowest bit is shifted off the end.
1009   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1010     // shl nuw can't remove any non-zero bits.
1011     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1012     if (BO->hasNoUnsignedWrap())
1013       return isKnownNonZero(X, TD, Depth);
1014
1015     APInt KnownZero(BitWidth, 0);
1016     APInt KnownOne(BitWidth, 0);
1017     computeKnownBits(X, KnownZero, KnownOne, TD, Depth);
1018     if (KnownOne[0])
1019       return true;
1020   }
1021   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1022   // defined if the sign bit is shifted off the end.
1023   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1024     // shr exact can only shift out zero bits.
1025     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1026     if (BO->isExact())
1027       return isKnownNonZero(X, TD, Depth);
1028
1029     bool XKnownNonNegative, XKnownNegative;
1030     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
1031     if (XKnownNegative)
1032       return true;
1033   }
1034   // div exact can only produce a zero if the dividend is zero.
1035   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1036     return isKnownNonZero(X, TD, Depth);
1037   }
1038   // X + Y.
1039   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1040     bool XKnownNonNegative, XKnownNegative;
1041     bool YKnownNonNegative, YKnownNegative;
1042     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
1043     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
1044
1045     // If X and Y are both non-negative (as signed values) then their sum is not
1046     // zero unless both X and Y are zero.
1047     if (XKnownNonNegative && YKnownNonNegative)
1048       if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
1049         return true;
1050
1051     // If X and Y are both negative (as signed values) then their sum is not
1052     // zero unless both X and Y equal INT_MIN.
1053     if (BitWidth && XKnownNegative && YKnownNegative) {
1054       APInt KnownZero(BitWidth, 0);
1055       APInt KnownOne(BitWidth, 0);
1056       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1057       // The sign bit of X is set.  If some other bit is set then X is not equal
1058       // to INT_MIN.
1059       computeKnownBits(X, KnownZero, KnownOne, TD, Depth);
1060       if ((KnownOne & Mask) != 0)
1061         return true;
1062       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1063       // to INT_MIN.
1064       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth);
1065       if ((KnownOne & Mask) != 0)
1066         return true;
1067     }
1068
1069     // The sum of a non-negative number and a power of two is not zero.
1070     if (XKnownNonNegative && isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth))
1071       return true;
1072     if (YKnownNonNegative && isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth))
1073       return true;
1074   }
1075   // X * Y.
1076   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1077     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1078     // If X and Y are non-zero then so is X * Y as long as the multiplication
1079     // does not overflow.
1080     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1081         isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
1082       return true;
1083   }
1084   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1085   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1086     if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
1087         isKnownNonZero(SI->getFalseValue(), TD, Depth))
1088       return true;
1089   }
1090
1091   if (!BitWidth) return false;
1092   APInt KnownZero(BitWidth, 0);
1093   APInt KnownOne(BitWidth, 0);
1094   computeKnownBits(V, KnownZero, KnownOne, TD, Depth);
1095   return KnownOne != 0;
1096 }
1097
1098 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1099 /// this predicate to simplify operations downstream.  Mask is known to be zero
1100 /// for bits that V cannot have.
1101 ///
1102 /// This function is defined on values with integer type, values with pointer
1103 /// type (but only if TD is non-null), and vectors of integers.  In the case
1104 /// where V is a vector, the mask, known zero, and known one values are the
1105 /// same width as the vector element, and the bit is set only if it is true
1106 /// for all of the elements in the vector.
1107 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
1108                              const DataLayout *TD, unsigned Depth) {
1109   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1110   computeKnownBits(V, KnownZero, KnownOne, TD, Depth);
1111   return (KnownZero & Mask) == Mask;
1112 }
1113
1114
1115
1116 /// ComputeNumSignBits - Return the number of times the sign bit of the
1117 /// register is replicated into the other bits.  We know that at least 1 bit
1118 /// is always equal to the sign bit (itself), but other cases can give us
1119 /// information.  For example, immediately after an "ashr X, 2", we know that
1120 /// the top 3 bits are all equal to each other, so we return 3.
1121 ///
1122 /// 'Op' must have a scalar integer type.
1123 ///
1124 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
1125                                   unsigned Depth) {
1126   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1127          "ComputeNumSignBits requires a DataLayout object to operate "
1128          "on non-integer values!");
1129   Type *Ty = V->getType();
1130   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1131                          Ty->getScalarSizeInBits();
1132   unsigned Tmp, Tmp2;
1133   unsigned FirstAnswer = 1;
1134
1135   // Note that ConstantInt is handled by the general computeKnownBits case
1136   // below.
1137
1138   if (Depth == 6)
1139     return 1;  // Limit search depth.
1140
1141   Operator *U = dyn_cast<Operator>(V);
1142   switch (Operator::getOpcode(V)) {
1143   default: break;
1144   case Instruction::SExt:
1145     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1146     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1147
1148   case Instruction::AShr: {
1149     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1150     // ashr X, C   -> adds C sign bits.  Vectors too.
1151     const APInt *ShAmt;
1152     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1153       Tmp += ShAmt->getZExtValue();
1154       if (Tmp > TyBits) Tmp = TyBits;
1155     }
1156     return Tmp;
1157   }
1158   case Instruction::Shl: {
1159     const APInt *ShAmt;
1160     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1161       // shl destroys sign bits.
1162       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1163       Tmp2 = ShAmt->getZExtValue();
1164       if (Tmp2 >= TyBits ||      // Bad shift.
1165           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
1166       return Tmp - Tmp2;
1167     }
1168     break;
1169   }
1170   case Instruction::And:
1171   case Instruction::Or:
1172   case Instruction::Xor:    // NOT is handled here.
1173     // Logical binary ops preserve the number of sign bits at the worst.
1174     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1175     if (Tmp != 1) {
1176       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1177       FirstAnswer = std::min(Tmp, Tmp2);
1178       // We computed what we know about the sign bits as our first
1179       // answer. Now proceed to the generic code that uses
1180       // computeKnownBits, and pick whichever answer is better.
1181     }
1182     break;
1183
1184   case Instruction::Select:
1185     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1186     if (Tmp == 1) return 1;  // Early out.
1187     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1188     return std::min(Tmp, Tmp2);
1189
1190   case Instruction::Add:
1191     // Add can have at most one carry bit.  Thus we know that the output
1192     // is, at worst, one more bit than the inputs.
1193     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1194     if (Tmp == 1) return 1;  // Early out.
1195
1196     // Special case decrementing a value (ADD X, -1):
1197     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1198       if (CRHS->isAllOnesValue()) {
1199         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1200         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
1201
1202         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1203         // sign bits set.
1204         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1205           return TyBits;
1206
1207         // If we are subtracting one from a positive number, there is no carry
1208         // out of the result.
1209         if (KnownZero.isNegative())
1210           return Tmp;
1211       }
1212
1213     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1214     if (Tmp2 == 1) return 1;
1215     return std::min(Tmp, Tmp2)-1;
1216
1217   case Instruction::Sub:
1218     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1219     if (Tmp2 == 1) return 1;
1220
1221     // Handle NEG.
1222     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1223       if (CLHS->isNullValue()) {
1224         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1225         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
1226         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1227         // sign bits set.
1228         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1229           return TyBits;
1230
1231         // If the input is known to be positive (the sign bit is known clear),
1232         // the output of the NEG has the same number of sign bits as the input.
1233         if (KnownZero.isNegative())
1234           return Tmp2;
1235
1236         // Otherwise, we treat this like a SUB.
1237       }
1238
1239     // Sub can have at most one carry bit.  Thus we know that the output
1240     // is, at worst, one more bit than the inputs.
1241     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1242     if (Tmp == 1) return 1;  // Early out.
1243     return std::min(Tmp, Tmp2)-1;
1244
1245   case Instruction::PHI: {
1246     PHINode *PN = cast<PHINode>(U);
1247     // Don't analyze large in-degree PHIs.
1248     if (PN->getNumIncomingValues() > 4) break;
1249
1250     // Take the minimum of all incoming values.  This can't infinitely loop
1251     // because of our depth threshold.
1252     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1253     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1254       if (Tmp == 1) return Tmp;
1255       Tmp = std::min(Tmp,
1256                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
1257     }
1258     return Tmp;
1259   }
1260
1261   case Instruction::Trunc:
1262     // FIXME: it's tricky to do anything useful for this, but it is an important
1263     // case for targets like X86.
1264     break;
1265   }
1266
1267   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1268   // use this information.
1269   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1270   APInt Mask;
1271   computeKnownBits(V, KnownZero, KnownOne, TD, Depth);
1272
1273   if (KnownZero.isNegative()) {        // sign bit is 0
1274     Mask = KnownZero;
1275   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1276     Mask = KnownOne;
1277   } else {
1278     // Nothing known.
1279     return FirstAnswer;
1280   }
1281
1282   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1283   // the number of identical bits in the top of the input value.
1284   Mask = ~Mask;
1285   Mask <<= Mask.getBitWidth()-TyBits;
1286   // Return # leading zeros.  We use 'min' here in case Val was zero before
1287   // shifting.  We don't want to return '64' as for an i32 "0".
1288   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1289 }
1290
1291 /// ComputeMultiple - This function computes the integer multiple of Base that
1292 /// equals V.  If successful, it returns true and returns the multiple in
1293 /// Multiple.  If unsuccessful, it returns false. It looks
1294 /// through SExt instructions only if LookThroughSExt is true.
1295 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1296                            bool LookThroughSExt, unsigned Depth) {
1297   const unsigned MaxDepth = 6;
1298
1299   assert(V && "No Value?");
1300   assert(Depth <= MaxDepth && "Limit Search Depth");
1301   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1302
1303   Type *T = V->getType();
1304
1305   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1306
1307   if (Base == 0)
1308     return false;
1309
1310   if (Base == 1) {
1311     Multiple = V;
1312     return true;
1313   }
1314
1315   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1316   Constant *BaseVal = ConstantInt::get(T, Base);
1317   if (CO && CO == BaseVal) {
1318     // Multiple is 1.
1319     Multiple = ConstantInt::get(T, 1);
1320     return true;
1321   }
1322
1323   if (CI && CI->getZExtValue() % Base == 0) {
1324     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1325     return true;
1326   }
1327
1328   if (Depth == MaxDepth) return false;  // Limit search depth.
1329
1330   Operator *I = dyn_cast<Operator>(V);
1331   if (!I) return false;
1332
1333   switch (I->getOpcode()) {
1334   default: break;
1335   case Instruction::SExt:
1336     if (!LookThroughSExt) return false;
1337     // otherwise fall through to ZExt
1338   case Instruction::ZExt:
1339     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1340                            LookThroughSExt, Depth+1);
1341   case Instruction::Shl:
1342   case Instruction::Mul: {
1343     Value *Op0 = I->getOperand(0);
1344     Value *Op1 = I->getOperand(1);
1345
1346     if (I->getOpcode() == Instruction::Shl) {
1347       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1348       if (!Op1CI) return false;
1349       // Turn Op0 << Op1 into Op0 * 2^Op1
1350       APInt Op1Int = Op1CI->getValue();
1351       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1352       APInt API(Op1Int.getBitWidth(), 0);
1353       API.setBit(BitToSet);
1354       Op1 = ConstantInt::get(V->getContext(), API);
1355     }
1356
1357     Value *Mul0 = nullptr;
1358     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1359       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1360         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1361           if (Op1C->getType()->getPrimitiveSizeInBits() <
1362               MulC->getType()->getPrimitiveSizeInBits())
1363             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1364           if (Op1C->getType()->getPrimitiveSizeInBits() >
1365               MulC->getType()->getPrimitiveSizeInBits())
1366             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1367
1368           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1369           Multiple = ConstantExpr::getMul(MulC, Op1C);
1370           return true;
1371         }
1372
1373       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1374         if (Mul0CI->getValue() == 1) {
1375           // V == Base * Op1, so return Op1
1376           Multiple = Op1;
1377           return true;
1378         }
1379     }
1380
1381     Value *Mul1 = nullptr;
1382     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1383       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1384         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1385           if (Op0C->getType()->getPrimitiveSizeInBits() <
1386               MulC->getType()->getPrimitiveSizeInBits())
1387             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1388           if (Op0C->getType()->getPrimitiveSizeInBits() >
1389               MulC->getType()->getPrimitiveSizeInBits())
1390             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1391
1392           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1393           Multiple = ConstantExpr::getMul(MulC, Op0C);
1394           return true;
1395         }
1396
1397       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1398         if (Mul1CI->getValue() == 1) {
1399           // V == Base * Op0, so return Op0
1400           Multiple = Op0;
1401           return true;
1402         }
1403     }
1404   }
1405   }
1406
1407   // We could not determine if V is a multiple of Base.
1408   return false;
1409 }
1410
1411 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
1412 /// value is never equal to -0.0.
1413 ///
1414 /// NOTE: this function will need to be revisited when we support non-default
1415 /// rounding modes!
1416 ///
1417 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1418   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1419     return !CFP->getValueAPF().isNegZero();
1420
1421   if (Depth == 6)
1422     return 1;  // Limit search depth.
1423
1424   const Operator *I = dyn_cast<Operator>(V);
1425   if (!I) return false;
1426
1427   // Check if the nsz fast-math flag is set
1428   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
1429     if (FPO->hasNoSignedZeros())
1430       return true;
1431
1432   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1433   if (I->getOpcode() == Instruction::FAdd)
1434     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
1435       if (CFP->isNullValue())
1436         return true;
1437
1438   // sitofp and uitofp turn into +0.0 for zero.
1439   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1440     return true;
1441
1442   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1443     // sqrt(-0.0) = -0.0, no other negative results are possible.
1444     if (II->getIntrinsicID() == Intrinsic::sqrt)
1445       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1446
1447   if (const CallInst *CI = dyn_cast<CallInst>(I))
1448     if (const Function *F = CI->getCalledFunction()) {
1449       if (F->isDeclaration()) {
1450         // abs(x) != -0.0
1451         if (F->getName() == "abs") return true;
1452         // fabs[lf](x) != -0.0
1453         if (F->getName() == "fabs") return true;
1454         if (F->getName() == "fabsf") return true;
1455         if (F->getName() == "fabsl") return true;
1456         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1457             F->getName() == "sqrtl")
1458           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
1459       }
1460     }
1461
1462   return false;
1463 }
1464
1465 /// isBytewiseValue - If the specified value can be set by repeating the same
1466 /// byte in memory, return the i8 value that it is represented with.  This is
1467 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1468 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1469 /// byte store (e.g. i16 0x1234), return null.
1470 Value *llvm::isBytewiseValue(Value *V) {
1471   // All byte-wide stores are splatable, even of arbitrary variables.
1472   if (V->getType()->isIntegerTy(8)) return V;
1473
1474   // Handle 'null' ConstantArrayZero etc.
1475   if (Constant *C = dyn_cast<Constant>(V))
1476     if (C->isNullValue())
1477       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
1478
1479   // Constant float and double values can be handled as integer values if the
1480   // corresponding integer value is "byteable".  An important case is 0.0.
1481   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1482     if (CFP->getType()->isFloatTy())
1483       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1484     if (CFP->getType()->isDoubleTy())
1485       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1486     // Don't handle long double formats, which have strange constraints.
1487   }
1488
1489   // We can handle constant integers that are power of two in size and a
1490   // multiple of 8 bits.
1491   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1492     unsigned Width = CI->getBitWidth();
1493     if (isPowerOf2_32(Width) && Width > 8) {
1494       // We can handle this value if the recursive binary decomposition is the
1495       // same at all levels.
1496       APInt Val = CI->getValue();
1497       APInt Val2;
1498       while (Val.getBitWidth() != 8) {
1499         unsigned NextWidth = Val.getBitWidth()/2;
1500         Val2  = Val.lshr(NextWidth);
1501         Val2 = Val2.trunc(Val.getBitWidth()/2);
1502         Val = Val.trunc(Val.getBitWidth()/2);
1503
1504         // If the top/bottom halves aren't the same, reject it.
1505         if (Val != Val2)
1506           return nullptr;
1507       }
1508       return ConstantInt::get(V->getContext(), Val);
1509     }
1510   }
1511
1512   // A ConstantDataArray/Vector is splatable if all its members are equal and
1513   // also splatable.
1514   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1515     Value *Elt = CA->getElementAsConstant(0);
1516     Value *Val = isBytewiseValue(Elt);
1517     if (!Val)
1518       return nullptr;
1519
1520     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1521       if (CA->getElementAsConstant(I) != Elt)
1522         return nullptr;
1523
1524     return Val;
1525   }
1526
1527   // Conceptually, we could handle things like:
1528   //   %a = zext i8 %X to i16
1529   //   %b = shl i16 %a, 8
1530   //   %c = or i16 %a, %b
1531   // but until there is an example that actually needs this, it doesn't seem
1532   // worth worrying about.
1533   return nullptr;
1534 }
1535
1536
1537 // This is the recursive version of BuildSubAggregate. It takes a few different
1538 // arguments. Idxs is the index within the nested struct From that we are
1539 // looking at now (which is of type IndexedType). IdxSkip is the number of
1540 // indices from Idxs that should be left out when inserting into the resulting
1541 // struct. To is the result struct built so far, new insertvalue instructions
1542 // build on that.
1543 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
1544                                 SmallVectorImpl<unsigned> &Idxs,
1545                                 unsigned IdxSkip,
1546                                 Instruction *InsertBefore) {
1547   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
1548   if (STy) {
1549     // Save the original To argument so we can modify it
1550     Value *OrigTo = To;
1551     // General case, the type indexed by Idxs is a struct
1552     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1553       // Process each struct element recursively
1554       Idxs.push_back(i);
1555       Value *PrevTo = To;
1556       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1557                              InsertBefore);
1558       Idxs.pop_back();
1559       if (!To) {
1560         // Couldn't find any inserted value for this index? Cleanup
1561         while (PrevTo != OrigTo) {
1562           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1563           PrevTo = Del->getAggregateOperand();
1564           Del->eraseFromParent();
1565         }
1566         // Stop processing elements
1567         break;
1568       }
1569     }
1570     // If we successfully found a value for each of our subaggregates
1571     if (To)
1572       return To;
1573   }
1574   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1575   // the struct's elements had a value that was inserted directly. In the latter
1576   // case, perhaps we can't determine each of the subelements individually, but
1577   // we might be able to find the complete struct somewhere.
1578
1579   // Find the value that is at that particular spot
1580   Value *V = FindInsertedValue(From, Idxs);
1581
1582   if (!V)
1583     return nullptr;
1584
1585   // Insert the value in the new (sub) aggregrate
1586   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
1587                                        "tmp", InsertBefore);
1588 }
1589
1590 // This helper takes a nested struct and extracts a part of it (which is again a
1591 // struct) into a new value. For example, given the struct:
1592 // { a, { b, { c, d }, e } }
1593 // and the indices "1, 1" this returns
1594 // { c, d }.
1595 //
1596 // It does this by inserting an insertvalue for each element in the resulting
1597 // struct, as opposed to just inserting a single struct. This will only work if
1598 // each of the elements of the substruct are known (ie, inserted into From by an
1599 // insertvalue instruction somewhere).
1600 //
1601 // All inserted insertvalue instructions are inserted before InsertBefore
1602 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
1603                                 Instruction *InsertBefore) {
1604   assert(InsertBefore && "Must have someplace to insert!");
1605   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1606                                                              idx_range);
1607   Value *To = UndefValue::get(IndexedType);
1608   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
1609   unsigned IdxSkip = Idxs.size();
1610
1611   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1612 }
1613
1614 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1615 /// the scalar value indexed is already around as a register, for example if it
1616 /// were inserted directly into the aggregrate.
1617 ///
1618 /// If InsertBefore is not null, this function will duplicate (modified)
1619 /// insertvalues when a part of a nested struct is extracted.
1620 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1621                                Instruction *InsertBefore) {
1622   // Nothing to index? Just return V then (this is useful at the end of our
1623   // recursion).
1624   if (idx_range.empty())
1625     return V;
1626   // We have indices, so V should have an indexable type.
1627   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1628          "Not looking at a struct or array?");
1629   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1630          "Invalid indices for type?");
1631
1632   if (Constant *C = dyn_cast<Constant>(V)) {
1633     C = C->getAggregateElement(idx_range[0]);
1634     if (!C) return nullptr;
1635     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1636   }
1637
1638   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1639     // Loop the indices for the insertvalue instruction in parallel with the
1640     // requested indices
1641     const unsigned *req_idx = idx_range.begin();
1642     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1643          i != e; ++i, ++req_idx) {
1644       if (req_idx == idx_range.end()) {
1645         // We can't handle this without inserting insertvalues
1646         if (!InsertBefore)
1647           return nullptr;
1648
1649         // The requested index identifies a part of a nested aggregate. Handle
1650         // this specially. For example,
1651         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1652         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1653         // %C = extractvalue {i32, { i32, i32 } } %B, 1
1654         // This can be changed into
1655         // %A = insertvalue {i32, i32 } undef, i32 10, 0
1656         // %C = insertvalue {i32, i32 } %A, i32 11, 1
1657         // which allows the unused 0,0 element from the nested struct to be
1658         // removed.
1659         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1660                                  InsertBefore);
1661       }
1662
1663       // This insert value inserts something else than what we are looking for.
1664       // See if the (aggregrate) value inserted into has the value we are
1665       // looking for, then.
1666       if (*req_idx != *i)
1667         return FindInsertedValue(I->getAggregateOperand(), idx_range,
1668                                  InsertBefore);
1669     }
1670     // If we end up here, the indices of the insertvalue match with those
1671     // requested (though possibly only partially). Now we recursively look at
1672     // the inserted value, passing any remaining indices.
1673     return FindInsertedValue(I->getInsertedValueOperand(),
1674                              makeArrayRef(req_idx, idx_range.end()),
1675                              InsertBefore);
1676   }
1677
1678   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1679     // If we're extracting a value from an aggregrate that was extracted from
1680     // something else, we can extract from that something else directly instead.
1681     // However, we will need to chain I's indices with the requested indices.
1682
1683     // Calculate the number of indices required
1684     unsigned size = I->getNumIndices() + idx_range.size();
1685     // Allocate some space to put the new indices in
1686     SmallVector<unsigned, 5> Idxs;
1687     Idxs.reserve(size);
1688     // Add indices from the extract value instruction
1689     Idxs.append(I->idx_begin(), I->idx_end());
1690
1691     // Add requested indices
1692     Idxs.append(idx_range.begin(), idx_range.end());
1693
1694     assert(Idxs.size() == size
1695            && "Number of indices added not correct?");
1696
1697     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
1698   }
1699   // Otherwise, we don't know (such as, extracting from a function return value
1700   // or load instruction)
1701   return nullptr;
1702 }
1703
1704 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1705 /// it can be expressed as a base pointer plus a constant offset.  Return the
1706 /// base and offset to the caller.
1707 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1708                                               const DataLayout *DL) {
1709   // Without DataLayout, conservatively assume 64-bit offsets, which is
1710   // the widest we support.
1711   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
1712   APInt ByteOffset(BitWidth, 0);
1713   while (1) {
1714     if (Ptr->getType()->isVectorTy())
1715       break;
1716
1717     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1718       if (DL) {
1719         APInt GEPOffset(BitWidth, 0);
1720         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
1721           break;
1722
1723         ByteOffset += GEPOffset;
1724       }
1725
1726       Ptr = GEP->getPointerOperand();
1727     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1728       Ptr = cast<Operator>(Ptr)->getOperand(0);
1729     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1730       if (GA->mayBeOverridden())
1731         break;
1732       Ptr = GA->getAliasee();
1733     } else {
1734       break;
1735     }
1736   }
1737   Offset = ByteOffset.getSExtValue();
1738   return Ptr;
1739 }
1740
1741
1742 /// getConstantStringInfo - This function computes the length of a
1743 /// null-terminated C string pointed to by V.  If successful, it returns true
1744 /// and returns the string in Str.  If unsuccessful, it returns false.
1745 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1746                                  uint64_t Offset, bool TrimAtNul) {
1747   assert(V);
1748
1749   // Look through bitcast instructions and geps.
1750   V = V->stripPointerCasts();
1751
1752   // If the value is a GEP instructionor  constant expression, treat it as an
1753   // offset.
1754   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1755     // Make sure the GEP has exactly three arguments.
1756     if (GEP->getNumOperands() != 3)
1757       return false;
1758
1759     // Make sure the index-ee is a pointer to array of i8.
1760     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1761     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1762     if (!AT || !AT->getElementType()->isIntegerTy(8))
1763       return false;
1764
1765     // Check to make sure that the first operand of the GEP is an integer and
1766     // has value 0 so that we are sure we're indexing into the initializer.
1767     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1768     if (!FirstIdx || !FirstIdx->isZero())
1769       return false;
1770
1771     // If the second index isn't a ConstantInt, then this is a variable index
1772     // into the array.  If this occurs, we can't say anything meaningful about
1773     // the string.
1774     uint64_t StartIdx = 0;
1775     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1776       StartIdx = CI->getZExtValue();
1777     else
1778       return false;
1779     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
1780   }
1781
1782   // The GEP instruction, constant or instruction, must reference a global
1783   // variable that is a constant and is initialized. The referenced constant
1784   // initializer is the array that we'll use for optimization.
1785   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1786   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1787     return false;
1788
1789   // Handle the all-zeros case
1790   if (GV->getInitializer()->isNullValue()) {
1791     // This is a degenerate case. The initializer is constant zero so the
1792     // length of the string must be zero.
1793     Str = "";
1794     return true;
1795   }
1796
1797   // Must be a Constant Array
1798   const ConstantDataArray *Array =
1799     dyn_cast<ConstantDataArray>(GV->getInitializer());
1800   if (!Array || !Array->isString())
1801     return false;
1802
1803   // Get the number of elements in the array
1804   uint64_t NumElts = Array->getType()->getArrayNumElements();
1805
1806   // Start out with the entire array in the StringRef.
1807   Str = Array->getAsString();
1808
1809   if (Offset > NumElts)
1810     return false;
1811
1812   // Skip over 'offset' bytes.
1813   Str = Str.substr(Offset);
1814
1815   if (TrimAtNul) {
1816     // Trim off the \0 and anything after it.  If the array is not nul
1817     // terminated, we just return the whole end of string.  The client may know
1818     // some other way that the string is length-bound.
1819     Str = Str.substr(0, Str.find('\0'));
1820   }
1821   return true;
1822 }
1823
1824 // These next two are very similar to the above, but also look through PHI
1825 // nodes.
1826 // TODO: See if we can integrate these two together.
1827
1828 /// GetStringLengthH - If we can compute the length of the string pointed to by
1829 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1830 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1831   // Look through noop bitcast instructions.
1832   V = V->stripPointerCasts();
1833
1834   // If this is a PHI node, there are two cases: either we have already seen it
1835   // or we haven't.
1836   if (PHINode *PN = dyn_cast<PHINode>(V)) {
1837     if (!PHIs.insert(PN))
1838       return ~0ULL;  // already in the set.
1839
1840     // If it was new, see if all the input strings are the same length.
1841     uint64_t LenSoFar = ~0ULL;
1842     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1843       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1844       if (Len == 0) return 0; // Unknown length -> unknown.
1845
1846       if (Len == ~0ULL) continue;
1847
1848       if (Len != LenSoFar && LenSoFar != ~0ULL)
1849         return 0;    // Disagree -> unknown.
1850       LenSoFar = Len;
1851     }
1852
1853     // Success, all agree.
1854     return LenSoFar;
1855   }
1856
1857   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1858   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1859     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1860     if (Len1 == 0) return 0;
1861     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1862     if (Len2 == 0) return 0;
1863     if (Len1 == ~0ULL) return Len2;
1864     if (Len2 == ~0ULL) return Len1;
1865     if (Len1 != Len2) return 0;
1866     return Len1;
1867   }
1868
1869   // Otherwise, see if we can read the string.
1870   StringRef StrData;
1871   if (!getConstantStringInfo(V, StrData))
1872     return 0;
1873
1874   return StrData.size()+1;
1875 }
1876
1877 /// GetStringLength - If we can compute the length of the string pointed to by
1878 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1879 uint64_t llvm::GetStringLength(Value *V) {
1880   if (!V->getType()->isPointerTy()) return 0;
1881
1882   SmallPtrSet<PHINode*, 32> PHIs;
1883   uint64_t Len = GetStringLengthH(V, PHIs);
1884   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1885   // an empty string as a length.
1886   return Len == ~0ULL ? 1 : Len;
1887 }
1888
1889 Value *
1890 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
1891   if (!V->getType()->isPointerTy())
1892     return V;
1893   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1894     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1895       V = GEP->getPointerOperand();
1896     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1897       V = cast<Operator>(V)->getOperand(0);
1898     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1899       if (GA->mayBeOverridden())
1900         return V;
1901       V = GA->getAliasee();
1902     } else {
1903       // See if InstructionSimplify knows any relevant tricks.
1904       if (Instruction *I = dyn_cast<Instruction>(V))
1905         // TODO: Acquire a DominatorTree and use it.
1906         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
1907           V = Simplified;
1908           continue;
1909         }
1910
1911       return V;
1912     }
1913     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1914   }
1915   return V;
1916 }
1917
1918 void
1919 llvm::GetUnderlyingObjects(Value *V,
1920                            SmallVectorImpl<Value *> &Objects,
1921                            const DataLayout *TD,
1922                            unsigned MaxLookup) {
1923   SmallPtrSet<Value *, 4> Visited;
1924   SmallVector<Value *, 4> Worklist;
1925   Worklist.push_back(V);
1926   do {
1927     Value *P = Worklist.pop_back_val();
1928     P = GetUnderlyingObject(P, TD, MaxLookup);
1929
1930     if (!Visited.insert(P))
1931       continue;
1932
1933     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
1934       Worklist.push_back(SI->getTrueValue());
1935       Worklist.push_back(SI->getFalseValue());
1936       continue;
1937     }
1938
1939     if (PHINode *PN = dyn_cast<PHINode>(P)) {
1940       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1941         Worklist.push_back(PN->getIncomingValue(i));
1942       continue;
1943     }
1944
1945     Objects.push_back(P);
1946   } while (!Worklist.empty());
1947 }
1948
1949 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1950 /// are lifetime markers.
1951 ///
1952 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1953   for (const User *U : V->users()) {
1954     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1955     if (!II) return false;
1956
1957     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1958         II->getIntrinsicID() != Intrinsic::lifetime_end)
1959       return false;
1960   }
1961   return true;
1962 }
1963
1964 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
1965                                         const DataLayout *TD) {
1966   const Operator *Inst = dyn_cast<Operator>(V);
1967   if (!Inst)
1968     return false;
1969
1970   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1971     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1972       if (C->canTrap())
1973         return false;
1974
1975   switch (Inst->getOpcode()) {
1976   default:
1977     return true;
1978   case Instruction::UDiv:
1979   case Instruction::URem:
1980     // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1981     return isKnownNonZero(Inst->getOperand(1), TD);
1982   case Instruction::SDiv:
1983   case Instruction::SRem: {
1984     Value *Op = Inst->getOperand(1);
1985     // x / y is undefined if y == 0
1986     if (!isKnownNonZero(Op, TD))
1987       return false;
1988     // x / y might be undefined if y == -1
1989     unsigned BitWidth = getBitWidth(Op->getType(), TD);
1990     if (BitWidth == 0)
1991       return false;
1992     APInt KnownZero(BitWidth, 0);
1993     APInt KnownOne(BitWidth, 0);
1994     computeKnownBits(Op, KnownZero, KnownOne, TD);
1995     return !!KnownZero;
1996   }
1997   case Instruction::Load: {
1998     const LoadInst *LI = cast<LoadInst>(Inst);
1999     if (!LI->isUnordered() ||
2000         // Speculative load may create a race that did not exist in the source.
2001         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2002       return false;
2003     return LI->getPointerOperand()->isDereferenceablePointer();
2004   }
2005   case Instruction::Call: {
2006    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2007      switch (II->getIntrinsicID()) {
2008        // These synthetic intrinsics have no side-effects, and just mark
2009        // information about their operands.
2010        // FIXME: There are other no-op synthetic instructions that potentially
2011        // should be considered at least *safe* to speculate...
2012        case Intrinsic::dbg_declare:
2013        case Intrinsic::dbg_value:
2014          return true;
2015
2016        case Intrinsic::bswap:
2017        case Intrinsic::ctlz:
2018        case Intrinsic::ctpop:
2019        case Intrinsic::cttz:
2020        case Intrinsic::objectsize:
2021        case Intrinsic::sadd_with_overflow:
2022        case Intrinsic::smul_with_overflow:
2023        case Intrinsic::ssub_with_overflow:
2024        case Intrinsic::uadd_with_overflow:
2025        case Intrinsic::umul_with_overflow:
2026        case Intrinsic::usub_with_overflow:
2027          return true;
2028        // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2029        // errno like libm sqrt would.
2030        case Intrinsic::sqrt:
2031        case Intrinsic::fma:
2032        case Intrinsic::fmuladd:
2033          return true;
2034        // TODO: some fp intrinsics are marked as having the same error handling
2035        // as libm. They're safe to speculate when they won't error.
2036        // TODO: are convert_{from,to}_fp16 safe?
2037        // TODO: can we list target-specific intrinsics here?
2038        default: break;
2039      }
2040    }
2041     return false; // The called function could have undefined behavior or
2042                   // side-effects, even if marked readnone nounwind.
2043   }
2044   case Instruction::VAArg:
2045   case Instruction::Alloca:
2046   case Instruction::Invoke:
2047   case Instruction::PHI:
2048   case Instruction::Store:
2049   case Instruction::Ret:
2050   case Instruction::Br:
2051   case Instruction::IndirectBr:
2052   case Instruction::Switch:
2053   case Instruction::Unreachable:
2054   case Instruction::Fence:
2055   case Instruction::LandingPad:
2056   case Instruction::AtomicRMW:
2057   case Instruction::AtomicCmpXchg:
2058   case Instruction::Resume:
2059     return false; // Misc instructions which have effects
2060   }
2061 }
2062
2063 /// isKnownNonNull - Return true if we know that the specified value is never
2064 /// null.
2065 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
2066   // Alloca never returns null, malloc might.
2067   if (isa<AllocaInst>(V)) return true;
2068
2069   // A byval, inalloca, or nonnull argument is never null.
2070   if (const Argument *A = dyn_cast<Argument>(V))
2071     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
2072
2073   // Global values are not null unless extern weak.
2074   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2075     return !GV->hasExternalWeakLinkage();
2076
2077   if (ImmutableCallSite CS = V)
2078     if (CS.paramHasAttr(0, Attribute::NonNull))
2079       return true;
2080
2081   // operator new never returns null.
2082   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2083     return true;
2084
2085   return false;
2086 }