scalarizePHI needs to insert the next ExtractElement in the same block
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineVectorOps.cpp
1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements instcombine for ExtractElement, InsertElement and
11 // ShuffleVector.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstCombine.h"
16 #include "llvm/Support/PatternMatch.h"
17 using namespace llvm;
18 using namespace PatternMatch;
19
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;
26
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)
31         return false;
32     return true;
33   }
34   Instruction *I = dyn_cast<Instruction>(V);
35   if (!I) return false;
36
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)))
41     return true;
42   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
43     return true;
44   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
45     if (BO->hasOneUse() &&
46         (CheapToScalarize(BO->getOperand(0), isConstant) ||
47          CheapToScalarize(BO->getOperand(1), isConstant)))
48       return true;
49   if (CmpInst *CI = dyn_cast<CmpInst>(I))
50     if (CI->hasOneUse() &&
51         (CheapToScalarize(CI->getOperand(0), isConstant) ||
52          CheapToScalarize(CI->getOperand(1), isConstant)))
53       return true;
54
55   return false;
56 }
57
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());
67
68   if (Constant *C = dyn_cast<Constant>(V))
69     return C->getAggregateElement(EltNo);
70
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)))
74       return 0;
75     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
76
77     // If this is an insert to the element we are looking for, return the
78     // inserted value.
79     if (EltNo == IIElt)
80       return III->getOperand(1);
81
82     // Otherwise, the insertelement doesn't modify the value, recurse on its
83     // vector input.
84     return FindScalarElement(III->getOperand(0), EltNo);
85   }
86
87   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
88     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
89     int InEl = SVI->getMaskValue(EltNo);
90     if (InEl < 0)
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);
95   }
96
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);
102   }
103
104   // Otherwise, we don't know.
105   return 0;
106 }
107
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))
114     return NULL;
115
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
118   // node.
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));
123
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))
130     return NULL;
131
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
146       // vector operand.
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"),
152           *B0);
153       Value *newPHIUser = InsertNewInstWith(
154         BinaryOperator::Create(B0->getOpcode(), scalarPHI,Op),
155         *B0);
156       scalarPHI->addIncoming(newPHIUser, inBB);
157     } else {
158       // Scalarize PHI input:
159       Instruction *newEI =
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)) {
165         InsertPos = pos;
166         ++InsertPos;
167       } else {
168         InsertPos = inBB->getFirstInsertionPt();
169       }
170
171       InsertNewInstWith(newEI, *InsertPos);
172
173       scalarPHI->addIncoming(newEI, inBB);
174     }
175   }
176   return ReplaceInstUsesWith(EI, scalarPHI);
177 }
178
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));
185
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();
191
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()));
196
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
199     // property.
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)) {
206         EI.setOperand(0, V);
207         return &EI;
208       }
209     }
210
211     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
212       return ReplaceInstUsesWith(EI, Elt);
213
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());
222     }
223
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);
228       if (scalarPHI)
229         return (scalarPHI);
230     }
231   }
232
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)))) {
239         Value *newEI0 =
240           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
241                                         EI.getName()+".lhs");
242         Value *newEI1 =
243           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
244                                         EI.getName()+".rhs");
245         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
246       }
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));
256         return &EI;
257       }
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());
263         Value *Src;
264         unsigned LHSWidth =
265           SVI->getOperand(0)->getType()->getVectorNumElements();
266
267         if (SrcIdx < 0)
268           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
269         if (SrcIdx < (int)LHSWidth)
270           Src = SVI->getOperand(0);
271         else {
272           SrcIdx -= LHSWidth;
273           Src = SVI->getOperand(1);
274         }
275         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
276         return ExtractElementInst::Create(Src,
277                                           ConstantInt::get(Int32Ty,
278                                                            SrcIdx, false));
279       }
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());
288       }
289     }
290   }
291   return 0;
292 }
293
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();
302
303   if (isa<UndefValue>(V)) {
304     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
305     return true;
306   }
307
308   if (V == LHS) {
309     for (unsigned i = 0; i != NumElts; ++i)
310       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
311     return true;
312   }
313
314   if (V == RHS) {
315     for (unsigned i = 0; i != NumElts; ++i)
316       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
317                                       i+NumElts));
318     return true;
319   }
320
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);
326
327     if (!isa<ConstantInt>(IdxOp))
328       return false;
329     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
330
331     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
332       // Okay, we can handle this if the vector we are insertinting into is
333       // transitively ok.
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()));
337         return true;
338       }
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();
344
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
348           // transitively ok.
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()),
354                                ExtractedIdx);
355             } else {
356               assert(EI->getOperand(0) == RHS);
357               Mask[InsertedIdx % NumElts] =
358               ConstantInt::get(Type::getInt32Ty(V->getContext()),
359                                ExtractedIdx+NumElts);
360             }
361             return true;
362           }
363         }
364       }
365     }
366   }
367   // TODO: Handle shufflevector here!
368
369   return false;
370 }
371
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,
376                                      Value *&RHS) {
377   assert(V->getType()->isVectorTy() &&
378          (RHS == 0 || V->getType() == RHS->getType()) &&
379          "Invalid shuffle!");
380   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
381
382   if (isa<UndefValue>(V)) {
383     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
384     return V;
385   }
386
387   if (isa<ConstantAggregateZero>(V)) {
388     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
389     return V;
390   }
391
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);
397
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();
404
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);
413           return V;
414         }
415
416         if (VecOp == RHS) {
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];
421
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()),
426                                          NumElts+i);
427           }
428           return V;
429         }
430
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);
435       }
436     }
437   }
438   // TODO: Handle shufflevector here!
439
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));
443   return V;
444 }
445
446 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
447   Value *VecOp    = IE.getOperand(0);
448   Value *ScalarOp = IE.getOperand(1);
449   Value *IdxOp    = IE.getOperand(2);
450
451   // Inserting an undef or into an undefined place, remove this.
452   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
453     ReplaceInstUsesWith(IE, VecOp);
454
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();
464
465       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
466         return ReplaceInstUsesWith(IE, VecOp);
467
468       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
469         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
470
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);
475
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;
480         Value *RHS = 0;
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));
485       }
486     }
487   }
488
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)) {
493     if (V != &IE)
494       return ReplaceInstUsesWith(IE, V);
495     return &IE;
496   }
497
498   return 0;
499 }
500
501
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();
506
507   bool MadeChange = false;
508
509   // Undefined shuffle mask -> undefined value.
510   if (isa<UndefValue>(SVI.getOperand(2)))
511     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
512
513   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
514
515   APInt UndefElts(VWidth, 0);
516   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
517   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
518     if (V != &SVI)
519       return ReplaceInstUsesWith(SVI, V);
520     LHS = SVI.getOperand(0);
521     RHS = SVI.getOperand(1);
522     MadeChange = true;
523   }
524
525   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
526
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);
535     }
536
537     // Remap any references to RHS to use LHS.
538     SmallVector<Constant*, 16> Elts;
539     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
540       if (Mask[i] < 0) {
541         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
542         continue;
543       }
544
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())));
549       } else {
550         Mask[i] = Mask[i] % e;  // Force to LHS.
551         Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
552                                         Mask[i]));
553       }
554     }
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);
560     MadeChange = true;
561   }
562
563   if (VWidth == LHSWidth) {
564     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
565     bool isLHSID = true, isRHSID = true;
566
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);
571
572       // Is this an identity shuffle of the RHS value?
573       isRHSID &= (Mask[i]-e == i);
574     }
575
576     // Eliminate identity shuffles.
577     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
578     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
579   }
580
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:
584   // 1.
585   // x1=shuffle(v1,v2,mask1)
586   //  x=shuffle(x1,undef,mask)
587   //        ==>
588   //  x=shuffle(v1,undef,newMask)
589   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
590   // 2.
591   // x1=shuffle(v1,undef,mask1)
592   //  x=shuffle(x1,x2,mask)
593   // where v1.size() == mask1.size()
594   //        ==>
595   //  x=shuffle(v1,x2,newMask)
596   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
597   // 3.
598   // x2=shuffle(v2,undef,mask2)
599   //  x=shuffle(x1,x2,mask)
600   // where v2.size() == mask2.size()
601   //        ==>
602   //  x=shuffle(x1,v2,newMask)
603   // newMask[i] = (mask[i] < x1.size())
604   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
605   // 4.
606   // x1=shuffle(v1,undef,mask1)
607   // x2=shuffle(v2,undef,mask2)
608   //  x=shuffle(x1,x2,mask)
609   // where v1.size() == v2.size()
610   //        ==>
611   //  x=shuffle(v1,v2,newMask)
612   // newMask[i] = (mask[i] < x1.size())
613   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
614   //
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);
626   if (LHSShuffle)
627     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
628       LHSShuffle = NULL;
629   if (RHSShuffle)
630     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
631       RHSShuffle = NULL;
632   if (!LHSShuffle && !RHSShuffle)
633     return MadeChange ? &SVI : 0;
634
635   Value* LHSOp0 = NULL;
636   Value* LHSOp1 = NULL;
637   Value* RHSOp0 = NULL;
638   unsigned LHSOp0Width = 0;
639   unsigned RHSOp0Width = 0;
640   if (LHSShuffle) {
641     LHSOp0 = LHSShuffle->getOperand(0);
642     LHSOp1 = LHSShuffle->getOperand(1);
643     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
644   }
645   if (RHSShuffle) {
646     RHSOp0 = RHSShuffle->getOperand(0);
647     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
648   }
649   Value* newLHS = LHS;
650   Value* newRHS = RHS;
651   if (LHSShuffle) {
652     // case 1
653     if (isa<UndefValue>(RHS)) {
654       newLHS = LHSOp0;
655       newRHS = LHSOp1;
656     }
657     // case 2 or 4
658     else if (LHSOp0Width == LHSWidth) {
659       newLHS = LHSOp0;
660     }
661   }
662   // case 3 or 4
663   if (RHSShuffle && RHSOp0Width == LHSWidth) {
664     newRHS = RHSOp0;
665   }
666   // case 4
667   if (LHSOp0 == RHSOp0) {
668     newLHS = LHSOp0;
669     newRHS = NULL;
670   }
671
672   if (newLHS == LHS && newRHS == RHS)
673     return MadeChange ? &SVI : 0;
674
675   SmallVector<int, 16> LHSMask;
676   SmallVector<int, 16> RHSMask;
677   if (newLHS != LHS)
678     LHSMask = LHSShuffle->getShuffleMask();
679   if (RHSShuffle && newRHS != RHS)
680     RHSMask = RHSShuffle->getShuffleMask();
681
682   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
683   SmallVector<int, 16> newMask;
684   bool isSplat = true;
685   int SplatElt = -1;
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) {
689     int eltMask;
690     if (Mask[i] < 0) {
691       // This element is an undef value.
692       eltMask = -1;
693     } else if (Mask[i] < (int)LHSWidth) {
694       // This element is from left hand side vector operand.
695       //
696       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
697       // new mask value for the element.
698       if (newLHS != LHS) {
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))
703           eltMask = -1;
704       } else
705         eltMask = Mask[i];
706     } else {
707       // This element is from right hand side vector operand
708       //
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))
712         eltMask = -1;
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");
722           eltMask = -1;
723         }
724       } else
725         eltMask = Mask[i]-LHSWidth;
726
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;
735     }
736
737     // Check if this could still be a splat.
738     if (eltMask >= 0) {
739       if (SplatElt >= 0 && SplatElt != eltMask)
740         isSplat = false;
741       SplatElt = eltMask;
742     }
743
744     newMask.push_back(eltMask);
745   }
746
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));
755       } else {
756         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
757       }
758     }
759     if (newRHS == NULL)
760       newRHS = UndefValue::get(newLHS->getType());
761     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
762   }
763
764   return MadeChange ? &SVI : 0;
765 }