1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements instcombine for ExtractElement, InsertElement and
13 //===----------------------------------------------------------------------===//
15 #include "InstCombine.h"
16 #include "llvm/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
21 /// is to leave as a vector operation. isConstant indicates whether we're
22 /// extracting one known element. If false we're extracting a variable index.
23 static bool CheapToScalarize(Value *V, bool isConstant) {
24 if (Constant *C = dyn_cast<Constant>(V)) {
25 if (isConstant) return true;
27 // If all elts are the same, we can extract it and use any of the values.
28 Constant *Op0 = C->getAggregateElement(0U);
29 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; ++i)
30 if (C->getAggregateElement(i) != Op0)
34 Instruction *I = dyn_cast<Instruction>(V);
37 // Insert element gets simplified to the inserted element or is deleted if
38 // this is constant idx extract element and its a constant idx insertelt.
39 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
40 isa<ConstantInt>(I->getOperand(2)))
42 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
44 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
45 if (BO->hasOneUse() &&
46 (CheapToScalarize(BO->getOperand(0), isConstant) ||
47 CheapToScalarize(BO->getOperand(1), isConstant)))
49 if (CmpInst *CI = dyn_cast<CmpInst>(I))
50 if (CI->hasOneUse() &&
51 (CheapToScalarize(CI->getOperand(0), isConstant) ||
52 CheapToScalarize(CI->getOperand(1), isConstant)))
58 /// FindScalarElement - Given a vector and an element number, see if the scalar
59 /// value is already around as a register, for example if it were inserted then
60 /// extracted from the vector.
61 static Value *FindScalarElement(Value *V, unsigned EltNo) {
62 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
63 VectorType *VTy = cast<VectorType>(V->getType());
64 unsigned Width = VTy->getNumElements();
65 if (EltNo >= Width) // Out of range access.
66 return UndefValue::get(VTy->getElementType());
68 if (Constant *C = dyn_cast<Constant>(V))
69 return C->getAggregateElement(EltNo);
71 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
72 // If this is an insert to a variable element, we don't know what it is.
73 if (!isa<ConstantInt>(III->getOperand(2)))
75 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
77 // If this is an insert to the element we are looking for, return the
80 return III->getOperand(1);
82 // Otherwise, the insertelement doesn't modify the value, recurse on its
84 return FindScalarElement(III->getOperand(0), EltNo);
87 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
88 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
89 int InEl = SVI->getMaskValue(EltNo);
91 return UndefValue::get(VTy->getElementType());
92 if (InEl < (int)LHSWidth)
93 return FindScalarElement(SVI->getOperand(0), InEl);
94 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
97 // Extract a value from a vector add operation with a constant zero.
98 Value *Val = 0; Constant *Con = 0;
99 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
100 if (Con->getAggregateElement(EltNo)->isNullValue())
101 return FindScalarElement(Val, EltNo);
104 // Otherwise, we don't know.
108 // If we have a PHI node with a vector type that has only 2 uses: feed
109 // itself and be an operand of extractelemnt at a constant location,
110 // try to replace the PHI of the vector type with a PHI of a scalar type
111 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
112 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
113 if (!PN->hasNUses(2))
116 // If so, it's known at this point that one operand is PHI and the other is
117 // an extractelement node. Find the PHI user that is not the extractelement
119 Value::use_iterator iu = PN->use_begin();
120 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
121 if (PHIUser == cast<Instruction>(&EI))
122 PHIUser = cast<Instruction>(*(++iu));
124 // Verify that this PHI user has one use, which is the PHI itself,
125 // and that it is a binary operation which is cheap to scalarize.
126 // otherwise return NULL.
127 if (!PHIUser->hasOneUse() || !(PHIUser->use_back() == PN) ||
128 !(isa<BinaryOperator>(PHIUser)) ||
129 !CheapToScalarize(PHIUser, true))
132 // Create a scalar PHI node that will replace the vector PHI node
133 // just before the current PHI node.
134 PHINode * scalarPHI = cast<PHINode>(
135 InsertNewInstWith(PHINode::Create(EI.getType(),
136 PN->getNumIncomingValues(), ""), *PN));
137 // Scalarize each PHI operand.
138 for (unsigned i=0; i < PN->getNumIncomingValues(); i++) {
139 Value *PHIInVal = PN->getIncomingValue(i);
140 BasicBlock *inBB = PN->getIncomingBlock(i);
141 Value *Elt = EI.getIndexOperand();
142 // If the operand is the PHI induction variable:
143 if (PHIInVal == PHIUser) {
144 // Scalarize the binary operation. Its first operand is the
145 // scalar PHI and the second operand is extracted from the other
147 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
148 unsigned opId = (B0->getOperand(0) == PN) ? 1: 0;
149 Value *Op = InsertNewInstWith(
150 ExtractElementInst::Create(B0->getOperand(opId), Elt,
151 B0->getOperand(opId)->getName() + ".Elt"),
153 Value *newPHIUser = InsertNewInstWith(
154 BinaryOperator::Create(B0->getOpcode(), scalarPHI,Op),
156 scalarPHI->addIncoming(newPHIUser, inBB);
158 // Scalarize PHI input:
160 ExtractElementInst::Create(PHIInVal, Elt, "");
161 // Insert the new instruction into the predecessor basic block.
162 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
163 BasicBlock::iterator InsertPos;
164 if (pos && !isa<PHINode>(pos)) {
168 InsertPos = inBB->getFirstInsertionPt();
171 InsertNewInstWith(newEI, *InsertPos);
173 scalarPHI->addIncoming(newEI, inBB);
176 return ReplaceInstUsesWith(EI, scalarPHI);
179 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
180 // If vector val is constant with all elements the same, replace EI with
181 // that element. We handle a known element # below.
182 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
183 if (CheapToScalarize(C, false))
184 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
186 // If extracting a specified index from the vector, see if we can recursively
187 // find a previously computed scalar that was inserted into the vector.
188 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
189 unsigned IndexVal = IdxC->getZExtValue();
190 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
192 // If this is extracting an invalid index, turn this into undef, to avoid
193 // crashing the code below.
194 if (IndexVal >= VectorWidth)
195 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
197 // This instruction only demands the single element from the input vector.
198 // If the input vector has a single use, simplify it based on this use
200 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
201 APInt UndefElts(VectorWidth, 0);
202 APInt DemandedMask(VectorWidth, 0);
203 DemandedMask.setBit(IndexVal);
204 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
205 DemandedMask, UndefElts)) {
211 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
212 return ReplaceInstUsesWith(EI, Elt);
214 // If the this extractelement is directly using a bitcast from a vector of
215 // the same number of elements, see if we can find the source element from
216 // it. In this case, we will end up needing to bitcast the scalars.
217 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
218 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
219 if (VT->getNumElements() == VectorWidth)
220 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
221 return new BitCastInst(Elt, EI.getType());
224 // If there's a vector PHI feeding a scalar use through this extractelement
225 // instruction, try to scalarize the PHI.
226 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
227 Instruction *scalarPHI = scalarizePHI(EI, PN);
233 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
234 // Push extractelement into predecessor operation if legal and
235 // profitable to do so
236 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
237 if (I->hasOneUse() &&
238 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
240 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
241 EI.getName()+".lhs");
243 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
244 EI.getName()+".rhs");
245 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
247 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
248 // Extracting the inserted element?
249 if (IE->getOperand(2) == EI.getOperand(1))
250 return ReplaceInstUsesWith(EI, IE->getOperand(1));
251 // If the inserted and extracted elements are constants, they must not
252 // be the same value, extract from the pre-inserted value instead.
253 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
254 Worklist.AddValue(EI.getOperand(0));
255 EI.setOperand(0, IE->getOperand(0));
258 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
259 // If this is extracting an element from a shufflevector, figure out where
260 // it came from and extract from the appropriate input element instead.
261 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
262 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
265 SVI->getOperand(0)->getType()->getVectorNumElements();
268 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
269 if (SrcIdx < (int)LHSWidth)
270 Src = SVI->getOperand(0);
273 Src = SVI->getOperand(1);
275 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
276 return ExtractElementInst::Create(Src,
277 ConstantInt::get(Int32Ty,
280 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
281 // Canonicalize extractelement(cast) -> cast(extractelement)
282 // bitcasts can change the number of vector elements and they cost nothing
283 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
284 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
285 EI.getIndexOperand());
286 Worklist.AddValue(EE);
287 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
294 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
295 /// elements from either LHS or RHS, return the shuffle mask and true.
296 /// Otherwise, return false.
297 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
298 SmallVectorImpl<Constant*> &Mask) {
299 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
300 "Invalid CollectSingleShuffleElements");
301 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
303 if (isa<UndefValue>(V)) {
304 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
309 for (unsigned i = 0; i != NumElts; ++i)
310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
315 for (unsigned i = 0; i != NumElts; ++i)
316 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
321 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
322 // If this is an insert of an extract from some other vector, include it.
323 Value *VecOp = IEI->getOperand(0);
324 Value *ScalarOp = IEI->getOperand(1);
325 Value *IdxOp = IEI->getOperand(2);
327 if (!isa<ConstantInt>(IdxOp))
329 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
331 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
332 // Okay, we can handle this if the vector we are insertinting into is
334 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
335 // If so, update the mask to reflect the inserted undef.
336 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
339 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
340 if (isa<ConstantInt>(EI->getOperand(1)) &&
341 EI->getOperand(0)->getType() == V->getType()) {
342 unsigned ExtractedIdx =
343 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
345 // This must be extracting from either LHS or RHS.
346 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
347 // Okay, we can handle this if the vector we are insertinting into is
349 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
350 // If so, update the mask to reflect the inserted value.
351 if (EI->getOperand(0) == LHS) {
352 Mask[InsertedIdx % NumElts] =
353 ConstantInt::get(Type::getInt32Ty(V->getContext()),
356 assert(EI->getOperand(0) == RHS);
357 Mask[InsertedIdx % NumElts] =
358 ConstantInt::get(Type::getInt32Ty(V->getContext()),
359 ExtractedIdx+NumElts);
367 // TODO: Handle shufflevector here!
372 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
373 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
374 /// that computes V and the LHS value of the shuffle.
375 static Value *CollectShuffleElements(Value *V, SmallVectorImpl<Constant*> &Mask,
377 assert(V->getType()->isVectorTy() &&
378 (RHS == 0 || V->getType() == RHS->getType()) &&
380 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
382 if (isa<UndefValue>(V)) {
383 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
387 if (isa<ConstantAggregateZero>(V)) {
388 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
392 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
393 // If this is an insert of an extract from some other vector, include it.
394 Value *VecOp = IEI->getOperand(0);
395 Value *ScalarOp = IEI->getOperand(1);
396 Value *IdxOp = IEI->getOperand(2);
398 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
399 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
400 EI->getOperand(0)->getType() == V->getType()) {
401 unsigned ExtractedIdx =
402 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
403 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
405 // Either the extracted from or inserted into vector must be RHSVec,
406 // otherwise we'd end up with a shuffle of three inputs.
407 if (EI->getOperand(0) == RHS || RHS == 0) {
408 RHS = EI->getOperand(0);
409 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
410 Mask[InsertedIdx % NumElts] =
411 ConstantInt::get(Type::getInt32Ty(V->getContext()),
412 NumElts+ExtractedIdx);
417 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
418 // Update Mask to reflect that `ScalarOp' has been inserted at
419 // position `InsertedIdx' within the vector returned by IEI.
420 Mask[InsertedIdx % NumElts] = Mask[ExtractedIdx];
422 // Everything but the extracted element is replaced with the RHS.
423 for (unsigned i = 0; i != NumElts; ++i) {
424 if (i != InsertedIdx)
425 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
431 // If this insertelement is a chain that comes from exactly these two
432 // vectors, return the vector and the effective shuffle.
433 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
434 return EI->getOperand(0);
438 // TODO: Handle shufflevector here!
440 // Otherwise, can't do anything fancy. Return an identity vector.
441 for (unsigned i = 0; i != NumElts; ++i)
442 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
446 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
447 Value *VecOp = IE.getOperand(0);
448 Value *ScalarOp = IE.getOperand(1);
449 Value *IdxOp = IE.getOperand(2);
451 // Inserting an undef or into an undefined place, remove this.
452 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
453 ReplaceInstUsesWith(IE, VecOp);
455 // If the inserted element was extracted from some other vector, and if the
456 // indexes are constant, try to turn this into a shufflevector operation.
457 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
458 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
459 EI->getOperand(0)->getType() == IE.getType()) {
460 unsigned NumVectorElts = IE.getType()->getNumElements();
461 unsigned ExtractedIdx =
462 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
463 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
465 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
466 return ReplaceInstUsesWith(IE, VecOp);
468 if (InsertedIdx >= NumVectorElts) // Out of range insert.
469 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
471 // If we are extracting a value from a vector, then inserting it right
472 // back into the same place, just use the input vector.
473 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
474 return ReplaceInstUsesWith(IE, VecOp);
476 // If this insertelement isn't used by some other insertelement, turn it
477 // (and any insertelements it points to), into one big shuffle.
478 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
479 SmallVector<Constant*, 16> Mask;
481 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
482 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
483 // We now have a shuffle of LHS, RHS, Mask.
484 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
489 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
490 APInt UndefElts(VWidth, 0);
491 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
492 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
494 return ReplaceInstUsesWith(IE, V);
502 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
503 Value *LHS = SVI.getOperand(0);
504 Value *RHS = SVI.getOperand(1);
505 SmallVector<int, 16> Mask = SVI.getShuffleMask();
507 bool MadeChange = false;
509 // Undefined shuffle mask -> undefined value.
510 if (isa<UndefValue>(SVI.getOperand(2)))
511 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
513 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
515 APInt UndefElts(VWidth, 0);
516 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
517 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
519 return ReplaceInstUsesWith(SVI, V);
520 LHS = SVI.getOperand(0);
521 RHS = SVI.getOperand(1);
525 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
527 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
528 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
529 if (LHS == RHS || isa<UndefValue>(LHS)) {
530 if (isa<UndefValue>(LHS) && LHS == RHS) {
531 // shuffle(undef,undef,mask) -> undef.
532 Value* result = (VWidth == LHSWidth)
533 ? LHS : UndefValue::get(SVI.getType());
534 return ReplaceInstUsesWith(SVI, result);
537 // Remap any references to RHS to use LHS.
538 SmallVector<Constant*, 16> Elts;
539 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
541 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
545 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
546 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
547 Mask[i] = -1; // Turn into undef.
548 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
550 Mask[i] = Mask[i] % e; // Force to LHS.
551 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
555 SVI.setOperand(0, SVI.getOperand(1));
556 SVI.setOperand(1, UndefValue::get(RHS->getType()));
557 SVI.setOperand(2, ConstantVector::get(Elts));
558 LHS = SVI.getOperand(0);
559 RHS = SVI.getOperand(1);
563 if (VWidth == LHSWidth) {
564 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
565 bool isLHSID = true, isRHSID = true;
567 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
568 if (Mask[i] < 0) continue; // Ignore undef values.
569 // Is this an identity shuffle of the LHS value?
570 isLHSID &= (Mask[i] == (int)i);
572 // Is this an identity shuffle of the RHS value?
573 isRHSID &= (Mask[i]-e == i);
576 // Eliminate identity shuffles.
577 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
578 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
581 // If the LHS is a shufflevector itself, see if we can combine it with this
582 // one without producing an unusual shuffle.
583 // Cases that might be simplified:
585 // x1=shuffle(v1,v2,mask1)
586 // x=shuffle(x1,undef,mask)
588 // x=shuffle(v1,undef,newMask)
589 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
591 // x1=shuffle(v1,undef,mask1)
592 // x=shuffle(x1,x2,mask)
593 // where v1.size() == mask1.size()
595 // x=shuffle(v1,x2,newMask)
596 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
598 // x2=shuffle(v2,undef,mask2)
599 // x=shuffle(x1,x2,mask)
600 // where v2.size() == mask2.size()
602 // x=shuffle(x1,v2,newMask)
603 // newMask[i] = (mask[i] < x1.size())
604 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
606 // x1=shuffle(v1,undef,mask1)
607 // x2=shuffle(v2,undef,mask2)
608 // x=shuffle(x1,x2,mask)
609 // where v1.size() == v2.size()
611 // x=shuffle(v1,v2,newMask)
612 // newMask[i] = (mask[i] < x1.size())
613 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
615 // Here we are really conservative:
616 // we are absolutely afraid of producing a shuffle mask not in the input
617 // program, because the code gen may not be smart enough to turn a merged
618 // shuffle into two specific shuffles: it may produce worse code. As such,
619 // we only merge two shuffles if the result is either a splat or one of the
620 // input shuffle masks. In this case, merging the shuffles just removes
621 // one instruction, which we know is safe. This is good for things like
622 // turning: (splat(splat)) -> splat, or
623 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
624 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
625 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
627 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
630 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
632 if (!LHSShuffle && !RHSShuffle)
633 return MadeChange ? &SVI : 0;
635 Value* LHSOp0 = NULL;
636 Value* LHSOp1 = NULL;
637 Value* RHSOp0 = NULL;
638 unsigned LHSOp0Width = 0;
639 unsigned RHSOp0Width = 0;
641 LHSOp0 = LHSShuffle->getOperand(0);
642 LHSOp1 = LHSShuffle->getOperand(1);
643 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
646 RHSOp0 = RHSShuffle->getOperand(0);
647 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
653 if (isa<UndefValue>(RHS)) {
658 else if (LHSOp0Width == LHSWidth) {
663 if (RHSShuffle && RHSOp0Width == LHSWidth) {
667 if (LHSOp0 == RHSOp0) {
672 if (newLHS == LHS && newRHS == RHS)
673 return MadeChange ? &SVI : 0;
675 SmallVector<int, 16> LHSMask;
676 SmallVector<int, 16> RHSMask;
678 LHSMask = LHSShuffle->getShuffleMask();
679 if (RHSShuffle && newRHS != RHS)
680 RHSMask = RHSShuffle->getShuffleMask();
682 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
683 SmallVector<int, 16> newMask;
686 // Create a new mask for the new ShuffleVectorInst so that the new
687 // ShuffleVectorInst is equivalent to the original one.
688 for (unsigned i = 0; i < VWidth; ++i) {
691 // This element is an undef value.
693 } else if (Mask[i] < (int)LHSWidth) {
694 // This element is from left hand side vector operand.
696 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
697 // new mask value for the element.
699 eltMask = LHSMask[Mask[i]];
700 // If the value selected is an undef value, explicitly specify it
701 // with a -1 mask value.
702 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
707 // This element is from right hand side vector operand
709 // If the value selected is an undef value, explicitly specify it
710 // with a -1 mask value. (case 1)
711 if (isa<UndefValue>(RHS))
713 // If RHS is going to be replaced (case 3 or 4), calculate the
714 // new mask value for the element.
715 else if (newRHS != RHS) {
716 eltMask = RHSMask[Mask[i]-LHSWidth];
717 // If the value selected is an undef value, explicitly specify it
718 // with a -1 mask value.
719 if (eltMask >= (int)RHSOp0Width) {
720 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
721 && "should have been check above");
725 eltMask = Mask[i]-LHSWidth;
727 // If LHS's width is changed, shift the mask value accordingly.
728 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
729 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
730 // If newRHS == newLHS, we want to remap any references from newRHS to
731 // newLHS so that we can properly identify splats that may occur due to
732 // obfuscation accross the two vectors.
733 if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
734 eltMask += newLHSWidth;
737 // Check if this could still be a splat.
739 if (SplatElt >= 0 && SplatElt != eltMask)
744 newMask.push_back(eltMask);
747 // If the result mask is equal to one of the original shuffle masks,
748 // or is a splat, do the replacement.
749 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
750 SmallVector<Constant*, 16> Elts;
751 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
752 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
753 if (newMask[i] < 0) {
754 Elts.push_back(UndefValue::get(Int32Ty));
756 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
760 newRHS = UndefValue::get(newLHS->getType());
761 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
764 return MadeChange ? &SVI : 0;