LLVM API Documentation

InstCombineVectorOps.cpp
Go to the documentation of this file.
00001 //===- InstCombineVectorOps.cpp -------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements instcombine for ExtractElement, InsertElement and
00011 // ShuffleVector.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "InstCombine.h"
00016 #include "llvm/IR/PatternMatch.h"
00017 using namespace llvm;
00018 using namespace PatternMatch;
00019 
00020 #define DEBUG_TYPE "instcombine"
00021 
00022 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
00023 /// is to leave as a vector operation.  isConstant indicates whether we're
00024 /// extracting one known element.  If false we're extracting a variable index.
00025 static bool CheapToScalarize(Value *V, bool isConstant) {
00026   if (Constant *C = dyn_cast<Constant>(V)) {
00027     if (isConstant) return true;
00028 
00029     // If all elts are the same, we can extract it and use any of the values.
00030     if (Constant *Op0 = C->getAggregateElement(0U)) {
00031       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
00032            ++i)
00033         if (C->getAggregateElement(i) != Op0)
00034           return false;
00035       return true;
00036     }
00037   }
00038   Instruction *I = dyn_cast<Instruction>(V);
00039   if (!I) return false;
00040 
00041   // Insert element gets simplified to the inserted element or is deleted if
00042   // this is constant idx extract element and its a constant idx insertelt.
00043   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
00044       isa<ConstantInt>(I->getOperand(2)))
00045     return true;
00046   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
00047     return true;
00048   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
00049     if (BO->hasOneUse() &&
00050         (CheapToScalarize(BO->getOperand(0), isConstant) ||
00051          CheapToScalarize(BO->getOperand(1), isConstant)))
00052       return true;
00053   if (CmpInst *CI = dyn_cast<CmpInst>(I))
00054     if (CI->hasOneUse() &&
00055         (CheapToScalarize(CI->getOperand(0), isConstant) ||
00056          CheapToScalarize(CI->getOperand(1), isConstant)))
00057       return true;
00058 
00059   return false;
00060 }
00061 
00062 /// FindScalarElement - Given a vector and an element number, see if the scalar
00063 /// value is already around as a register, for example if it were inserted then
00064 /// extracted from the vector.
00065 static Value *FindScalarElement(Value *V, unsigned EltNo) {
00066   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
00067   VectorType *VTy = cast<VectorType>(V->getType());
00068   unsigned Width = VTy->getNumElements();
00069   if (EltNo >= Width)  // Out of range access.
00070     return UndefValue::get(VTy->getElementType());
00071 
00072   if (Constant *C = dyn_cast<Constant>(V))
00073     return C->getAggregateElement(EltNo);
00074 
00075   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
00076     // If this is an insert to a variable element, we don't know what it is.
00077     if (!isa<ConstantInt>(III->getOperand(2)))
00078       return nullptr;
00079     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
00080 
00081     // If this is an insert to the element we are looking for, return the
00082     // inserted value.
00083     if (EltNo == IIElt)
00084       return III->getOperand(1);
00085 
00086     // Otherwise, the insertelement doesn't modify the value, recurse on its
00087     // vector input.
00088     return FindScalarElement(III->getOperand(0), EltNo);
00089   }
00090 
00091   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
00092     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
00093     int InEl = SVI->getMaskValue(EltNo);
00094     if (InEl < 0)
00095       return UndefValue::get(VTy->getElementType());
00096     if (InEl < (int)LHSWidth)
00097       return FindScalarElement(SVI->getOperand(0), InEl);
00098     return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
00099   }
00100 
00101   // Extract a value from a vector add operation with a constant zero.
00102   Value *Val = nullptr; Constant *Con = nullptr;
00103   if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
00104     if (Con->getAggregateElement(EltNo)->isNullValue())
00105       return FindScalarElement(Val, EltNo);
00106   }
00107 
00108   // Otherwise, we don't know.
00109   return nullptr;
00110 }
00111 
00112 // If we have a PHI node with a vector type that has only 2 uses: feed
00113 // itself and be an operand of extractelement at a constant location,
00114 // try to replace the PHI of the vector type with a PHI of a scalar type.
00115 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
00116   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
00117   if (!PN->hasNUses(2))
00118     return nullptr;
00119 
00120   // If so, it's known at this point that one operand is PHI and the other is
00121   // an extractelement node. Find the PHI user that is not the extractelement
00122   // node.
00123   auto iu = PN->user_begin();
00124   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
00125   if (PHIUser == cast<Instruction>(&EI))
00126     PHIUser = cast<Instruction>(*(++iu));
00127 
00128   // Verify that this PHI user has one use, which is the PHI itself,
00129   // and that it is a binary operation which is cheap to scalarize.
00130   // otherwise return NULL.
00131   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
00132       !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
00133     return nullptr;
00134 
00135   // Create a scalar PHI node that will replace the vector PHI node
00136   // just before the current PHI node.
00137   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
00138       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
00139   // Scalarize each PHI operand.
00140   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
00141     Value *PHIInVal = PN->getIncomingValue(i);
00142     BasicBlock *inBB = PN->getIncomingBlock(i);
00143     Value *Elt = EI.getIndexOperand();
00144     // If the operand is the PHI induction variable:
00145     if (PHIInVal == PHIUser) {
00146       // Scalarize the binary operation. Its first operand is the
00147       // scalar PHI, and the second operand is extracted from the other
00148       // vector operand.
00149       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
00150       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
00151       Value *Op = InsertNewInstWith(
00152           ExtractElementInst::Create(B0->getOperand(opId), Elt,
00153                                      B0->getOperand(opId)->getName() + ".Elt"),
00154           *B0);
00155       Value *newPHIUser = InsertNewInstWith(
00156           BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
00157       scalarPHI->addIncoming(newPHIUser, inBB);
00158     } else {
00159       // Scalarize PHI input:
00160       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
00161       // Insert the new instruction into the predecessor basic block.
00162       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
00163       BasicBlock::iterator InsertPos;
00164       if (pos && !isa<PHINode>(pos)) {
00165         InsertPos = pos;
00166         ++InsertPos;
00167       } else {
00168         InsertPos = inBB->getFirstInsertionPt();
00169       }
00170 
00171       InsertNewInstWith(newEI, *InsertPos);
00172 
00173       scalarPHI->addIncoming(newEI, inBB);
00174     }
00175   }
00176   return ReplaceInstUsesWith(EI, scalarPHI);
00177 }
00178 
00179 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
00180   // If vector val is constant with all elements the same, replace EI with
00181   // that element.  We handle a known element # below.
00182   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
00183     if (CheapToScalarize(C, false))
00184       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
00185 
00186   // If extracting a specified index from the vector, see if we can recursively
00187   // find a previously computed scalar that was inserted into the vector.
00188   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
00189     unsigned IndexVal = IdxC->getZExtValue();
00190     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
00191 
00192     // If this is extracting an invalid index, turn this into undef, to avoid
00193     // crashing the code below.
00194     if (IndexVal >= VectorWidth)
00195       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
00196 
00197     // This instruction only demands the single element from the input vector.
00198     // If the input vector has a single use, simplify it based on this use
00199     // property.
00200     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
00201       APInt UndefElts(VectorWidth, 0);
00202       APInt DemandedMask(VectorWidth, 0);
00203       DemandedMask.setBit(IndexVal);
00204       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
00205                                                 DemandedMask, UndefElts)) {
00206         EI.setOperand(0, V);
00207         return &EI;
00208       }
00209     }
00210 
00211     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
00212       return ReplaceInstUsesWith(EI, Elt);
00213 
00214     // If the this extractelement is directly using a bitcast from a vector of
00215     // the same number of elements, see if we can find the source element from
00216     // it.  In this case, we will end up needing to bitcast the scalars.
00217     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
00218       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
00219         if (VT->getNumElements() == VectorWidth)
00220           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
00221             return new BitCastInst(Elt, EI.getType());
00222     }
00223 
00224     // If there's a vector PHI feeding a scalar use through this extractelement
00225     // instruction, try to scalarize the PHI.
00226     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
00227       Instruction *scalarPHI = scalarizePHI(EI, PN);
00228       if (scalarPHI)
00229         return scalarPHI;
00230     }
00231   }
00232 
00233   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
00234     // Push extractelement into predecessor operation if legal and
00235     // profitable to do so
00236     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
00237       if (I->hasOneUse() &&
00238           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
00239         Value *newEI0 =
00240           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
00241                                         EI.getName()+".lhs");
00242         Value *newEI1 =
00243           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
00244                                         EI.getName()+".rhs");
00245         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
00246       }
00247     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
00248       // Extracting the inserted element?
00249       if (IE->getOperand(2) == EI.getOperand(1))
00250         return ReplaceInstUsesWith(EI, IE->getOperand(1));
00251       // If the inserted and extracted elements are constants, they must not
00252       // be the same value, extract from the pre-inserted value instead.
00253       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
00254         Worklist.AddValue(EI.getOperand(0));
00255         EI.setOperand(0, IE->getOperand(0));
00256         return &EI;
00257       }
00258     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
00259       // If this is extracting an element from a shufflevector, figure out where
00260       // it came from and extract from the appropriate input element instead.
00261       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
00262         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
00263         Value *Src;
00264         unsigned LHSWidth =
00265           SVI->getOperand(0)->getType()->getVectorNumElements();
00266 
00267         if (SrcIdx < 0)
00268           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
00269         if (SrcIdx < (int)LHSWidth)
00270           Src = SVI->getOperand(0);
00271         else {
00272           SrcIdx -= LHSWidth;
00273           Src = SVI->getOperand(1);
00274         }
00275         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
00276         return ExtractElementInst::Create(Src,
00277                                           ConstantInt::get(Int32Ty,
00278                                                            SrcIdx, false));
00279       }
00280     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
00281       // Canonicalize extractelement(cast) -> cast(extractelement)
00282       // bitcasts can change the number of vector elements and they cost nothing
00283       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
00284         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
00285                                                   EI.getIndexOperand());
00286         Worklist.AddValue(EE);
00287         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
00288       }
00289     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00290       if (SI->hasOneUse()) {
00291         // TODO: For a select on vectors, it might be useful to do this if it
00292         // has multiple extractelement uses. For vector select, that seems to
00293         // fight the vectorizer.
00294 
00295         // If we are extracting an element from a vector select or a select on
00296         // vectors, a select on the scalars extracted from the vector arguments.
00297         Value *TrueVal = SI->getTrueValue();
00298         Value *FalseVal = SI->getFalseValue();
00299 
00300         Value *Cond = SI->getCondition();
00301         if (Cond->getType()->isVectorTy()) {
00302           Cond = Builder->CreateExtractElement(Cond,
00303                                                EI.getIndexOperand(),
00304                                                Cond->getName() + ".elt");
00305         }
00306 
00307         Value *V1Elem
00308           = Builder->CreateExtractElement(TrueVal,
00309                                           EI.getIndexOperand(),
00310                                           TrueVal->getName() + ".elt");
00311 
00312         Value *V2Elem
00313           = Builder->CreateExtractElement(FalseVal,
00314                                           EI.getIndexOperand(),
00315                                           FalseVal->getName() + ".elt");
00316         return SelectInst::Create(Cond,
00317                                   V1Elem,
00318                                   V2Elem,
00319                                   SI->getName() + ".elt");
00320       }
00321     }
00322   }
00323   return nullptr;
00324 }
00325 
00326 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
00327 /// elements from either LHS or RHS, return the shuffle mask and true.
00328 /// Otherwise, return false.
00329 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
00330                                          SmallVectorImpl<Constant*> &Mask) {
00331   assert(LHS->getType() == RHS->getType() &&
00332          "Invalid CollectSingleShuffleElements");
00333   unsigned NumElts = V->getType()->getVectorNumElements();
00334 
00335   if (isa<UndefValue>(V)) {
00336     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
00337     return true;
00338   }
00339 
00340   if (V == LHS) {
00341     for (unsigned i = 0; i != NumElts; ++i)
00342       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
00343     return true;
00344   }
00345 
00346   if (V == RHS) {
00347     for (unsigned i = 0; i != NumElts; ++i)
00348       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
00349                                       i+NumElts));
00350     return true;
00351   }
00352 
00353   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
00354     // If this is an insert of an extract from some other vector, include it.
00355     Value *VecOp    = IEI->getOperand(0);
00356     Value *ScalarOp = IEI->getOperand(1);
00357     Value *IdxOp    = IEI->getOperand(2);
00358 
00359     if (!isa<ConstantInt>(IdxOp))
00360       return false;
00361     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00362 
00363     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
00364       // We can handle this if the vector we are inserting into is
00365       // transitively ok.
00366       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
00367         // If so, update the mask to reflect the inserted undef.
00368         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
00369         return true;
00370       }
00371     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
00372       if (isa<ConstantInt>(EI->getOperand(1))) {
00373         unsigned ExtractedIdx =
00374         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00375         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
00376 
00377         // This must be extracting from either LHS or RHS.
00378         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
00379           // We can handle this if the vector we are inserting into is
00380           // transitively ok.
00381           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
00382             // If so, update the mask to reflect the inserted value.
00383             if (EI->getOperand(0) == LHS) {
00384               Mask[InsertedIdx % NumElts] =
00385               ConstantInt::get(Type::getInt32Ty(V->getContext()),
00386                                ExtractedIdx);
00387             } else {
00388               assert(EI->getOperand(0) == RHS);
00389               Mask[InsertedIdx % NumElts] =
00390               ConstantInt::get(Type::getInt32Ty(V->getContext()),
00391                                ExtractedIdx + NumLHSElts);
00392             }
00393             return true;
00394           }
00395         }
00396       }
00397     }
00398   }
00399 
00400   return false;
00401 }
00402 
00403 
00404 /// We are building a shuffle to create V, which is a sequence of insertelement,
00405 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
00406 /// not rely on the second vector source. Return a std::pair containing the
00407 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
00408 /// parameter as required.
00409 ///
00410 /// Note: we intentionally don't try to fold earlier shuffles since they have
00411 /// often been chosen carefully to be efficiently implementable on the target.
00412 typedef std::pair<Value *, Value *> ShuffleOps;
00413 
00414 static ShuffleOps CollectShuffleElements(Value *V,
00415                                          SmallVectorImpl<Constant *> &Mask,
00416                                          Value *PermittedRHS) {
00417   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
00418   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
00419 
00420   if (isa<UndefValue>(V)) {
00421     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
00422     return std::make_pair(
00423         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
00424   }
00425 
00426   if (isa<ConstantAggregateZero>(V)) {
00427     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
00428     return std::make_pair(V, nullptr);
00429   }
00430 
00431   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
00432     // If this is an insert of an extract from some other vector, include it.
00433     Value *VecOp    = IEI->getOperand(0);
00434     Value *ScalarOp = IEI->getOperand(1);
00435     Value *IdxOp    = IEI->getOperand(2);
00436 
00437     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
00438       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
00439         unsigned ExtractedIdx =
00440           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00441         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00442 
00443         // Either the extracted from or inserted into vector must be RHSVec,
00444         // otherwise we'd end up with a shuffle of three inputs.
00445         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
00446           Value *RHS = EI->getOperand(0);
00447           ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
00448           assert(LR.second == nullptr || LR.second == RHS);
00449 
00450           if (LR.first->getType() != RHS->getType()) {
00451             // We tried our best, but we can't find anything compatible with RHS
00452             // further up the chain. Return a trivial shuffle.
00453             for (unsigned i = 0; i < NumElts; ++i)
00454               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
00455             return std::make_pair(V, nullptr);
00456           }
00457 
00458           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
00459           Mask[InsertedIdx % NumElts] =
00460             ConstantInt::get(Type::getInt32Ty(V->getContext()),
00461                              NumLHSElts+ExtractedIdx);
00462           return std::make_pair(LR.first, RHS);
00463         }
00464 
00465         if (VecOp == PermittedRHS) {
00466           // We've gone as far as we can: anything on the other side of the
00467           // extractelement will already have been converted into a shuffle.
00468           unsigned NumLHSElts =
00469               EI->getOperand(0)->getType()->getVectorNumElements();
00470           for (unsigned i = 0; i != NumElts; ++i)
00471             Mask.push_back(ConstantInt::get(
00472                 Type::getInt32Ty(V->getContext()),
00473                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
00474           return std::make_pair(EI->getOperand(0), PermittedRHS);
00475         }
00476 
00477         // If this insertelement is a chain that comes from exactly these two
00478         // vectors, return the vector and the effective shuffle.
00479         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
00480             CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
00481                                          Mask))
00482           return std::make_pair(EI->getOperand(0), PermittedRHS);
00483       }
00484     }
00485   }
00486 
00487   // Otherwise, can't do anything fancy.  Return an identity vector.
00488   for (unsigned i = 0; i != NumElts; ++i)
00489     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
00490   return std::make_pair(V, nullptr);
00491 }
00492 
00493 /// Try to find redundant insertvalue instructions, like the following ones:
00494 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
00495 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
00496 /// Here the second instruction inserts values at the same indices, as the
00497 /// first one, making the first one redundant.
00498 /// It should be transformed to:
00499 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
00500 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
00501   bool IsRedundant = false;
00502   ArrayRef<unsigned int> FirstIndices = I.getIndices();
00503 
00504   // If there is a chain of insertvalue instructions (each of them except the
00505   // last one has only one use and it's another insertvalue insn from this
00506   // chain), check if any of the 'children' uses the same indices as the first
00507   // instruction. In this case, the first one is redundant.
00508   Value *V = &I;
00509   unsigned Depth = 0;
00510   while (V->hasOneUse() && Depth < 10) {
00511     User *U = V->user_back();
00512     auto UserInsInst = dyn_cast<InsertValueInst>(U);
00513     if (!UserInsInst || U->getOperand(0) != V)
00514       break;
00515     if (UserInsInst->getIndices() == FirstIndices) {
00516       IsRedundant = true;
00517       break;
00518     }
00519     V = UserInsInst;
00520     Depth++;
00521   }
00522 
00523   if (IsRedundant)
00524     return ReplaceInstUsesWith(I, I.getOperand(0));
00525   return nullptr;
00526 }
00527 
00528 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
00529   Value *VecOp    = IE.getOperand(0);
00530   Value *ScalarOp = IE.getOperand(1);
00531   Value *IdxOp    = IE.getOperand(2);
00532 
00533   // Inserting an undef or into an undefined place, remove this.
00534   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
00535     ReplaceInstUsesWith(IE, VecOp);
00536 
00537   // If the inserted element was extracted from some other vector, and if the
00538   // indexes are constant, try to turn this into a shufflevector operation.
00539   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
00540     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
00541       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
00542       unsigned NumExtractVectorElts =
00543           EI->getOperand(0)->getType()->getVectorNumElements();
00544       unsigned ExtractedIdx =
00545         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00546       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00547 
00548       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
00549         return ReplaceInstUsesWith(IE, VecOp);
00550 
00551       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
00552         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
00553 
00554       // If we are extracting a value from a vector, then inserting it right
00555       // back into the same place, just use the input vector.
00556       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
00557         return ReplaceInstUsesWith(IE, VecOp);
00558 
00559       // If this insertelement isn't used by some other insertelement, turn it
00560       // (and any insertelements it points to), into one big shuffle.
00561       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
00562         SmallVector<Constant*, 16> Mask;
00563         ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
00564 
00565         // The proposed shuffle may be trivial, in which case we shouldn't
00566         // perform the combine.
00567         if (LR.first != &IE && LR.second != &IE) {
00568           // We now have a shuffle of LHS, RHS, Mask.
00569           if (LR.second == nullptr)
00570             LR.second = UndefValue::get(LR.first->getType());
00571           return new ShuffleVectorInst(LR.first, LR.second,
00572                                        ConstantVector::get(Mask));
00573         }
00574       }
00575     }
00576   }
00577 
00578   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
00579   APInt UndefElts(VWidth, 0);
00580   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00581   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
00582     if (V != &IE)
00583       return ReplaceInstUsesWith(IE, V);
00584     return &IE;
00585   }
00586 
00587   return nullptr;
00588 }
00589 
00590 /// Return true if we can evaluate the specified expression tree if the vector
00591 /// elements were shuffled in a different order.
00592 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
00593                                 unsigned Depth = 5) {
00594   // We can always reorder the elements of a constant.
00595   if (isa<Constant>(V))
00596     return true;
00597 
00598   // We won't reorder vector arguments. No IPO here.
00599   Instruction *I = dyn_cast<Instruction>(V);
00600   if (!I) return false;
00601 
00602   // Two users may expect different orders of the elements. Don't try it.
00603   if (!I->hasOneUse())
00604     return false;
00605 
00606   if (Depth == 0) return false;
00607 
00608   switch (I->getOpcode()) {
00609     case Instruction::Add:
00610     case Instruction::FAdd:
00611     case Instruction::Sub:
00612     case Instruction::FSub:
00613     case Instruction::Mul:
00614     case Instruction::FMul:
00615     case Instruction::UDiv:
00616     case Instruction::SDiv:
00617     case Instruction::FDiv:
00618     case Instruction::URem:
00619     case Instruction::SRem:
00620     case Instruction::FRem:
00621     case Instruction::Shl:
00622     case Instruction::LShr:
00623     case Instruction::AShr:
00624     case Instruction::And:
00625     case Instruction::Or:
00626     case Instruction::Xor:
00627     case Instruction::ICmp:
00628     case Instruction::FCmp:
00629     case Instruction::Trunc:
00630     case Instruction::ZExt:
00631     case Instruction::SExt:
00632     case Instruction::FPToUI:
00633     case Instruction::FPToSI:
00634     case Instruction::UIToFP:
00635     case Instruction::SIToFP:
00636     case Instruction::FPTrunc:
00637     case Instruction::FPExt:
00638     case Instruction::GetElementPtr: {
00639       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
00640         if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
00641           return false;
00642       }
00643       return true;
00644     }
00645     case Instruction::InsertElement: {
00646       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
00647       if (!CI) return false;
00648       int ElementNumber = CI->getLimitedValue();
00649 
00650       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
00651       // can't put an element into multiple indices.
00652       bool SeenOnce = false;
00653       for (int i = 0, e = Mask.size(); i != e; ++i) {
00654         if (Mask[i] == ElementNumber) {
00655           if (SeenOnce)
00656             return false;
00657           SeenOnce = true;
00658         }
00659       }
00660       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
00661     }
00662   }
00663   return false;
00664 }
00665 
00666 /// Rebuild a new instruction just like 'I' but with the new operands given.
00667 /// In the event of type mismatch, the type of the operands is correct.
00668 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
00669   // We don't want to use the IRBuilder here because we want the replacement
00670   // instructions to appear next to 'I', not the builder's insertion point.
00671   switch (I->getOpcode()) {
00672     case Instruction::Add:
00673     case Instruction::FAdd:
00674     case Instruction::Sub:
00675     case Instruction::FSub:
00676     case Instruction::Mul:
00677     case Instruction::FMul:
00678     case Instruction::UDiv:
00679     case Instruction::SDiv:
00680     case Instruction::FDiv:
00681     case Instruction::URem:
00682     case Instruction::SRem:
00683     case Instruction::FRem:
00684     case Instruction::Shl:
00685     case Instruction::LShr:
00686     case Instruction::AShr:
00687     case Instruction::And:
00688     case Instruction::Or:
00689     case Instruction::Xor: {
00690       BinaryOperator *BO = cast<BinaryOperator>(I);
00691       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
00692       BinaryOperator *New =
00693           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
00694                                  NewOps[0], NewOps[1], "", BO);
00695       if (isa<OverflowingBinaryOperator>(BO)) {
00696         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
00697         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
00698       }
00699       if (isa<PossiblyExactOperator>(BO)) {
00700         New->setIsExact(BO->isExact());
00701       }
00702       if (isa<FPMathOperator>(BO))
00703         New->copyFastMathFlags(I);
00704       return New;
00705     }
00706     case Instruction::ICmp:
00707       assert(NewOps.size() == 2 && "icmp with #ops != 2");
00708       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
00709                           NewOps[0], NewOps[1]);
00710     case Instruction::FCmp:
00711       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
00712       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
00713                           NewOps[0], NewOps[1]);
00714     case Instruction::Trunc:
00715     case Instruction::ZExt:
00716     case Instruction::SExt:
00717     case Instruction::FPToUI:
00718     case Instruction::FPToSI:
00719     case Instruction::UIToFP:
00720     case Instruction::SIToFP:
00721     case Instruction::FPTrunc:
00722     case Instruction::FPExt: {
00723       // It's possible that the mask has a different number of elements from
00724       // the original cast. We recompute the destination type to match the mask.
00725       Type *DestTy =
00726           VectorType::get(I->getType()->getScalarType(),
00727                           NewOps[0]->getType()->getVectorNumElements());
00728       assert(NewOps.size() == 1 && "cast with #ops != 1");
00729       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
00730                               "", I);
00731     }
00732     case Instruction::GetElementPtr: {
00733       Value *Ptr = NewOps[0];
00734       ArrayRef<Value*> Idx = NewOps.slice(1);
00735       GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
00736       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
00737       return GEP;
00738     }
00739   }
00740   llvm_unreachable("failed to rebuild vector instructions");
00741 }
00742 
00743 Value *
00744 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
00745   // Mask.size() does not need to be equal to the number of vector elements.
00746 
00747   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
00748   if (isa<UndefValue>(V)) {
00749     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
00750                                            Mask.size()));
00751   }
00752   if (isa<ConstantAggregateZero>(V)) {
00753     return ConstantAggregateZero::get(
00754                VectorType::get(V->getType()->getScalarType(),
00755                                Mask.size()));
00756   }
00757   if (Constant *C = dyn_cast<Constant>(V)) {
00758     SmallVector<Constant *, 16> MaskValues;
00759     for (int i = 0, e = Mask.size(); i != e; ++i) {
00760       if (Mask[i] == -1)
00761         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
00762       else
00763         MaskValues.push_back(Builder->getInt32(Mask[i]));
00764     }
00765     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
00766                                           ConstantVector::get(MaskValues));
00767   }
00768 
00769   Instruction *I = cast<Instruction>(V);
00770   switch (I->getOpcode()) {
00771     case Instruction::Add:
00772     case Instruction::FAdd:
00773     case Instruction::Sub:
00774     case Instruction::FSub:
00775     case Instruction::Mul:
00776     case Instruction::FMul:
00777     case Instruction::UDiv:
00778     case Instruction::SDiv:
00779     case Instruction::FDiv:
00780     case Instruction::URem:
00781     case Instruction::SRem:
00782     case Instruction::FRem:
00783     case Instruction::Shl:
00784     case Instruction::LShr:
00785     case Instruction::AShr:
00786     case Instruction::And:
00787     case Instruction::Or:
00788     case Instruction::Xor:
00789     case Instruction::ICmp:
00790     case Instruction::FCmp:
00791     case Instruction::Trunc:
00792     case Instruction::ZExt:
00793     case Instruction::SExt:
00794     case Instruction::FPToUI:
00795     case Instruction::FPToSI:
00796     case Instruction::UIToFP:
00797     case Instruction::SIToFP:
00798     case Instruction::FPTrunc:
00799     case Instruction::FPExt:
00800     case Instruction::Select:
00801     case Instruction::GetElementPtr: {
00802       SmallVector<Value*, 8> NewOps;
00803       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
00804       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
00805         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
00806         NewOps.push_back(V);
00807         NeedsRebuild |= (V != I->getOperand(i));
00808       }
00809       if (NeedsRebuild) {
00810         return BuildNew(I, NewOps);
00811       }
00812       return I;
00813     }
00814     case Instruction::InsertElement: {
00815       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
00816 
00817       // The insertelement was inserting at Element. Figure out which element
00818       // that becomes after shuffling. The answer is guaranteed to be unique
00819       // by CanEvaluateShuffled.
00820       bool Found = false;
00821       int Index = 0;
00822       for (int e = Mask.size(); Index != e; ++Index) {
00823         if (Mask[Index] == Element) {
00824           Found = true;
00825           break;
00826         }
00827       }
00828 
00829       // If element is not in Mask, no need to handle the operand 1 (element to
00830       // be inserted). Just evaluate values in operand 0 according to Mask.
00831       if (!Found)
00832         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00833 
00834       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00835       return InsertElementInst::Create(V, I->getOperand(1),
00836                                        Builder->getInt32(Index), "", I);
00837     }
00838   }
00839   llvm_unreachable("failed to reorder elements of vector instruction!");
00840 }
00841 
00842 static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
00843                                   bool &isLHSID, bool &isRHSID) {
00844   isLHSID = isRHSID = true;
00845 
00846   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
00847     if (Mask[i] < 0) continue;  // Ignore undef values.
00848     // Is this an identity shuffle of the LHS value?
00849     isLHSID &= (Mask[i] == (int)i);
00850 
00851     // Is this an identity shuffle of the RHS value?
00852     isRHSID &= (Mask[i]-e == i);
00853   }
00854 }
00855 
00856 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
00857   Value *LHS = SVI.getOperand(0);
00858   Value *RHS = SVI.getOperand(1);
00859   SmallVector<int, 16> Mask = SVI.getShuffleMask();
00860 
00861   bool MadeChange = false;
00862 
00863   // Undefined shuffle mask -> undefined value.
00864   if (isa<UndefValue>(SVI.getOperand(2)))
00865     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
00866 
00867   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
00868 
00869   APInt UndefElts(VWidth, 0);
00870   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00871   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
00872     if (V != &SVI)
00873       return ReplaceInstUsesWith(SVI, V);
00874     LHS = SVI.getOperand(0);
00875     RHS = SVI.getOperand(1);
00876     MadeChange = true;
00877   }
00878 
00879   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
00880 
00881   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
00882   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
00883   if (LHS == RHS || isa<UndefValue>(LHS)) {
00884     if (isa<UndefValue>(LHS) && LHS == RHS) {
00885       // shuffle(undef,undef,mask) -> undef.
00886       Value *Result = (VWidth == LHSWidth)
00887                       ? LHS : UndefValue::get(SVI.getType());
00888       return ReplaceInstUsesWith(SVI, Result);
00889     }
00890 
00891     // Remap any references to RHS to use LHS.
00892     SmallVector<Constant*, 16> Elts;
00893     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
00894       if (Mask[i] < 0) {
00895         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
00896         continue;
00897       }
00898 
00899       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
00900           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
00901         Mask[i] = -1;     // Turn into undef.
00902         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
00903       } else {
00904         Mask[i] = Mask[i] % e;  // Force to LHS.
00905         Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
00906                                         Mask[i]));
00907       }
00908     }
00909     SVI.setOperand(0, SVI.getOperand(1));
00910     SVI.setOperand(1, UndefValue::get(RHS->getType()));
00911     SVI.setOperand(2, ConstantVector::get(Elts));
00912     LHS = SVI.getOperand(0);
00913     RHS = SVI.getOperand(1);
00914     MadeChange = true;
00915   }
00916 
00917   if (VWidth == LHSWidth) {
00918     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
00919     bool isLHSID, isRHSID;
00920     RecognizeIdentityMask(Mask, isLHSID, isRHSID);
00921 
00922     // Eliminate identity shuffles.
00923     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
00924     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
00925   }
00926 
00927   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
00928     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
00929     return ReplaceInstUsesWith(SVI, V);
00930   }
00931 
00932   // If the LHS is a shufflevector itself, see if we can combine it with this
00933   // one without producing an unusual shuffle.
00934   // Cases that might be simplified:
00935   // 1.
00936   // x1=shuffle(v1,v2,mask1)
00937   //  x=shuffle(x1,undef,mask)
00938   //        ==>
00939   //  x=shuffle(v1,undef,newMask)
00940   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
00941   // 2.
00942   // x1=shuffle(v1,undef,mask1)
00943   //  x=shuffle(x1,x2,mask)
00944   // where v1.size() == mask1.size()
00945   //        ==>
00946   //  x=shuffle(v1,x2,newMask)
00947   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
00948   // 3.
00949   // x2=shuffle(v2,undef,mask2)
00950   //  x=shuffle(x1,x2,mask)
00951   // where v2.size() == mask2.size()
00952   //        ==>
00953   //  x=shuffle(x1,v2,newMask)
00954   // newMask[i] = (mask[i] < x1.size())
00955   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
00956   // 4.
00957   // x1=shuffle(v1,undef,mask1)
00958   // x2=shuffle(v2,undef,mask2)
00959   //  x=shuffle(x1,x2,mask)
00960   // where v1.size() == v2.size()
00961   //        ==>
00962   //  x=shuffle(v1,v2,newMask)
00963   // newMask[i] = (mask[i] < x1.size())
00964   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
00965   //
00966   // Here we are really conservative:
00967   // we are absolutely afraid of producing a shuffle mask not in the input
00968   // program, because the code gen may not be smart enough to turn a merged
00969   // shuffle into two specific shuffles: it may produce worse code.  As such,
00970   // we only merge two shuffles if the result is either a splat or one of the
00971   // input shuffle masks.  In this case, merging the shuffles just removes
00972   // one instruction, which we know is safe.  This is good for things like
00973   // turning: (splat(splat)) -> splat, or
00974   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
00975   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
00976   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
00977   if (LHSShuffle)
00978     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
00979       LHSShuffle = nullptr;
00980   if (RHSShuffle)
00981     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
00982       RHSShuffle = nullptr;
00983   if (!LHSShuffle && !RHSShuffle)
00984     return MadeChange ? &SVI : nullptr;
00985 
00986   Value* LHSOp0 = nullptr;
00987   Value* LHSOp1 = nullptr;
00988   Value* RHSOp0 = nullptr;
00989   unsigned LHSOp0Width = 0;
00990   unsigned RHSOp0Width = 0;
00991   if (LHSShuffle) {
00992     LHSOp0 = LHSShuffle->getOperand(0);
00993     LHSOp1 = LHSShuffle->getOperand(1);
00994     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
00995   }
00996   if (RHSShuffle) {
00997     RHSOp0 = RHSShuffle->getOperand(0);
00998     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
00999   }
01000   Value* newLHS = LHS;
01001   Value* newRHS = RHS;
01002   if (LHSShuffle) {
01003     // case 1
01004     if (isa<UndefValue>(RHS)) {
01005       newLHS = LHSOp0;
01006       newRHS = LHSOp1;
01007     }
01008     // case 2 or 4
01009     else if (LHSOp0Width == LHSWidth) {
01010       newLHS = LHSOp0;
01011     }
01012   }
01013   // case 3 or 4
01014   if (RHSShuffle && RHSOp0Width == LHSWidth) {
01015     newRHS = RHSOp0;
01016   }
01017   // case 4
01018   if (LHSOp0 == RHSOp0) {
01019     newLHS = LHSOp0;
01020     newRHS = nullptr;
01021   }
01022 
01023   if (newLHS == LHS && newRHS == RHS)
01024     return MadeChange ? &SVI : nullptr;
01025 
01026   SmallVector<int, 16> LHSMask;
01027   SmallVector<int, 16> RHSMask;
01028   if (newLHS != LHS)
01029     LHSMask = LHSShuffle->getShuffleMask();
01030   if (RHSShuffle && newRHS != RHS)
01031     RHSMask = RHSShuffle->getShuffleMask();
01032 
01033   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
01034   SmallVector<int, 16> newMask;
01035   bool isSplat = true;
01036   int SplatElt = -1;
01037   // Create a new mask for the new ShuffleVectorInst so that the new
01038   // ShuffleVectorInst is equivalent to the original one.
01039   for (unsigned i = 0; i < VWidth; ++i) {
01040     int eltMask;
01041     if (Mask[i] < 0) {
01042       // This element is an undef value.
01043       eltMask = -1;
01044     } else if (Mask[i] < (int)LHSWidth) {
01045       // This element is from left hand side vector operand.
01046       //
01047       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
01048       // new mask value for the element.
01049       if (newLHS != LHS) {
01050         eltMask = LHSMask[Mask[i]];
01051         // If the value selected is an undef value, explicitly specify it
01052         // with a -1 mask value.
01053         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
01054           eltMask = -1;
01055       } else
01056         eltMask = Mask[i];
01057     } else {
01058       // This element is from right hand side vector operand
01059       //
01060       // If the value selected is an undef value, explicitly specify it
01061       // with a -1 mask value. (case 1)
01062       if (isa<UndefValue>(RHS))
01063         eltMask = -1;
01064       // If RHS is going to be replaced (case 3 or 4), calculate the
01065       // new mask value for the element.
01066       else if (newRHS != RHS) {
01067         eltMask = RHSMask[Mask[i]-LHSWidth];
01068         // If the value selected is an undef value, explicitly specify it
01069         // with a -1 mask value.
01070         if (eltMask >= (int)RHSOp0Width) {
01071           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
01072                  && "should have been check above");
01073           eltMask = -1;
01074         }
01075       } else
01076         eltMask = Mask[i]-LHSWidth;
01077 
01078       // If LHS's width is changed, shift the mask value accordingly.
01079       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
01080       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
01081       // If newRHS == newLHS, we want to remap any references from newRHS to
01082       // newLHS so that we can properly identify splats that may occur due to
01083       // obfuscation across the two vectors.
01084       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
01085         eltMask += newLHSWidth;
01086     }
01087 
01088     // Check if this could still be a splat.
01089     if (eltMask >= 0) {
01090       if (SplatElt >= 0 && SplatElt != eltMask)
01091         isSplat = false;
01092       SplatElt = eltMask;
01093     }
01094 
01095     newMask.push_back(eltMask);
01096   }
01097 
01098   // If the result mask is equal to one of the original shuffle masks,
01099   // or is a splat, do the replacement.
01100   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
01101     SmallVector<Constant*, 16> Elts;
01102     Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
01103     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
01104       if (newMask[i] < 0) {
01105         Elts.push_back(UndefValue::get(Int32Ty));
01106       } else {
01107         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
01108       }
01109     }
01110     if (!newRHS)
01111       newRHS = UndefValue::get(newLHS->getType());
01112     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
01113   }
01114 
01115   // If the result mask is an identity, replace uses of this instruction with
01116   // corresponding argument.
01117   bool isLHSID, isRHSID;
01118   RecognizeIdentityMask(newMask, isLHSID, isRHSID);
01119   if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
01120   if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
01121 
01122   return MadeChange ? &SVI : nullptr;
01123 }