xref: /llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp (revision 269e3f7369d2286a1e711a7fa0442ca64817ff9f)
1 //===- InstCombineCasts.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visit functions for cast operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/PatternMatch.h"
18 #include "llvm/Support/KnownBits.h"
19 #include "llvm/Transforms/InstCombine/InstCombiner.h"
20 using namespace llvm;
21 using namespace PatternMatch;
22 
23 #define DEBUG_TYPE "instcombine"
24 
25 /// Analyze 'Val', seeing if it is a simple linear expression.
26 /// If so, decompose it, returning some value X, such that Val is
27 /// X*Scale+Offset.
28 ///
29 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
30                                         uint64_t &Offset) {
31   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
32     Offset = CI->getZExtValue();
33     Scale  = 0;
34     return ConstantInt::get(Val->getType(), 0);
35   }
36 
37   if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
38     // Cannot look past anything that might overflow.
39     OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
40     if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
41       Scale = 1;
42       Offset = 0;
43       return Val;
44     }
45 
46     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
47       if (I->getOpcode() == Instruction::Shl) {
48         // This is a value scaled by '1 << the shift amt'.
49         Scale = UINT64_C(1) << RHS->getZExtValue();
50         Offset = 0;
51         return I->getOperand(0);
52       }
53 
54       if (I->getOpcode() == Instruction::Mul) {
55         // This value is scaled by 'RHS'.
56         Scale = RHS->getZExtValue();
57         Offset = 0;
58         return I->getOperand(0);
59       }
60 
61       if (I->getOpcode() == Instruction::Add) {
62         // We have X+C.  Check to see if we really have (X*C2)+C1,
63         // where C1 is divisible by C2.
64         unsigned SubScale;
65         Value *SubVal =
66           decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
67         Offset += RHS->getZExtValue();
68         Scale = SubScale;
69         return SubVal;
70       }
71     }
72   }
73 
74   // Otherwise, we can't look past this.
75   Scale = 1;
76   Offset = 0;
77   return Val;
78 }
79 
80 /// If we find a cast of an allocation instruction, try to eliminate the cast by
81 /// moving the type information into the alloc.
82 Instruction *InstCombinerImpl::PromoteCastOfAllocation(BitCastInst &CI,
83                                                        AllocaInst &AI) {
84   PointerType *PTy = cast<PointerType>(CI.getType());
85   // Opaque pointers don't have an element type we could replace with.
86   if (PTy->isOpaque())
87     return nullptr;
88 
89   IRBuilderBase::InsertPointGuard Guard(Builder);
90   Builder.SetInsertPoint(&AI);
91 
92   // Get the type really allocated and the type casted to.
93   Type *AllocElTy = AI.getAllocatedType();
94   Type *CastElTy = PTy->getNonOpaquePointerElementType();
95   if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
96 
97   // This optimisation does not work for cases where the cast type
98   // is scalable and the allocated type is not. This because we need to
99   // know how many times the casted type fits into the allocated type.
100   // For the opposite case where the allocated type is scalable and the
101   // cast type is not this leads to poor code quality due to the
102   // introduction of 'vscale' into the calculations. It seems better to
103   // bail out for this case too until we've done a proper cost-benefit
104   // analysis.
105   bool AllocIsScalable = isa<ScalableVectorType>(AllocElTy);
106   bool CastIsScalable = isa<ScalableVectorType>(CastElTy);
107   if (AllocIsScalable != CastIsScalable) return nullptr;
108 
109   Align AllocElTyAlign = DL.getABITypeAlign(AllocElTy);
110   Align CastElTyAlign = DL.getABITypeAlign(CastElTy);
111   if (CastElTyAlign < AllocElTyAlign) return nullptr;
112 
113   // If the allocation has multiple uses, only promote it if we are strictly
114   // increasing the alignment of the resultant allocation.  If we keep it the
115   // same, we open the door to infinite loops of various kinds.
116   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
117 
118   // The alloc and cast types should be either both fixed or both scalable.
119   uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy).getKnownMinSize();
120   uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy).getKnownMinSize();
121   if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
122 
123   // If the allocation has multiple uses, only promote it if we're not
124   // shrinking the amount of memory being allocated.
125   uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy).getKnownMinSize();
126   uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy).getKnownMinSize();
127   if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
128 
129   // See if we can satisfy the modulus by pulling a scale out of the array
130   // size argument.
131   unsigned ArraySizeScale;
132   uint64_t ArrayOffset;
133   Value *NumElements = // See if the array size is a decomposable linear expr.
134     decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
135 
136   // If we can now satisfy the modulus, by using a non-1 scale, we really can
137   // do the xform.
138   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
139       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return nullptr;
140 
141   // We don't currently support arrays of scalable types.
142   assert(!AllocIsScalable || (ArrayOffset == 1 && ArraySizeScale == 0));
143 
144   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
145   Value *Amt = nullptr;
146   if (Scale == 1) {
147     Amt = NumElements;
148   } else {
149     Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
150     // Insert before the alloca, not before the cast.
151     Amt = Builder.CreateMul(Amt, NumElements);
152   }
153 
154   if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
155     Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
156                                   Offset, true);
157     Amt = Builder.CreateAdd(Amt, Off);
158   }
159 
160   AllocaInst *New = Builder.CreateAlloca(CastElTy, AI.getAddressSpace(), Amt);
161   New->setAlignment(AI.getAlign());
162   New->takeName(&AI);
163   New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
164 
165   // If the allocation has multiple real uses, insert a cast and change all
166   // things that used it to use the new cast.  This will also hack on CI, but it
167   // will die soon.
168   if (!AI.hasOneUse()) {
169     // New is the allocation instruction, pointer typed. AI is the original
170     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
171     Value *NewCast = Builder.CreateBitCast(New, AI.getType(), "tmpcast");
172     replaceInstUsesWith(AI, NewCast);
173     eraseInstFromFunction(AI);
174   }
175   return replaceInstUsesWith(CI, New);
176 }
177 
178 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns
179 /// true for, actually insert the code to evaluate the expression.
180 Value *InstCombinerImpl::EvaluateInDifferentType(Value *V, Type *Ty,
181                                                  bool isSigned) {
182   if (Constant *C = dyn_cast<Constant>(V)) {
183     C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
184     // If we got a constantexpr back, try to simplify it with DL info.
185     return ConstantFoldConstant(C, DL, &TLI);
186   }
187 
188   // Otherwise, it must be an instruction.
189   Instruction *I = cast<Instruction>(V);
190   Instruction *Res = nullptr;
191   unsigned Opc = I->getOpcode();
192   switch (Opc) {
193   case Instruction::Add:
194   case Instruction::Sub:
195   case Instruction::Mul:
196   case Instruction::And:
197   case Instruction::Or:
198   case Instruction::Xor:
199   case Instruction::AShr:
200   case Instruction::LShr:
201   case Instruction::Shl:
202   case Instruction::UDiv:
203   case Instruction::URem: {
204     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
205     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
206     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
207     break;
208   }
209   case Instruction::Trunc:
210   case Instruction::ZExt:
211   case Instruction::SExt:
212     // If the source type of the cast is the type we're trying for then we can
213     // just return the source.  There's no need to insert it because it is not
214     // new.
215     if (I->getOperand(0)->getType() == Ty)
216       return I->getOperand(0);
217 
218     // Otherwise, must be the same type of cast, so just reinsert a new one.
219     // This also handles the case of zext(trunc(x)) -> zext(x).
220     Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
221                                       Opc == Instruction::SExt);
222     break;
223   case Instruction::Select: {
224     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
225     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
226     Res = SelectInst::Create(I->getOperand(0), True, False);
227     break;
228   }
229   case Instruction::PHI: {
230     PHINode *OPN = cast<PHINode>(I);
231     PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
232     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
233       Value *V =
234           EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
235       NPN->addIncoming(V, OPN->getIncomingBlock(i));
236     }
237     Res = NPN;
238     break;
239   }
240   default:
241     // TODO: Can handle more cases here.
242     llvm_unreachable("Unreachable!");
243   }
244 
245   Res->takeName(I);
246   return InsertNewInstWith(Res, *I);
247 }
248 
249 Instruction::CastOps
250 InstCombinerImpl::isEliminableCastPair(const CastInst *CI1,
251                                        const CastInst *CI2) {
252   Type *SrcTy = CI1->getSrcTy();
253   Type *MidTy = CI1->getDestTy();
254   Type *DstTy = CI2->getDestTy();
255 
256   Instruction::CastOps firstOp = CI1->getOpcode();
257   Instruction::CastOps secondOp = CI2->getOpcode();
258   Type *SrcIntPtrTy =
259       SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
260   Type *MidIntPtrTy =
261       MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
262   Type *DstIntPtrTy =
263       DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
264   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
265                                                 DstTy, SrcIntPtrTy, MidIntPtrTy,
266                                                 DstIntPtrTy);
267 
268   // We don't want to form an inttoptr or ptrtoint that converts to an integer
269   // type that differs from the pointer size.
270   if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
271       (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
272     Res = 0;
273 
274   return Instruction::CastOps(Res);
275 }
276 
277 /// Implement the transforms common to all CastInst visitors.
278 Instruction *InstCombinerImpl::commonCastTransforms(CastInst &CI) {
279   Value *Src = CI.getOperand(0);
280   Type *Ty = CI.getType();
281 
282   // Try to eliminate a cast of a cast.
283   if (auto *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
284     if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) {
285       // The first cast (CSrc) is eliminable so we need to fix up or replace
286       // the second cast (CI). CSrc will then have a good chance of being dead.
287       auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty);
288       // Point debug users of the dying cast to the new one.
289       if (CSrc->hasOneUse())
290         replaceAllDbgUsesWith(*CSrc, *Res, CI, DT);
291       return Res;
292     }
293   }
294 
295   if (auto *Sel = dyn_cast<SelectInst>(Src)) {
296     // We are casting a select. Try to fold the cast into the select if the
297     // select does not have a compare instruction with matching operand types
298     // or the select is likely better done in a narrow type.
299     // Creating a select with operands that are different sizes than its
300     // condition may inhibit other folds and lead to worse codegen.
301     auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition());
302     if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType() ||
303         (CI.getOpcode() == Instruction::Trunc &&
304          shouldChangeType(CI.getSrcTy(), CI.getType()))) {
305       if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) {
306         replaceAllDbgUsesWith(*Sel, *NV, CI, DT);
307         return NV;
308       }
309     }
310   }
311 
312   // If we are casting a PHI, then fold the cast into the PHI.
313   if (auto *PN = dyn_cast<PHINode>(Src)) {
314     // Don't do this if it would create a PHI node with an illegal type from a
315     // legal type.
316     if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
317         shouldChangeType(CI.getSrcTy(), CI.getType()))
318       if (Instruction *NV = foldOpIntoPhi(CI, PN))
319         return NV;
320   }
321 
322   // Canonicalize a unary shuffle after the cast if neither operation changes
323   // the size or element size of the input vector.
324   // TODO: We could allow size-changing ops if that doesn't harm codegen.
325   // cast (shuffle X, Mask) --> shuffle (cast X), Mask
326   Value *X;
327   ArrayRef<int> Mask;
328   if (match(Src, m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))) {
329     // TODO: Allow scalable vectors?
330     auto *SrcTy = dyn_cast<FixedVectorType>(X->getType());
331     auto *DestTy = dyn_cast<FixedVectorType>(Ty);
332     if (SrcTy && DestTy &&
333         SrcTy->getNumElements() == DestTy->getNumElements() &&
334         SrcTy->getPrimitiveSizeInBits() == DestTy->getPrimitiveSizeInBits()) {
335       Value *CastX = Builder.CreateCast(CI.getOpcode(), X, DestTy);
336       return new ShuffleVectorInst(CastX, Mask);
337     }
338   }
339 
340   return nullptr;
341 }
342 
343 /// Constants and extensions/truncates from the destination type are always
344 /// free to be evaluated in that type. This is a helper for canEvaluate*.
345 static bool canAlwaysEvaluateInType(Value *V, Type *Ty) {
346   if (isa<Constant>(V))
347     return true;
348   Value *X;
349   if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) &&
350       X->getType() == Ty)
351     return true;
352 
353   return false;
354 }
355 
356 /// Filter out values that we can not evaluate in the destination type for free.
357 /// This is a helper for canEvaluate*.
358 static bool canNotEvaluateInType(Value *V, Type *Ty) {
359   assert(!isa<Constant>(V) && "Constant should already be handled.");
360   if (!isa<Instruction>(V))
361     return true;
362   // We don't extend or shrink something that has multiple uses --  doing so
363   // would require duplicating the instruction which isn't profitable.
364   if (!V->hasOneUse())
365     return true;
366 
367   return false;
368 }
369 
370 /// Return true if we can evaluate the specified expression tree as type Ty
371 /// instead of its larger type, and arrive with the same value.
372 /// This is used by code that tries to eliminate truncates.
373 ///
374 /// Ty will always be a type smaller than V.  We should return true if trunc(V)
375 /// can be computed by computing V in the smaller type.  If V is an instruction,
376 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
377 /// makes sense if x and y can be efficiently truncated.
378 ///
379 /// This function works on both vectors and scalars.
380 ///
381 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombinerImpl &IC,
382                                  Instruction *CxtI) {
383   if (canAlwaysEvaluateInType(V, Ty))
384     return true;
385   if (canNotEvaluateInType(V, Ty))
386     return false;
387 
388   auto *I = cast<Instruction>(V);
389   Type *OrigTy = V->getType();
390   switch (I->getOpcode()) {
391   case Instruction::Add:
392   case Instruction::Sub:
393   case Instruction::Mul:
394   case Instruction::And:
395   case Instruction::Or:
396   case Instruction::Xor:
397     // These operators can all arbitrarily be extended or truncated.
398     return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
399            canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
400 
401   case Instruction::UDiv:
402   case Instruction::URem: {
403     // UDiv and URem can be truncated if all the truncated bits are zero.
404     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
405     uint32_t BitWidth = Ty->getScalarSizeInBits();
406     assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!");
407     APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
408     if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
409         IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
410       return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
411              canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
412     }
413     break;
414   }
415   case Instruction::Shl: {
416     // If we are truncating the result of this SHL, and if it's a shift of an
417     // inrange amount, we can always perform a SHL in a smaller type.
418     uint32_t BitWidth = Ty->getScalarSizeInBits();
419     KnownBits AmtKnownBits =
420         llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
421     if (AmtKnownBits.getMaxValue().ult(BitWidth))
422       return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
423              canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
424     break;
425   }
426   case Instruction::LShr: {
427     // If this is a truncate of a logical shr, we can truncate it to a smaller
428     // lshr iff we know that the bits we would otherwise be shifting in are
429     // already zeros.
430     // TODO: It is enough to check that the bits we would be shifting in are
431     //       zero - use AmtKnownBits.getMaxValue().
432     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
433     uint32_t BitWidth = Ty->getScalarSizeInBits();
434     KnownBits AmtKnownBits =
435         llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
436     APInt ShiftedBits = APInt::getBitsSetFrom(OrigBitWidth, BitWidth);
437     if (AmtKnownBits.getMaxValue().ult(BitWidth) &&
438         IC.MaskedValueIsZero(I->getOperand(0), ShiftedBits, 0, CxtI)) {
439       return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
440              canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
441     }
442     break;
443   }
444   case Instruction::AShr: {
445     // If this is a truncate of an arithmetic shr, we can truncate it to a
446     // smaller ashr iff we know that all the bits from the sign bit of the
447     // original type and the sign bit of the truncate type are similar.
448     // TODO: It is enough to check that the bits we would be shifting in are
449     //       similar to sign bit of the truncate type.
450     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
451     uint32_t BitWidth = Ty->getScalarSizeInBits();
452     KnownBits AmtKnownBits =
453         llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout());
454     unsigned ShiftedBits = OrigBitWidth - BitWidth;
455     if (AmtKnownBits.getMaxValue().ult(BitWidth) &&
456         ShiftedBits < IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI))
457       return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
458              canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
459     break;
460   }
461   case Instruction::Trunc:
462     // trunc(trunc(x)) -> trunc(x)
463     return true;
464   case Instruction::ZExt:
465   case Instruction::SExt:
466     // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
467     // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
468     return true;
469   case Instruction::Select: {
470     SelectInst *SI = cast<SelectInst>(I);
471     return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
472            canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
473   }
474   case Instruction::PHI: {
475     // We can change a phi if we can change all operands.  Note that we never
476     // get into trouble with cyclic PHIs here because we only consider
477     // instructions with a single use.
478     PHINode *PN = cast<PHINode>(I);
479     for (Value *IncValue : PN->incoming_values())
480       if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI))
481         return false;
482     return true;
483   }
484   default:
485     // TODO: Can handle more cases here.
486     break;
487   }
488 
489   return false;
490 }
491 
492 /// Given a vector that is bitcast to an integer, optionally logically
493 /// right-shifted, and truncated, convert it to an extractelement.
494 /// Example (big endian):
495 ///   trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32
496 ///   --->
497 ///   extractelement <4 x i32> %X, 1
498 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc,
499                                          InstCombinerImpl &IC) {
500   Value *TruncOp = Trunc.getOperand(0);
501   Type *DestType = Trunc.getType();
502   if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType))
503     return nullptr;
504 
505   Value *VecInput = nullptr;
506   ConstantInt *ShiftVal = nullptr;
507   if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)),
508                                   m_LShr(m_BitCast(m_Value(VecInput)),
509                                          m_ConstantInt(ShiftVal)))) ||
510       !isa<VectorType>(VecInput->getType()))
511     return nullptr;
512 
513   VectorType *VecType = cast<VectorType>(VecInput->getType());
514   unsigned VecWidth = VecType->getPrimitiveSizeInBits();
515   unsigned DestWidth = DestType->getPrimitiveSizeInBits();
516   unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0;
517 
518   if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
519     return nullptr;
520 
521   // If the element type of the vector doesn't match the result type,
522   // bitcast it to a vector type that we can extract from.
523   unsigned NumVecElts = VecWidth / DestWidth;
524   if (VecType->getElementType() != DestType) {
525     VecType = FixedVectorType::get(DestType, NumVecElts);
526     VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc");
527   }
528 
529   unsigned Elt = ShiftAmount / DestWidth;
530   if (IC.getDataLayout().isBigEndian())
531     Elt = NumVecElts - 1 - Elt;
532 
533   return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt));
534 }
535 
536 /// Funnel/Rotate left/right may occur in a wider type than necessary because of
537 /// type promotion rules. Try to narrow the inputs and convert to funnel shift.
538 Instruction *InstCombinerImpl::narrowFunnelShift(TruncInst &Trunc) {
539   assert((isa<VectorType>(Trunc.getSrcTy()) ||
540           shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) &&
541          "Don't narrow to an illegal scalar type");
542 
543   // Bail out on strange types. It is possible to handle some of these patterns
544   // even with non-power-of-2 sizes, but it is not a likely scenario.
545   Type *DestTy = Trunc.getType();
546   unsigned NarrowWidth = DestTy->getScalarSizeInBits();
547   unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits();
548   if (!isPowerOf2_32(NarrowWidth))
549     return nullptr;
550 
551   // First, find an or'd pair of opposite shifts:
552   // trunc (or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1))
553   BinaryOperator *Or0, *Or1;
554   if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
555     return nullptr;
556 
557   Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
558   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
559       !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
560       Or0->getOpcode() == Or1->getOpcode())
561     return nullptr;
562 
563   // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
564   if (Or0->getOpcode() == BinaryOperator::LShr) {
565     std::swap(Or0, Or1);
566     std::swap(ShVal0, ShVal1);
567     std::swap(ShAmt0, ShAmt1);
568   }
569   assert(Or0->getOpcode() == BinaryOperator::Shl &&
570          Or1->getOpcode() == BinaryOperator::LShr &&
571          "Illegal or(shift,shift) pair");
572 
573   // Match the shift amount operands for a funnel/rotate pattern. This always
574   // matches a subtraction on the R operand.
575   auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
576     // The shift amounts may add up to the narrow bit width:
577     // (shl ShVal0, L) | (lshr ShVal1, Width - L)
578     // If this is a funnel shift (different operands are shifted), then the
579     // shift amount can not over-shift (create poison) in the narrow type.
580     unsigned MaxShiftAmountWidth = Log2_32(NarrowWidth);
581     APInt HiBitMask = ~APInt::getLowBitsSet(WideWidth, MaxShiftAmountWidth);
582     if (ShVal0 == ShVal1 || MaskedValueIsZero(L, HiBitMask))
583       if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L)))))
584         return L;
585 
586     // The following patterns currently only work for rotation patterns.
587     // TODO: Add more general funnel-shift compatible patterns.
588     if (ShVal0 != ShVal1)
589       return nullptr;
590 
591     // The shift amount may be masked with negation:
592     // (shl ShVal0, (X & (Width - 1))) | (lshr ShVal1, ((-X) & (Width - 1)))
593     Value *X;
594     unsigned Mask = Width - 1;
595     if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
596         match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
597       return X;
598 
599     // Same as above, but the shift amount may be extended after masking:
600     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
601         match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
602       return X;
603 
604     return nullptr;
605   };
606 
607   Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth);
608   bool IsFshl = true; // Sub on LSHR.
609   if (!ShAmt) {
610     ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth);
611     IsFshl = false; // Sub on SHL.
612   }
613   if (!ShAmt)
614     return nullptr;
615 
616   // The right-shifted value must have high zeros in the wide type (for example
617   // from 'zext', 'and' or 'shift'). High bits of the left-shifted value are
618   // truncated, so those do not matter.
619   APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth);
620   if (!MaskedValueIsZero(ShVal1, HiBitMask, 0, &Trunc))
621     return nullptr;
622 
623   // We have an unnecessarily wide rotate!
624   // trunc (or (shl ShVal0, ShAmt), (lshr ShVal1, BitWidth - ShAmt))
625   // Narrow the inputs and convert to funnel shift intrinsic:
626   // llvm.fshl.i8(trunc(ShVal), trunc(ShVal), trunc(ShAmt))
627   Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy);
628   Value *X, *Y;
629   X = Y = Builder.CreateTrunc(ShVal0, DestTy);
630   if (ShVal0 != ShVal1)
631     Y = Builder.CreateTrunc(ShVal1, DestTy);
632   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
633   Function *F = Intrinsic::getDeclaration(Trunc.getModule(), IID, DestTy);
634   return CallInst::Create(F, {X, Y, NarrowShAmt});
635 }
636 
637 /// Try to narrow the width of math or bitwise logic instructions by pulling a
638 /// truncate ahead of binary operators.
639 Instruction *InstCombinerImpl::narrowBinOp(TruncInst &Trunc) {
640   Type *SrcTy = Trunc.getSrcTy();
641   Type *DestTy = Trunc.getType();
642   unsigned SrcWidth = SrcTy->getScalarSizeInBits();
643   unsigned DestWidth = DestTy->getScalarSizeInBits();
644 
645   if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy))
646     return nullptr;
647 
648   BinaryOperator *BinOp;
649   if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp))))
650     return nullptr;
651 
652   Value *BinOp0 = BinOp->getOperand(0);
653   Value *BinOp1 = BinOp->getOperand(1);
654   switch (BinOp->getOpcode()) {
655   case Instruction::And:
656   case Instruction::Or:
657   case Instruction::Xor:
658   case Instruction::Add:
659   case Instruction::Sub:
660   case Instruction::Mul: {
661     Constant *C;
662     if (match(BinOp0, m_Constant(C))) {
663       // trunc (binop C, X) --> binop (trunc C', X)
664       Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
665       Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
666       return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX);
667     }
668     if (match(BinOp1, m_Constant(C))) {
669       // trunc (binop X, C) --> binop (trunc X, C')
670       Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy);
671       Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
672       return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC);
673     }
674     Value *X;
675     if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
676       // trunc (binop (ext X), Y) --> binop X, (trunc Y)
677       Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
678       return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1);
679     }
680     if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) {
681       // trunc (binop Y, (ext X)) --> binop (trunc Y), X
682       Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
683       return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X);
684     }
685     break;
686   }
687   case Instruction::LShr:
688   case Instruction::AShr: {
689     // trunc (*shr (trunc A), C) --> trunc(*shr A, C)
690     Value *A;
691     Constant *C;
692     if (match(BinOp0, m_Trunc(m_Value(A))) && match(BinOp1, m_Constant(C))) {
693       unsigned MaxShiftAmt = SrcWidth - DestWidth;
694       // If the shift is small enough, all zero/sign bits created by the shift
695       // are removed by the trunc.
696       if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE,
697                                       APInt(SrcWidth, MaxShiftAmt)))) {
698         auto *OldShift = cast<Instruction>(Trunc.getOperand(0));
699         bool IsExact = OldShift->isExact();
700         auto *ShAmt = ConstantExpr::getIntegerCast(C, A->getType(), true);
701         ShAmt = Constant::mergeUndefsWith(ShAmt, C);
702         Value *Shift =
703             OldShift->getOpcode() == Instruction::AShr
704                 ? Builder.CreateAShr(A, ShAmt, OldShift->getName(), IsExact)
705                 : Builder.CreateLShr(A, ShAmt, OldShift->getName(), IsExact);
706         return CastInst::CreateTruncOrBitCast(Shift, DestTy);
707       }
708     }
709     break;
710   }
711   default: break;
712   }
713 
714   if (Instruction *NarrowOr = narrowFunnelShift(Trunc))
715     return NarrowOr;
716 
717   return nullptr;
718 }
719 
720 /// Try to narrow the width of a splat shuffle. This could be generalized to any
721 /// shuffle with a constant operand, but we limit the transform to avoid
722 /// creating a shuffle type that targets may not be able to lower effectively.
723 static Instruction *shrinkSplatShuffle(TruncInst &Trunc,
724                                        InstCombiner::BuilderTy &Builder) {
725   auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0));
726   if (Shuf && Shuf->hasOneUse() && match(Shuf->getOperand(1), m_Undef()) &&
727       is_splat(Shuf->getShuffleMask()) &&
728       Shuf->getType() == Shuf->getOperand(0)->getType()) {
729     // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Poison, SplatMask
730     // trunc (shuf X, Poison, SplatMask) --> shuf (trunc X), Poison, SplatMask
731     Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType());
732     return new ShuffleVectorInst(NarrowOp, Shuf->getShuffleMask());
733   }
734 
735   return nullptr;
736 }
737 
738 /// Try to narrow the width of an insert element. This could be generalized for
739 /// any vector constant, but we limit the transform to insertion into undef to
740 /// avoid potential backend problems from unsupported insertion widths. This
741 /// could also be extended to handle the case of inserting a scalar constant
742 /// into a vector variable.
743 static Instruction *shrinkInsertElt(CastInst &Trunc,
744                                     InstCombiner::BuilderTy &Builder) {
745   Instruction::CastOps Opcode = Trunc.getOpcode();
746   assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
747          "Unexpected instruction for shrinking");
748 
749   auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0));
750   if (!InsElt || !InsElt->hasOneUse())
751     return nullptr;
752 
753   Type *DestTy = Trunc.getType();
754   Type *DestScalarTy = DestTy->getScalarType();
755   Value *VecOp = InsElt->getOperand(0);
756   Value *ScalarOp = InsElt->getOperand(1);
757   Value *Index = InsElt->getOperand(2);
758 
759   if (match(VecOp, m_Undef())) {
760     // trunc   (inselt undef, X, Index) --> inselt undef,   (trunc X), Index
761     // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index
762     UndefValue *NarrowUndef = UndefValue::get(DestTy);
763     Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy);
764     return InsertElementInst::Create(NarrowUndef, NarrowOp, Index);
765   }
766 
767   return nullptr;
768 }
769 
770 Instruction *InstCombinerImpl::visitTrunc(TruncInst &Trunc) {
771   if (Instruction *Result = commonCastTransforms(Trunc))
772     return Result;
773 
774   Value *Src = Trunc.getOperand(0);
775   Type *DestTy = Trunc.getType(), *SrcTy = Src->getType();
776   unsigned DestWidth = DestTy->getScalarSizeInBits();
777   unsigned SrcWidth = SrcTy->getScalarSizeInBits();
778 
779   // Attempt to truncate the entire input expression tree to the destination
780   // type.   Only do this if the dest type is a simple type, don't convert the
781   // expression tree to something weird like i93 unless the source is also
782   // strange.
783   if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
784       canEvaluateTruncated(Src, DestTy, *this, &Trunc)) {
785 
786     // If this cast is a truncate, evaluting in a different type always
787     // eliminates the cast, so it is always a win.
788     LLVM_DEBUG(
789         dbgs() << "ICE: EvaluateInDifferentType converting expression type"
790                   " to avoid cast: "
791                << Trunc << '\n');
792     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
793     assert(Res->getType() == DestTy);
794     return replaceInstUsesWith(Trunc, Res);
795   }
796 
797   // For integer types, check if we can shorten the entire input expression to
798   // DestWidth * 2, which won't allow removing the truncate, but reducing the
799   // width may enable further optimizations, e.g. allowing for larger
800   // vectorization factors.
801   if (auto *DestITy = dyn_cast<IntegerType>(DestTy)) {
802     if (DestWidth * 2 < SrcWidth) {
803       auto *NewDestTy = DestITy->getExtendedType();
804       if (shouldChangeType(SrcTy, NewDestTy) &&
805           canEvaluateTruncated(Src, NewDestTy, *this, &Trunc)) {
806         LLVM_DEBUG(
807             dbgs() << "ICE: EvaluateInDifferentType converting expression type"
808                       " to reduce the width of operand of"
809                    << Trunc << '\n');
810         Value *Res = EvaluateInDifferentType(Src, NewDestTy, false);
811         return new TruncInst(Res, DestTy);
812       }
813     }
814   }
815 
816   // Test if the trunc is the user of a select which is part of a
817   // minimum or maximum operation. If so, don't do any more simplification.
818   // Even simplifying demanded bits can break the canonical form of a
819   // min/max.
820   Value *LHS, *RHS;
821   if (SelectInst *Sel = dyn_cast<SelectInst>(Src))
822     if (matchSelectPattern(Sel, LHS, RHS).Flavor != SPF_UNKNOWN)
823       return nullptr;
824 
825   // See if we can simplify any instructions used by the input whose sole
826   // purpose is to compute bits we don't care about.
827   if (SimplifyDemandedInstructionBits(Trunc))
828     return &Trunc;
829 
830   if (DestWidth == 1) {
831     Value *Zero = Constant::getNullValue(SrcTy);
832     if (DestTy->isIntegerTy()) {
833       // Canonicalize trunc x to i1 -> icmp ne (and x, 1), 0 (scalar only).
834       // TODO: We canonicalize to more instructions here because we are probably
835       // lacking equivalent analysis for trunc relative to icmp. There may also
836       // be codegen concerns. If those trunc limitations were removed, we could
837       // remove this transform.
838       Value *And = Builder.CreateAnd(Src, ConstantInt::get(SrcTy, 1));
839       return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
840     }
841 
842     // For vectors, we do not canonicalize all truncs to icmp, so optimize
843     // patterns that would be covered within visitICmpInst.
844     Value *X;
845     Constant *C;
846     if (match(Src, m_OneUse(m_LShr(m_Value(X), m_Constant(C))))) {
847       // trunc (lshr X, C) to i1 --> icmp ne (and X, C'), 0
848       Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
849       Constant *MaskC = ConstantExpr::getShl(One, C);
850       Value *And = Builder.CreateAnd(X, MaskC);
851       return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
852     }
853     if (match(Src, m_OneUse(m_c_Or(m_LShr(m_Value(X), m_Constant(C)),
854                                    m_Deferred(X))))) {
855       // trunc (or (lshr X, C), X) to i1 --> icmp ne (and X, C'), 0
856       Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1));
857       Constant *MaskC = ConstantExpr::getShl(One, C);
858       MaskC = ConstantExpr::getOr(MaskC, One);
859       Value *And = Builder.CreateAnd(X, MaskC);
860       return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
861     }
862   }
863 
864   Value *A, *B;
865   Constant *C;
866   if (match(Src, m_LShr(m_SExt(m_Value(A)), m_Constant(C)))) {
867     unsigned AWidth = A->getType()->getScalarSizeInBits();
868     unsigned MaxShiftAmt = SrcWidth - std::max(DestWidth, AWidth);
869     auto *OldSh = cast<Instruction>(Src);
870     bool IsExact = OldSh->isExact();
871 
872     // If the shift is small enough, all zero bits created by the shift are
873     // removed by the trunc.
874     if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULE,
875                                     APInt(SrcWidth, MaxShiftAmt)))) {
876       // trunc (lshr (sext A), C) --> ashr A, C
877       if (A->getType() == DestTy) {
878         Constant *MaxAmt = ConstantInt::get(SrcTy, DestWidth - 1, false);
879         Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt);
880         ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType());
881         ShAmt = Constant::mergeUndefsWith(ShAmt, C);
882         return IsExact ? BinaryOperator::CreateExactAShr(A, ShAmt)
883                        : BinaryOperator::CreateAShr(A, ShAmt);
884       }
885       // The types are mismatched, so create a cast after shifting:
886       // trunc (lshr (sext A), C) --> sext/trunc (ashr A, C)
887       if (Src->hasOneUse()) {
888         Constant *MaxAmt = ConstantInt::get(SrcTy, AWidth - 1, false);
889         Constant *ShAmt = ConstantExpr::getUMin(C, MaxAmt);
890         ShAmt = ConstantExpr::getTrunc(ShAmt, A->getType());
891         Value *Shift = Builder.CreateAShr(A, ShAmt, "", IsExact);
892         return CastInst::CreateIntegerCast(Shift, DestTy, true);
893       }
894     }
895     // TODO: Mask high bits with 'and'.
896   }
897 
898   if (Instruction *I = narrowBinOp(Trunc))
899     return I;
900 
901   if (Instruction *I = shrinkSplatShuffle(Trunc, Builder))
902     return I;
903 
904   if (Instruction *I = shrinkInsertElt(Trunc, Builder))
905     return I;
906 
907   if (Src->hasOneUse() &&
908       (isa<VectorType>(SrcTy) || shouldChangeType(SrcTy, DestTy))) {
909     // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the
910     // dest type is native and cst < dest size.
911     if (match(Src, m_Shl(m_Value(A), m_Constant(C))) &&
912         !match(A, m_Shr(m_Value(), m_Constant()))) {
913       // Skip shifts of shift by constants. It undoes a combine in
914       // FoldShiftByConstant and is the extend in reg pattern.
915       APInt Threshold = APInt(C->getType()->getScalarSizeInBits(), DestWidth);
916       if (match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold))) {
917         Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr");
918         return BinaryOperator::Create(Instruction::Shl, NewTrunc,
919                                       ConstantExpr::getTrunc(C, DestTy));
920       }
921     }
922   }
923 
924   if (Instruction *I = foldVecTruncToExtElt(Trunc, *this))
925     return I;
926 
927   // Whenever an element is extracted from a vector, and then truncated,
928   // canonicalize by converting it to a bitcast followed by an
929   // extractelement.
930   //
931   // Example (little endian):
932   //   trunc (extractelement <4 x i64> %X, 0) to i32
933   //   --->
934   //   extractelement <8 x i32> (bitcast <4 x i64> %X to <8 x i32>), i32 0
935   Value *VecOp;
936   ConstantInt *Cst;
937   if (match(Src, m_OneUse(m_ExtractElt(m_Value(VecOp), m_ConstantInt(Cst))))) {
938     auto *VecOpTy = cast<VectorType>(VecOp->getType());
939     auto VecElts = VecOpTy->getElementCount();
940 
941     // A badly fit destination size would result in an invalid cast.
942     if (SrcWidth % DestWidth == 0) {
943       uint64_t TruncRatio = SrcWidth / DestWidth;
944       uint64_t BitCastNumElts = VecElts.getKnownMinValue() * TruncRatio;
945       uint64_t VecOpIdx = Cst->getZExtValue();
946       uint64_t NewIdx = DL.isBigEndian() ? (VecOpIdx + 1) * TruncRatio - 1
947                                          : VecOpIdx * TruncRatio;
948       assert(BitCastNumElts <= std::numeric_limits<uint32_t>::max() &&
949              "overflow 32-bits");
950 
951       auto *BitCastTo =
952           VectorType::get(DestTy, BitCastNumElts, VecElts.isScalable());
953       Value *BitCast = Builder.CreateBitCast(VecOp, BitCastTo);
954       return ExtractElementInst::Create(BitCast, Builder.getInt32(NewIdx));
955     }
956   }
957 
958   // trunc (ctlz_i32(zext(A), B) --> add(ctlz_i16(A, B), C)
959   if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ctlz>(m_ZExt(m_Value(A)),
960                                                        m_Value(B))))) {
961     unsigned AWidth = A->getType()->getScalarSizeInBits();
962     if (AWidth == DestWidth && AWidth > Log2_32(SrcWidth)) {
963       Value *WidthDiff = ConstantInt::get(A->getType(), SrcWidth - AWidth);
964       Value *NarrowCtlz =
965           Builder.CreateIntrinsic(Intrinsic::ctlz, {Trunc.getType()}, {A, B});
966       return BinaryOperator::CreateAdd(NarrowCtlz, WidthDiff);
967     }
968   }
969 
970   if (match(Src, m_VScale(DL))) {
971     if (Trunc.getFunction() &&
972         Trunc.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
973       Attribute Attr =
974           Trunc.getFunction()->getFnAttribute(Attribute::VScaleRange);
975       if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
976         if (Log2_32(MaxVScale.getValue()) < DestWidth) {
977           Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
978           return replaceInstUsesWith(Trunc, VScale);
979         }
980       }
981     }
982   }
983 
984   return nullptr;
985 }
986 
987 Instruction *InstCombinerImpl::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext) {
988   // If we are just checking for a icmp eq of a single bit and zext'ing it
989   // to an integer, then shift the bit to the appropriate place and then
990   // cast to integer to avoid the comparison.
991 
992   // FIXME: This set of transforms does not check for extra uses and/or creates
993   //        an extra instruction (an optional final cast is not included
994   //        in the transform comments). We may also want to favor icmp over
995   //        shifts in cases of equal instructions because icmp has better
996   //        analysis in general (invert the transform).
997 
998   const APInt *Op1CV;
999   if (match(Cmp->getOperand(1), m_APInt(Op1CV))) {
1000 
1001     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
1002     if (Cmp->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isZero()) {
1003       Value *In = Cmp->getOperand(0);
1004       Value *Sh = ConstantInt::get(In->getType(),
1005                                    In->getType()->getScalarSizeInBits() - 1);
1006       In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit");
1007       if (In->getType() != Zext.getType())
1008         In = Builder.CreateIntCast(In, Zext.getType(), false /*ZExt*/);
1009 
1010       return replaceInstUsesWith(Zext, In);
1011     }
1012 
1013     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
1014     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
1015     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
1016     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
1017     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
1018     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
1019     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
1020     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
1021     if ((Op1CV->isZero() || Op1CV->isPowerOf2()) &&
1022         // This only works for EQ and NE
1023         Cmp->isEquality()) {
1024       // If Op1C some other power of two, convert:
1025       KnownBits Known = computeKnownBits(Cmp->getOperand(0), 0, &Zext);
1026 
1027       APInt KnownZeroMask(~Known.Zero);
1028       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
1029         bool isNE = Cmp->getPredicate() == ICmpInst::ICMP_NE;
1030         if (!Op1CV->isZero() && (*Op1CV != KnownZeroMask)) {
1031           // (X&4) == 2 --> false
1032           // (X&4) != 2 --> true
1033           Constant *Res = ConstantInt::get(Zext.getType(), isNE);
1034           return replaceInstUsesWith(Zext, Res);
1035         }
1036 
1037         uint32_t ShAmt = KnownZeroMask.logBase2();
1038         Value *In = Cmp->getOperand(0);
1039         if (ShAmt) {
1040           // Perform a logical shr by shiftamt.
1041           // Insert the shift to put the result in the low bit.
1042           In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt),
1043                                   In->getName() + ".lobit");
1044         }
1045 
1046         if (!Op1CV->isZero() == isNE) { // Toggle the low bit.
1047           Constant *One = ConstantInt::get(In->getType(), 1);
1048           In = Builder.CreateXor(In, One);
1049         }
1050 
1051         if (Zext.getType() == In->getType())
1052           return replaceInstUsesWith(Zext, In);
1053 
1054         Value *IntCast = Builder.CreateIntCast(In, Zext.getType(), false);
1055         return replaceInstUsesWith(Zext, IntCast);
1056       }
1057     }
1058   }
1059 
1060   if (Cmp->isEquality() && Zext.getType() == Cmp->getOperand(0)->getType()) {
1061     // Test if a bit is clear/set using a shifted-one mask:
1062     // zext (icmp eq (and X, (1 << ShAmt)), 0) --> and (lshr (not X), ShAmt), 1
1063     // zext (icmp ne (and X, (1 << ShAmt)), 0) --> and (lshr X, ShAmt), 1
1064     Value *X, *ShAmt;
1065     if (Cmp->hasOneUse() && match(Cmp->getOperand(1), m_ZeroInt()) &&
1066         match(Cmp->getOperand(0),
1067               m_OneUse(m_c_And(m_Shl(m_One(), m_Value(ShAmt)), m_Value(X))))) {
1068       if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
1069         X = Builder.CreateNot(X);
1070       Value *Lshr = Builder.CreateLShr(X, ShAmt);
1071       Value *And1 = Builder.CreateAnd(Lshr, ConstantInt::get(X->getType(), 1));
1072       return replaceInstUsesWith(Zext, And1);
1073     }
1074 
1075     // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
1076     // It is also profitable to transform icmp eq into not(xor(A, B)) because
1077     // that may lead to additional simplifications.
1078     if (IntegerType *ITy = dyn_cast<IntegerType>(Zext.getType())) {
1079       Value *LHS = Cmp->getOperand(0);
1080       Value *RHS = Cmp->getOperand(1);
1081 
1082       KnownBits KnownLHS = computeKnownBits(LHS, 0, &Zext);
1083       KnownBits KnownRHS = computeKnownBits(RHS, 0, &Zext);
1084 
1085       if (KnownLHS == KnownRHS) {
1086         APInt KnownBits = KnownLHS.Zero | KnownLHS.One;
1087         APInt UnknownBit = ~KnownBits;
1088         if (UnknownBit.countPopulation() == 1) {
1089           Value *Result = Builder.CreateXor(LHS, RHS);
1090 
1091           // Mask off any bits that are set and won't be shifted away.
1092           if (KnownLHS.One.uge(UnknownBit))
1093             Result = Builder.CreateAnd(Result,
1094                                         ConstantInt::get(ITy, UnknownBit));
1095 
1096           // Shift the bit we're testing down to the lsb.
1097           Result = Builder.CreateLShr(
1098                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
1099 
1100           if (Cmp->getPredicate() == ICmpInst::ICMP_EQ)
1101             Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1));
1102           Result->takeName(Cmp);
1103           return replaceInstUsesWith(Zext, Result);
1104         }
1105       }
1106     }
1107   }
1108 
1109   return nullptr;
1110 }
1111 
1112 /// Determine if the specified value can be computed in the specified wider type
1113 /// and produce the same low bits. If not, return false.
1114 ///
1115 /// If this function returns true, it can also return a non-zero number of bits
1116 /// (in BitsToClear) which indicates that the value it computes is correct for
1117 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
1118 /// out.  For example, to promote something like:
1119 ///
1120 ///   %B = trunc i64 %A to i32
1121 ///   %C = lshr i32 %B, 8
1122 ///   %E = zext i32 %C to i64
1123 ///
1124 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
1125 /// set to 8 to indicate that the promoted value needs to have bits 24-31
1126 /// cleared in addition to bits 32-63.  Since an 'and' will be generated to
1127 /// clear the top bits anyway, doing this has no extra cost.
1128 ///
1129 /// This function works on both vectors and scalars.
1130 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
1131                              InstCombinerImpl &IC, Instruction *CxtI) {
1132   BitsToClear = 0;
1133   if (canAlwaysEvaluateInType(V, Ty))
1134     return true;
1135   if (canNotEvaluateInType(V, Ty))
1136     return false;
1137 
1138   auto *I = cast<Instruction>(V);
1139   unsigned Tmp;
1140   switch (I->getOpcode()) {
1141   case Instruction::ZExt:  // zext(zext(x)) -> zext(x).
1142   case Instruction::SExt:  // zext(sext(x)) -> sext(x).
1143   case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
1144     return true;
1145   case Instruction::And:
1146   case Instruction::Or:
1147   case Instruction::Xor:
1148   case Instruction::Add:
1149   case Instruction::Sub:
1150   case Instruction::Mul:
1151     if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
1152         !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
1153       return false;
1154     // These can all be promoted if neither operand has 'bits to clear'.
1155     if (BitsToClear == 0 && Tmp == 0)
1156       return true;
1157 
1158     // If the operation is an AND/OR/XOR and the bits to clear are zero in the
1159     // other side, BitsToClear is ok.
1160     if (Tmp == 0 && I->isBitwiseLogicOp()) {
1161       // We use MaskedValueIsZero here for generality, but the case we care
1162       // about the most is constant RHS.
1163       unsigned VSize = V->getType()->getScalarSizeInBits();
1164       if (IC.MaskedValueIsZero(I->getOperand(1),
1165                                APInt::getHighBitsSet(VSize, BitsToClear),
1166                                0, CxtI)) {
1167         // If this is an And instruction and all of the BitsToClear are
1168         // known to be zero we can reset BitsToClear.
1169         if (I->getOpcode() == Instruction::And)
1170           BitsToClear = 0;
1171         return true;
1172       }
1173     }
1174 
1175     // Otherwise, we don't know how to analyze this BitsToClear case yet.
1176     return false;
1177 
1178   case Instruction::Shl: {
1179     // We can promote shl(x, cst) if we can promote x.  Since shl overwrites the
1180     // upper bits we can reduce BitsToClear by the shift amount.
1181     const APInt *Amt;
1182     if (match(I->getOperand(1), m_APInt(Amt))) {
1183       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1184         return false;
1185       uint64_t ShiftAmt = Amt->getZExtValue();
1186       BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
1187       return true;
1188     }
1189     return false;
1190   }
1191   case Instruction::LShr: {
1192     // We can promote lshr(x, cst) if we can promote x.  This requires the
1193     // ultimate 'and' to clear out the high zero bits we're clearing out though.
1194     const APInt *Amt;
1195     if (match(I->getOperand(1), m_APInt(Amt))) {
1196       if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
1197         return false;
1198       BitsToClear += Amt->getZExtValue();
1199       if (BitsToClear > V->getType()->getScalarSizeInBits())
1200         BitsToClear = V->getType()->getScalarSizeInBits();
1201       return true;
1202     }
1203     // Cannot promote variable LSHR.
1204     return false;
1205   }
1206   case Instruction::Select:
1207     if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
1208         !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
1209         // TODO: If important, we could handle the case when the BitsToClear are
1210         // known zero in the disagreeing side.
1211         Tmp != BitsToClear)
1212       return false;
1213     return true;
1214 
1215   case Instruction::PHI: {
1216     // We can change a phi if we can change all operands.  Note that we never
1217     // get into trouble with cyclic PHIs here because we only consider
1218     // instructions with a single use.
1219     PHINode *PN = cast<PHINode>(I);
1220     if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
1221       return false;
1222     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
1223       if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
1224           // TODO: If important, we could handle the case when the BitsToClear
1225           // are known zero in the disagreeing input.
1226           Tmp != BitsToClear)
1227         return false;
1228     return true;
1229   }
1230   default:
1231     // TODO: Can handle more cases here.
1232     return false;
1233   }
1234 }
1235 
1236 Instruction *InstCombinerImpl::visitZExt(ZExtInst &CI) {
1237   // If this zero extend is only used by a truncate, let the truncate be
1238   // eliminated before we try to optimize this zext.
1239   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1240     return nullptr;
1241 
1242   // If one of the common conversion will work, do it.
1243   if (Instruction *Result = commonCastTransforms(CI))
1244     return Result;
1245 
1246   Value *Src = CI.getOperand(0);
1247   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1248 
1249   // Try to extend the entire expression tree to the wide destination type.
1250   unsigned BitsToClear;
1251   if (shouldChangeType(SrcTy, DestTy) &&
1252       canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
1253     assert(BitsToClear <= SrcTy->getScalarSizeInBits() &&
1254            "Can't clear more bits than in SrcTy");
1255 
1256     // Okay, we can transform this!  Insert the new expression now.
1257     LLVM_DEBUG(
1258         dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1259                   " to avoid zero extend: "
1260                << CI << '\n');
1261     Value *Res = EvaluateInDifferentType(Src, DestTy, false);
1262     assert(Res->getType() == DestTy);
1263 
1264     // Preserve debug values referring to Src if the zext is its last use.
1265     if (auto *SrcOp = dyn_cast<Instruction>(Src))
1266       if (SrcOp->hasOneUse())
1267         replaceAllDbgUsesWith(*SrcOp, *Res, CI, DT);
1268 
1269     uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
1270     uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1271 
1272     // If the high bits are already filled with zeros, just replace this
1273     // cast with the result.
1274     if (MaskedValueIsZero(Res,
1275                           APInt::getHighBitsSet(DestBitSize,
1276                                                 DestBitSize-SrcBitsKept),
1277                              0, &CI))
1278       return replaceInstUsesWith(CI, Res);
1279 
1280     // We need to emit an AND to clear the high bits.
1281     Constant *C = ConstantInt::get(Res->getType(),
1282                                APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
1283     return BinaryOperator::CreateAnd(Res, C);
1284   }
1285 
1286   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
1287   // types and if the sizes are just right we can convert this into a logical
1288   // 'and' which will be much cheaper than the pair of casts.
1289   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
1290     // TODO: Subsume this into EvaluateInDifferentType.
1291 
1292     // Get the sizes of the types involved.  We know that the intermediate type
1293     // will be smaller than A or C, but don't know the relation between A and C.
1294     Value *A = CSrc->getOperand(0);
1295     unsigned SrcSize = A->getType()->getScalarSizeInBits();
1296     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
1297     unsigned DstSize = CI.getType()->getScalarSizeInBits();
1298     // If we're actually extending zero bits, then if
1299     // SrcSize <  DstSize: zext(a & mask)
1300     // SrcSize == DstSize: a & mask
1301     // SrcSize  > DstSize: trunc(a) & mask
1302     if (SrcSize < DstSize) {
1303       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1304       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
1305       Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask");
1306       return new ZExtInst(And, CI.getType());
1307     }
1308 
1309     if (SrcSize == DstSize) {
1310       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
1311       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
1312                                                            AndValue));
1313     }
1314     if (SrcSize > DstSize) {
1315       Value *Trunc = Builder.CreateTrunc(A, CI.getType());
1316       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
1317       return BinaryOperator::CreateAnd(Trunc,
1318                                        ConstantInt::get(Trunc->getType(),
1319                                                         AndValue));
1320     }
1321   }
1322 
1323   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Src))
1324     return transformZExtICmp(Cmp, CI);
1325 
1326   // zext(trunc(X) & C) -> (X & zext(C)).
1327   Constant *C;
1328   Value *X;
1329   if (match(Src, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
1330       X->getType() == CI.getType())
1331     return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
1332 
1333   // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
1334   Value *And;
1335   if (match(Src, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
1336       match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
1337       X->getType() == CI.getType()) {
1338     Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
1339     return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
1340   }
1341 
1342   if (match(Src, m_VScale(DL))) {
1343     if (CI.getFunction() &&
1344         CI.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
1345       Attribute Attr = CI.getFunction()->getFnAttribute(Attribute::VScaleRange);
1346       if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
1347         unsigned TypeWidth = Src->getType()->getScalarSizeInBits();
1348         if (Log2_32(MaxVScale.getValue()) < TypeWidth) {
1349           Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
1350           return replaceInstUsesWith(CI, VScale);
1351         }
1352       }
1353     }
1354   }
1355 
1356   return nullptr;
1357 }
1358 
1359 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp.
1360 Instruction *InstCombinerImpl::transformSExtICmp(ICmpInst *ICI,
1361                                                  Instruction &CI) {
1362   Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
1363   ICmpInst::Predicate Pred = ICI->getPredicate();
1364 
1365   // Don't bother if Op1 isn't of vector or integer type.
1366   if (!Op1->getType()->isIntOrIntVectorTy())
1367     return nullptr;
1368 
1369   if ((Pred == ICmpInst::ICMP_SLT && match(Op1, m_ZeroInt())) ||
1370       (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))) {
1371     // (x <s  0) ? -1 : 0 -> ashr x, 31        -> all ones if negative
1372     // (x >s -1) ? -1 : 0 -> not (ashr x, 31)  -> all ones if positive
1373     Value *Sh = ConstantInt::get(Op0->getType(),
1374                                  Op0->getType()->getScalarSizeInBits() - 1);
1375     Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit");
1376     if (In->getType() != CI.getType())
1377       In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/);
1378 
1379     if (Pred == ICmpInst::ICMP_SGT)
1380       In = Builder.CreateNot(In, In->getName() + ".not");
1381     return replaceInstUsesWith(CI, In);
1382   }
1383 
1384   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1385     // If we know that only one bit of the LHS of the icmp can be set and we
1386     // have an equality comparison with zero or a power of 2, we can transform
1387     // the icmp and sext into bitwise/integer operations.
1388     if (ICI->hasOneUse() &&
1389         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
1390       KnownBits Known = computeKnownBits(Op0, 0, &CI);
1391 
1392       APInt KnownZeroMask(~Known.Zero);
1393       if (KnownZeroMask.isPowerOf2()) {
1394         Value *In = ICI->getOperand(0);
1395 
1396         // If the icmp tests for a known zero bit we can constant fold it.
1397         if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
1398           Value *V = Pred == ICmpInst::ICMP_NE ?
1399                        ConstantInt::getAllOnesValue(CI.getType()) :
1400                        ConstantInt::getNullValue(CI.getType());
1401           return replaceInstUsesWith(CI, V);
1402         }
1403 
1404         if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
1405           // sext ((x & 2^n) == 0)   -> (x >> n) - 1
1406           // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
1407           unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
1408           // Perform a right shift to place the desired bit in the LSB.
1409           if (ShiftAmt)
1410             In = Builder.CreateLShr(In,
1411                                     ConstantInt::get(In->getType(), ShiftAmt));
1412 
1413           // At this point "In" is either 1 or 0. Subtract 1 to turn
1414           // {1, 0} -> {0, -1}.
1415           In = Builder.CreateAdd(In,
1416                                  ConstantInt::getAllOnesValue(In->getType()),
1417                                  "sext");
1418         } else {
1419           // sext ((x & 2^n) != 0)   -> (x << bitwidth-n) a>> bitwidth-1
1420           // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
1421           unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
1422           // Perform a left shift to place the desired bit in the MSB.
1423           if (ShiftAmt)
1424             In = Builder.CreateShl(In,
1425                                    ConstantInt::get(In->getType(), ShiftAmt));
1426 
1427           // Distribute the bit over the whole bit width.
1428           In = Builder.CreateAShr(In, ConstantInt::get(In->getType(),
1429                                   KnownZeroMask.getBitWidth() - 1), "sext");
1430         }
1431 
1432         if (CI.getType() == In->getType())
1433           return replaceInstUsesWith(CI, In);
1434         return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1435       }
1436     }
1437   }
1438 
1439   return nullptr;
1440 }
1441 
1442 /// Return true if we can take the specified value and return it as type Ty
1443 /// without inserting any new casts and without changing the value of the common
1444 /// low bits.  This is used by code that tries to promote integer operations to
1445 /// a wider types will allow us to eliminate the extension.
1446 ///
1447 /// This function works on both vectors and scalars.
1448 ///
1449 static bool canEvaluateSExtd(Value *V, Type *Ty) {
1450   assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1451          "Can't sign extend type to a smaller type");
1452   if (canAlwaysEvaluateInType(V, Ty))
1453     return true;
1454   if (canNotEvaluateInType(V, Ty))
1455     return false;
1456 
1457   auto *I = cast<Instruction>(V);
1458   switch (I->getOpcode()) {
1459   case Instruction::SExt:  // sext(sext(x)) -> sext(x)
1460   case Instruction::ZExt:  // sext(zext(x)) -> zext(x)
1461   case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1462     return true;
1463   case Instruction::And:
1464   case Instruction::Or:
1465   case Instruction::Xor:
1466   case Instruction::Add:
1467   case Instruction::Sub:
1468   case Instruction::Mul:
1469     // These operators can all arbitrarily be extended if their inputs can.
1470     return canEvaluateSExtd(I->getOperand(0), Ty) &&
1471            canEvaluateSExtd(I->getOperand(1), Ty);
1472 
1473   //case Instruction::Shl:   TODO
1474   //case Instruction::LShr:  TODO
1475 
1476   case Instruction::Select:
1477     return canEvaluateSExtd(I->getOperand(1), Ty) &&
1478            canEvaluateSExtd(I->getOperand(2), Ty);
1479 
1480   case Instruction::PHI: {
1481     // We can change a phi if we can change all operands.  Note that we never
1482     // get into trouble with cyclic PHIs here because we only consider
1483     // instructions with a single use.
1484     PHINode *PN = cast<PHINode>(I);
1485     for (Value *IncValue : PN->incoming_values())
1486       if (!canEvaluateSExtd(IncValue, Ty)) return false;
1487     return true;
1488   }
1489   default:
1490     // TODO: Can handle more cases here.
1491     break;
1492   }
1493 
1494   return false;
1495 }
1496 
1497 Instruction *InstCombinerImpl::visitSExt(SExtInst &CI) {
1498   // If this sign extend is only used by a truncate, let the truncate be
1499   // eliminated before we try to optimize this sext.
1500   if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
1501     return nullptr;
1502 
1503   if (Instruction *I = commonCastTransforms(CI))
1504     return I;
1505 
1506   Value *Src = CI.getOperand(0);
1507   Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1508   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1509   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1510 
1511   // If the value being extended is zero or positive, use a zext instead.
1512   if (isKnownNonNegative(Src, DL, 0, &AC, &CI, &DT))
1513     return CastInst::Create(Instruction::ZExt, Src, DestTy);
1514 
1515   // Try to extend the entire expression tree to the wide destination type.
1516   if (shouldChangeType(SrcTy, DestTy) && canEvaluateSExtd(Src, DestTy)) {
1517     // Okay, we can transform this!  Insert the new expression now.
1518     LLVM_DEBUG(
1519         dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1520                   " to avoid sign extend: "
1521                << CI << '\n');
1522     Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1523     assert(Res->getType() == DestTy);
1524 
1525     // If the high bits are already filled with sign bit, just replace this
1526     // cast with the result.
1527     if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
1528       return replaceInstUsesWith(CI, Res);
1529 
1530     // We need to emit a shl + ashr to do the sign extend.
1531     Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1532     return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"),
1533                                       ShAmt);
1534   }
1535 
1536   Value *X;
1537   if (match(Src, m_Trunc(m_Value(X)))) {
1538     // If the input has more sign bits than bits truncated, then convert
1539     // directly to final type.
1540     unsigned XBitSize = X->getType()->getScalarSizeInBits();
1541     if (ComputeNumSignBits(X, 0, &CI) > XBitSize - SrcBitSize)
1542       return CastInst::CreateIntegerCast(X, DestTy, /* isSigned */ true);
1543 
1544     // If input is a trunc from the destination type, then convert into shifts.
1545     if (Src->hasOneUse() && X->getType() == DestTy) {
1546       // sext (trunc X) --> ashr (shl X, C), C
1547       Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize);
1548       return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
1549     }
1550 
1551     // If we are replacing shifted-in high zero bits with sign bits, convert
1552     // the logic shift to arithmetic shift and eliminate the cast to
1553     // intermediate type:
1554     // sext (trunc (lshr Y, C)) --> sext/trunc (ashr Y, C)
1555     Value *Y;
1556     if (Src->hasOneUse() &&
1557         match(X, m_LShr(m_Value(Y),
1558                         m_SpecificIntAllowUndef(XBitSize - SrcBitSize)))) {
1559       Value *Ashr = Builder.CreateAShr(Y, XBitSize - SrcBitSize);
1560       return CastInst::CreateIntegerCast(Ashr, DestTy, /* isSigned */ true);
1561     }
1562   }
1563 
1564   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1565     return transformSExtICmp(ICI, CI);
1566 
1567   // If the input is a shl/ashr pair of a same constant, then this is a sign
1568   // extension from a smaller value.  If we could trust arbitrary bitwidth
1569   // integers, we could turn this into a truncate to the smaller bit and then
1570   // use a sext for the whole extension.  Since we don't, look deeper and check
1571   // for a truncate.  If the source and dest are the same type, eliminate the
1572   // trunc and extend and just do shifts.  For example, turn:
1573   //   %a = trunc i32 %i to i8
1574   //   %b = shl i8 %a, C
1575   //   %c = ashr i8 %b, C
1576   //   %d = sext i8 %c to i32
1577   // into:
1578   //   %a = shl i32 %i, 32-(8-C)
1579   //   %d = ashr i32 %a, 32-(8-C)
1580   Value *A = nullptr;
1581   // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1582   Constant *BA = nullptr, *CA = nullptr;
1583   if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_Constant(BA)),
1584                         m_Constant(CA))) &&
1585       BA->isElementWiseEqual(CA) && A->getType() == DestTy) {
1586     Constant *WideCurrShAmt = ConstantExpr::getSExt(CA, DestTy);
1587     Constant *NumLowbitsLeft = ConstantExpr::getSub(
1588         ConstantInt::get(DestTy, SrcTy->getScalarSizeInBits()), WideCurrShAmt);
1589     Constant *NewShAmt = ConstantExpr::getSub(
1590         ConstantInt::get(DestTy, DestTy->getScalarSizeInBits()),
1591         NumLowbitsLeft);
1592     NewShAmt =
1593         Constant::mergeUndefsWith(Constant::mergeUndefsWith(NewShAmt, BA), CA);
1594     A = Builder.CreateShl(A, NewShAmt, CI.getName());
1595     return BinaryOperator::CreateAShr(A, NewShAmt);
1596   }
1597 
1598   // Splatting a bit of constant-index across a value:
1599   // sext (ashr (trunc iN X to iM), M-1) to iN --> ashr (shl X, N-M), N-1
1600   // If the dest type is different, use a cast (adjust use check).
1601   if (match(Src, m_OneUse(m_AShr(m_Trunc(m_Value(X)),
1602                                  m_SpecificInt(SrcBitSize - 1))))) {
1603     Type *XTy = X->getType();
1604     unsigned XBitSize = XTy->getScalarSizeInBits();
1605     Constant *ShlAmtC = ConstantInt::get(XTy, XBitSize - SrcBitSize);
1606     Constant *AshrAmtC = ConstantInt::get(XTy, XBitSize - 1);
1607     if (XTy == DestTy)
1608       return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShlAmtC),
1609                                         AshrAmtC);
1610     if (cast<BinaryOperator>(Src)->getOperand(0)->hasOneUse()) {
1611       Value *Ashr = Builder.CreateAShr(Builder.CreateShl(X, ShlAmtC), AshrAmtC);
1612       return CastInst::CreateIntegerCast(Ashr, DestTy, /* isSigned */ true);
1613     }
1614   }
1615 
1616   if (match(Src, m_VScale(DL))) {
1617     if (CI.getFunction() &&
1618         CI.getFunction()->hasFnAttribute(Attribute::VScaleRange)) {
1619       Attribute Attr = CI.getFunction()->getFnAttribute(Attribute::VScaleRange);
1620       if (Optional<unsigned> MaxVScale = Attr.getVScaleRangeMax()) {
1621         if (Log2_32(MaxVScale.getValue()) < (SrcBitSize - 1)) {
1622           Value *VScale = Builder.CreateVScale(ConstantInt::get(DestTy, 1));
1623           return replaceInstUsesWith(CI, VScale);
1624         }
1625       }
1626     }
1627   }
1628 
1629   return nullptr;
1630 }
1631 
1632 /// Return a Constant* for the specified floating-point constant if it fits
1633 /// in the specified FP type without changing its value.
1634 static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1635   bool losesInfo;
1636   APFloat F = CFP->getValueAPF();
1637   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1638   return !losesInfo;
1639 }
1640 
1641 static Type *shrinkFPConstant(ConstantFP *CFP) {
1642   if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext()))
1643     return nullptr;  // No constant folding of this.
1644   // See if the value can be truncated to half and then reextended.
1645   if (fitsInFPType(CFP, APFloat::IEEEhalf()))
1646     return Type::getHalfTy(CFP->getContext());
1647   // See if the value can be truncated to float and then reextended.
1648   if (fitsInFPType(CFP, APFloat::IEEEsingle()))
1649     return Type::getFloatTy(CFP->getContext());
1650   if (CFP->getType()->isDoubleTy())
1651     return nullptr;  // Won't shrink.
1652   if (fitsInFPType(CFP, APFloat::IEEEdouble()))
1653     return Type::getDoubleTy(CFP->getContext());
1654   // Don't try to shrink to various long double types.
1655   return nullptr;
1656 }
1657 
1658 // Determine if this is a vector of ConstantFPs and if so, return the minimal
1659 // type we can safely truncate all elements to.
1660 // TODO: Make these support undef elements.
1661 static Type *shrinkFPConstantVector(Value *V) {
1662   auto *CV = dyn_cast<Constant>(V);
1663   auto *CVVTy = dyn_cast<FixedVectorType>(V->getType());
1664   if (!CV || !CVVTy)
1665     return nullptr;
1666 
1667   Type *MinType = nullptr;
1668 
1669   unsigned NumElts = CVVTy->getNumElements();
1670 
1671   // For fixed-width vectors we find the minimal type by looking
1672   // through the constant values of the vector.
1673   for (unsigned i = 0; i != NumElts; ++i) {
1674     auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
1675     if (!CFP)
1676       return nullptr;
1677 
1678     Type *T = shrinkFPConstant(CFP);
1679     if (!T)
1680       return nullptr;
1681 
1682     // If we haven't found a type yet or this type has a larger mantissa than
1683     // our previous type, this is our new minimal type.
1684     if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth())
1685       MinType = T;
1686   }
1687 
1688   // Make a vector type from the minimal type.
1689   return FixedVectorType::get(MinType, NumElts);
1690 }
1691 
1692 /// Find the minimum FP type we can safely truncate to.
1693 static Type *getMinimumFPType(Value *V) {
1694   if (auto *FPExt = dyn_cast<FPExtInst>(V))
1695     return FPExt->getOperand(0)->getType();
1696 
1697   // If this value is a constant, return the constant in the smallest FP type
1698   // that can accurately represent it.  This allows us to turn
1699   // (float)((double)X+2.0) into x+2.0f.
1700   if (auto *CFP = dyn_cast<ConstantFP>(V))
1701     if (Type *T = shrinkFPConstant(CFP))
1702       return T;
1703 
1704   // We can only correctly find a minimum type for a scalable vector when it is
1705   // a splat. For splats of constant values the fpext is wrapped up as a
1706   // ConstantExpr.
1707   if (auto *FPCExt = dyn_cast<ConstantExpr>(V))
1708     if (FPCExt->getOpcode() == Instruction::FPExt)
1709       return FPCExt->getOperand(0)->getType();
1710 
1711   // Try to shrink a vector of FP constants. This returns nullptr on scalable
1712   // vectors
1713   if (Type *T = shrinkFPConstantVector(V))
1714     return T;
1715 
1716   return V->getType();
1717 }
1718 
1719 /// Return true if the cast from integer to FP can be proven to be exact for all
1720 /// possible inputs (the conversion does not lose any precision).
1721 static bool isKnownExactCastIntToFP(CastInst &I) {
1722   CastInst::CastOps Opcode = I.getOpcode();
1723   assert((Opcode == CastInst::SIToFP || Opcode == CastInst::UIToFP) &&
1724          "Unexpected cast");
1725   Value *Src = I.getOperand(0);
1726   Type *SrcTy = Src->getType();
1727   Type *FPTy = I.getType();
1728   bool IsSigned = Opcode == Instruction::SIToFP;
1729   int SrcSize = (int)SrcTy->getScalarSizeInBits() - IsSigned;
1730 
1731   // Easy case - if the source integer type has less bits than the FP mantissa,
1732   // then the cast must be exact.
1733   int DestNumSigBits = FPTy->getFPMantissaWidth();
1734   if (SrcSize <= DestNumSigBits)
1735     return true;
1736 
1737   // Cast from FP to integer and back to FP is independent of the intermediate
1738   // integer width because of poison on overflow.
1739   Value *F;
1740   if (match(Src, m_FPToSI(m_Value(F))) || match(Src, m_FPToUI(m_Value(F)))) {
1741     // If this is uitofp (fptosi F), the source needs an extra bit to avoid
1742     // potential rounding of negative FP input values.
1743     int SrcNumSigBits = F->getType()->getFPMantissaWidth();
1744     if (!IsSigned && match(Src, m_FPToSI(m_Value())))
1745       SrcNumSigBits++;
1746 
1747     // [su]itofp (fpto[su]i F) --> exact if the source type has less or equal
1748     // significant bits than the destination (and make sure neither type is
1749     // weird -- ppc_fp128).
1750     if (SrcNumSigBits > 0 && DestNumSigBits > 0 &&
1751         SrcNumSigBits <= DestNumSigBits)
1752       return true;
1753   }
1754 
1755   // TODO:
1756   // Try harder to find if the source integer type has less significant bits.
1757   // For example, compute number of sign bits or compute low bit mask.
1758   return false;
1759 }
1760 
1761 Instruction *InstCombinerImpl::visitFPTrunc(FPTruncInst &FPT) {
1762   if (Instruction *I = commonCastTransforms(FPT))
1763     return I;
1764 
1765   // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1766   // simplify this expression to avoid one or more of the trunc/extend
1767   // operations if we can do so without changing the numerical results.
1768   //
1769   // The exact manner in which the widths of the operands interact to limit
1770   // what we can and cannot do safely varies from operation to operation, and
1771   // is explained below in the various case statements.
1772   Type *Ty = FPT.getType();
1773   auto *BO = dyn_cast<BinaryOperator>(FPT.getOperand(0));
1774   if (BO && BO->hasOneUse()) {
1775     Type *LHSMinType = getMinimumFPType(BO->getOperand(0));
1776     Type *RHSMinType = getMinimumFPType(BO->getOperand(1));
1777     unsigned OpWidth = BO->getType()->getFPMantissaWidth();
1778     unsigned LHSWidth = LHSMinType->getFPMantissaWidth();
1779     unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
1780     unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1781     unsigned DstWidth = Ty->getFPMantissaWidth();
1782     switch (BO->getOpcode()) {
1783       default: break;
1784       case Instruction::FAdd:
1785       case Instruction::FSub:
1786         // For addition and subtraction, the infinitely precise result can
1787         // essentially be arbitrarily wide; proving that double rounding
1788         // will not occur because the result of OpI is exact (as we will for
1789         // FMul, for example) is hopeless.  However, we *can* nonetheless
1790         // frequently know that double rounding cannot occur (or that it is
1791         // innocuous) by taking advantage of the specific structure of
1792         // infinitely-precise results that admit double rounding.
1793         //
1794         // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1795         // to represent both sources, we can guarantee that the double
1796         // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1797         // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1798         // for proof of this fact).
1799         //
1800         // Note: Figueroa does not consider the case where DstFormat !=
1801         // SrcFormat.  It's possible (likely even!) that this analysis
1802         // could be tightened for those cases, but they are rare (the main
1803         // case of interest here is (float)((double)float + float)).
1804         if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1805           Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
1806           Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
1807           Instruction *RI = BinaryOperator::Create(BO->getOpcode(), LHS, RHS);
1808           RI->copyFastMathFlags(BO);
1809           return RI;
1810         }
1811         break;
1812       case Instruction::FMul:
1813         // For multiplication, the infinitely precise result has at most
1814         // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1815         // that such a value can be exactly represented, then no double
1816         // rounding can possibly occur; we can safely perform the operation
1817         // in the destination format if it can represent both sources.
1818         if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1819           Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
1820           Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
1821           return BinaryOperator::CreateFMulFMF(LHS, RHS, BO);
1822         }
1823         break;
1824       case Instruction::FDiv:
1825         // For division, we use again use the bound from Figueroa's
1826         // dissertation.  I am entirely certain that this bound can be
1827         // tightened in the unbalanced operand case by an analysis based on
1828         // the diophantine rational approximation bound, but the well-known
1829         // condition used here is a good conservative first pass.
1830         // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1831         if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1832           Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty);
1833           Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty);
1834           return BinaryOperator::CreateFDivFMF(LHS, RHS, BO);
1835         }
1836         break;
1837       case Instruction::FRem: {
1838         // Remainder is straightforward.  Remainder is always exact, so the
1839         // type of OpI doesn't enter into things at all.  We simply evaluate
1840         // in whichever source type is larger, then convert to the
1841         // destination type.
1842         if (SrcWidth == OpWidth)
1843           break;
1844         Value *LHS, *RHS;
1845         if (LHSWidth == SrcWidth) {
1846            LHS = Builder.CreateFPTrunc(BO->getOperand(0), LHSMinType);
1847            RHS = Builder.CreateFPTrunc(BO->getOperand(1), LHSMinType);
1848         } else {
1849            LHS = Builder.CreateFPTrunc(BO->getOperand(0), RHSMinType);
1850            RHS = Builder.CreateFPTrunc(BO->getOperand(1), RHSMinType);
1851         }
1852 
1853         Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, BO);
1854         return CastInst::CreateFPCast(ExactResult, Ty);
1855       }
1856     }
1857   }
1858 
1859   // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1860   Value *X;
1861   Instruction *Op = dyn_cast<Instruction>(FPT.getOperand(0));
1862   if (Op && Op->hasOneUse()) {
1863     // FIXME: The FMF should propagate from the fptrunc, not the source op.
1864     IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1865     if (isa<FPMathOperator>(Op))
1866       Builder.setFastMathFlags(Op->getFastMathFlags());
1867 
1868     if (match(Op, m_FNeg(m_Value(X)))) {
1869       Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty);
1870 
1871       return UnaryOperator::CreateFNegFMF(InnerTrunc, Op);
1872     }
1873 
1874     // If we are truncating a select that has an extended operand, we can
1875     // narrow the other operand and do the select as a narrow op.
1876     Value *Cond, *X, *Y;
1877     if (match(Op, m_Select(m_Value(Cond), m_FPExt(m_Value(X)), m_Value(Y))) &&
1878         X->getType() == Ty) {
1879       // fptrunc (select Cond, (fpext X), Y --> select Cond, X, (fptrunc Y)
1880       Value *NarrowY = Builder.CreateFPTrunc(Y, Ty);
1881       Value *Sel = Builder.CreateSelect(Cond, X, NarrowY, "narrow.sel", Op);
1882       return replaceInstUsesWith(FPT, Sel);
1883     }
1884     if (match(Op, m_Select(m_Value(Cond), m_Value(Y), m_FPExt(m_Value(X)))) &&
1885         X->getType() == Ty) {
1886       // fptrunc (select Cond, Y, (fpext X) --> select Cond, (fptrunc Y), X
1887       Value *NarrowY = Builder.CreateFPTrunc(Y, Ty);
1888       Value *Sel = Builder.CreateSelect(Cond, NarrowY, X, "narrow.sel", Op);
1889       return replaceInstUsesWith(FPT, Sel);
1890     }
1891   }
1892 
1893   if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) {
1894     switch (II->getIntrinsicID()) {
1895     default: break;
1896     case Intrinsic::ceil:
1897     case Intrinsic::fabs:
1898     case Intrinsic::floor:
1899     case Intrinsic::nearbyint:
1900     case Intrinsic::rint:
1901     case Intrinsic::round:
1902     case Intrinsic::roundeven:
1903     case Intrinsic::trunc: {
1904       Value *Src = II->getArgOperand(0);
1905       if (!Src->hasOneUse())
1906         break;
1907 
1908       // Except for fabs, this transformation requires the input of the unary FP
1909       // operation to be itself an fpext from the type to which we're
1910       // truncating.
1911       if (II->getIntrinsicID() != Intrinsic::fabs) {
1912         FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src);
1913         if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty)
1914           break;
1915       }
1916 
1917       // Do unary FP operation on smaller type.
1918       // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1919       Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
1920       Function *Overload = Intrinsic::getDeclaration(FPT.getModule(),
1921                                                      II->getIntrinsicID(), Ty);
1922       SmallVector<OperandBundleDef, 1> OpBundles;
1923       II->getOperandBundlesAsDefs(OpBundles);
1924       CallInst *NewCI =
1925           CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName());
1926       NewCI->copyFastMathFlags(II);
1927       return NewCI;
1928     }
1929     }
1930   }
1931 
1932   if (Instruction *I = shrinkInsertElt(FPT, Builder))
1933     return I;
1934 
1935   Value *Src = FPT.getOperand(0);
1936   if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
1937     auto *FPCast = cast<CastInst>(Src);
1938     if (isKnownExactCastIntToFP(*FPCast))
1939       return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
1940   }
1941 
1942   return nullptr;
1943 }
1944 
1945 Instruction *InstCombinerImpl::visitFPExt(CastInst &FPExt) {
1946   // If the source operand is a cast from integer to FP and known exact, then
1947   // cast the integer operand directly to the destination type.
1948   Type *Ty = FPExt.getType();
1949   Value *Src = FPExt.getOperand(0);
1950   if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) {
1951     auto *FPCast = cast<CastInst>(Src);
1952     if (isKnownExactCastIntToFP(*FPCast))
1953       return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty);
1954   }
1955 
1956   return commonCastTransforms(FPExt);
1957 }
1958 
1959 /// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1960 /// This is safe if the intermediate type has enough bits in its mantissa to
1961 /// accurately represent all values of X.  For example, this won't work with
1962 /// i64 -> float -> i64.
1963 Instruction *InstCombinerImpl::foldItoFPtoI(CastInst &FI) {
1964   if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1965     return nullptr;
1966 
1967   auto *OpI = cast<CastInst>(FI.getOperand(0));
1968   Value *X = OpI->getOperand(0);
1969   Type *XType = X->getType();
1970   Type *DestType = FI.getType();
1971   bool IsOutputSigned = isa<FPToSIInst>(FI);
1972 
1973   // Since we can assume the conversion won't overflow, our decision as to
1974   // whether the input will fit in the float should depend on the minimum
1975   // of the input range and output range.
1976 
1977   // This means this is also safe for a signed input and unsigned output, since
1978   // a negative input would lead to undefined behavior.
1979   if (!isKnownExactCastIntToFP(*OpI)) {
1980     // The first cast may not round exactly based on the source integer width
1981     // and FP width, but the overflow UB rules can still allow this to fold.
1982     // If the destination type is narrow, that means the intermediate FP value
1983     // must be large enough to hold the source value exactly.
1984     // For example, (uint8_t)((float)(uint32_t 16777217) is undefined behavior.
1985     int OutputSize = (int)DestType->getScalarSizeInBits();
1986     if (OutputSize > OpI->getType()->getFPMantissaWidth())
1987       return nullptr;
1988   }
1989 
1990   if (DestType->getScalarSizeInBits() > XType->getScalarSizeInBits()) {
1991     bool IsInputSigned = isa<SIToFPInst>(OpI);
1992     if (IsInputSigned && IsOutputSigned)
1993       return new SExtInst(X, DestType);
1994     return new ZExtInst(X, DestType);
1995   }
1996   if (DestType->getScalarSizeInBits() < XType->getScalarSizeInBits())
1997     return new TruncInst(X, DestType);
1998 
1999   assert(XType == DestType && "Unexpected types for int to FP to int casts");
2000   return replaceInstUsesWith(FI, X);
2001 }
2002 
2003 Instruction *InstCombinerImpl::visitFPToUI(FPToUIInst &FI) {
2004   if (Instruction *I = foldItoFPtoI(FI))
2005     return I;
2006 
2007   return commonCastTransforms(FI);
2008 }
2009 
2010 Instruction *InstCombinerImpl::visitFPToSI(FPToSIInst &FI) {
2011   if (Instruction *I = foldItoFPtoI(FI))
2012     return I;
2013 
2014   return commonCastTransforms(FI);
2015 }
2016 
2017 Instruction *InstCombinerImpl::visitUIToFP(CastInst &CI) {
2018   return commonCastTransforms(CI);
2019 }
2020 
2021 Instruction *InstCombinerImpl::visitSIToFP(CastInst &CI) {
2022   return commonCastTransforms(CI);
2023 }
2024 
2025 Instruction *InstCombinerImpl::visitIntToPtr(IntToPtrInst &CI) {
2026   // If the source integer type is not the intptr_t type for this target, do a
2027   // trunc or zext to the intptr_t type, then inttoptr of it.  This allows the
2028   // cast to be exposed to other transforms.
2029   unsigned AS = CI.getAddressSpace();
2030   if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
2031       DL.getPointerSizeInBits(AS)) {
2032     Type *Ty = CI.getOperand(0)->getType()->getWithNewType(
2033         DL.getIntPtrType(CI.getContext(), AS));
2034     Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty);
2035     return new IntToPtrInst(P, CI.getType());
2036   }
2037 
2038   if (Instruction *I = commonCastTransforms(CI))
2039     return I;
2040 
2041   return nullptr;
2042 }
2043 
2044 /// Implement the transforms for cast of pointer (bitcast/ptrtoint)
2045 Instruction *InstCombinerImpl::commonPointerCastTransforms(CastInst &CI) {
2046   Value *Src = CI.getOperand(0);
2047 
2048   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2049     // If casting the result of a getelementptr instruction with no offset, turn
2050     // this into a cast of the original pointer!
2051     if (GEP->hasAllZeroIndices() &&
2052         // If CI is an addrspacecast and GEP changes the poiner type, merging
2053         // GEP into CI would undo canonicalizing addrspacecast with different
2054         // pointer types, causing infinite loops.
2055         (!isa<AddrSpaceCastInst>(CI) ||
2056          GEP->getType() == GEP->getPointerOperandType())) {
2057       // Changing the cast operand is usually not a good idea but it is safe
2058       // here because the pointer operand is being replaced with another
2059       // pointer operand so the opcode doesn't need to change.
2060       return replaceOperand(CI, 0, GEP->getOperand(0));
2061     }
2062   }
2063 
2064   return commonCastTransforms(CI);
2065 }
2066 
2067 Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) {
2068   // If the destination integer type is not the intptr_t type for this target,
2069   // do a ptrtoint to intptr_t then do a trunc or zext.  This allows the cast
2070   // to be exposed to other transforms.
2071   Value *SrcOp = CI.getPointerOperand();
2072   Type *SrcTy = SrcOp->getType();
2073   Type *Ty = CI.getType();
2074   unsigned AS = CI.getPointerAddressSpace();
2075   unsigned TySize = Ty->getScalarSizeInBits();
2076   unsigned PtrSize = DL.getPointerSizeInBits(AS);
2077   if (TySize != PtrSize) {
2078     Type *IntPtrTy =
2079         SrcTy->getWithNewType(DL.getIntPtrType(CI.getContext(), AS));
2080     Value *P = Builder.CreatePtrToInt(SrcOp, IntPtrTy);
2081     return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
2082   }
2083 
2084   if (auto *GEP = dyn_cast<GetElementPtrInst>(SrcOp)) {
2085     // Fold ptrtoint(gep null, x) to multiply + constant if the GEP has one use.
2086     // While this can increase the number of instructions it doesn't actually
2087     // increase the overall complexity since the arithmetic is just part of
2088     // the GEP otherwise.
2089     if (GEP->hasOneUse() &&
2090         isa<ConstantPointerNull>(GEP->getPointerOperand())) {
2091       return replaceInstUsesWith(CI,
2092                                  Builder.CreateIntCast(EmitGEPOffset(GEP), Ty,
2093                                                        /*isSigned=*/false));
2094     }
2095   }
2096 
2097   Value *Vec, *Scalar, *Index;
2098   if (match(SrcOp, m_OneUse(m_InsertElt(m_IntToPtr(m_Value(Vec)),
2099                                         m_Value(Scalar), m_Value(Index)))) &&
2100       Vec->getType() == Ty) {
2101     assert(Vec->getType()->getScalarSizeInBits() == PtrSize && "Wrong type");
2102     // Convert the scalar to int followed by insert to eliminate one cast:
2103     // p2i (ins (i2p Vec), Scalar, Index --> ins Vec, (p2i Scalar), Index
2104     Value *NewCast = Builder.CreatePtrToInt(Scalar, Ty->getScalarType());
2105     return InsertElementInst::Create(Vec, NewCast, Index);
2106   }
2107 
2108   return commonPointerCastTransforms(CI);
2109 }
2110 
2111 /// This input value (which is known to have vector type) is being zero extended
2112 /// or truncated to the specified vector type. Since the zext/trunc is done
2113 /// using an integer type, we have a (bitcast(cast(bitcast))) pattern,
2114 /// endianness will impact which end of the vector that is extended or
2115 /// truncated.
2116 ///
2117 /// A vector is always stored with index 0 at the lowest address, which
2118 /// corresponds to the most significant bits for a big endian stored integer and
2119 /// the least significant bits for little endian. A trunc/zext of an integer
2120 /// impacts the big end of the integer. Thus, we need to add/remove elements at
2121 /// the front of the vector for big endian targets, and the back of the vector
2122 /// for little endian targets.
2123 ///
2124 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible.
2125 ///
2126 /// The source and destination vector types may have different element types.
2127 static Instruction *
2128 optimizeVectorResizeWithIntegerBitCasts(Value *InVal, VectorType *DestTy,
2129                                         InstCombinerImpl &IC) {
2130   // We can only do this optimization if the output is a multiple of the input
2131   // element size, or the input is a multiple of the output element size.
2132   // Convert the input type to have the same element type as the output.
2133   VectorType *SrcTy = cast<VectorType>(InVal->getType());
2134 
2135   if (SrcTy->getElementType() != DestTy->getElementType()) {
2136     // The input types don't need to be identical, but for now they must be the
2137     // same size.  There is no specific reason we couldn't handle things like
2138     // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
2139     // there yet.
2140     if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
2141         DestTy->getElementType()->getPrimitiveSizeInBits())
2142       return nullptr;
2143 
2144     SrcTy =
2145         FixedVectorType::get(DestTy->getElementType(),
2146                              cast<FixedVectorType>(SrcTy)->getNumElements());
2147     InVal = IC.Builder.CreateBitCast(InVal, SrcTy);
2148   }
2149 
2150   bool IsBigEndian = IC.getDataLayout().isBigEndian();
2151   unsigned SrcElts = cast<FixedVectorType>(SrcTy)->getNumElements();
2152   unsigned DestElts = cast<FixedVectorType>(DestTy)->getNumElements();
2153 
2154   assert(SrcElts != DestElts && "Element counts should be different.");
2155 
2156   // Now that the element types match, get the shuffle mask and RHS of the
2157   // shuffle to use, which depends on whether we're increasing or decreasing the
2158   // size of the input.
2159   auto ShuffleMaskStorage = llvm::to_vector<16>(llvm::seq<int>(0, SrcElts));
2160   ArrayRef<int> ShuffleMask;
2161   Value *V2;
2162 
2163   if (SrcElts > DestElts) {
2164     // If we're shrinking the number of elements (rewriting an integer
2165     // truncate), just shuffle in the elements corresponding to the least
2166     // significant bits from the input and use poison as the second shuffle
2167     // input.
2168     V2 = PoisonValue::get(SrcTy);
2169     // Make sure the shuffle mask selects the "least significant bits" by
2170     // keeping elements from back of the src vector for big endian, and from the
2171     // front for little endian.
2172     ShuffleMask = ShuffleMaskStorage;
2173     if (IsBigEndian)
2174       ShuffleMask = ShuffleMask.take_back(DestElts);
2175     else
2176       ShuffleMask = ShuffleMask.take_front(DestElts);
2177   } else {
2178     // If we're increasing the number of elements (rewriting an integer zext),
2179     // shuffle in all of the elements from InVal. Fill the rest of the result
2180     // elements with zeros from a constant zero.
2181     V2 = Constant::getNullValue(SrcTy);
2182     // Use first elt from V2 when indicating zero in the shuffle mask.
2183     uint32_t NullElt = SrcElts;
2184     // Extend with null values in the "most significant bits" by adding elements
2185     // in front of the src vector for big endian, and at the back for little
2186     // endian.
2187     unsigned DeltaElts = DestElts - SrcElts;
2188     if (IsBigEndian)
2189       ShuffleMaskStorage.insert(ShuffleMaskStorage.begin(), DeltaElts, NullElt);
2190     else
2191       ShuffleMaskStorage.append(DeltaElts, NullElt);
2192     ShuffleMask = ShuffleMaskStorage;
2193   }
2194 
2195   return new ShuffleVectorInst(InVal, V2, ShuffleMask);
2196 }
2197 
2198 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
2199   return Value % Ty->getPrimitiveSizeInBits() == 0;
2200 }
2201 
2202 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
2203   return Value / Ty->getPrimitiveSizeInBits();
2204 }
2205 
2206 /// V is a value which is inserted into a vector of VecEltTy.
2207 /// Look through the value to see if we can decompose it into
2208 /// insertions into the vector.  See the example in the comment for
2209 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
2210 /// The type of V is always a non-zero multiple of VecEltTy's size.
2211 /// Shift is the number of bits between the lsb of V and the lsb of
2212 /// the vector.
2213 ///
2214 /// This returns false if the pattern can't be matched or true if it can,
2215 /// filling in Elements with the elements found here.
2216 static bool collectInsertionElements(Value *V, unsigned Shift,
2217                                      SmallVectorImpl<Value *> &Elements,
2218                                      Type *VecEltTy, bool isBigEndian) {
2219   assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
2220          "Shift should be a multiple of the element type size");
2221 
2222   // Undef values never contribute useful bits to the result.
2223   if (isa<UndefValue>(V)) return true;
2224 
2225   // If we got down to a value of the right type, we win, try inserting into the
2226   // right element.
2227   if (V->getType() == VecEltTy) {
2228     // Inserting null doesn't actually insert any elements.
2229     if (Constant *C = dyn_cast<Constant>(V))
2230       if (C->isNullValue())
2231         return true;
2232 
2233     unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
2234     if (isBigEndian)
2235       ElementIndex = Elements.size() - ElementIndex - 1;
2236 
2237     // Fail if multiple elements are inserted into this slot.
2238     if (Elements[ElementIndex])
2239       return false;
2240 
2241     Elements[ElementIndex] = V;
2242     return true;
2243   }
2244 
2245   if (Constant *C = dyn_cast<Constant>(V)) {
2246     // Figure out the # elements this provides, and bitcast it or slice it up
2247     // as required.
2248     unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
2249                                         VecEltTy);
2250     // If the constant is the size of a vector element, we just need to bitcast
2251     // it to the right type so it gets properly inserted.
2252     if (NumElts == 1)
2253       return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
2254                                       Shift, Elements, VecEltTy, isBigEndian);
2255 
2256     // Okay, this is a constant that covers multiple elements.  Slice it up into
2257     // pieces and insert each element-sized piece into the vector.
2258     if (!isa<IntegerType>(C->getType()))
2259       C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
2260                                        C->getType()->getPrimitiveSizeInBits()));
2261     unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
2262     Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
2263 
2264     for (unsigned i = 0; i != NumElts; ++i) {
2265       unsigned ShiftI = Shift+i*ElementSize;
2266       Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
2267                                                                   ShiftI));
2268       Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
2269       if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
2270                                     isBigEndian))
2271         return false;
2272     }
2273     return true;
2274   }
2275 
2276   if (!V->hasOneUse()) return false;
2277 
2278   Instruction *I = dyn_cast<Instruction>(V);
2279   if (!I) return false;
2280   switch (I->getOpcode()) {
2281   default: return false; // Unhandled case.
2282   case Instruction::BitCast:
2283     if (I->getOperand(0)->getType()->isVectorTy())
2284       return false;
2285     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2286                                     isBigEndian);
2287   case Instruction::ZExt:
2288     if (!isMultipleOfTypeSize(
2289                           I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
2290                               VecEltTy))
2291       return false;
2292     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2293                                     isBigEndian);
2294   case Instruction::Or:
2295     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2296                                     isBigEndian) &&
2297            collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
2298                                     isBigEndian);
2299   case Instruction::Shl: {
2300     // Must be shifting by a constant that is a multiple of the element size.
2301     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
2302     if (!CI) return false;
2303     Shift += CI->getZExtValue();
2304     if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
2305     return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
2306                                     isBigEndian);
2307   }
2308 
2309   }
2310 }
2311 
2312 
2313 /// If the input is an 'or' instruction, we may be doing shifts and ors to
2314 /// assemble the elements of the vector manually.
2315 /// Try to rip the code out and replace it with insertelements.  This is to
2316 /// optimize code like this:
2317 ///
2318 ///    %tmp37 = bitcast float %inc to i32
2319 ///    %tmp38 = zext i32 %tmp37 to i64
2320 ///    %tmp31 = bitcast float %inc5 to i32
2321 ///    %tmp32 = zext i32 %tmp31 to i64
2322 ///    %tmp33 = shl i64 %tmp32, 32
2323 ///    %ins35 = or i64 %tmp33, %tmp38
2324 ///    %tmp43 = bitcast i64 %ins35 to <2 x float>
2325 ///
2326 /// Into two insertelements that do "buildvector{%inc, %inc5}".
2327 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI,
2328                                                 InstCombinerImpl &IC) {
2329   auto *DestVecTy = cast<FixedVectorType>(CI.getType());
2330   Value *IntInput = CI.getOperand(0);
2331 
2332   SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
2333   if (!collectInsertionElements(IntInput, 0, Elements,
2334                                 DestVecTy->getElementType(),
2335                                 IC.getDataLayout().isBigEndian()))
2336     return nullptr;
2337 
2338   // If we succeeded, we know that all of the element are specified by Elements
2339   // or are zero if Elements has a null entry.  Recast this as a set of
2340   // insertions.
2341   Value *Result = Constant::getNullValue(CI.getType());
2342   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
2343     if (!Elements[i]) continue;  // Unset element.
2344 
2345     Result = IC.Builder.CreateInsertElement(Result, Elements[i],
2346                                             IC.Builder.getInt32(i));
2347   }
2348 
2349   return Result;
2350 }
2351 
2352 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the
2353 /// vector followed by extract element. The backend tends to handle bitcasts of
2354 /// vectors better than bitcasts of scalars because vector registers are
2355 /// usually not type-specific like scalar integer or scalar floating-point.
2356 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast,
2357                                               InstCombinerImpl &IC) {
2358   Value *VecOp, *Index;
2359   if (!match(BitCast.getOperand(0),
2360              m_OneUse(m_ExtractElt(m_Value(VecOp), m_Value(Index)))))
2361     return nullptr;
2362 
2363   // The bitcast must be to a vectorizable type, otherwise we can't make a new
2364   // type to extract from.
2365   Type *DestType = BitCast.getType();
2366   if (!VectorType::isValidElementType(DestType))
2367     return nullptr;
2368 
2369   auto *NewVecType =
2370       VectorType::get(DestType, cast<VectorType>(VecOp->getType()));
2371   auto *NewBC = IC.Builder.CreateBitCast(VecOp, NewVecType, "bc");
2372   return ExtractElementInst::Create(NewBC, Index);
2373 }
2374 
2375 /// Change the type of a bitwise logic operation if we can eliminate a bitcast.
2376 static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast,
2377                                             InstCombiner::BuilderTy &Builder) {
2378   Type *DestTy = BitCast.getType();
2379   BinaryOperator *BO;
2380   if (!DestTy->isIntOrIntVectorTy() ||
2381       !match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) ||
2382       !BO->isBitwiseLogicOp())
2383     return nullptr;
2384 
2385   // FIXME: This transform is restricted to vector types to avoid backend
2386   // problems caused by creating potentially illegal operations. If a fix-up is
2387   // added to handle that situation, we can remove this check.
2388   if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy())
2389     return nullptr;
2390 
2391   Value *X;
2392   if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) &&
2393       X->getType() == DestTy && !isa<Constant>(X)) {
2394     // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
2395     Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy);
2396     return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1);
2397   }
2398 
2399   if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) &&
2400       X->getType() == DestTy && !isa<Constant>(X)) {
2401     // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X)
2402     Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2403     return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X);
2404   }
2405 
2406   // Canonicalize vector bitcasts to come before vector bitwise logic with a
2407   // constant. This eases recognition of special constants for later ops.
2408   // Example:
2409   // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
2410   Constant *C;
2411   if (match(BO->getOperand(1), m_Constant(C))) {
2412     // bitcast (logic X, C) --> logic (bitcast X, C')
2413     Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy);
2414     Value *CastedC = Builder.CreateBitCast(C, DestTy);
2415     return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC);
2416   }
2417 
2418   return nullptr;
2419 }
2420 
2421 /// Change the type of a select if we can eliminate a bitcast.
2422 static Instruction *foldBitCastSelect(BitCastInst &BitCast,
2423                                       InstCombiner::BuilderTy &Builder) {
2424   Value *Cond, *TVal, *FVal;
2425   if (!match(BitCast.getOperand(0),
2426              m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
2427     return nullptr;
2428 
2429   // A vector select must maintain the same number of elements in its operands.
2430   Type *CondTy = Cond->getType();
2431   Type *DestTy = BitCast.getType();
2432   if (auto *CondVTy = dyn_cast<VectorType>(CondTy))
2433     if (!DestTy->isVectorTy() ||
2434         CondVTy->getElementCount() !=
2435             cast<VectorType>(DestTy)->getElementCount())
2436       return nullptr;
2437 
2438   // FIXME: This transform is restricted from changing the select between
2439   // scalars and vectors to avoid backend problems caused by creating
2440   // potentially illegal operations. If a fix-up is added to handle that
2441   // situation, we can remove this check.
2442   if (DestTy->isVectorTy() != TVal->getType()->isVectorTy())
2443     return nullptr;
2444 
2445   auto *Sel = cast<Instruction>(BitCast.getOperand(0));
2446   Value *X;
2447   if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
2448       !isa<Constant>(X)) {
2449     // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y))
2450     Value *CastedVal = Builder.CreateBitCast(FVal, DestTy);
2451     return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel);
2452   }
2453 
2454   if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy &&
2455       !isa<Constant>(X)) {
2456     // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X)
2457     Value *CastedVal = Builder.CreateBitCast(TVal, DestTy);
2458     return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel);
2459   }
2460 
2461   return nullptr;
2462 }
2463 
2464 /// Check if all users of CI are StoreInsts.
2465 static bool hasStoreUsersOnly(CastInst &CI) {
2466   for (User *U : CI.users()) {
2467     if (!isa<StoreInst>(U))
2468       return false;
2469   }
2470   return true;
2471 }
2472 
2473 /// This function handles following case
2474 ///
2475 ///     A  ->  B    cast
2476 ///     PHI
2477 ///     B  ->  A    cast
2478 ///
2479 /// All the related PHI nodes can be replaced by new PHI nodes with type A.
2480 /// The uses of \p CI can be changed to the new PHI node corresponding to \p PN.
2481 Instruction *InstCombinerImpl::optimizeBitCastFromPhi(CastInst &CI,
2482                                                       PHINode *PN) {
2483   // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp.
2484   if (hasStoreUsersOnly(CI))
2485     return nullptr;
2486 
2487   Value *Src = CI.getOperand(0);
2488   Type *SrcTy = Src->getType();         // Type B
2489   Type *DestTy = CI.getType();          // Type A
2490 
2491   SmallVector<PHINode *, 4> PhiWorklist;
2492   SmallSetVector<PHINode *, 4> OldPhiNodes;
2493 
2494   // Find all of the A->B casts and PHI nodes.
2495   // We need to inspect all related PHI nodes, but PHIs can be cyclic, so
2496   // OldPhiNodes is used to track all known PHI nodes, before adding a new
2497   // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first.
2498   PhiWorklist.push_back(PN);
2499   OldPhiNodes.insert(PN);
2500   while (!PhiWorklist.empty()) {
2501     auto *OldPN = PhiWorklist.pop_back_val();
2502     for (Value *IncValue : OldPN->incoming_values()) {
2503       if (isa<Constant>(IncValue))
2504         continue;
2505 
2506       if (auto *LI = dyn_cast<LoadInst>(IncValue)) {
2507         // If there is a sequence of one or more load instructions, each loaded
2508         // value is used as address of later load instruction, bitcast is
2509         // necessary to change the value type, don't optimize it. For
2510         // simplicity we give up if the load address comes from another load.
2511         Value *Addr = LI->getOperand(0);
2512         if (Addr == &CI || isa<LoadInst>(Addr))
2513           return nullptr;
2514         // Don't tranform "load <256 x i32>, <256 x i32>*" to
2515         // "load x86_amx, x86_amx*", because x86_amx* is invalid.
2516         // TODO: Remove this check when bitcast between vector and x86_amx
2517         // is replaced with a specific intrinsic.
2518         if (DestTy->isX86_AMXTy())
2519           return nullptr;
2520         if (LI->hasOneUse() && LI->isSimple())
2521           continue;
2522         // If a LoadInst has more than one use, changing the type of loaded
2523         // value may create another bitcast.
2524         return nullptr;
2525       }
2526 
2527       if (auto *PNode = dyn_cast<PHINode>(IncValue)) {
2528         if (OldPhiNodes.insert(PNode))
2529           PhiWorklist.push_back(PNode);
2530         continue;
2531       }
2532 
2533       auto *BCI = dyn_cast<BitCastInst>(IncValue);
2534       // We can't handle other instructions.
2535       if (!BCI)
2536         return nullptr;
2537 
2538       // Verify it's a A->B cast.
2539       Type *TyA = BCI->getOperand(0)->getType();
2540       Type *TyB = BCI->getType();
2541       if (TyA != DestTy || TyB != SrcTy)
2542         return nullptr;
2543     }
2544   }
2545 
2546   // Check that each user of each old PHI node is something that we can
2547   // rewrite, so that all of the old PHI nodes can be cleaned up afterwards.
2548   for (auto *OldPN : OldPhiNodes) {
2549     for (User *V : OldPN->users()) {
2550       if (auto *SI = dyn_cast<StoreInst>(V)) {
2551         if (!SI->isSimple() || SI->getOperand(0) != OldPN)
2552           return nullptr;
2553       } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2554         // Verify it's a B->A cast.
2555         Type *TyB = BCI->getOperand(0)->getType();
2556         Type *TyA = BCI->getType();
2557         if (TyA != DestTy || TyB != SrcTy)
2558           return nullptr;
2559       } else if (auto *PHI = dyn_cast<PHINode>(V)) {
2560         // As long as the user is another old PHI node, then even if we don't
2561         // rewrite it, the PHI web we're considering won't have any users
2562         // outside itself, so it'll be dead.
2563         if (!OldPhiNodes.contains(PHI))
2564           return nullptr;
2565       } else {
2566         return nullptr;
2567       }
2568     }
2569   }
2570 
2571   // For each old PHI node, create a corresponding new PHI node with a type A.
2572   SmallDenseMap<PHINode *, PHINode *> NewPNodes;
2573   for (auto *OldPN : OldPhiNodes) {
2574     Builder.SetInsertPoint(OldPN);
2575     PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
2576     NewPNodes[OldPN] = NewPN;
2577   }
2578 
2579   // Fill in the operands of new PHI nodes.
2580   for (auto *OldPN : OldPhiNodes) {
2581     PHINode *NewPN = NewPNodes[OldPN];
2582     for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) {
2583       Value *V = OldPN->getOperand(j);
2584       Value *NewV = nullptr;
2585       if (auto *C = dyn_cast<Constant>(V)) {
2586         NewV = ConstantExpr::getBitCast(C, DestTy);
2587       } else if (auto *LI = dyn_cast<LoadInst>(V)) {
2588         // Explicitly perform load combine to make sure no opposing transform
2589         // can remove the bitcast in the meantime and trigger an infinite loop.
2590         Builder.SetInsertPoint(LI);
2591         NewV = combineLoadToNewType(*LI, DestTy);
2592         // Remove the old load and its use in the old phi, which itself becomes
2593         // dead once the whole transform finishes.
2594         replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
2595         eraseInstFromFunction(*LI);
2596       } else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2597         NewV = BCI->getOperand(0);
2598       } else if (auto *PrevPN = dyn_cast<PHINode>(V)) {
2599         NewV = NewPNodes[PrevPN];
2600       }
2601       assert(NewV);
2602       NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j));
2603     }
2604   }
2605 
2606   // Traverse all accumulated PHI nodes and process its users,
2607   // which are Stores and BitcCasts. Without this processing
2608   // NewPHI nodes could be replicated and could lead to extra
2609   // moves generated after DeSSA.
2610   // If there is a store with type B, change it to type A.
2611 
2612 
2613   // Replace users of BitCast B->A with NewPHI. These will help
2614   // later to get rid off a closure formed by OldPHI nodes.
2615   Instruction *RetVal = nullptr;
2616   for (auto *OldPN : OldPhiNodes) {
2617     PHINode *NewPN = NewPNodes[OldPN];
2618     for (User *V : make_early_inc_range(OldPN->users())) {
2619       if (auto *SI = dyn_cast<StoreInst>(V)) {
2620         assert(SI->isSimple() && SI->getOperand(0) == OldPN);
2621         Builder.SetInsertPoint(SI);
2622         auto *NewBC =
2623           cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy));
2624         SI->setOperand(0, NewBC);
2625         Worklist.push(SI);
2626         assert(hasStoreUsersOnly(*NewBC));
2627       }
2628       else if (auto *BCI = dyn_cast<BitCastInst>(V)) {
2629         Type *TyB = BCI->getOperand(0)->getType();
2630         Type *TyA = BCI->getType();
2631         assert(TyA == DestTy && TyB == SrcTy);
2632         (void) TyA;
2633         (void) TyB;
2634         Instruction *I = replaceInstUsesWith(*BCI, NewPN);
2635         if (BCI == &CI)
2636           RetVal = I;
2637       } else if (auto *PHI = dyn_cast<PHINode>(V)) {
2638         assert(OldPhiNodes.contains(PHI));
2639         (void) PHI;
2640       } else {
2641         llvm_unreachable("all uses should be handled");
2642       }
2643     }
2644   }
2645 
2646   return RetVal;
2647 }
2648 
2649 static Instruction *convertBitCastToGEP(BitCastInst &CI, IRBuilderBase &Builder,
2650                                         const DataLayout &DL) {
2651   Value *Src = CI.getOperand(0);
2652   PointerType *SrcPTy = cast<PointerType>(Src->getType());
2653   PointerType *DstPTy = cast<PointerType>(CI.getType());
2654 
2655   // Bitcasts involving opaque pointers cannot be converted into a GEP.
2656   if (SrcPTy->isOpaque() || DstPTy->isOpaque())
2657     return nullptr;
2658 
2659   Type *DstElTy = DstPTy->getNonOpaquePointerElementType();
2660   Type *SrcElTy = SrcPTy->getNonOpaquePointerElementType();
2661 
2662   // When the type pointed to is not sized the cast cannot be
2663   // turned into a gep.
2664   if (!SrcElTy->isSized())
2665     return nullptr;
2666 
2667   // If the source and destination are pointers, and this cast is equivalent
2668   // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
2669   // This can enhance SROA and other transforms that want type-safe pointers.
2670   unsigned NumZeros = 0;
2671   while (SrcElTy && SrcElTy != DstElTy) {
2672     SrcElTy = GetElementPtrInst::getTypeAtIndex(SrcElTy, (uint64_t)0);
2673     ++NumZeros;
2674   }
2675 
2676   // If we found a path from the src to dest, create the getelementptr now.
2677   if (SrcElTy == DstElTy) {
2678     SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0));
2679     GetElementPtrInst *GEP = GetElementPtrInst::Create(
2680         SrcPTy->getNonOpaquePointerElementType(), Src, Idxs);
2681 
2682     // If the source pointer is dereferenceable, then assume it points to an
2683     // allocated object and apply "inbounds" to the GEP.
2684     bool CanBeNull, CanBeFreed;
2685     if (Src->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed)) {
2686       // In a non-default address space (not 0), a null pointer can not be
2687       // assumed inbounds, so ignore that case (dereferenceable_or_null).
2688       // The reason is that 'null' is not treated differently in these address
2689       // spaces, and we consequently ignore the 'gep inbounds' special case
2690       // for 'null' which allows 'inbounds' on 'null' if the indices are
2691       // zeros.
2692       if (SrcPTy->getAddressSpace() == 0 || !CanBeNull)
2693         GEP->setIsInBounds();
2694     }
2695     return GEP;
2696   }
2697   return nullptr;
2698 }
2699 
2700 Instruction *InstCombinerImpl::visitBitCast(BitCastInst &CI) {
2701   // If the operands are integer typed then apply the integer transforms,
2702   // otherwise just apply the common ones.
2703   Value *Src = CI.getOperand(0);
2704   Type *SrcTy = Src->getType();
2705   Type *DestTy = CI.getType();
2706 
2707   // Get rid of casts from one type to the same type. These are useless and can
2708   // be replaced by the operand.
2709   if (DestTy == Src->getType())
2710     return replaceInstUsesWith(CI, Src);
2711 
2712   if (isa<PointerType>(SrcTy) && isa<PointerType>(DestTy)) {
2713     // If we are casting a alloca to a pointer to a type of the same
2714     // size, rewrite the allocation instruction to allocate the "right" type.
2715     // There is no need to modify malloc calls because it is their bitcast that
2716     // needs to be cleaned up.
2717     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
2718       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
2719         return V;
2720 
2721     if (Instruction *I = convertBitCastToGEP(CI, Builder, DL))
2722       return I;
2723   }
2724 
2725   if (FixedVectorType *DestVTy = dyn_cast<FixedVectorType>(DestTy)) {
2726     // Beware: messing with this target-specific oddity may cause trouble.
2727     if (DestVTy->getNumElements() == 1 && SrcTy->isX86_MMXTy()) {
2728       Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType());
2729       return InsertElementInst::Create(PoisonValue::get(DestTy), Elem,
2730                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2731     }
2732 
2733     if (isa<IntegerType>(SrcTy)) {
2734       // If this is a cast from an integer to vector, check to see if the input
2735       // is a trunc or zext of a bitcast from vector.  If so, we can replace all
2736       // the casts with a shuffle and (potentially) a bitcast.
2737       if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
2738         CastInst *SrcCast = cast<CastInst>(Src);
2739         if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
2740           if (isa<VectorType>(BCIn->getOperand(0)->getType()))
2741             if (Instruction *I = optimizeVectorResizeWithIntegerBitCasts(
2742                     BCIn->getOperand(0), cast<VectorType>(DestTy), *this))
2743               return I;
2744       }
2745 
2746       // If the input is an 'or' instruction, we may be doing shifts and ors to
2747       // assemble the elements of the vector manually.  Try to rip the code out
2748       // and replace it with insertelements.
2749       if (Value *V = optimizeIntegerToVectorInsertions(CI, *this))
2750         return replaceInstUsesWith(CI, V);
2751     }
2752   }
2753 
2754   if (FixedVectorType *SrcVTy = dyn_cast<FixedVectorType>(SrcTy)) {
2755     if (SrcVTy->getNumElements() == 1) {
2756       // If our destination is not a vector, then make this a straight
2757       // scalar-scalar cast.
2758       if (!DestTy->isVectorTy()) {
2759         Value *Elem =
2760           Builder.CreateExtractElement(Src,
2761                      Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
2762         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
2763       }
2764 
2765       // Otherwise, see if our source is an insert. If so, then use the scalar
2766       // component directly:
2767       // bitcast (inselt <1 x elt> V, X, 0) to <n x m> --> bitcast X to <n x m>
2768       if (auto *InsElt = dyn_cast<InsertElementInst>(Src))
2769         return new BitCastInst(InsElt->getOperand(1), DestTy);
2770     }
2771 
2772     // Convert an artificial vector insert into more analyzable bitwise logic.
2773     unsigned BitWidth = DestTy->getScalarSizeInBits();
2774     Value *X, *Y;
2775     uint64_t IndexC;
2776     if (match(Src, m_OneUse(m_InsertElt(m_OneUse(m_BitCast(m_Value(X))),
2777                                         m_Value(Y), m_ConstantInt(IndexC)))) &&
2778         DestTy->isIntegerTy() && X->getType() == DestTy &&
2779         Y->getType()->isIntegerTy() && isDesirableIntType(BitWidth)) {
2780       // Adjust for big endian - the LSBs are at the high index.
2781       if (DL.isBigEndian())
2782         IndexC = SrcVTy->getNumElements() - 1 - IndexC;
2783 
2784       // We only handle (endian-normalized) insert to index 0. Any other insert
2785       // would require a left-shift, so that is an extra instruction.
2786       if (IndexC == 0) {
2787         // bitcast (inselt (bitcast X), Y, 0) --> or (and X, MaskC), (zext Y)
2788         unsigned EltWidth = Y->getType()->getScalarSizeInBits();
2789         APInt MaskC = APInt::getHighBitsSet(BitWidth, BitWidth - EltWidth);
2790         Value *AndX = Builder.CreateAnd(X, MaskC);
2791         Value *ZextY = Builder.CreateZExt(Y, DestTy);
2792         return BinaryOperator::CreateOr(AndX, ZextY);
2793       }
2794     }
2795   }
2796 
2797   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(Src)) {
2798     // Okay, we have (bitcast (shuffle ..)).  Check to see if this is
2799     // a bitcast to a vector with the same # elts.
2800     Value *ShufOp0 = Shuf->getOperand(0);
2801     Value *ShufOp1 = Shuf->getOperand(1);
2802     auto ShufElts = cast<VectorType>(Shuf->getType())->getElementCount();
2803     auto SrcVecElts = cast<VectorType>(ShufOp0->getType())->getElementCount();
2804     if (Shuf->hasOneUse() && DestTy->isVectorTy() &&
2805         cast<VectorType>(DestTy)->getElementCount() == ShufElts &&
2806         ShufElts == SrcVecElts) {
2807       BitCastInst *Tmp;
2808       // If either of the operands is a cast from CI.getType(), then
2809       // evaluating the shuffle in the casted destination's type will allow
2810       // us to eliminate at least one cast.
2811       if (((Tmp = dyn_cast<BitCastInst>(ShufOp0)) &&
2812            Tmp->getOperand(0)->getType() == DestTy) ||
2813           ((Tmp = dyn_cast<BitCastInst>(ShufOp1)) &&
2814            Tmp->getOperand(0)->getType() == DestTy)) {
2815         Value *LHS = Builder.CreateBitCast(ShufOp0, DestTy);
2816         Value *RHS = Builder.CreateBitCast(ShufOp1, DestTy);
2817         // Return a new shuffle vector.  Use the same element ID's, as we
2818         // know the vector types match #elts.
2819         return new ShuffleVectorInst(LHS, RHS, Shuf->getShuffleMask());
2820       }
2821     }
2822 
2823     // A bitcasted-to-scalar and byte-reversing shuffle is better recognized as
2824     // a byte-swap:
2825     // bitcast <N x i8> (shuf X, undef, <N, N-1,...0>) --> bswap (bitcast X)
2826     // TODO: We should match the related pattern for bitreverse.
2827     if (DestTy->isIntegerTy() &&
2828         DL.isLegalInteger(DestTy->getScalarSizeInBits()) &&
2829         SrcTy->getScalarSizeInBits() == 8 &&
2830         ShufElts.getKnownMinValue() % 2 == 0 && Shuf->hasOneUse() &&
2831         Shuf->isReverse()) {
2832       assert(ShufOp0->getType() == SrcTy && "Unexpected shuffle mask");
2833       assert(match(ShufOp1, m_Undef()) && "Unexpected shuffle op");
2834       Function *Bswap =
2835           Intrinsic::getDeclaration(CI.getModule(), Intrinsic::bswap, DestTy);
2836       Value *ScalarX = Builder.CreateBitCast(ShufOp0, DestTy);
2837       return CallInst::Create(Bswap, { ScalarX });
2838     }
2839   }
2840 
2841   // Handle the A->B->A cast, and there is an intervening PHI node.
2842   if (PHINode *PN = dyn_cast<PHINode>(Src))
2843     if (Instruction *I = optimizeBitCastFromPhi(CI, PN))
2844       return I;
2845 
2846   if (Instruction *I = canonicalizeBitCastExtElt(CI, *this))
2847     return I;
2848 
2849   if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder))
2850     return I;
2851 
2852   if (Instruction *I = foldBitCastSelect(CI, Builder))
2853     return I;
2854 
2855   if (SrcTy->isPointerTy())
2856     return commonPointerCastTransforms(CI);
2857   return commonCastTransforms(CI);
2858 }
2859 
2860 Instruction *InstCombinerImpl::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
2861   // If the destination pointer element type is not the same as the source's
2862   // first do a bitcast to the destination type, and then the addrspacecast.
2863   // This allows the cast to be exposed to other transforms.
2864   Value *Src = CI.getOperand(0);
2865   PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
2866   PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
2867 
2868   if (!SrcTy->hasSameElementTypeAs(DestTy)) {
2869     Type *MidTy =
2870         PointerType::getWithSamePointeeType(DestTy, SrcTy->getAddressSpace());
2871     // Handle vectors of pointers.
2872     if (VectorType *VT = dyn_cast<VectorType>(CI.getType()))
2873       MidTy = VectorType::get(MidTy, VT->getElementCount());
2874 
2875     Value *NewBitCast = Builder.CreateBitCast(Src, MidTy);
2876     return new AddrSpaceCastInst(NewBitCast, CI.getType());
2877   }
2878 
2879   return commonPointerCastTransforms(CI);
2880 }
2881