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 0;
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 = 0; Constant *Con = 0;
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 0;
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 NULL;
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 NULL;
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 0;
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       // Okay, we can handle this if the vector we are insertinting 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           // Okay, we can handle this if the vector we are insertinting 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 an 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 == 0) {
00446           Value *RHS = EI->getOperand(0);
00447           ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
00448           assert(LR.second == 0 || 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 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
00494   Value *VecOp    = IE.getOperand(0);
00495   Value *ScalarOp = IE.getOperand(1);
00496   Value *IdxOp    = IE.getOperand(2);
00497 
00498   // Inserting an undef or into an undefined place, remove this.
00499   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
00500     ReplaceInstUsesWith(IE, VecOp);
00501 
00502   // If the inserted element was extracted from some other vector, and if the
00503   // indexes are constant, try to turn this into a shufflevector operation.
00504   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
00505     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
00506       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
00507       unsigned NumExtractVectorElts =
00508           EI->getOperand(0)->getType()->getVectorNumElements();
00509       unsigned ExtractedIdx =
00510         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
00511       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
00512 
00513       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
00514         return ReplaceInstUsesWith(IE, VecOp);
00515 
00516       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
00517         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
00518 
00519       // If we are extracting a value from a vector, then inserting it right
00520       // back into the same place, just use the input vector.
00521       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
00522         return ReplaceInstUsesWith(IE, VecOp);
00523 
00524       // If this insertelement isn't used by some other insertelement, turn it
00525       // (and any insertelements it points to), into one big shuffle.
00526       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
00527         SmallVector<Constant*, 16> Mask;
00528         ShuffleOps LR = CollectShuffleElements(&IE, Mask, 0);
00529 
00530         // The proposed shuffle may be trivial, in which case we shouldn't
00531         // perform the combine.
00532         if (LR.first != &IE && LR.second != &IE) {
00533           // We now have a shuffle of LHS, RHS, Mask.
00534           if (LR.second == 0) LR.second = UndefValue::get(LR.first->getType());
00535           return new ShuffleVectorInst(LR.first, LR.second,
00536                                        ConstantVector::get(Mask));
00537         }
00538       }
00539     }
00540   }
00541 
00542   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
00543   APInt UndefElts(VWidth, 0);
00544   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00545   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
00546     if (V != &IE)
00547       return ReplaceInstUsesWith(IE, V);
00548     return &IE;
00549   }
00550 
00551   return 0;
00552 }
00553 
00554 /// Return true if we can evaluate the specified expression tree if the vector
00555 /// elements were shuffled in a different order.
00556 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
00557                                 unsigned Depth = 5) {
00558   // We can always reorder the elements of a constant.
00559   if (isa<Constant>(V))
00560     return true;
00561 
00562   // We won't reorder vector arguments. No IPO here.
00563   Instruction *I = dyn_cast<Instruction>(V);
00564   if (!I) return false;
00565 
00566   // Two users may expect different orders of the elements. Don't try it.
00567   if (!I->hasOneUse())
00568     return false;
00569 
00570   if (Depth == 0) return false;
00571 
00572   switch (I->getOpcode()) {
00573     case Instruction::Add:
00574     case Instruction::FAdd:
00575     case Instruction::Sub:
00576     case Instruction::FSub:
00577     case Instruction::Mul:
00578     case Instruction::FMul:
00579     case Instruction::UDiv:
00580     case Instruction::SDiv:
00581     case Instruction::FDiv:
00582     case Instruction::URem:
00583     case Instruction::SRem:
00584     case Instruction::FRem:
00585     case Instruction::Shl:
00586     case Instruction::LShr:
00587     case Instruction::AShr:
00588     case Instruction::And:
00589     case Instruction::Or:
00590     case Instruction::Xor:
00591     case Instruction::ICmp:
00592     case Instruction::FCmp:
00593     case Instruction::Trunc:
00594     case Instruction::ZExt:
00595     case Instruction::SExt:
00596     case Instruction::FPToUI:
00597     case Instruction::FPToSI:
00598     case Instruction::UIToFP:
00599     case Instruction::SIToFP:
00600     case Instruction::FPTrunc:
00601     case Instruction::FPExt:
00602     case Instruction::GetElementPtr: {
00603       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
00604         if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
00605           return false;
00606       }
00607       return true;
00608     }
00609     case Instruction::InsertElement: {
00610       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
00611       if (!CI) return false;
00612       int ElementNumber = CI->getLimitedValue();
00613 
00614       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
00615       // can't put an element into multiple indices.
00616       bool SeenOnce = false;
00617       for (int i = 0, e = Mask.size(); i != e; ++i) {
00618         if (Mask[i] == ElementNumber) {
00619           if (SeenOnce)
00620             return false;
00621           SeenOnce = true;
00622         }
00623       }
00624       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
00625     }
00626   }
00627   return false;
00628 }
00629 
00630 /// Rebuild a new instruction just like 'I' but with the new operands given.
00631 /// In the event of type mismatch, the type of the operands is correct.
00632 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
00633   // We don't want to use the IRBuilder here because we want the replacement
00634   // instructions to appear next to 'I', not the builder's insertion point.
00635   switch (I->getOpcode()) {
00636     case Instruction::Add:
00637     case Instruction::FAdd:
00638     case Instruction::Sub:
00639     case Instruction::FSub:
00640     case Instruction::Mul:
00641     case Instruction::FMul:
00642     case Instruction::UDiv:
00643     case Instruction::SDiv:
00644     case Instruction::FDiv:
00645     case Instruction::URem:
00646     case Instruction::SRem:
00647     case Instruction::FRem:
00648     case Instruction::Shl:
00649     case Instruction::LShr:
00650     case Instruction::AShr:
00651     case Instruction::And:
00652     case Instruction::Or:
00653     case Instruction::Xor: {
00654       BinaryOperator *BO = cast<BinaryOperator>(I);
00655       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
00656       BinaryOperator *New =
00657           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
00658                                  NewOps[0], NewOps[1], "", BO);
00659       if (isa<OverflowingBinaryOperator>(BO)) {
00660         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
00661         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
00662       }
00663       if (isa<PossiblyExactOperator>(BO)) {
00664         New->setIsExact(BO->isExact());
00665       }
00666       if (isa<FPMathOperator>(BO))
00667         New->copyFastMathFlags(I);
00668       return New;
00669     }
00670     case Instruction::ICmp:
00671       assert(NewOps.size() == 2 && "icmp with #ops != 2");
00672       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
00673                           NewOps[0], NewOps[1]);
00674     case Instruction::FCmp:
00675       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
00676       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
00677                           NewOps[0], NewOps[1]);
00678     case Instruction::Trunc:
00679     case Instruction::ZExt:
00680     case Instruction::SExt:
00681     case Instruction::FPToUI:
00682     case Instruction::FPToSI:
00683     case Instruction::UIToFP:
00684     case Instruction::SIToFP:
00685     case Instruction::FPTrunc:
00686     case Instruction::FPExt: {
00687       // It's possible that the mask has a different number of elements from
00688       // the original cast. We recompute the destination type to match the mask.
00689       Type *DestTy =
00690           VectorType::get(I->getType()->getScalarType(),
00691                           NewOps[0]->getType()->getVectorNumElements());
00692       assert(NewOps.size() == 1 && "cast with #ops != 1");
00693       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
00694                               "", I);
00695     }
00696     case Instruction::GetElementPtr: {
00697       Value *Ptr = NewOps[0];
00698       ArrayRef<Value*> Idx = NewOps.slice(1);
00699       GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
00700       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
00701       return GEP;
00702     }
00703   }
00704   llvm_unreachable("failed to rebuild vector instructions");
00705 }
00706 
00707 Value *
00708 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
00709   // Mask.size() does not need to be equal to the number of vector elements.
00710 
00711   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
00712   if (isa<UndefValue>(V)) {
00713     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
00714                                            Mask.size()));
00715   }
00716   if (isa<ConstantAggregateZero>(V)) {
00717     return ConstantAggregateZero::get(
00718                VectorType::get(V->getType()->getScalarType(),
00719                                Mask.size()));
00720   }
00721   if (Constant *C = dyn_cast<Constant>(V)) {
00722     SmallVector<Constant *, 16> MaskValues;
00723     for (int i = 0, e = Mask.size(); i != e; ++i) {
00724       if (Mask[i] == -1)
00725         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
00726       else
00727         MaskValues.push_back(Builder->getInt32(Mask[i]));
00728     }
00729     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
00730                                           ConstantVector::get(MaskValues));
00731   }
00732 
00733   Instruction *I = cast<Instruction>(V);
00734   switch (I->getOpcode()) {
00735     case Instruction::Add:
00736     case Instruction::FAdd:
00737     case Instruction::Sub:
00738     case Instruction::FSub:
00739     case Instruction::Mul:
00740     case Instruction::FMul:
00741     case Instruction::UDiv:
00742     case Instruction::SDiv:
00743     case Instruction::FDiv:
00744     case Instruction::URem:
00745     case Instruction::SRem:
00746     case Instruction::FRem:
00747     case Instruction::Shl:
00748     case Instruction::LShr:
00749     case Instruction::AShr:
00750     case Instruction::And:
00751     case Instruction::Or:
00752     case Instruction::Xor:
00753     case Instruction::ICmp:
00754     case Instruction::FCmp:
00755     case Instruction::Trunc:
00756     case Instruction::ZExt:
00757     case Instruction::SExt:
00758     case Instruction::FPToUI:
00759     case Instruction::FPToSI:
00760     case Instruction::UIToFP:
00761     case Instruction::SIToFP:
00762     case Instruction::FPTrunc:
00763     case Instruction::FPExt:
00764     case Instruction::Select:
00765     case Instruction::GetElementPtr: {
00766       SmallVector<Value*, 8> NewOps;
00767       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
00768       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
00769         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
00770         NewOps.push_back(V);
00771         NeedsRebuild |= (V != I->getOperand(i));
00772       }
00773       if (NeedsRebuild) {
00774         return BuildNew(I, NewOps);
00775       }
00776       return I;
00777     }
00778     case Instruction::InsertElement: {
00779       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
00780 
00781       // The insertelement was inserting at Element. Figure out which element
00782       // that becomes after shuffling. The answer is guaranteed to be unique
00783       // by CanEvaluateShuffled.
00784       bool Found = false;
00785       int Index = 0;
00786       for (int e = Mask.size(); Index != e; ++Index) {
00787         if (Mask[Index] == Element) {
00788           Found = true;
00789           break;
00790         }
00791       }
00792 
00793       // If element is not in Mask, no need to handle the operand 1 (element to
00794       // be inserted). Just evaluate values in operand 0 according to Mask.
00795       if (!Found)
00796         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00797 
00798       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
00799       return InsertElementInst::Create(V, I->getOperand(1),
00800                                        Builder->getInt32(Index), "", I);
00801     }
00802   }
00803   llvm_unreachable("failed to reorder elements of vector instruction!");
00804 }
00805 
00806 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
00807   Value *LHS = SVI.getOperand(0);
00808   Value *RHS = SVI.getOperand(1);
00809   SmallVector<int, 16> Mask = SVI.getShuffleMask();
00810 
00811   bool MadeChange = false;
00812 
00813   // Undefined shuffle mask -> undefined value.
00814   if (isa<UndefValue>(SVI.getOperand(2)))
00815     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
00816 
00817   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
00818 
00819   APInt UndefElts(VWidth, 0);
00820   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
00821   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
00822     if (V != &SVI)
00823       return ReplaceInstUsesWith(SVI, V);
00824     LHS = SVI.getOperand(0);
00825     RHS = SVI.getOperand(1);
00826     MadeChange = true;
00827   }
00828 
00829   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
00830 
00831   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
00832   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
00833   if (LHS == RHS || isa<UndefValue>(LHS)) {
00834     if (isa<UndefValue>(LHS) && LHS == RHS) {
00835       // shuffle(undef,undef,mask) -> undef.
00836       Value *Result = (VWidth == LHSWidth)
00837                       ? LHS : UndefValue::get(SVI.getType());
00838       return ReplaceInstUsesWith(SVI, Result);
00839     }
00840 
00841     // Remap any references to RHS to use LHS.
00842     SmallVector<Constant*, 16> Elts;
00843     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
00844       if (Mask[i] < 0) {
00845         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
00846         continue;
00847       }
00848 
00849       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
00850           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
00851         Mask[i] = -1;     // Turn into undef.
00852         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
00853       } else {
00854         Mask[i] = Mask[i] % e;  // Force to LHS.
00855         Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
00856                                         Mask[i]));
00857       }
00858     }
00859     SVI.setOperand(0, SVI.getOperand(1));
00860     SVI.setOperand(1, UndefValue::get(RHS->getType()));
00861     SVI.setOperand(2, ConstantVector::get(Elts));
00862     LHS = SVI.getOperand(0);
00863     RHS = SVI.getOperand(1);
00864     MadeChange = true;
00865   }
00866 
00867   if (VWidth == LHSWidth) {
00868     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
00869     bool isLHSID = true, isRHSID = true;
00870 
00871     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
00872       if (Mask[i] < 0) continue;  // Ignore undef values.
00873       // Is this an identity shuffle of the LHS value?
00874       isLHSID &= (Mask[i] == (int)i);
00875 
00876       // Is this an identity shuffle of the RHS value?
00877       isRHSID &= (Mask[i]-e == i);
00878     }
00879 
00880     // Eliminate identity shuffles.
00881     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
00882     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
00883   }
00884 
00885   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
00886     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
00887     return ReplaceInstUsesWith(SVI, V);
00888   }
00889 
00890   // If the LHS is a shufflevector itself, see if we can combine it with this
00891   // one without producing an unusual shuffle.
00892   // Cases that might be simplified:
00893   // 1.
00894   // x1=shuffle(v1,v2,mask1)
00895   //  x=shuffle(x1,undef,mask)
00896   //        ==>
00897   //  x=shuffle(v1,undef,newMask)
00898   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
00899   // 2.
00900   // x1=shuffle(v1,undef,mask1)
00901   //  x=shuffle(x1,x2,mask)
00902   // where v1.size() == mask1.size()
00903   //        ==>
00904   //  x=shuffle(v1,x2,newMask)
00905   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
00906   // 3.
00907   // x2=shuffle(v2,undef,mask2)
00908   //  x=shuffle(x1,x2,mask)
00909   // where v2.size() == mask2.size()
00910   //        ==>
00911   //  x=shuffle(x1,v2,newMask)
00912   // newMask[i] = (mask[i] < x1.size())
00913   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
00914   // 4.
00915   // x1=shuffle(v1,undef,mask1)
00916   // x2=shuffle(v2,undef,mask2)
00917   //  x=shuffle(x1,x2,mask)
00918   // where v1.size() == v2.size()
00919   //        ==>
00920   //  x=shuffle(v1,v2,newMask)
00921   // newMask[i] = (mask[i] < x1.size())
00922   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
00923   //
00924   // Here we are really conservative:
00925   // we are absolutely afraid of producing a shuffle mask not in the input
00926   // program, because the code gen may not be smart enough to turn a merged
00927   // shuffle into two specific shuffles: it may produce worse code.  As such,
00928   // we only merge two shuffles if the result is either a splat or one of the
00929   // input shuffle masks.  In this case, merging the shuffles just removes
00930   // one instruction, which we know is safe.  This is good for things like
00931   // turning: (splat(splat)) -> splat, or
00932   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
00933   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
00934   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
00935   if (LHSShuffle)
00936     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
00937       LHSShuffle = NULL;
00938   if (RHSShuffle)
00939     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
00940       RHSShuffle = NULL;
00941   if (!LHSShuffle && !RHSShuffle)
00942     return MadeChange ? &SVI : 0;
00943 
00944   Value* LHSOp0 = NULL;
00945   Value* LHSOp1 = NULL;
00946   Value* RHSOp0 = NULL;
00947   unsigned LHSOp0Width = 0;
00948   unsigned RHSOp0Width = 0;
00949   if (LHSShuffle) {
00950     LHSOp0 = LHSShuffle->getOperand(0);
00951     LHSOp1 = LHSShuffle->getOperand(1);
00952     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
00953   }
00954   if (RHSShuffle) {
00955     RHSOp0 = RHSShuffle->getOperand(0);
00956     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
00957   }
00958   Value* newLHS = LHS;
00959   Value* newRHS = RHS;
00960   if (LHSShuffle) {
00961     // case 1
00962     if (isa<UndefValue>(RHS)) {
00963       newLHS = LHSOp0;
00964       newRHS = LHSOp1;
00965     }
00966     // case 2 or 4
00967     else if (LHSOp0Width == LHSWidth) {
00968       newLHS = LHSOp0;
00969     }
00970   }
00971   // case 3 or 4
00972   if (RHSShuffle && RHSOp0Width == LHSWidth) {
00973     newRHS = RHSOp0;
00974   }
00975   // case 4
00976   if (LHSOp0 == RHSOp0) {
00977     newLHS = LHSOp0;
00978     newRHS = NULL;
00979   }
00980 
00981   if (newLHS == LHS && newRHS == RHS)
00982     return MadeChange ? &SVI : 0;
00983 
00984   SmallVector<int, 16> LHSMask;
00985   SmallVector<int, 16> RHSMask;
00986   if (newLHS != LHS)
00987     LHSMask = LHSShuffle->getShuffleMask();
00988   if (RHSShuffle && newRHS != RHS)
00989     RHSMask = RHSShuffle->getShuffleMask();
00990 
00991   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
00992   SmallVector<int, 16> newMask;
00993   bool isSplat = true;
00994   int SplatElt = -1;
00995   // Create a new mask for the new ShuffleVectorInst so that the new
00996   // ShuffleVectorInst is equivalent to the original one.
00997   for (unsigned i = 0; i < VWidth; ++i) {
00998     int eltMask;
00999     if (Mask[i] < 0) {
01000       // This element is an undef value.
01001       eltMask = -1;
01002     } else if (Mask[i] < (int)LHSWidth) {
01003       // This element is from left hand side vector operand.
01004       //
01005       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
01006       // new mask value for the element.
01007       if (newLHS != LHS) {
01008         eltMask = LHSMask[Mask[i]];
01009         // If the value selected is an undef value, explicitly specify it
01010         // with a -1 mask value.
01011         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
01012           eltMask = -1;
01013       } else
01014         eltMask = Mask[i];
01015     } else {
01016       // This element is from right hand side vector operand
01017       //
01018       // If the value selected is an undef value, explicitly specify it
01019       // with a -1 mask value. (case 1)
01020       if (isa<UndefValue>(RHS))
01021         eltMask = -1;
01022       // If RHS is going to be replaced (case 3 or 4), calculate the
01023       // new mask value for the element.
01024       else if (newRHS != RHS) {
01025         eltMask = RHSMask[Mask[i]-LHSWidth];
01026         // If the value selected is an undef value, explicitly specify it
01027         // with a -1 mask value.
01028         if (eltMask >= (int)RHSOp0Width) {
01029           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
01030                  && "should have been check above");
01031           eltMask = -1;
01032         }
01033       } else
01034         eltMask = Mask[i]-LHSWidth;
01035 
01036       // If LHS's width is changed, shift the mask value accordingly.
01037       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
01038       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
01039       // If newRHS == newLHS, we want to remap any references from newRHS to
01040       // newLHS so that we can properly identify splats that may occur due to
01041       // obfuscation across the two vectors.
01042       if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
01043         eltMask += newLHSWidth;
01044     }
01045 
01046     // Check if this could still be a splat.
01047     if (eltMask >= 0) {
01048       if (SplatElt >= 0 && SplatElt != eltMask)
01049         isSplat = false;
01050       SplatElt = eltMask;
01051     }
01052 
01053     newMask.push_back(eltMask);
01054   }
01055 
01056   // If the result mask is equal to one of the original shuffle masks,
01057   // or is a splat, do the replacement.
01058   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
01059     SmallVector<Constant*, 16> Elts;
01060     Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
01061     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
01062       if (newMask[i] < 0) {
01063         Elts.push_back(UndefValue::get(Int32Ty));
01064       } else {
01065         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
01066       }
01067     }
01068     if (newRHS == NULL)
01069       newRHS = UndefValue::get(newLHS->getType());
01070     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
01071   }
01072 
01073   return MadeChange ? &SVI : 0;
01074 }