1 //===- InstCombineCasts.cpp -----------------------------------------------===//
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 the visit functions for cast operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/Support/KnownBits.h"
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// Analyze 'Val', seeing if it is a simple linear expression.
28 /// If so, decompose it, returning some value X, such that Val is
29 /// X*Scale+Offset.
30 ///
31 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
32                                         uint64_t &Offset) {
33   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
34     Offset = CI->getZExtValue();
35     Scale  = 0;
36     return ConstantInt::get(Val->getType(), 0);
37   }
38 
39   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
40     // Cannot look past anything that might overflow.
41     OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
42     if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
43       Scale = 1;
44       Offset = 0;
45       return Val;
46     }
47 
48     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
49       if (I->getOpcode() == Instruction::Shl) {
50         // This is a value scaled by '1 << the shift amt'.
51         Scale = UINT64_C(1) << RHS->getZExtValue();
52         Offset = 0;
53         return I->getOperand(0);
54       }
55 
56       if (I->getOpcode() == Instruction::Mul) {
57         // This value is scaled by 'RHS'.
58         Scale = RHS->getZExtValue();
59         Offset = 0;
60         return I->getOperand(0);
61       }
62 
63       if (I->getOpcode() == Instruction::Add) {
64         // We have X+C.  Check to see if we really have (X*C2)+C1,
65         // where C1 is divisible by C2.
66         unsigned SubScale;
67         Value *SubVal =
68           decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
69         Offset += RHS->getZExtValue();
70         Scale = SubScale;
71         return SubVal;
72       }
73     }
74   }
75 
76   // Otherwise, we can't look past this.
77   Scale = 1;
78   Offset = 0;
79   return Val;
80 }
81 
82 /// If we find a cast of an allocation instruction, try to eliminate the cast by
83 /// moving the type information into the alloc.
84 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
85                                                    AllocaInst &AI) {
86   PointerType *PTy = cast<PointerType>(CI.getType());
87 
88   BuilderTy AllocaBuilder(Builder);
89   AllocaBuilder.SetInsertPoint(&AI);
90 
91   // Get the type really allocated and the type casted to.
92   Type *AllocElTy = AI.getAllocatedType();
93   Type *CastElTy = PTy->getElementType();
94   if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
95 
96   unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
97   unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
98   if (CastElTyAlign < AllocElTyAlign) return nullptr;
99 
100   // If the allocation has multiple uses, only promote it if we are strictly
101   // increasing the alignment of the resultant allocation.  If we keep it the
102   // same, we open the door to infinite loops of various kinds.
103   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
104 
105   uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
106   uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
107   if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
108 
109   // If the allocation has multiple uses, only promote it if we're not
110   // shrinking the amount of memory being allocated.
111   uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
112   uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
113   if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
114 
115   // See if we can satisfy the modulus by pulling a scale out of the array
116   // size argument.
117   unsigned ArraySizeScale;
118   uint64_t ArrayOffset;
119   Value *NumElements = // See if the array size is a decomposable linear expr.
120     decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
121 
122   // If we can now satisfy the modulus, by using a non-1 scale, we really can
123   // do the xform.
124   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
125       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return nullptr;
126 
127   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
128   Value *Amt = nullptr;
129   if (Scale == 1) {
130     Amt = NumElements;
131   } else {
132     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
133     // Insert before the alloca, not before the cast.
134     Amt = AllocaBuilder.CreateMul(Amt, NumElements);
135   }
136 
137   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
138     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
139                                   Offset, true);
140     Amt = AllocaBuilder.CreateAdd(Amt, Off);
141   }
142 
143   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
144   New->setAlignment(AI.getAlignment());
145   New->takeName(&AI);
146   New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
147 
148   // If the allocation has multiple real uses, insert a cast and change all
149   // things that used it to use the new cast.  This will also hack on CI, but it
150   // will die soon.
151   if (!AI.hasOneUse()) {
152     // New is the allocation instruction, pointer typed. AI is the original
153     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
154     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
155     replaceInstUsesWith(AI, NewCast);
156   }
157   return replaceInstUsesWith(CI, New);
158 }
159 
160 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
161 /// true for, actually insert the code to evaluate the expression.
162 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
163                                              bool isSigned) {
164   if (Constant *C = dyn_cast<Constant>(V)) {
165     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
166     // If we got a constantexpr back, try to simplify it with DL info.
167     if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI))
168       C = FoldedC;
169     return C;
170   }
171 
172   // Otherwise, it must be an instruction.
173   Instruction *I = cast<Instruction>(V);
174   Instruction *Res = nullptr;
175   unsigned Opc = I->getOpcode();
176   switch (Opc) {
177   case Instruction::Add:
178   case Instruction::Sub:
179   case Instruction::Mul:
180   case Instruction::And:
181   case Instruction::Or:
182   case Instruction::Xor:
183   case Instruction::AShr:
184   case Instruction::LShr:
185   case Instruction::Shl:
186   case Instruction::UDiv:
187   case Instruction::URem: {
188     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
189     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
190     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
191     break;
192   }
193   case Instruction::Trunc:
194   case Instruction::ZExt:
195   case Instruction::SExt:
196     // If the source type of the cast is the type we're trying for then we can
197     // just return the source.  There's no need to insert it because it is not
198     // new.
199     if (I->getOperand(0)->getType() == Ty)
200       return I->getOperand(0);
201 
202     // Otherwise, must be the same type of cast, so just reinsert a new one.
203     // This also handles the case of zext(trunc(x)) -> zext(x).
204     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
205                                       Opc == Instruction::SExt);
206     break;
207   case Instruction::Select: {
208     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
209     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
210     Res = SelectInst::Create(I->getOperand(0), True, False);
211     break;
212   }
213   case Instruction::PHI: {
214     PHINode *OPN = cast<PHINode>(I);
215     PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
216     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
217       Value *V =
218           EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
219       NPN->addIncoming(V, OPN->getIncomingBlock(i));
220     }
221     Res = NPN;
222     break;
223   }
224   default:
225     // TODO: Can handle more cases here.
226     llvm_unreachable("Unreachable!");
227   }
228 
229   Res->takeName(I);
230   return InsertNewInstWith(Res, *I);
231 }
232 
233 Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1,
234                                                         const CastInst *CI2) {
235   Type *SrcTy = CI1->getSrcTy();
236   Type *MidTy = CI1->getDestTy();
237   Type *DstTy = CI2->getDestTy();
238 
239   Instruction::CastOps firstOp = CI1->getOpcode();
240   Instruction::CastOps secondOp = CI2->getOpcode();
241   Type *SrcIntPtrTy =
242       SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
243   Type *MidIntPtrTy =
244       MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
245   Type *DstIntPtrTy =
246       DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
247   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
248                                                 DstTy, SrcIntPtrTy, MidIntPtrTy,
249                                                 DstIntPtrTy);
250 
251   // We don't want to form an inttoptr or ptrtoint that converts to an integer
252   // type that differs from the pointer size.
253   if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
254       (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
255     Res = 0;
256 
257   return Instruction::CastOps(Res);
258 }
259 
260 /// Implement the transforms common to all CastInst visitors.
261 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
262   Value *Src = CI.getOperand(0);
263 
264   // Try to eliminate a cast of a cast.
265   if (auto *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
266     if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) {
267       // The first cast (CSrc) is eliminable so we need to fix up or replace
268       // the second cast (CI). CSrc will then have a good chance of being dead.
269       auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), CI.getType());
270 
271       // If the eliminable cast has debug users, insert a debug value after the
272       // cast pointing to the new Value.
273       SmallVector<DbgInfoIntrinsic *, 1> CSrcDbgInsts;
274       findDbgUsers(CSrcDbgInsts, CSrc);
275       if (CSrcDbgInsts.size()) {
276         DIBuilder DIB(*CI.getModule());
277         for (auto *DII : CSrcDbgInsts)
278           DIB.insertDbgValueIntrinsic(
279               Res, DII->getVariable(), DII->getExpression(),
280               DII->getDebugLoc().get(), &*std::next(CI.getIterator()));
281       }
282       return Res;
283     }
284   }
285 
286   // If we are casting a select, then fold the cast into the select.
287   if (auto *SI = dyn_cast<SelectInst>(Src))
288     if (Instruction *NV = FoldOpIntoSelect(CI, SI))
289       return NV;
290 
291   // If we are casting a PHI, then fold the cast into the PHI.
292   if (auto *PN = dyn_cast<PHINode>(Src)) {
293     // Don't do this if it would create a PHI node with an illegal type from a
294     // legal type.
295     if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
296         shouldChangeType(CI.getType(), Src->getType()))
297       if (Instruction *NV = foldOpIntoPhi(CI, PN))
298         return NV;
299   }
300 
301   return nullptr;
302 }
303 
304 /// Constants and extensions/truncates from the destination type are always
305 /// free to be evaluated in that type. This is a helper for canEvaluate*.
306 static bool canAlwaysEvaluateInType(Value *V, Type *Ty) {
307   if (isa<Constant>(V))
308     return true;
309   Value *X;
310   if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) &&
311       X->getType() == Ty)
312     return true;
313 
314   return false;
315 }
316 
317 /// Filter out values that we can not evaluate in the destination type for free.
318 /// This is a helper for canEvaluate*.
319 static bool canNotEvaluateInType(Value *V, Type *Ty) {
320   assert(!isa<Constant>(V) && "Constant should already be handled.");
321   if (!isa<Instruction>(V))
322     return true;
323   // We don't extend or shrink something that has multiple uses --  doing so
324   // would require duplicating the instruction which isn't profitable.
325   if (!V->hasOneUse())
326     return true;
327 
328   return false;
329 }
330 
331 /// Return true if we can evaluate the specified expression tree as type Ty
332 /// instead of its larger type, and arrive with the same value.
333 /// This is used by code that tries to eliminate truncates.
334 ///
335 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
336 /// can be computed by computing V in the smaller type.  If V is an instruction,
337 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
338 /// makes sense if x and y can be efficiently truncated.
339 ///
340 /// This function works on both vectors and scalars.
341 ///
342 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
343                                  Instruction *CxtI) {
344   if (canAlwaysEvaluateInType(V, Ty))
345     return true;
346   if (canNotEvaluateInType(V, Ty))
347     return false;
348 
349   auto *I = cast<Instruction>(V);
350   Type *OrigTy = V->getType();
351   switch (I->getOpcode()) {
352   case Instruction::Add:
353   case Instruction::Sub:
354   case Instruction::Mul:
355   case Instruction::And:
356   case Instruction::Or:
357   case Instruction::Xor:
358     // These operators can all arbitrarily be extended or truncated.
359     return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
360            canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
361 
362   case Instruction::UDiv:
363   case Instruction::URem: {
364     // UDiv and URem can be truncated if all the truncated bits are zero.
365     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
366     uint32_t BitWidth = Ty->getScalarSizeInBits();
367     if (BitWidth < OrigBitWidth) {
368       APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
369       if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
370           IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
371         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
372                canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
373       }
374     }
375     break;
376   }
377   case Instruction::Shl: {
378     // If we are truncating the result of this SHL, and if it's a shift of a
379     // constant amount, we can always perform a SHL in a smaller type.
380     const APInt *Amt;
381     if (match(I->getOperand(1), m_APInt(Amt))) {
382       uint32_t BitWidth = Ty->getScalarSizeInBits();
383       if (Amt->getLimitedValue(BitWidth) < BitWidth)
384         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
385     }
386     break;
387   }
388   case Instruction::LShr: {
389     // If this is a truncate of a logical shr, we can truncate it to a smaller
390     // lshr iff we know that the bits we would otherwise be shifting in are
391     // already zeros.
392     const APInt *Amt;
393     if (match(I->getOperand(1), m_APInt(Amt))) {
394       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
395       uint32_t BitWidth = Ty->getScalarSizeInBits();
396       if (Amt->getLimitedValue(BitWidth) < BitWidth &&
397           IC.MaskedValueIsZero(I->getOperand(0),
398             APInt::getBitsSetFrom(OrigBitWidth, BitWidth), 0, CxtI)) {
399         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
400       }
401     }
402     break;
403   }
404   case Instruction::AShr: {
405     // If this is a truncate of an arithmetic shr, we can truncate it to a
406     // smaller ashr iff we know that all the bits from the sign bit of the
407     // original type and the sign bit of the truncate type are similar.
408     // TODO: It is enough to check that the bits we would be shifting in are
409     //       similar to sign bit of the truncate type.
410     const APInt *Amt;
411     if (match(I->getOperand(1), m_APInt(Amt))) {
412       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
413       uint32_t BitWidth = Ty->getScalarSizeInBits();
414       if (Amt->getLimitedValue(BitWidth) < BitWidth &&
415           OrigBitWidth - BitWidth <
416               IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI))
417         return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
418     }
419     break;
420   }
421   case Instruction::Trunc:
422     // trunc(trunc(x)) -> trunc(x)
423     return true;
424   case Instruction::ZExt:
425   case Instruction::SExt:
426     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
427     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
428     return true;
429   case Instruction::Select: {
430     SelectInst *SI = cast<SelectInst>(I);
431     return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
432            canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
433   }
434   case Instruction::PHI: {
435     // We can change a phi if we can change all operands.  Note that we never
436     // get into trouble with cyclic PHIs here because we only consider
437     // instructions with a single use.
438     PHINode *PN = cast<PHINode>(I);
439     for (Value *IncValue : PN->incoming_values())
440       if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
441         return false;
442     return true;
443   }
444   default:
445     // TODO: Can handle more cases here.
446     break;
447   }
448 
449   return false;
450 }
451 
452 /// Given a vector that is bitcast to an integer, optionally logically
453 /// right-shifted, and truncated, convert it to an extractelement.
454 /// Example (big endian):
455 ///   trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
456 ///   --->
457 ///   extractelement <4 x i32> %X, 1
458 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC) {
459   Value *TruncOp = Trunc.getOperand(0);
460   Type *DestType = Trunc.getType();
461   if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
462     return nullptr;
463 
464   Value *VecInput = nullptr;
465   ConstantInt *ShiftVal = nullptr;
466   if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
467                                   m_LShr(m_BitCast(m_Value(VecInput)),
468                                          m_ConstantInt(ShiftVal)))) ||
469       !isa<VectorType>(VecInput->getType()))
470     return nullptr;
471 
472   VectorType *VecType = cast<VectorType>(VecInput->getType());
473   unsigned VecWidth = VecType->getPrimitiveSizeInBits();
474   unsigned DestWidth = DestType->getPrimitiveSizeInBits();
475   unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
476 
477   if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
478     return nullptr;
479 
480   // If the element type of the vector doesn't match the result type,
481   // bitcast it to a vector type that we can extract from.
482   unsigned NumVecElts = VecWidth / DestWidth;
483   if (VecType->getElementType() != DestType) {
484     VecType = VectorType::get(DestType, NumVecElts);
485     VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc");
486   }
487 
488   unsigned Elt = ShiftAmount / DestWidth;
489   if (IC.getDataLayout().isBigEndian())
490     Elt = NumVecElts - 1 - Elt;
491 
492   return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt));
493 }
494 
495 /// Rotate left/right may occur in a wider type than necessary because of type
496 /// promotion rules. Try to narrow all of the component instructions.
497 Instruction *InstCombiner::narrowRotate(TruncInst &Trunc) {
498   assert((isa<VectorType>(Trunc.getSrcTy()) ||
499           shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) &&
500          "Don't narrow to an illegal scalar type");
501 
502   // First, find an or'd pair of opposite shifts with the same shifted operand:
503   // trunc (or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1))
504   Value *Or0, *Or1;
505   if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
506     return nullptr;
507 
508   Value *ShVal, *ShAmt0, *ShAmt1;
509   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal), m_Value(ShAmt0)))) ||
510       !match(Or1, m_OneUse(m_LogicalShift(m_Specific(ShVal), m_Value(ShAmt1)))))
511     return nullptr;
512 
513   auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
514   auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
515   if (ShiftOpcode0 == ShiftOpcode1)
516     return nullptr;
517 
518   // The shift amounts must add up to the narrow bit width.
519   Value *ShAmt;
520   bool SubIsOnLHS;
521   Type *DestTy = Trunc.getType();
522   unsigned NarrowWidth = DestTy->getScalarSizeInBits();
523   if (match(ShAmt0,
524             m_OneUse(m_Sub(m_SpecificInt(NarrowWidth), m_Specific(ShAmt1))))) {
525     ShAmt = ShAmt1;
526     SubIsOnLHS = true;
527   } else if (match(ShAmt1, m_OneUse(m_Sub(m_SpecificInt(NarrowWidth),
528                                           m_Specific(ShAmt0))))) {
529     ShAmt = ShAmt0;
530     SubIsOnLHS = false;
531   } else {
532     return nullptr;
533   }
534 
535   // The shifted value must have high zeros in the wide type. Typically, this
536   // will be a zext, but it could also be the result of an 'and' or 'shift'.
537   unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits();
538   APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth);
539   if (!MaskedValueIsZero(ShVal, HiBitMask, 0, &Trunc))
540     return nullptr;
541 
542   // We have an unnecessarily wide rotate!
543   // trunc (or (lshr ShVal, ShAmt), (shl ShVal, BitWidth - ShAmt))
544   // Narrow it down to eliminate the zext/trunc:
545   // or (lshr trunc(ShVal), ShAmt0'), (shl trunc(ShVal), ShAmt1')
546   Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy);
547   Value *NegShAmt = Builder.CreateNeg(NarrowShAmt);
548 
549   // Mask both shift amounts to ensure there's no UB from oversized shifts.
550   Constant *MaskC = ConstantInt::get(DestTy, NarrowWidth - 1);
551   Value *MaskedShAmt = Builder.CreateAnd(NarrowShAmt, MaskC);
552   Value *MaskedNegShAmt = Builder.CreateAnd(NegShAmt, MaskC);
553 
554   // Truncate the original value and use narrow ops.
555   Value *X = Builder.CreateTrunc(ShVal, DestTy);
556   Value *NarrowShAmt0 = SubIsOnLHS ? MaskedNegShAmt : MaskedShAmt;
557   Value *NarrowShAmt1 = SubIsOnLHS ? MaskedShAmt : MaskedNegShAmt;
558   Value *NarrowSh0 = Builder.CreateBinOp(ShiftOpcode0, X, NarrowShAmt0);
559   Value *NarrowSh1 = Builder.CreateBinOp(ShiftOpcode1, X, NarrowShAmt1);
560   return BinaryOperator::CreateOr(NarrowSh0, NarrowSh1);
561 }
562 
563 /// Try to narrow the width of math or bitwise logic instructions by pulling a
564 /// truncate ahead of binary operators.
565 /// TODO: Transforms for truncated shifts should be moved into here.
566 Instruction *InstCombiner::narrowBinOp(TruncInst &Trunc) {
567   Type *SrcTy = Trunc.getSrcTy();
568   Type *DestTy = Trunc.getType();
569   if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy))
570     return nullptr;
571 
572   BinaryOperator *BinOp;
573   if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp))))
574     return nullptr;
575 
576   Value *BinOp0 = BinOp->getOperand(0);
577   Value *BinOp1 = BinOp->getOperand(1);
578   switch (BinOp->getOpcode()) {
579   case Instruction::And:
580   case Instruction::Or:
581   case Instruction::Xor:
582   case Instruction::Add:
583   case Instruction::Sub:
584   case Instruction::Mul: {
585     Constant *C;
586     if (match(BinOp0, m_Constant(C))) {
587       // trunc (binop C, X) --> binop (trunc C', X)
588       Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
589       Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
590       return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX);
591     }
592     if (match(BinOp1, m_Constant(C))) {
593       // trunc (binop X, C) --> binop (trunc X, C')
594       Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
595       Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
596       return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC);
597     }
598     Value *X;
599     if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
600       // trunc (binop (ext X), Y) --> binop X, (trunc Y)
601       Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
602       return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1);
603     }
604     if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
605       // trunc (binop Y, (ext X)) --> binop (trunc Y), X
606       Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
607       return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X);
608     }
609     break;
610   }
611 
612   default: break;
613   }
614 
615   if (Instruction *NarrowOr = narrowRotate(Trunc))
616     return NarrowOr;
617 
618   return nullptr;
619 }
620 
621 /// Try to narrow the width of a splat shuffle. This could be generalized to any
622 /// shuffle with a constant operand, but we limit the transform to avoid
623 /// creating a shuffle type that targets may not be able to lower effectively.
624 static Instruction *shrinkSplatShuffle(TruncInst &Trunc,
625                                        InstCombiner::BuilderTy &Builder) {
626   auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0));
627   if (Shuf && Shuf->hasOneUse() && isa<UndefValue>(Shuf->getOperand(1)) &&
628       Shuf->getMask()->getSplatValue() &&
629       Shuf->getType() == Shuf->getOperand(0)->getType()) {
630     // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Undef, SplatMask
631     Constant *NarrowUndef = UndefValue::get(Trunc.getType());
632     Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType());
633     return new ShuffleVectorInst(NarrowOp, NarrowUndef, Shuf->getMask());
634   }
635 
636   return nullptr;
637 }
638 
639 /// Try to narrow the width of an insert element. This could be generalized for
640 /// any vector constant, but we limit the transform to insertion into undef to
641 /// avoid potential backend problems from unsupported insertion widths. This
642 /// could also be extended to handle the case of inserting a scalar constant
643 /// into a vector variable.
644 static Instruction *shrinkInsertElt(CastInst &Trunc,
645                                     InstCombiner::BuilderTy &Builder) {
646   Instruction::CastOps Opcode = Trunc.getOpcode();
647   assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
648          "Unexpected instruction for shrinking");
649 
650   auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0));
651   if (!InsElt || !InsElt->hasOneUse())
652     return nullptr;
653 
654   Type *DestTy = Trunc.getType();
655   Type *DestScalarTy = DestTy->getScalarType();
656   Value *VecOp = InsElt->getOperand(0);
657   Value *ScalarOp = InsElt->getOperand(1);
658   Value *Index = InsElt->getOperand(2);
659 
660   if (isa<UndefValue>(VecOp)) {
661     // trunc   (inselt undef, X, Index) --> inselt undef,   (trunc X), Index
662     // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index
663     UndefValue *NarrowUndef = UndefValue::get(DestTy);
664     Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy);
665     return InsertElementInst::Create(NarrowUndef, NarrowOp, Index);
666   }
667 
668   return nullptr;
669 }
670 
671 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
672   if (Instruction *Result = commonCastTransforms(CI))
673     return Result;
674 
675   // Test if the trunc is the user of a select which is part of a
676   // minimum or maximum operation. If so, don't do any more simplification.
677   // Even simplifying demanded bits can break the canonical form of a
678   // min/max.
679   Value *LHS, *RHS;
680   if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
681     if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
682       return nullptr;
683 
684   // See if we can simplify any instructions used by the input whose sole
685   // purpose is to compute bits we don't care about.
686   if (SimplifyDemandedInstructionBits(CI))
687     return &CI;
688 
689   Value *Src = CI.getOperand(0);
690   Type *DestTy = CI.getType(), *SrcTy = Src->getType();
691 
692   // Attempt to truncate the entire input expression tree to the destination
693   // type.   Only do this if the dest type is a simple type, don't convert the
694   // expression tree to something weird like i93 unless the source is also
695   // strange.
696   if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
697       canEvaluateTruncated(Src, DestTy, *this, &CI)) {
698 
699     // If this cast is a truncate, evaluting in a different type always
700     // eliminates the cast, so it is always a win.
701     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
702           " to avoid cast: " << CI << '\n');
703     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
704     assert(Res->getType() == DestTy);
705     return replaceInstUsesWith(CI, Res);
706   }
707 
708   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
709   if (DestTy->getScalarSizeInBits() == 1) {
710     Constant *One = ConstantInt::get(SrcTy, 1);
711     Src = Builder.CreateAnd(Src, One);
712     Value *Zero = Constant::getNullValue(Src->getType());
713     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
714   }
715 
716   // FIXME: Maybe combine the next two transforms to handle the no cast case
717   // more efficiently. Support vector types. Cleanup code by using m_OneUse.
718 
719   // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
720   Value *A = nullptr; ConstantInt *Cst = nullptr;
721   if (Src->hasOneUse() &&
722       match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
723     // We have three types to worry about here, the type of A, the source of
724     // the truncate (MidSize), and the destination of the truncate. We know that
725     // ASize < MidSize   and MidSize > ResultSize, but don't know the relation
726     // between ASize and ResultSize.
727     unsigned ASize = A->getType()->getPrimitiveSizeInBits();
728 
729     // If the shift amount is larger than the size of A, then the result is
730     // known to be zero because all the input bits got shifted out.
731     if (Cst->getZExtValue() >= ASize)
732       return replaceInstUsesWith(CI, Constant::getNullValue(DestTy));
733 
734     // Since we're doing an lshr and a zero extend, and know that the shift
735     // amount is smaller than ASize, it is always safe to do the shift in A's
736     // type, then zero extend or truncate to the result.
737     Value *Shift = Builder.CreateLShr(A, Cst->getZExtValue());
738     Shift->takeName(Src);
739     return CastInst::CreateIntegerCast(Shift, DestTy, false);
740   }
741 
742   // FIXME: We should canonicalize to zext/trunc and remove this transform.
743   // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
744   // conversion.
745   // It works because bits coming from sign extension have the same value as
746   // the sign bit of the original value; performing ashr instead of lshr
747   // generates bits of the same value as the sign bit.
748   if (Src->hasOneUse() &&
749       match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst)))) {
750     Value *SExt = cast<Instruction>(Src)->getOperand(0);
751     const unsigned SExtSize = SExt->getType()->getPrimitiveSizeInBits();
752     const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
753     const unsigned CISize = CI.getType()->getPrimitiveSizeInBits();
754     const unsigned MaxAmt = SExtSize - std::max(CISize, ASize);
755     unsigned ShiftAmt = Cst->getZExtValue();
756 
757     // This optimization can be only performed when zero bits generated by
758     // the original lshr aren't pulled into the value after truncation, so we
759     // can only shift by values no larger than the number of extension bits.
760     // FIXME: Instead of bailing when the shift is too large, use and to clear
761     // the extra bits.
762     if (ShiftAmt <= MaxAmt) {
763       if (CISize == ASize)
764         return BinaryOperator::CreateAShr(A, ConstantInt::get(CI.getType(),
765                                           std::min(ShiftAmt, ASize - 1)));
766       if (SExt->hasOneUse()) {
767         Value *Shift = Builder.CreateAShr(A, std::min(ShiftAmt, ASize - 1));
768         Shift->takeName(Src);
769         return CastInst::CreateIntegerCast(Shift, CI.getType(), true);
770       }
771     }
772   }
773 
774   if (Instruction *I = narrowBinOp(CI))
775     return I;
776 
777   if (Instruction *I = shrinkSplatShuffle(CI, Builder))
778     return I;
779 
780   if (Instruction *I = shrinkInsertElt(CI, Builder))
781     return I;
782 
783   if (Src->hasOneUse() && isa<IntegerType>(SrcTy) &&
784       shouldChangeType(SrcTy, DestTy)) {
785     // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the
786     // dest type is native and cst < dest size.
787     if (match(Src, m_Shl(m_Value(A), m_ConstantInt(Cst))) &&
788         !match(A, m_Shr(m_Value(), m_Constant()))) {
789       // Skip shifts of shift by constants. It undoes a combine in
790       // FoldShiftByConstant and is the extend in reg pattern.
791       const unsigned DestSize = DestTy->getScalarSizeInBits();
792       if (Cst->getValue().ult(DestSize)) {
793         Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr");
794 
795         return BinaryOperator::Create(
796           Instruction::Shl, NewTrunc,
797           ConstantInt::get(DestTy, Cst->getValue().trunc(DestSize)));
798       }
799     }
800   }
801 
802   if (Instruction *I = foldVecTruncToExtElt(CI, *this))
803     return I;
804 
805   return nullptr;
806 }
807 
808 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
809                                              bool DoTransform) {
810   // If we are just checking for a icmp eq of a single bit and zext'ing it
811   // to an integer, then shift the bit to the appropriate place and then
812   // cast to integer to avoid the comparison.
813   const APInt *Op1CV;
814   if (match(ICI->getOperand(1), m_APInt(Op1CV))) {
815 
816     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
817     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
818     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isNullValue()) ||
819         (ICI->getPredicate() == ICmpInst::ICMP_SGT && Op1CV->isAllOnesValue())) {
820       if (!DoTransform) return ICI;
821 
822       Value *In = ICI->getOperand(0);
823       Value *Sh = ConstantInt::get(In->getType(),
824                                    In->getType()->getScalarSizeInBits() - 1);
825       In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit");
826       if (In->getType() != CI.getType())
827         In = Builder.CreateIntCast(In, CI.getType(), false /*ZExt*/);
828 
829       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
830         Constant *One = ConstantInt::get(In->getType(), 1);
831         In = Builder.CreateXor(In, One, In->getName() + ".not");
832       }
833 
834       return replaceInstUsesWith(CI, In);
835     }
836 
837     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
838     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
839     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
840     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
841     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
842     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
843     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
844     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
845     if ((Op1CV->isNullValue() || Op1CV->isPowerOf2()) &&
846         // This only works for EQ and NE
847         ICI->isEquality()) {
848       // If Op1C some other power of two, convert:
849       KnownBits Known = computeKnownBits(ICI->getOperand(0), 0, &CI);
850 
851       APInt KnownZeroMask(~Known.Zero);
852       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
853         if (!DoTransform) return ICI;
854 
855         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
856         if (!Op1CV->isNullValue() && (*Op1CV != KnownZeroMask)) {
857           // (X&4) == 2 --> false
858           // (X&4) != 2 --> true
859           Constant *Res = ConstantInt::get(CI.getType(), isNE);
860           return replaceInstUsesWith(CI, Res);
861         }
862 
863         uint32_t ShAmt = KnownZeroMask.logBase2();
864         Value *In = ICI->getOperand(0);
865         if (ShAmt) {
866           // Perform a logical shr by shiftamt.
867           // Insert the shift to put the result in the low bit.
868           In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
869                                   In->getName() + ".lobit");
870         }
871 
872         if (!Op1CV->isNullValue() == isNE) { // Toggle the low bit.
873           Constant *One = ConstantInt::get(In->getType(), 1);
874           In = Builder.CreateXor(In, One);
875         }
876 
877         if (CI.getType() == In->getType())
878           return replaceInstUsesWith(CI, In);
879 
880         Value *IntCast = Builder.CreateIntCast(In, CI.getType(), false);
881         return replaceInstUsesWith(CI, IntCast);
882       }
883     }
884   }
885 
886   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
887   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
888   // may lead to additional simplifications.
889   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
890     if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
891       Value *LHS = ICI->getOperand(0);
892       Value *RHS = ICI->getOperand(1);
893 
894       KnownBits KnownLHS = computeKnownBits(LHS, 0, &CI);
895       KnownBits KnownRHS = computeKnownBits(RHS, 0, &CI);
896 
897       if (KnownLHS.Zero == KnownRHS.Zero && KnownLHS.One == KnownRHS.One) {
898         APInt KnownBits = KnownLHS.Zero | KnownLHS.One;
899         APInt UnknownBit = ~KnownBits;
900         if (UnknownBit.countPopulation() == 1) {
901           if (!DoTransform) return ICI;
902 
903           Value *Result = Builder.CreateXor(LHS, RHS);
904 
905           // Mask off any bits that are set and won't be shifted away.
906           if (KnownLHS.One.uge(UnknownBit))
907             Result = Builder.CreateAnd(Result,
908                                         ConstantInt::get(ITy, UnknownBit));
909 
910           // Shift the bit we're testing down to the lsb.
911           Result = Builder.CreateLShr(
912                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
913 
914           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
915             Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1));
916           Result->takeName(ICI);
917           return replaceInstUsesWith(CI, Result);
918         }
919       }
920     }
921   }
922 
923   return nullptr;
924 }
925 
926 /// Determine if the specified value can be computed in the specified wider type
927 /// and produce the same low bits. If not, return false.
928 ///
929 /// If this function returns true, it can also return a non-zero number of bits
930 /// (in BitsToClear) which indicates that the value it computes is correct for
931 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
932 /// out.  For example, to promote something like:
933 ///
934 ///   %B = trunc i64 %A to i32
935 ///   %C = lshr i32 %B, 8
936 ///   %E = zext i32 %C to i64
937 ///
938 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
939 /// set to 8 to indicate that the promoted value needs to have bits 24-31
940 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
941 /// clear the top bits anyway, doing this has no extra cost.
942 ///
943 /// This function works on both vectors and scalars.
944 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
945                              InstCombiner &IC, Instruction *CxtI) {
946   BitsToClear = 0;
947   if (canAlwaysEvaluateInType(V, Ty))
948     return true;
949   if (canNotEvaluateInType(V, Ty))
950     return false;
951 
952   auto *I = cast<Instruction>(V);
953   unsigned Tmp;
954   switch (I->getOpcode()) {
955   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
956   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
957   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
958     return true;
959   case Instruction::And:
960   case Instruction::Or:
961   case Instruction::Xor:
962   case Instruction::Add:
963   case Instruction::Sub:
964   case Instruction::Mul:
965     if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
966         !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
967       return false;
968     // These can all be promoted if neither operand has 'bits to clear'.
969     if (BitsToClear == 0 && Tmp == 0)
970       return true;
971 
972     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
973     // other side, BitsToClear is ok.
974     if (Tmp == 0 && I->isBitwiseLogicOp()) {
975       // We use MaskedValueIsZero here for generality, but the case we care
976       // about the most is constant RHS.
977       unsigned VSize = V->getType()->getScalarSizeInBits();
978       if (IC.MaskedValueIsZero(I->getOperand(1),
979                                APInt::getHighBitsSet(VSize, BitsToClear),
980                                0, CxtI)) {
981         // If this is an And instruction and all of the BitsToClear are
982         // known to be zero we can reset BitsToClear.
983         if (I->getOpcode() == Instruction::And)
984           BitsToClear = 0;
985         return true;
986       }
987     }
988 
989     // Otherwise, we don't know how to analyze this BitsToClear case yet.
990     return false;
991 
992   case Instruction::Shl: {
993     // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
994     // upper bits we can reduce BitsToClear by the shift amount.
995     const APInt *Amt;
996     if (match(I->getOperand(1), m_APInt(Amt))) {
997       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
998         return false;
999       uint64_t ShiftAmt = Amt->getZExtValue();
1000       BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
1001       return true;
1002     }
1003     return false;
1004   }
1005   case Instruction::LShr: {
1006     // We can promote lshr(x, cst) if we can promote x.  This requires the
1007     // ultimate 'and' to clear out the high zero bits we're clearing out though.
1008     const APInt *Amt;
1009     if (match(I->getOperand(1), m_APInt(Amt))) {
1010       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1011         return false;
1012       BitsToClear += Amt->getZExtValue();
1013       if (BitsToClear > V->getType()->getScalarSizeInBits())
1014         BitsToClear = V->getType()->getScalarSizeInBits();
1015       return true;
1016     }
1017     // Cannot promote variable LSHR.
1018     return false;
1019   }
1020   case Instruction::Select:
1021     if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
1022         !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
1023         // TODO: If important, we could handle the case when the BitsToClear are
1024         // known zero in the disagreeing side.
1025         Tmp != BitsToClear)
1026       return false;
1027     return true;
1028 
1029   case Instruction::PHI: {
1030     // We can change a phi if we can change all operands.  Note that we never
1031     // get into trouble with cyclic PHIs here because we only consider
1032     // instructions with a single use.
1033     PHINode *PN = cast<PHINode>(I);
1034     if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
1035       return false;
1036     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
1037       if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
1038           // TODO: If important, we could handle the case when the BitsToClear
1039           // are known zero in the disagreeing input.
1040           Tmp != BitsToClear)
1041         return false;
1042     return true;
1043   }
1044   default:
1045     // TODO: Can handle more cases here.
1046     return false;
1047   }
1048 }
1049 
1050 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
1051   // If this zero extend is only used by a truncate, let the truncate be
1052   // eliminated before we try to optimize this zext.
1053   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1054     return nullptr;
1055 
1056   // If one of the common conversion will work, do it.
1057   if (Instruction *Result = commonCastTransforms(CI))
1058     return Result;
1059 
1060   Value *Src = CI.getOperand(0);
1061   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1062 
1063   // Attempt to extend the entire input expression tree to the destination
1064   // type.   Only do this if the dest type is a simple type, don't convert the
1065   // expression tree to something weird like i93 unless the source is also
1066   // strange.
1067   unsigned BitsToClear;
1068   if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
1069       canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
1070     assert(BitsToClear <= SrcTy->getScalarSizeInBits() &&
1071            "Can't clear more bits than in SrcTy");
1072 
1073     // Okay, we can transform this!  Insert the new expression now.
1074     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1075           " to avoid zero extend: " << CI << '\n');
1076     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
1077     assert(Res->getType() == DestTy);
1078 
1079     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
1080     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1081 
1082     // If the high bits are already filled with zeros, just replace this
1083     // cast with the result.
1084     if (MaskedValueIsZero(Res,
1085                           APInt::getHighBitsSet(DestBitSize,
1086                                                 DestBitSize-SrcBitsKept),
1087                              0, &CI))
1088       return replaceInstUsesWith(CI, Res);
1089 
1090     // We need to emit an AND to clear the high bits.
1091     Constant *C = ConstantInt::get(Res->getType(),
1092                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
1093     return BinaryOperator::CreateAnd(Res, C);
1094   }
1095 
1096   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
1097   // types and if the sizes are just right we can convert this into a logical
1098   // 'and' which will be much cheaper than the pair of casts.
1099   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
1100     // TODO: Subsume this into EvaluateInDifferentType.
1101 
1102     // Get the sizes of the types involved.  We know that the intermediate type
1103     // will be smaller than A or C, but don't know the relation between A and C.
1104     Value *A = CSrc->getOperand(0);
1105     unsigned SrcSize = A->getType()->getScalarSizeInBits();
1106     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
1107     unsigned DstSize = CI.getType()->getScalarSizeInBits();
1108     // If we're actually extending zero bits, then if
1109     // SrcSize <  DstSize: zext(a & mask)
1110     // SrcSize == DstSize: a & mask
1111     // SrcSize  > DstSize: trunc(a) & mask
1112     if (SrcSize < DstSize) {
1113       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1114       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
1115       Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask");
1116       return new ZExtInst(And, CI.getType());
1117     }
1118 
1119     if (SrcSize == DstSize) {
1120       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1121       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
1122                                                            AndValue));
1123     }
1124     if (SrcSize > DstSize) {
1125       Value *Trunc = Builder.CreateTrunc(A, CI.getType());
1126       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
1127       return BinaryOperator::CreateAnd(Trunc,
1128                                        ConstantInt::get(Trunc->getType(),
1129                                                         AndValue));
1130     }
1131   }
1132 
1133   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1134     return transformZExtICmp(ICI, CI);
1135 
1136   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
1137   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
1138     // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one
1139     // of the (zext icmp) can be eliminated. If so, immediately perform the
1140     // according elimination.
1141     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
1142     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
1143     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
1144         (transformZExtICmp(LHS, CI, false) ||
1145          transformZExtICmp(RHS, CI, false))) {
1146       // zext (or icmp, icmp) -> or (zext icmp), (zext icmp)
1147       Value *LCast = Builder.CreateZExt(LHS, CI.getType(), LHS->getName());
1148       Value *RCast = Builder.CreateZExt(RHS, CI.getType(), RHS->getName());
1149       BinaryOperator *Or = BinaryOperator::Create(Instruction::Or, LCast, RCast);
1150 
1151       // Perform the elimination.
1152       if (auto *LZExt = dyn_cast<ZExtInst>(LCast))
1153         transformZExtICmp(LHS, *LZExt);
1154       if (auto *RZExt = dyn_cast<ZExtInst>(RCast))
1155         transformZExtICmp(RHS, *RZExt);
1156 
1157       return Or;
1158     }
1159   }
1160 
1161   // zext(trunc(X) & C) -> (X & zext(C)).
1162   Constant *C;
1163   Value *X;
1164   if (SrcI &&
1165       match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
1166       X->getType() == CI.getType())
1167     return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
1168 
1169   // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
1170   Value *And;
1171   if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
1172       match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
1173       X->getType() == CI.getType()) {
1174     Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
1175     return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
1176   }
1177 
1178   return nullptr;
1179 }
1180 
1181 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
1182 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
1183   Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
1184   ICmpInst::Predicate Pred = ICI->getPredicate();
1185 
1186   // Don't bother if Op1 isn't of vector or integer type.
1187   if (!Op1->getType()->isIntOrIntVectorTy())
1188     return nullptr;
1189 
1190   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1191     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
1192     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
1193     if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
1194         (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
1195 
1196       Value *Sh = ConstantInt::get(Op0->getType(),
1197                                    Op0->getType()->getScalarSizeInBits()-1);
1198       Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit");
1199       if (In->getType() != CI.getType())
1200         In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/);
1201 
1202       if (Pred == ICmpInst::ICMP_SGT)
1203         In = Builder.CreateNot(In, In->getName() + ".not");
1204       return replaceInstUsesWith(CI, In);
1205     }
1206   }
1207 
1208   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1209     // If we know that only one bit of the LHS of the icmp can be set and we
1210     // have an equality comparison with zero or a power of 2, we can transform
1211     // the icmp and sext into bitwise/integer operations.
1212     if (ICI->hasOneUse() &&
1213         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
1214       KnownBits Known = computeKnownBits(Op0, 0, &CI);
1215 
1216       APInt KnownZeroMask(~Known.Zero);
1217       if (KnownZeroMask.isPowerOf2()) {
1218         Value *In = ICI->getOperand(0);
1219 
1220         // If the icmp tests for a known zero bit we can constant fold it.
1221         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
1222           Value *V = Pred == ICmpInst::ICMP_NE ?
1223                        ConstantInt::getAllOnesValue(CI.getType()) :
1224                        ConstantInt::getNullValue(CI.getType());
1225           return replaceInstUsesWith(CI, V);
1226         }
1227 
1228         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1229           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
1230           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1231           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
1232           // Perform a right shift to place the desired bit in the LSB.
1233           if (ShiftAmt)
1234             In = Builder.CreateLShr(In,
1235                                     ConstantInt::get(In->getType(), ShiftAmt));
1236 
1237           // At this point "In" is either 1 or 0. Subtract 1 to turn
1238           // {1, 0} -> {0, -1}.
1239           In = Builder.CreateAdd(In,
1240                                  ConstantInt::getAllOnesValue(In->getType()),
1241                                  "sext");
1242         } else {
1243           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
1244           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1245           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1246           // Perform a left shift to place the desired bit in the MSB.
1247           if (ShiftAmt)
1248             In = Builder.CreateShl(In,
1249                                    ConstantInt::get(In->getType(), ShiftAmt));
1250 
1251           // Distribute the bit over the whole bit width.
1252           In = Builder.CreateAShr(In, ConstantInt::get(In->getType(),
1253                                   KnownZeroMask.getBitWidth() - 1), "sext");
1254         }
1255 
1256         if (CI.getType() == In->getType())
1257           return replaceInstUsesWith(CI, In);
1258         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1259       }
1260     }
1261   }
1262 
1263   return nullptr;
1264 }
1265 
1266 /// Return true if we can take the specified value and return it as type Ty
1267 /// without inserting any new casts and without changing the value of the common
1268 /// low bits.  This is used by code that tries to promote integer operations to
1269 /// a wider types will allow us to eliminate the extension.
1270 ///
1271 /// This function works on both vectors and scalars.
1272 ///
1273 static bool canEvaluateSExtd(Value *V, Type *Ty) {
1274   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1275          "Can't sign extend type to a smaller type");
1276   if (canAlwaysEvaluateInType(V, Ty))
1277     return true;
1278   if (canNotEvaluateInType(V, Ty))
1279     return false;
1280 
1281   auto *I = cast<Instruction>(V);
1282   switch (I->getOpcode()) {
1283   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
1284   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
1285   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1286     return true;
1287   case Instruction::And:
1288   case Instruction::Or:
1289   case Instruction::Xor:
1290   case Instruction::Add:
1291   case Instruction::Sub:
1292   case Instruction::Mul:
1293     // These operators can all arbitrarily be extended if their inputs can.
1294     return canEvaluateSExtd(I->getOperand(0), Ty) &&
1295            canEvaluateSExtd(I->getOperand(1), Ty);
1296 
1297   //case Instruction::Shl:   TODO
1298   //case Instruction::LShr:  TODO
1299 
1300   case Instruction::Select:
1301     return canEvaluateSExtd(I->getOperand(1), Ty) &&
1302            canEvaluateSExtd(I->getOperand(2), Ty);
1303 
1304   case Instruction::PHI: {
1305     // We can change a phi if we can change all operands.  Note that we never
1306     // get into trouble with cyclic PHIs here because we only consider
1307     // instructions with a single use.
1308     PHINode *PN = cast<PHINode>(I);
1309     for (Value *IncValue : PN->incoming_values())
1310       if (!canEvaluateSExtd(IncValue, Ty)) return false;
1311     return true;
1312   }
1313   default:
1314     // TODO: Can handle more cases here.
1315     break;
1316   }
1317 
1318   return false;
1319 }
1320 
1321 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1322   // If this sign extend is only used by a truncate, let the truncate be
1323   // eliminated before we try to optimize this sext.
1324   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1325     return nullptr;
1326 
1327   if (Instruction *I = commonCastTransforms(CI))
1328     return I;
1329 
1330   Value *Src = CI.getOperand(0);
1331   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1332 
1333   // If we know that the value being extended is positive, we can use a zext
1334   // instead.
1335   KnownBits Known = computeKnownBits(Src, 0, &CI);
1336   if (Known.isNonNegative()) {
1337     Value *ZExt = Builder.CreateZExt(Src, DestTy);
1338     return replaceInstUsesWith(CI, ZExt);
1339   }
1340 
1341   // Attempt to extend the entire input expression tree to the destination
1342   // type.   Only do this if the dest type is a simple type, don't convert the
1343   // expression tree to something weird like i93 unless the source is also
1344   // strange.
1345   if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
1346       canEvaluateSExtd(Src, DestTy)) {
1347     // Okay, we can transform this!  Insert the new expression now.
1348     DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1349           " to avoid sign extend: " << CI << '\n');
1350     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1351     assert(Res->getType() == DestTy);
1352 
1353     uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1354     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1355 
1356     // If the high bits are already filled with sign bit, just replace this
1357     // cast with the result.
1358     if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
1359       return replaceInstUsesWith(CI, Res);
1360 
1361     // We need to emit a shl + ashr to do the sign extend.
1362     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1363     return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"),
1364                                       ShAmt);
1365   }
1366 
1367   // If the input is a trunc from the destination type, then turn sext(trunc(x))
1368   // into shifts.
1369   Value *X;
1370   if (match(Src, m_OneUse(m_Trunc(m_Value(X)))) && X->getType() == DestTy) {
1371     // sext(trunc(X)) --> ashr(shl(X, C), C)
1372     unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1373     unsigned DestBitSize = DestTy->getScalarSizeInBits();
1374     Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
1375     return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
1376   }
1377 
1378   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1379     return transformSExtICmp(ICI, CI);
1380 
1381   // If the input is a shl/ashr pair of a same constant, then this is a sign
1382   // extension from a smaller value.  If we could trust arbitrary bitwidth
1383   // integers, we could turn this into a truncate to the smaller bit and then
1384   // use a sext for the whole extension.  Since we don't, look deeper and check
1385   // for a truncate.  If the source and dest are the same type, eliminate the
1386   // trunc and extend and just do shifts.  For example, turn:
1387   //   %a = trunc i32 %i to i8
1388   //   %b = shl i8 %a, 6
1389   //   %c = ashr i8 %b, 6
1390   //   %d = sext i8 %c to i32
1391   // into:
1392   //   %a = shl i32 %i, 30
1393   //   %d = ashr i32 %a, 30
1394   Value *A = nullptr;
1395   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1396   ConstantInt *BA = nullptr, *CA = nullptr;
1397   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1398                         m_ConstantInt(CA))) &&
1399       BA == CA && A->getType() == CI.getType()) {
1400     unsigned MidSize = Src->getType()->getScalarSizeInBits();
1401     unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1402     unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1403     Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1404     A = Builder.CreateShl(A, ShAmtV, CI.getName());
1405     return BinaryOperator::CreateAShr(A, ShAmtV);
1406   }
1407 
1408   return nullptr;
1409 }
1410 
1411 
1412 /// Return a Constant* for the specified floating-point constant if it fits
1413 /// in the specified FP type without changing its value.
1414 static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1415   bool losesInfo;
1416   APFloat F = CFP->getValueAPF();
1417   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1418   return !losesInfo;
1419 }
1420 
1421 static Type *shrinkFPConstant(ConstantFP *CFP) {
1422   if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext()))
1423     return nullptr;  // No constant folding of this.
1424   // See if the value can be truncated to half and then reextended.
1425   if (fitsInFPType(CFP, APFloat::IEEEhalf()))
1426     return Type::getHalfTy(CFP->getContext());
1427   // See if the value can be truncated to float and then reextended.
1428   if (fitsInFPType(CFP, APFloat::IEEEsingle()))
1429     return Type::getFloatTy(CFP->getContext());
1430   if (CFP->getType()->isDoubleTy())
1431     return nullptr;  // Won't shrink.
1432   if (fitsInFPType(CFP, APFloat::IEEEdouble()))
1433     return Type::getDoubleTy(CFP->getContext());
1434   // Don't try to shrink to various long double types.
1435   return nullptr;
1436 }
1437 
1438 // Determine if this is a vector of ConstantFPs and if so, return the minimal
1439 // type we can safely truncate all elements to.
1440 // TODO: Make these support undef elements.
1441 static Type *shrinkFPConstantVector(Value *V) {
1442   auto *CV = dyn_cast<Constant>(V);
1443   if (!CV || !CV->getType()->isVectorTy())
1444     return nullptr;
1445 
1446   Type *MinType = nullptr;
1447 
1448   unsigned NumElts = CV->getType()->getVectorNumElements();
1449   for (unsigned i = 0; i != NumElts; ++i) {
1450     auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
1451     if (!CFP)
1452       return nullptr;
1453 
1454     Type *T = shrinkFPConstant(CFP);
1455     if (!T)
1456       return nullptr;
1457 
1458     // If we haven't found a type yet or this type has a larger mantissa than
1459     // our previous type, this is our new minimal type.
1460     if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth())
1461       MinType = T;
1462   }
1463 
1464   // Make a vector type from the minimal type.
1465   return VectorType::get(MinType, NumElts);
1466 }
1467 
1468 /// Find the minimum FP type we can safely truncate to.
1469 static Type *getMinimumFPType(Value *V) {
1470   if (auto *FPExt = dyn_cast<FPExtInst>(V))
1471     return FPExt->getOperand(0)->getType();
1472 
1473   // If this value is a constant, return the constant in the smallest FP type
1474   // that can accurately represent it.  This allows us to turn
1475   // (float)((double)X+2.0) into x+2.0f.
1476   if (auto *CFP = dyn_cast<ConstantFP>(V))
1477     if (Type *T = shrinkFPConstant(CFP))
1478       return T;
1479 
1480   // Try to shrink a vector of FP constants.
1481   if (Type *T = shrinkFPConstantVector(V))
1482     return T;
1483 
1484   return V->getType();
1485 }
1486 
1487 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &FPT) {
1488   if (Instruction *I = commonCastTransforms(FPT))
1489     return I;
1490 
1491   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1492   // simplify this expression to avoid one or more of the trunc/extend
1493   // operations if we can do so without changing the numerical results.
1494   //
1495   // The exact manner in which the widths of the operands interact to limit
1496   // what we can and cannot do safely varies from operation to operation, and
1497   // is explained below in the various case statements.
1498   Type *Ty = FPT.getType();
1499   BinaryOperator *OpI = dyn_cast<BinaryOperator>(FPT.getOperand(0));
1500   if (OpI && OpI->hasOneUse()) {
1501     Type *LHSMinType = getMinimumFPType(OpI->getOperand(0));
1502     Type *RHSMinType = getMinimumFPType(OpI->getOperand(1));
1503     unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1504     unsigned LHSWidth = LHSMinType->getFPMantissaWidth();
1505     unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
1506     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1507     unsigned DstWidth = Ty->getFPMantissaWidth();
1508     switch (OpI->getOpcode()) {
1509       default: break;
1510       case Instruction::FAdd:
1511       case Instruction::FSub:
1512         // For addition and subtraction, the infinitely precise result can
1513         // essentially be arbitrarily wide; proving that double rounding
1514         // will not occur because the result of OpI is exact (as we will for
1515         // FMul, for example) is hopeless.  However, we *can* nonetheless
1516         // frequently know that double rounding cannot occur (or that it is
1517         // innocuous) by taking advantage of the specific structure of
1518         // infinitely-precise results that admit double rounding.
1519         //
1520         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1521         // to represent both sources, we can guarantee that the double
1522         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1523         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1524         // for proof of this fact).
1525         //
1526         // Note: Figueroa does not consider the case where DstFormat !=
1527         // SrcFormat.  It's possible (likely even!) that this analysis
1528         // could be tightened for those cases, but they are rare (the main
1529         // case of interest here is (float)((double)float + float)).
1530         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1531           Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1532           Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1533           Instruction *RI = BinaryOperator::Create(OpI->getOpcode(), LHS, RHS);
1534           RI->copyFastMathFlags(OpI);
1535           return RI;
1536         }
1537         break;
1538       case Instruction::FMul:
1539         // For multiplication, the infinitely precise result has at most
1540         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1541         // that such a value can be exactly represented, then no double
1542         // rounding can possibly occur; we can safely perform the operation
1543         // in the destination format if it can represent both sources.
1544         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1545           Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1546           Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1547           return BinaryOperator::CreateFMulFMF(LHS, RHS, OpI);
1548         }
1549         break;
1550       case Instruction::FDiv:
1551         // For division, we use again use the bound from Figueroa's
1552         // dissertation.  I am entirely certain that this bound can be
1553         // tightened in the unbalanced operand case by an analysis based on
1554         // the diophantine rational approximation bound, but the well-known
1555         // condition used here is a good conservative first pass.
1556         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1557         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1558           Value *LHS = Builder.CreateFPTrunc(OpI->getOperand(0), Ty);
1559           Value *RHS = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1560           return BinaryOperator::CreateFDivFMF(LHS, RHS, OpI);
1561         }
1562         break;
1563       case Instruction::FRem: {
1564         // Remainder is straightforward.  Remainder is always exact, so the
1565         // type of OpI doesn't enter into things at all.  We simply evaluate
1566         // in whichever source type is larger, then convert to the
1567         // destination type.
1568         if (SrcWidth == OpWidth)
1569           break;
1570         Value *LHS, *RHS;
1571         if (LHSWidth == SrcWidth) {
1572            LHS = Builder.CreateFPTrunc(OpI->getOperand(0), LHSMinType);
1573            RHS = Builder.CreateFPTrunc(OpI->getOperand(1), LHSMinType);
1574         } else {
1575            LHS = Builder.CreateFPTrunc(OpI->getOperand(0), RHSMinType);
1576            RHS = Builder.CreateFPTrunc(OpI->getOperand(1), RHSMinType);
1577         }
1578 
1579         Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, OpI);
1580         return CastInst::CreateFPCast(ExactResult, Ty);
1581       }
1582     }
1583 
1584     // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1585     if (BinaryOperator::isFNeg(OpI)) {
1586       Value *InnerTrunc = Builder.CreateFPTrunc(OpI->getOperand(1), Ty);
1587       return BinaryOperator::CreateFNegFMF(InnerTrunc, OpI);
1588     }
1589   }
1590 
1591   // (fptrunc (select cond, R1, Cst)) -->
1592   // (select cond, (fptrunc R1), (fptrunc Cst))
1593   //
1594   //  - but only if this isn't part of a min/max operation, else we'll
1595   // ruin min/max canonical form which is to have the select and
1596   // compare's operands be of the same type with no casts to look through.
1597   Value *LHS, *RHS;
1598   SelectInst *SI = dyn_cast<SelectInst>(FPT.getOperand(0));
1599   if (SI &&
1600       (isa<ConstantFP>(SI->getOperand(1)) ||
1601        isa<ConstantFP>(SI->getOperand(2))) &&
1602       matchSelectPattern(SI, LHS, RHS).Flavor == SPF_UNKNOWN) {
1603     Value *LHSTrunc = Builder.CreateFPTrunc(SI->getOperand(1), Ty);
1604     Value *RHSTrunc = Builder.CreateFPTrunc(SI->getOperand(2), Ty);
1605     return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1606   }
1607 
1608   if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) {
1609     switch (II->getIntrinsicID()) {
1610     default: break;
1611     case Intrinsic::ceil:
1612     case Intrinsic::fabs:
1613     case Intrinsic::floor:
1614     case Intrinsic::nearbyint:
1615     case Intrinsic::rint:
1616     case Intrinsic::round:
1617     case Intrinsic::trunc: {
1618       Value *Src = II->getArgOperand(0);
1619       if (!Src->hasOneUse())
1620         break;
1621 
1622       // Except for fabs, this transformation requires the input of the unary FP
1623       // operation to be itself an fpext from the type to which we're
1624       // truncating.
1625       if (II->getIntrinsicID() != Intrinsic::fabs) {
1626         FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src);
1627         if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty)
1628           break;
1629       }
1630 
1631       // Do unary FP operation on smaller type.
1632       // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1633       Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
1634       Function *Overload = Intrinsic::getDeclaration(FPT.getModule(),
1635                                                      II->getIntrinsicID(), Ty);
1636       SmallVector<OperandBundleDef, 1> OpBundles;
1637       II->getOperandBundlesAsDefs(OpBundles);
1638       CallInst *NewCI = CallInst::Create(Overload, { InnerTrunc }, OpBundles,
1639                                          II->getName());
1640       NewCI->copyFastMathFlags(II);
1641       return NewCI;
1642     }
1643     }
1644   }
1645 
1646   if (Instruction *I = shrinkInsertElt(FPT, Builder))
1647     return I;
1648 
1649   return nullptr;
1650 }
1651 
1652 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1653   return commonCastTransforms(CI);
1654 }
1655 
1656 // fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1657 // This is safe if the intermediate type has enough bits in its mantissa to
1658 // accurately represent all values of X.  For example, this won't work with
1659 // i64 -> float -> i64.
1660 Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1661   if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1662     return nullptr;
1663   Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1664 
1665   Value *SrcI = OpI->getOperand(0);
1666   Type *FITy = FI.getType();
1667   Type *OpITy = OpI->getType();
1668   Type *SrcTy = SrcI->getType();
1669   bool IsInputSigned = isa<SIToFPInst>(OpI);
1670   bool IsOutputSigned = isa<FPToSIInst>(FI);
1671 
1672   // We can safely assume the conversion won't overflow the output range,
1673   // because (for example) (uint8_t)18293.f is undefined behavior.
1674 
1675   // Since we can assume the conversion won't overflow, our decision as to
1676   // whether the input will fit in the float should depend on the minimum
1677   // of the input range and output range.
1678 
1679   // This means this is also safe for a signed input and unsigned output, since
1680   // a negative input would lead to undefined behavior.
1681   int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1682   int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1683   int ActualSize = std::min(InputSize, OutputSize);
1684 
1685   if (ActualSize <= OpITy->getFPMantissaWidth()) {
1686     if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1687       if (IsInputSigned && IsOutputSigned)
1688         return new SExtInst(SrcI, FITy);
1689       return new ZExtInst(SrcI, FITy);
1690     }
1691     if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1692       return new TruncInst(SrcI, FITy);
1693     if (SrcTy == FITy)
1694       return replaceInstUsesWith(FI, SrcI);
1695     return new BitCastInst(SrcI, FITy);
1696   }
1697   return nullptr;
1698 }
1699 
1700 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1701   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1702   if (!OpI)
1703     return commonCastTransforms(FI);
1704 
1705   if (Instruction *I = FoldItoFPtoI(FI))
1706     return I;
1707 
1708   return commonCastTransforms(FI);
1709 }
1710 
1711 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1712   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1713   if (!OpI)
1714     return commonCastTransforms(FI);
1715 
1716   if (Instruction *I = FoldItoFPtoI(FI))
1717     return I;
1718 
1719   return commonCastTransforms(FI);
1720 }
1721 
1722 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1723   return commonCastTransforms(CI);
1724 }
1725 
1726 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1727   return commonCastTransforms(CI);
1728 }
1729 
1730 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1731   // If the source integer type is not the intptr_t type for this target, do a
1732   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
1733   // cast to be exposed to other transforms.
1734   unsigned AS = CI.getAddressSpace();
1735   if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1736       DL.getPointerSizeInBits(AS)) {
1737     Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1738     if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1739       Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1740 
1741     Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty);
1742     return new IntToPtrInst(P, CI.getType());
1743   }
1744 
1745   if (Instruction *I = commonCastTransforms(CI))
1746     return I;
1747 
1748   return nullptr;
1749 }
1750 
1751 /// Implement the transforms for cast of pointer (bitcast/ptrtoint)
1752 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1753   Value *Src = CI.getOperand(0);
1754 
1755   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1756     // If casting the result of a getelementptr instruction with no offset, turn
1757     // this into a cast of the original pointer!
1758     if (GEP->hasAllZeroIndices() &&
1759         // If CI is an addrspacecast and GEP changes the poiner type, merging
1760         // GEP into CI would undo canonicalizing addrspacecast with different
1761         // pointer types, causing infinite loops.
1762         (!isa<AddrSpaceCastInst>(CI) ||
1763          GEP->getType() == GEP->getPointerOperandType())) {
1764       // Changing the cast operand is usually not a good idea but it is safe
1765       // here because the pointer operand is being replaced with another
1766       // pointer operand so the opcode doesn't need to change.
1767       Worklist.Add(GEP);
1768       CI.setOperand(0, GEP->getOperand(0));
1769       return &CI;
1770     }
1771   }
1772 
1773   return commonCastTransforms(CI);
1774 }
1775 
1776 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1777   // If the destination integer type is not the intptr_t type for this target,
1778   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
1779   // to be exposed to other transforms.
1780 
1781   Type *Ty = CI.getType();
1782   unsigned AS = CI.getPointerAddressSpace();
1783 
1784   if (Ty->getScalarSizeInBits() == DL.getIndexSizeInBits(AS))
1785     return commonPointerCastTransforms(CI);
1786 
1787   Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
1788   if (Ty->isVectorTy()) // Handle vectors of pointers.
1789     PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1790 
1791   Value *P = Builder.CreatePtrToInt(CI.getOperand(0), PtrTy);
1792   return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
1793 }
1794 
1795 /// This input value (which is known to have vector type) is being zero extended
1796 /// or truncated to the specified vector type.
1797 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
1798 ///
1799 /// The source and destination vector types may have different element types.
1800 static Instruction *optimizeVectorResize(Value *InVal, VectorType *DestTy,
1801                                          InstCombiner &IC) {
1802   // We can only do this optimization if the output is a multiple of the input
1803   // element size, or the input is a multiple of the output element size.
1804   // Convert the input type to have the same element type as the output.
1805   VectorType *SrcTy = cast<VectorType>(InVal->getType());
1806 
1807   if (SrcTy->getElementType() != DestTy->getElementType()) {
1808     // The input types don't need to be identical, but for now they must be the
1809     // same size.  There is no specific reason we couldn't handle things like
1810     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1811     // there yet.
1812     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1813         DestTy->getElementType()->getPrimitiveSizeInBits())
1814       return nullptr;
1815 
1816     SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1817     InVal = IC.Builder.CreateBitCast(InVal, SrcTy);
1818   }
1819 
1820   // Now that the element types match, get the shuffle mask and RHS of the
1821   // shuffle to use, which depends on whether we're increasing or decreasing the
1822   // size of the input.
1823   SmallVector<uint32_t, 16> ShuffleMask;
1824   Value *V2;
1825 
1826   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1827     // If we're shrinking the number of elements, just shuffle in the low
1828     // elements from the input and use undef as the second shuffle input.
1829     V2 = UndefValue::get(SrcTy);
1830     for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1831       ShuffleMask.push_back(i);
1832 
1833   } else {
1834     // If we're increasing the number of elements, shuffle in all of the
1835     // elements from InVal and fill the rest of the result elements with zeros
1836     // from a constant zero.
1837     V2 = Constant::getNullValue(SrcTy);
1838     unsigned SrcElts = SrcTy->getNumElements();
1839     for (unsigned i = 0, e = SrcElts; i != e; ++i)
1840       ShuffleMask.push_back(i);
1841 
1842     // The excess elements reference the first element of the zero input.
1843     for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1844       ShuffleMask.push_back(SrcElts);
1845   }
1846 
1847   return new ShuffleVectorInst(InVal, V2,
1848                                ConstantDataVector::get(V2->getContext(),
1849                                                        ShuffleMask));
1850 }
1851 
1852 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1853   return Value % Ty->getPrimitiveSizeInBits() == 0;
1854 }
1855 
1856 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1857   return Value / Ty->getPrimitiveSizeInBits();
1858 }
1859 
1860 /// V is a value which is inserted into a vector of VecEltTy.
1861 /// Look through the value to see if we can decompose it into
1862 /// insertions into the vector.  See the example in the comment for
1863 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1864 /// The type of V is always a non-zero multiple of VecEltTy's size.
1865 /// Shift is the number of bits between the lsb of V and the lsb of
1866 /// the vector.
1867 ///
1868 /// This returns false if the pattern can't be matched or true if it can,
1869 /// filling in Elements with the elements found here.
1870 static bool collectInsertionElements(Value *V, unsigned Shift,
1871                                      SmallVectorImpl<Value *> &Elements,
1872                                      Type *VecEltTy, bool isBigEndian) {
1873   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1874          "Shift should be a multiple of the element type size");
1875 
1876   // Undef values never contribute useful bits to the result.
1877   if (isa<UndefValue>(V)) return true;
1878 
1879   // If we got down to a value of the right type, we win, try inserting into the
1880   // right element.
1881   if (V->getType() == VecEltTy) {
1882     // Inserting null doesn't actually insert any elements.
1883     if (Constant *C = dyn_cast<Constant>(V))
1884       if (C->isNullValue())
1885         return true;
1886 
1887     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1888     if (isBigEndian)
1889       ElementIndex = Elements.size() - ElementIndex - 1;
1890 
1891     // Fail if multiple elements are inserted into this slot.
1892     if (Elements[ElementIndex])
1893       return false;
1894 
1895     Elements[ElementIndex] = V;
1896     return true;
1897   }
1898 
1899   if (Constant *C = dyn_cast<Constant>(V)) {
1900     // Figure out the # elements this provides, and bitcast it or slice it up
1901     // as required.
1902     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1903                                         VecEltTy);
1904     // If the constant is the size of a vector element, we just need to bitcast
1905     // it to the right type so it gets properly inserted.
1906     if (NumElts == 1)
1907       return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1908                                       Shift, Elements, VecEltTy, isBigEndian);
1909 
1910     // Okay, this is a constant that covers multiple elements.  Slice it up into
1911     // pieces and insert each element-sized piece into the vector.
1912     if (!isa<IntegerType>(C->getType()))
1913       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1914                                        C->getType()->getPrimitiveSizeInBits()));
1915     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1916     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1917 
1918     for (unsigned i = 0; i != NumElts; ++i) {
1919       unsigned ShiftI = Shift+i*ElementSize;
1920       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1921                                                                   ShiftI));
1922       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1923       if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
1924                                     isBigEndian))
1925         return false;
1926     }
1927     return true;
1928   }
1929 
1930   if (!V->hasOneUse()) return false;
1931 
1932   Instruction *I = dyn_cast<Instruction>(V);
1933   if (!I) return false;
1934   switch (I->getOpcode()) {
1935   default: return false; // Unhandled case.
1936   case Instruction::BitCast:
1937     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1938                                     isBigEndian);
1939   case Instruction::ZExt:
1940     if (!isMultipleOfTypeSize(
1941                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1942                               VecEltTy))
1943       return false;
1944     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1945                                     isBigEndian);
1946   case Instruction::Or:
1947     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1948                                     isBigEndian) &&
1949            collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
1950                                     isBigEndian);
1951   case Instruction::Shl: {
1952     // Must be shifting by a constant that is a multiple of the element size.
1953     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1954     if (!CI) return false;
1955     Shift += CI->getZExtValue();
1956     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1957     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1958                                     isBigEndian);
1959   }
1960 
1961   }
1962 }
1963 
1964 
1965 /// If the input is an 'or' instruction, we may be doing shifts and ors to
1966 /// assemble the elements of the vector manually.
1967 /// Try to rip the code out and replace it with insertelements.  This is to
1968 /// optimize code like this:
1969 ///
1970 ///    %tmp37 = bitcast float %inc to i32
1971 ///    %tmp38 = zext i32 %tmp37 to i64
1972 ///    %tmp31 = bitcast float %inc5 to i32
1973 ///    %tmp32 = zext i32 %tmp31 to i64
1974 ///    %tmp33 = shl i64 %tmp32, 32
1975 ///    %ins35 = or i64 %tmp33, %tmp38
1976 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
1977 ///
1978 /// Into two insertelements that do "buildvector{%inc, %inc5}".
1979 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
1980                                                 InstCombiner &IC) {
1981   VectorType *DestVecTy = cast<VectorType>(CI.getType());
1982   Value *IntInput = CI.getOperand(0);
1983 
1984   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1985   if (!collectInsertionElements(IntInput, 0, Elements,
1986                                 DestVecTy->getElementType(),
1987                                 IC.getDataLayout().isBigEndian()))
1988     return nullptr;
1989 
1990   // If we succeeded, we know that all of the element are specified by Elements
1991   // or are zero if Elements has a null entry.  Recast this as a set of
1992   // insertions.
1993   Value *Result = Constant::getNullValue(CI.getType());
1994   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1995     if (!Elements[i]) continue;  // Unset element.
1996 
1997     Result = IC.Builder.CreateInsertElement(Result, Elements[i],
1998                                             IC.Builder.getInt32(i));
1999   }
2000 
2001   return Result;
2002 }
2003 
2004 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
2005 /// vector followed by extract element. The backend tends to handle bitcasts of
2006 /// vectors better than bitcasts of scalars because vector registers are
2007 /// usually not type-specific like scalar integer or scalar floating-point.
2008 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
2009                                               InstCombiner &IC) {
2010   // TODO: Create and use a pattern matcher for ExtractElementInst.
2011   auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0));
2012   if (!ExtElt || !ExtElt->hasOneUse())
2013     return nullptr;
2014 
2015   // The bitcast must be to a vectorizable type, otherwise we can't make a new
2016   // type to extract from.
2017   Type *DestType = BitCast.getType();
2018   if (!VectorType::isValidElementType(DestType))
2019     return nullptr;
2020 
2021   unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
2022   auto *NewVecType = VectorType::get(DestType, NumElts);
2023   auto *NewBC = IC.Builder.CreateBitCast(ExtElt->getVectorOperand(),
2024                                          NewVecType, "bc");
2025   return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand());
2026 }
2027 
2028 /// Change the type of a bitwise logic operation if we can eliminate a bitcast.
2029 static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast,
2030                                             InstCombiner::BuilderTy &Builder) {
2031   Type *DestTy = BitCast.getType();
2032   BinaryOperator *BO;
2033   if (!DestTy->isIntOrIntVectorTy() ||
2034       !match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) ||
2035       !BO->isBitwiseLogicOp())
2036     return nullptr;
2037 
2038   // FIXME: This transform is restricted to vector types to avoid backend
2039   // problems caused by creating potentially illegal operations. If a fix-up is
2040   // added to handle that situation, we can remove this check.
2041   if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy())
2042     return nullptr;
2043 
2044   Value *X;
2045   if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
2046       X->getType() == DestTy && !isa<Constant>(X)) {
2047     // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
2048     Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy);
2049     return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1);
2050   }
2051 
2052   if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) &&
2053       X->getType() == DestTy && !isa<Constant>(X)) {
2054     // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X)
2055     Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2056     return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X);
2057   }
2058 
2059   // Canonicalize vector bitcasts to come before vector bitwise logic with a
2060   // constant. This eases recognition of special constants for later ops.
2061   // Example:
2062   // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
2063   Constant *C;
2064   if (match(BO->getOperand(1), m_Constant(C))) {
2065     // bitcast (logic X, C) --> logic (bitcast X, C')
2066     Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2067     Value *CastedC = ConstantExpr::getBitCast(C, DestTy);
2068     return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC);
2069   }
2070 
2071   return nullptr;
2072 }
2073 
2074 /// Change the type of a select if we can eliminate a bitcast.
2075 static Instruction *foldBitCastSelect(BitCastInst &BitCast,
2076                                       InstCombiner::BuilderTy &Builder) {
2077   Value *Cond, *TVal, *FVal;
2078   if (!match(BitCast.getOperand(0),
2079              m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
2080     return nullptr;
2081 
2082   // A vector select must maintain the same number of elements in its operands.
2083   Type *CondTy = Cond->getType();
2084   Type *DestTy = BitCast.getType();
2085   if (CondTy->isVectorTy()) {
2086     if (!DestTy->isVectorTy())
2087       return nullptr;
2088     if (DestTy->getVectorNumElements() != CondTy->getVectorNumElements())
2089       return nullptr;
2090   }
2091 
2092   // FIXME: This transform is restricted from changing the select between
2093   // scalars and vectors to avoid backend problems caused by creating
2094   // potentially illegal operations. If a fix-up is added to handle that
2095   // situation, we can remove this check.
2096   if (DestTy->isVectorTy() != TVal->getType()->isVectorTy())
2097     return nullptr;
2098 
2099   auto *Sel = cast<Instruction>(BitCast.getOperand(0));
2100   Value *X;
2101   if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
2102       !isa<Constant>(X)) {
2103     // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y))
2104     Value *CastedVal = Builder.CreateBitCast(FVal, DestTy);
2105     return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel);
2106   }
2107 
2108   if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
2109       !isa<Constant>(X)) {
2110     // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X)
2111     Value *CastedVal = Builder.CreateBitCast(TVal, DestTy);
2112     return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel);
2113   }
2114 
2115   return nullptr;
2116 }
2117 
2118 /// Check if all users of CI are StoreInsts.
2119 static bool hasStoreUsersOnly(CastInst &CI) {
2120   for (User *U : CI.users()) {
2121     if (!isa<StoreInst>(U))
2122       return false;
2123   }
2124   return true;
2125 }
2126 
2127 /// This function handles following case
2128 ///
2129 ///     A  ->  B    cast
2130 ///     PHI
2131 ///     B  ->  A    cast
2132 ///
2133 /// All the related PHI nodes can be replaced by new PHI nodes with type A.
2134 /// The uses of \p CI can be changed to the new PHI node corresponding to \p PN.
2135 Instruction *InstCombiner::optimizeBitCastFromPhi(CastInst &CI, PHINode *PN) {
2136   // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp.
2137   if (hasStoreUsersOnly(CI))
2138     return nullptr;
2139 
2140   Value *Src = CI.getOperand(0);
2141   Type *SrcTy = Src->getType();         // Type B
2142   Type *DestTy = CI.getType();          // Type A
2143 
2144   SmallVector<PHINode *, 4> PhiWorklist;
2145   SmallSetVector<PHINode *, 4> OldPhiNodes;
2146 
2147   // Find all of the A->B casts and PHI nodes.
2148   // We need to inpect all related PHI nodes, but PHIs can be cyclic, so
2149   // OldPhiNodes is used to track all known PHI nodes, before adding a new
2150   // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first.
2151   PhiWorklist.push_back(PN);
2152   OldPhiNodes.insert(PN);
2153   while (!PhiWorklist.empty()) {
2154     auto *OldPN = PhiWorklist.pop_back_val();
2155     for (Value *IncValue : OldPN->incoming_values()) {
2156       if (isa<Constant>(IncValue))
2157         continue;
2158 
2159       if (auto *LI = dyn_cast<LoadInst>(IncValue)) {
2160         // If there is a sequence of one or more load instructions, each loaded
2161         // value is used as address of later load instruction, bitcast is
2162         // necessary to change the value type, don't optimize it. For
2163         // simplicity we give up if the load address comes from another load.
2164         Value *Addr = LI->getOperand(0);
2165         if (Addr == &CI || isa<LoadInst>(Addr))
2166           return nullptr;
2167         if (LI->hasOneUse() && LI->isSimple())
2168           continue;
2169         // If a LoadInst has more than one use, changing the type of loaded
2170         // value may create another bitcast.
2171         return nullptr;
2172       }
2173 
2174       if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
2175         if (OldPhiNodes.insert(PNode))
2176           PhiWorklist.push_back(PNode);
2177         continue;
2178       }
2179 
2180       auto *BCI = dyn_cast<BitCastInst>(IncValue);
2181       // We can't handle other instructions.
2182       if (!BCI)
2183         return nullptr;
2184 
2185       // Verify it's a A->B cast.
2186       Type *TyA = BCI->getOperand(0)->getType();
2187       Type *TyB = BCI->getType();
2188       if (TyA != DestTy || TyB != SrcTy)
2189         return nullptr;
2190     }
2191   }
2192 
2193   // For each old PHI node, create a corresponding new PHI node with a type A.
2194   SmallDenseMap<PHINode *, PHINode *> NewPNodes;
2195   for (auto *OldPN : OldPhiNodes) {
2196     Builder.SetInsertPoint(OldPN);
2197     PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
2198     NewPNodes[OldPN] = NewPN;
2199   }
2200 
2201   // Fill in the operands of new PHI nodes.
2202   for (auto *OldPN : OldPhiNodes) {
2203     PHINode *NewPN = NewPNodes[OldPN];
2204     for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) {
2205       Value *V = OldPN->getOperand(j);
2206       Value *NewV = nullptr;
2207       if (auto *C = dyn_cast<Constant>(V)) {
2208         NewV = ConstantExpr::getBitCast(C, DestTy);
2209       } else if (auto *LI = dyn_cast<LoadInst>(V)) {
2210         Builder.SetInsertPoint(LI->getNextNode());
2211         NewV = Builder.CreateBitCast(LI, DestTy);
2212         Worklist.Add(LI);
2213       } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2214         NewV = BCI->getOperand(0);
2215       } else if (auto *PrevPN = dyn_cast<PHINode>(V)) {
2216         NewV = NewPNodes[PrevPN];
2217       }
2218       assert(NewV);
2219       NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j));
2220     }
2221   }
2222 
2223   // If there is a store with type B, change it to type A.
2224   for (User *U : PN->users()) {
2225     auto *SI = dyn_cast<StoreInst>(U);
2226     if (SI && SI->isSimple() && SI->getOperand(0) == PN) {
2227       Builder.SetInsertPoint(SI);
2228       auto *NewBC =
2229           cast<BitCastInst>(Builder.CreateBitCast(NewPNodes[PN], SrcTy));
2230       SI->setOperand(0, NewBC);
2231       Worklist.Add(SI);
2232       assert(hasStoreUsersOnly(*NewBC));
2233     }
2234   }
2235 
2236   return replaceInstUsesWith(CI, NewPNodes[PN]);
2237 }
2238 
2239 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
2240   // If the operands are integer typed then apply the integer transforms,
2241   // otherwise just apply the common ones.
2242   Value *Src = CI.getOperand(0);
2243   Type *SrcTy = Src->getType();
2244   Type *DestTy = CI.getType();
2245 
2246   // Get rid of casts from one type to the same type. These are useless and can
2247   // be replaced by the operand.
2248   if (DestTy == Src->getType())
2249     return replaceInstUsesWith(CI, Src);
2250 
2251   if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
2252     PointerType *SrcPTy = cast<PointerType>(SrcTy);
2253     Type *DstElTy = DstPTy->getElementType();
2254     Type *SrcElTy = SrcPTy->getElementType();
2255 
2256     // If we are casting a alloca to a pointer to a type of the same
2257     // size, rewrite the allocation instruction to allocate the "right" type.
2258     // There is no need to modify malloc calls because it is their bitcast that
2259     // needs to be cleaned up.
2260     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
2261       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
2262         return V;
2263 
2264     // When the type pointed to is not sized the cast cannot be
2265     // turned into a gep.
2266     Type *PointeeType =
2267         cast<PointerType>(Src->getType()->getScalarType())->getElementType();
2268     if (!PointeeType->isSized())
2269       return nullptr;
2270 
2271     // If the source and destination are pointers, and this cast is equivalent
2272     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
2273     // This can enhance SROA and other transforms that want type-safe pointers.
2274     unsigned NumZeros = 0;
2275     while (SrcElTy != DstElTy &&
2276            isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
2277            SrcElTy->getNumContainedTypes() /* not "{}" */) {
2278       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
2279       ++NumZeros;
2280     }
2281 
2282     // If we found a path from the src to dest, create the getelementptr now.
2283     if (SrcElTy == DstElTy) {
2284       SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0));
2285       return GetElementPtrInst::CreateInBounds(Src, Idxs);
2286     }
2287   }
2288 
2289   if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
2290     if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
2291       Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType());
2292       return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
2293                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2294       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
2295     }
2296 
2297     if (isa<IntegerType>(SrcTy)) {
2298       // If this is a cast from an integer to vector, check to see if the input
2299       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
2300       // the casts with a shuffle and (potentially) a bitcast.
2301       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
2302         CastInst *SrcCast = cast<CastInst>(Src);
2303         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
2304           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
2305             if (Instruction *I = optimizeVectorResize(BCIn->getOperand(0),
2306                                                cast<VectorType>(DestTy), *this))
2307               return I;
2308       }
2309 
2310       // If the input is an 'or' instruction, we may be doing shifts and ors to
2311       // assemble the elements of the vector manually.  Try to rip the code out
2312       // and replace it with insertelements.
2313       if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
2314         return replaceInstUsesWith(CI, V);
2315     }
2316   }
2317 
2318   if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
2319     if (SrcVTy->getNumElements() == 1) {
2320       // If our destination is not a vector, then make this a straight
2321       // scalar-scalar cast.
2322       if (!DestTy->isVectorTy()) {
2323         Value *Elem =
2324           Builder.CreateExtractElement(Src,
2325                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2326         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
2327       }
2328 
2329       // Otherwise, see if our source is an insert. If so, then use the scalar
2330       // component directly.
2331       if (InsertElementInst *IEI =
2332             dyn_cast<InsertElementInst>(CI.getOperand(0)))
2333         return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
2334                                 DestTy);
2335     }
2336   }
2337 
2338   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
2339     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
2340     // a bitcast to a vector with the same # elts.
2341     if (SVI->hasOneUse() && DestTy->isVectorTy() &&
2342         DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
2343         SVI->getType()->getNumElements() ==
2344         SVI->getOperand(0)->getType()->getVectorNumElements()) {
2345       BitCastInst *Tmp;
2346       // If either of the operands is a cast from CI.getType(), then
2347       // evaluating the shuffle in the casted destination's type will allow
2348       // us to eliminate at least one cast.
2349       if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
2350            Tmp->getOperand(0)->getType() == DestTy) ||
2351           ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
2352            Tmp->getOperand(0)->getType() == DestTy)) {
2353         Value *LHS = Builder.CreateBitCast(SVI->getOperand(0), DestTy);
2354         Value *RHS = Builder.CreateBitCast(SVI->getOperand(1), DestTy);
2355         // Return a new shuffle vector.  Use the same element ID's, as we
2356         // know the vector types match #elts.
2357         return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
2358       }
2359     }
2360   }
2361 
2362   // Handle the A->B->A cast, and there is an intervening PHI node.
2363   if (PHINode *PN = dyn_cast<PHINode>(Src))
2364     if (Instruction *I = optimizeBitCastFromPhi(CI, PN))
2365       return I;
2366 
2367   if (Instruction *I = canonicalizeBitCastExtElt(CI, *this))
2368     return I;
2369 
2370   if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder))
2371     return I;
2372 
2373   if (Instruction *I = foldBitCastSelect(CI, Builder))
2374     return I;
2375 
2376   if (SrcTy->isPointerTy())
2377     return commonPointerCastTransforms(CI);
2378   return commonCastTransforms(CI);
2379 }
2380 
2381 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
2382   // If the destination pointer element type is not the same as the source's
2383   // first do a bitcast to the destination type, and then the addrspacecast.
2384   // This allows the cast to be exposed to other transforms.
2385   Value *Src = CI.getOperand(0);
2386   PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
2387   PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
2388 
2389   Type *DestElemTy = DestTy->getElementType();
2390   if (SrcTy->getElementType() != DestElemTy) {
2391     Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
2392     if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
2393       // Handle vectors of pointers.
2394       MidTy = VectorType::get(MidTy, VT->getNumElements());
2395     }
2396 
2397     Value *NewBitCast = Builder.CreateBitCast(Src, MidTy);
2398     return new AddrSpaceCastInst(NewBitCast, CI.getType());
2399   }
2400 
2401   return commonPointerCastTransforms(CI);
2402 }
2403