501d87ca4ada70d8b6f5cbca553522b68c543e9f
[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 #define DEBUG_TYPE "instcombine"
16 #include "InstCombine.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
22 /// is to leave as a vector operation.  isConstant indicates whether we're
23 /// extracting one known element.  If false we're extracting a variable index.
24 static bool CheapToScalarize(Value *V, bool isConstant) {
25   if (Constant *C = dyn_cast<Constant>(V)) {
26     if (isConstant) return true;
27
28     // If all elts are the same, we can extract it and use any of the values.
29     if (Constant *Op0 = C->getAggregateElement(0U)) {
30       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
31            ++i)
32         if (C->getAggregateElement(i) != Op0)
33           return false;
34       return true;
35     }
36   }
37   Instruction *I = dyn_cast<Instruction>(V);
38   if (!I) return false;
39
40   // Insert element gets simplified to the inserted element or is deleted if
41   // this is constant idx extract element and its a constant idx insertelt.
42   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
43       isa<ConstantInt>(I->getOperand(2)))
44     return true;
45   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
46     return true;
47   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
48     if (BO->hasOneUse() &&
49         (CheapToScalarize(BO->getOperand(0), isConstant) ||
50          CheapToScalarize(BO->getOperand(1), isConstant)))
51       return true;
52   if (CmpInst *CI = dyn_cast<CmpInst>(I))
53     if (CI->hasOneUse() &&
54         (CheapToScalarize(CI->getOperand(0), isConstant) ||
55          CheapToScalarize(CI->getOperand(1), isConstant)))
56       return true;
57
58   return false;
59 }
60
61 /// FindScalarElement - Given a vector and an element number, see if the scalar
62 /// value is already around as a register, for example if it were inserted then
63 /// extracted from the vector.
64 static Value *FindScalarElement(Value *V, unsigned EltNo) {
65   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
66   VectorType *VTy = cast<VectorType>(V->getType());
67   unsigned Width = VTy->getNumElements();
68   if (EltNo >= Width)  // Out of range access.
69     return UndefValue::get(VTy->getElementType());
70
71   if (Constant *C = dyn_cast<Constant>(V))
72     return C->getAggregateElement(EltNo);
73
74   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
75     // If this is an insert to a variable element, we don't know what it is.
76     if (!isa<ConstantInt>(III->getOperand(2)))
77       return 0;
78     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
79
80     // If this is an insert to the element we are looking for, return the
81     // inserted value.
82     if (EltNo == IIElt)
83       return III->getOperand(1);
84
85     // Otherwise, the insertelement doesn't modify the value, recurse on its
86     // vector input.
87     return FindScalarElement(III->getOperand(0), EltNo);
88   }
89
90   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
91     unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
92     int InEl = SVI->getMaskValue(EltNo);
93     if (InEl < 0)
94       return UndefValue::get(VTy->getElementType());
95     if (InEl < (int)LHSWidth)
96       return FindScalarElement(SVI->getOperand(0), InEl);
97     return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
98   }
99
100   // Extract a value from a vector add operation with a constant zero.
101   Value *Val = 0; Constant *Con = 0;
102   if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
103     if (Con->getAggregateElement(EltNo)->isNullValue())
104       return FindScalarElement(Val, EltNo);
105   }
106
107   // Otherwise, we don't know.
108   return 0;
109 }
110
111 // If we have a PHI node with a vector type that has only 2 uses: feed
112 // itself and be an operand of extractelement at a constant location,
113 // try to replace the PHI of the vector type with a PHI of a scalar type.
114 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
115   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
116   if (!PN->hasNUses(2))
117     return NULL;
118
119   // If so, it's known at this point that one operand is PHI and the other is
120   // an extractelement node. Find the PHI user that is not the extractelement
121   // node.
122   auto iu = PN->user_begin();
123   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
124   if (PHIUser == cast<Instruction>(&EI))
125     PHIUser = cast<Instruction>(*(++iu));
126
127   // Verify that this PHI user has one use, which is the PHI itself,
128   // and that it is a binary operation which is cheap to scalarize.
129   // otherwise return NULL.
130   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
131       !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
132     return NULL;
133
134   // Create a scalar PHI node that will replace the vector PHI node
135   // just before the current PHI node.
136   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
137       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
138   // Scalarize each PHI operand.
139   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
140     Value *PHIInVal = PN->getIncomingValue(i);
141     BasicBlock *inBB = PN->getIncomingBlock(i);
142     Value *Elt = EI.getIndexOperand();
143     // If the operand is the PHI induction variable:
144     if (PHIInVal == PHIUser) {
145       // Scalarize the binary operation. Its first operand is the
146       // scalar PHI and the second operand is extracted from the other
147       // vector operand.
148       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
149       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
150       Value *Op = InsertNewInstWith(
151           ExtractElementInst::Create(B0->getOperand(opId), Elt,
152                                      B0->getOperand(opId)->getName() + ".Elt"),
153           *B0);
154       Value *newPHIUser = InsertNewInstWith(
155           BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
156       scalarPHI->addIncoming(newPHIUser, inBB);
157     } else {
158       // Scalarize PHI input:
159       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
160       // Insert the new instruction into the predecessor basic block.
161       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
162       BasicBlock::iterator InsertPos;
163       if (pos && !isa<PHINode>(pos)) {
164         InsertPos = pos;
165         ++InsertPos;
166       } else {
167         InsertPos = inBB->getFirstInsertionPt();
168       }
169
170       InsertNewInstWith(newEI, *InsertPos);
171
172       scalarPHI->addIncoming(newEI, inBB);
173     }
174   }
175   return ReplaceInstUsesWith(EI, scalarPHI);
176 }
177
178 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
179   // If vector val is constant with all elements the same, replace EI with
180   // that element.  We handle a known element # below.
181   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
182     if (CheapToScalarize(C, false))
183       return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
184
185   // If extracting a specified index from the vector, see if we can recursively
186   // find a previously computed scalar that was inserted into the vector.
187   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
188     unsigned IndexVal = IdxC->getZExtValue();
189     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
190
191     // If this is extracting an invalid index, turn this into undef, to avoid
192     // crashing the code below.
193     if (IndexVal >= VectorWidth)
194       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
195
196     // This instruction only demands the single element from the input vector.
197     // If the input vector has a single use, simplify it based on this use
198     // property.
199     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
200       APInt UndefElts(VectorWidth, 0);
201       APInt DemandedMask(VectorWidth, 0);
202       DemandedMask.setBit(IndexVal);
203       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
204                                                 DemandedMask, UndefElts)) {
205         EI.setOperand(0, V);
206         return &EI;
207       }
208     }
209
210     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
211       return ReplaceInstUsesWith(EI, Elt);
212
213     // If the this extractelement is directly using a bitcast from a vector of
214     // the same number of elements, see if we can find the source element from
215     // it.  In this case, we will end up needing to bitcast the scalars.
216     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
217       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
218         if (VT->getNumElements() == VectorWidth)
219           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
220             return new BitCastInst(Elt, EI.getType());
221     }
222
223     // If there's a vector PHI feeding a scalar use through this extractelement
224     // instruction, try to scalarize the PHI.
225     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
226       Instruction *scalarPHI = scalarizePHI(EI, PN);
227       if (scalarPHI)
228         return scalarPHI;
229     }
230   }
231
232   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
233     // Push extractelement into predecessor operation if legal and
234     // profitable to do so
235     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
236       if (I->hasOneUse() &&
237           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
238         Value *newEI0 =
239           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
240                                         EI.getName()+".lhs");
241         Value *newEI1 =
242           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
243                                         EI.getName()+".rhs");
244         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
245       }
246     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
247       // Extracting the inserted element?
248       if (IE->getOperand(2) == EI.getOperand(1))
249         return ReplaceInstUsesWith(EI, IE->getOperand(1));
250       // If the inserted and extracted elements are constants, they must not
251       // be the same value, extract from the pre-inserted value instead.
252       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
253         Worklist.AddValue(EI.getOperand(0));
254         EI.setOperand(0, IE->getOperand(0));
255         return &EI;
256       }
257     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
258       // If this is extracting an element from a shufflevector, figure out where
259       // it came from and extract from the appropriate input element instead.
260       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
261         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
262         Value *Src;
263         unsigned LHSWidth =
264           SVI->getOperand(0)->getType()->getVectorNumElements();
265
266         if (SrcIdx < 0)
267           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
268         if (SrcIdx < (int)LHSWidth)
269           Src = SVI->getOperand(0);
270         else {
271           SrcIdx -= LHSWidth;
272           Src = SVI->getOperand(1);
273         }
274         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
275         return ExtractElementInst::Create(Src,
276                                           ConstantInt::get(Int32Ty,
277                                                            SrcIdx, false));
278       }
279     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
280       // Canonicalize extractelement(cast) -> cast(extractelement)
281       // bitcasts can change the number of vector elements and they cost nothing
282       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
283         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
284                                                   EI.getIndexOperand());
285         Worklist.AddValue(EE);
286         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
287       }
288     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
289       if (SI->hasOneUse()) {
290         // TODO: For a select on vectors, it might be useful to do this if it
291         // has multiple extractelement uses. For vector select, that seems to
292         // fight the vectorizer.
293
294         // If we are extracting an element from a vector select or a select on
295         // vectors, a select on the scalars extracted from the vector arguments.
296         Value *TrueVal = SI->getTrueValue();
297         Value *FalseVal = SI->getFalseValue();
298
299         Value *Cond = SI->getCondition();
300         if (Cond->getType()->isVectorTy()) {
301           Cond = Builder->CreateExtractElement(Cond,
302                                                EI.getIndexOperand(),
303                                                Cond->getName() + ".elt");
304         }
305
306         Value *V1Elem
307           = Builder->CreateExtractElement(TrueVal,
308                                           EI.getIndexOperand(),
309                                           TrueVal->getName() + ".elt");
310
311         Value *V2Elem
312           = Builder->CreateExtractElement(FalseVal,
313                                           EI.getIndexOperand(),
314                                           FalseVal->getName() + ".elt");
315         return SelectInst::Create(Cond,
316                                   V1Elem,
317                                   V2Elem,
318                                   SI->getName() + ".elt");
319       }
320     }
321   }
322   return 0;
323 }
324
325 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
326 /// elements from either LHS or RHS, return the shuffle mask and true.
327 /// Otherwise, return false.
328 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
329                                          SmallVectorImpl<Constant*> &Mask) {
330   assert(LHS->getType() == RHS->getType() &&
331          "Invalid CollectSingleShuffleElements");
332   unsigned NumElts = V->getType()->getVectorNumElements();
333
334   if (isa<UndefValue>(V)) {
335     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
336     return true;
337   }
338
339   if (V == LHS) {
340     for (unsigned i = 0; i != NumElts; ++i)
341       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
342     return true;
343   }
344
345   if (V == RHS) {
346     for (unsigned i = 0; i != NumElts; ++i)
347       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
348                                       i+NumElts));
349     return true;
350   }
351
352   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
353     // If this is an insert of an extract from some other vector, include it.
354     Value *VecOp    = IEI->getOperand(0);
355     Value *ScalarOp = IEI->getOperand(1);
356     Value *IdxOp    = IEI->getOperand(2);
357
358     if (!isa<ConstantInt>(IdxOp))
359       return false;
360     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
361
362     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
363       // Okay, we can handle this if the vector we are insertinting into is
364       // transitively ok.
365       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
366         // If so, update the mask to reflect the inserted undef.
367         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
368         return true;
369       }
370     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
371       if (isa<ConstantInt>(EI->getOperand(1))) {
372         unsigned ExtractedIdx =
373         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
374         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
375
376         // This must be extracting from either LHS or RHS.
377         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
378           // Okay, we can handle this if the vector we are insertinting into is
379           // transitively ok.
380           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
381             // If so, update the mask to reflect the inserted value.
382             if (EI->getOperand(0) == LHS) {
383               Mask[InsertedIdx % NumElts] =
384               ConstantInt::get(Type::getInt32Ty(V->getContext()),
385                                ExtractedIdx);
386             } else {
387               assert(EI->getOperand(0) == RHS);
388               Mask[InsertedIdx % NumElts] =
389               ConstantInt::get(Type::getInt32Ty(V->getContext()),
390                                ExtractedIdx + NumLHSElts);
391             }
392             return true;
393           }
394         }
395       }
396     }
397   }
398
399   return false;
400 }
401
402
403 /// We are building a shuffle to create V, which is a sequence of insertelement,
404 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
405 /// not rely on the second vector source. Return an std::pair containing the
406 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
407 /// parameter as required.
408 ///
409 /// Note: we intentionally don't try to fold earlier shuffles since they have
410 /// often been chosen carefully to be efficiently implementable on the target.
411 typedef std::pair<Value *, Value *> ShuffleOps;
412
413 static ShuffleOps CollectShuffleElements(Value *V,
414                                          SmallVectorImpl<Constant *> &Mask,
415                                          Value *PermittedRHS) {
416   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
417   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
418
419   if (isa<UndefValue>(V)) {
420     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
421     return std::make_pair(
422         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
423   }
424
425   if (isa<ConstantAggregateZero>(V)) {
426     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
427     return std::make_pair(V, nullptr);
428   }
429
430   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
431     // If this is an insert of an extract from some other vector, include it.
432     Value *VecOp    = IEI->getOperand(0);
433     Value *ScalarOp = IEI->getOperand(1);
434     Value *IdxOp    = IEI->getOperand(2);
435
436     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
437       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
438         unsigned ExtractedIdx =
439           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
440         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
441
442         // Either the extracted from or inserted into vector must be RHSVec,
443         // otherwise we'd end up with a shuffle of three inputs.
444         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == 0) {
445           Value *RHS = EI->getOperand(0);
446           ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
447           assert(LR.second == 0 || LR.second == RHS);
448
449           if (LR.first->getType() != RHS->getType()) {
450             // We tried our best, but we can't find anything compatible with RHS
451             // further up the chain. Return a trivial shuffle.
452             for (unsigned i = 0; i < NumElts; ++i)
453               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
454             return std::make_pair(V, nullptr);
455           }
456
457           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
458           Mask[InsertedIdx % NumElts] =
459             ConstantInt::get(Type::getInt32Ty(V->getContext()),
460                              NumLHSElts+ExtractedIdx);
461           return std::make_pair(LR.first, RHS);
462         }
463
464         if (VecOp == PermittedRHS) {
465           // We've gone as far as we can: anything on the other side of the
466           // extractelement will already have been converted into a shuffle.
467           unsigned NumLHSElts =
468               EI->getOperand(0)->getType()->getVectorNumElements();
469           for (unsigned i = 0; i != NumElts; ++i)
470             Mask.push_back(ConstantInt::get(
471                 Type::getInt32Ty(V->getContext()),
472                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
473           return std::make_pair(EI->getOperand(0), PermittedRHS);
474         }
475
476         // If this insertelement is a chain that comes from exactly these two
477         // vectors, return the vector and the effective shuffle.
478         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
479             CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
480                                          Mask))
481           return std::make_pair(EI->getOperand(0), PermittedRHS);
482       }
483     }
484   }
485
486   // Otherwise, can't do anything fancy.  Return an identity vector.
487   for (unsigned i = 0; i != NumElts; ++i)
488     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
489   return std::make_pair(V, nullptr);
490 }
491
492 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
493   Value *VecOp    = IE.getOperand(0);
494   Value *ScalarOp = IE.getOperand(1);
495   Value *IdxOp    = IE.getOperand(2);
496
497   // Inserting an undef or into an undefined place, remove this.
498   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
499     ReplaceInstUsesWith(IE, VecOp);
500
501   // If the inserted element was extracted from some other vector, and if the
502   // indexes are constant, try to turn this into a shufflevector operation.
503   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
504     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
505       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
506       unsigned NumExtractVectorElts =
507           EI->getOperand(0)->getType()->getVectorNumElements();
508       unsigned ExtractedIdx =
509         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
510       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
511
512       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
513         return ReplaceInstUsesWith(IE, VecOp);
514
515       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
516         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
517
518       // If we are extracting a value from a vector, then inserting it right
519       // back into the same place, just use the input vector.
520       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
521         return ReplaceInstUsesWith(IE, VecOp);
522
523       // If this insertelement isn't used by some other insertelement, turn it
524       // (and any insertelements it points to), into one big shuffle.
525       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
526         SmallVector<Constant*, 16> Mask;
527         ShuffleOps LR = CollectShuffleElements(&IE, Mask, 0);
528
529         // The proposed shuffle may be trivial, in which case we shouldn't
530         // perform the combine.
531         if (LR.first != &IE && LR.second != &IE) {
532           // We now have a shuffle of LHS, RHS, Mask.
533           if (LR.second == 0) LR.second = UndefValue::get(LR.first->getType());
534           return new ShuffleVectorInst(LR.first, LR.second,
535                                        ConstantVector::get(Mask));
536         }
537       }
538     }
539   }
540
541   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
542   APInt UndefElts(VWidth, 0);
543   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
544   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
545     if (V != &IE)
546       return ReplaceInstUsesWith(IE, V);
547     return &IE;
548   }
549
550   return 0;
551 }
552
553 /// Return true if we can evaluate the specified expression tree if the vector
554 /// elements were shuffled in a different order.
555 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
556                                 unsigned Depth = 5) {
557   // We can always reorder the elements of a constant.
558   if (isa<Constant>(V))
559     return true;
560
561   // We won't reorder vector arguments. No IPO here.
562   Instruction *I = dyn_cast<Instruction>(V);
563   if (!I) return false;
564
565   // Two users may expect different orders of the elements. Don't try it.
566   if (!I->hasOneUse())
567     return false;
568
569   if (Depth == 0) return false;
570
571   switch (I->getOpcode()) {
572     case Instruction::Add:
573     case Instruction::FAdd:
574     case Instruction::Sub:
575     case Instruction::FSub:
576     case Instruction::Mul:
577     case Instruction::FMul:
578     case Instruction::UDiv:
579     case Instruction::SDiv:
580     case Instruction::FDiv:
581     case Instruction::URem:
582     case Instruction::SRem:
583     case Instruction::FRem:
584     case Instruction::Shl:
585     case Instruction::LShr:
586     case Instruction::AShr:
587     case Instruction::And:
588     case Instruction::Or:
589     case Instruction::Xor:
590     case Instruction::ICmp:
591     case Instruction::FCmp:
592     case Instruction::Trunc:
593     case Instruction::ZExt:
594     case Instruction::SExt:
595     case Instruction::FPToUI:
596     case Instruction::FPToSI:
597     case Instruction::UIToFP:
598     case Instruction::SIToFP:
599     case Instruction::FPTrunc:
600     case Instruction::FPExt:
601     case Instruction::GetElementPtr: {
602       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
603         if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
604           return false;
605       }
606       return true;
607     }
608     case Instruction::InsertElement: {
609       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
610       if (!CI) return false;
611       int ElementNumber = CI->getLimitedValue();
612
613       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
614       // can't put an element into multiple indices.
615       bool SeenOnce = false;
616       for (int i = 0, e = Mask.size(); i != e; ++i) {
617         if (Mask[i] == ElementNumber) {
618           if (SeenOnce)
619             return false;
620           SeenOnce = true;
621         }
622       }
623       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
624     }
625   }
626   return false;
627 }
628
629 /// Rebuild a new instruction just like 'I' but with the new operands given.
630 /// In the event of type mismatch, the type of the operands is correct.
631 static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
632   // We don't want to use the IRBuilder here because we want the replacement
633   // instructions to appear next to 'I', not the builder's insertion point.
634   switch (I->getOpcode()) {
635     case Instruction::Add:
636     case Instruction::FAdd:
637     case Instruction::Sub:
638     case Instruction::FSub:
639     case Instruction::Mul:
640     case Instruction::FMul:
641     case Instruction::UDiv:
642     case Instruction::SDiv:
643     case Instruction::FDiv:
644     case Instruction::URem:
645     case Instruction::SRem:
646     case Instruction::FRem:
647     case Instruction::Shl:
648     case Instruction::LShr:
649     case Instruction::AShr:
650     case Instruction::And:
651     case Instruction::Or:
652     case Instruction::Xor: {
653       BinaryOperator *BO = cast<BinaryOperator>(I);
654       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
655       BinaryOperator *New =
656           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
657                                  NewOps[0], NewOps[1], "", BO);
658       if (isa<OverflowingBinaryOperator>(BO)) {
659         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
660         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
661       }
662       if (isa<PossiblyExactOperator>(BO)) {
663         New->setIsExact(BO->isExact());
664       }
665       if (isa<FPMathOperator>(BO))
666         New->copyFastMathFlags(I);
667       return New;
668     }
669     case Instruction::ICmp:
670       assert(NewOps.size() == 2 && "icmp with #ops != 2");
671       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
672                           NewOps[0], NewOps[1]);
673     case Instruction::FCmp:
674       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
675       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
676                           NewOps[0], NewOps[1]);
677     case Instruction::Trunc:
678     case Instruction::ZExt:
679     case Instruction::SExt:
680     case Instruction::FPToUI:
681     case Instruction::FPToSI:
682     case Instruction::UIToFP:
683     case Instruction::SIToFP:
684     case Instruction::FPTrunc:
685     case Instruction::FPExt: {
686       // It's possible that the mask has a different number of elements from
687       // the original cast. We recompute the destination type to match the mask.
688       Type *DestTy =
689           VectorType::get(I->getType()->getScalarType(),
690                           NewOps[0]->getType()->getVectorNumElements());
691       assert(NewOps.size() == 1 && "cast with #ops != 1");
692       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
693                               "", I);
694     }
695     case Instruction::GetElementPtr: {
696       Value *Ptr = NewOps[0];
697       ArrayRef<Value*> Idx = NewOps.slice(1);
698       GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
699       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
700       return GEP;
701     }
702   }
703   llvm_unreachable("failed to rebuild vector instructions");
704 }
705
706 Value *
707 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
708   // Mask.size() does not need to be equal to the number of vector elements.
709
710   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
711   if (isa<UndefValue>(V)) {
712     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
713                                            Mask.size()));
714   }
715   if (isa<ConstantAggregateZero>(V)) {
716     return ConstantAggregateZero::get(
717                VectorType::get(V->getType()->getScalarType(),
718                                Mask.size()));
719   }
720   if (Constant *C = dyn_cast<Constant>(V)) {
721     SmallVector<Constant *, 16> MaskValues;
722     for (int i = 0, e = Mask.size(); i != e; ++i) {
723       if (Mask[i] == -1)
724         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
725       else
726         MaskValues.push_back(Builder->getInt32(Mask[i]));
727     }
728     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
729                                           ConstantVector::get(MaskValues));
730   }
731
732   Instruction *I = cast<Instruction>(V);
733   switch (I->getOpcode()) {
734     case Instruction::Add:
735     case Instruction::FAdd:
736     case Instruction::Sub:
737     case Instruction::FSub:
738     case Instruction::Mul:
739     case Instruction::FMul:
740     case Instruction::UDiv:
741     case Instruction::SDiv:
742     case Instruction::FDiv:
743     case Instruction::URem:
744     case Instruction::SRem:
745     case Instruction::FRem:
746     case Instruction::Shl:
747     case Instruction::LShr:
748     case Instruction::AShr:
749     case Instruction::And:
750     case Instruction::Or:
751     case Instruction::Xor:
752     case Instruction::ICmp:
753     case Instruction::FCmp:
754     case Instruction::Trunc:
755     case Instruction::ZExt:
756     case Instruction::SExt:
757     case Instruction::FPToUI:
758     case Instruction::FPToSI:
759     case Instruction::UIToFP:
760     case Instruction::SIToFP:
761     case Instruction::FPTrunc:
762     case Instruction::FPExt:
763     case Instruction::Select:
764     case Instruction::GetElementPtr: {
765       SmallVector<Value*, 8> NewOps;
766       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
767       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
768         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
769         NewOps.push_back(V);
770         NeedsRebuild |= (V != I->getOperand(i));
771       }
772       if (NeedsRebuild) {
773         return BuildNew(I, NewOps);
774       }
775       return I;
776     }
777     case Instruction::InsertElement: {
778       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
779
780       // The insertelement was inserting at Element. Figure out which element
781       // that becomes after shuffling. The answer is guaranteed to be unique
782       // by CanEvaluateShuffled.
783       bool Found = false;
784       int Index = 0;
785       for (int e = Mask.size(); Index != e; ++Index) {
786         if (Mask[Index] == Element) {
787           Found = true;
788           break;
789         }
790       }
791
792       // If element is not in Mask, no need to handle the operand 1 (element to
793       // be inserted). Just evaluate values in operand 0 according to Mask.
794       if (!Found)
795         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
796
797       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
798       return InsertElementInst::Create(V, I->getOperand(1),
799                                        Builder->getInt32(Index), "", I);
800     }
801   }
802   llvm_unreachable("failed to reorder elements of vector instruction!");
803 }
804
805 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
806   Value *LHS = SVI.getOperand(0);
807   Value *RHS = SVI.getOperand(1);
808   SmallVector<int, 16> Mask = SVI.getShuffleMask();
809
810   bool MadeChange = false;
811
812   // Undefined shuffle mask -> undefined value.
813   if (isa<UndefValue>(SVI.getOperand(2)))
814     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
815
816   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
817
818   APInt UndefElts(VWidth, 0);
819   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
820   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
821     if (V != &SVI)
822       return ReplaceInstUsesWith(SVI, V);
823     LHS = SVI.getOperand(0);
824     RHS = SVI.getOperand(1);
825     MadeChange = true;
826   }
827
828   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
829
830   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
831   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
832   if (LHS == RHS || isa<UndefValue>(LHS)) {
833     if (isa<UndefValue>(LHS) && LHS == RHS) {
834       // shuffle(undef,undef,mask) -> undef.
835       Value *Result = (VWidth == LHSWidth)
836                       ? LHS : UndefValue::get(SVI.getType());
837       return ReplaceInstUsesWith(SVI, Result);
838     }
839
840     // Remap any references to RHS to use LHS.
841     SmallVector<Constant*, 16> Elts;
842     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
843       if (Mask[i] < 0) {
844         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
845         continue;
846       }
847
848       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
849           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
850         Mask[i] = -1;     // Turn into undef.
851         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
852       } else {
853         Mask[i] = Mask[i] % e;  // Force to LHS.
854         Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
855                                         Mask[i]));
856       }
857     }
858     SVI.setOperand(0, SVI.getOperand(1));
859     SVI.setOperand(1, UndefValue::get(RHS->getType()));
860     SVI.setOperand(2, ConstantVector::get(Elts));
861     LHS = SVI.getOperand(0);
862     RHS = SVI.getOperand(1);
863     MadeChange = true;
864   }
865
866   if (VWidth == LHSWidth) {
867     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
868     bool isLHSID = true, isRHSID = true;
869
870     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
871       if (Mask[i] < 0) continue;  // Ignore undef values.
872       // Is this an identity shuffle of the LHS value?
873       isLHSID &= (Mask[i] == (int)i);
874
875       // Is this an identity shuffle of the RHS value?
876       isRHSID &= (Mask[i]-e == i);
877     }
878
879     // Eliminate identity shuffles.
880     if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
881     if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
882   }
883
884   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
885     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
886     return ReplaceInstUsesWith(SVI, V);
887   }
888
889   // If the LHS is a shufflevector itself, see if we can combine it with this
890   // one without producing an unusual shuffle.
891   // Cases that might be simplified:
892   // 1.
893   // x1=shuffle(v1,v2,mask1)
894   //  x=shuffle(x1,undef,mask)
895   //        ==>
896   //  x=shuffle(v1,undef,newMask)
897   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
898   // 2.
899   // x1=shuffle(v1,undef,mask1)
900   //  x=shuffle(x1,x2,mask)
901   // where v1.size() == mask1.size()
902   //        ==>
903   //  x=shuffle(v1,x2,newMask)
904   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
905   // 3.
906   // x2=shuffle(v2,undef,mask2)
907   //  x=shuffle(x1,x2,mask)
908   // where v2.size() == mask2.size()
909   //        ==>
910   //  x=shuffle(x1,v2,newMask)
911   // newMask[i] = (mask[i] < x1.size())
912   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
913   // 4.
914   // x1=shuffle(v1,undef,mask1)
915   // x2=shuffle(v2,undef,mask2)
916   //  x=shuffle(x1,x2,mask)
917   // where v1.size() == v2.size()
918   //        ==>
919   //  x=shuffle(v1,v2,newMask)
920   // newMask[i] = (mask[i] < x1.size())
921   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
922   //
923   // Here we are really conservative:
924   // we are absolutely afraid of producing a shuffle mask not in the input
925   // program, because the code gen may not be smart enough to turn a merged
926   // shuffle into two specific shuffles: it may produce worse code.  As such,
927   // we only merge two shuffles if the result is either a splat or one of the
928   // input shuffle masks.  In this case, merging the shuffles just removes
929   // one instruction, which we know is safe.  This is good for things like
930   // turning: (splat(splat)) -> splat, or
931   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
932   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
933   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
934   if (LHSShuffle)
935     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
936       LHSShuffle = NULL;
937   if (RHSShuffle)
938     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
939       RHSShuffle = NULL;
940   if (!LHSShuffle && !RHSShuffle)
941     return MadeChange ? &SVI : 0;
942
943   Value* LHSOp0 = NULL;
944   Value* LHSOp1 = NULL;
945   Value* RHSOp0 = NULL;
946   unsigned LHSOp0Width = 0;
947   unsigned RHSOp0Width = 0;
948   if (LHSShuffle) {
949     LHSOp0 = LHSShuffle->getOperand(0);
950     LHSOp1 = LHSShuffle->getOperand(1);
951     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
952   }
953   if (RHSShuffle) {
954     RHSOp0 = RHSShuffle->getOperand(0);
955     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
956   }
957   Value* newLHS = LHS;
958   Value* newRHS = RHS;
959   if (LHSShuffle) {
960     // case 1
961     if (isa<UndefValue>(RHS)) {
962       newLHS = LHSOp0;
963       newRHS = LHSOp1;
964     }
965     // case 2 or 4
966     else if (LHSOp0Width == LHSWidth) {
967       newLHS = LHSOp0;
968     }
969   }
970   // case 3 or 4
971   if (RHSShuffle && RHSOp0Width == LHSWidth) {
972     newRHS = RHSOp0;
973   }
974   // case 4
975   if (LHSOp0 == RHSOp0) {
976     newLHS = LHSOp0;
977     newRHS = NULL;
978   }
979
980   if (newLHS == LHS && newRHS == RHS)
981     return MadeChange ? &SVI : 0;
982
983   SmallVector<int, 16> LHSMask;
984   SmallVector<int, 16> RHSMask;
985   if (newLHS != LHS)
986     LHSMask = LHSShuffle->getShuffleMask();
987   if (RHSShuffle && newRHS != RHS)
988     RHSMask = RHSShuffle->getShuffleMask();
989
990   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
991   SmallVector<int, 16> newMask;
992   bool isSplat = true;
993   int SplatElt = -1;
994   // Create a new mask for the new ShuffleVectorInst so that the new
995   // ShuffleVectorInst is equivalent to the original one.
996   for (unsigned i = 0; i < VWidth; ++i) {
997     int eltMask;
998     if (Mask[i] < 0) {
999       // This element is an undef value.
1000       eltMask = -1;
1001     } else if (Mask[i] < (int)LHSWidth) {
1002       // This element is from left hand side vector operand.
1003       //
1004       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1005       // new mask value for the element.
1006       if (newLHS != LHS) {
1007         eltMask = LHSMask[Mask[i]];
1008         // If the value selected is an undef value, explicitly specify it
1009         // with a -1 mask value.
1010         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1011           eltMask = -1;
1012       } else
1013         eltMask = Mask[i];
1014     } else {
1015       // This element is from right hand side vector operand
1016       //
1017       // If the value selected is an undef value, explicitly specify it
1018       // with a -1 mask value. (case 1)
1019       if (isa<UndefValue>(RHS))
1020         eltMask = -1;
1021       // If RHS is going to be replaced (case 3 or 4), calculate the
1022       // new mask value for the element.
1023       else if (newRHS != RHS) {
1024         eltMask = RHSMask[Mask[i]-LHSWidth];
1025         // If the value selected is an undef value, explicitly specify it
1026         // with a -1 mask value.
1027         if (eltMask >= (int)RHSOp0Width) {
1028           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1029                  && "should have been check above");
1030           eltMask = -1;
1031         }
1032       } else
1033         eltMask = Mask[i]-LHSWidth;
1034
1035       // If LHS's width is changed, shift the mask value accordingly.
1036       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1037       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1038       // If newRHS == newLHS, we want to remap any references from newRHS to
1039       // newLHS so that we can properly identify splats that may occur due to
1040       // obfuscation across the two vectors.
1041       if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
1042         eltMask += newLHSWidth;
1043     }
1044
1045     // Check if this could still be a splat.
1046     if (eltMask >= 0) {
1047       if (SplatElt >= 0 && SplatElt != eltMask)
1048         isSplat = false;
1049       SplatElt = eltMask;
1050     }
1051
1052     newMask.push_back(eltMask);
1053   }
1054
1055   // If the result mask is equal to one of the original shuffle masks,
1056   // or is a splat, do the replacement.
1057   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1058     SmallVector<Constant*, 16> Elts;
1059     Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1060     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1061       if (newMask[i] < 0) {
1062         Elts.push_back(UndefValue::get(Int32Ty));
1063       } else {
1064         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1065       }
1066     }
1067     if (newRHS == NULL)
1068       newRHS = UndefValue::get(newLHS->getType());
1069     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1070   }
1071
1072   return MadeChange ? &SVI : 0;
1073 }