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