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