xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- InstCombineVectorOps.cpp -------------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements instcombine for ExtractElement, InsertElement and
1009467b48Spatrick // ShuffleVector.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick 
1409467b48Spatrick #include "InstCombineInternal.h"
1509467b48Spatrick #include "llvm/ADT/APInt.h"
1609467b48Spatrick #include "llvm/ADT/ArrayRef.h"
1709467b48Spatrick #include "llvm/ADT/DenseMap.h"
1809467b48Spatrick #include "llvm/ADT/STLExtras.h"
19097a140dSpatrick #include "llvm/ADT/SmallBitVector.h"
2009467b48Spatrick #include "llvm/ADT/SmallVector.h"
2173471bf0Spatrick #include "llvm/ADT/Statistic.h"
2209467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h"
2309467b48Spatrick #include "llvm/Analysis/VectorUtils.h"
2409467b48Spatrick #include "llvm/IR/BasicBlock.h"
2509467b48Spatrick #include "llvm/IR/Constant.h"
2609467b48Spatrick #include "llvm/IR/Constants.h"
2709467b48Spatrick #include "llvm/IR/DerivedTypes.h"
2809467b48Spatrick #include "llvm/IR/InstrTypes.h"
2909467b48Spatrick #include "llvm/IR/Instruction.h"
3009467b48Spatrick #include "llvm/IR/Instructions.h"
3109467b48Spatrick #include "llvm/IR/Operator.h"
3209467b48Spatrick #include "llvm/IR/PatternMatch.h"
3309467b48Spatrick #include "llvm/IR/Type.h"
3409467b48Spatrick #include "llvm/IR/User.h"
3509467b48Spatrick #include "llvm/IR/Value.h"
3609467b48Spatrick #include "llvm/Support/Casting.h"
3709467b48Spatrick #include "llvm/Support/ErrorHandling.h"
3873471bf0Spatrick #include "llvm/Transforms/InstCombine/InstCombiner.h"
3909467b48Spatrick #include <cassert>
4009467b48Spatrick #include <cstdint>
4109467b48Spatrick #include <iterator>
4209467b48Spatrick #include <utility>
4309467b48Spatrick 
44*d415bd75Srobert #define DEBUG_TYPE "instcombine"
45*d415bd75Srobert 
4609467b48Spatrick using namespace llvm;
4709467b48Spatrick using namespace PatternMatch;
4809467b48Spatrick 
4973471bf0Spatrick STATISTIC(NumAggregateReconstructionsSimplified,
5073471bf0Spatrick           "Number of aggregate reconstructions turned into reuse of the "
5173471bf0Spatrick           "original aggregate");
5273471bf0Spatrick 
5309467b48Spatrick /// Return true if the value is cheaper to scalarize than it is to leave as a
54*d415bd75Srobert /// vector operation. If the extract index \p EI is a constant integer then
55*d415bd75Srobert /// some operations may be cheap to scalarize.
5609467b48Spatrick ///
5709467b48Spatrick /// FIXME: It's possible to create more instructions than previously existed.
cheapToScalarize(Value * V,Value * EI)58*d415bd75Srobert static bool cheapToScalarize(Value *V, Value *EI) {
59*d415bd75Srobert   ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
60*d415bd75Srobert 
6109467b48Spatrick   // If we can pick a scalar constant value out of a vector, that is free.
6209467b48Spatrick   if (auto *C = dyn_cast<Constant>(V))
63*d415bd75Srobert     return CEI || C->getSplatValue();
64*d415bd75Srobert 
65*d415bd75Srobert   if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
66*d415bd75Srobert     ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
67*d415bd75Srobert     // Index needs to be lower than the minimum size of the vector, because
68*d415bd75Srobert     // for scalable vector, the vector size is known at run time.
69*d415bd75Srobert     return CEI->getValue().ult(EC.getKnownMinValue());
70*d415bd75Srobert   }
7109467b48Spatrick 
7209467b48Spatrick   // An insertelement to the same constant index as our extract will simplify
7309467b48Spatrick   // to the scalar inserted element. An insertelement to a different constant
7409467b48Spatrick   // index is irrelevant to our extract.
75097a140dSpatrick   if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
76*d415bd75Srobert     return CEI;
7709467b48Spatrick 
7809467b48Spatrick   if (match(V, m_OneUse(m_Load(m_Value()))))
7909467b48Spatrick     return true;
8009467b48Spatrick 
81097a140dSpatrick   if (match(V, m_OneUse(m_UnOp())))
82097a140dSpatrick     return true;
83097a140dSpatrick 
8409467b48Spatrick   Value *V0, *V1;
8509467b48Spatrick   if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
86*d415bd75Srobert     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
8709467b48Spatrick       return true;
8809467b48Spatrick 
8909467b48Spatrick   CmpInst::Predicate UnusedPred;
9009467b48Spatrick   if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
91*d415bd75Srobert     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
9209467b48Spatrick       return true;
9309467b48Spatrick 
9409467b48Spatrick   return false;
9509467b48Spatrick }
9609467b48Spatrick 
9709467b48Spatrick // If we have a PHI node with a vector type that is only used to feed
9809467b48Spatrick // itself and be an operand of extractelement at a constant location,
9909467b48Spatrick // try to replace the PHI of the vector type with a PHI of a scalar type.
scalarizePHI(ExtractElementInst & EI,PHINode * PN)10073471bf0Spatrick Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
10173471bf0Spatrick                                             PHINode *PN) {
10209467b48Spatrick   SmallVector<Instruction *, 2> Extracts;
10309467b48Spatrick   // The users we want the PHI to have are:
10409467b48Spatrick   // 1) The EI ExtractElement (we already know this)
10509467b48Spatrick   // 2) Possibly more ExtractElements with the same index.
10609467b48Spatrick   // 3) Another operand, which will feed back into the PHI.
10709467b48Spatrick   Instruction *PHIUser = nullptr;
108*d415bd75Srobert   for (auto *U : PN->users()) {
10909467b48Spatrick     if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
11009467b48Spatrick       if (EI.getIndexOperand() == EU->getIndexOperand())
11109467b48Spatrick         Extracts.push_back(EU);
11209467b48Spatrick       else
11309467b48Spatrick         return nullptr;
11409467b48Spatrick     } else if (!PHIUser) {
11509467b48Spatrick       PHIUser = cast<Instruction>(U);
11609467b48Spatrick     } else {
11709467b48Spatrick       return nullptr;
11809467b48Spatrick     }
11909467b48Spatrick   }
12009467b48Spatrick 
12109467b48Spatrick   if (!PHIUser)
12209467b48Spatrick     return nullptr;
12309467b48Spatrick 
12409467b48Spatrick   // Verify that this PHI user has one use, which is the PHI itself,
12509467b48Spatrick   // and that it is a binary operation which is cheap to scalarize.
12609467b48Spatrick   // otherwise return nullptr.
12709467b48Spatrick   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
128*d415bd75Srobert       !(isa<BinaryOperator>(PHIUser)) ||
129*d415bd75Srobert       !cheapToScalarize(PHIUser, EI.getIndexOperand()))
13009467b48Spatrick     return nullptr;
13109467b48Spatrick 
13209467b48Spatrick   // Create a scalar PHI node that will replace the vector PHI node
13309467b48Spatrick   // just before the current PHI node.
13409467b48Spatrick   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
13509467b48Spatrick       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
13609467b48Spatrick   // Scalarize each PHI operand.
13709467b48Spatrick   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
13809467b48Spatrick     Value *PHIInVal = PN->getIncomingValue(i);
13909467b48Spatrick     BasicBlock *inBB = PN->getIncomingBlock(i);
14009467b48Spatrick     Value *Elt = EI.getIndexOperand();
14109467b48Spatrick     // If the operand is the PHI induction variable:
14209467b48Spatrick     if (PHIInVal == PHIUser) {
14309467b48Spatrick       // Scalarize the binary operation. Its first operand is the
14409467b48Spatrick       // scalar PHI, and the second operand is extracted from the other
14509467b48Spatrick       // vector operand.
14609467b48Spatrick       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
14709467b48Spatrick       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
14809467b48Spatrick       Value *Op = InsertNewInstWith(
14909467b48Spatrick           ExtractElementInst::Create(B0->getOperand(opId), Elt,
15009467b48Spatrick                                      B0->getOperand(opId)->getName() + ".Elt"),
15109467b48Spatrick           *B0);
15209467b48Spatrick       Value *newPHIUser = InsertNewInstWith(
15309467b48Spatrick           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
15409467b48Spatrick                                                 scalarPHI, Op, B0), *B0);
15509467b48Spatrick       scalarPHI->addIncoming(newPHIUser, inBB);
15609467b48Spatrick     } else {
15709467b48Spatrick       // Scalarize PHI input:
15809467b48Spatrick       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
15909467b48Spatrick       // Insert the new instruction into the predecessor basic block.
16009467b48Spatrick       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
16109467b48Spatrick       BasicBlock::iterator InsertPos;
16209467b48Spatrick       if (pos && !isa<PHINode>(pos)) {
16309467b48Spatrick         InsertPos = ++pos->getIterator();
16409467b48Spatrick       } else {
16509467b48Spatrick         InsertPos = inBB->getFirstInsertionPt();
16609467b48Spatrick       }
16709467b48Spatrick 
16809467b48Spatrick       InsertNewInstWith(newEI, *InsertPos);
16909467b48Spatrick 
17009467b48Spatrick       scalarPHI->addIncoming(newEI, inBB);
17109467b48Spatrick     }
17209467b48Spatrick   }
17309467b48Spatrick 
174*d415bd75Srobert   for (auto *E : Extracts)
17509467b48Spatrick     replaceInstUsesWith(*E, scalarPHI);
17609467b48Spatrick 
17709467b48Spatrick   return &EI;
17809467b48Spatrick }
17909467b48Spatrick 
foldBitcastExtElt(ExtractElementInst & Ext)180*d415bd75Srobert Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
18109467b48Spatrick   Value *X;
18209467b48Spatrick   uint64_t ExtIndexC;
18309467b48Spatrick   if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
18409467b48Spatrick       !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
18509467b48Spatrick     return nullptr;
18609467b48Spatrick 
187*d415bd75Srobert   ElementCount NumElts =
188*d415bd75Srobert       cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
189*d415bd75Srobert   Type *DestTy = Ext.getType();
190*d415bd75Srobert   unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
191*d415bd75Srobert   bool IsBigEndian = DL.isBigEndian();
192*d415bd75Srobert 
193*d415bd75Srobert   // If we are casting an integer to vector and extracting a portion, that is
194*d415bd75Srobert   // a shift-right and truncate.
195*d415bd75Srobert   if (X->getType()->isIntegerTy()) {
196*d415bd75Srobert     assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
197*d415bd75Srobert            "Expected fixed vector type for bitcast from scalar integer");
198*d415bd75Srobert 
199*d415bd75Srobert     // Big endian requires adjusting the extract index since MSB is at index 0.
200*d415bd75Srobert     // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
201*d415bd75Srobert     // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
202*d415bd75Srobert     if (IsBigEndian)
203*d415bd75Srobert       ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
204*d415bd75Srobert     unsigned ShiftAmountC = ExtIndexC * DestWidth;
205*d415bd75Srobert     if (!ShiftAmountC ||
206*d415bd75Srobert         (isDesirableIntType(X->getType()->getPrimitiveSizeInBits()) &&
207*d415bd75Srobert         Ext.getVectorOperand()->hasOneUse())) {
208*d415bd75Srobert       if (ShiftAmountC)
209*d415bd75Srobert         X = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
210*d415bd75Srobert       if (DestTy->isFloatingPointTy()) {
211*d415bd75Srobert         Type *DstIntTy = IntegerType::getIntNTy(X->getContext(), DestWidth);
212*d415bd75Srobert         Value *Trunc = Builder.CreateTrunc(X, DstIntTy);
213*d415bd75Srobert         return new BitCastInst(Trunc, DestTy);
214*d415bd75Srobert       }
215*d415bd75Srobert       return new TruncInst(X, DestTy);
216*d415bd75Srobert     }
217*d415bd75Srobert   }
218*d415bd75Srobert 
219*d415bd75Srobert   if (!X->getType()->isVectorTy())
220*d415bd75Srobert     return nullptr;
221*d415bd75Srobert 
22209467b48Spatrick   // If this extractelement is using a bitcast from a vector of the same number
22309467b48Spatrick   // of elements, see if we can find the source element from the source vector:
22409467b48Spatrick   // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
225097a140dSpatrick   auto *SrcTy = cast<VectorType>(X->getType());
22673471bf0Spatrick   ElementCount NumSrcElts = SrcTy->getElementCount();
22709467b48Spatrick   if (NumSrcElts == NumElts)
22809467b48Spatrick     if (Value *Elt = findScalarElement(X, ExtIndexC))
22909467b48Spatrick       return new BitCastInst(Elt, DestTy);
23009467b48Spatrick 
23173471bf0Spatrick   assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
23273471bf0Spatrick          "Src and Dst must be the same sort of vector type");
23373471bf0Spatrick 
23409467b48Spatrick   // If the source elements are wider than the destination, try to shift and
23509467b48Spatrick   // truncate a subset of scalar bits of an insert op.
23673471bf0Spatrick   if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
23709467b48Spatrick     Value *Scalar;
238*d415bd75Srobert     Value *Vec;
23909467b48Spatrick     uint64_t InsIndexC;
240*d415bd75Srobert     if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
24109467b48Spatrick                               m_ConstantInt(InsIndexC))))
24209467b48Spatrick       return nullptr;
24309467b48Spatrick 
24409467b48Spatrick     // The extract must be from the subset of vector elements that we inserted
24509467b48Spatrick     // into. Example: if we inserted element 1 of a <2 x i64> and we are
24609467b48Spatrick     // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
24709467b48Spatrick     // of elements 4-7 of the bitcasted vector.
24873471bf0Spatrick     unsigned NarrowingRatio =
24973471bf0Spatrick         NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
250*d415bd75Srobert 
251*d415bd75Srobert     if (ExtIndexC / NarrowingRatio != InsIndexC) {
252*d415bd75Srobert       // Remove insertelement, if we don't use the inserted element.
253*d415bd75Srobert       // extractelement (bitcast (insertelement (Vec, b)), a) ->
254*d415bd75Srobert       // extractelement (bitcast (Vec), a)
255*d415bd75Srobert       // FIXME: this should be removed to SimplifyDemandedVectorElts,
256*d415bd75Srobert       // once scale vectors are supported.
257*d415bd75Srobert       if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
258*d415bd75Srobert         Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
259*d415bd75Srobert         return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
260*d415bd75Srobert       }
26109467b48Spatrick       return nullptr;
262*d415bd75Srobert     }
26309467b48Spatrick 
26409467b48Spatrick     // We are extracting part of the original scalar. How that scalar is
26509467b48Spatrick     // inserted into the vector depends on the endian-ness. Example:
26609467b48Spatrick     //              Vector Byte Elt Index:    0  1  2  3  4  5  6  7
26709467b48Spatrick     //                                       +--+--+--+--+--+--+--+--+
26809467b48Spatrick     // inselt <2 x i32> V, <i32> S, 1:       |V0|V1|V2|V3|S0|S1|S2|S3|
26909467b48Spatrick     // extelt <4 x i16> V', 3:               |                 |S2|S3|
27009467b48Spatrick     //                                       +--+--+--+--+--+--+--+--+
27109467b48Spatrick     // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
27209467b48Spatrick     // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
27309467b48Spatrick     // In this example, we must right-shift little-endian. Big-endian is just a
27409467b48Spatrick     // truncate.
27509467b48Spatrick     unsigned Chunk = ExtIndexC % NarrowingRatio;
27609467b48Spatrick     if (IsBigEndian)
27709467b48Spatrick       Chunk = NarrowingRatio - 1 - Chunk;
27809467b48Spatrick 
27909467b48Spatrick     // Bail out if this is an FP vector to FP vector sequence. That would take
28009467b48Spatrick     // more instructions than we started with unless there is no shift, and it
28109467b48Spatrick     // may not be handled as well in the backend.
28209467b48Spatrick     bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
28309467b48Spatrick     bool NeedDestBitcast = DestTy->isFloatingPointTy();
28409467b48Spatrick     if (NeedSrcBitcast && NeedDestBitcast)
28509467b48Spatrick       return nullptr;
28609467b48Spatrick 
28709467b48Spatrick     unsigned SrcWidth = SrcTy->getScalarSizeInBits();
28809467b48Spatrick     unsigned ShAmt = Chunk * DestWidth;
28909467b48Spatrick 
29009467b48Spatrick     // TODO: This limitation is more strict than necessary. We could sum the
29109467b48Spatrick     // number of new instructions and subtract the number eliminated to know if
29209467b48Spatrick     // we can proceed.
29309467b48Spatrick     if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
29409467b48Spatrick       if (NeedSrcBitcast || NeedDestBitcast)
29509467b48Spatrick         return nullptr;
29609467b48Spatrick 
29709467b48Spatrick     if (NeedSrcBitcast) {
29809467b48Spatrick       Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
29909467b48Spatrick       Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
30009467b48Spatrick     }
30109467b48Spatrick 
30209467b48Spatrick     if (ShAmt) {
30309467b48Spatrick       // Bail out if we could end with more instructions than we started with.
30409467b48Spatrick       if (!Ext.getVectorOperand()->hasOneUse())
30509467b48Spatrick         return nullptr;
30609467b48Spatrick       Scalar = Builder.CreateLShr(Scalar, ShAmt);
30709467b48Spatrick     }
30809467b48Spatrick 
30909467b48Spatrick     if (NeedDestBitcast) {
31009467b48Spatrick       Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
31109467b48Spatrick       return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
31209467b48Spatrick     }
31309467b48Spatrick     return new TruncInst(Scalar, DestTy);
31409467b48Spatrick   }
31509467b48Spatrick 
31609467b48Spatrick   return nullptr;
31709467b48Spatrick }
31809467b48Spatrick 
31909467b48Spatrick /// Find elements of V demanded by UserInstr.
findDemandedEltsBySingleUser(Value * V,Instruction * UserInstr)32009467b48Spatrick static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
32173471bf0Spatrick   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
32209467b48Spatrick 
32309467b48Spatrick   // Conservatively assume that all elements are needed.
324*d415bd75Srobert   APInt UsedElts(APInt::getAllOnes(VWidth));
32509467b48Spatrick 
32609467b48Spatrick   switch (UserInstr->getOpcode()) {
32709467b48Spatrick   case Instruction::ExtractElement: {
32809467b48Spatrick     ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
32909467b48Spatrick     assert(EEI->getVectorOperand() == V);
33009467b48Spatrick     ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
33109467b48Spatrick     if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
33209467b48Spatrick       UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
33309467b48Spatrick     }
33409467b48Spatrick     break;
33509467b48Spatrick   }
33609467b48Spatrick   case Instruction::ShuffleVector: {
33709467b48Spatrick     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
338097a140dSpatrick     unsigned MaskNumElts =
33973471bf0Spatrick         cast<FixedVectorType>(UserInstr->getType())->getNumElements();
34009467b48Spatrick 
34109467b48Spatrick     UsedElts = APInt(VWidth, 0);
34209467b48Spatrick     for (unsigned i = 0; i < MaskNumElts; i++) {
34309467b48Spatrick       unsigned MaskVal = Shuffle->getMaskValue(i);
34409467b48Spatrick       if (MaskVal == -1u || MaskVal >= 2 * VWidth)
34509467b48Spatrick         continue;
34609467b48Spatrick       if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
34709467b48Spatrick         UsedElts.setBit(MaskVal);
34809467b48Spatrick       if (Shuffle->getOperand(1) == V &&
34909467b48Spatrick           ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
35009467b48Spatrick         UsedElts.setBit(MaskVal - VWidth);
35109467b48Spatrick     }
35209467b48Spatrick     break;
35309467b48Spatrick   }
35409467b48Spatrick   default:
35509467b48Spatrick     break;
35609467b48Spatrick   }
35709467b48Spatrick   return UsedElts;
35809467b48Spatrick }
35909467b48Spatrick 
36009467b48Spatrick /// Find union of elements of V demanded by all its users.
36109467b48Spatrick /// If it is known by querying findDemandedEltsBySingleUser that
36209467b48Spatrick /// no user demands an element of V, then the corresponding bit
36309467b48Spatrick /// remains unset in the returned value.
findDemandedEltsByAllUsers(Value * V)36409467b48Spatrick static APInt findDemandedEltsByAllUsers(Value *V) {
36573471bf0Spatrick   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
36609467b48Spatrick 
36709467b48Spatrick   APInt UnionUsedElts(VWidth, 0);
36809467b48Spatrick   for (const Use &U : V->uses()) {
36909467b48Spatrick     if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
37009467b48Spatrick       UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
37109467b48Spatrick     } else {
372*d415bd75Srobert       UnionUsedElts = APInt::getAllOnes(VWidth);
37309467b48Spatrick       break;
37409467b48Spatrick     }
37509467b48Spatrick 
376*d415bd75Srobert     if (UnionUsedElts.isAllOnes())
37709467b48Spatrick       break;
37809467b48Spatrick   }
37909467b48Spatrick 
38009467b48Spatrick   return UnionUsedElts;
38109467b48Spatrick }
38209467b48Spatrick 
383*d415bd75Srobert /// Given a constant index for a extractelement or insertelement instruction,
384*d415bd75Srobert /// return it with the canonical type if it isn't already canonical.  We
385*d415bd75Srobert /// arbitrarily pick 64 bit as our canonical type.  The actual bitwidth doesn't
386*d415bd75Srobert /// matter, we just want a consistent type to simplify CSE.
getPreferredVectorIndex(ConstantInt * IndexC)387*d415bd75Srobert ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
388*d415bd75Srobert   const unsigned IndexBW = IndexC->getType()->getBitWidth();
389*d415bd75Srobert   if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
390*d415bd75Srobert     return nullptr;
391*d415bd75Srobert   return ConstantInt::get(IndexC->getContext(),
392*d415bd75Srobert                           IndexC->getValue().zextOrTrunc(64));
393*d415bd75Srobert }
394*d415bd75Srobert 
visitExtractElementInst(ExtractElementInst & EI)39573471bf0Spatrick Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
39609467b48Spatrick   Value *SrcVec = EI.getVectorOperand();
39709467b48Spatrick   Value *Index = EI.getIndexOperand();
398*d415bd75Srobert   if (Value *V = simplifyExtractElementInst(SrcVec, Index,
39909467b48Spatrick                                             SQ.getWithInstruction(&EI)))
40009467b48Spatrick     return replaceInstUsesWith(EI, V);
40109467b48Spatrick 
402*d415bd75Srobert   // extractelt (select %x, %vec1, %vec2), %const ->
403*d415bd75Srobert   // select %x, %vec1[%const], %vec2[%const]
404*d415bd75Srobert   // TODO: Support constant folding of multiple select operands:
405*d415bd75Srobert   // extractelt (select %x, %vec1, %vec2), (select %x, %c1, %c2)
406*d415bd75Srobert   // If the extractelement will for instance try to do out of bounds accesses
407*d415bd75Srobert   // because of the values of %c1 and/or %c2, the sequence could be optimized
408*d415bd75Srobert   // early. This is currently not possible because constant folding will reach
409*d415bd75Srobert   // an unreachable assertion if it doesn't find a constant operand.
410*d415bd75Srobert   if (SelectInst *SI = dyn_cast<SelectInst>(EI.getVectorOperand()))
411*d415bd75Srobert     if (SI->getCondition()->getType()->isIntegerTy() &&
412*d415bd75Srobert         isa<Constant>(EI.getIndexOperand()))
413*d415bd75Srobert       if (Instruction *R = FoldOpIntoSelect(EI, SI))
414*d415bd75Srobert         return R;
415*d415bd75Srobert 
41609467b48Spatrick   // If extracting a specified index from the vector, see if we can recursively
41709467b48Spatrick   // find a previously computed scalar that was inserted into the vector.
41809467b48Spatrick   auto *IndexC = dyn_cast<ConstantInt>(Index);
41909467b48Spatrick   if (IndexC) {
420*d415bd75Srobert     // Canonicalize type of constant indices to i64 to simplify CSE
421*d415bd75Srobert     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
422*d415bd75Srobert       return replaceOperand(EI, 1, NewIdx);
423*d415bd75Srobert 
424097a140dSpatrick     ElementCount EC = EI.getVectorOperandType()->getElementCount();
42573471bf0Spatrick     unsigned NumElts = EC.getKnownMinValue();
42673471bf0Spatrick 
42773471bf0Spatrick     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
42873471bf0Spatrick       Intrinsic::ID IID = II->getIntrinsicID();
42973471bf0Spatrick       // Index needs to be lower than the minimum size of the vector, because
43073471bf0Spatrick       // for scalable vector, the vector size is known at run time.
43173471bf0Spatrick       if (IID == Intrinsic::experimental_stepvector &&
43273471bf0Spatrick           IndexC->getValue().ult(NumElts)) {
43373471bf0Spatrick         Type *Ty = EI.getType();
43473471bf0Spatrick         unsigned BitWidth = Ty->getIntegerBitWidth();
43573471bf0Spatrick         Value *Idx;
43673471bf0Spatrick         // Return index when its value does not exceed the allowed limit
43773471bf0Spatrick         // for the element type of the vector, otherwise return undefined.
43873471bf0Spatrick         if (IndexC->getValue().getActiveBits() <= BitWidth)
43973471bf0Spatrick           Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
44073471bf0Spatrick         else
44173471bf0Spatrick           Idx = UndefValue::get(Ty);
44273471bf0Spatrick         return replaceInstUsesWith(EI, Idx);
44373471bf0Spatrick       }
44473471bf0Spatrick     }
44509467b48Spatrick 
44609467b48Spatrick     // InstSimplify should handle cases where the index is invalid.
447097a140dSpatrick     // For fixed-length vector, it's invalid to extract out-of-range element.
44873471bf0Spatrick     if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
44909467b48Spatrick       return nullptr;
45009467b48Spatrick 
451*d415bd75Srobert     if (Instruction *I = foldBitcastExtElt(EI))
45209467b48Spatrick       return I;
45309467b48Spatrick 
45409467b48Spatrick     // If there's a vector PHI feeding a scalar use through this extractelement
45509467b48Spatrick     // instruction, try to scalarize the PHI.
45609467b48Spatrick     if (auto *Phi = dyn_cast<PHINode>(SrcVec))
45709467b48Spatrick       if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
45809467b48Spatrick         return ScalarPHI;
45909467b48Spatrick   }
46009467b48Spatrick 
461097a140dSpatrick   // TODO come up with a n-ary matcher that subsumes both unary and
462097a140dSpatrick   // binary matchers.
463097a140dSpatrick   UnaryOperator *UO;
464*d415bd75Srobert   if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
465097a140dSpatrick     // extelt (unop X), Index --> unop (extelt X, Index)
466097a140dSpatrick     Value *X = UO->getOperand(0);
467097a140dSpatrick     Value *E = Builder.CreateExtractElement(X, Index);
468097a140dSpatrick     return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
469097a140dSpatrick   }
470097a140dSpatrick 
47109467b48Spatrick   BinaryOperator *BO;
472*d415bd75Srobert   if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
47309467b48Spatrick     // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
47409467b48Spatrick     Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
47509467b48Spatrick     Value *E0 = Builder.CreateExtractElement(X, Index);
47609467b48Spatrick     Value *E1 = Builder.CreateExtractElement(Y, Index);
47709467b48Spatrick     return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
47809467b48Spatrick   }
47909467b48Spatrick 
48009467b48Spatrick   Value *X, *Y;
48109467b48Spatrick   CmpInst::Predicate Pred;
48209467b48Spatrick   if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
483*d415bd75Srobert       cheapToScalarize(SrcVec, Index)) {
48409467b48Spatrick     // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
48509467b48Spatrick     Value *E0 = Builder.CreateExtractElement(X, Index);
48609467b48Spatrick     Value *E1 = Builder.CreateExtractElement(Y, Index);
48709467b48Spatrick     return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
48809467b48Spatrick   }
48909467b48Spatrick 
49009467b48Spatrick   if (auto *I = dyn_cast<Instruction>(SrcVec)) {
49109467b48Spatrick     if (auto *IE = dyn_cast<InsertElementInst>(I)) {
492*d415bd75Srobert       // instsimplify already handled the case where the indices are constants
493*d415bd75Srobert       // and equal by value, if both are constants, they must not be the same
494*d415bd75Srobert       // value, extract from the pre-inserted value instead.
495097a140dSpatrick       if (isa<Constant>(IE->getOperand(2)) && IndexC)
496097a140dSpatrick         return replaceOperand(EI, 0, IE->getOperand(0));
49773471bf0Spatrick     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
49873471bf0Spatrick       auto *VecType = cast<VectorType>(GEP->getType());
49973471bf0Spatrick       ElementCount EC = VecType->getElementCount();
50073471bf0Spatrick       uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
50173471bf0Spatrick       if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
50273471bf0Spatrick         // Find out why we have a vector result - these are a few examples:
50373471bf0Spatrick         //  1. We have a scalar pointer and a vector of indices, or
50473471bf0Spatrick         //  2. We have a vector of pointers and a scalar index, or
50573471bf0Spatrick         //  3. We have a vector of pointers and a vector of indices, etc.
50673471bf0Spatrick         // Here we only consider combining when there is exactly one vector
50773471bf0Spatrick         // operand, since the optimization is less obviously a win due to
50873471bf0Spatrick         // needing more than one extractelements.
50973471bf0Spatrick 
51073471bf0Spatrick         unsigned VectorOps =
51173471bf0Spatrick             llvm::count_if(GEP->operands(), [](const Value *V) {
51273471bf0Spatrick               return isa<VectorType>(V->getType());
51373471bf0Spatrick             });
514*d415bd75Srobert         if (VectorOps == 1) {
51573471bf0Spatrick           Value *NewPtr = GEP->getPointerOperand();
51673471bf0Spatrick           if (isa<VectorType>(NewPtr->getType()))
51773471bf0Spatrick             NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
51873471bf0Spatrick 
51973471bf0Spatrick           SmallVector<Value *> NewOps;
52073471bf0Spatrick           for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
52173471bf0Spatrick             Value *Op = GEP->getOperand(I);
52273471bf0Spatrick             if (isa<VectorType>(Op->getType()))
52373471bf0Spatrick               NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
52473471bf0Spatrick             else
52573471bf0Spatrick               NewOps.push_back(Op);
52673471bf0Spatrick           }
52773471bf0Spatrick 
52873471bf0Spatrick           GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
529*d415bd75Srobert               GEP->getSourceElementType(), NewPtr, NewOps);
53073471bf0Spatrick           NewGEP->setIsInBounds(GEP->isInBounds());
53173471bf0Spatrick           return NewGEP;
53273471bf0Spatrick         }
533*d415bd75Srobert       }
53409467b48Spatrick     } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
53509467b48Spatrick       // If this is extracting an element from a shufflevector, figure out where
53609467b48Spatrick       // it came from and extract from the appropriate input element instead.
537097a140dSpatrick       // Restrict the following transformation to fixed-length vector.
538097a140dSpatrick       if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
539097a140dSpatrick         int SrcIdx =
540097a140dSpatrick             SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
54109467b48Spatrick         Value *Src;
542097a140dSpatrick         unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
543097a140dSpatrick                                 ->getNumElements();
54409467b48Spatrick 
54509467b48Spatrick         if (SrcIdx < 0)
54609467b48Spatrick           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
54709467b48Spatrick         if (SrcIdx < (int)LHSWidth)
54809467b48Spatrick           Src = SVI->getOperand(0);
54909467b48Spatrick         else {
55009467b48Spatrick           SrcIdx -= LHSWidth;
55109467b48Spatrick           Src = SVI->getOperand(1);
55209467b48Spatrick         }
55309467b48Spatrick         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
554097a140dSpatrick         return ExtractElementInst::Create(
555097a140dSpatrick             Src, ConstantInt::get(Int32Ty, SrcIdx, false));
55609467b48Spatrick       }
55709467b48Spatrick     } else if (auto *CI = dyn_cast<CastInst>(I)) {
55809467b48Spatrick       // Canonicalize extractelement(cast) -> cast(extractelement).
55909467b48Spatrick       // Bitcasts can change the number of vector elements, and they cost
56009467b48Spatrick       // nothing.
56109467b48Spatrick       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
56209467b48Spatrick         Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
56309467b48Spatrick         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
56409467b48Spatrick       }
56509467b48Spatrick     }
56609467b48Spatrick   }
567*d415bd75Srobert 
568*d415bd75Srobert   // Run demanded elements after other transforms as this can drop flags on
569*d415bd75Srobert   // binops.  If there's two paths to the same final result, we prefer the
570*d415bd75Srobert   // one which doesn't force us to drop flags.
571*d415bd75Srobert   if (IndexC) {
572*d415bd75Srobert     ElementCount EC = EI.getVectorOperandType()->getElementCount();
573*d415bd75Srobert     unsigned NumElts = EC.getKnownMinValue();
574*d415bd75Srobert     // This instruction only demands the single element from the input vector.
575*d415bd75Srobert     // Skip for scalable type, the number of elements is unknown at
576*d415bd75Srobert     // compile-time.
577*d415bd75Srobert     if (!EC.isScalable() && NumElts != 1) {
578*d415bd75Srobert       // If the input vector has a single use, simplify it based on this use
579*d415bd75Srobert       // property.
580*d415bd75Srobert       if (SrcVec->hasOneUse()) {
581*d415bd75Srobert         APInt UndefElts(NumElts, 0);
582*d415bd75Srobert         APInt DemandedElts(NumElts, 0);
583*d415bd75Srobert         DemandedElts.setBit(IndexC->getZExtValue());
584*d415bd75Srobert         if (Value *V =
585*d415bd75Srobert                 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
586*d415bd75Srobert           return replaceOperand(EI, 0, V);
587*d415bd75Srobert       } else {
588*d415bd75Srobert         // If the input vector has multiple uses, simplify it based on a union
589*d415bd75Srobert         // of all elements used.
590*d415bd75Srobert         APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
591*d415bd75Srobert         if (!DemandedElts.isAllOnes()) {
592*d415bd75Srobert           APInt UndefElts(NumElts, 0);
593*d415bd75Srobert           if (Value *V = SimplifyDemandedVectorElts(
594*d415bd75Srobert                   SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
595*d415bd75Srobert                   true /* AllowMultipleUsers */)) {
596*d415bd75Srobert             if (V != SrcVec) {
597*d415bd75Srobert               SrcVec->replaceAllUsesWith(V);
598*d415bd75Srobert               return &EI;
599*d415bd75Srobert             }
600*d415bd75Srobert           }
601*d415bd75Srobert         }
602*d415bd75Srobert       }
603*d415bd75Srobert     }
604*d415bd75Srobert   }
60509467b48Spatrick   return nullptr;
60609467b48Spatrick }
60709467b48Spatrick 
60809467b48Spatrick /// If V is a shuffle of values that ONLY returns elements from either LHS or
60909467b48Spatrick /// RHS, return the shuffle mask and true. Otherwise, return false.
collectSingleShuffleElements(Value * V,Value * LHS,Value * RHS,SmallVectorImpl<int> & Mask)61009467b48Spatrick static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
611097a140dSpatrick                                          SmallVectorImpl<int> &Mask) {
61209467b48Spatrick   assert(LHS->getType() == RHS->getType() &&
61309467b48Spatrick          "Invalid CollectSingleShuffleElements");
61473471bf0Spatrick   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
61509467b48Spatrick 
61673471bf0Spatrick   if (match(V, m_Undef())) {
617097a140dSpatrick     Mask.assign(NumElts, -1);
61809467b48Spatrick     return true;
61909467b48Spatrick   }
62009467b48Spatrick 
62109467b48Spatrick   if (V == LHS) {
62209467b48Spatrick     for (unsigned i = 0; i != NumElts; ++i)
623097a140dSpatrick       Mask.push_back(i);
62409467b48Spatrick     return true;
62509467b48Spatrick   }
62609467b48Spatrick 
62709467b48Spatrick   if (V == RHS) {
62809467b48Spatrick     for (unsigned i = 0; i != NumElts; ++i)
629097a140dSpatrick       Mask.push_back(i + NumElts);
63009467b48Spatrick     return true;
63109467b48Spatrick   }
63209467b48Spatrick 
63309467b48Spatrick   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
63409467b48Spatrick     // If this is an insert of an extract from some other vector, include it.
63509467b48Spatrick     Value *VecOp    = IEI->getOperand(0);
63609467b48Spatrick     Value *ScalarOp = IEI->getOperand(1);
63709467b48Spatrick     Value *IdxOp    = IEI->getOperand(2);
63809467b48Spatrick 
63909467b48Spatrick     if (!isa<ConstantInt>(IdxOp))
64009467b48Spatrick       return false;
64109467b48Spatrick     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
64209467b48Spatrick 
64309467b48Spatrick     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
64409467b48Spatrick       // We can handle this if the vector we are inserting into is
64509467b48Spatrick       // transitively ok.
64609467b48Spatrick       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
64709467b48Spatrick         // If so, update the mask to reflect the inserted undef.
648097a140dSpatrick         Mask[InsertedIdx] = -1;
64909467b48Spatrick         return true;
65009467b48Spatrick       }
65109467b48Spatrick     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
65209467b48Spatrick       if (isa<ConstantInt>(EI->getOperand(1))) {
65309467b48Spatrick         unsigned ExtractedIdx =
65409467b48Spatrick         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
655097a140dSpatrick         unsigned NumLHSElts =
65673471bf0Spatrick             cast<FixedVectorType>(LHS->getType())->getNumElements();
65709467b48Spatrick 
65809467b48Spatrick         // This must be extracting from either LHS or RHS.
65909467b48Spatrick         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
66009467b48Spatrick           // We can handle this if the vector we are inserting into is
66109467b48Spatrick           // transitively ok.
66209467b48Spatrick           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
66309467b48Spatrick             // If so, update the mask to reflect the inserted value.
66409467b48Spatrick             if (EI->getOperand(0) == LHS) {
665097a140dSpatrick               Mask[InsertedIdx % NumElts] = ExtractedIdx;
66609467b48Spatrick             } else {
66709467b48Spatrick               assert(EI->getOperand(0) == RHS);
668097a140dSpatrick               Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
66909467b48Spatrick             }
67009467b48Spatrick             return true;
67109467b48Spatrick           }
67209467b48Spatrick         }
67309467b48Spatrick       }
67409467b48Spatrick     }
67509467b48Spatrick   }
67609467b48Spatrick 
67709467b48Spatrick   return false;
67809467b48Spatrick }
67909467b48Spatrick 
68009467b48Spatrick /// If we have insertion into a vector that is wider than the vector that we
68109467b48Spatrick /// are extracting from, try to widen the source vector to allow a single
68209467b48Spatrick /// shufflevector to replace one or more insert/extract pairs.
replaceExtractElements(InsertElementInst * InsElt,ExtractElementInst * ExtElt,InstCombinerImpl & IC)68309467b48Spatrick static void replaceExtractElements(InsertElementInst *InsElt,
68409467b48Spatrick                                    ExtractElementInst *ExtElt,
68573471bf0Spatrick                                    InstCombinerImpl &IC) {
68673471bf0Spatrick   auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
68773471bf0Spatrick   auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
688097a140dSpatrick   unsigned NumInsElts = InsVecType->getNumElements();
689097a140dSpatrick   unsigned NumExtElts = ExtVecType->getNumElements();
69009467b48Spatrick 
69109467b48Spatrick   // The inserted-to vector must be wider than the extracted-from vector.
69209467b48Spatrick   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
69309467b48Spatrick       NumExtElts >= NumInsElts)
69409467b48Spatrick     return;
69509467b48Spatrick 
69673471bf0Spatrick   // Create a shuffle mask to widen the extended-from vector using poison
69709467b48Spatrick   // values. The mask selects all of the values of the original vector followed
69873471bf0Spatrick   // by as many poison values as needed to create a vector of the same length
69909467b48Spatrick   // as the inserted-to vector.
700097a140dSpatrick   SmallVector<int, 16> ExtendMask;
70109467b48Spatrick   for (unsigned i = 0; i < NumExtElts; ++i)
702097a140dSpatrick     ExtendMask.push_back(i);
70309467b48Spatrick   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
704097a140dSpatrick     ExtendMask.push_back(-1);
70509467b48Spatrick 
70609467b48Spatrick   Value *ExtVecOp = ExtElt->getVectorOperand();
70709467b48Spatrick   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
70809467b48Spatrick   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
70909467b48Spatrick                                    ? ExtVecOpInst->getParent()
71009467b48Spatrick                                    : ExtElt->getParent();
71109467b48Spatrick 
71209467b48Spatrick   // TODO: This restriction matches the basic block check below when creating
71309467b48Spatrick   // new extractelement instructions. If that limitation is removed, this one
71409467b48Spatrick   // could also be removed. But for now, we just bail out to ensure that we
71509467b48Spatrick   // will replace the extractelement instruction that is feeding our
71609467b48Spatrick   // insertelement instruction. This allows the insertelement to then be
71709467b48Spatrick   // replaced by a shufflevector. If the insertelement is not replaced, we can
71809467b48Spatrick   // induce infinite looping because there's an optimization for extractelement
71909467b48Spatrick   // that will delete our widening shuffle. This would trigger another attempt
72009467b48Spatrick   // here to create that shuffle, and we spin forever.
72109467b48Spatrick   if (InsertionBlock != InsElt->getParent())
72209467b48Spatrick     return;
72309467b48Spatrick 
72409467b48Spatrick   // TODO: This restriction matches the check in visitInsertElementInst() and
72509467b48Spatrick   // prevents an infinite loop caused by not turning the extract/insert pair
72609467b48Spatrick   // into a shuffle. We really should not need either check, but we're lacking
72709467b48Spatrick   // folds for shufflevectors because we're afraid to generate shuffle masks
72809467b48Spatrick   // that the backend can't handle.
72909467b48Spatrick   if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
73009467b48Spatrick     return;
73109467b48Spatrick 
732*d415bd75Srobert   auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
73309467b48Spatrick 
73409467b48Spatrick   // Insert the new shuffle after the vector operand of the extract is defined
73509467b48Spatrick   // (as long as it's not a PHI) or at the start of the basic block of the
73609467b48Spatrick   // extract, so any subsequent extracts in the same basic block can use it.
73709467b48Spatrick   // TODO: Insert before the earliest ExtractElementInst that is replaced.
73809467b48Spatrick   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
73909467b48Spatrick     WideVec->insertAfter(ExtVecOpInst);
74009467b48Spatrick   else
74109467b48Spatrick     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
74209467b48Spatrick 
74309467b48Spatrick   // Replace extracts from the original narrow vector with extracts from the new
74409467b48Spatrick   // wide vector.
74509467b48Spatrick   for (User *U : ExtVecOp->users()) {
74609467b48Spatrick     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
74709467b48Spatrick     if (!OldExt || OldExt->getParent() != WideVec->getParent())
74809467b48Spatrick       continue;
74909467b48Spatrick     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
75009467b48Spatrick     NewExt->insertAfter(OldExt);
75109467b48Spatrick     IC.replaceInstUsesWith(*OldExt, NewExt);
75209467b48Spatrick   }
75309467b48Spatrick }
75409467b48Spatrick 
75509467b48Spatrick /// We are building a shuffle to create V, which is a sequence of insertelement,
75609467b48Spatrick /// extractelement pairs. If PermittedRHS is set, then we must either use it or
75709467b48Spatrick /// not rely on the second vector source. Return a std::pair containing the
75809467b48Spatrick /// left and right vectors of the proposed shuffle (or 0), and set the Mask
75909467b48Spatrick /// parameter as required.
76009467b48Spatrick ///
76109467b48Spatrick /// Note: we intentionally don't try to fold earlier shuffles since they have
76209467b48Spatrick /// often been chosen carefully to be efficiently implementable on the target.
76309467b48Spatrick using ShuffleOps = std::pair<Value *, Value *>;
76409467b48Spatrick 
collectShuffleElements(Value * V,SmallVectorImpl<int> & Mask,Value * PermittedRHS,InstCombinerImpl & IC)765097a140dSpatrick static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
76609467b48Spatrick                                          Value *PermittedRHS,
76773471bf0Spatrick                                          InstCombinerImpl &IC) {
76809467b48Spatrick   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
769097a140dSpatrick   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
77009467b48Spatrick 
77173471bf0Spatrick   if (match(V, m_Undef())) {
772097a140dSpatrick     Mask.assign(NumElts, -1);
77309467b48Spatrick     return std::make_pair(
77409467b48Spatrick         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
77509467b48Spatrick   }
77609467b48Spatrick 
77709467b48Spatrick   if (isa<ConstantAggregateZero>(V)) {
778097a140dSpatrick     Mask.assign(NumElts, 0);
77909467b48Spatrick     return std::make_pair(V, nullptr);
78009467b48Spatrick   }
78109467b48Spatrick 
78209467b48Spatrick   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
78309467b48Spatrick     // If this is an insert of an extract from some other vector, include it.
78409467b48Spatrick     Value *VecOp    = IEI->getOperand(0);
78509467b48Spatrick     Value *ScalarOp = IEI->getOperand(1);
78609467b48Spatrick     Value *IdxOp    = IEI->getOperand(2);
78709467b48Spatrick 
78809467b48Spatrick     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
78909467b48Spatrick       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
79009467b48Spatrick         unsigned ExtractedIdx =
79109467b48Spatrick           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
79209467b48Spatrick         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
79309467b48Spatrick 
79409467b48Spatrick         // Either the extracted from or inserted into vector must be RHSVec,
79509467b48Spatrick         // otherwise we'd end up with a shuffle of three inputs.
79609467b48Spatrick         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
79709467b48Spatrick           Value *RHS = EI->getOperand(0);
79809467b48Spatrick           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
79909467b48Spatrick           assert(LR.second == nullptr || LR.second == RHS);
80009467b48Spatrick 
80109467b48Spatrick           if (LR.first->getType() != RHS->getType()) {
80209467b48Spatrick             // Although we are giving up for now, see if we can create extracts
80309467b48Spatrick             // that match the inserts for another round of combining.
80409467b48Spatrick             replaceExtractElements(IEI, EI, IC);
80509467b48Spatrick 
80609467b48Spatrick             // We tried our best, but we can't find anything compatible with RHS
80709467b48Spatrick             // further up the chain. Return a trivial shuffle.
80809467b48Spatrick             for (unsigned i = 0; i < NumElts; ++i)
809097a140dSpatrick               Mask[i] = i;
81009467b48Spatrick             return std::make_pair(V, nullptr);
81109467b48Spatrick           }
81209467b48Spatrick 
813097a140dSpatrick           unsigned NumLHSElts =
81473471bf0Spatrick               cast<FixedVectorType>(RHS->getType())->getNumElements();
815097a140dSpatrick           Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
81609467b48Spatrick           return std::make_pair(LR.first, RHS);
81709467b48Spatrick         }
81809467b48Spatrick 
81909467b48Spatrick         if (VecOp == PermittedRHS) {
82009467b48Spatrick           // We've gone as far as we can: anything on the other side of the
82109467b48Spatrick           // extractelement will already have been converted into a shuffle.
82209467b48Spatrick           unsigned NumLHSElts =
82373471bf0Spatrick               cast<FixedVectorType>(EI->getOperand(0)->getType())
82473471bf0Spatrick                   ->getNumElements();
82509467b48Spatrick           for (unsigned i = 0; i != NumElts; ++i)
826097a140dSpatrick             Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
82709467b48Spatrick           return std::make_pair(EI->getOperand(0), PermittedRHS);
82809467b48Spatrick         }
82909467b48Spatrick 
83009467b48Spatrick         // If this insertelement is a chain that comes from exactly these two
83109467b48Spatrick         // vectors, return the vector and the effective shuffle.
83209467b48Spatrick         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
83309467b48Spatrick             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
83409467b48Spatrick                                          Mask))
83509467b48Spatrick           return std::make_pair(EI->getOperand(0), PermittedRHS);
83609467b48Spatrick       }
83709467b48Spatrick     }
83809467b48Spatrick   }
83909467b48Spatrick 
84009467b48Spatrick   // Otherwise, we can't do anything fancy. Return an identity vector.
84109467b48Spatrick   for (unsigned i = 0; i != NumElts; ++i)
842097a140dSpatrick     Mask.push_back(i);
84309467b48Spatrick   return std::make_pair(V, nullptr);
84409467b48Spatrick }
84509467b48Spatrick 
84673471bf0Spatrick /// Look for chain of insertvalue's that fully define an aggregate, and trace
84773471bf0Spatrick /// back the values inserted, see if they are all were extractvalue'd from
84873471bf0Spatrick /// the same source aggregate from the exact same element indexes.
84973471bf0Spatrick /// If they were, just reuse the source aggregate.
85073471bf0Spatrick /// This potentially deals with PHI indirections.
foldAggregateConstructionIntoAggregateReuse(InsertValueInst & OrigIVI)85173471bf0Spatrick Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
85273471bf0Spatrick     InsertValueInst &OrigIVI) {
85373471bf0Spatrick   Type *AggTy = OrigIVI.getType();
85473471bf0Spatrick   unsigned NumAggElts;
85573471bf0Spatrick   switch (AggTy->getTypeID()) {
85673471bf0Spatrick   case Type::StructTyID:
85773471bf0Spatrick     NumAggElts = AggTy->getStructNumElements();
85873471bf0Spatrick     break;
85973471bf0Spatrick   case Type::ArrayTyID:
86073471bf0Spatrick     NumAggElts = AggTy->getArrayNumElements();
86173471bf0Spatrick     break;
86273471bf0Spatrick   default:
86373471bf0Spatrick     llvm_unreachable("Unhandled aggregate type?");
86473471bf0Spatrick   }
86573471bf0Spatrick 
86673471bf0Spatrick   // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
86773471bf0Spatrick   // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
86873471bf0Spatrick   // FIXME: any interesting patterns to be caught with larger limit?
86973471bf0Spatrick   assert(NumAggElts > 0 && "Aggregate should have elements.");
87073471bf0Spatrick   if (NumAggElts > 2)
87173471bf0Spatrick     return nullptr;
87273471bf0Spatrick 
873*d415bd75Srobert   static constexpr auto NotFound = std::nullopt;
87473471bf0Spatrick   static constexpr auto FoundMismatch = nullptr;
87573471bf0Spatrick 
87673471bf0Spatrick   // Try to find a value of each element of an aggregate.
87773471bf0Spatrick   // FIXME: deal with more complex, not one-dimensional, aggregate types
878*d415bd75Srobert   SmallVector<std::optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
87973471bf0Spatrick 
88073471bf0Spatrick   // Do we know values for each element of the aggregate?
88173471bf0Spatrick   auto KnowAllElts = [&AggElts]() {
882*d415bd75Srobert     return !llvm::is_contained(AggElts, NotFound);
88373471bf0Spatrick   };
88473471bf0Spatrick 
88573471bf0Spatrick   int Depth = 0;
88673471bf0Spatrick 
88773471bf0Spatrick   // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
88873471bf0Spatrick   // every element being overwritten twice, which should never happen.
88973471bf0Spatrick   static const int DepthLimit = 2 * NumAggElts;
89073471bf0Spatrick 
89173471bf0Spatrick   // Recurse up the chain of `insertvalue` aggregate operands until either we've
89273471bf0Spatrick   // reconstructed full initializer or can't visit any more `insertvalue`'s.
89373471bf0Spatrick   for (InsertValueInst *CurrIVI = &OrigIVI;
89473471bf0Spatrick        Depth < DepthLimit && CurrIVI && !KnowAllElts();
89573471bf0Spatrick        CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
89673471bf0Spatrick                        ++Depth) {
89773471bf0Spatrick     auto *InsertedValue =
89873471bf0Spatrick         dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
89973471bf0Spatrick     if (!InsertedValue)
90073471bf0Spatrick       return nullptr; // Inserted value must be produced by an instruction.
90173471bf0Spatrick 
90273471bf0Spatrick     ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
90373471bf0Spatrick 
90473471bf0Spatrick     // Don't bother with more than single-level aggregates.
90573471bf0Spatrick     if (Indices.size() != 1)
90673471bf0Spatrick       return nullptr; // FIXME: deal with more complex aggregates?
90773471bf0Spatrick 
90873471bf0Spatrick     // Now, we may have already previously recorded the value for this element
90973471bf0Spatrick     // of an aggregate. If we did, that means the CurrIVI will later be
91073471bf0Spatrick     // overwritten with the already-recorded value. But if not, let's record it!
911*d415bd75Srobert     std::optional<Instruction *> &Elt = AggElts[Indices.front()];
912*d415bd75Srobert     Elt = Elt.value_or(InsertedValue);
91373471bf0Spatrick 
91473471bf0Spatrick     // FIXME: should we handle chain-terminating undef base operand?
91573471bf0Spatrick   }
91673471bf0Spatrick 
91773471bf0Spatrick   // Was that sufficient to deduce the full initializer for the aggregate?
91873471bf0Spatrick   if (!KnowAllElts())
91973471bf0Spatrick     return nullptr; // Give up then.
92073471bf0Spatrick 
92173471bf0Spatrick   // We now want to find the source[s] of the aggregate elements we've found.
92273471bf0Spatrick   // And with "source" we mean the original aggregate[s] from which
92373471bf0Spatrick   // the inserted elements were extracted. This may require PHI translation.
92473471bf0Spatrick 
92573471bf0Spatrick   enum class AggregateDescription {
92673471bf0Spatrick     /// When analyzing the value that was inserted into an aggregate, we did
92773471bf0Spatrick     /// not manage to find defining `extractvalue` instruction to analyze.
92873471bf0Spatrick     NotFound,
92973471bf0Spatrick     /// When analyzing the value that was inserted into an aggregate, we did
93073471bf0Spatrick     /// manage to find defining `extractvalue` instruction[s], and everything
93173471bf0Spatrick     /// matched perfectly - aggregate type, element insertion/extraction index.
93273471bf0Spatrick     Found,
93373471bf0Spatrick     /// When analyzing the value that was inserted into an aggregate, we did
93473471bf0Spatrick     /// manage to find defining `extractvalue` instruction, but there was
93573471bf0Spatrick     /// a mismatch: either the source type from which the extraction was didn't
93673471bf0Spatrick     /// match the aggregate type into which the insertion was,
93773471bf0Spatrick     /// or the extraction/insertion channels mismatched,
93873471bf0Spatrick     /// or different elements had different source aggregates.
93973471bf0Spatrick     FoundMismatch
94073471bf0Spatrick   };
941*d415bd75Srobert   auto Describe = [](std::optional<Value *> SourceAggregate) {
94273471bf0Spatrick     if (SourceAggregate == NotFound)
94373471bf0Spatrick       return AggregateDescription::NotFound;
94473471bf0Spatrick     if (*SourceAggregate == FoundMismatch)
94573471bf0Spatrick       return AggregateDescription::FoundMismatch;
94673471bf0Spatrick     return AggregateDescription::Found;
94773471bf0Spatrick   };
94873471bf0Spatrick 
94973471bf0Spatrick   // Given the value \p Elt that was being inserted into element \p EltIdx of an
95073471bf0Spatrick   // aggregate AggTy, see if \p Elt was originally defined by an
95173471bf0Spatrick   // appropriate extractvalue (same element index, same aggregate type).
95273471bf0Spatrick   // If found, return the source aggregate from which the extraction was.
95373471bf0Spatrick   // If \p PredBB is provided, does PHI translation of an \p Elt first.
95473471bf0Spatrick   auto FindSourceAggregate =
955*d415bd75Srobert       [&](Instruction *Elt, unsigned EltIdx, std::optional<BasicBlock *> UseBB,
956*d415bd75Srobert           std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
95773471bf0Spatrick     // For now(?), only deal with, at most, a single level of PHI indirection.
95873471bf0Spatrick     if (UseBB && PredBB)
95973471bf0Spatrick       Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
96073471bf0Spatrick     // FIXME: deal with multiple levels of PHI indirection?
96173471bf0Spatrick 
96273471bf0Spatrick     // Did we find an extraction?
96373471bf0Spatrick     auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
96473471bf0Spatrick     if (!EVI)
96573471bf0Spatrick       return NotFound;
96673471bf0Spatrick 
96773471bf0Spatrick     Value *SourceAggregate = EVI->getAggregateOperand();
96873471bf0Spatrick 
96973471bf0Spatrick     // Is the extraction from the same type into which the insertion was?
97073471bf0Spatrick     if (SourceAggregate->getType() != AggTy)
97173471bf0Spatrick       return FoundMismatch;
97273471bf0Spatrick     // And the element index doesn't change between extraction and insertion?
97373471bf0Spatrick     if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
97473471bf0Spatrick       return FoundMismatch;
97573471bf0Spatrick 
97673471bf0Spatrick     return SourceAggregate; // AggregateDescription::Found
97773471bf0Spatrick   };
97873471bf0Spatrick 
97973471bf0Spatrick   // Given elements AggElts that were constructing an aggregate OrigIVI,
98073471bf0Spatrick   // see if we can find appropriate source aggregate for each of the elements,
98173471bf0Spatrick   // and see it's the same aggregate for each element. If so, return it.
98273471bf0Spatrick   auto FindCommonSourceAggregate =
983*d415bd75Srobert       [&](std::optional<BasicBlock *> UseBB,
984*d415bd75Srobert           std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
985*d415bd75Srobert     std::optional<Value *> SourceAggregate;
98673471bf0Spatrick 
98773471bf0Spatrick     for (auto I : enumerate(AggElts)) {
98873471bf0Spatrick       assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
98973471bf0Spatrick              "We don't store nullptr in SourceAggregate!");
99073471bf0Spatrick       assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
99173471bf0Spatrick                  (I.index() != 0) &&
992*d415bd75Srobert              "SourceAggregate should be valid after the first element,");
99373471bf0Spatrick 
99473471bf0Spatrick       // For this element, is there a plausible source aggregate?
99573471bf0Spatrick       // FIXME: we could special-case undef element, IFF we know that in the
99673471bf0Spatrick       //        source aggregate said element isn't poison.
997*d415bd75Srobert       std::optional<Value *> SourceAggregateForElement =
99873471bf0Spatrick           FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
99973471bf0Spatrick 
100073471bf0Spatrick       // Okay, what have we found? Does that correlate with previous findings?
100173471bf0Spatrick 
100273471bf0Spatrick       // Regardless of whether or not we have previously found source
100373471bf0Spatrick       // aggregate for previous elements (if any), if we didn't find one for
100473471bf0Spatrick       // this element, passthrough whatever we have just found.
100573471bf0Spatrick       if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
100673471bf0Spatrick         return SourceAggregateForElement;
100773471bf0Spatrick 
100873471bf0Spatrick       // Okay, we have found source aggregate for this element.
100973471bf0Spatrick       // Let's see what we already know from previous elements, if any.
101073471bf0Spatrick       switch (Describe(SourceAggregate)) {
101173471bf0Spatrick       case AggregateDescription::NotFound:
101273471bf0Spatrick         // This is apparently the first element that we have examined.
101373471bf0Spatrick         SourceAggregate = SourceAggregateForElement; // Record the aggregate!
101473471bf0Spatrick         continue; // Great, now look at next element.
101573471bf0Spatrick       case AggregateDescription::Found:
101673471bf0Spatrick         // We have previously already successfully examined other elements.
101773471bf0Spatrick         // Is this the same source aggregate we've found for other elements?
101873471bf0Spatrick         if (*SourceAggregateForElement != *SourceAggregate)
101973471bf0Spatrick           return FoundMismatch;
102073471bf0Spatrick         continue; // Still the same aggregate, look at next element.
102173471bf0Spatrick       case AggregateDescription::FoundMismatch:
102273471bf0Spatrick         llvm_unreachable("Can't happen. We would have early-exited then.");
102373471bf0Spatrick       };
102473471bf0Spatrick     }
102573471bf0Spatrick 
102673471bf0Spatrick     assert(Describe(SourceAggregate) == AggregateDescription::Found &&
102773471bf0Spatrick            "Must be a valid Value");
102873471bf0Spatrick     return *SourceAggregate;
102973471bf0Spatrick   };
103073471bf0Spatrick 
1031*d415bd75Srobert   std::optional<Value *> SourceAggregate;
103273471bf0Spatrick 
103373471bf0Spatrick   // Can we find the source aggregate without looking at predecessors?
1034*d415bd75Srobert   SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/std::nullopt,
1035*d415bd75Srobert                                               /*PredBB=*/std::nullopt);
103673471bf0Spatrick   if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
103773471bf0Spatrick     if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
103873471bf0Spatrick       return nullptr; // Conflicting source aggregates!
103973471bf0Spatrick     ++NumAggregateReconstructionsSimplified;
104073471bf0Spatrick     return replaceInstUsesWith(OrigIVI, *SourceAggregate);
104173471bf0Spatrick   }
104273471bf0Spatrick 
104373471bf0Spatrick   // Okay, apparently we need to look at predecessors.
104473471bf0Spatrick 
104573471bf0Spatrick   // We should be smart about picking the "use" basic block, which will be the
104673471bf0Spatrick   // merge point for aggregate, where we'll insert the final PHI that will be
104773471bf0Spatrick   // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
104873471bf0Spatrick   // We should look in which blocks each of the AggElts is being defined,
104973471bf0Spatrick   // they all should be defined in the same basic block.
105073471bf0Spatrick   BasicBlock *UseBB = nullptr;
105173471bf0Spatrick 
1052*d415bd75Srobert   for (const std::optional<Instruction *> &I : AggElts) {
105373471bf0Spatrick     BasicBlock *BB = (*I)->getParent();
105473471bf0Spatrick     // If it's the first instruction we've encountered, record the basic block.
105573471bf0Spatrick     if (!UseBB) {
105673471bf0Spatrick       UseBB = BB;
105773471bf0Spatrick       continue;
105873471bf0Spatrick     }
105973471bf0Spatrick     // Otherwise, this must be the same basic block we've seen previously.
106073471bf0Spatrick     if (UseBB != BB)
106173471bf0Spatrick       return nullptr;
106273471bf0Spatrick   }
106373471bf0Spatrick 
106473471bf0Spatrick   // If *all* of the elements are basic-block-independent, meaning they are
106573471bf0Spatrick   // either function arguments, or constant expressions, then if we didn't
106673471bf0Spatrick   // handle them without predecessor-aware handling, we won't handle them now.
106773471bf0Spatrick   if (!UseBB)
106873471bf0Spatrick     return nullptr;
106973471bf0Spatrick 
107073471bf0Spatrick   // If we didn't manage to find source aggregate without looking at
107173471bf0Spatrick   // predecessors, and there are no predecessors to look at, then we're done.
107273471bf0Spatrick   if (pred_empty(UseBB))
107373471bf0Spatrick     return nullptr;
107473471bf0Spatrick 
107573471bf0Spatrick   // Arbitrary predecessor count limit.
107673471bf0Spatrick   static const int PredCountLimit = 64;
107773471bf0Spatrick 
107873471bf0Spatrick   // Cache the (non-uniqified!) list of predecessors in a vector,
107973471bf0Spatrick   // checking the limit at the same time for efficiency.
108073471bf0Spatrick   SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
108173471bf0Spatrick   for (BasicBlock *Pred : predecessors(UseBB)) {
108273471bf0Spatrick     // Don't bother if there are too many predecessors.
108373471bf0Spatrick     if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
108473471bf0Spatrick       return nullptr;
108573471bf0Spatrick     Preds.emplace_back(Pred);
108673471bf0Spatrick   }
108773471bf0Spatrick 
108873471bf0Spatrick   // For each predecessor, what is the source aggregate,
108973471bf0Spatrick   // from which all the elements were originally extracted from?
109073471bf0Spatrick   // Note that we want for the map to have stable iteration order!
109173471bf0Spatrick   SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
109273471bf0Spatrick   for (BasicBlock *Pred : Preds) {
109373471bf0Spatrick     std::pair<decltype(SourceAggregates)::iterator, bool> IV =
109473471bf0Spatrick         SourceAggregates.insert({Pred, nullptr});
109573471bf0Spatrick     // Did we already evaluate this predecessor?
109673471bf0Spatrick     if (!IV.second)
109773471bf0Spatrick       continue;
109873471bf0Spatrick 
109973471bf0Spatrick     // Let's hope that when coming from predecessor Pred, all elements of the
110073471bf0Spatrick     // aggregate produced by OrigIVI must have been originally extracted from
110173471bf0Spatrick     // the same aggregate. Is that so? Can we find said original aggregate?
110273471bf0Spatrick     SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
110373471bf0Spatrick     if (Describe(SourceAggregate) != AggregateDescription::Found)
110473471bf0Spatrick       return nullptr; // Give up.
110573471bf0Spatrick     IV.first->second = *SourceAggregate;
110673471bf0Spatrick   }
110773471bf0Spatrick 
110873471bf0Spatrick   // All good! Now we just need to thread the source aggregates here.
110973471bf0Spatrick   // Note that we have to insert the new PHI here, ourselves, because we can't
111073471bf0Spatrick   // rely on InstCombinerImpl::run() inserting it into the right basic block.
111173471bf0Spatrick   // Note that the same block can be a predecessor more than once,
111273471bf0Spatrick   // and we need to preserve that invariant for the PHI node.
111373471bf0Spatrick   BuilderTy::InsertPointGuard Guard(Builder);
111473471bf0Spatrick   Builder.SetInsertPoint(UseBB->getFirstNonPHI());
111573471bf0Spatrick   auto *PHI =
111673471bf0Spatrick       Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
111773471bf0Spatrick   for (BasicBlock *Pred : Preds)
111873471bf0Spatrick     PHI->addIncoming(SourceAggregates[Pred], Pred);
111973471bf0Spatrick 
112073471bf0Spatrick   ++NumAggregateReconstructionsSimplified;
112173471bf0Spatrick   return replaceInstUsesWith(OrigIVI, PHI);
112273471bf0Spatrick }
112373471bf0Spatrick 
112409467b48Spatrick /// Try to find redundant insertvalue instructions, like the following ones:
112509467b48Spatrick ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
112609467b48Spatrick ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
112709467b48Spatrick /// Here the second instruction inserts values at the same indices, as the
112809467b48Spatrick /// first one, making the first one redundant.
112909467b48Spatrick /// It should be transformed to:
113009467b48Spatrick ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
visitInsertValueInst(InsertValueInst & I)113173471bf0Spatrick Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
113209467b48Spatrick   bool IsRedundant = false;
113309467b48Spatrick   ArrayRef<unsigned int> FirstIndices = I.getIndices();
113409467b48Spatrick 
113509467b48Spatrick   // If there is a chain of insertvalue instructions (each of them except the
113609467b48Spatrick   // last one has only one use and it's another insertvalue insn from this
113709467b48Spatrick   // chain), check if any of the 'children' uses the same indices as the first
113809467b48Spatrick   // instruction. In this case, the first one is redundant.
113909467b48Spatrick   Value *V = &I;
114009467b48Spatrick   unsigned Depth = 0;
114109467b48Spatrick   while (V->hasOneUse() && Depth < 10) {
114209467b48Spatrick     User *U = V->user_back();
114309467b48Spatrick     auto UserInsInst = dyn_cast<InsertValueInst>(U);
114409467b48Spatrick     if (!UserInsInst || U->getOperand(0) != V)
114509467b48Spatrick       break;
114609467b48Spatrick     if (UserInsInst->getIndices() == FirstIndices) {
114709467b48Spatrick       IsRedundant = true;
114809467b48Spatrick       break;
114909467b48Spatrick     }
115009467b48Spatrick     V = UserInsInst;
115109467b48Spatrick     Depth++;
115209467b48Spatrick   }
115309467b48Spatrick 
115409467b48Spatrick   if (IsRedundant)
115509467b48Spatrick     return replaceInstUsesWith(I, I.getOperand(0));
115673471bf0Spatrick 
115773471bf0Spatrick   if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
115873471bf0Spatrick     return NewI;
115973471bf0Spatrick 
116009467b48Spatrick   return nullptr;
116109467b48Spatrick }
116209467b48Spatrick 
isShuffleEquivalentToSelect(ShuffleVectorInst & Shuf)116309467b48Spatrick static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
1164097a140dSpatrick   // Can not analyze scalable type, the number of elements is not a compile-time
1165097a140dSpatrick   // constant.
1166097a140dSpatrick   if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
1167097a140dSpatrick     return false;
1168097a140dSpatrick 
1169097a140dSpatrick   int MaskSize = Shuf.getShuffleMask().size();
1170097a140dSpatrick   int VecSize =
1171097a140dSpatrick       cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
117209467b48Spatrick 
117309467b48Spatrick   // A vector select does not change the size of the operands.
117409467b48Spatrick   if (MaskSize != VecSize)
117509467b48Spatrick     return false;
117609467b48Spatrick 
117709467b48Spatrick   // Each mask element must be undefined or choose a vector element from one of
117809467b48Spatrick   // the source operands without crossing vector lanes.
117909467b48Spatrick   for (int i = 0; i != MaskSize; ++i) {
118009467b48Spatrick     int Elt = Shuf.getMaskValue(i);
118109467b48Spatrick     if (Elt != -1 && Elt != i && Elt != i + VecSize)
118209467b48Spatrick       return false;
118309467b48Spatrick   }
118409467b48Spatrick 
118509467b48Spatrick   return true;
118609467b48Spatrick }
118709467b48Spatrick 
118809467b48Spatrick /// Turn a chain of inserts that splats a value into an insert + shuffle:
118909467b48Spatrick /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
119073471bf0Spatrick /// shufflevector(insertelt(X, %k, 0), poison, zero)
foldInsSequenceIntoSplat(InsertElementInst & InsElt)119109467b48Spatrick static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
119209467b48Spatrick   // We are interested in the last insert in a chain. So if this insert has a
119309467b48Spatrick   // single user and that user is an insert, bail.
119409467b48Spatrick   if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
119509467b48Spatrick     return nullptr;
119609467b48Spatrick 
1197097a140dSpatrick   VectorType *VecTy = InsElt.getType();
1198097a140dSpatrick   // Can not handle scalable type, the number of elements is not a compile-time
1199097a140dSpatrick   // constant.
1200097a140dSpatrick   if (isa<ScalableVectorType>(VecTy))
1201097a140dSpatrick     return nullptr;
1202097a140dSpatrick   unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
120309467b48Spatrick 
120409467b48Spatrick   // Do not try to do this for a one-element vector, since that's a nop,
120509467b48Spatrick   // and will cause an inf-loop.
120609467b48Spatrick   if (NumElements == 1)
120709467b48Spatrick     return nullptr;
120809467b48Spatrick 
120909467b48Spatrick   Value *SplatVal = InsElt.getOperand(1);
121009467b48Spatrick   InsertElementInst *CurrIE = &InsElt;
1211097a140dSpatrick   SmallBitVector ElementPresent(NumElements, false);
121209467b48Spatrick   InsertElementInst *FirstIE = nullptr;
121309467b48Spatrick 
121409467b48Spatrick   // Walk the chain backwards, keeping track of which indices we inserted into,
121509467b48Spatrick   // until we hit something that isn't an insert of the splatted value.
121609467b48Spatrick   while (CurrIE) {
121709467b48Spatrick     auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
121809467b48Spatrick     if (!Idx || CurrIE->getOperand(1) != SplatVal)
121909467b48Spatrick       return nullptr;
122009467b48Spatrick 
122109467b48Spatrick     auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
122209467b48Spatrick     // Check none of the intermediate steps have any additional uses, except
122309467b48Spatrick     // for the root insertelement instruction, which can be re-used, if it
122409467b48Spatrick     // inserts at position 0.
122509467b48Spatrick     if (CurrIE != &InsElt &&
122609467b48Spatrick         (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
122709467b48Spatrick       return nullptr;
122809467b48Spatrick 
122909467b48Spatrick     ElementPresent[Idx->getZExtValue()] = true;
123009467b48Spatrick     FirstIE = CurrIE;
123109467b48Spatrick     CurrIE = NextIE;
123209467b48Spatrick   }
123309467b48Spatrick 
123409467b48Spatrick   // If this is just a single insertelement (not a sequence), we are done.
123509467b48Spatrick   if (FirstIE == &InsElt)
123609467b48Spatrick     return nullptr;
123709467b48Spatrick 
123809467b48Spatrick   // If we are not inserting into an undef vector, make sure we've seen an
123909467b48Spatrick   // insert into every element.
124009467b48Spatrick   // TODO: If the base vector is not undef, it might be better to create a splat
124109467b48Spatrick   //       and then a select-shuffle (blend) with the base vector.
124273471bf0Spatrick   if (!match(FirstIE->getOperand(0), m_Undef()))
1243097a140dSpatrick     if (!ElementPresent.all())
124409467b48Spatrick       return nullptr;
124509467b48Spatrick 
124609467b48Spatrick   // Create the insert + shuffle.
124709467b48Spatrick   Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
124873471bf0Spatrick   PoisonValue *PoisonVec = PoisonValue::get(VecTy);
124909467b48Spatrick   Constant *Zero = ConstantInt::get(Int32Ty, 0);
125009467b48Spatrick   if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
125173471bf0Spatrick     FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
125209467b48Spatrick 
125309467b48Spatrick   // Splat from element 0, but replace absent elements with undef in the mask.
1254097a140dSpatrick   SmallVector<int, 16> Mask(NumElements, 0);
125509467b48Spatrick   for (unsigned i = 0; i != NumElements; ++i)
125609467b48Spatrick     if (!ElementPresent[i])
1257097a140dSpatrick       Mask[i] = -1;
125809467b48Spatrick 
1259*d415bd75Srobert   return new ShuffleVectorInst(FirstIE, Mask);
126009467b48Spatrick }
126109467b48Spatrick 
126209467b48Spatrick /// Try to fold an insert element into an existing splat shuffle by changing
126309467b48Spatrick /// the shuffle's mask to include the index of this insert element.
foldInsEltIntoSplat(InsertElementInst & InsElt)126409467b48Spatrick static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
126509467b48Spatrick   // Check if the vector operand of this insert is a canonical splat shuffle.
126609467b48Spatrick   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
126709467b48Spatrick   if (!Shuf || !Shuf->isZeroEltSplat())
126809467b48Spatrick     return nullptr;
126909467b48Spatrick 
1270097a140dSpatrick   // Bail out early if shuffle is scalable type. The number of elements in
1271097a140dSpatrick   // shuffle mask is unknown at compile-time.
1272097a140dSpatrick   if (isa<ScalableVectorType>(Shuf->getType()))
1273097a140dSpatrick     return nullptr;
1274097a140dSpatrick 
127509467b48Spatrick   // Check for a constant insertion index.
127609467b48Spatrick   uint64_t IdxC;
127709467b48Spatrick   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
127809467b48Spatrick     return nullptr;
127909467b48Spatrick 
128009467b48Spatrick   // Check if the splat shuffle's input is the same as this insert's scalar op.
128109467b48Spatrick   Value *X = InsElt.getOperand(1);
128209467b48Spatrick   Value *Op0 = Shuf->getOperand(0);
1283097a140dSpatrick   if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
128409467b48Spatrick     return nullptr;
128509467b48Spatrick 
128609467b48Spatrick   // Replace the shuffle mask element at the index of this insert with a zero.
128709467b48Spatrick   // For example:
1288*d415bd75Srobert   // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1289*d415bd75Srobert   //   --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
129073471bf0Spatrick   unsigned NumMaskElts =
129173471bf0Spatrick       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1292097a140dSpatrick   SmallVector<int, 16> NewMask(NumMaskElts);
129309467b48Spatrick   for (unsigned i = 0; i != NumMaskElts; ++i)
1294097a140dSpatrick     NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
129509467b48Spatrick 
1296*d415bd75Srobert   return new ShuffleVectorInst(Op0, NewMask);
129709467b48Spatrick }
129809467b48Spatrick 
129909467b48Spatrick /// Try to fold an extract+insert element into an existing identity shuffle by
130009467b48Spatrick /// changing the shuffle's mask to include the index of this insert element.
foldInsEltIntoIdentityShuffle(InsertElementInst & InsElt)130109467b48Spatrick static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
130209467b48Spatrick   // Check if the vector operand of this insert is an identity shuffle.
130309467b48Spatrick   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
130473471bf0Spatrick   if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
130509467b48Spatrick       !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
130609467b48Spatrick     return nullptr;
130709467b48Spatrick 
1308097a140dSpatrick   // Bail out early if shuffle is scalable type. The number of elements in
1309097a140dSpatrick   // shuffle mask is unknown at compile-time.
1310097a140dSpatrick   if (isa<ScalableVectorType>(Shuf->getType()))
1311097a140dSpatrick     return nullptr;
1312097a140dSpatrick 
131309467b48Spatrick   // Check for a constant insertion index.
131409467b48Spatrick   uint64_t IdxC;
131509467b48Spatrick   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
131609467b48Spatrick     return nullptr;
131709467b48Spatrick 
131809467b48Spatrick   // Check if this insert's scalar op is extracted from the identity shuffle's
131909467b48Spatrick   // input vector.
132009467b48Spatrick   Value *Scalar = InsElt.getOperand(1);
132109467b48Spatrick   Value *X = Shuf->getOperand(0);
1322097a140dSpatrick   if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
132309467b48Spatrick     return nullptr;
132409467b48Spatrick 
132509467b48Spatrick   // Replace the shuffle mask element at the index of this extract+insert with
132609467b48Spatrick   // that same index value.
132709467b48Spatrick   // For example:
132809467b48Spatrick   // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
132973471bf0Spatrick   unsigned NumMaskElts =
133073471bf0Spatrick       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1331097a140dSpatrick   SmallVector<int, 16> NewMask(NumMaskElts);
1332097a140dSpatrick   ArrayRef<int> OldMask = Shuf->getShuffleMask();
133309467b48Spatrick   for (unsigned i = 0; i != NumMaskElts; ++i) {
133409467b48Spatrick     if (i != IdxC) {
133509467b48Spatrick       // All mask elements besides the inserted element remain the same.
1336097a140dSpatrick       NewMask[i] = OldMask[i];
1337097a140dSpatrick     } else if (OldMask[i] == (int)IdxC) {
133809467b48Spatrick       // If the mask element was already set, there's nothing to do
133909467b48Spatrick       // (demanded elements analysis may unset it later).
134009467b48Spatrick       return nullptr;
134109467b48Spatrick     } else {
1342097a140dSpatrick       assert(OldMask[i] == UndefMaskElem &&
134309467b48Spatrick              "Unexpected shuffle mask element for identity shuffle");
1344097a140dSpatrick       NewMask[i] = IdxC;
134509467b48Spatrick     }
134609467b48Spatrick   }
134709467b48Spatrick 
134809467b48Spatrick   return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
134909467b48Spatrick }
135009467b48Spatrick 
135109467b48Spatrick /// If we have an insertelement instruction feeding into another insertelement
135209467b48Spatrick /// and the 2nd is inserting a constant into the vector, canonicalize that
135309467b48Spatrick /// constant insertion before the insertion of a variable:
135409467b48Spatrick ///
135509467b48Spatrick /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
135609467b48Spatrick /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
135709467b48Spatrick ///
135809467b48Spatrick /// This has the potential of eliminating the 2nd insertelement instruction
135909467b48Spatrick /// via constant folding of the scalar constant into a vector constant.
hoistInsEltConst(InsertElementInst & InsElt2,InstCombiner::BuilderTy & Builder)136009467b48Spatrick static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
136109467b48Spatrick                                      InstCombiner::BuilderTy &Builder) {
136209467b48Spatrick   auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
136309467b48Spatrick   if (!InsElt1 || !InsElt1->hasOneUse())
136409467b48Spatrick     return nullptr;
136509467b48Spatrick 
136609467b48Spatrick   Value *X, *Y;
136709467b48Spatrick   Constant *ScalarC;
136809467b48Spatrick   ConstantInt *IdxC1, *IdxC2;
136909467b48Spatrick   if (match(InsElt1->getOperand(0), m_Value(X)) &&
137009467b48Spatrick       match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
137109467b48Spatrick       match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
137209467b48Spatrick       match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
137309467b48Spatrick       match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
137409467b48Spatrick     Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
137509467b48Spatrick     return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
137609467b48Spatrick   }
137709467b48Spatrick 
137809467b48Spatrick   return nullptr;
137909467b48Spatrick }
138009467b48Spatrick 
138109467b48Spatrick /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
138209467b48Spatrick /// --> shufflevector X, CVec', Mask'
foldConstantInsEltIntoShuffle(InsertElementInst & InsElt)138309467b48Spatrick static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
138409467b48Spatrick   auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
138509467b48Spatrick   // Bail out if the parent has more than one use. In that case, we'd be
138609467b48Spatrick   // replacing the insertelt with a shuffle, and that's not a clear win.
138709467b48Spatrick   if (!Inst || !Inst->hasOneUse())
138809467b48Spatrick     return nullptr;
138909467b48Spatrick   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
139009467b48Spatrick     // The shuffle must have a constant vector operand. The insertelt must have
139109467b48Spatrick     // a constant scalar being inserted at a constant position in the vector.
139209467b48Spatrick     Constant *ShufConstVec, *InsEltScalar;
139309467b48Spatrick     uint64_t InsEltIndex;
139409467b48Spatrick     if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
139509467b48Spatrick         !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
139609467b48Spatrick         !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
139709467b48Spatrick       return nullptr;
139809467b48Spatrick 
139909467b48Spatrick     // Adding an element to an arbitrary shuffle could be expensive, but a
140009467b48Spatrick     // shuffle that selects elements from vectors without crossing lanes is
140109467b48Spatrick     // assumed cheap.
140209467b48Spatrick     // If we're just adding a constant into that shuffle, it will still be
140309467b48Spatrick     // cheap.
140409467b48Spatrick     if (!isShuffleEquivalentToSelect(*Shuf))
140509467b48Spatrick       return nullptr;
140609467b48Spatrick 
140709467b48Spatrick     // From the above 'select' check, we know that the mask has the same number
140809467b48Spatrick     // of elements as the vector input operands. We also know that each constant
140909467b48Spatrick     // input element is used in its lane and can not be used more than once by
141009467b48Spatrick     // the shuffle. Therefore, replace the constant in the shuffle's constant
141109467b48Spatrick     // vector with the insertelt constant. Replace the constant in the shuffle's
141209467b48Spatrick     // mask vector with the insertelt index plus the length of the vector
141309467b48Spatrick     // (because the constant vector operand of a shuffle is always the 2nd
141409467b48Spatrick     // operand).
1415097a140dSpatrick     ArrayRef<int> Mask = Shuf->getShuffleMask();
1416097a140dSpatrick     unsigned NumElts = Mask.size();
141709467b48Spatrick     SmallVector<Constant *, 16> NewShufElts(NumElts);
1418097a140dSpatrick     SmallVector<int, 16> NewMaskElts(NumElts);
141909467b48Spatrick     for (unsigned I = 0; I != NumElts; ++I) {
142009467b48Spatrick       if (I == InsEltIndex) {
142109467b48Spatrick         NewShufElts[I] = InsEltScalar;
1422097a140dSpatrick         NewMaskElts[I] = InsEltIndex + NumElts;
142309467b48Spatrick       } else {
142409467b48Spatrick         // Copy over the existing values.
142509467b48Spatrick         NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1426097a140dSpatrick         NewMaskElts[I] = Mask[I];
142709467b48Spatrick       }
1428*d415bd75Srobert 
1429*d415bd75Srobert       // Bail if we failed to find an element.
1430*d415bd75Srobert       if (!NewShufElts[I])
1431*d415bd75Srobert         return nullptr;
143209467b48Spatrick     }
143309467b48Spatrick 
143409467b48Spatrick     // Create new operands for a shuffle that includes the constant of the
143509467b48Spatrick     // original insertelt. The old shuffle will be dead now.
143609467b48Spatrick     return new ShuffleVectorInst(Shuf->getOperand(0),
1437097a140dSpatrick                                  ConstantVector::get(NewShufElts), NewMaskElts);
143809467b48Spatrick   } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
143909467b48Spatrick     // Transform sequences of insertelements ops with constant data/indexes into
144009467b48Spatrick     // a single shuffle op.
1441097a140dSpatrick     // Can not handle scalable type, the number of elements needed to create
1442097a140dSpatrick     // shuffle mask is not a compile-time constant.
1443097a140dSpatrick     if (isa<ScalableVectorType>(InsElt.getType()))
1444097a140dSpatrick       return nullptr;
1445097a140dSpatrick     unsigned NumElts =
1446097a140dSpatrick         cast<FixedVectorType>(InsElt.getType())->getNumElements();
144709467b48Spatrick 
144809467b48Spatrick     uint64_t InsertIdx[2];
144909467b48Spatrick     Constant *Val[2];
145009467b48Spatrick     if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
145109467b48Spatrick         !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
145209467b48Spatrick         !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
145309467b48Spatrick         !match(IEI->getOperand(1), m_Constant(Val[1])))
145409467b48Spatrick       return nullptr;
145509467b48Spatrick     SmallVector<Constant *, 16> Values(NumElts);
1456097a140dSpatrick     SmallVector<int, 16> Mask(NumElts);
145709467b48Spatrick     auto ValI = std::begin(Val);
145809467b48Spatrick     // Generate new constant vector and mask.
145909467b48Spatrick     // We have 2 values/masks from the insertelements instructions. Insert them
146009467b48Spatrick     // into new value/mask vectors.
146109467b48Spatrick     for (uint64_t I : InsertIdx) {
146209467b48Spatrick       if (!Values[I]) {
146309467b48Spatrick         Values[I] = *ValI;
1464097a140dSpatrick         Mask[I] = NumElts + I;
146509467b48Spatrick       }
146609467b48Spatrick       ++ValI;
146709467b48Spatrick     }
146809467b48Spatrick     // Remaining values are filled with 'undef' values.
146909467b48Spatrick     for (unsigned I = 0; I < NumElts; ++I) {
147009467b48Spatrick       if (!Values[I]) {
147109467b48Spatrick         Values[I] = UndefValue::get(InsElt.getType()->getElementType());
1472097a140dSpatrick         Mask[I] = I;
147309467b48Spatrick       }
147409467b48Spatrick     }
147509467b48Spatrick     // Create new operands for a shuffle that includes the constant of the
147609467b48Spatrick     // original insertelt.
147709467b48Spatrick     return new ShuffleVectorInst(IEI->getOperand(0),
1478097a140dSpatrick                                  ConstantVector::get(Values), Mask);
147909467b48Spatrick   }
148009467b48Spatrick   return nullptr;
148109467b48Spatrick }
148209467b48Spatrick 
1483*d415bd75Srobert /// If both the base vector and the inserted element are extended from the same
1484*d415bd75Srobert /// type, do the insert element in the narrow source type followed by extend.
1485*d415bd75Srobert /// TODO: This can be extended to include other cast opcodes, but particularly
1486*d415bd75Srobert ///       if we create a wider insertelement, make sure codegen is not harmed.
narrowInsElt(InsertElementInst & InsElt,InstCombiner::BuilderTy & Builder)1487*d415bd75Srobert static Instruction *narrowInsElt(InsertElementInst &InsElt,
1488*d415bd75Srobert                                  InstCombiner::BuilderTy &Builder) {
1489*d415bd75Srobert   // We are creating a vector extend. If the original vector extend has another
1490*d415bd75Srobert   // use, that would mean we end up with 2 vector extends, so avoid that.
1491*d415bd75Srobert   // TODO: We could ease the use-clause to "if at least one op has one use"
1492*d415bd75Srobert   //       (assuming that the source types match - see next TODO comment).
1493*d415bd75Srobert   Value *Vec = InsElt.getOperand(0);
1494*d415bd75Srobert   if (!Vec->hasOneUse())
1495*d415bd75Srobert     return nullptr;
1496*d415bd75Srobert 
1497*d415bd75Srobert   Value *Scalar = InsElt.getOperand(1);
1498*d415bd75Srobert   Value *X, *Y;
1499*d415bd75Srobert   CastInst::CastOps CastOpcode;
1500*d415bd75Srobert   if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1501*d415bd75Srobert     CastOpcode = Instruction::FPExt;
1502*d415bd75Srobert   else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1503*d415bd75Srobert     CastOpcode = Instruction::SExt;
1504*d415bd75Srobert   else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1505*d415bd75Srobert     CastOpcode = Instruction::ZExt;
1506*d415bd75Srobert   else
1507*d415bd75Srobert     return nullptr;
1508*d415bd75Srobert 
1509*d415bd75Srobert   // TODO: We can allow mismatched types by creating an intermediate cast.
1510*d415bd75Srobert   if (X->getType()->getScalarType() != Y->getType())
1511*d415bd75Srobert     return nullptr;
1512*d415bd75Srobert 
1513*d415bd75Srobert   // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1514*d415bd75Srobert   Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1515*d415bd75Srobert   return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1516*d415bd75Srobert }
1517*d415bd75Srobert 
1518*d415bd75Srobert /// If we are inserting 2 halves of a value into adjacent elements of a vector,
1519*d415bd75Srobert /// try to convert to a single insert with appropriate bitcasts.
foldTruncInsEltPair(InsertElementInst & InsElt,bool IsBigEndian,InstCombiner::BuilderTy & Builder)1520*d415bd75Srobert static Instruction *foldTruncInsEltPair(InsertElementInst &InsElt,
1521*d415bd75Srobert                                         bool IsBigEndian,
1522*d415bd75Srobert                                         InstCombiner::BuilderTy &Builder) {
1523*d415bd75Srobert   Value *VecOp    = InsElt.getOperand(0);
1524*d415bd75Srobert   Value *ScalarOp = InsElt.getOperand(1);
1525*d415bd75Srobert   Value *IndexOp  = InsElt.getOperand(2);
1526*d415bd75Srobert 
1527*d415bd75Srobert   // Pattern depends on endian because we expect lower index is inserted first.
1528*d415bd75Srobert   // Big endian:
1529*d415bd75Srobert   // inselt (inselt BaseVec, (trunc (lshr X, BW/2), Index0), (trunc X), Index1
1530*d415bd75Srobert   // Little endian:
1531*d415bd75Srobert   // inselt (inselt BaseVec, (trunc X), Index0), (trunc (lshr X, BW/2)), Index1
1532*d415bd75Srobert   // Note: It is not safe to do this transform with an arbitrary base vector
1533*d415bd75Srobert   //       because the bitcast of that vector to fewer/larger elements could
1534*d415bd75Srobert   //       allow poison to spill into an element that was not poison before.
1535*d415bd75Srobert   // TODO: Detect smaller fractions of the scalar.
1536*d415bd75Srobert   // TODO: One-use checks are conservative.
1537*d415bd75Srobert   auto *VTy = dyn_cast<FixedVectorType>(InsElt.getType());
1538*d415bd75Srobert   Value *Scalar0, *BaseVec;
1539*d415bd75Srobert   uint64_t Index0, Index1;
1540*d415bd75Srobert   if (!VTy || (VTy->getNumElements() & 1) ||
1541*d415bd75Srobert       !match(IndexOp, m_ConstantInt(Index1)) ||
1542*d415bd75Srobert       !match(VecOp, m_InsertElt(m_Value(BaseVec), m_Value(Scalar0),
1543*d415bd75Srobert                                 m_ConstantInt(Index0))) ||
1544*d415bd75Srobert       !match(BaseVec, m_Undef()))
1545*d415bd75Srobert     return nullptr;
1546*d415bd75Srobert 
1547*d415bd75Srobert   // The first insert must be to the index one less than this one, and
1548*d415bd75Srobert   // the first insert must be to an even index.
1549*d415bd75Srobert   if (Index0 + 1 != Index1 || Index0 & 1)
1550*d415bd75Srobert     return nullptr;
1551*d415bd75Srobert 
1552*d415bd75Srobert   // For big endian, the high half of the value should be inserted first.
1553*d415bd75Srobert   // For little endian, the low half of the value should be inserted first.
1554*d415bd75Srobert   Value *X;
1555*d415bd75Srobert   uint64_t ShAmt;
1556*d415bd75Srobert   if (IsBigEndian) {
1557*d415bd75Srobert     if (!match(ScalarOp, m_Trunc(m_Value(X))) ||
1558*d415bd75Srobert         !match(Scalar0, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1559*d415bd75Srobert       return nullptr;
1560*d415bd75Srobert   } else {
1561*d415bd75Srobert     if (!match(Scalar0, m_Trunc(m_Value(X))) ||
1562*d415bd75Srobert         !match(ScalarOp, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1563*d415bd75Srobert       return nullptr;
1564*d415bd75Srobert   }
1565*d415bd75Srobert 
1566*d415bd75Srobert   Type *SrcTy = X->getType();
1567*d415bd75Srobert   unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
1568*d415bd75Srobert   unsigned VecEltWidth = VTy->getScalarSizeInBits();
1569*d415bd75Srobert   if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
1570*d415bd75Srobert     return nullptr;
1571*d415bd75Srobert 
1572*d415bd75Srobert   // Bitcast the base vector to a vector type with the source element type.
1573*d415bd75Srobert   Type *CastTy = FixedVectorType::get(SrcTy, VTy->getNumElements() / 2);
1574*d415bd75Srobert   Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
1575*d415bd75Srobert 
1576*d415bd75Srobert   // Scale the insert index for a vector with half as many elements.
1577*d415bd75Srobert   // bitcast (inselt (bitcast BaseVec), X, NewIndex)
1578*d415bd75Srobert   uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
1579*d415bd75Srobert   Value *NewInsert = Builder.CreateInsertElement(CastBaseVec, X, NewIndex);
1580*d415bd75Srobert   return new BitCastInst(NewInsert, VTy);
1581*d415bd75Srobert }
1582*d415bd75Srobert 
visitInsertElementInst(InsertElementInst & IE)158373471bf0Spatrick Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
158409467b48Spatrick   Value *VecOp    = IE.getOperand(0);
158509467b48Spatrick   Value *ScalarOp = IE.getOperand(1);
158609467b48Spatrick   Value *IdxOp    = IE.getOperand(2);
158709467b48Spatrick 
1588*d415bd75Srobert   if (auto *V = simplifyInsertElementInst(
158909467b48Spatrick           VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
159009467b48Spatrick     return replaceInstUsesWith(IE, V);
159109467b48Spatrick 
1592*d415bd75Srobert   // Canonicalize type of constant indices to i64 to simplify CSE
1593*d415bd75Srobert   if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp)) {
1594*d415bd75Srobert     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1595*d415bd75Srobert       return replaceOperand(IE, 2, NewIdx);
1596*d415bd75Srobert 
1597*d415bd75Srobert     Value *BaseVec, *OtherScalar;
1598*d415bd75Srobert     uint64_t OtherIndexVal;
1599*d415bd75Srobert     if (match(VecOp, m_OneUse(m_InsertElt(m_Value(BaseVec),
1600*d415bd75Srobert                                           m_Value(OtherScalar),
1601*d415bd75Srobert                                           m_ConstantInt(OtherIndexVal)))) &&
1602*d415bd75Srobert         !isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
1603*d415bd75Srobert       Value *NewIns = Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
1604*d415bd75Srobert       return InsertElementInst::Create(NewIns, OtherScalar,
1605*d415bd75Srobert                                        Builder.getInt64(OtherIndexVal));
1606*d415bd75Srobert     }
1607*d415bd75Srobert   }
1608*d415bd75Srobert 
1609097a140dSpatrick   // If the scalar is bitcast and inserted into undef, do the insert in the
1610097a140dSpatrick   // source type followed by bitcast.
1611097a140dSpatrick   // TODO: Generalize for insert into any constant, not just undef?
1612097a140dSpatrick   Value *ScalarSrc;
1613097a140dSpatrick   if (match(VecOp, m_Undef()) &&
1614097a140dSpatrick       match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1615097a140dSpatrick       (ScalarSrc->getType()->isIntegerTy() ||
1616097a140dSpatrick        ScalarSrc->getType()->isFloatingPointTy())) {
1617097a140dSpatrick     // inselt undef, (bitcast ScalarSrc), IdxOp -->
1618097a140dSpatrick     //   bitcast (inselt undef, ScalarSrc, IdxOp)
1619097a140dSpatrick     Type *ScalarTy = ScalarSrc->getType();
1620097a140dSpatrick     Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1621097a140dSpatrick     UndefValue *NewUndef = UndefValue::get(VecTy);
1622097a140dSpatrick     Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1623097a140dSpatrick     return new BitCastInst(NewInsElt, IE.getType());
1624097a140dSpatrick   }
1625097a140dSpatrick 
162609467b48Spatrick   // If the vector and scalar are both bitcast from the same element type, do
162709467b48Spatrick   // the insert in that source type followed by bitcast.
1628097a140dSpatrick   Value *VecSrc;
162909467b48Spatrick   if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
163009467b48Spatrick       match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
163109467b48Spatrick       (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
163209467b48Spatrick       VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1633097a140dSpatrick       cast<VectorType>(VecSrc->getType())->getElementType() ==
1634097a140dSpatrick           ScalarSrc->getType()) {
163509467b48Spatrick     // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
163609467b48Spatrick     //   bitcast (inselt VecSrc, ScalarSrc, IdxOp)
163709467b48Spatrick     Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
163809467b48Spatrick     return new BitCastInst(NewInsElt, IE.getType());
163909467b48Spatrick   }
164009467b48Spatrick 
1641097a140dSpatrick   // If the inserted element was extracted from some other fixed-length vector
1642097a140dSpatrick   // and both indexes are valid constants, try to turn this into a shuffle.
1643097a140dSpatrick   // Can not handle scalable vector type, the number of elements needed to
1644097a140dSpatrick   // create shuffle mask is not a compile-time constant.
164509467b48Spatrick   uint64_t InsertedIdx, ExtractedIdx;
164609467b48Spatrick   Value *ExtVecOp;
1647097a140dSpatrick   if (isa<FixedVectorType>(IE.getType()) &&
1648097a140dSpatrick       match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1649097a140dSpatrick       match(ScalarOp,
1650097a140dSpatrick             m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1651097a140dSpatrick       isa<FixedVectorType>(ExtVecOp->getType()) &&
1652097a140dSpatrick       ExtractedIdx <
1653097a140dSpatrick           cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
165409467b48Spatrick     // TODO: Looking at the user(s) to determine if this insert is a
165509467b48Spatrick     // fold-to-shuffle opportunity does not match the usual instcombine
165609467b48Spatrick     // constraints. We should decide if the transform is worthy based only
165709467b48Spatrick     // on this instruction and its operands, but that may not work currently.
165809467b48Spatrick     //
165909467b48Spatrick     // Here, we are trying to avoid creating shuffles before reaching
166009467b48Spatrick     // the end of a chain of extract-insert pairs. This is complicated because
166109467b48Spatrick     // we do not generally form arbitrary shuffle masks in instcombine
166209467b48Spatrick     // (because those may codegen poorly), but collectShuffleElements() does
166309467b48Spatrick     // exactly that.
166409467b48Spatrick     //
166509467b48Spatrick     // The rules for determining what is an acceptable target-independent
166609467b48Spatrick     // shuffle mask are fuzzy because they evolve based on the backend's
166709467b48Spatrick     // capabilities and real-world impact.
166809467b48Spatrick     auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
166909467b48Spatrick       if (!Insert.hasOneUse())
167009467b48Spatrick         return true;
167109467b48Spatrick       auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
167209467b48Spatrick       if (!InsertUser)
167309467b48Spatrick         return true;
167409467b48Spatrick       return false;
167509467b48Spatrick     };
167609467b48Spatrick 
167709467b48Spatrick     // Try to form a shuffle from a chain of extract-insert ops.
167809467b48Spatrick     if (isShuffleRootCandidate(IE)) {
1679097a140dSpatrick       SmallVector<int, 16> Mask;
168009467b48Spatrick       ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
168109467b48Spatrick 
168209467b48Spatrick       // The proposed shuffle may be trivial, in which case we shouldn't
168309467b48Spatrick       // perform the combine.
168409467b48Spatrick       if (LR.first != &IE && LR.second != &IE) {
168509467b48Spatrick         // We now have a shuffle of LHS, RHS, Mask.
168609467b48Spatrick         if (LR.second == nullptr)
168709467b48Spatrick           LR.second = UndefValue::get(LR.first->getType());
1688097a140dSpatrick         return new ShuffleVectorInst(LR.first, LR.second, Mask);
168909467b48Spatrick       }
169009467b48Spatrick     }
169109467b48Spatrick   }
169209467b48Spatrick 
1693097a140dSpatrick   if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1694097a140dSpatrick     unsigned VWidth = VecTy->getNumElements();
169509467b48Spatrick     APInt UndefElts(VWidth, 0);
1696*d415bd75Srobert     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
169709467b48Spatrick     if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
169809467b48Spatrick       if (V != &IE)
169909467b48Spatrick         return replaceInstUsesWith(IE, V);
170009467b48Spatrick       return &IE;
170109467b48Spatrick     }
1702097a140dSpatrick   }
170309467b48Spatrick 
170409467b48Spatrick   if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
170509467b48Spatrick     return Shuf;
170609467b48Spatrick 
170709467b48Spatrick   if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
170809467b48Spatrick     return NewInsElt;
170909467b48Spatrick 
171009467b48Spatrick   if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
171109467b48Spatrick     return Broadcast;
171209467b48Spatrick 
171309467b48Spatrick   if (Instruction *Splat = foldInsEltIntoSplat(IE))
171409467b48Spatrick     return Splat;
171509467b48Spatrick 
171609467b48Spatrick   if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
171709467b48Spatrick     return IdentityShuf;
171809467b48Spatrick 
1719*d415bd75Srobert   if (Instruction *Ext = narrowInsElt(IE, Builder))
1720*d415bd75Srobert     return Ext;
1721*d415bd75Srobert 
1722*d415bd75Srobert   if (Instruction *Ext = foldTruncInsEltPair(IE, DL.isBigEndian(), Builder))
1723*d415bd75Srobert     return Ext;
1724*d415bd75Srobert 
172509467b48Spatrick   return nullptr;
172609467b48Spatrick }
172709467b48Spatrick 
172809467b48Spatrick /// Return true if we can evaluate the specified expression tree if the vector
172909467b48Spatrick /// elements were shuffled in a different order.
canEvaluateShuffled(Value * V,ArrayRef<int> Mask,unsigned Depth=5)173009467b48Spatrick static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
173109467b48Spatrick                                 unsigned Depth = 5) {
173209467b48Spatrick   // We can always reorder the elements of a constant.
173309467b48Spatrick   if (isa<Constant>(V))
173409467b48Spatrick     return true;
173509467b48Spatrick 
173609467b48Spatrick   // We won't reorder vector arguments. No IPO here.
173709467b48Spatrick   Instruction *I = dyn_cast<Instruction>(V);
173809467b48Spatrick   if (!I) return false;
173909467b48Spatrick 
174009467b48Spatrick   // Two users may expect different orders of the elements. Don't try it.
174109467b48Spatrick   if (!I->hasOneUse())
174209467b48Spatrick     return false;
174309467b48Spatrick 
174409467b48Spatrick   if (Depth == 0) return false;
174509467b48Spatrick 
174609467b48Spatrick   switch (I->getOpcode()) {
174709467b48Spatrick     case Instruction::UDiv:
174809467b48Spatrick     case Instruction::SDiv:
174909467b48Spatrick     case Instruction::URem:
175009467b48Spatrick     case Instruction::SRem:
175109467b48Spatrick       // Propagating an undefined shuffle mask element to integer div/rem is not
175209467b48Spatrick       // allowed because those opcodes can create immediate undefined behavior
175309467b48Spatrick       // from an undefined element in an operand.
175473471bf0Spatrick       if (llvm::is_contained(Mask, -1))
175509467b48Spatrick         return false;
1756*d415bd75Srobert       [[fallthrough]];
175709467b48Spatrick     case Instruction::Add:
175809467b48Spatrick     case Instruction::FAdd:
175909467b48Spatrick     case Instruction::Sub:
176009467b48Spatrick     case Instruction::FSub:
176109467b48Spatrick     case Instruction::Mul:
176209467b48Spatrick     case Instruction::FMul:
176309467b48Spatrick     case Instruction::FDiv:
176409467b48Spatrick     case Instruction::FRem:
176509467b48Spatrick     case Instruction::Shl:
176609467b48Spatrick     case Instruction::LShr:
176709467b48Spatrick     case Instruction::AShr:
176809467b48Spatrick     case Instruction::And:
176909467b48Spatrick     case Instruction::Or:
177009467b48Spatrick     case Instruction::Xor:
177109467b48Spatrick     case Instruction::ICmp:
177209467b48Spatrick     case Instruction::FCmp:
177309467b48Spatrick     case Instruction::Trunc:
177409467b48Spatrick     case Instruction::ZExt:
177509467b48Spatrick     case Instruction::SExt:
177609467b48Spatrick     case Instruction::FPToUI:
177709467b48Spatrick     case Instruction::FPToSI:
177809467b48Spatrick     case Instruction::UIToFP:
177909467b48Spatrick     case Instruction::SIToFP:
178009467b48Spatrick     case Instruction::FPTrunc:
178109467b48Spatrick     case Instruction::FPExt:
178209467b48Spatrick     case Instruction::GetElementPtr: {
178309467b48Spatrick       // Bail out if we would create longer vector ops. We could allow creating
178409467b48Spatrick       // longer vector ops, but that may result in more expensive codegen.
178509467b48Spatrick       Type *ITy = I->getType();
1786097a140dSpatrick       if (ITy->isVectorTy() &&
178773471bf0Spatrick           Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
178809467b48Spatrick         return false;
178909467b48Spatrick       for (Value *Operand : I->operands()) {
179009467b48Spatrick         if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
179109467b48Spatrick           return false;
179209467b48Spatrick       }
179309467b48Spatrick       return true;
179409467b48Spatrick     }
179509467b48Spatrick     case Instruction::InsertElement: {
179609467b48Spatrick       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
179709467b48Spatrick       if (!CI) return false;
179809467b48Spatrick       int ElementNumber = CI->getLimitedValue();
179909467b48Spatrick 
180009467b48Spatrick       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
180109467b48Spatrick       // can't put an element into multiple indices.
180209467b48Spatrick       bool SeenOnce = false;
1803*d415bd75Srobert       for (int I : Mask) {
1804*d415bd75Srobert         if (I == ElementNumber) {
180509467b48Spatrick           if (SeenOnce)
180609467b48Spatrick             return false;
180709467b48Spatrick           SeenOnce = true;
180809467b48Spatrick         }
180909467b48Spatrick       }
181009467b48Spatrick       return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
181109467b48Spatrick     }
181209467b48Spatrick   }
181309467b48Spatrick   return false;
181409467b48Spatrick }
181509467b48Spatrick 
181609467b48Spatrick /// Rebuild a new instruction just like 'I' but with the new operands given.
181709467b48Spatrick /// In the event of type mismatch, the type of the operands is correct.
buildNew(Instruction * I,ArrayRef<Value * > NewOps)181809467b48Spatrick static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
181909467b48Spatrick   // We don't want to use the IRBuilder here because we want the replacement
182009467b48Spatrick   // instructions to appear next to 'I', not the builder's insertion point.
182109467b48Spatrick   switch (I->getOpcode()) {
182209467b48Spatrick     case Instruction::Add:
182309467b48Spatrick     case Instruction::FAdd:
182409467b48Spatrick     case Instruction::Sub:
182509467b48Spatrick     case Instruction::FSub:
182609467b48Spatrick     case Instruction::Mul:
182709467b48Spatrick     case Instruction::FMul:
182809467b48Spatrick     case Instruction::UDiv:
182909467b48Spatrick     case Instruction::SDiv:
183009467b48Spatrick     case Instruction::FDiv:
183109467b48Spatrick     case Instruction::URem:
183209467b48Spatrick     case Instruction::SRem:
183309467b48Spatrick     case Instruction::FRem:
183409467b48Spatrick     case Instruction::Shl:
183509467b48Spatrick     case Instruction::LShr:
183609467b48Spatrick     case Instruction::AShr:
183709467b48Spatrick     case Instruction::And:
183809467b48Spatrick     case Instruction::Or:
183909467b48Spatrick     case Instruction::Xor: {
184009467b48Spatrick       BinaryOperator *BO = cast<BinaryOperator>(I);
184109467b48Spatrick       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
184209467b48Spatrick       BinaryOperator *New =
184309467b48Spatrick           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
184409467b48Spatrick                                  NewOps[0], NewOps[1], "", BO);
184509467b48Spatrick       if (isa<OverflowingBinaryOperator>(BO)) {
184609467b48Spatrick         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
184709467b48Spatrick         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
184809467b48Spatrick       }
184909467b48Spatrick       if (isa<PossiblyExactOperator>(BO)) {
185009467b48Spatrick         New->setIsExact(BO->isExact());
185109467b48Spatrick       }
185209467b48Spatrick       if (isa<FPMathOperator>(BO))
185309467b48Spatrick         New->copyFastMathFlags(I);
185409467b48Spatrick       return New;
185509467b48Spatrick     }
185609467b48Spatrick     case Instruction::ICmp:
185709467b48Spatrick       assert(NewOps.size() == 2 && "icmp with #ops != 2");
185809467b48Spatrick       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
185909467b48Spatrick                           NewOps[0], NewOps[1]);
186009467b48Spatrick     case Instruction::FCmp:
186109467b48Spatrick       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
186209467b48Spatrick       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
186309467b48Spatrick                           NewOps[0], NewOps[1]);
186409467b48Spatrick     case Instruction::Trunc:
186509467b48Spatrick     case Instruction::ZExt:
186609467b48Spatrick     case Instruction::SExt:
186709467b48Spatrick     case Instruction::FPToUI:
186809467b48Spatrick     case Instruction::FPToSI:
186909467b48Spatrick     case Instruction::UIToFP:
187009467b48Spatrick     case Instruction::SIToFP:
187109467b48Spatrick     case Instruction::FPTrunc:
187209467b48Spatrick     case Instruction::FPExt: {
187309467b48Spatrick       // It's possible that the mask has a different number of elements from
187409467b48Spatrick       // the original cast. We recompute the destination type to match the mask.
1875097a140dSpatrick       Type *DestTy = VectorType::get(
1876097a140dSpatrick           I->getType()->getScalarType(),
1877097a140dSpatrick           cast<VectorType>(NewOps[0]->getType())->getElementCount());
187809467b48Spatrick       assert(NewOps.size() == 1 && "cast with #ops != 1");
187909467b48Spatrick       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
188009467b48Spatrick                               "", I);
188109467b48Spatrick     }
188209467b48Spatrick     case Instruction::GetElementPtr: {
188309467b48Spatrick       Value *Ptr = NewOps[0];
188409467b48Spatrick       ArrayRef<Value*> Idx = NewOps.slice(1);
188509467b48Spatrick       GetElementPtrInst *GEP = GetElementPtrInst::Create(
188609467b48Spatrick           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
188709467b48Spatrick       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
188809467b48Spatrick       return GEP;
188909467b48Spatrick     }
189009467b48Spatrick   }
189109467b48Spatrick   llvm_unreachable("failed to rebuild vector instructions");
189209467b48Spatrick }
189309467b48Spatrick 
evaluateInDifferentElementOrder(Value * V,ArrayRef<int> Mask)189409467b48Spatrick static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
189509467b48Spatrick   // Mask.size() does not need to be equal to the number of vector elements.
189609467b48Spatrick 
189709467b48Spatrick   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
189809467b48Spatrick   Type *EltTy = V->getType()->getScalarType();
189909467b48Spatrick   Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
190073471bf0Spatrick   if (match(V, m_Undef()))
1901097a140dSpatrick     return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
190209467b48Spatrick 
190309467b48Spatrick   if (isa<ConstantAggregateZero>(V))
1904097a140dSpatrick     return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
190509467b48Spatrick 
1906097a140dSpatrick   if (Constant *C = dyn_cast<Constant>(V))
190773471bf0Spatrick     return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
1908097a140dSpatrick                                           Mask);
190909467b48Spatrick 
191009467b48Spatrick   Instruction *I = cast<Instruction>(V);
191109467b48Spatrick   switch (I->getOpcode()) {
191209467b48Spatrick     case Instruction::Add:
191309467b48Spatrick     case Instruction::FAdd:
191409467b48Spatrick     case Instruction::Sub:
191509467b48Spatrick     case Instruction::FSub:
191609467b48Spatrick     case Instruction::Mul:
191709467b48Spatrick     case Instruction::FMul:
191809467b48Spatrick     case Instruction::UDiv:
191909467b48Spatrick     case Instruction::SDiv:
192009467b48Spatrick     case Instruction::FDiv:
192109467b48Spatrick     case Instruction::URem:
192209467b48Spatrick     case Instruction::SRem:
192309467b48Spatrick     case Instruction::FRem:
192409467b48Spatrick     case Instruction::Shl:
192509467b48Spatrick     case Instruction::LShr:
192609467b48Spatrick     case Instruction::AShr:
192709467b48Spatrick     case Instruction::And:
192809467b48Spatrick     case Instruction::Or:
192909467b48Spatrick     case Instruction::Xor:
193009467b48Spatrick     case Instruction::ICmp:
193109467b48Spatrick     case Instruction::FCmp:
193209467b48Spatrick     case Instruction::Trunc:
193309467b48Spatrick     case Instruction::ZExt:
193409467b48Spatrick     case Instruction::SExt:
193509467b48Spatrick     case Instruction::FPToUI:
193609467b48Spatrick     case Instruction::FPToSI:
193709467b48Spatrick     case Instruction::UIToFP:
193809467b48Spatrick     case Instruction::SIToFP:
193909467b48Spatrick     case Instruction::FPTrunc:
194009467b48Spatrick     case Instruction::FPExt:
194109467b48Spatrick     case Instruction::Select:
194209467b48Spatrick     case Instruction::GetElementPtr: {
194309467b48Spatrick       SmallVector<Value*, 8> NewOps;
1944097a140dSpatrick       bool NeedsRebuild =
194573471bf0Spatrick           (Mask.size() !=
194673471bf0Spatrick            cast<FixedVectorType>(I->getType())->getNumElements());
194709467b48Spatrick       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
194809467b48Spatrick         Value *V;
194909467b48Spatrick         // Recursively call evaluateInDifferentElementOrder on vector arguments
195009467b48Spatrick         // as well. E.g. GetElementPtr may have scalar operands even if the
195109467b48Spatrick         // return value is a vector, so we need to examine the operand type.
195209467b48Spatrick         if (I->getOperand(i)->getType()->isVectorTy())
195309467b48Spatrick           V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
195409467b48Spatrick         else
195509467b48Spatrick           V = I->getOperand(i);
195609467b48Spatrick         NewOps.push_back(V);
195709467b48Spatrick         NeedsRebuild |= (V != I->getOperand(i));
195809467b48Spatrick       }
195909467b48Spatrick       if (NeedsRebuild) {
196009467b48Spatrick         return buildNew(I, NewOps);
196109467b48Spatrick       }
196209467b48Spatrick       return I;
196309467b48Spatrick     }
196409467b48Spatrick     case Instruction::InsertElement: {
196509467b48Spatrick       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
196609467b48Spatrick 
196709467b48Spatrick       // The insertelement was inserting at Element. Figure out which element
196809467b48Spatrick       // that becomes after shuffling. The answer is guaranteed to be unique
196909467b48Spatrick       // by CanEvaluateShuffled.
197009467b48Spatrick       bool Found = false;
197109467b48Spatrick       int Index = 0;
197209467b48Spatrick       for (int e = Mask.size(); Index != e; ++Index) {
197309467b48Spatrick         if (Mask[Index] == Element) {
197409467b48Spatrick           Found = true;
197509467b48Spatrick           break;
197609467b48Spatrick         }
197709467b48Spatrick       }
197809467b48Spatrick 
197909467b48Spatrick       // If element is not in Mask, no need to handle the operand 1 (element to
198009467b48Spatrick       // be inserted). Just evaluate values in operand 0 according to Mask.
198109467b48Spatrick       if (!Found)
198209467b48Spatrick         return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
198309467b48Spatrick 
198409467b48Spatrick       Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
198509467b48Spatrick       return InsertElementInst::Create(V, I->getOperand(1),
198609467b48Spatrick                                        ConstantInt::get(I32Ty, Index), "", I);
198709467b48Spatrick     }
198809467b48Spatrick   }
198909467b48Spatrick   llvm_unreachable("failed to reorder elements of vector instruction!");
199009467b48Spatrick }
199109467b48Spatrick 
199209467b48Spatrick // Returns true if the shuffle is extracting a contiguous range of values from
199309467b48Spatrick // LHS, for example:
199409467b48Spatrick //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
199509467b48Spatrick //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
199609467b48Spatrick //   Shuffles to:  |EE|FF|GG|HH|
199709467b48Spatrick //                 +--+--+--+--+
isShuffleExtractingFromLHS(ShuffleVectorInst & SVI,ArrayRef<int> Mask)199809467b48Spatrick static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1999097a140dSpatrick                                        ArrayRef<int> Mask) {
2000097a140dSpatrick   unsigned LHSElems =
200173471bf0Spatrick       cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
200209467b48Spatrick   unsigned MaskElems = Mask.size();
200309467b48Spatrick   unsigned BegIdx = Mask.front();
200409467b48Spatrick   unsigned EndIdx = Mask.back();
200509467b48Spatrick   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
200609467b48Spatrick     return false;
200709467b48Spatrick   for (unsigned I = 0; I != MaskElems; ++I)
200809467b48Spatrick     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
200909467b48Spatrick       return false;
201009467b48Spatrick   return true;
201109467b48Spatrick }
201209467b48Spatrick 
201309467b48Spatrick /// These are the ingredients in an alternate form binary operator as described
201409467b48Spatrick /// below.
201509467b48Spatrick struct BinopElts {
201609467b48Spatrick   BinaryOperator::BinaryOps Opcode;
201709467b48Spatrick   Value *Op0;
201809467b48Spatrick   Value *Op1;
BinopEltsBinopElts201909467b48Spatrick   BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
202009467b48Spatrick             Value *V0 = nullptr, Value *V1 = nullptr) :
202109467b48Spatrick       Opcode(Opc), Op0(V0), Op1(V1) {}
operator boolBinopElts202209467b48Spatrick   operator bool() const { return Opcode != 0; }
202309467b48Spatrick };
202409467b48Spatrick 
202509467b48Spatrick /// Binops may be transformed into binops with different opcodes and operands.
202609467b48Spatrick /// Reverse the usual canonicalization to enable folds with the non-canonical
202709467b48Spatrick /// form of the binop. If a transform is possible, return the elements of the
202809467b48Spatrick /// new binop. If not, return invalid elements.
getAlternateBinop(BinaryOperator * BO,const DataLayout & DL)202909467b48Spatrick static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
203009467b48Spatrick   Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
203109467b48Spatrick   Type *Ty = BO->getType();
203209467b48Spatrick   switch (BO->getOpcode()) {
203309467b48Spatrick   case Instruction::Shl: {
203409467b48Spatrick     // shl X, C --> mul X, (1 << C)
203509467b48Spatrick     Constant *C;
203609467b48Spatrick     if (match(BO1, m_Constant(C))) {
203709467b48Spatrick       Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
203809467b48Spatrick       return {Instruction::Mul, BO0, ShlOne};
203909467b48Spatrick     }
204009467b48Spatrick     break;
204109467b48Spatrick   }
204209467b48Spatrick   case Instruction::Or: {
204309467b48Spatrick     // or X, C --> add X, C (when X and C have no common bits set)
204409467b48Spatrick     const APInt *C;
204509467b48Spatrick     if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
204609467b48Spatrick       return {Instruction::Add, BO0, BO1};
204709467b48Spatrick     break;
204809467b48Spatrick   }
2049*d415bd75Srobert   case Instruction::Sub:
2050*d415bd75Srobert     // sub 0, X --> mul X, -1
2051*d415bd75Srobert     if (match(BO0, m_ZeroInt()))
2052*d415bd75Srobert       return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
2053*d415bd75Srobert     break;
205409467b48Spatrick   default:
205509467b48Spatrick     break;
205609467b48Spatrick   }
205709467b48Spatrick   return {};
205809467b48Spatrick }
205909467b48Spatrick 
2060*d415bd75Srobert /// A select shuffle of a select shuffle with a shared operand can be reduced
2061*d415bd75Srobert /// to a single select shuffle. This is an obvious improvement in IR, and the
2062*d415bd75Srobert /// backend is expected to lower select shuffles efficiently.
foldSelectShuffleOfSelectShuffle(ShuffleVectorInst & Shuf)2063*d415bd75Srobert static Instruction *foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf) {
2064*d415bd75Srobert   assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2065*d415bd75Srobert 
2066*d415bd75Srobert   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2067*d415bd75Srobert   SmallVector<int, 16> Mask;
2068*d415bd75Srobert   Shuf.getShuffleMask(Mask);
2069*d415bd75Srobert   unsigned NumElts = Mask.size();
2070*d415bd75Srobert 
2071*d415bd75Srobert   // Canonicalize a select shuffle with common operand as Op1.
2072*d415bd75Srobert   auto *ShufOp = dyn_cast<ShuffleVectorInst>(Op0);
2073*d415bd75Srobert   if (ShufOp && ShufOp->isSelect() &&
2074*d415bd75Srobert       (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
2075*d415bd75Srobert     std::swap(Op0, Op1);
2076*d415bd75Srobert     ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
2077*d415bd75Srobert   }
2078*d415bd75Srobert 
2079*d415bd75Srobert   ShufOp = dyn_cast<ShuffleVectorInst>(Op1);
2080*d415bd75Srobert   if (!ShufOp || !ShufOp->isSelect() ||
2081*d415bd75Srobert       (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
2082*d415bd75Srobert     return nullptr;
2083*d415bd75Srobert 
2084*d415bd75Srobert   Value *X = ShufOp->getOperand(0), *Y = ShufOp->getOperand(1);
2085*d415bd75Srobert   SmallVector<int, 16> Mask1;
2086*d415bd75Srobert   ShufOp->getShuffleMask(Mask1);
2087*d415bd75Srobert   assert(Mask1.size() == NumElts && "Vector size changed with select shuffle");
2088*d415bd75Srobert 
2089*d415bd75Srobert   // Canonicalize common operand (Op0) as X (first operand of first shuffle).
2090*d415bd75Srobert   if (Y == Op0) {
2091*d415bd75Srobert     std::swap(X, Y);
2092*d415bd75Srobert     ShuffleVectorInst::commuteShuffleMask(Mask1, NumElts);
2093*d415bd75Srobert   }
2094*d415bd75Srobert 
2095*d415bd75Srobert   // If the mask chooses from X (operand 0), it stays the same.
2096*d415bd75Srobert   // If the mask chooses from the earlier shuffle, the other mask value is
2097*d415bd75Srobert   // transferred to the combined select shuffle:
2098*d415bd75Srobert   // shuf X, (shuf X, Y, M1), M --> shuf X, Y, M'
2099*d415bd75Srobert   SmallVector<int, 16> NewMask(NumElts);
2100*d415bd75Srobert   for (unsigned i = 0; i != NumElts; ++i)
2101*d415bd75Srobert     NewMask[i] = Mask[i] < (signed)NumElts ? Mask[i] : Mask1[i];
2102*d415bd75Srobert 
2103*d415bd75Srobert   // A select mask with undef elements might look like an identity mask.
2104*d415bd75Srobert   assert((ShuffleVectorInst::isSelectMask(NewMask) ||
2105*d415bd75Srobert           ShuffleVectorInst::isIdentityMask(NewMask)) &&
2106*d415bd75Srobert          "Unexpected shuffle mask");
2107*d415bd75Srobert   return new ShuffleVectorInst(X, Y, NewMask);
2108*d415bd75Srobert }
2109*d415bd75Srobert 
foldSelectShuffleWith1Binop(ShuffleVectorInst & Shuf)211009467b48Spatrick static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
211109467b48Spatrick   assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
211209467b48Spatrick 
211309467b48Spatrick   // Are we shuffling together some value and that same value after it has been
211409467b48Spatrick   // modified by a binop with a constant?
211509467b48Spatrick   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
211609467b48Spatrick   Constant *C;
211709467b48Spatrick   bool Op0IsBinop;
211809467b48Spatrick   if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
211909467b48Spatrick     Op0IsBinop = true;
212009467b48Spatrick   else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
212109467b48Spatrick     Op0IsBinop = false;
212209467b48Spatrick   else
212309467b48Spatrick     return nullptr;
212409467b48Spatrick 
212509467b48Spatrick   // The identity constant for a binop leaves a variable operand unchanged. For
212609467b48Spatrick   // a vector, this is a splat of something like 0, -1, or 1.
212709467b48Spatrick   // If there's no identity constant for this binop, we're done.
212809467b48Spatrick   auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
212909467b48Spatrick   BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
213009467b48Spatrick   Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
213109467b48Spatrick   if (!IdC)
213209467b48Spatrick     return nullptr;
213309467b48Spatrick 
213409467b48Spatrick   // Shuffle identity constants into the lanes that return the original value.
213509467b48Spatrick   // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
213609467b48Spatrick   // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
213709467b48Spatrick   // The existing binop constant vector remains in the same operand position.
2138097a140dSpatrick   ArrayRef<int> Mask = Shuf.getShuffleMask();
213909467b48Spatrick   Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
214009467b48Spatrick                                 ConstantExpr::getShuffleVector(IdC, C, Mask);
214109467b48Spatrick 
214209467b48Spatrick   bool MightCreatePoisonOrUB =
2143097a140dSpatrick       is_contained(Mask, UndefMaskElem) &&
214409467b48Spatrick       (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
214509467b48Spatrick   if (MightCreatePoisonOrUB)
214673471bf0Spatrick     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
214709467b48Spatrick 
214809467b48Spatrick   // shuf (bop X, C), X, M --> bop X, C'
214909467b48Spatrick   // shuf X, (bop X, C), M --> bop X, C'
215009467b48Spatrick   Value *X = Op0IsBinop ? Op1 : Op0;
215109467b48Spatrick   Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
215209467b48Spatrick   NewBO->copyIRFlags(BO);
215309467b48Spatrick 
215409467b48Spatrick   // An undef shuffle mask element may propagate as an undef constant element in
215509467b48Spatrick   // the new binop. That would produce poison where the original code might not.
215609467b48Spatrick   // If we already made a safe constant, then there's no danger.
2157097a140dSpatrick   if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
215809467b48Spatrick     NewBO->dropPoisonGeneratingFlags();
215909467b48Spatrick   return NewBO;
216009467b48Spatrick }
216109467b48Spatrick 
216209467b48Spatrick /// If we have an insert of a scalar to a non-zero element of an undefined
216309467b48Spatrick /// vector and then shuffle that value, that's the same as inserting to the zero
216409467b48Spatrick /// element and shuffling. Splatting from the zero element is recognized as the
216509467b48Spatrick /// canonical form of splat.
canonicalizeInsertSplat(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)216609467b48Spatrick static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
216709467b48Spatrick                                             InstCombiner::BuilderTy &Builder) {
216809467b48Spatrick   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2169097a140dSpatrick   ArrayRef<int> Mask = Shuf.getShuffleMask();
217009467b48Spatrick   Value *X;
217109467b48Spatrick   uint64_t IndexC;
217209467b48Spatrick 
217309467b48Spatrick   // Match a shuffle that is a splat to a non-zero element.
2174097a140dSpatrick   if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
217509467b48Spatrick                                        m_ConstantInt(IndexC)))) ||
2176097a140dSpatrick       !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
217709467b48Spatrick     return nullptr;
217809467b48Spatrick 
217909467b48Spatrick   // Insert into element 0 of an undef vector.
218009467b48Spatrick   UndefValue *UndefVec = UndefValue::get(Shuf.getType());
218109467b48Spatrick   Constant *Zero = Builder.getInt32(0);
218209467b48Spatrick   Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
218309467b48Spatrick 
218409467b48Spatrick   // Splat from element 0. Any mask element that is undefined remains undefined.
218509467b48Spatrick   // For example:
2186*d415bd75Srobert   // shuf (inselt undef, X, 2), _, <2,2,undef>
2187*d415bd75Srobert   //   --> shuf (inselt undef, X, 0), poison, <0,0,undef>
218873471bf0Spatrick   unsigned NumMaskElts =
218973471bf0Spatrick       cast<FixedVectorType>(Shuf.getType())->getNumElements();
2190097a140dSpatrick   SmallVector<int, 16> NewMask(NumMaskElts, 0);
219109467b48Spatrick   for (unsigned i = 0; i != NumMaskElts; ++i)
2192097a140dSpatrick     if (Mask[i] == UndefMaskElem)
2193097a140dSpatrick       NewMask[i] = Mask[i];
219409467b48Spatrick 
2195*d415bd75Srobert   return new ShuffleVectorInst(NewIns, NewMask);
219609467b48Spatrick }
219709467b48Spatrick 
219809467b48Spatrick /// Try to fold shuffles that are the equivalent of a vector select.
foldSelectShuffle(ShuffleVectorInst & Shuf)2199*d415bd75Srobert Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
220009467b48Spatrick   if (!Shuf.isSelect())
220109467b48Spatrick     return nullptr;
220209467b48Spatrick 
220309467b48Spatrick   // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
220409467b48Spatrick   // Commuting undef to operand 0 conflicts with another canonicalization.
220573471bf0Spatrick   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
220673471bf0Spatrick   if (!match(Shuf.getOperand(1), m_Undef()) &&
220709467b48Spatrick       Shuf.getMaskValue(0) >= (int)NumElts) {
220809467b48Spatrick     // TODO: Can we assert that both operands of a shuffle-select are not undef
220909467b48Spatrick     // (otherwise, it would have been folded by instsimplify?
221009467b48Spatrick     Shuf.commute();
221109467b48Spatrick     return &Shuf;
221209467b48Spatrick   }
221309467b48Spatrick 
2214*d415bd75Srobert   if (Instruction *I = foldSelectShuffleOfSelectShuffle(Shuf))
2215*d415bd75Srobert     return I;
2216*d415bd75Srobert 
221709467b48Spatrick   if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
221809467b48Spatrick     return I;
221909467b48Spatrick 
222009467b48Spatrick   BinaryOperator *B0, *B1;
222109467b48Spatrick   if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
222209467b48Spatrick       !match(Shuf.getOperand(1), m_BinOp(B1)))
222309467b48Spatrick     return nullptr;
222409467b48Spatrick 
2225*d415bd75Srobert   // If one operand is "0 - X", allow that to be viewed as "X * -1"
2226*d415bd75Srobert   // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
2227*d415bd75Srobert   // with a multiply, we will exit because C0/C1 will not be set.
222809467b48Spatrick   Value *X, *Y;
2229*d415bd75Srobert   Constant *C0 = nullptr, *C1 = nullptr;
223009467b48Spatrick   bool ConstantsAreOp1;
2231*d415bd75Srobert   if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
223209467b48Spatrick       match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
223309467b48Spatrick     ConstantsAreOp1 = false;
2234*d415bd75Srobert   else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
2235*d415bd75Srobert                                  m_Neg(m_Value(X)))) &&
2236*d415bd75Srobert            match(B1, m_CombineOr(m_BinOp(m_Value(Y), m_Constant(C1)),
2237*d415bd75Srobert                                  m_Neg(m_Value(Y)))))
2238*d415bd75Srobert     ConstantsAreOp1 = true;
223909467b48Spatrick   else
224009467b48Spatrick     return nullptr;
224109467b48Spatrick 
224209467b48Spatrick   // We need matching binops to fold the lanes together.
224309467b48Spatrick   BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
224409467b48Spatrick   BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
224509467b48Spatrick   bool DropNSW = false;
224609467b48Spatrick   if (ConstantsAreOp1 && Opc0 != Opc1) {
224709467b48Spatrick     // TODO: We drop "nsw" if shift is converted into multiply because it may
224809467b48Spatrick     // not be correct when the shift amount is BitWidth - 1. We could examine
224909467b48Spatrick     // each vector element to determine if it is safe to keep that flag.
225009467b48Spatrick     if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
225109467b48Spatrick       DropNSW = true;
225209467b48Spatrick     if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
225309467b48Spatrick       assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
225409467b48Spatrick       Opc0 = AltB0.Opcode;
225509467b48Spatrick       C0 = cast<Constant>(AltB0.Op1);
225609467b48Spatrick     } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
225709467b48Spatrick       assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
225809467b48Spatrick       Opc1 = AltB1.Opcode;
225909467b48Spatrick       C1 = cast<Constant>(AltB1.Op1);
226009467b48Spatrick     }
226109467b48Spatrick   }
226209467b48Spatrick 
2263*d415bd75Srobert   if (Opc0 != Opc1 || !C0 || !C1)
226409467b48Spatrick     return nullptr;
226509467b48Spatrick 
226609467b48Spatrick   // The opcodes must be the same. Use a new name to make that clear.
226709467b48Spatrick   BinaryOperator::BinaryOps BOpc = Opc0;
226809467b48Spatrick 
226909467b48Spatrick   // Select the constant elements needed for the single binop.
2270097a140dSpatrick   ArrayRef<int> Mask = Shuf.getShuffleMask();
227109467b48Spatrick   Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
227209467b48Spatrick 
227309467b48Spatrick   // We are moving a binop after a shuffle. When a shuffle has an undefined
227409467b48Spatrick   // mask element, the result is undefined, but it is not poison or undefined
227509467b48Spatrick   // behavior. That is not necessarily true for div/rem/shift.
227609467b48Spatrick   bool MightCreatePoisonOrUB =
2277097a140dSpatrick       is_contained(Mask, UndefMaskElem) &&
227809467b48Spatrick       (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
227909467b48Spatrick   if (MightCreatePoisonOrUB)
228073471bf0Spatrick     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
228173471bf0Spatrick                                                        ConstantsAreOp1);
228209467b48Spatrick 
228309467b48Spatrick   Value *V;
228409467b48Spatrick   if (X == Y) {
228509467b48Spatrick     // Remove a binop and the shuffle by rearranging the constant:
228609467b48Spatrick     // shuffle (op V, C0), (op V, C1), M --> op V, C'
228709467b48Spatrick     // shuffle (op C0, V), (op C1, V), M --> op C', V
228809467b48Spatrick     V = X;
228909467b48Spatrick   } else {
229009467b48Spatrick     // If there are 2 different variable operands, we must create a new shuffle
229109467b48Spatrick     // (select) first, so check uses to ensure that we don't end up with more
229209467b48Spatrick     // instructions than we started with.
229309467b48Spatrick     if (!B0->hasOneUse() && !B1->hasOneUse())
229409467b48Spatrick       return nullptr;
229509467b48Spatrick 
229609467b48Spatrick     // If we use the original shuffle mask and op1 is *variable*, we would be
229709467b48Spatrick     // putting an undef into operand 1 of div/rem/shift. This is either UB or
229809467b48Spatrick     // poison. We do not have to guard against UB when *constants* are op1
229909467b48Spatrick     // because safe constants guarantee that we do not overflow sdiv/srem (and
230009467b48Spatrick     // there's no danger for other opcodes).
230109467b48Spatrick     // TODO: To allow this case, create a new shuffle mask with no undefs.
230209467b48Spatrick     if (MightCreatePoisonOrUB && !ConstantsAreOp1)
230309467b48Spatrick       return nullptr;
230409467b48Spatrick 
230509467b48Spatrick     // Note: In general, we do not create new shuffles in InstCombine because we
230609467b48Spatrick     // do not know if a target can lower an arbitrary shuffle optimally. In this
230709467b48Spatrick     // case, the shuffle uses the existing mask, so there is no additional risk.
230809467b48Spatrick 
230909467b48Spatrick     // Select the variable vectors first, then perform the binop:
231009467b48Spatrick     // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
231109467b48Spatrick     // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
231209467b48Spatrick     V = Builder.CreateShuffleVector(X, Y, Mask);
231309467b48Spatrick   }
231409467b48Spatrick 
2315*d415bd75Srobert   Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2316*d415bd75Srobert                                    Builder.CreateBinOp(BOpc, NewC, V);
231709467b48Spatrick 
231809467b48Spatrick   // Flags are intersected from the 2 source binops. But there are 2 exceptions:
231909467b48Spatrick   // 1. If we changed an opcode, poison conditions might have changed.
232009467b48Spatrick   // 2. If the shuffle had undef mask elements, the new binop might have undefs
232109467b48Spatrick   //    where the original code did not. But if we already made a safe constant,
232209467b48Spatrick   //    then there's no danger.
2323*d415bd75Srobert   if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2324*d415bd75Srobert     NewI->copyIRFlags(B0);
2325*d415bd75Srobert     NewI->andIRFlags(B1);
232609467b48Spatrick     if (DropNSW)
2327*d415bd75Srobert       NewI->setHasNoSignedWrap(false);
2328097a140dSpatrick     if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2329*d415bd75Srobert       NewI->dropPoisonGeneratingFlags();
2330*d415bd75Srobert   }
2331*d415bd75Srobert   return replaceInstUsesWith(Shuf, NewBO);
233209467b48Spatrick }
233309467b48Spatrick 
2334097a140dSpatrick /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2335097a140dSpatrick /// Example (little endian):
2336097a140dSpatrick /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
foldTruncShuffle(ShuffleVectorInst & Shuf,bool IsBigEndian)2337097a140dSpatrick static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
2338097a140dSpatrick                                      bool IsBigEndian) {
2339097a140dSpatrick   // This must be a bitcasted shuffle of 1 vector integer operand.
2340097a140dSpatrick   Type *DestType = Shuf.getType();
2341097a140dSpatrick   Value *X;
2342097a140dSpatrick   if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2343097a140dSpatrick       !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
2344097a140dSpatrick     return nullptr;
2345097a140dSpatrick 
2346097a140dSpatrick   // The source type must have the same number of elements as the shuffle,
2347097a140dSpatrick   // and the source element type must be larger than the shuffle element type.
2348097a140dSpatrick   Type *SrcType = X->getType();
2349097a140dSpatrick   if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
235073471bf0Spatrick       cast<FixedVectorType>(SrcType)->getNumElements() !=
235173471bf0Spatrick           cast<FixedVectorType>(DestType)->getNumElements() ||
2352097a140dSpatrick       SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2353097a140dSpatrick     return nullptr;
2354097a140dSpatrick 
2355097a140dSpatrick   assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2356097a140dSpatrick          "Expected a shuffle that decreases length");
2357097a140dSpatrick 
2358097a140dSpatrick   // Last, check that the mask chooses the correct low bits for each narrow
2359097a140dSpatrick   // element in the result.
2360097a140dSpatrick   uint64_t TruncRatio =
2361097a140dSpatrick       SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2362097a140dSpatrick   ArrayRef<int> Mask = Shuf.getShuffleMask();
2363097a140dSpatrick   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2364097a140dSpatrick     if (Mask[i] == UndefMaskElem)
2365097a140dSpatrick       continue;
2366097a140dSpatrick     uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
236773471bf0Spatrick     assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2368097a140dSpatrick     if (Mask[i] != (int)LSBIndex)
2369097a140dSpatrick       return nullptr;
2370097a140dSpatrick   }
2371097a140dSpatrick 
2372097a140dSpatrick   return new TruncInst(X, DestType);
2373097a140dSpatrick }
2374097a140dSpatrick 
237509467b48Spatrick /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
237609467b48Spatrick /// narrowing (concatenating with undef and extracting back to the original
237709467b48Spatrick /// length). This allows replacing the wide select with a narrow select.
narrowVectorSelect(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)237809467b48Spatrick static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
237909467b48Spatrick                                        InstCombiner::BuilderTy &Builder) {
238009467b48Spatrick   // This must be a narrowing identity shuffle. It extracts the 1st N elements
238109467b48Spatrick   // of the 1st vector operand of a shuffle.
238209467b48Spatrick   if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
238309467b48Spatrick     return nullptr;
238409467b48Spatrick 
238509467b48Spatrick   // The vector being shuffled must be a vector select that we can eliminate.
238609467b48Spatrick   // TODO: The one-use requirement could be eased if X and/or Y are constants.
238709467b48Spatrick   Value *Cond, *X, *Y;
238809467b48Spatrick   if (!match(Shuf.getOperand(0),
238909467b48Spatrick              m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
239009467b48Spatrick     return nullptr;
239109467b48Spatrick 
239209467b48Spatrick   // We need a narrow condition value. It must be extended with undef elements
239309467b48Spatrick   // and have the same number of elements as this shuffle.
239473471bf0Spatrick   unsigned NarrowNumElts =
239573471bf0Spatrick       cast<FixedVectorType>(Shuf.getType())->getNumElements();
239609467b48Spatrick   Value *NarrowCond;
2397097a140dSpatrick   if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
239873471bf0Spatrick       cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2399097a140dSpatrick           NarrowNumElts ||
240009467b48Spatrick       !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
240109467b48Spatrick     return nullptr;
240209467b48Spatrick 
240309467b48Spatrick   // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
240409467b48Spatrick   // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
240573471bf0Spatrick   Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
240673471bf0Spatrick   Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
240709467b48Spatrick   return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
240809467b48Spatrick }
240909467b48Spatrick 
2410*d415bd75Srobert /// Canonicalize FP negate after shuffle.
foldFNegShuffle(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2411*d415bd75Srobert static Instruction *foldFNegShuffle(ShuffleVectorInst &Shuf,
2412*d415bd75Srobert                                     InstCombiner::BuilderTy &Builder) {
2413*d415bd75Srobert   Instruction *FNeg0;
2414*d415bd75Srobert   Value *X;
2415*d415bd75Srobert   if (!match(Shuf.getOperand(0), m_CombineAnd(m_Instruction(FNeg0),
2416*d415bd75Srobert                                               m_FNeg(m_Value(X)))))
2417*d415bd75Srobert     return nullptr;
2418*d415bd75Srobert 
2419*d415bd75Srobert   // shuffle (fneg X), Mask --> fneg (shuffle X, Mask)
2420*d415bd75Srobert   if (FNeg0->hasOneUse() && match(Shuf.getOperand(1), m_Undef())) {
2421*d415bd75Srobert     Value *NewShuf = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2422*d415bd75Srobert     return UnaryOperator::CreateFNegFMF(NewShuf, FNeg0);
2423*d415bd75Srobert   }
2424*d415bd75Srobert 
2425*d415bd75Srobert   Instruction *FNeg1;
2426*d415bd75Srobert   Value *Y;
2427*d415bd75Srobert   if (!match(Shuf.getOperand(1), m_CombineAnd(m_Instruction(FNeg1),
2428*d415bd75Srobert                                               m_FNeg(m_Value(Y)))))
2429*d415bd75Srobert     return nullptr;
2430*d415bd75Srobert 
2431*d415bd75Srobert   // shuffle (fneg X), (fneg Y), Mask --> fneg (shuffle X, Y, Mask)
2432*d415bd75Srobert   if (FNeg0->hasOneUse() || FNeg1->hasOneUse()) {
2433*d415bd75Srobert     Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2434*d415bd75Srobert     Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewShuf);
2435*d415bd75Srobert     NewFNeg->copyIRFlags(FNeg0);
2436*d415bd75Srobert     NewFNeg->andIRFlags(FNeg1);
2437*d415bd75Srobert     return NewFNeg;
2438*d415bd75Srobert   }
2439*d415bd75Srobert 
2440*d415bd75Srobert   return nullptr;
2441*d415bd75Srobert }
2442*d415bd75Srobert 
2443*d415bd75Srobert /// Canonicalize casts after shuffle.
foldCastShuffle(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2444*d415bd75Srobert static Instruction *foldCastShuffle(ShuffleVectorInst &Shuf,
2445*d415bd75Srobert                                     InstCombiner::BuilderTy &Builder) {
2446*d415bd75Srobert   // Do we have 2 matching cast operands?
2447*d415bd75Srobert   auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
2448*d415bd75Srobert   auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
2449*d415bd75Srobert   if (!Cast0 || !Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2450*d415bd75Srobert       Cast0->getSrcTy() != Cast1->getSrcTy())
2451*d415bd75Srobert     return nullptr;
2452*d415bd75Srobert 
2453*d415bd75Srobert   // TODO: Allow other opcodes? That would require easing the type restrictions
2454*d415bd75Srobert   //       below here.
2455*d415bd75Srobert   CastInst::CastOps CastOpcode = Cast0->getOpcode();
2456*d415bd75Srobert   switch (CastOpcode) {
2457*d415bd75Srobert   case Instruction::FPToSI:
2458*d415bd75Srobert   case Instruction::FPToUI:
2459*d415bd75Srobert   case Instruction::SIToFP:
2460*d415bd75Srobert   case Instruction::UIToFP:
2461*d415bd75Srobert     break;
2462*d415bd75Srobert   default:
2463*d415bd75Srobert     return nullptr;
2464*d415bd75Srobert   }
2465*d415bd75Srobert 
2466*d415bd75Srobert   VectorType *ShufTy = Shuf.getType();
2467*d415bd75Srobert   VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
2468*d415bd75Srobert   VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
2469*d415bd75Srobert 
2470*d415bd75Srobert   // TODO: Allow length-increasing shuffles?
2471*d415bd75Srobert   if (ShufTy->getElementCount().getKnownMinValue() >
2472*d415bd75Srobert       ShufOpTy->getElementCount().getKnownMinValue())
2473*d415bd75Srobert     return nullptr;
2474*d415bd75Srobert 
2475*d415bd75Srobert   // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
2476*d415bd75Srobert   assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
2477*d415bd75Srobert          "Expected fixed vector operands for casts and binary shuffle");
2478*d415bd75Srobert   if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2479*d415bd75Srobert     return nullptr;
2480*d415bd75Srobert 
2481*d415bd75Srobert   // At least one of the operands must have only one use (the shuffle).
2482*d415bd75Srobert   if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2483*d415bd75Srobert     return nullptr;
2484*d415bd75Srobert 
2485*d415bd75Srobert   // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
2486*d415bd75Srobert   Value *X = Cast0->getOperand(0);
2487*d415bd75Srobert   Value *Y = Cast1->getOperand(0);
2488*d415bd75Srobert   Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2489*d415bd75Srobert   return CastInst::Create(CastOpcode, NewShuf, ShufTy);
2490*d415bd75Srobert }
2491*d415bd75Srobert 
249273471bf0Spatrick /// Try to fold an extract subvector operation.
foldIdentityExtractShuffle(ShuffleVectorInst & Shuf)249309467b48Spatrick static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
249409467b48Spatrick   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
249573471bf0Spatrick   if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
249609467b48Spatrick     return nullptr;
249709467b48Spatrick 
249873471bf0Spatrick   // Check if we are extracting all bits of an inserted scalar:
249973471bf0Spatrick   // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
250073471bf0Spatrick   Value *X;
250173471bf0Spatrick   if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
250273471bf0Spatrick       X->getType()->getPrimitiveSizeInBits() ==
250373471bf0Spatrick           Shuf.getType()->getPrimitiveSizeInBits())
250473471bf0Spatrick     return new BitCastInst(X, Shuf.getType());
250573471bf0Spatrick 
250673471bf0Spatrick   // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
250773471bf0Spatrick   Value *Y;
2508097a140dSpatrick   ArrayRef<int> Mask;
2509097a140dSpatrick   if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
251009467b48Spatrick     return nullptr;
251109467b48Spatrick 
251209467b48Spatrick   // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
251309467b48Spatrick   // then combining may result in worse codegen.
251409467b48Spatrick   if (!Op0->hasOneUse())
251509467b48Spatrick     return nullptr;
251609467b48Spatrick 
251709467b48Spatrick   // We are extracting a subvector from a shuffle. Remove excess elements from
251809467b48Spatrick   // the 1st shuffle mask to eliminate the extract.
251909467b48Spatrick   //
252009467b48Spatrick   // This transform is conservatively limited to identity extracts because we do
252109467b48Spatrick   // not allow arbitrary shuffle mask creation as a target-independent transform
252209467b48Spatrick   // (because we can't guarantee that will lower efficiently).
252309467b48Spatrick   //
252409467b48Spatrick   // If the extracting shuffle has an undef mask element, it transfers to the
252509467b48Spatrick   // new shuffle mask. Otherwise, copy the original mask element. Example:
252609467b48Spatrick   //   shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
252709467b48Spatrick   //   shuf X, Y, <C0, undef, C2, undef>
252873471bf0Spatrick   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2529097a140dSpatrick   SmallVector<int, 16> NewMask(NumElts);
2530097a140dSpatrick   assert(NumElts < Mask.size() &&
253109467b48Spatrick          "Identity with extract must have less elements than its inputs");
253209467b48Spatrick 
253309467b48Spatrick   for (unsigned i = 0; i != NumElts; ++i) {
2534097a140dSpatrick     int ExtractMaskElt = Shuf.getMaskValue(i);
2535097a140dSpatrick     int MaskElt = Mask[i];
2536097a140dSpatrick     NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
253709467b48Spatrick   }
2538097a140dSpatrick   return new ShuffleVectorInst(X, Y, NewMask);
253909467b48Spatrick }
254009467b48Spatrick 
254109467b48Spatrick /// Try to replace a shuffle with an insertelement or try to replace a shuffle
254209467b48Spatrick /// operand with the operand of an insertelement.
foldShuffleWithInsert(ShuffleVectorInst & Shuf,InstCombinerImpl & IC)2543097a140dSpatrick static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
254473471bf0Spatrick                                           InstCombinerImpl &IC) {
254509467b48Spatrick   Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2546097a140dSpatrick   SmallVector<int, 16> Mask;
2547097a140dSpatrick   Shuf.getShuffleMask(Mask);
254809467b48Spatrick 
254909467b48Spatrick   int NumElts = Mask.size();
2550*d415bd75Srobert   int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
255109467b48Spatrick 
255209467b48Spatrick   // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
255309467b48Spatrick   // not be able to handle it there if the insertelement has >1 use.
255409467b48Spatrick   // If the shuffle has an insertelement operand but does not choose the
255509467b48Spatrick   // inserted scalar element from that value, then we can replace that shuffle
255609467b48Spatrick   // operand with the source vector of the insertelement.
255709467b48Spatrick   Value *X;
255809467b48Spatrick   uint64_t IdxC;
2559097a140dSpatrick   if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
256009467b48Spatrick     // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
256173471bf0Spatrick     if (!is_contained(Mask, (int)IdxC))
2562097a140dSpatrick       return IC.replaceOperand(Shuf, 0, X);
256309467b48Spatrick   }
2564097a140dSpatrick   if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
256509467b48Spatrick     // Offset the index constant by the vector width because we are checking for
256609467b48Spatrick     // accesses to the 2nd vector input of the shuffle.
2567*d415bd75Srobert     IdxC += InpNumElts;
256809467b48Spatrick     // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
256973471bf0Spatrick     if (!is_contained(Mask, (int)IdxC))
2570097a140dSpatrick       return IC.replaceOperand(Shuf, 1, X);
257109467b48Spatrick   }
2572*d415bd75Srobert   // For the rest of the transform, the shuffle must not change vector sizes.
2573*d415bd75Srobert   // TODO: This restriction could be removed if the insert has only one use
2574*d415bd75Srobert   //       (because the transform would require a new length-changing shuffle).
2575*d415bd75Srobert   if (NumElts != InpNumElts)
2576*d415bd75Srobert     return nullptr;
257709467b48Spatrick 
257809467b48Spatrick   // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
257909467b48Spatrick   auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
258009467b48Spatrick     // We need an insertelement with a constant index.
2581097a140dSpatrick     if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
258209467b48Spatrick                                m_ConstantInt(IndexC))))
258309467b48Spatrick       return false;
258409467b48Spatrick 
258509467b48Spatrick     // Test the shuffle mask to see if it splices the inserted scalar into the
258609467b48Spatrick     // operand 1 vector of the shuffle.
258709467b48Spatrick     int NewInsIndex = -1;
258809467b48Spatrick     for (int i = 0; i != NumElts; ++i) {
258909467b48Spatrick       // Ignore undef mask elements.
259009467b48Spatrick       if (Mask[i] == -1)
259109467b48Spatrick         continue;
259209467b48Spatrick 
259309467b48Spatrick       // The shuffle takes elements of operand 1 without lane changes.
259409467b48Spatrick       if (Mask[i] == NumElts + i)
259509467b48Spatrick         continue;
259609467b48Spatrick 
259709467b48Spatrick       // The shuffle must choose the inserted scalar exactly once.
259809467b48Spatrick       if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
259909467b48Spatrick         return false;
260009467b48Spatrick 
260109467b48Spatrick       // The shuffle is placing the inserted scalar into element i.
260209467b48Spatrick       NewInsIndex = i;
260309467b48Spatrick     }
260409467b48Spatrick 
260509467b48Spatrick     assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
260609467b48Spatrick 
260709467b48Spatrick     // Index is updated to the potentially translated insertion lane.
260809467b48Spatrick     IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
260909467b48Spatrick     return true;
261009467b48Spatrick   };
261109467b48Spatrick 
261209467b48Spatrick   // If the shuffle is unnecessary, insert the scalar operand directly into
261309467b48Spatrick   // operand 1 of the shuffle. Example:
261409467b48Spatrick   // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
261509467b48Spatrick   Value *Scalar;
261609467b48Spatrick   ConstantInt *IndexC;
261709467b48Spatrick   if (isShufflingScalarIntoOp1(Scalar, IndexC))
261809467b48Spatrick     return InsertElementInst::Create(V1, Scalar, IndexC);
261909467b48Spatrick 
262009467b48Spatrick   // Try again after commuting shuffle. Example:
262109467b48Spatrick   // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
262209467b48Spatrick   // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
262309467b48Spatrick   std::swap(V0, V1);
262409467b48Spatrick   ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
262509467b48Spatrick   if (isShufflingScalarIntoOp1(Scalar, IndexC))
262609467b48Spatrick     return InsertElementInst::Create(V1, Scalar, IndexC);
262709467b48Spatrick 
262809467b48Spatrick   return nullptr;
262909467b48Spatrick }
263009467b48Spatrick 
foldIdentityPaddedShuffles(ShuffleVectorInst & Shuf)263109467b48Spatrick static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
263209467b48Spatrick   // Match the operands as identity with padding (also known as concatenation
263309467b48Spatrick   // with undef) shuffles of the same source type. The backend is expected to
263409467b48Spatrick   // recreate these concatenations from a shuffle of narrow operands.
263509467b48Spatrick   auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
263609467b48Spatrick   auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
263709467b48Spatrick   if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
263809467b48Spatrick       !Shuffle1 || !Shuffle1->isIdentityWithPadding())
263909467b48Spatrick     return nullptr;
264009467b48Spatrick 
264109467b48Spatrick   // We limit this transform to power-of-2 types because we expect that the
264209467b48Spatrick   // backend can convert the simplified IR patterns to identical nodes as the
264309467b48Spatrick   // original IR.
264409467b48Spatrick   // TODO: If we can verify the same behavior for arbitrary types, the
264509467b48Spatrick   //       power-of-2 checks can be removed.
264609467b48Spatrick   Value *X = Shuffle0->getOperand(0);
264709467b48Spatrick   Value *Y = Shuffle1->getOperand(0);
264809467b48Spatrick   if (X->getType() != Y->getType() ||
264973471bf0Spatrick       !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
265073471bf0Spatrick       !isPowerOf2_32(
265173471bf0Spatrick           cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
265273471bf0Spatrick       !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
265373471bf0Spatrick       match(X, m_Undef()) || match(Y, m_Undef()))
265409467b48Spatrick     return nullptr;
265573471bf0Spatrick   assert(match(Shuffle0->getOperand(1), m_Undef()) &&
265673471bf0Spatrick          match(Shuffle1->getOperand(1), m_Undef()) &&
265709467b48Spatrick          "Unexpected operand for identity shuffle");
265809467b48Spatrick 
265909467b48Spatrick   // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
266009467b48Spatrick   // operands directly by adjusting the shuffle mask to account for the narrower
266109467b48Spatrick   // types:
266209467b48Spatrick   // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
266373471bf0Spatrick   int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
266473471bf0Spatrick   int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
266509467b48Spatrick   assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
266609467b48Spatrick 
2667097a140dSpatrick   ArrayRef<int> Mask = Shuf.getShuffleMask();
2668097a140dSpatrick   SmallVector<int, 16> NewMask(Mask.size(), -1);
266909467b48Spatrick   for (int i = 0, e = Mask.size(); i != e; ++i) {
267009467b48Spatrick     if (Mask[i] == -1)
267109467b48Spatrick       continue;
267209467b48Spatrick 
267309467b48Spatrick     // If this shuffle is choosing an undef element from 1 of the sources, that
267409467b48Spatrick     // element is undef.
267509467b48Spatrick     if (Mask[i] < WideElts) {
267609467b48Spatrick       if (Shuffle0->getMaskValue(Mask[i]) == -1)
267709467b48Spatrick         continue;
267809467b48Spatrick     } else {
267909467b48Spatrick       if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
268009467b48Spatrick         continue;
268109467b48Spatrick     }
268209467b48Spatrick 
268309467b48Spatrick     // If this shuffle is choosing from the 1st narrow op, the mask element is
268409467b48Spatrick     // the same. If this shuffle is choosing from the 2nd narrow op, the mask
268509467b48Spatrick     // element is offset down to adjust for the narrow vector widths.
268609467b48Spatrick     if (Mask[i] < WideElts) {
268709467b48Spatrick       assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2688097a140dSpatrick       NewMask[i] = Mask[i];
268909467b48Spatrick     } else {
269009467b48Spatrick       assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2691097a140dSpatrick       NewMask[i] = Mask[i] - (WideElts - NarrowElts);
269209467b48Spatrick     }
269309467b48Spatrick   }
2694097a140dSpatrick   return new ShuffleVectorInst(X, Y, NewMask);
269509467b48Spatrick }
269609467b48Spatrick 
2697*d415bd75Srobert // Splatting the first element of the result of a BinOp, where any of the
2698*d415bd75Srobert // BinOp's operands are the result of a first element splat can be simplified to
2699*d415bd75Srobert // splatting the first element of the result of the BinOp
simplifyBinOpSplats(ShuffleVectorInst & SVI)2700*d415bd75Srobert Instruction *InstCombinerImpl::simplifyBinOpSplats(ShuffleVectorInst &SVI) {
2701*d415bd75Srobert   if (!match(SVI.getOperand(1), m_Undef()) ||
2702*d415bd75Srobert       !match(SVI.getShuffleMask(), m_ZeroMask()))
2703*d415bd75Srobert     return nullptr;
2704*d415bd75Srobert 
2705*d415bd75Srobert   Value *Op0 = SVI.getOperand(0);
2706*d415bd75Srobert   Value *X, *Y;
2707*d415bd75Srobert   if (!match(Op0, m_BinOp(m_Shuffle(m_Value(X), m_Undef(), m_ZeroMask()),
2708*d415bd75Srobert                           m_Value(Y))) &&
2709*d415bd75Srobert       !match(Op0, m_BinOp(m_Value(X),
2710*d415bd75Srobert                           m_Shuffle(m_Value(Y), m_Undef(), m_ZeroMask()))))
2711*d415bd75Srobert     return nullptr;
2712*d415bd75Srobert   if (X->getType() != Y->getType())
2713*d415bd75Srobert     return nullptr;
2714*d415bd75Srobert 
2715*d415bd75Srobert   auto *BinOp = cast<BinaryOperator>(Op0);
2716*d415bd75Srobert   if (!isSafeToSpeculativelyExecute(BinOp))
2717*d415bd75Srobert     return nullptr;
2718*d415bd75Srobert 
2719*d415bd75Srobert   Value *NewBO = Builder.CreateBinOp(BinOp->getOpcode(), X, Y);
2720*d415bd75Srobert   if (auto NewBOI = dyn_cast<Instruction>(NewBO))
2721*d415bd75Srobert     NewBOI->copyIRFlags(BinOp);
2722*d415bd75Srobert 
2723*d415bd75Srobert   return new ShuffleVectorInst(NewBO, SVI.getShuffleMask());
2724*d415bd75Srobert }
2725*d415bd75Srobert 
visitShuffleVectorInst(ShuffleVectorInst & SVI)272673471bf0Spatrick Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
272709467b48Spatrick   Value *LHS = SVI.getOperand(0);
272809467b48Spatrick   Value *RHS = SVI.getOperand(1);
2729097a140dSpatrick   SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
2730*d415bd75Srobert   if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
2731097a140dSpatrick                                           SVI.getType(), ShufQuery))
273209467b48Spatrick     return replaceInstUsesWith(SVI, V);
273309467b48Spatrick 
2734*d415bd75Srobert   if (Instruction *I = simplifyBinOpSplats(SVI))
2735*d415bd75Srobert     return I;
2736*d415bd75Srobert 
273773471bf0Spatrick   if (isa<ScalableVectorType>(LHS->getType()))
273873471bf0Spatrick     return nullptr;
273973471bf0Spatrick 
274073471bf0Spatrick   unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
274173471bf0Spatrick   unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
274273471bf0Spatrick 
274373471bf0Spatrick   // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
274473471bf0Spatrick   //
274573471bf0Spatrick   // if X and Y are of the same (vector) type, and the element size is not
274673471bf0Spatrick   // changed by the bitcasts, we can distribute the bitcasts through the
274773471bf0Spatrick   // shuffle, hopefully reducing the number of instructions. We make sure that
274873471bf0Spatrick   // at least one bitcast only has one use, so we don't *increase* the number of
274973471bf0Spatrick   // instructions here.
275073471bf0Spatrick   Value *X, *Y;
275173471bf0Spatrick   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
275273471bf0Spatrick       X->getType()->isVectorTy() && X->getType() == Y->getType() &&
275373471bf0Spatrick       X->getType()->getScalarSizeInBits() ==
275473471bf0Spatrick           SVI.getType()->getScalarSizeInBits() &&
275573471bf0Spatrick       (LHS->hasOneUse() || RHS->hasOneUse())) {
275673471bf0Spatrick     Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
275773471bf0Spatrick                                            SVI.getName() + ".uncasted");
275873471bf0Spatrick     return new BitCastInst(V, SVI.getType());
275973471bf0Spatrick   }
276073471bf0Spatrick 
2761097a140dSpatrick   ArrayRef<int> Mask = SVI.getShuffleMask();
276209467b48Spatrick   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
2763097a140dSpatrick 
2764097a140dSpatrick   // Peek through a bitcasted shuffle operand by scaling the mask. If the
2765097a140dSpatrick   // simulated shuffle can simplify, then this shuffle is unnecessary:
2766097a140dSpatrick   // shuf (bitcast X), undef, Mask --> bitcast X'
2767097a140dSpatrick   // TODO: This could be extended to allow length-changing shuffles.
2768097a140dSpatrick   //       The transform might also be obsoleted if we allowed canonicalization
2769097a140dSpatrick   //       of bitcasted shuffles.
2770097a140dSpatrick   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
2771097a140dSpatrick       X->getType()->isVectorTy() && VWidth == LHSWidth) {
2772097a140dSpatrick     // Try to create a scaled mask constant.
277373471bf0Spatrick     auto *XType = cast<FixedVectorType>(X->getType());
2774097a140dSpatrick     unsigned XNumElts = XType->getNumElements();
2775097a140dSpatrick     SmallVector<int, 16> ScaledMask;
2776097a140dSpatrick     if (XNumElts >= VWidth) {
2777097a140dSpatrick       assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
2778097a140dSpatrick       narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
2779097a140dSpatrick     } else {
2780097a140dSpatrick       assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
2781097a140dSpatrick       if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
2782097a140dSpatrick         ScaledMask.clear();
2783097a140dSpatrick     }
2784097a140dSpatrick     if (!ScaledMask.empty()) {
2785097a140dSpatrick       // If the shuffled source vector simplifies, cast that value to this
2786097a140dSpatrick       // shuffle's type.
2787*d415bd75Srobert       if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
2788097a140dSpatrick                                               ScaledMask, XType, ShufQuery))
2789097a140dSpatrick         return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
2790097a140dSpatrick     }
2791097a140dSpatrick   }
2792097a140dSpatrick 
279373471bf0Spatrick   // shuffle x, x, mask --> shuffle x, undef, mask'
279409467b48Spatrick   if (LHS == RHS) {
279573471bf0Spatrick     assert(!match(RHS, m_Undef()) &&
279673471bf0Spatrick            "Shuffle with 2 undef ops not simplified?");
2797*d415bd75Srobert     return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
279809467b48Spatrick   }
279909467b48Spatrick 
280009467b48Spatrick   // shuffle undef, x, mask --> shuffle x, undef, mask'
280173471bf0Spatrick   if (match(LHS, m_Undef())) {
280209467b48Spatrick     SVI.commute();
280309467b48Spatrick     return &SVI;
280409467b48Spatrick   }
280509467b48Spatrick 
280609467b48Spatrick   if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
280709467b48Spatrick     return I;
280809467b48Spatrick 
2809*d415bd75Srobert   if (Instruction *I = foldSelectShuffle(SVI))
281009467b48Spatrick     return I;
281109467b48Spatrick 
2812097a140dSpatrick   if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
2813097a140dSpatrick     return I;
2814097a140dSpatrick 
281509467b48Spatrick   if (Instruction *I = narrowVectorSelect(SVI, Builder))
281609467b48Spatrick     return I;
281709467b48Spatrick 
2818*d415bd75Srobert   if (Instruction *I = foldFNegShuffle(SVI, Builder))
2819*d415bd75Srobert     return I;
2820*d415bd75Srobert 
2821*d415bd75Srobert   if (Instruction *I = foldCastShuffle(SVI, Builder))
2822*d415bd75Srobert     return I;
2823*d415bd75Srobert 
282409467b48Spatrick   APInt UndefElts(VWidth, 0);
2825*d415bd75Srobert   APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
282609467b48Spatrick   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
282709467b48Spatrick     if (V != &SVI)
282809467b48Spatrick       return replaceInstUsesWith(SVI, V);
282909467b48Spatrick     return &SVI;
283009467b48Spatrick   }
283109467b48Spatrick 
283209467b48Spatrick   if (Instruction *I = foldIdentityExtractShuffle(SVI))
283309467b48Spatrick     return I;
283409467b48Spatrick 
283509467b48Spatrick   // These transforms have the potential to lose undef knowledge, so they are
283609467b48Spatrick   // intentionally placed after SimplifyDemandedVectorElts().
2837097a140dSpatrick   if (Instruction *I = foldShuffleWithInsert(SVI, *this))
283809467b48Spatrick     return I;
283909467b48Spatrick   if (Instruction *I = foldIdentityPaddedShuffles(SVI))
284009467b48Spatrick     return I;
284109467b48Spatrick 
284273471bf0Spatrick   if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
284309467b48Spatrick     Value *V = evaluateInDifferentElementOrder(LHS, Mask);
284409467b48Spatrick     return replaceInstUsesWith(SVI, V);
284509467b48Spatrick   }
284609467b48Spatrick 
284709467b48Spatrick   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
284809467b48Spatrick   // a non-vector type. We can instead bitcast the original vector followed by
284909467b48Spatrick   // an extract of the desired element:
285009467b48Spatrick   //
285109467b48Spatrick   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
285209467b48Spatrick   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
285309467b48Spatrick   //   %1 = bitcast <4 x i8> %sroa to i32
285409467b48Spatrick   // Becomes:
285509467b48Spatrick   //   %bc = bitcast <16 x i8> %in to <4 x i32>
285609467b48Spatrick   //   %ext = extractelement <4 x i32> %bc, i32 0
285709467b48Spatrick   //
285809467b48Spatrick   // If the shuffle is extracting a contiguous range of values from the input
285909467b48Spatrick   // vector then each use which is a bitcast of the extracted size can be
286009467b48Spatrick   // replaced. This will work if the vector types are compatible, and the begin
286109467b48Spatrick   // index is aligned to a value in the casted vector type. If the begin index
286209467b48Spatrick   // isn't aligned then we can shuffle the original vector (keeping the same
286309467b48Spatrick   // vector type) before extracting.
286409467b48Spatrick   //
286509467b48Spatrick   // This code will bail out if the target type is fundamentally incompatible
286609467b48Spatrick   // with vectors of the source type.
286709467b48Spatrick   //
286809467b48Spatrick   // Example of <16 x i8>, target type i32:
286909467b48Spatrick   // Index range [4,8):         v-----------v Will work.
287009467b48Spatrick   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
287109467b48Spatrick   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
287209467b48Spatrick   //     <4 x i32>: |           |           |           |           |
287309467b48Spatrick   //                +-----------+-----------+-----------+-----------+
287409467b48Spatrick   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
287509467b48Spatrick   // Target type i40:           ^--------------^ Won't work, bail.
287609467b48Spatrick   bool MadeChange = false;
287709467b48Spatrick   if (isShuffleExtractingFromLHS(SVI, Mask)) {
287809467b48Spatrick     Value *V = LHS;
287909467b48Spatrick     unsigned MaskElems = Mask.size();
288073471bf0Spatrick     auto *SrcTy = cast<FixedVectorType>(V->getType());
2881*d415bd75Srobert     unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedValue();
288209467b48Spatrick     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
288309467b48Spatrick     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
288409467b48Spatrick     unsigned SrcNumElems = SrcTy->getNumElements();
288509467b48Spatrick     SmallVector<BitCastInst *, 8> BCs;
288609467b48Spatrick     DenseMap<Type *, Value *> NewBCs;
288709467b48Spatrick     for (User *U : SVI.users())
288809467b48Spatrick       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
288909467b48Spatrick         if (!BC->use_empty())
289009467b48Spatrick           // Only visit bitcasts that weren't previously handled.
289109467b48Spatrick           BCs.push_back(BC);
289209467b48Spatrick     for (BitCastInst *BC : BCs) {
289309467b48Spatrick       unsigned BegIdx = Mask.front();
289409467b48Spatrick       Type *TgtTy = BC->getDestTy();
289509467b48Spatrick       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
289609467b48Spatrick       if (!TgtElemBitWidth)
289709467b48Spatrick         continue;
289809467b48Spatrick       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
289909467b48Spatrick       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
290009467b48Spatrick       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
290109467b48Spatrick       if (!VecBitWidthsEqual)
290209467b48Spatrick         continue;
290309467b48Spatrick       if (!VectorType::isValidElementType(TgtTy))
290409467b48Spatrick         continue;
2905097a140dSpatrick       auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
290609467b48Spatrick       if (!BegIsAligned) {
290709467b48Spatrick         // Shuffle the input so [0,NumElements) contains the output, and
290809467b48Spatrick         // [NumElems,SrcNumElems) is undef.
2909097a140dSpatrick         SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
291009467b48Spatrick         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
2911097a140dSpatrick           ShuffleMask[I] = Idx;
291273471bf0Spatrick         V = Builder.CreateShuffleVector(V, ShuffleMask,
291309467b48Spatrick                                         SVI.getName() + ".extract");
291409467b48Spatrick         BegIdx = 0;
291509467b48Spatrick       }
291609467b48Spatrick       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
291709467b48Spatrick       assert(SrcElemsPerTgtElem);
291809467b48Spatrick       BegIdx /= SrcElemsPerTgtElem;
291909467b48Spatrick       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
292009467b48Spatrick       auto *NewBC =
292109467b48Spatrick           BCAlreadyExists
292209467b48Spatrick               ? NewBCs[CastSrcTy]
292309467b48Spatrick               : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
292409467b48Spatrick       if (!BCAlreadyExists)
292509467b48Spatrick         NewBCs[CastSrcTy] = NewBC;
292609467b48Spatrick       auto *Ext = Builder.CreateExtractElement(
292709467b48Spatrick           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
292809467b48Spatrick       // The shufflevector isn't being replaced: the bitcast that used it
292909467b48Spatrick       // is. InstCombine will visit the newly-created instructions.
293009467b48Spatrick       replaceInstUsesWith(*BC, Ext);
293109467b48Spatrick       MadeChange = true;
293209467b48Spatrick     }
293309467b48Spatrick   }
293409467b48Spatrick 
293509467b48Spatrick   // If the LHS is a shufflevector itself, see if we can combine it with this
293609467b48Spatrick   // one without producing an unusual shuffle.
293709467b48Spatrick   // Cases that might be simplified:
293809467b48Spatrick   // 1.
293909467b48Spatrick   // x1=shuffle(v1,v2,mask1)
294009467b48Spatrick   //  x=shuffle(x1,undef,mask)
294109467b48Spatrick   //        ==>
294209467b48Spatrick   //  x=shuffle(v1,undef,newMask)
294309467b48Spatrick   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
294409467b48Spatrick   // 2.
294509467b48Spatrick   // x1=shuffle(v1,undef,mask1)
294609467b48Spatrick   //  x=shuffle(x1,x2,mask)
294709467b48Spatrick   // where v1.size() == mask1.size()
294809467b48Spatrick   //        ==>
294909467b48Spatrick   //  x=shuffle(v1,x2,newMask)
295009467b48Spatrick   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
295109467b48Spatrick   // 3.
295209467b48Spatrick   // x2=shuffle(v2,undef,mask2)
295309467b48Spatrick   //  x=shuffle(x1,x2,mask)
295409467b48Spatrick   // where v2.size() == mask2.size()
295509467b48Spatrick   //        ==>
295609467b48Spatrick   //  x=shuffle(x1,v2,newMask)
295709467b48Spatrick   // newMask[i] = (mask[i] < x1.size())
295809467b48Spatrick   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
295909467b48Spatrick   // 4.
296009467b48Spatrick   // x1=shuffle(v1,undef,mask1)
296109467b48Spatrick   // x2=shuffle(v2,undef,mask2)
296209467b48Spatrick   //  x=shuffle(x1,x2,mask)
296309467b48Spatrick   // where v1.size() == v2.size()
296409467b48Spatrick   //        ==>
296509467b48Spatrick   //  x=shuffle(v1,v2,newMask)
296609467b48Spatrick   // newMask[i] = (mask[i] < x1.size())
296709467b48Spatrick   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
296809467b48Spatrick   //
296909467b48Spatrick   // Here we are really conservative:
297009467b48Spatrick   // we are absolutely afraid of producing a shuffle mask not in the input
297109467b48Spatrick   // program, because the code gen may not be smart enough to turn a merged
297209467b48Spatrick   // shuffle into two specific shuffles: it may produce worse code.  As such,
297309467b48Spatrick   // we only merge two shuffles if the result is either a splat or one of the
297409467b48Spatrick   // input shuffle masks.  In this case, merging the shuffles just removes
297509467b48Spatrick   // one instruction, which we know is safe.  This is good for things like
297609467b48Spatrick   // turning: (splat(splat)) -> splat, or
297709467b48Spatrick   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
297809467b48Spatrick   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
297909467b48Spatrick   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
298009467b48Spatrick   if (LHSShuffle)
298173471bf0Spatrick     if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
298209467b48Spatrick       LHSShuffle = nullptr;
298309467b48Spatrick   if (RHSShuffle)
298473471bf0Spatrick     if (!match(RHSShuffle->getOperand(1), m_Undef()))
298509467b48Spatrick       RHSShuffle = nullptr;
298609467b48Spatrick   if (!LHSShuffle && !RHSShuffle)
298709467b48Spatrick     return MadeChange ? &SVI : nullptr;
298809467b48Spatrick 
298909467b48Spatrick   Value* LHSOp0 = nullptr;
299009467b48Spatrick   Value* LHSOp1 = nullptr;
299109467b48Spatrick   Value* RHSOp0 = nullptr;
299209467b48Spatrick   unsigned LHSOp0Width = 0;
299309467b48Spatrick   unsigned RHSOp0Width = 0;
299409467b48Spatrick   if (LHSShuffle) {
299509467b48Spatrick     LHSOp0 = LHSShuffle->getOperand(0);
299609467b48Spatrick     LHSOp1 = LHSShuffle->getOperand(1);
299773471bf0Spatrick     LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
299809467b48Spatrick   }
299909467b48Spatrick   if (RHSShuffle) {
300009467b48Spatrick     RHSOp0 = RHSShuffle->getOperand(0);
300173471bf0Spatrick     RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
300209467b48Spatrick   }
300309467b48Spatrick   Value* newLHS = LHS;
300409467b48Spatrick   Value* newRHS = RHS;
300509467b48Spatrick   if (LHSShuffle) {
300609467b48Spatrick     // case 1
300773471bf0Spatrick     if (match(RHS, m_Undef())) {
300809467b48Spatrick       newLHS = LHSOp0;
300909467b48Spatrick       newRHS = LHSOp1;
301009467b48Spatrick     }
301109467b48Spatrick     // case 2 or 4
301209467b48Spatrick     else if (LHSOp0Width == LHSWidth) {
301309467b48Spatrick       newLHS = LHSOp0;
301409467b48Spatrick     }
301509467b48Spatrick   }
301609467b48Spatrick   // case 3 or 4
301709467b48Spatrick   if (RHSShuffle && RHSOp0Width == LHSWidth) {
301809467b48Spatrick     newRHS = RHSOp0;
301909467b48Spatrick   }
302009467b48Spatrick   // case 4
302109467b48Spatrick   if (LHSOp0 == RHSOp0) {
302209467b48Spatrick     newLHS = LHSOp0;
302309467b48Spatrick     newRHS = nullptr;
302409467b48Spatrick   }
302509467b48Spatrick 
302609467b48Spatrick   if (newLHS == LHS && newRHS == RHS)
302709467b48Spatrick     return MadeChange ? &SVI : nullptr;
302809467b48Spatrick 
3029097a140dSpatrick   ArrayRef<int> LHSMask;
3030097a140dSpatrick   ArrayRef<int> RHSMask;
303109467b48Spatrick   if (newLHS != LHS)
303209467b48Spatrick     LHSMask = LHSShuffle->getShuffleMask();
303309467b48Spatrick   if (RHSShuffle && newRHS != RHS)
303409467b48Spatrick     RHSMask = RHSShuffle->getShuffleMask();
303509467b48Spatrick 
303609467b48Spatrick   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
303709467b48Spatrick   SmallVector<int, 16> newMask;
303809467b48Spatrick   bool isSplat = true;
303909467b48Spatrick   int SplatElt = -1;
304009467b48Spatrick   // Create a new mask for the new ShuffleVectorInst so that the new
304109467b48Spatrick   // ShuffleVectorInst is equivalent to the original one.
304209467b48Spatrick   for (unsigned i = 0; i < VWidth; ++i) {
304309467b48Spatrick     int eltMask;
304409467b48Spatrick     if (Mask[i] < 0) {
304509467b48Spatrick       // This element is an undef value.
304609467b48Spatrick       eltMask = -1;
304709467b48Spatrick     } else if (Mask[i] < (int)LHSWidth) {
304809467b48Spatrick       // This element is from left hand side vector operand.
304909467b48Spatrick       //
305009467b48Spatrick       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
305109467b48Spatrick       // new mask value for the element.
305209467b48Spatrick       if (newLHS != LHS) {
305309467b48Spatrick         eltMask = LHSMask[Mask[i]];
305409467b48Spatrick         // If the value selected is an undef value, explicitly specify it
305509467b48Spatrick         // with a -1 mask value.
305609467b48Spatrick         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
305709467b48Spatrick           eltMask = -1;
305809467b48Spatrick       } else
305909467b48Spatrick         eltMask = Mask[i];
306009467b48Spatrick     } else {
306109467b48Spatrick       // This element is from right hand side vector operand
306209467b48Spatrick       //
306309467b48Spatrick       // If the value selected is an undef value, explicitly specify it
306409467b48Spatrick       // with a -1 mask value. (case 1)
306573471bf0Spatrick       if (match(RHS, m_Undef()))
306609467b48Spatrick         eltMask = -1;
306709467b48Spatrick       // If RHS is going to be replaced (case 3 or 4), calculate the
306809467b48Spatrick       // new mask value for the element.
306909467b48Spatrick       else if (newRHS != RHS) {
307009467b48Spatrick         eltMask = RHSMask[Mask[i]-LHSWidth];
307109467b48Spatrick         // If the value selected is an undef value, explicitly specify it
307209467b48Spatrick         // with a -1 mask value.
307309467b48Spatrick         if (eltMask >= (int)RHSOp0Width) {
307473471bf0Spatrick           assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
307573471bf0Spatrick                  "should have been check above");
307609467b48Spatrick           eltMask = -1;
307709467b48Spatrick         }
307809467b48Spatrick       } else
307909467b48Spatrick         eltMask = Mask[i]-LHSWidth;
308009467b48Spatrick 
308109467b48Spatrick       // If LHS's width is changed, shift the mask value accordingly.
308209467b48Spatrick       // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
308309467b48Spatrick       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
308409467b48Spatrick       // If newRHS == newLHS, we want to remap any references from newRHS to
308509467b48Spatrick       // newLHS so that we can properly identify splats that may occur due to
308609467b48Spatrick       // obfuscation across the two vectors.
308709467b48Spatrick       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
308809467b48Spatrick         eltMask += newLHSWidth;
308909467b48Spatrick     }
309009467b48Spatrick 
309109467b48Spatrick     // Check if this could still be a splat.
309209467b48Spatrick     if (eltMask >= 0) {
309309467b48Spatrick       if (SplatElt >= 0 && SplatElt != eltMask)
309409467b48Spatrick         isSplat = false;
309509467b48Spatrick       SplatElt = eltMask;
309609467b48Spatrick     }
309709467b48Spatrick 
309809467b48Spatrick     newMask.push_back(eltMask);
309909467b48Spatrick   }
310009467b48Spatrick 
310109467b48Spatrick   // If the result mask is equal to one of the original shuffle masks,
310209467b48Spatrick   // or is a splat, do the replacement.
310309467b48Spatrick   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
310409467b48Spatrick     if (!newRHS)
310509467b48Spatrick       newRHS = UndefValue::get(newLHS->getType());
310673471bf0Spatrick     return new ShuffleVectorInst(newLHS, newRHS, newMask);
310709467b48Spatrick   }
310809467b48Spatrick 
310909467b48Spatrick   return MadeChange ? &SVI : nullptr;
311009467b48Spatrick }
3111