cbc1d630d52770f8297df72f567c8c8dd69e28fc
[oota-llvm.git] / lib / Transforms / Vectorize / BBVectorize.cpp
1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
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 a basic-block vectorization pass. The algorithm was
11 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12 // et al. It works by looking for chains of pairable operations and then
13 // pairing them.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define BBV_NAME "bb-vectorize"
18 #define DEBUG_TYPE BBV_NAME
19 #include "llvm/Transforms/Vectorize.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/AliasSetTracker.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/ScalarEvolution.h"
31 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ValueHandle.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include <algorithm>
51 using namespace llvm;
52
53 static cl::opt<bool>
54 IgnoreTargetInfo("bb-vectorize-ignore-target-info",  cl::init(false),
55   cl::Hidden, cl::desc("Ignore target information"));
56
57 static cl::opt<unsigned>
58 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
59   cl::desc("The required chain depth for vectorization"));
60
61 static cl::opt<bool>
62 UseChainDepthWithTI("bb-vectorize-use-chain-depth",  cl::init(false),
63   cl::Hidden, cl::desc("Use the chain depth requirement with"
64                        " target information"));
65
66 static cl::opt<unsigned>
67 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
68   cl::desc("The maximum search distance for instruction pairs"));
69
70 static cl::opt<bool>
71 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
72   cl::desc("Replicating one element to a pair breaks the chain"));
73
74 static cl::opt<unsigned>
75 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
76   cl::desc("The size of the native vector registers"));
77
78 static cl::opt<unsigned>
79 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
80   cl::desc("The maximum number of pairing iterations"));
81
82 static cl::opt<bool>
83 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
84   cl::desc("Don't try to form non-2^n-length vectors"));
85
86 static cl::opt<unsigned>
87 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
88   cl::desc("The maximum number of pairable instructions per group"));
89
90 static cl::opt<unsigned>
91 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
92   cl::desc("The maximum number of candidate instruction pairs per group"));
93
94 static cl::opt<unsigned>
95 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
96   cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
97                        " a full cycle check"));
98
99 static cl::opt<bool>
100 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
101   cl::desc("Don't try to vectorize boolean (i1) values"));
102
103 static cl::opt<bool>
104 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
105   cl::desc("Don't try to vectorize integer values"));
106
107 static cl::opt<bool>
108 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
109   cl::desc("Don't try to vectorize floating-point values"));
110
111 // FIXME: This should default to false once pointer vector support works.
112 static cl::opt<bool>
113 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
114   cl::desc("Don't try to vectorize pointer values"));
115
116 static cl::opt<bool>
117 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
118   cl::desc("Don't try to vectorize casting (conversion) operations"));
119
120 static cl::opt<bool>
121 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
122   cl::desc("Don't try to vectorize floating-point math intrinsics"));
123
124 static cl::opt<bool>
125 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
126   cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
127
128 static cl::opt<bool>
129 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
130   cl::desc("Don't try to vectorize select instructions"));
131
132 static cl::opt<bool>
133 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
134   cl::desc("Don't try to vectorize comparison instructions"));
135
136 static cl::opt<bool>
137 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
138   cl::desc("Don't try to vectorize getelementptr instructions"));
139
140 static cl::opt<bool>
141 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
142   cl::desc("Don't try to vectorize loads and stores"));
143
144 static cl::opt<bool>
145 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
146   cl::desc("Only generate aligned loads and stores"));
147
148 static cl::opt<bool>
149 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
150   cl::init(false), cl::Hidden,
151   cl::desc("Don't boost the chain-depth contribution of loads and stores"));
152
153 static cl::opt<bool>
154 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
155   cl::desc("Use a fast instruction dependency analysis"));
156
157 #ifndef NDEBUG
158 static cl::opt<bool>
159 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
160   cl::init(false), cl::Hidden,
161   cl::desc("When debugging is enabled, output information on the"
162            " instruction-examination process"));
163 static cl::opt<bool>
164 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
165   cl::init(false), cl::Hidden,
166   cl::desc("When debugging is enabled, output information on the"
167            " candidate-selection process"));
168 static cl::opt<bool>
169 DebugPairSelection("bb-vectorize-debug-pair-selection",
170   cl::init(false), cl::Hidden,
171   cl::desc("When debugging is enabled, output information on the"
172            " pair-selection process"));
173 static cl::opt<bool>
174 DebugCycleCheck("bb-vectorize-debug-cycle-check",
175   cl::init(false), cl::Hidden,
176   cl::desc("When debugging is enabled, output information on the"
177            " cycle-checking process"));
178
179 static cl::opt<bool>
180 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
181   cl::init(false), cl::Hidden,
182   cl::desc("When debugging is enabled, dump the basic block after"
183            " every pair is fused"));
184 #endif
185
186 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
187
188 namespace {
189   struct BBVectorize : public BasicBlockPass {
190     static char ID; // Pass identification, replacement for typeid
191
192     const VectorizeConfig Config;
193
194     BBVectorize(const VectorizeConfig &C = VectorizeConfig())
195       : BasicBlockPass(ID), Config(C) {
196       initializeBBVectorizePass(*PassRegistry::getPassRegistry());
197     }
198
199     BBVectorize(Pass *P, const VectorizeConfig &C)
200       : BasicBlockPass(ID), Config(C) {
201       AA = &P->getAnalysis<AliasAnalysis>();
202       DT = &P->getAnalysis<DominatorTree>();
203       SE = &P->getAnalysis<ScalarEvolution>();
204       TD = P->getAnalysisIfAvailable<DataLayout>();
205       TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
206     }
207
208     typedef std::pair<Value *, Value *> ValuePair;
209     typedef std::pair<ValuePair, int> ValuePairWithCost;
210     typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
211     typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
212     typedef std::pair<VPPair, unsigned> VPPairWithType;
213
214     AliasAnalysis *AA;
215     DominatorTree *DT;
216     ScalarEvolution *SE;
217     DataLayout *TD;
218     const TargetTransformInfo *TTI;
219
220     // FIXME: const correct?
221
222     bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
223
224     bool getCandidatePairs(BasicBlock &BB,
225                        BasicBlock::iterator &Start,
226                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
227                        DenseSet<ValuePair> &FixedOrderPairs,
228                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
229                        std::vector<Value *> &PairableInsts, bool NonPow2Len);
230
231     // FIXME: The current implementation does not account for pairs that
232     // are connected in multiple ways. For example:
233     //   C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
234     enum PairConnectionType {
235       PairConnectionDirect,
236       PairConnectionSwap,
237       PairConnectionSplat
238     };
239
240     void computeConnectedPairs(
241              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
242              DenseSet<ValuePair> &CandidatePairsSet,
243              std::vector<Value *> &PairableInsts,
244              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
245              DenseMap<VPPair, unsigned> &PairConnectionTypes);
246
247     void buildDepMap(BasicBlock &BB,
248              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
249              std::vector<Value *> &PairableInsts,
250              DenseSet<ValuePair> &PairableInstUsers);
251
252     void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
253              DenseSet<ValuePair> &CandidatePairsSet,
254              DenseMap<ValuePair, int> &CandidatePairCostSavings,
255              std::vector<Value *> &PairableInsts,
256              DenseSet<ValuePair> &FixedOrderPairs,
257              DenseMap<VPPair, unsigned> &PairConnectionTypes,
258              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
259              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
260              DenseSet<ValuePair> &PairableInstUsers,
261              DenseMap<Value *, Value *>& ChosenPairs);
262
263     void fuseChosenPairs(BasicBlock &BB,
264              std::vector<Value *> &PairableInsts,
265              DenseMap<Value *, Value *>& ChosenPairs,
266              DenseSet<ValuePair> &FixedOrderPairs,
267              DenseMap<VPPair, unsigned> &PairConnectionTypes,
268              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
269              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
270
271
272     bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
273
274     bool areInstsCompatible(Instruction *I, Instruction *J,
275                        bool IsSimpleLoadStore, bool NonPow2Len,
276                        int &CostSavings, int &FixedOrder);
277
278     bool trackUsesOfI(DenseSet<Value *> &Users,
279                       AliasSetTracker &WriteSet, Instruction *I,
280                       Instruction *J, bool UpdateUsers = true,
281                       DenseSet<ValuePair> *LoadMoveSetPairs = 0);
282
283   void computePairsConnectedTo(
284              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
285              DenseSet<ValuePair> &CandidatePairsSet,
286              std::vector<Value *> &PairableInsts,
287              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
288              DenseMap<VPPair, unsigned> &PairConnectionTypes,
289              ValuePair P);
290
291     bool pairsConflict(ValuePair P, ValuePair Q,
292              DenseSet<ValuePair> &PairableInstUsers,
293              DenseMap<ValuePair, std::vector<ValuePair> >
294                *PairableInstUserMap = 0,
295              DenseSet<VPPair> *PairableInstUserPairSet = 0);
296
297     bool pairWillFormCycle(ValuePair P,
298              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
299              DenseSet<ValuePair> &CurrentPairs);
300
301     void pruneDAGFor(
302              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
303              std::vector<Value *> &PairableInsts,
304              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
305              DenseSet<ValuePair> &PairableInstUsers,
306              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
307              DenseSet<VPPair> &PairableInstUserPairSet,
308              DenseMap<Value *, Value *> &ChosenPairs,
309              DenseMap<ValuePair, size_t> &DAG,
310              DenseSet<ValuePair> &PrunedDAG, ValuePair J,
311              bool UseCycleCheck);
312
313     void buildInitialDAGFor(
314              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
315              DenseSet<ValuePair> &CandidatePairsSet,
316              std::vector<Value *> &PairableInsts,
317              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
318              DenseSet<ValuePair> &PairableInstUsers,
319              DenseMap<Value *, Value *> &ChosenPairs,
320              DenseMap<ValuePair, size_t> &DAG, ValuePair J);
321
322     void findBestDAGFor(
323              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
324              DenseSet<ValuePair> &CandidatePairsSet,
325              DenseMap<ValuePair, int> &CandidatePairCostSavings,
326              std::vector<Value *> &PairableInsts,
327              DenseSet<ValuePair> &FixedOrderPairs,
328              DenseMap<VPPair, unsigned> &PairConnectionTypes,
329              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
330              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
331              DenseSet<ValuePair> &PairableInstUsers,
332              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
333              DenseSet<VPPair> &PairableInstUserPairSet,
334              DenseMap<Value *, Value *> &ChosenPairs,
335              DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
336              int &BestEffSize, Value *II, std::vector<Value *>&JJ,
337              bool UseCycleCheck);
338
339     Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
340                      Instruction *J, unsigned o);
341
342     void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
343                      unsigned MaskOffset, unsigned NumInElem,
344                      unsigned NumInElem1, unsigned IdxOffset,
345                      std::vector<Constant*> &Mask);
346
347     Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
348                      Instruction *J);
349
350     bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
351                        unsigned o, Value *&LOp, unsigned numElemL,
352                        Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
353                        unsigned IdxOff = 0);
354
355     Value *getReplacementInput(LLVMContext& Context, Instruction *I,
356                      Instruction *J, unsigned o, bool IBeforeJ);
357
358     void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
359                      Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
360                      bool IBeforeJ);
361
362     void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
363                      Instruction *J, Instruction *K,
364                      Instruction *&InsertionPt, Instruction *&K1,
365                      Instruction *&K2);
366
367     void collectPairLoadMoveSet(BasicBlock &BB,
368                      DenseMap<Value *, Value *> &ChosenPairs,
369                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
370                      DenseSet<ValuePair> &LoadMoveSetPairs,
371                      Instruction *I);
372
373     void collectLoadMoveSet(BasicBlock &BB,
374                      std::vector<Value *> &PairableInsts,
375                      DenseMap<Value *, Value *> &ChosenPairs,
376                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
377                      DenseSet<ValuePair> &LoadMoveSetPairs);
378
379     bool canMoveUsesOfIAfterJ(BasicBlock &BB,
380                      DenseSet<ValuePair> &LoadMoveSetPairs,
381                      Instruction *I, Instruction *J);
382
383     void moveUsesOfIAfterJ(BasicBlock &BB,
384                      DenseSet<ValuePair> &LoadMoveSetPairs,
385                      Instruction *&InsertionPt,
386                      Instruction *I, Instruction *J);
387
388     void combineMetadata(Instruction *K, const Instruction *J);
389
390     bool vectorizeBB(BasicBlock &BB) {
391       if (!DT->isReachableFromEntry(&BB)) {
392         DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
393               " in " << BB.getParent()->getName() << "\n");
394         return false;
395       }
396
397       DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
398
399       bool changed = false;
400       // Iterate a sufficient number of times to merge types of size 1 bit,
401       // then 2 bits, then 4, etc. up to half of the target vector width of the
402       // target vector register.
403       unsigned n = 1;
404       for (unsigned v = 2;
405            (TTI || v <= Config.VectorBits) &&
406            (!Config.MaxIter || n <= Config.MaxIter);
407            v *= 2, ++n) {
408         DEBUG(dbgs() << "BBV: fusing loop #" << n <<
409               " for " << BB.getName() << " in " <<
410               BB.getParent()->getName() << "...\n");
411         if (vectorizePairs(BB))
412           changed = true;
413         else
414           break;
415       }
416
417       if (changed && !Pow2LenOnly) {
418         ++n;
419         for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
420           DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
421                 n << " for " << BB.getName() << " in " <<
422                 BB.getParent()->getName() << "...\n");
423           if (!vectorizePairs(BB, true)) break;
424         }
425       }
426
427       DEBUG(dbgs() << "BBV: done!\n");
428       return changed;
429     }
430
431     virtual bool runOnBasicBlock(BasicBlock &BB) {
432       AA = &getAnalysis<AliasAnalysis>();
433       DT = &getAnalysis<DominatorTree>();
434       SE = &getAnalysis<ScalarEvolution>();
435       TD = getAnalysisIfAvailable<DataLayout>();
436       TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
437
438       return vectorizeBB(BB);
439     }
440
441     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
442       BasicBlockPass::getAnalysisUsage(AU);
443       AU.addRequired<AliasAnalysis>();
444       AU.addRequired<DominatorTree>();
445       AU.addRequired<ScalarEvolution>();
446       AU.addRequired<TargetTransformInfo>();
447       AU.addPreserved<AliasAnalysis>();
448       AU.addPreserved<DominatorTree>();
449       AU.addPreserved<ScalarEvolution>();
450       AU.setPreservesCFG();
451     }
452
453     static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
454       assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
455              "Cannot form vector from incompatible scalar types");
456       Type *STy = ElemTy->getScalarType();
457
458       unsigned numElem;
459       if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
460         numElem = VTy->getNumElements();
461       } else {
462         numElem = 1;
463       }
464
465       if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
466         numElem += VTy->getNumElements();
467       } else {
468         numElem += 1;
469       }
470
471       return VectorType::get(STy, numElem);
472     }
473
474     static inline void getInstructionTypes(Instruction *I,
475                                            Type *&T1, Type *&T2) {
476       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
477         // For stores, it is the value type, not the pointer type that matters
478         // because the value is what will come from a vector register.
479   
480         Value *IVal = SI->getValueOperand();
481         T1 = IVal->getType();
482       } else {
483         T1 = I->getType();
484       }
485   
486       if (CastInst *CI = dyn_cast<CastInst>(I))
487         T2 = CI->getSrcTy();
488       else
489         T2 = T1;
490
491       if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
492         T2 = SI->getCondition()->getType();
493       } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
494         T2 = SI->getOperand(0)->getType();
495       } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
496         T2 = CI->getOperand(0)->getType();
497       }
498     }
499
500     // Returns the weight associated with the provided value. A chain of
501     // candidate pairs has a length given by the sum of the weights of its
502     // members (one weight per pair; the weight of each member of the pair
503     // is assumed to be the same). This length is then compared to the
504     // chain-length threshold to determine if a given chain is significant
505     // enough to be vectorized. The length is also used in comparing
506     // candidate chains where longer chains are considered to be better.
507     // Note: when this function returns 0, the resulting instructions are
508     // not actually fused.
509     inline size_t getDepthFactor(Value *V) {
510       // InsertElement and ExtractElement have a depth factor of zero. This is
511       // for two reasons: First, they cannot be usefully fused. Second, because
512       // the pass generates a lot of these, they can confuse the simple metric
513       // used to compare the dags in the next iteration. Thus, giving them a
514       // weight of zero allows the pass to essentially ignore them in
515       // subsequent iterations when looking for vectorization opportunities
516       // while still tracking dependency chains that flow through those
517       // instructions.
518       if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
519         return 0;
520
521       // Give a load or store half of the required depth so that load/store
522       // pairs will vectorize.
523       if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
524         return Config.ReqChainDepth/2;
525
526       return 1;
527     }
528
529     // Returns the cost of the provided instruction using TTI.
530     // This does not handle loads and stores.
531     unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
532       switch (Opcode) {
533       default: break;
534       case Instruction::GetElementPtr:
535         // We mark this instruction as zero-cost because scalar GEPs are usually
536         // lowered to the intruction addressing mode. At the moment we don't
537         // generate vector GEPs.
538         return 0;
539       case Instruction::Br:
540         return TTI->getCFInstrCost(Opcode);
541       case Instruction::PHI:
542         return 0;
543       case Instruction::Add:
544       case Instruction::FAdd:
545       case Instruction::Sub:
546       case Instruction::FSub:
547       case Instruction::Mul:
548       case Instruction::FMul:
549       case Instruction::UDiv:
550       case Instruction::SDiv:
551       case Instruction::FDiv:
552       case Instruction::URem:
553       case Instruction::SRem:
554       case Instruction::FRem:
555       case Instruction::Shl:
556       case Instruction::LShr:
557       case Instruction::AShr:
558       case Instruction::And:
559       case Instruction::Or:
560       case Instruction::Xor:
561         return TTI->getArithmeticInstrCost(Opcode, T1);
562       case Instruction::Select:
563       case Instruction::ICmp:
564       case Instruction::FCmp:
565         return TTI->getCmpSelInstrCost(Opcode, T1, T2);
566       case Instruction::ZExt:
567       case Instruction::SExt:
568       case Instruction::FPToUI:
569       case Instruction::FPToSI:
570       case Instruction::FPExt:
571       case Instruction::PtrToInt:
572       case Instruction::IntToPtr:
573       case Instruction::SIToFP:
574       case Instruction::UIToFP:
575       case Instruction::Trunc:
576       case Instruction::FPTrunc:
577       case Instruction::BitCast:
578       case Instruction::ShuffleVector:
579         return TTI->getCastInstrCost(Opcode, T1, T2);
580       }
581
582       return 1;
583     }
584
585     // This determines the relative offset of two loads or stores, returning
586     // true if the offset could be determined to be some constant value.
587     // For example, if OffsetInElmts == 1, then J accesses the memory directly
588     // after I; if OffsetInElmts == -1 then I accesses the memory
589     // directly after J.
590     bool getPairPtrInfo(Instruction *I, Instruction *J,
591         Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
592         unsigned &IAddressSpace, unsigned &JAddressSpace,
593         int64_t &OffsetInElmts, bool ComputeOffset = true) {
594       OffsetInElmts = 0;
595       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
596         LoadInst *LJ = cast<LoadInst>(J);
597         IPtr = LI->getPointerOperand();
598         JPtr = LJ->getPointerOperand();
599         IAlignment = LI->getAlignment();
600         JAlignment = LJ->getAlignment();
601         IAddressSpace = LI->getPointerAddressSpace();
602         JAddressSpace = LJ->getPointerAddressSpace();
603       } else {
604         StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
605         IPtr = SI->getPointerOperand();
606         JPtr = SJ->getPointerOperand();
607         IAlignment = SI->getAlignment();
608         JAlignment = SJ->getAlignment();
609         IAddressSpace = SI->getPointerAddressSpace();
610         JAddressSpace = SJ->getPointerAddressSpace();
611       }
612
613       if (!ComputeOffset)
614         return true;
615
616       const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
617       const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
618
619       // If this is a trivial offset, then we'll get something like
620       // 1*sizeof(type). With target data, which we need anyway, this will get
621       // constant folded into a number.
622       const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
623       if (const SCEVConstant *ConstOffSCEV =
624             dyn_cast<SCEVConstant>(OffsetSCEV)) {
625         ConstantInt *IntOff = ConstOffSCEV->getValue();
626         int64_t Offset = IntOff->getSExtValue();
627
628         Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
629         int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
630
631         Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
632         if (VTy != VTy2 && Offset < 0) {
633           int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
634           OffsetInElmts = Offset/VTy2TSS;
635           return (abs64(Offset) % VTy2TSS) == 0;
636         }
637
638         OffsetInElmts = Offset/VTyTSS;
639         return (abs64(Offset) % VTyTSS) == 0;
640       }
641
642       return false;
643     }
644
645     // Returns true if the provided CallInst represents an intrinsic that can
646     // be vectorized.
647     bool isVectorizableIntrinsic(CallInst* I) {
648       Function *F = I->getCalledFunction();
649       if (!F) return false;
650
651       Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
652       if (!IID) return false;
653
654       switch(IID) {
655       default:
656         return false;
657       case Intrinsic::sqrt:
658       case Intrinsic::powi:
659       case Intrinsic::sin:
660       case Intrinsic::cos:
661       case Intrinsic::log:
662       case Intrinsic::log2:
663       case Intrinsic::log10:
664       case Intrinsic::exp:
665       case Intrinsic::exp2:
666       case Intrinsic::pow:
667         return Config.VectorizeMath;
668       case Intrinsic::fma:
669       case Intrinsic::fmuladd:
670         return Config.VectorizeFMA;
671       }
672     }
673
674     bool isPureIEChain(InsertElementInst *IE) {
675       InsertElementInst *IENext = IE;
676       do {
677         if (!isa<UndefValue>(IENext->getOperand(0)) &&
678             !isa<InsertElementInst>(IENext->getOperand(0))) {
679           return false;
680         }
681       } while ((IENext =
682                  dyn_cast<InsertElementInst>(IENext->getOperand(0))));
683
684       return true;
685     }
686   };
687
688   // This function implements one vectorization iteration on the provided
689   // basic block. It returns true if the block is changed.
690   bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
691     bool ShouldContinue;
692     BasicBlock::iterator Start = BB.getFirstInsertionPt();
693
694     std::vector<Value *> AllPairableInsts;
695     DenseMap<Value *, Value *> AllChosenPairs;
696     DenseSet<ValuePair> AllFixedOrderPairs;
697     DenseMap<VPPair, unsigned> AllPairConnectionTypes;
698     DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
699                                                  AllConnectedPairDeps;
700
701     do {
702       std::vector<Value *> PairableInsts;
703       DenseMap<Value *, std::vector<Value *> > CandidatePairs;
704       DenseSet<ValuePair> FixedOrderPairs;
705       DenseMap<ValuePair, int> CandidatePairCostSavings;
706       ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
707                                          FixedOrderPairs,
708                                          CandidatePairCostSavings,
709                                          PairableInsts, NonPow2Len);
710       if (PairableInsts.empty()) continue;
711
712       // Build the candidate pair set for faster lookups.
713       DenseSet<ValuePair> CandidatePairsSet;
714       for (DenseMap<Value *, std::vector<Value *> >::iterator I =
715            CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
716         for (std::vector<Value *>::iterator J = I->second.begin(),
717              JE = I->second.end(); J != JE; ++J)
718           CandidatePairsSet.insert(ValuePair(I->first, *J));
719
720       // Now we have a map of all of the pairable instructions and we need to
721       // select the best possible pairing. A good pairing is one such that the
722       // users of the pair are also paired. This defines a (directed) forest
723       // over the pairs such that two pairs are connected iff the second pair
724       // uses the first.
725
726       // Note that it only matters that both members of the second pair use some
727       // element of the first pair (to allow for splatting).
728
729       DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
730                                                    ConnectedPairDeps;
731       DenseMap<VPPair, unsigned> PairConnectionTypes;
732       computeConnectedPairs(CandidatePairs, CandidatePairsSet,
733                             PairableInsts, ConnectedPairs, PairConnectionTypes);
734       if (ConnectedPairs.empty()) continue;
735
736       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
737            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
738            I != IE; ++I)
739         for (std::vector<ValuePair>::iterator J = I->second.begin(),
740              JE = I->second.end(); J != JE; ++J)
741           ConnectedPairDeps[*J].push_back(I->first);
742
743       // Build the pairable-instruction dependency map
744       DenseSet<ValuePair> PairableInstUsers;
745       buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
746
747       // There is now a graph of the connected pairs. For each variable, pick
748       // the pairing with the largest dag meeting the depth requirement on at
749       // least one branch. Then select all pairings that are part of that dag
750       // and remove them from the list of available pairings and pairable
751       // variables.
752
753       DenseMap<Value *, Value *> ChosenPairs;
754       choosePairs(CandidatePairs, CandidatePairsSet,
755         CandidatePairCostSavings,
756         PairableInsts, FixedOrderPairs, PairConnectionTypes,
757         ConnectedPairs, ConnectedPairDeps,
758         PairableInstUsers, ChosenPairs);
759
760       if (ChosenPairs.empty()) continue;
761       AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
762                               PairableInsts.end());
763       AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
764
765       // Only for the chosen pairs, propagate information on fixed-order pairs,
766       // pair connections, and their types to the data structures used by the
767       // pair fusion procedures.
768       for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
769            IE = ChosenPairs.end(); I != IE; ++I) {
770         if (FixedOrderPairs.count(*I))
771           AllFixedOrderPairs.insert(*I);
772         else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
773           AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
774
775         for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
776              J != IE; ++J) {
777           DenseMap<VPPair, unsigned>::iterator K =
778             PairConnectionTypes.find(VPPair(*I, *J));
779           if (K != PairConnectionTypes.end()) {
780             AllPairConnectionTypes.insert(*K);
781           } else {
782             K = PairConnectionTypes.find(VPPair(*J, *I));
783             if (K != PairConnectionTypes.end())
784               AllPairConnectionTypes.insert(*K);
785           }
786         }
787       }
788
789       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
790            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
791            I != IE; ++I)
792         for (std::vector<ValuePair>::iterator J = I->second.begin(),
793           JE = I->second.end(); J != JE; ++J)
794           if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
795             AllConnectedPairs[I->first].push_back(*J);
796             AllConnectedPairDeps[*J].push_back(I->first);
797           }
798     } while (ShouldContinue);
799
800     if (AllChosenPairs.empty()) return false;
801     NumFusedOps += AllChosenPairs.size();
802
803     // A set of pairs has now been selected. It is now necessary to replace the
804     // paired instructions with vector instructions. For this procedure each
805     // operand must be replaced with a vector operand. This vector is formed
806     // by using build_vector on the old operands. The replaced values are then
807     // replaced with a vector_extract on the result.  Subsequent optimization
808     // passes should coalesce the build/extract combinations.
809
810     fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
811                     AllPairConnectionTypes,
812                     AllConnectedPairs, AllConnectedPairDeps);
813
814     // It is important to cleanup here so that future iterations of this
815     // function have less work to do.
816     (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
817     return true;
818   }
819
820   // This function returns true if the provided instruction is capable of being
821   // fused into a vector instruction. This determination is based only on the
822   // type and other attributes of the instruction.
823   bool BBVectorize::isInstVectorizable(Instruction *I,
824                                          bool &IsSimpleLoadStore) {
825     IsSimpleLoadStore = false;
826
827     if (CallInst *C = dyn_cast<CallInst>(I)) {
828       if (!isVectorizableIntrinsic(C))
829         return false;
830     } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
831       // Vectorize simple loads if possbile:
832       IsSimpleLoadStore = L->isSimple();
833       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
834         return false;
835     } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
836       // Vectorize simple stores if possbile:
837       IsSimpleLoadStore = S->isSimple();
838       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
839         return false;
840     } else if (CastInst *C = dyn_cast<CastInst>(I)) {
841       // We can vectorize casts, but not casts of pointer types, etc.
842       if (!Config.VectorizeCasts)
843         return false;
844
845       Type *SrcTy = C->getSrcTy();
846       if (!SrcTy->isSingleValueType())
847         return false;
848
849       Type *DestTy = C->getDestTy();
850       if (!DestTy->isSingleValueType())
851         return false;
852     } else if (isa<SelectInst>(I)) {
853       if (!Config.VectorizeSelect)
854         return false;
855     } else if (isa<CmpInst>(I)) {
856       if (!Config.VectorizeCmp)
857         return false;
858     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
859       if (!Config.VectorizeGEP)
860         return false;
861
862       // Currently, vector GEPs exist only with one index.
863       if (G->getNumIndices() != 1)
864         return false;
865     } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
866         isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
867       return false;
868     }
869
870     // We can't vectorize memory operations without target data
871     if (TD == 0 && IsSimpleLoadStore)
872       return false;
873
874     Type *T1, *T2;
875     getInstructionTypes(I, T1, T2);
876
877     // Not every type can be vectorized...
878     if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
879         !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
880       return false;
881
882     if (T1->getScalarSizeInBits() == 1) {
883       if (!Config.VectorizeBools)
884         return false;
885     } else {
886       if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
887         return false;
888     }
889
890     if (T2->getScalarSizeInBits() == 1) {
891       if (!Config.VectorizeBools)
892         return false;
893     } else {
894       if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
895         return false;
896     }
897
898     if (!Config.VectorizeFloats
899         && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
900       return false;
901
902     // Don't vectorize target-specific types.
903     if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
904       return false;
905     if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
906       return false;
907
908     if ((!Config.VectorizePointers || TD == 0) &&
909         (T1->getScalarType()->isPointerTy() ||
910          T2->getScalarType()->isPointerTy()))
911       return false;
912
913     if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
914                  T2->getPrimitiveSizeInBits() >= Config.VectorBits))
915       return false;
916
917     return true;
918   }
919
920   // This function returns true if the two provided instructions are compatible
921   // (meaning that they can be fused into a vector instruction). This assumes
922   // that I has already been determined to be vectorizable and that J is not
923   // in the use dag of I.
924   bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
925                        bool IsSimpleLoadStore, bool NonPow2Len,
926                        int &CostSavings, int &FixedOrder) {
927     DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
928                      " <-> " << *J << "\n");
929
930     CostSavings = 0;
931     FixedOrder = 0;
932
933     // Loads and stores can be merged if they have different alignments,
934     // but are otherwise the same.
935     if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
936                       (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
937       return false;
938
939     Type *IT1, *IT2, *JT1, *JT2;
940     getInstructionTypes(I, IT1, IT2);
941     getInstructionTypes(J, JT1, JT2);
942     unsigned MaxTypeBits = std::max(
943       IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
944       IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
945     if (!TTI && MaxTypeBits > Config.VectorBits)
946       return false;
947
948     // FIXME: handle addsub-type operations!
949
950     if (IsSimpleLoadStore) {
951       Value *IPtr, *JPtr;
952       unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
953       int64_t OffsetInElmts = 0;
954       if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
955             IAddressSpace, JAddressSpace,
956             OffsetInElmts) && abs64(OffsetInElmts) == 1) {
957         FixedOrder = (int) OffsetInElmts;
958         unsigned BottomAlignment = IAlignment;
959         if (OffsetInElmts < 0) BottomAlignment = JAlignment;
960
961         Type *aTypeI = isa<StoreInst>(I) ?
962           cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
963         Type *aTypeJ = isa<StoreInst>(J) ?
964           cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
965         Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
966
967         if (Config.AlignedOnly) {
968           // An aligned load or store is possible only if the instruction
969           // with the lower offset has an alignment suitable for the
970           // vector type.
971
972           unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
973           if (BottomAlignment < VecAlignment)
974             return false;
975         }
976
977         if (TTI) {
978           unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
979                                                 IAlignment, IAddressSpace);
980           unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
981                                                 JAlignment, JAddressSpace);
982           unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
983                                                 BottomAlignment,
984                                                 IAddressSpace);
985
986           ICost += TTI->getAddressComputationCost(aTypeI);
987           JCost += TTI->getAddressComputationCost(aTypeJ);
988           VCost += TTI->getAddressComputationCost(VType);
989
990           if (VCost > ICost + JCost)
991             return false;
992
993           // We don't want to fuse to a type that will be split, even
994           // if the two input types will also be split and there is no other
995           // associated cost.
996           unsigned VParts = TTI->getNumberOfParts(VType);
997           if (VParts > 1)
998             return false;
999           else if (!VParts && VCost == ICost + JCost)
1000             return false;
1001
1002           CostSavings = ICost + JCost - VCost;
1003         }
1004       } else {
1005         return false;
1006       }
1007     } else if (TTI) {
1008       unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1009       unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1010       Type *VT1 = getVecTypeForPair(IT1, JT1),
1011            *VT2 = getVecTypeForPair(IT2, JT2);
1012
1013       // Note that this procedure is incorrect for insert and extract element
1014       // instructions (because combining these often results in a shuffle),
1015       // but this cost is ignored (because insert and extract element
1016       // instructions are assigned a zero depth factor and are not really
1017       // fused in general).
1018       unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
1019
1020       if (VCost > ICost + JCost)
1021         return false;
1022
1023       // We don't want to fuse to a type that will be split, even
1024       // if the two input types will also be split and there is no other
1025       // associated cost.
1026       unsigned VParts1 = TTI->getNumberOfParts(VT1),
1027                VParts2 = TTI->getNumberOfParts(VT2);
1028       if (VParts1 > 1 || VParts2 > 1)
1029         return false;
1030       else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1031         return false;
1032
1033       CostSavings = ICost + JCost - VCost;
1034     }
1035
1036     // The powi intrinsic is special because only the first argument is
1037     // vectorized, the second arguments must be equal.
1038     CallInst *CI = dyn_cast<CallInst>(I);
1039     Function *FI;
1040     if (CI && (FI = CI->getCalledFunction())) {
1041       Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1042       if (IID == Intrinsic::powi) {
1043         Value *A1I = CI->getArgOperand(1),
1044               *A1J = cast<CallInst>(J)->getArgOperand(1);
1045         const SCEV *A1ISCEV = SE->getSCEV(A1I),
1046                    *A1JSCEV = SE->getSCEV(A1J);
1047         return (A1ISCEV == A1JSCEV);
1048       }
1049
1050       if (IID && TTI) {
1051         SmallVector<Type*, 4> Tys;
1052         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1053           Tys.push_back(CI->getArgOperand(i)->getType());
1054         unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1055
1056         Tys.clear();
1057         CallInst *CJ = cast<CallInst>(J);
1058         for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1059           Tys.push_back(CJ->getArgOperand(i)->getType());
1060         unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1061
1062         Tys.clear();
1063         assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1064                "Intrinsic argument counts differ");
1065         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1066           if (IID == Intrinsic::powi && i == 1)
1067             Tys.push_back(CI->getArgOperand(i)->getType());
1068           else
1069             Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1070                                             CJ->getArgOperand(i)->getType()));
1071         }
1072
1073         Type *RetTy = getVecTypeForPair(IT1, JT1);
1074         unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1075
1076         if (VCost > ICost + JCost)
1077           return false;
1078
1079         // We don't want to fuse to a type that will be split, even
1080         // if the two input types will also be split and there is no other
1081         // associated cost.
1082         unsigned RetParts = TTI->getNumberOfParts(RetTy);
1083         if (RetParts > 1)
1084           return false;
1085         else if (!RetParts && VCost == ICost + JCost)
1086           return false;
1087
1088         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1089           if (!Tys[i]->isVectorTy())
1090             continue;
1091
1092           unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1093           if (NumParts > 1)
1094             return false;
1095           else if (!NumParts && VCost == ICost + JCost)
1096             return false;
1097         }
1098
1099         CostSavings = ICost + JCost - VCost;
1100       }
1101     }
1102
1103     return true;
1104   }
1105
1106   // Figure out whether or not J uses I and update the users and write-set
1107   // structures associated with I. Specifically, Users represents the set of
1108   // instructions that depend on I. WriteSet represents the set
1109   // of memory locations that are dependent on I. If UpdateUsers is true,
1110   // and J uses I, then Users is updated to contain J and WriteSet is updated
1111   // to contain any memory locations to which J writes. The function returns
1112   // true if J uses I. By default, alias analysis is used to determine
1113   // whether J reads from memory that overlaps with a location in WriteSet.
1114   // If LoadMoveSet is not null, then it is a previously-computed map
1115   // where the key is the memory-based user instruction and the value is
1116   // the instruction to be compared with I. So, if LoadMoveSet is provided,
1117   // then the alias analysis is not used. This is necessary because this
1118   // function is called during the process of moving instructions during
1119   // vectorization and the results of the alias analysis are not stable during
1120   // that process.
1121   bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1122                        AliasSetTracker &WriteSet, Instruction *I,
1123                        Instruction *J, bool UpdateUsers,
1124                        DenseSet<ValuePair> *LoadMoveSetPairs) {
1125     bool UsesI = false;
1126
1127     // This instruction may already be marked as a user due, for example, to
1128     // being a member of a selected pair.
1129     if (Users.count(J))
1130       UsesI = true;
1131
1132     if (!UsesI)
1133       for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1134            JU != JE; ++JU) {
1135         Value *V = *JU;
1136         if (I == V || Users.count(V)) {
1137           UsesI = true;
1138           break;
1139         }
1140       }
1141     if (!UsesI && J->mayReadFromMemory()) {
1142       if (LoadMoveSetPairs) {
1143         UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1144       } else {
1145         for (AliasSetTracker::iterator W = WriteSet.begin(),
1146              WE = WriteSet.end(); W != WE; ++W) {
1147           if (W->aliasesUnknownInst(J, *AA)) {
1148             UsesI = true;
1149             break;
1150           }
1151         }
1152       }
1153     }
1154
1155     if (UsesI && UpdateUsers) {
1156       if (J->mayWriteToMemory()) WriteSet.add(J);
1157       Users.insert(J);
1158     }
1159
1160     return UsesI;
1161   }
1162
1163   // This function iterates over all instruction pairs in the provided
1164   // basic block and collects all candidate pairs for vectorization.
1165   bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1166                        BasicBlock::iterator &Start,
1167                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1168                        DenseSet<ValuePair> &FixedOrderPairs,
1169                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
1170                        std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1171     size_t TotalPairs = 0;
1172     BasicBlock::iterator E = BB.end();
1173     if (Start == E) return false;
1174
1175     bool ShouldContinue = false, IAfterStart = false;
1176     for (BasicBlock::iterator I = Start++; I != E; ++I) {
1177       if (I == Start) IAfterStart = true;
1178
1179       bool IsSimpleLoadStore;
1180       if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1181
1182       // Look for an instruction with which to pair instruction *I...
1183       DenseSet<Value *> Users;
1184       AliasSetTracker WriteSet(*AA);
1185       bool JAfterStart = IAfterStart;
1186       BasicBlock::iterator J = llvm::next(I);
1187       for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1188         if (J == Start) JAfterStart = true;
1189
1190         // Determine if J uses I, if so, exit the loop.
1191         bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1192         if (Config.FastDep) {
1193           // Note: For this heuristic to be effective, independent operations
1194           // must tend to be intermixed. This is likely to be true from some
1195           // kinds of grouped loop unrolling (but not the generic LLVM pass),
1196           // but otherwise may require some kind of reordering pass.
1197
1198           // When using fast dependency analysis,
1199           // stop searching after first use:
1200           if (UsesI) break;
1201         } else {
1202           if (UsesI) continue;
1203         }
1204
1205         // J does not use I, and comes before the first use of I, so it can be
1206         // merged with I if the instructions are compatible.
1207         int CostSavings, FixedOrder;
1208         if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1209             CostSavings, FixedOrder)) continue;
1210
1211         // J is a candidate for merging with I.
1212         if (!PairableInsts.size() ||
1213              PairableInsts[PairableInsts.size()-1] != I) {
1214           PairableInsts.push_back(I);
1215         }
1216
1217         CandidatePairs[I].push_back(J);
1218         ++TotalPairs;
1219         if (TTI)
1220           CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1221                                                             CostSavings));
1222
1223         if (FixedOrder == 1)
1224           FixedOrderPairs.insert(ValuePair(I, J));
1225         else if (FixedOrder == -1)
1226           FixedOrderPairs.insert(ValuePair(J, I));
1227
1228         // The next call to this function must start after the last instruction
1229         // selected during this invocation.
1230         if (JAfterStart) {
1231           Start = llvm::next(J);
1232           IAfterStart = JAfterStart = false;
1233         }
1234
1235         DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1236                      << *I << " <-> " << *J << " (cost savings: " <<
1237                      CostSavings << ")\n");
1238
1239         // If we have already found too many pairs, break here and this function
1240         // will be called again starting after the last instruction selected
1241         // during this invocation.
1242         if (PairableInsts.size() >= Config.MaxInsts ||
1243             TotalPairs >= Config.MaxPairs) {
1244           ShouldContinue = true;
1245           break;
1246         }
1247       }
1248
1249       if (ShouldContinue)
1250         break;
1251     }
1252
1253     DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1254            << " instructions with candidate pairs\n");
1255
1256     return ShouldContinue;
1257   }
1258
1259   // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1260   // it looks for pairs such that both members have an input which is an
1261   // output of PI or PJ.
1262   void BBVectorize::computePairsConnectedTo(
1263                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1264                   DenseSet<ValuePair> &CandidatePairsSet,
1265                   std::vector<Value *> &PairableInsts,
1266                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1267                   DenseMap<VPPair, unsigned> &PairConnectionTypes,
1268                   ValuePair P) {
1269     StoreInst *SI, *SJ;
1270
1271     // For each possible pairing for this variable, look at the uses of
1272     // the first value...
1273     for (Value::use_iterator I = P.first->use_begin(),
1274          E = P.first->use_end(); I != E; ++I) {
1275       if (isa<LoadInst>(*I)) {
1276         // A pair cannot be connected to a load because the load only takes one
1277         // operand (the address) and it is a scalar even after vectorization.
1278         continue;
1279       } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1280                  P.first == SI->getPointerOperand()) {
1281         // Similarly, a pair cannot be connected to a store through its
1282         // pointer operand.
1283         continue;
1284       }
1285
1286       // For each use of the first variable, look for uses of the second
1287       // variable...
1288       for (Value::use_iterator J = P.second->use_begin(),
1289            E2 = P.second->use_end(); J != E2; ++J) {
1290         if ((SJ = dyn_cast<StoreInst>(*J)) &&
1291             P.second == SJ->getPointerOperand())
1292           continue;
1293
1294         // Look for <I, J>:
1295         if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1296           VPPair VP(P, ValuePair(*I, *J));
1297           ConnectedPairs[VP.first].push_back(VP.second);
1298           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1299         }
1300
1301         // Look for <J, I>:
1302         if (CandidatePairsSet.count(ValuePair(*J, *I))) {
1303           VPPair VP(P, ValuePair(*J, *I));
1304           ConnectedPairs[VP.first].push_back(VP.second);
1305           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1306         }
1307       }
1308
1309       if (Config.SplatBreaksChain) continue;
1310       // Look for cases where just the first value in the pair is used by
1311       // both members of another pair (splatting).
1312       for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1313         if ((SJ = dyn_cast<StoreInst>(*J)) &&
1314             P.first == SJ->getPointerOperand())
1315           continue;
1316
1317         if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1318           VPPair VP(P, ValuePair(*I, *J));
1319           ConnectedPairs[VP.first].push_back(VP.second);
1320           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1321         }
1322       }
1323     }
1324
1325     if (Config.SplatBreaksChain) return;
1326     // Look for cases where just the second value in the pair is used by
1327     // both members of another pair (splatting).
1328     for (Value::use_iterator I = P.second->use_begin(),
1329          E = P.second->use_end(); I != E; ++I) {
1330       if (isa<LoadInst>(*I))
1331         continue;
1332       else if ((SI = dyn_cast<StoreInst>(*I)) &&
1333                P.second == SI->getPointerOperand())
1334         continue;
1335
1336       for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1337         if ((SJ = dyn_cast<StoreInst>(*J)) &&
1338             P.second == SJ->getPointerOperand())
1339           continue;
1340
1341         if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1342           VPPair VP(P, ValuePair(*I, *J));
1343           ConnectedPairs[VP.first].push_back(VP.second);
1344           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1345         }
1346       }
1347     }
1348   }
1349
1350   // This function figures out which pairs are connected.  Two pairs are
1351   // connected if some output of the first pair forms an input to both members
1352   // of the second pair.
1353   void BBVectorize::computeConnectedPairs(
1354                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1355                   DenseSet<ValuePair> &CandidatePairsSet,
1356                   std::vector<Value *> &PairableInsts,
1357                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1358                   DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1359     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1360          PE = PairableInsts.end(); PI != PE; ++PI) {
1361       DenseMap<Value *, std::vector<Value *> >::iterator PP =
1362         CandidatePairs.find(*PI);
1363       if (PP == CandidatePairs.end())
1364         continue;
1365
1366       for (std::vector<Value *>::iterator P = PP->second.begin(),
1367            E = PP->second.end(); P != E; ++P)
1368         computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1369                                 PairableInsts, ConnectedPairs,
1370                                 PairConnectionTypes, ValuePair(*PI, *P));
1371     }
1372
1373     DEBUG(size_t TotalPairs = 0;
1374           for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1375                ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1376             TotalPairs += I->second.size();
1377           dbgs() << "BBV: found " << TotalPairs
1378                  << " pair connections.\n");
1379   }
1380
1381   // This function builds a set of use tuples such that <A, B> is in the set
1382   // if B is in the use dag of A. If B is in the use dag of A, then B
1383   // depends on the output of A.
1384   void BBVectorize::buildDepMap(
1385                       BasicBlock &BB,
1386                       DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1387                       std::vector<Value *> &PairableInsts,
1388                       DenseSet<ValuePair> &PairableInstUsers) {
1389     DenseSet<Value *> IsInPair;
1390     for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1391          CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1392       IsInPair.insert(C->first);
1393       IsInPair.insert(C->second.begin(), C->second.end());
1394     }
1395
1396     // Iterate through the basic block, recording all users of each
1397     // pairable instruction.
1398
1399     BasicBlock::iterator E = BB.end(), EL =
1400       BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1401     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1402       if (IsInPair.find(I) == IsInPair.end()) continue;
1403
1404       DenseSet<Value *> Users;
1405       AliasSetTracker WriteSet(*AA);
1406       for (BasicBlock::iterator J = llvm::next(I); J != E; ++J) {
1407         (void) trackUsesOfI(Users, WriteSet, I, J);
1408
1409         if (J == EL)
1410           break;
1411       }
1412
1413       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1414            U != E; ++U) {
1415         if (IsInPair.find(*U) == IsInPair.end()) continue;
1416         PairableInstUsers.insert(ValuePair(I, *U));
1417       }
1418
1419       if (I == EL)
1420         break;
1421     }
1422   }
1423
1424   // Returns true if an input to pair P is an output of pair Q and also an
1425   // input of pair Q is an output of pair P. If this is the case, then these
1426   // two pairs cannot be simultaneously fused.
1427   bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1428              DenseSet<ValuePair> &PairableInstUsers,
1429              DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1430              DenseSet<VPPair> *PairableInstUserPairSet) {
1431     // Two pairs are in conflict if they are mutual Users of eachother.
1432     bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
1433                   PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
1434                   PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
1435                   PairableInstUsers.count(ValuePair(P.second, Q.second));
1436     bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
1437                   PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
1438                   PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
1439                   PairableInstUsers.count(ValuePair(Q.second, P.second));
1440     if (PairableInstUserMap) {
1441       // FIXME: The expensive part of the cycle check is not so much the cycle
1442       // check itself but this edge insertion procedure. This needs some
1443       // profiling and probably a different data structure.
1444       if (PUsesQ) {
1445         if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1446           (*PairableInstUserMap)[Q].push_back(P);
1447       }
1448       if (QUsesP) {
1449         if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1450           (*PairableInstUserMap)[P].push_back(Q);
1451       }
1452     }
1453
1454     return (QUsesP && PUsesQ);
1455   }
1456
1457   // This function walks the use graph of current pairs to see if, starting
1458   // from P, the walk returns to P.
1459   bool BBVectorize::pairWillFormCycle(ValuePair P,
1460              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1461              DenseSet<ValuePair> &CurrentPairs) {
1462     DEBUG(if (DebugCycleCheck)
1463             dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1464                    << *P.second << "\n");
1465     // A lookup table of visisted pairs is kept because the PairableInstUserMap
1466     // contains non-direct associations.
1467     DenseSet<ValuePair> Visited;
1468     SmallVector<ValuePair, 32> Q;
1469     // General depth-first post-order traversal:
1470     Q.push_back(P);
1471     do {
1472       ValuePair QTop = Q.pop_back_val();
1473       Visited.insert(QTop);
1474
1475       DEBUG(if (DebugCycleCheck)
1476               dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1477                      << *QTop.second << "\n");
1478       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1479         PairableInstUserMap.find(QTop);
1480       if (QQ == PairableInstUserMap.end())
1481         continue;
1482
1483       for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1484            CE = QQ->second.end(); C != CE; ++C) {
1485         if (*C == P) {
1486           DEBUG(dbgs()
1487                  << "BBV: rejected to prevent non-trivial cycle formation: "
1488                  << QTop.first << " <-> " << C->second << "\n");
1489           return true;
1490         }
1491
1492         if (CurrentPairs.count(*C) && !Visited.count(*C))
1493           Q.push_back(*C);
1494       }
1495     } while (!Q.empty());
1496
1497     return false;
1498   }
1499
1500   // This function builds the initial dag of connected pairs with the
1501   // pair J at the root.
1502   void BBVectorize::buildInitialDAGFor(
1503                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1504                   DenseSet<ValuePair> &CandidatePairsSet,
1505                   std::vector<Value *> &PairableInsts,
1506                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1507                   DenseSet<ValuePair> &PairableInstUsers,
1508                   DenseMap<Value *, Value *> &ChosenPairs,
1509                   DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1510     // Each of these pairs is viewed as the root node of a DAG. The DAG
1511     // is then walked (depth-first). As this happens, we keep track of
1512     // the pairs that compose the DAG and the maximum depth of the DAG.
1513     SmallVector<ValuePairWithDepth, 32> Q;
1514     // General depth-first post-order traversal:
1515     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1516     do {
1517       ValuePairWithDepth QTop = Q.back();
1518
1519       // Push each child onto the queue:
1520       bool MoreChildren = false;
1521       size_t MaxChildDepth = QTop.second;
1522       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1523         ConnectedPairs.find(QTop.first);
1524       if (QQ != ConnectedPairs.end())
1525         for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1526              ke = QQ->second.end(); k != ke; ++k) {
1527           // Make sure that this child pair is still a candidate:
1528           if (CandidatePairsSet.count(*k)) {
1529             DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
1530             if (C == DAG.end()) {
1531               size_t d = getDepthFactor(k->first);
1532               Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1533               MoreChildren = true;
1534             } else {
1535               MaxChildDepth = std::max(MaxChildDepth, C->second);
1536             }
1537           }
1538         }
1539
1540       if (!MoreChildren) {
1541         // Record the current pair as part of the DAG:
1542         DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1543         Q.pop_back();
1544       }
1545     } while (!Q.empty());
1546   }
1547
1548   // Given some initial dag, prune it by removing conflicting pairs (pairs
1549   // that cannot be simultaneously chosen for vectorization).
1550   void BBVectorize::pruneDAGFor(
1551               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1552               std::vector<Value *> &PairableInsts,
1553               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1554               DenseSet<ValuePair> &PairableInstUsers,
1555               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1556               DenseSet<VPPair> &PairableInstUserPairSet,
1557               DenseMap<Value *, Value *> &ChosenPairs,
1558               DenseMap<ValuePair, size_t> &DAG,
1559               DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1560               bool UseCycleCheck) {
1561     SmallVector<ValuePairWithDepth, 32> Q;
1562     // General depth-first post-order traversal:
1563     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1564     do {
1565       ValuePairWithDepth QTop = Q.pop_back_val();
1566       PrunedDAG.insert(QTop.first);
1567
1568       // Visit each child, pruning as necessary...
1569       SmallVector<ValuePairWithDepth, 8> BestChildren;
1570       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1571         ConnectedPairs.find(QTop.first);
1572       if (QQ == ConnectedPairs.end())
1573         continue;
1574
1575       for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1576            KE = QQ->second.end(); K != KE; ++K) {
1577         DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
1578         if (C == DAG.end()) continue;
1579
1580         // This child is in the DAG, now we need to make sure it is the
1581         // best of any conflicting children. There could be multiple
1582         // conflicting children, so first, determine if we're keeping
1583         // this child, then delete conflicting children as necessary.
1584
1585         // It is also necessary to guard against pairing-induced
1586         // dependencies. Consider instructions a .. x .. y .. b
1587         // such that (a,b) are to be fused and (x,y) are to be fused
1588         // but a is an input to x and b is an output from y. This
1589         // means that y cannot be moved after b but x must be moved
1590         // after b for (a,b) to be fused. In other words, after
1591         // fusing (a,b) we have y .. a/b .. x where y is an input
1592         // to a/b and x is an output to a/b: x and y can no longer
1593         // be legally fused. To prevent this condition, we must
1594         // make sure that a child pair added to the DAG is not
1595         // both an input and output of an already-selected pair.
1596
1597         // Pairing-induced dependencies can also form from more complicated
1598         // cycles. The pair vs. pair conflicts are easy to check, and so
1599         // that is done explicitly for "fast rejection", and because for
1600         // child vs. child conflicts, we may prefer to keep the current
1601         // pair in preference to the already-selected child.
1602         DenseSet<ValuePair> CurrentPairs;
1603
1604         bool CanAdd = true;
1605         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1606               = BestChildren.begin(), E2 = BestChildren.end();
1607              C2 != E2; ++C2) {
1608           if (C2->first.first == C->first.first ||
1609               C2->first.first == C->first.second ||
1610               C2->first.second == C->first.first ||
1611               C2->first.second == C->first.second ||
1612               pairsConflict(C2->first, C->first, PairableInstUsers,
1613                             UseCycleCheck ? &PairableInstUserMap : 0,
1614                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1615             if (C2->second >= C->second) {
1616               CanAdd = false;
1617               break;
1618             }
1619
1620             CurrentPairs.insert(C2->first);
1621           }
1622         }
1623         if (!CanAdd) continue;
1624
1625         // Even worse, this child could conflict with another node already
1626         // selected for the DAG. If that is the case, ignore this child.
1627         for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1628              E2 = PrunedDAG.end(); T != E2; ++T) {
1629           if (T->first == C->first.first ||
1630               T->first == C->first.second ||
1631               T->second == C->first.first ||
1632               T->second == C->first.second ||
1633               pairsConflict(*T, C->first, PairableInstUsers,
1634                             UseCycleCheck ? &PairableInstUserMap : 0,
1635                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1636             CanAdd = false;
1637             break;
1638           }
1639
1640           CurrentPairs.insert(*T);
1641         }
1642         if (!CanAdd) continue;
1643
1644         // And check the queue too...
1645         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
1646              E2 = Q.end(); C2 != E2; ++C2) {
1647           if (C2->first.first == C->first.first ||
1648               C2->first.first == C->first.second ||
1649               C2->first.second == C->first.first ||
1650               C2->first.second == C->first.second ||
1651               pairsConflict(C2->first, C->first, PairableInstUsers,
1652                             UseCycleCheck ? &PairableInstUserMap : 0,
1653                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1654             CanAdd = false;
1655             break;
1656           }
1657
1658           CurrentPairs.insert(C2->first);
1659         }
1660         if (!CanAdd) continue;
1661
1662         // Last but not least, check for a conflict with any of the
1663         // already-chosen pairs.
1664         for (DenseMap<Value *, Value *>::iterator C2 =
1665               ChosenPairs.begin(), E2 = ChosenPairs.end();
1666              C2 != E2; ++C2) {
1667           if (pairsConflict(*C2, C->first, PairableInstUsers,
1668                             UseCycleCheck ? &PairableInstUserMap : 0,
1669                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1670             CanAdd = false;
1671             break;
1672           }
1673
1674           CurrentPairs.insert(*C2);
1675         }
1676         if (!CanAdd) continue;
1677
1678         // To check for non-trivial cycles formed by the addition of the
1679         // current pair we've formed a list of all relevant pairs, now use a
1680         // graph walk to check for a cycle. We start from the current pair and
1681         // walk the use dag to see if we again reach the current pair. If we
1682         // do, then the current pair is rejected.
1683
1684         // FIXME: It may be more efficient to use a topological-ordering
1685         // algorithm to improve the cycle check. This should be investigated.
1686         if (UseCycleCheck &&
1687             pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1688           continue;
1689
1690         // This child can be added, but we may have chosen it in preference
1691         // to an already-selected child. Check for this here, and if a
1692         // conflict is found, then remove the previously-selected child
1693         // before adding this one in its place.
1694         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1695               = BestChildren.begin(); C2 != BestChildren.end();) {
1696           if (C2->first.first == C->first.first ||
1697               C2->first.first == C->first.second ||
1698               C2->first.second == C->first.first ||
1699               C2->first.second == C->first.second ||
1700               pairsConflict(C2->first, C->first, PairableInstUsers))
1701             C2 = BestChildren.erase(C2);
1702           else
1703             ++C2;
1704         }
1705
1706         BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1707       }
1708
1709       for (SmallVectorImpl<ValuePairWithDepth>::iterator C
1710             = BestChildren.begin(), E2 = BestChildren.end();
1711            C != E2; ++C) {
1712         size_t DepthF = getDepthFactor(C->first.first);
1713         Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1714       }
1715     } while (!Q.empty());
1716   }
1717
1718   // This function finds the best dag of mututally-compatible connected
1719   // pairs, given the choice of root pairs as an iterator range.
1720   void BBVectorize::findBestDAGFor(
1721               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1722               DenseSet<ValuePair> &CandidatePairsSet,
1723               DenseMap<ValuePair, int> &CandidatePairCostSavings,
1724               std::vector<Value *> &PairableInsts,
1725               DenseSet<ValuePair> &FixedOrderPairs,
1726               DenseMap<VPPair, unsigned> &PairConnectionTypes,
1727               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1728               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1729               DenseSet<ValuePair> &PairableInstUsers,
1730               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1731               DenseSet<VPPair> &PairableInstUserPairSet,
1732               DenseMap<Value *, Value *> &ChosenPairs,
1733               DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1734               int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1735               bool UseCycleCheck) {
1736     for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1737          J != JE; ++J) {
1738       ValuePair IJ(II, *J);
1739       if (!CandidatePairsSet.count(IJ))
1740         continue;
1741
1742       // Before going any further, make sure that this pair does not
1743       // conflict with any already-selected pairs (see comment below
1744       // near the DAG pruning for more details).
1745       DenseSet<ValuePair> ChosenPairSet;
1746       bool DoesConflict = false;
1747       for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1748            E = ChosenPairs.end(); C != E; ++C) {
1749         if (pairsConflict(*C, IJ, PairableInstUsers,
1750                           UseCycleCheck ? &PairableInstUserMap : 0,
1751                           UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1752           DoesConflict = true;
1753           break;
1754         }
1755
1756         ChosenPairSet.insert(*C);
1757       }
1758       if (DoesConflict) continue;
1759
1760       if (UseCycleCheck &&
1761           pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1762         continue;
1763
1764       DenseMap<ValuePair, size_t> DAG;
1765       buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1766                           PairableInsts, ConnectedPairs,
1767                           PairableInstUsers, ChosenPairs, DAG, IJ);
1768
1769       // Because we'll keep the child with the largest depth, the largest
1770       // depth is still the same in the unpruned DAG.
1771       size_t MaxDepth = DAG.lookup(IJ);
1772
1773       DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1774                    << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1775                    MaxDepth << " and size " << DAG.size() << "\n");
1776
1777       // At this point the DAG has been constructed, but, may contain
1778       // contradictory children (meaning that different children of
1779       // some dag node may be attempting to fuse the same instruction).
1780       // So now we walk the dag again, in the case of a conflict,
1781       // keep only the child with the largest depth. To break a tie,
1782       // favor the first child.
1783
1784       DenseSet<ValuePair> PrunedDAG;
1785       pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1786                    PairableInstUsers, PairableInstUserMap,
1787                    PairableInstUserPairSet,
1788                    ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1789
1790       int EffSize = 0;
1791       if (TTI) {
1792         DenseSet<Value *> PrunedDAGInstrs;
1793         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1794              E = PrunedDAG.end(); S != E; ++S) {
1795           PrunedDAGInstrs.insert(S->first);
1796           PrunedDAGInstrs.insert(S->second);
1797         }
1798
1799         // The set of pairs that have already contributed to the total cost.
1800         DenseSet<ValuePair> IncomingPairs;
1801
1802         // If the cost model were perfect, this might not be necessary; but we
1803         // need to make sure that we don't get stuck vectorizing our own
1804         // shuffle chains.
1805         bool HasNontrivialInsts = false;
1806
1807         // The node weights represent the cost savings associated with
1808         // fusing the pair of instructions.
1809         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1810              E = PrunedDAG.end(); S != E; ++S) {
1811           if (!isa<ShuffleVectorInst>(S->first) &&
1812               !isa<InsertElementInst>(S->first) &&
1813               !isa<ExtractElementInst>(S->first))
1814             HasNontrivialInsts = true;
1815
1816           bool FlipOrder = false;
1817
1818           if (getDepthFactor(S->first)) {
1819             int ESContrib = CandidatePairCostSavings.find(*S)->second;
1820             DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1821                    << *S->first << " <-> " << *S->second << "} = " <<
1822                    ESContrib << "\n");
1823             EffSize += ESContrib;
1824           }
1825
1826           // The edge weights contribute in a negative sense: they represent
1827           // the cost of shuffles.
1828           DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1829             ConnectedPairDeps.find(*S);
1830           if (SS != ConnectedPairDeps.end()) {
1831             unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1832             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1833                  TE = SS->second.end(); T != TE; ++T) {
1834               VPPair Q(*S, *T);
1835               if (!PrunedDAG.count(Q.second))
1836                 continue;
1837               DenseMap<VPPair, unsigned>::iterator R =
1838                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1839               assert(R != PairConnectionTypes.end() &&
1840                      "Cannot find pair connection type");
1841               if (R->second == PairConnectionDirect)
1842                 ++NumDepsDirect;
1843               else if (R->second == PairConnectionSwap)
1844                 ++NumDepsSwap;
1845             }
1846
1847             // If there are more swaps than direct connections, then
1848             // the pair order will be flipped during fusion. So the real
1849             // number of swaps is the minimum number.
1850             FlipOrder = !FixedOrderPairs.count(*S) &&
1851               ((NumDepsSwap > NumDepsDirect) ||
1852                 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1853
1854             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1855                  TE = SS->second.end(); T != TE; ++T) {
1856               VPPair Q(*S, *T);
1857               if (!PrunedDAG.count(Q.second))
1858                 continue;
1859               DenseMap<VPPair, unsigned>::iterator R =
1860                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1861               assert(R != PairConnectionTypes.end() &&
1862                      "Cannot find pair connection type");
1863               Type *Ty1 = Q.second.first->getType(),
1864                    *Ty2 = Q.second.second->getType();
1865               Type *VTy = getVecTypeForPair(Ty1, Ty2);
1866               if ((R->second == PairConnectionDirect && FlipOrder) ||
1867                   (R->second == PairConnectionSwap && !FlipOrder)  ||
1868                   R->second == PairConnectionSplat) {
1869                 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1870                                                    VTy, VTy);
1871
1872                 if (VTy->getVectorNumElements() == 2) {
1873                   if (R->second == PairConnectionSplat)
1874                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1875                       TargetTransformInfo::SK_Broadcast, VTy));
1876                   else
1877                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1878                       TargetTransformInfo::SK_Reverse, VTy));
1879                 }
1880
1881                 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1882                   *Q.second.first << " <-> " << *Q.second.second <<
1883                     "} -> {" <<
1884                   *S->first << " <-> " << *S->second << "} = " <<
1885                    ESContrib << "\n");
1886                 EffSize -= ESContrib;
1887               }
1888             }
1889           }
1890
1891           // Compute the cost of outgoing edges. We assume that edges outgoing
1892           // to shuffles, inserts or extracts can be merged, and so contribute
1893           // no additional cost.
1894           if (!S->first->getType()->isVoidTy()) {
1895             Type *Ty1 = S->first->getType(),
1896                  *Ty2 = S->second->getType();
1897             Type *VTy = getVecTypeForPair(Ty1, Ty2);
1898
1899             bool NeedsExtraction = false;
1900             for (Value::use_iterator I = S->first->use_begin(),
1901                  IE = S->first->use_end(); I != IE; ++I) {
1902               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1903                 // Shuffle can be folded if it has no other input
1904                 if (isa<UndefValue>(SI->getOperand(1)))
1905                   continue;
1906               }
1907               if (isa<ExtractElementInst>(*I))
1908                 continue;
1909               if (PrunedDAGInstrs.count(*I))
1910                 continue;
1911               NeedsExtraction = true;
1912               break;
1913             }
1914
1915             if (NeedsExtraction) {
1916               int ESContrib;
1917               if (Ty1->isVectorTy()) {
1918                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1919                                                Ty1, VTy);
1920                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1921                   TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1922               } else
1923                 ESContrib = (int) TTI->getVectorInstrCost(
1924                                     Instruction::ExtractElement, VTy, 0);
1925
1926               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1927                 *S->first << "} = " << ESContrib << "\n");
1928               EffSize -= ESContrib;
1929             }
1930
1931             NeedsExtraction = false;
1932             for (Value::use_iterator I = S->second->use_begin(),
1933                  IE = S->second->use_end(); I != IE; ++I) {
1934               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1935                 // Shuffle can be folded if it has no other input
1936                 if (isa<UndefValue>(SI->getOperand(1)))
1937                   continue;
1938               }
1939               if (isa<ExtractElementInst>(*I))
1940                 continue;
1941               if (PrunedDAGInstrs.count(*I))
1942                 continue;
1943               NeedsExtraction = true;
1944               break;
1945             }
1946
1947             if (NeedsExtraction) {
1948               int ESContrib;
1949               if (Ty2->isVectorTy()) {
1950                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1951                                                Ty2, VTy);
1952                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1953                   TargetTransformInfo::SK_ExtractSubvector, VTy,
1954                   Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
1955               } else
1956                 ESContrib = (int) TTI->getVectorInstrCost(
1957                                     Instruction::ExtractElement, VTy, 1);
1958               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1959                 *S->second << "} = " << ESContrib << "\n");
1960               EffSize -= ESContrib;
1961             }
1962           }
1963
1964           // Compute the cost of incoming edges.
1965           if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
1966             Instruction *S1 = cast<Instruction>(S->first),
1967                         *S2 = cast<Instruction>(S->second);
1968             for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
1969               Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
1970
1971               // Combining constants into vector constants (or small vector
1972               // constants into larger ones are assumed free).
1973               if (isa<Constant>(O1) && isa<Constant>(O2))
1974                 continue;
1975
1976               if (FlipOrder)
1977                 std::swap(O1, O2);
1978
1979               ValuePair VP  = ValuePair(O1, O2);
1980               ValuePair VPR = ValuePair(O2, O1);
1981
1982               // Internal edges are not handled here.
1983               if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
1984                 continue;
1985
1986               Type *Ty1 = O1->getType(),
1987                    *Ty2 = O2->getType();
1988               Type *VTy = getVecTypeForPair(Ty1, Ty2);
1989
1990               // Combining vector operations of the same type is also assumed
1991               // folded with other operations.
1992               if (Ty1 == Ty2) {
1993                 // If both are insert elements, then both can be widened.
1994                 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
1995                                   *IEO2 = dyn_cast<InsertElementInst>(O2);
1996                 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
1997                   continue;
1998                 // If both are extract elements, and both have the same input
1999                 // type, then they can be replaced with a shuffle
2000                 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2001                                    *EIO2 = dyn_cast<ExtractElementInst>(O2);
2002                 if (EIO1 && EIO2 &&
2003                     EIO1->getOperand(0)->getType() ==
2004                       EIO2->getOperand(0)->getType())
2005                   continue;
2006                 // If both are a shuffle with equal operand types and only two
2007                 // unqiue operands, then they can be replaced with a single
2008                 // shuffle
2009                 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2010                                   *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2011                 if (SIO1 && SIO2 &&
2012                     SIO1->getOperand(0)->getType() ==
2013                       SIO2->getOperand(0)->getType()) {
2014                   SmallSet<Value *, 4> SIOps;
2015                   SIOps.insert(SIO1->getOperand(0));
2016                   SIOps.insert(SIO1->getOperand(1));
2017                   SIOps.insert(SIO2->getOperand(0));
2018                   SIOps.insert(SIO2->getOperand(1));
2019                   if (SIOps.size() <= 2)
2020                     continue;
2021                 }
2022               }
2023
2024               int ESContrib;
2025               // This pair has already been formed.
2026               if (IncomingPairs.count(VP)) {
2027                 continue;
2028               } else if (IncomingPairs.count(VPR)) {
2029                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2030                                                VTy, VTy);
2031
2032                 if (VTy->getVectorNumElements() == 2)
2033                   ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2034                     TargetTransformInfo::SK_Reverse, VTy));
2035               } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2036                 ESContrib = (int) TTI->getVectorInstrCost(
2037                                     Instruction::InsertElement, VTy, 0);
2038                 ESContrib += (int) TTI->getVectorInstrCost(
2039                                      Instruction::InsertElement, VTy, 1);
2040               } else if (!Ty1->isVectorTy()) {
2041                 // O1 needs to be inserted into a vector of size O2, and then
2042                 // both need to be shuffled together.
2043                 ESContrib = (int) TTI->getVectorInstrCost(
2044                                     Instruction::InsertElement, Ty2, 0);
2045                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2046                                                 VTy, Ty2);
2047               } else if (!Ty2->isVectorTy()) {
2048                 // O2 needs to be inserted into a vector of size O1, and then
2049                 // both need to be shuffled together.
2050                 ESContrib = (int) TTI->getVectorInstrCost(
2051                                     Instruction::InsertElement, Ty1, 0);
2052                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2053                                                 VTy, Ty1);
2054               } else {
2055                 Type *TyBig = Ty1, *TySmall = Ty2;
2056                 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2057                   std::swap(TyBig, TySmall);
2058
2059                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2060                                                VTy, TyBig);
2061                 if (TyBig != TySmall)
2062                   ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2063                                                   TyBig, TySmall);
2064               }
2065
2066               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2067                      << *O1 << " <-> " << *O2 << "} = " <<
2068                      ESContrib << "\n");
2069               EffSize -= ESContrib;
2070               IncomingPairs.insert(VP);
2071             }
2072           }
2073         }
2074
2075         if (!HasNontrivialInsts) {
2076           DEBUG(if (DebugPairSelection) dbgs() <<
2077                 "\tNo non-trivial instructions in DAG;"
2078                 " override to zero effective size\n");
2079           EffSize = 0;
2080         }
2081       } else {
2082         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2083              E = PrunedDAG.end(); S != E; ++S)
2084           EffSize += (int) getDepthFactor(S->first);
2085       }
2086
2087       DEBUG(if (DebugPairSelection)
2088              dbgs() << "BBV: found pruned DAG for pair {"
2089              << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2090              MaxDepth << " and size " << PrunedDAG.size() <<
2091             " (effective size: " << EffSize << ")\n");
2092       if (((TTI && !UseChainDepthWithTI) ||
2093             MaxDepth >= Config.ReqChainDepth) &&
2094           EffSize > 0 && EffSize > BestEffSize) {
2095         BestMaxDepth = MaxDepth;
2096         BestEffSize = EffSize;
2097         BestDAG = PrunedDAG;
2098       }
2099     }
2100   }
2101
2102   // Given the list of candidate pairs, this function selects those
2103   // that will be fused into vector instructions.
2104   void BBVectorize::choosePairs(
2105                 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2106                 DenseSet<ValuePair> &CandidatePairsSet,
2107                 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2108                 std::vector<Value *> &PairableInsts,
2109                 DenseSet<ValuePair> &FixedOrderPairs,
2110                 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2111                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2112                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2113                 DenseSet<ValuePair> &PairableInstUsers,
2114                 DenseMap<Value *, Value *>& ChosenPairs) {
2115     bool UseCycleCheck =
2116      CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2117
2118     DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2119     for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2120          E = CandidatePairsSet.end(); I != E; ++I) {
2121       std::vector<Value *> &JJ = CandidatePairs2[I->second];
2122       if (JJ.empty()) JJ.reserve(32);
2123       JJ.push_back(I->first);
2124     }
2125
2126     DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2127     DenseSet<VPPair> PairableInstUserPairSet;
2128     for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2129          E = PairableInsts.end(); I != E; ++I) {
2130       // The number of possible pairings for this variable:
2131       size_t NumChoices = CandidatePairs.lookup(*I).size();
2132       if (!NumChoices) continue;
2133
2134       std::vector<Value *> &JJ = CandidatePairs[*I];
2135
2136       // The best pair to choose and its dag:
2137       size_t BestMaxDepth = 0;
2138       int BestEffSize = 0;
2139       DenseSet<ValuePair> BestDAG;
2140       findBestDAGFor(CandidatePairs, CandidatePairsSet,
2141                       CandidatePairCostSavings,
2142                       PairableInsts, FixedOrderPairs, PairConnectionTypes,
2143                       ConnectedPairs, ConnectedPairDeps,
2144                       PairableInstUsers, PairableInstUserMap,
2145                       PairableInstUserPairSet, ChosenPairs,
2146                       BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2147                       UseCycleCheck);
2148
2149       if (BestDAG.empty())
2150         continue;
2151
2152       // A dag has been chosen (or not) at this point. If no dag was
2153       // chosen, then this instruction, I, cannot be paired (and is no longer
2154       // considered).
2155
2156       DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2157                    << *cast<Instruction>(*I) << "\n");
2158
2159       for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2160            SE2 = BestDAG.end(); S != SE2; ++S) {
2161         // Insert the members of this dag into the list of chosen pairs.
2162         ChosenPairs.insert(ValuePair(S->first, S->second));
2163         DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2164                *S->second << "\n");
2165
2166         // Remove all candidate pairs that have values in the chosen dag.
2167         std::vector<Value *> &KK = CandidatePairs[S->first];
2168         for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2169              K != KE; ++K) {
2170           if (*K == S->second)
2171             continue;
2172
2173           CandidatePairsSet.erase(ValuePair(S->first, *K));
2174         }
2175
2176         std::vector<Value *> &LL = CandidatePairs2[S->second];
2177         for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2178              L != LE; ++L) {
2179           if (*L == S->first)
2180             continue;
2181
2182           CandidatePairsSet.erase(ValuePair(*L, S->second));
2183         }
2184
2185         std::vector<Value *> &MM = CandidatePairs[S->second];
2186         for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2187              M != ME; ++M) {
2188           assert(*M != S->first && "Flipped pair in candidate list?");
2189           CandidatePairsSet.erase(ValuePair(S->second, *M));
2190         }
2191
2192         std::vector<Value *> &NN = CandidatePairs2[S->first];
2193         for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2194              N != NE; ++N) {
2195           assert(*N != S->second && "Flipped pair in candidate list?");
2196           CandidatePairsSet.erase(ValuePair(*N, S->first));
2197         }
2198       }
2199     }
2200
2201     DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2202   }
2203
2204   std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2205                      unsigned n = 0) {
2206     if (!I->hasName())
2207       return "";
2208
2209     return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2210              (n > 0 ? "." + utostr(n) : "")).str();
2211   }
2212
2213   // Returns the value that is to be used as the pointer input to the vector
2214   // instruction that fuses I with J.
2215   Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2216                      Instruction *I, Instruction *J, unsigned o) {
2217     Value *IPtr, *JPtr;
2218     unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2219     int64_t OffsetInElmts;
2220
2221     // Note: the analysis might fail here, that is why the pair order has
2222     // been precomputed (OffsetInElmts must be unused here).
2223     (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2224                           IAddressSpace, JAddressSpace,
2225                           OffsetInElmts, false);
2226
2227     // The pointer value is taken to be the one with the lowest offset.
2228     Value *VPtr = IPtr;
2229
2230     Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
2231     Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
2232     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2233     Type *VArgPtrType = PointerType::get(VArgType,
2234       cast<PointerType>(IPtr->getType())->getAddressSpace());
2235     return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2236                         /* insert before */ I);
2237   }
2238
2239   void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2240                      unsigned MaskOffset, unsigned NumInElem,
2241                      unsigned NumInElem1, unsigned IdxOffset,
2242                      std::vector<Constant*> &Mask) {
2243     unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
2244     for (unsigned v = 0; v < NumElem1; ++v) {
2245       int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2246       if (m < 0) {
2247         Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2248       } else {
2249         unsigned mm = m + (int) IdxOffset;
2250         if (m >= (int) NumInElem1)
2251           mm += (int) NumInElem;
2252
2253         Mask[v+MaskOffset] =
2254           ConstantInt::get(Type::getInt32Ty(Context), mm);
2255       }
2256     }
2257   }
2258
2259   // Returns the value that is to be used as the vector-shuffle mask to the
2260   // vector instruction that fuses I with J.
2261   Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2262                      Instruction *I, Instruction *J) {
2263     // This is the shuffle mask. We need to append the second
2264     // mask to the first, and the numbers need to be adjusted.
2265
2266     Type *ArgTypeI = I->getType();
2267     Type *ArgTypeJ = J->getType();
2268     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2269
2270     unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
2271
2272     // Get the total number of elements in the fused vector type.
2273     // By definition, this must equal the number of elements in
2274     // the final mask.
2275     unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
2276     std::vector<Constant*> Mask(NumElem);
2277
2278     Type *OpTypeI = I->getOperand(0)->getType();
2279     unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
2280     Type *OpTypeJ = J->getOperand(0)->getType();
2281     unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
2282
2283     // The fused vector will be:
2284     // -----------------------------------------------------
2285     // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2286     // -----------------------------------------------------
2287     // from which we'll extract NumElem total elements (where the first NumElemI
2288     // of them come from the mask in I and the remainder come from the mask
2289     // in J.
2290
2291     // For the mask from the first pair...
2292     fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
2293                        0,          Mask);
2294
2295     // For the mask from the second pair...
2296     fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2297                        NumInElemI, Mask);
2298
2299     return ConstantVector::get(Mask);
2300   }
2301
2302   bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2303                                   Instruction *J, unsigned o, Value *&LOp,
2304                                   unsigned numElemL,
2305                                   Type *ArgTypeL, Type *ArgTypeH,
2306                                   bool IBeforeJ, unsigned IdxOff) {
2307     bool ExpandedIEChain = false;
2308     if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2309       // If we have a pure insertelement chain, then this can be rewritten
2310       // into a chain that directly builds the larger type.
2311       if (isPureIEChain(LIE)) {
2312         SmallVector<Value *, 8> VectElemts(numElemL,
2313           UndefValue::get(ArgTypeL->getScalarType()));
2314         InsertElementInst *LIENext = LIE;
2315         do {
2316           unsigned Idx =
2317             cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2318           VectElemts[Idx] = LIENext->getOperand(1);
2319         } while ((LIENext =
2320                    dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2321
2322         LIENext = 0;
2323         Value *LIEPrev = UndefValue::get(ArgTypeH);
2324         for (unsigned i = 0; i < numElemL; ++i) {
2325           if (isa<UndefValue>(VectElemts[i])) continue;
2326           LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2327                              ConstantInt::get(Type::getInt32Ty(Context),
2328                                               i + IdxOff),
2329                              getReplacementName(IBeforeJ ? I : J,
2330                                                 true, o, i+1));
2331           LIENext->insertBefore(IBeforeJ ? J : I);
2332           LIEPrev = LIENext;
2333         }
2334
2335         LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2336         ExpandedIEChain = true;
2337       }
2338     }
2339
2340     return ExpandedIEChain;
2341   }
2342
2343   // Returns the value to be used as the specified operand of the vector
2344   // instruction that fuses I with J.
2345   Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2346                      Instruction *J, unsigned o, bool IBeforeJ) {
2347     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2348     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2349
2350     // Compute the fused vector type for this operand
2351     Type *ArgTypeI = I->getOperand(o)->getType();
2352     Type *ArgTypeJ = J->getOperand(o)->getType();
2353     VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2354
2355     Instruction *L = I, *H = J;
2356     Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2357
2358     unsigned numElemL;
2359     if (ArgTypeL->isVectorTy())
2360       numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
2361     else
2362       numElemL = 1;
2363
2364     unsigned numElemH;
2365     if (ArgTypeH->isVectorTy())
2366       numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
2367     else
2368       numElemH = 1;
2369
2370     Value *LOp = L->getOperand(o);
2371     Value *HOp = H->getOperand(o);
2372     unsigned numElem = VArgType->getNumElements();
2373
2374     // First, we check if we can reuse the "original" vector outputs (if these
2375     // exist). We might need a shuffle.
2376     ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2377     ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2378     ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2379     ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2380
2381     // FIXME: If we're fusing shuffle instructions, then we can't apply this
2382     // optimization. The input vectors to the shuffle might be a different
2383     // length from the shuffle outputs. Unfortunately, the replacement
2384     // shuffle mask has already been formed, and the mask entries are sensitive
2385     // to the sizes of the inputs.
2386     bool IsSizeChangeShuffle =
2387       isa<ShuffleVectorInst>(L) &&
2388         (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2389
2390     if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2391       // We can have at most two unique vector inputs.
2392       bool CanUseInputs = true;
2393       Value *I1, *I2 = 0;
2394       if (LEE) {
2395         I1 = LEE->getOperand(0);
2396       } else {
2397         I1 = LSV->getOperand(0);
2398         I2 = LSV->getOperand(1);
2399         if (I2 == I1 || isa<UndefValue>(I2))
2400           I2 = 0;
2401       }
2402   
2403       if (HEE) {
2404         Value *I3 = HEE->getOperand(0);
2405         if (!I2 && I3 != I1)
2406           I2 = I3;
2407         else if (I3 != I1 && I3 != I2)
2408           CanUseInputs = false;
2409       } else {
2410         Value *I3 = HSV->getOperand(0);
2411         if (!I2 && I3 != I1)
2412           I2 = I3;
2413         else if (I3 != I1 && I3 != I2)
2414           CanUseInputs = false;
2415
2416         if (CanUseInputs) {
2417           Value *I4 = HSV->getOperand(1);
2418           if (!isa<UndefValue>(I4)) {
2419             if (!I2 && I4 != I1)
2420               I2 = I4;
2421             else if (I4 != I1 && I4 != I2)
2422               CanUseInputs = false;
2423           }
2424         }
2425       }
2426
2427       if (CanUseInputs) {
2428         unsigned LOpElem =
2429           cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2430             ->getNumElements();
2431         unsigned HOpElem =
2432           cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2433             ->getNumElements();
2434
2435         // We have one or two input vectors. We need to map each index of the
2436         // operands to the index of the original vector.
2437         SmallVector<std::pair<int, int>, 8>  II(numElem);
2438         for (unsigned i = 0; i < numElemL; ++i) {
2439           int Idx, INum;
2440           if (LEE) {
2441             Idx =
2442               cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2443             INum = LEE->getOperand(0) == I1 ? 0 : 1;
2444           } else {
2445             Idx = LSV->getMaskValue(i);
2446             if (Idx < (int) LOpElem) {
2447               INum = LSV->getOperand(0) == I1 ? 0 : 1;
2448             } else {
2449               Idx -= LOpElem;
2450               INum = LSV->getOperand(1) == I1 ? 0 : 1;
2451             }
2452           }
2453
2454           II[i] = std::pair<int, int>(Idx, INum);
2455         }
2456         for (unsigned i = 0; i < numElemH; ++i) {
2457           int Idx, INum;
2458           if (HEE) {
2459             Idx =
2460               cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2461             INum = HEE->getOperand(0) == I1 ? 0 : 1;
2462           } else {
2463             Idx = HSV->getMaskValue(i);
2464             if (Idx < (int) HOpElem) {
2465               INum = HSV->getOperand(0) == I1 ? 0 : 1;
2466             } else {
2467               Idx -= HOpElem;
2468               INum = HSV->getOperand(1) == I1 ? 0 : 1;
2469             }
2470           }
2471
2472           II[i + numElemL] = std::pair<int, int>(Idx, INum);
2473         }
2474
2475         // We now have an array which tells us from which index of which
2476         // input vector each element of the operand comes.
2477         VectorType *I1T = cast<VectorType>(I1->getType());
2478         unsigned I1Elem = I1T->getNumElements();
2479
2480         if (!I2) {
2481           // In this case there is only one underlying vector input. Check for
2482           // the trivial case where we can use the input directly.
2483           if (I1Elem == numElem) {
2484             bool ElemInOrder = true;
2485             for (unsigned i = 0; i < numElem; ++i) {
2486               if (II[i].first != (int) i && II[i].first != -1) {
2487                 ElemInOrder = false;
2488                 break;
2489               }
2490             }
2491
2492             if (ElemInOrder)
2493               return I1;
2494           }
2495
2496           // A shuffle is needed.
2497           std::vector<Constant *> Mask(numElem);
2498           for (unsigned i = 0; i < numElem; ++i) {
2499             int Idx = II[i].first;
2500             if (Idx == -1)
2501               Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2502             else
2503               Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2504           }
2505
2506           Instruction *S =
2507             new ShuffleVectorInst(I1, UndefValue::get(I1T),
2508                                   ConstantVector::get(Mask),
2509                                   getReplacementName(IBeforeJ ? I : J,
2510                                                      true, o));
2511           S->insertBefore(IBeforeJ ? J : I);
2512           return S;
2513         }
2514
2515         VectorType *I2T = cast<VectorType>(I2->getType());
2516         unsigned I2Elem = I2T->getNumElements();
2517
2518         // This input comes from two distinct vectors. The first step is to
2519         // make sure that both vectors are the same length. If not, the
2520         // smaller one will need to grow before they can be shuffled together.
2521         if (I1Elem < I2Elem) {
2522           std::vector<Constant *> Mask(I2Elem);
2523           unsigned v = 0;
2524           for (; v < I1Elem; ++v)
2525             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2526           for (; v < I2Elem; ++v)
2527             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2528
2529           Instruction *NewI1 =
2530             new ShuffleVectorInst(I1, UndefValue::get(I1T),
2531                                   ConstantVector::get(Mask),
2532                                   getReplacementName(IBeforeJ ? I : J,
2533                                                      true, o, 1));
2534           NewI1->insertBefore(IBeforeJ ? J : I);
2535           I1 = NewI1;
2536           I1T = I2T;
2537           I1Elem = I2Elem;
2538         } else if (I1Elem > I2Elem) {
2539           std::vector<Constant *> Mask(I1Elem);
2540           unsigned v = 0;
2541           for (; v < I2Elem; ++v)
2542             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2543           for (; v < I1Elem; ++v)
2544             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2545
2546           Instruction *NewI2 =
2547             new ShuffleVectorInst(I2, UndefValue::get(I2T),
2548                                   ConstantVector::get(Mask),
2549                                   getReplacementName(IBeforeJ ? I : J,
2550                                                      true, o, 1));
2551           NewI2->insertBefore(IBeforeJ ? J : I);
2552           I2 = NewI2;
2553           I2T = I1T;
2554           I2Elem = I1Elem;
2555         }
2556
2557         // Now that both I1 and I2 are the same length we can shuffle them
2558         // together (and use the result).
2559         std::vector<Constant *> Mask(numElem);
2560         for (unsigned v = 0; v < numElem; ++v) {
2561           if (II[v].first == -1) {
2562             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2563           } else {
2564             int Idx = II[v].first + II[v].second * I1Elem;
2565             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2566           }
2567         }
2568
2569         Instruction *NewOp =
2570           new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2571                                 getReplacementName(IBeforeJ ? I : J, true, o));
2572         NewOp->insertBefore(IBeforeJ ? J : I);
2573         return NewOp;
2574       }
2575     }
2576
2577     Type *ArgType = ArgTypeL;
2578     if (numElemL < numElemH) {
2579       if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2580                                          ArgTypeL, VArgType, IBeforeJ, 1)) {
2581         // This is another short-circuit case: we're combining a scalar into
2582         // a vector that is formed by an IE chain. We've just expanded the IE
2583         // chain, now insert the scalar and we're done.
2584
2585         Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2586                            getReplacementName(IBeforeJ ? I : J, true, o));
2587         S->insertBefore(IBeforeJ ? J : I);
2588         return S;
2589       } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2590                                 ArgTypeH, IBeforeJ)) {
2591         // The two vector inputs to the shuffle must be the same length,
2592         // so extend the smaller vector to be the same length as the larger one.
2593         Instruction *NLOp;
2594         if (numElemL > 1) {
2595   
2596           std::vector<Constant *> Mask(numElemH);
2597           unsigned v = 0;
2598           for (; v < numElemL; ++v)
2599             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2600           for (; v < numElemH; ++v)
2601             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2602     
2603           NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2604                                        ConstantVector::get(Mask),
2605                                        getReplacementName(IBeforeJ ? I : J,
2606                                                           true, o, 1));
2607         } else {
2608           NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2609                                            getReplacementName(IBeforeJ ? I : J,
2610                                                               true, o, 1));
2611         }
2612   
2613         NLOp->insertBefore(IBeforeJ ? J : I);
2614         LOp = NLOp;
2615       }
2616
2617       ArgType = ArgTypeH;
2618     } else if (numElemL > numElemH) {
2619       if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2620                                          ArgTypeH, VArgType, IBeforeJ)) {
2621         Instruction *S =
2622           InsertElementInst::Create(LOp, HOp, 
2623                                     ConstantInt::get(Type::getInt32Ty(Context),
2624                                                      numElemL),
2625                                     getReplacementName(IBeforeJ ? I : J,
2626                                                        true, o));
2627         S->insertBefore(IBeforeJ ? J : I);
2628         return S;
2629       } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2630                                 ArgTypeL, IBeforeJ)) {
2631         Instruction *NHOp;
2632         if (numElemH > 1) {
2633           std::vector<Constant *> Mask(numElemL);
2634           unsigned v = 0;
2635           for (; v < numElemH; ++v)
2636             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2637           for (; v < numElemL; ++v)
2638             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2639     
2640           NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2641                                        ConstantVector::get(Mask),
2642                                        getReplacementName(IBeforeJ ? I : J,
2643                                                           true, o, 1));
2644         } else {
2645           NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2646                                            getReplacementName(IBeforeJ ? I : J,
2647                                                               true, o, 1));
2648         }
2649   
2650         NHOp->insertBefore(IBeforeJ ? J : I);
2651         HOp = NHOp;
2652       }
2653     }
2654
2655     if (ArgType->isVectorTy()) {
2656       unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2657       std::vector<Constant*> Mask(numElem);
2658       for (unsigned v = 0; v < numElem; ++v) {
2659         unsigned Idx = v;
2660         // If the low vector was expanded, we need to skip the extra
2661         // undefined entries.
2662         if (v >= numElemL && numElemH > numElemL)
2663           Idx += (numElemH - numElemL);
2664         Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2665       }
2666
2667       Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2668                           ConstantVector::get(Mask),
2669                           getReplacementName(IBeforeJ ? I : J, true, o));
2670       BV->insertBefore(IBeforeJ ? J : I);
2671       return BV;
2672     }
2673
2674     Instruction *BV1 = InsertElementInst::Create(
2675                                           UndefValue::get(VArgType), LOp, CV0,
2676                                           getReplacementName(IBeforeJ ? I : J,
2677                                                              true, o, 1));
2678     BV1->insertBefore(IBeforeJ ? J : I);
2679     Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2680                                           getReplacementName(IBeforeJ ? I : J,
2681                                                              true, o, 2));
2682     BV2->insertBefore(IBeforeJ ? J : I);
2683     return BV2;
2684   }
2685
2686   // This function creates an array of values that will be used as the inputs
2687   // to the vector instruction that fuses I with J.
2688   void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2689                      Instruction *I, Instruction *J,
2690                      SmallVectorImpl<Value *> &ReplacedOperands,
2691                      bool IBeforeJ) {
2692     unsigned NumOperands = I->getNumOperands();
2693
2694     for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2695       // Iterate backward so that we look at the store pointer
2696       // first and know whether or not we need to flip the inputs.
2697
2698       if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2699         // This is the pointer for a load/store instruction.
2700         ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2701         continue;
2702       } else if (isa<CallInst>(I)) {
2703         Function *F = cast<CallInst>(I)->getCalledFunction();
2704         Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2705         if (o == NumOperands-1) {
2706           BasicBlock &BB = *I->getParent();
2707
2708           Module *M = BB.getParent()->getParent();
2709           Type *ArgTypeI = I->getType();
2710           Type *ArgTypeJ = J->getType();
2711           Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2712
2713           ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2714           continue;
2715         } else if (IID == Intrinsic::powi && o == 1) {
2716           // The second argument of powi is a single integer and we've already
2717           // checked that both arguments are equal. As a result, we just keep
2718           // I's second argument.
2719           ReplacedOperands[o] = I->getOperand(o);
2720           continue;
2721         }
2722       } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2723         ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2724         continue;
2725       }
2726
2727       ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2728     }
2729   }
2730
2731   // This function creates two values that represent the outputs of the
2732   // original I and J instructions. These are generally vector shuffles
2733   // or extracts. In many cases, these will end up being unused and, thus,
2734   // eliminated by later passes.
2735   void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2736                      Instruction *J, Instruction *K,
2737                      Instruction *&InsertionPt,
2738                      Instruction *&K1, Instruction *&K2) {
2739     if (isa<StoreInst>(I)) {
2740       AA->replaceWithNewValue(I, K);
2741       AA->replaceWithNewValue(J, K);
2742     } else {
2743       Type *IType = I->getType();
2744       Type *JType = J->getType();
2745
2746       VectorType *VType = getVecTypeForPair(IType, JType);
2747       unsigned numElem = VType->getNumElements();
2748
2749       unsigned numElemI, numElemJ;
2750       if (IType->isVectorTy())
2751         numElemI = cast<VectorType>(IType)->getNumElements();
2752       else
2753         numElemI = 1;
2754
2755       if (JType->isVectorTy())
2756         numElemJ = cast<VectorType>(JType)->getNumElements();
2757       else
2758         numElemJ = 1;
2759
2760       if (IType->isVectorTy()) {
2761         std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2762         for (unsigned v = 0; v < numElemI; ++v) {
2763           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2764           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2765         }
2766
2767         K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2768                                    ConstantVector::get( Mask1),
2769                                    getReplacementName(K, false, 1));
2770       } else {
2771         Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2772         K1 = ExtractElementInst::Create(K, CV0,
2773                                           getReplacementName(K, false, 1));
2774       }
2775
2776       if (JType->isVectorTy()) {
2777         std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2778         for (unsigned v = 0; v < numElemJ; ++v) {
2779           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2780           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2781         }
2782
2783         K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2784                                    ConstantVector::get( Mask2),
2785                                    getReplacementName(K, false, 2));
2786       } else {
2787         Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2788         K2 = ExtractElementInst::Create(K, CV1,
2789                                           getReplacementName(K, false, 2));
2790       }
2791
2792       K1->insertAfter(K);
2793       K2->insertAfter(K1);
2794       InsertionPt = K2;
2795     }
2796   }
2797
2798   // Move all uses of the function I (including pairing-induced uses) after J.
2799   bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2800                      DenseSet<ValuePair> &LoadMoveSetPairs,
2801                      Instruction *I, Instruction *J) {
2802     // Skip to the first instruction past I.
2803     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2804
2805     DenseSet<Value *> Users;
2806     AliasSetTracker WriteSet(*AA);
2807     for (; cast<Instruction>(L) != J; ++L)
2808       (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2809
2810     assert(cast<Instruction>(L) == J &&
2811       "Tracking has not proceeded far enough to check for dependencies");
2812     // If J is now in the use set of I, then trackUsesOfI will return true
2813     // and we have a dependency cycle (and the fusing operation must abort).
2814     return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2815   }
2816
2817   // Move all uses of the function I (including pairing-induced uses) after J.
2818   void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2819                      DenseSet<ValuePair> &LoadMoveSetPairs,
2820                      Instruction *&InsertionPt,
2821                      Instruction *I, Instruction *J) {
2822     // Skip to the first instruction past I.
2823     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2824
2825     DenseSet<Value *> Users;
2826     AliasSetTracker WriteSet(*AA);
2827     for (; cast<Instruction>(L) != J;) {
2828       if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2829         // Move this instruction
2830         Instruction *InstToMove = L; ++L;
2831
2832         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2833                         " to after " << *InsertionPt << "\n");
2834         InstToMove->removeFromParent();
2835         InstToMove->insertAfter(InsertionPt);
2836         InsertionPt = InstToMove;
2837       } else {
2838         ++L;
2839       }
2840     }
2841   }
2842
2843   // Collect all load instruction that are in the move set of a given first
2844   // pair member.  These loads depend on the first instruction, I, and so need
2845   // to be moved after J (the second instruction) when the pair is fused.
2846   void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2847                      DenseMap<Value *, Value *> &ChosenPairs,
2848                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2849                      DenseSet<ValuePair> &LoadMoveSetPairs,
2850                      Instruction *I) {
2851     // Skip to the first instruction past I.
2852     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2853
2854     DenseSet<Value *> Users;
2855     AliasSetTracker WriteSet(*AA);
2856
2857     // Note: We cannot end the loop when we reach J because J could be moved
2858     // farther down the use chain by another instruction pairing. Also, J
2859     // could be before I if this is an inverted input.
2860     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2861       if (trackUsesOfI(Users, WriteSet, I, L)) {
2862         if (L->mayReadFromMemory()) {
2863           LoadMoveSet[L].push_back(I);
2864           LoadMoveSetPairs.insert(ValuePair(L, I));
2865         }
2866       }
2867     }
2868   }
2869
2870   // In cases where both load/stores and the computation of their pointers
2871   // are chosen for vectorization, we can end up in a situation where the
2872   // aliasing analysis starts returning different query results as the
2873   // process of fusing instruction pairs continues. Because the algorithm
2874   // relies on finding the same use dags here as were found earlier, we'll
2875   // need to precompute the necessary aliasing information here and then
2876   // manually update it during the fusion process.
2877   void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2878                      std::vector<Value *> &PairableInsts,
2879                      DenseMap<Value *, Value *> &ChosenPairs,
2880                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2881                      DenseSet<ValuePair> &LoadMoveSetPairs) {
2882     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2883          PIE = PairableInsts.end(); PI != PIE; ++PI) {
2884       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2885       if (P == ChosenPairs.end()) continue;
2886
2887       Instruction *I = cast<Instruction>(P->first);
2888       collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2889                              LoadMoveSetPairs, I);
2890     }
2891   }
2892
2893   // When the first instruction in each pair is cloned, it will inherit its
2894   // parent's metadata. This metadata must be combined with that of the other
2895   // instruction in a safe way.
2896   void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2897     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2898     K->getAllMetadataOtherThanDebugLoc(Metadata);
2899     for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2900       unsigned Kind = Metadata[i].first;
2901       MDNode *JMD = J->getMetadata(Kind);
2902       MDNode *KMD = Metadata[i].second;
2903
2904       switch (Kind) {
2905       default:
2906         K->setMetadata(Kind, 0); // Remove unknown metadata
2907         break;
2908       case LLVMContext::MD_tbaa:
2909         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2910         break;
2911       case LLVMContext::MD_fpmath:
2912         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2913         break;
2914       }
2915     }
2916   }
2917
2918   // This function fuses the chosen instruction pairs into vector instructions,
2919   // taking care preserve any needed scalar outputs and, then, it reorders the
2920   // remaining instructions as needed (users of the first member of the pair
2921   // need to be moved to after the location of the second member of the pair
2922   // because the vector instruction is inserted in the location of the pair's
2923   // second member).
2924   void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2925              std::vector<Value *> &PairableInsts,
2926              DenseMap<Value *, Value *> &ChosenPairs,
2927              DenseSet<ValuePair> &FixedOrderPairs,
2928              DenseMap<VPPair, unsigned> &PairConnectionTypes,
2929              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2930              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
2931     LLVMContext& Context = BB.getContext();
2932
2933     // During the vectorization process, the order of the pairs to be fused
2934     // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2935     // list. After a pair is fused, the flipped pair is removed from the list.
2936     DenseSet<ValuePair> FlippedPairs;
2937     for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2938          E = ChosenPairs.end(); P != E; ++P)
2939       FlippedPairs.insert(ValuePair(P->second, P->first));
2940     for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2941          E = FlippedPairs.end(); P != E; ++P)
2942       ChosenPairs.insert(*P);
2943
2944     DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
2945     DenseSet<ValuePair> LoadMoveSetPairs;
2946     collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2947                        LoadMoveSet, LoadMoveSetPairs);
2948
2949     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2950
2951     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2952       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2953       if (P == ChosenPairs.end()) {
2954         ++PI;
2955         continue;
2956       }
2957
2958       if (getDepthFactor(P->first) == 0) {
2959         // These instructions are not really fused, but are tracked as though
2960         // they are. Any case in which it would be interesting to fuse them
2961         // will be taken care of by InstCombine.
2962         --NumFusedOps;
2963         ++PI;
2964         continue;
2965       }
2966
2967       Instruction *I = cast<Instruction>(P->first),
2968         *J = cast<Instruction>(P->second);
2969
2970       DEBUG(dbgs() << "BBV: fusing: " << *I <<
2971              " <-> " << *J << "\n");
2972
2973       // Remove the pair and flipped pair from the list.
2974       DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2975       assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2976       ChosenPairs.erase(FP);
2977       ChosenPairs.erase(P);
2978
2979       if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
2980         DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2981                " <-> " << *J <<
2982                " aborted because of non-trivial dependency cycle\n");
2983         --NumFusedOps;
2984         ++PI;
2985         continue;
2986       }
2987
2988       // If the pair must have the other order, then flip it.
2989       bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2990       if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2991         // This pair does not have a fixed order, and so we might want to
2992         // flip it if that will yield fewer shuffles. We count the number
2993         // of dependencies connected via swaps, and those directly connected,
2994         // and flip the order if the number of swaps is greater.
2995         bool OrigOrder = true;
2996         DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
2997           ConnectedPairDeps.find(ValuePair(I, J));
2998         if (IJ == ConnectedPairDeps.end()) {
2999           IJ = ConnectedPairDeps.find(ValuePair(J, I));
3000           OrigOrder = false;
3001         }
3002
3003         if (IJ != ConnectedPairDeps.end()) {
3004           unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3005           for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3006                TE = IJ->second.end(); T != TE; ++T) {
3007             VPPair Q(IJ->first, *T);
3008             DenseMap<VPPair, unsigned>::iterator R =
3009               PairConnectionTypes.find(VPPair(Q.second, Q.first));
3010             assert(R != PairConnectionTypes.end() &&
3011                    "Cannot find pair connection type");
3012             if (R->second == PairConnectionDirect)
3013               ++NumDepsDirect;
3014             else if (R->second == PairConnectionSwap)
3015               ++NumDepsSwap;
3016           }
3017
3018           if (!OrigOrder)
3019             std::swap(NumDepsDirect, NumDepsSwap);
3020
3021           if (NumDepsSwap > NumDepsDirect) {
3022             FlipPairOrder = true;
3023             DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3024                             " <-> " << *J << "\n");
3025           }
3026         }
3027       }
3028
3029       Instruction *L = I, *H = J;
3030       if (FlipPairOrder)
3031         std::swap(H, L);
3032
3033       // If the pair being fused uses the opposite order from that in the pair
3034       // connection map, then we need to flip the types.
3035       DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3036         ConnectedPairs.find(ValuePair(H, L));
3037       if (HL != ConnectedPairs.end())
3038         for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3039              TE = HL->second.end(); T != TE; ++T) {
3040           VPPair Q(HL->first, *T);
3041           DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3042           assert(R != PairConnectionTypes.end() &&
3043                  "Cannot find pair connection type");
3044           if (R->second == PairConnectionDirect)
3045             R->second = PairConnectionSwap;
3046           else if (R->second == PairConnectionSwap)
3047             R->second = PairConnectionDirect;
3048         }
3049
3050       bool LBeforeH = !FlipPairOrder;
3051       unsigned NumOperands = I->getNumOperands();
3052       SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3053       getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3054                                   LBeforeH);
3055
3056       // Make a copy of the original operation, change its type to the vector
3057       // type and replace its operands with the vector operands.
3058       Instruction *K = L->clone();
3059       if (L->hasName())
3060         K->takeName(L);
3061       else if (H->hasName())
3062         K->takeName(H);
3063
3064       if (!isa<StoreInst>(K))
3065         K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3066
3067       combineMetadata(K, H);
3068       K->intersectOptionalDataWith(H);
3069
3070       for (unsigned o = 0; o < NumOperands; ++o)
3071         K->setOperand(o, ReplacedOperands[o]);
3072
3073       K->insertAfter(J);
3074
3075       // Instruction insertion point:
3076       Instruction *InsertionPt = K;
3077       Instruction *K1 = 0, *K2 = 0;
3078       replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3079
3080       // The use dag of the first original instruction must be moved to after
3081       // the location of the second instruction. The entire use dag of the
3082       // first instruction is disjoint from the input dag of the second
3083       // (by definition), and so commutes with it.
3084
3085       moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3086
3087       if (!isa<StoreInst>(I)) {
3088         L->replaceAllUsesWith(K1);
3089         H->replaceAllUsesWith(K2);
3090         AA->replaceWithNewValue(L, K1);
3091         AA->replaceWithNewValue(H, K2);
3092       }
3093
3094       // Instructions that may read from memory may be in the load move set.
3095       // Once an instruction is fused, we no longer need its move set, and so
3096       // the values of the map never need to be updated. However, when a load
3097       // is fused, we need to merge the entries from both instructions in the
3098       // pair in case those instructions were in the move set of some other
3099       // yet-to-be-fused pair. The loads in question are the keys of the map.
3100       if (I->mayReadFromMemory()) {
3101         std::vector<ValuePair> NewSetMembers;
3102         DenseMap<Value *, std::vector<Value *> >::iterator II =
3103           LoadMoveSet.find(I);
3104         if (II != LoadMoveSet.end())
3105           for (std::vector<Value *>::iterator N = II->second.begin(),
3106                NE = II->second.end(); N != NE; ++N)
3107             NewSetMembers.push_back(ValuePair(K, *N));
3108         DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3109           LoadMoveSet.find(J);
3110         if (JJ != LoadMoveSet.end())
3111           for (std::vector<Value *>::iterator N = JJ->second.begin(),
3112                NE = JJ->second.end(); N != NE; ++N)
3113             NewSetMembers.push_back(ValuePair(K, *N));
3114         for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3115              AE = NewSetMembers.end(); A != AE; ++A) {
3116           LoadMoveSet[A->first].push_back(A->second);
3117           LoadMoveSetPairs.insert(*A);
3118         }
3119       }
3120
3121       // Before removing I, set the iterator to the next instruction.
3122       PI = llvm::next(BasicBlock::iterator(I));
3123       if (cast<Instruction>(PI) == J)
3124         ++PI;
3125
3126       SE->forgetValue(I);
3127       SE->forgetValue(J);
3128       I->eraseFromParent();
3129       J->eraseFromParent();
3130
3131       DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3132                                                BB << "\n");
3133     }
3134
3135     DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3136   }
3137 }
3138
3139 char BBVectorize::ID = 0;
3140 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3141 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3142 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3143 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3144 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3145 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3146 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3147
3148 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3149   return new BBVectorize(C);
3150 }
3151
3152 bool
3153 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3154   BBVectorize BBVectorizer(P, C);
3155   return BBVectorizer.vectorizeBB(BB);
3156 }
3157
3158 //===----------------------------------------------------------------------===//
3159 VectorizeConfig::VectorizeConfig() {
3160   VectorBits = ::VectorBits;
3161   VectorizeBools = !::NoBools;
3162   VectorizeInts = !::NoInts;
3163   VectorizeFloats = !::NoFloats;
3164   VectorizePointers = !::NoPointers;
3165   VectorizeCasts = !::NoCasts;
3166   VectorizeMath = !::NoMath;
3167   VectorizeFMA = !::NoFMA;
3168   VectorizeSelect = !::NoSelect;
3169   VectorizeCmp = !::NoCmp;
3170   VectorizeGEP = !::NoGEP;
3171   VectorizeMemOps = !::NoMemOps;
3172   AlignedOnly = ::AlignedOnly;
3173   ReqChainDepth= ::ReqChainDepth;
3174   SearchLimit = ::SearchLimit;
3175   MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3176   SplatBreaksChain = ::SplatBreaksChain;
3177   MaxInsts = ::MaxInsts;
3178   MaxPairs = ::MaxPairs;
3179   MaxIter = ::MaxIter;
3180   Pow2LenOnly = ::Pow2LenOnly;
3181   NoMemOpBoost = ::NoMemOpBoost;
3182   FastDep = ::FastDep;
3183 }