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