Allow BBVectorize to form non-2^n-length vectors.
[oota-llvm.git] / lib / Transforms / Vectorize / BBVectorize.cpp
1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a basic-block vectorization pass. The algorithm was
11 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12 // et al. It works by looking for chains of pairable operations and then
13 // pairing them.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define BBV_NAME "bb-vectorize"
18 #define DEBUG_TYPE BBV_NAME
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Metadata.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Type.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/ScalarEvolution.h"
38 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Transforms/Vectorize.h"
47 #include <algorithm>
48 #include <map>
49 using namespace llvm;
50
51 static cl::opt<unsigned>
52 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
53   cl::desc("The required chain depth for vectorization"));
54
55 static cl::opt<unsigned>
56 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
57   cl::desc("The maximum search distance for instruction pairs"));
58
59 static cl::opt<bool>
60 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
61   cl::desc("Replicating one element to a pair breaks the chain"));
62
63 static cl::opt<unsigned>
64 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
65   cl::desc("The size of the native vector registers"));
66
67 static cl::opt<unsigned>
68 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
69   cl::desc("The maximum number of pairing iterations"));
70
71 static cl::opt<bool>
72 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
73   cl::desc("Don't try to form non-2^n-length vectors"));
74
75 static cl::opt<unsigned>
76 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
77   cl::desc("The maximum number of pairable instructions per group"));
78
79 static cl::opt<unsigned>
80 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
81   cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
82                        " a full cycle check"));
83
84 static cl::opt<bool>
85 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
86   cl::desc("Don't try to vectorize boolean (i1) values"));
87
88 static cl::opt<bool>
89 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
90   cl::desc("Don't try to vectorize integer values"));
91
92 static cl::opt<bool>
93 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
94   cl::desc("Don't try to vectorize floating-point values"));
95
96 static cl::opt<bool>
97 NoPointers("bb-vectorize-no-pointers", cl::init(false), cl::Hidden,
98   cl::desc("Don't try to vectorize pointer values"));
99
100 static cl::opt<bool>
101 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
102   cl::desc("Don't try to vectorize casting (conversion) operations"));
103
104 static cl::opt<bool>
105 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
106   cl::desc("Don't try to vectorize floating-point math intrinsics"));
107
108 static cl::opt<bool>
109 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
110   cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
111
112 static cl::opt<bool>
113 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
114   cl::desc("Don't try to vectorize select instructions"));
115
116 static cl::opt<bool>
117 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
118   cl::desc("Don't try to vectorize comparison instructions"));
119
120 static cl::opt<bool>
121 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
122   cl::desc("Don't try to vectorize getelementptr instructions"));
123
124 static cl::opt<bool>
125 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
126   cl::desc("Don't try to vectorize loads and stores"));
127
128 static cl::opt<bool>
129 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
130   cl::desc("Only generate aligned loads and stores"));
131
132 static cl::opt<bool>
133 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
134   cl::init(false), cl::Hidden,
135   cl::desc("Don't boost the chain-depth contribution of loads and stores"));
136
137 static cl::opt<bool>
138 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
139   cl::desc("Use a fast instruction dependency analysis"));
140
141 #ifndef NDEBUG
142 static cl::opt<bool>
143 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
144   cl::init(false), cl::Hidden,
145   cl::desc("When debugging is enabled, output information on the"
146            " instruction-examination process"));
147 static cl::opt<bool>
148 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
149   cl::init(false), cl::Hidden,
150   cl::desc("When debugging is enabled, output information on the"
151            " candidate-selection process"));
152 static cl::opt<bool>
153 DebugPairSelection("bb-vectorize-debug-pair-selection",
154   cl::init(false), cl::Hidden,
155   cl::desc("When debugging is enabled, output information on the"
156            " pair-selection process"));
157 static cl::opt<bool>
158 DebugCycleCheck("bb-vectorize-debug-cycle-check",
159   cl::init(false), cl::Hidden,
160   cl::desc("When debugging is enabled, output information on the"
161            " cycle-checking process"));
162 #endif
163
164 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
165
166 namespace {
167   struct BBVectorize : public BasicBlockPass {
168     static char ID; // Pass identification, replacement for typeid
169
170     const VectorizeConfig Config;
171
172     BBVectorize(const VectorizeConfig &C = VectorizeConfig())
173       : BasicBlockPass(ID), Config(C) {
174       initializeBBVectorizePass(*PassRegistry::getPassRegistry());
175     }
176
177     BBVectorize(Pass *P, const VectorizeConfig &C)
178       : BasicBlockPass(ID), Config(C) {
179       AA = &P->getAnalysis<AliasAnalysis>();
180       SE = &P->getAnalysis<ScalarEvolution>();
181       TD = P->getAnalysisIfAvailable<TargetData>();
182     }
183
184     typedef std::pair<Value *, Value *> ValuePair;
185     typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
186     typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
187     typedef std::pair<std::multimap<Value *, Value *>::iterator,
188               std::multimap<Value *, Value *>::iterator> VPIteratorPair;
189     typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
190               std::multimap<ValuePair, ValuePair>::iterator>
191                 VPPIteratorPair;
192
193     AliasAnalysis *AA;
194     ScalarEvolution *SE;
195     TargetData *TD;
196
197     // FIXME: const correct?
198
199     bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
200
201     bool getCandidatePairs(BasicBlock &BB,
202                        BasicBlock::iterator &Start,
203                        std::multimap<Value *, Value *> &CandidatePairs,
204                        std::vector<Value *> &PairableInsts, bool NonPow2Len);
205
206     void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
207                        std::vector<Value *> &PairableInsts,
208                        std::multimap<ValuePair, ValuePair> &ConnectedPairs);
209
210     void buildDepMap(BasicBlock &BB,
211                        std::multimap<Value *, Value *> &CandidatePairs,
212                        std::vector<Value *> &PairableInsts,
213                        DenseSet<ValuePair> &PairableInstUsers);
214
215     void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
216                         std::vector<Value *> &PairableInsts,
217                         std::multimap<ValuePair, ValuePair> &ConnectedPairs,
218                         DenseSet<ValuePair> &PairableInstUsers,
219                         DenseMap<Value *, Value *>& ChosenPairs);
220
221     void fuseChosenPairs(BasicBlock &BB,
222                      std::vector<Value *> &PairableInsts,
223                      DenseMap<Value *, Value *>& ChosenPairs);
224
225     bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
226
227     bool areInstsCompatible(Instruction *I, Instruction *J,
228                        bool IsSimpleLoadStore, bool NonPow2Len);
229
230     bool trackUsesOfI(DenseSet<Value *> &Users,
231                       AliasSetTracker &WriteSet, Instruction *I,
232                       Instruction *J, bool UpdateUsers = true,
233                       std::multimap<Value *, Value *> *LoadMoveSet = 0);
234
235     void computePairsConnectedTo(
236                       std::multimap<Value *, Value *> &CandidatePairs,
237                       std::vector<Value *> &PairableInsts,
238                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
239                       ValuePair P);
240
241     bool pairsConflict(ValuePair P, ValuePair Q,
242                  DenseSet<ValuePair> &PairableInstUsers,
243                  std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
244
245     bool pairWillFormCycle(ValuePair P,
246                        std::multimap<ValuePair, ValuePair> &PairableInstUsers,
247                        DenseSet<ValuePair> &CurrentPairs);
248
249     void pruneTreeFor(
250                       std::multimap<Value *, Value *> &CandidatePairs,
251                       std::vector<Value *> &PairableInsts,
252                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
253                       DenseSet<ValuePair> &PairableInstUsers,
254                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
255                       DenseMap<Value *, Value *> &ChosenPairs,
256                       DenseMap<ValuePair, size_t> &Tree,
257                       DenseSet<ValuePair> &PrunedTree, ValuePair J,
258                       bool UseCycleCheck);
259
260     void buildInitialTreeFor(
261                       std::multimap<Value *, Value *> &CandidatePairs,
262                       std::vector<Value *> &PairableInsts,
263                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
264                       DenseSet<ValuePair> &PairableInstUsers,
265                       DenseMap<Value *, Value *> &ChosenPairs,
266                       DenseMap<ValuePair, size_t> &Tree, ValuePair J);
267
268     void findBestTreeFor(
269                       std::multimap<Value *, Value *> &CandidatePairs,
270                       std::vector<Value *> &PairableInsts,
271                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
272                       DenseSet<ValuePair> &PairableInstUsers,
273                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
274                       DenseMap<Value *, Value *> &ChosenPairs,
275                       DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
276                       size_t &BestEffSize, VPIteratorPair ChoiceRange,
277                       bool UseCycleCheck);
278
279     Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
280                      Instruction *J, unsigned o, bool &FlipMemInputs);
281
282     void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
283                      unsigned MaskOffset, unsigned NumInElem,
284                      unsigned NumInElem1, unsigned IdxOffset,
285                      std::vector<Constant*> &Mask);
286
287     Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
288                      Instruction *J);
289
290     bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
291                        unsigned o, Value *&LOp, unsigned numElemL,
292                        Type *ArgTypeL, Type *ArgTypeR,
293                        unsigned IdxOff = 0);
294
295     Value *getReplacementInput(LLVMContext& Context, Instruction *I,
296                      Instruction *J, unsigned o, bool FlipMemInputs);
297
298     void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
299                      Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
300                      bool &FlipMemInputs);
301
302     void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
303                      Instruction *J, Instruction *K,
304                      Instruction *&InsertionPt, Instruction *&K1,
305                      Instruction *&K2, bool &FlipMemInputs);
306
307     void collectPairLoadMoveSet(BasicBlock &BB,
308                      DenseMap<Value *, Value *> &ChosenPairs,
309                      std::multimap<Value *, Value *> &LoadMoveSet,
310                      Instruction *I);
311
312     void collectLoadMoveSet(BasicBlock &BB,
313                      std::vector<Value *> &PairableInsts,
314                      DenseMap<Value *, Value *> &ChosenPairs,
315                      std::multimap<Value *, Value *> &LoadMoveSet);
316
317     bool canMoveUsesOfIAfterJ(BasicBlock &BB,
318                      std::multimap<Value *, Value *> &LoadMoveSet,
319                      Instruction *I, Instruction *J);
320
321     void moveUsesOfIAfterJ(BasicBlock &BB,
322                      std::multimap<Value *, Value *> &LoadMoveSet,
323                      Instruction *&InsertionPt,
324                      Instruction *I, Instruction *J);
325
326     void combineMetadata(Instruction *K, const Instruction *J);
327
328     bool vectorizeBB(BasicBlock &BB) {
329       bool changed = false;
330       // Iterate a sufficient number of times to merge types of size 1 bit,
331       // then 2 bits, then 4, etc. up to half of the target vector width of the
332       // target vector register.
333       unsigned n = 1;
334       for (unsigned v = 2;
335            v <= Config.VectorBits && (!Config.MaxIter || n <= Config.MaxIter);
336            v *= 2, ++n) {
337         DEBUG(dbgs() << "BBV: fusing loop #" << n <<
338               " for " << BB.getName() << " in " <<
339               BB.getParent()->getName() << "...\n");
340         if (vectorizePairs(BB))
341           changed = true;
342         else
343           break;
344       }
345
346       if (changed && !Pow2LenOnly) {
347         ++n;
348         for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
349           DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
350                 n << " for " << BB.getName() << " in " <<
351                 BB.getParent()->getName() << "...\n");
352           if (!vectorizePairs(BB, true)) break;
353         }
354       }
355
356       DEBUG(dbgs() << "BBV: done!\n");
357       return changed;
358     }
359
360     virtual bool runOnBasicBlock(BasicBlock &BB) {
361       AA = &getAnalysis<AliasAnalysis>();
362       SE = &getAnalysis<ScalarEvolution>();
363       TD = getAnalysisIfAvailable<TargetData>();
364
365       return vectorizeBB(BB);
366     }
367
368     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
369       BasicBlockPass::getAnalysisUsage(AU);
370       AU.addRequired<AliasAnalysis>();
371       AU.addRequired<ScalarEvolution>();
372       AU.addPreserved<AliasAnalysis>();
373       AU.addPreserved<ScalarEvolution>();
374       AU.setPreservesCFG();
375     }
376
377     static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
378       assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
379              "Cannot form vector from incompatible scalar types");
380       Type *STy = ElemTy->getScalarType();
381
382       unsigned numElem;
383       if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
384         numElem = VTy->getNumElements();
385       } else {
386         numElem = 1;
387       }
388
389       if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
390         numElem += VTy->getNumElements();
391       } else {
392         numElem += 1;
393       }
394
395       return VectorType::get(STy, numElem);
396     }
397
398     static inline void getInstructionTypes(Instruction *I,
399                                            Type *&T1, Type *&T2) {
400       if (isa<StoreInst>(I)) {
401         // For stores, it is the value type, not the pointer type that matters
402         // because the value is what will come from a vector register.
403   
404         Value *IVal = cast<StoreInst>(I)->getValueOperand();
405         T1 = IVal->getType();
406       } else {
407         T1 = I->getType();
408       }
409   
410       if (I->isCast())
411         T2 = cast<CastInst>(I)->getSrcTy();
412       else
413         T2 = T1;
414     }
415
416     // Returns the weight associated with the provided value. A chain of
417     // candidate pairs has a length given by the sum of the weights of its
418     // members (one weight per pair; the weight of each member of the pair
419     // is assumed to be the same). This length is then compared to the
420     // chain-length threshold to determine if a given chain is significant
421     // enough to be vectorized. The length is also used in comparing
422     // candidate chains where longer chains are considered to be better.
423     // Note: when this function returns 0, the resulting instructions are
424     // not actually fused.
425     inline size_t getDepthFactor(Value *V) {
426       // InsertElement and ExtractElement have a depth factor of zero. This is
427       // for two reasons: First, they cannot be usefully fused. Second, because
428       // the pass generates a lot of these, they can confuse the simple metric
429       // used to compare the trees in the next iteration. Thus, giving them a
430       // weight of zero allows the pass to essentially ignore them in
431       // subsequent iterations when looking for vectorization opportunities
432       // while still tracking dependency chains that flow through those
433       // instructions.
434       if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
435         return 0;
436
437       // Give a load or store half of the required depth so that load/store
438       // pairs will vectorize.
439       if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
440         return Config.ReqChainDepth/2;
441
442       return 1;
443     }
444
445     // This determines the relative offset of two loads or stores, returning
446     // true if the offset could be determined to be some constant value.
447     // For example, if OffsetInElmts == 1, then J accesses the memory directly
448     // after I; if OffsetInElmts == -1 then I accesses the memory
449     // directly after J.
450     bool getPairPtrInfo(Instruction *I, Instruction *J,
451         Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
452         int64_t &OffsetInElmts) {
453       OffsetInElmts = 0;
454       if (isa<LoadInst>(I)) {
455         IPtr = cast<LoadInst>(I)->getPointerOperand();
456         JPtr = cast<LoadInst>(J)->getPointerOperand();
457         IAlignment = cast<LoadInst>(I)->getAlignment();
458         JAlignment = cast<LoadInst>(J)->getAlignment();
459       } else {
460         IPtr = cast<StoreInst>(I)->getPointerOperand();
461         JPtr = cast<StoreInst>(J)->getPointerOperand();
462         IAlignment = cast<StoreInst>(I)->getAlignment();
463         JAlignment = cast<StoreInst>(J)->getAlignment();
464       }
465
466       const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
467       const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
468
469       // If this is a trivial offset, then we'll get something like
470       // 1*sizeof(type). With target data, which we need anyway, this will get
471       // constant folded into a number.
472       const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
473       if (const SCEVConstant *ConstOffSCEV =
474             dyn_cast<SCEVConstant>(OffsetSCEV)) {
475         ConstantInt *IntOff = ConstOffSCEV->getValue();
476         int64_t Offset = IntOff->getSExtValue();
477
478         Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
479         int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
480
481         Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
482         if (VTy != VTy2 && Offset < 0) {
483           int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
484           OffsetInElmts = Offset/VTy2TSS;
485           return (abs64(Offset) % VTy2TSS) == 0;
486         }
487
488         OffsetInElmts = Offset/VTyTSS;
489         return (abs64(Offset) % VTyTSS) == 0;
490       }
491
492       return false;
493     }
494
495     // Returns true if the provided CallInst represents an intrinsic that can
496     // be vectorized.
497     bool isVectorizableIntrinsic(CallInst* I) {
498       Function *F = I->getCalledFunction();
499       if (!F) return false;
500
501       unsigned IID = F->getIntrinsicID();
502       if (!IID) return false;
503
504       switch(IID) {
505       default:
506         return false;
507       case Intrinsic::sqrt:
508       case Intrinsic::powi:
509       case Intrinsic::sin:
510       case Intrinsic::cos:
511       case Intrinsic::log:
512       case Intrinsic::log2:
513       case Intrinsic::log10:
514       case Intrinsic::exp:
515       case Intrinsic::exp2:
516       case Intrinsic::pow:
517         return Config.VectorizeMath;
518       case Intrinsic::fma:
519         return Config.VectorizeFMA;
520       }
521     }
522
523     // Returns true if J is the second element in some pair referenced by
524     // some multimap pair iterator pair.
525     template <typename V>
526     bool isSecondInIteratorPair(V J, std::pair<
527            typename std::multimap<V, V>::iterator,
528            typename std::multimap<V, V>::iterator> PairRange) {
529       for (typename std::multimap<V, V>::iterator K = PairRange.first;
530            K != PairRange.second; ++K)
531         if (K->second == J) return true;
532
533       return false;
534     }
535   };
536
537   // This function implements one vectorization iteration on the provided
538   // basic block. It returns true if the block is changed.
539   bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
540     bool ShouldContinue;
541     BasicBlock::iterator Start = BB.getFirstInsertionPt();
542
543     std::vector<Value *> AllPairableInsts;
544     DenseMap<Value *, Value *> AllChosenPairs;
545
546     do {
547       std::vector<Value *> PairableInsts;
548       std::multimap<Value *, Value *> CandidatePairs;
549       ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
550                                          PairableInsts, NonPow2Len);
551       if (PairableInsts.empty()) continue;
552
553       // Now we have a map of all of the pairable instructions and we need to
554       // select the best possible pairing. A good pairing is one such that the
555       // users of the pair are also paired. This defines a (directed) forest
556       // over the pairs such that two pairs are connected iff the second pair
557       // uses the first.
558
559       // Note that it only matters that both members of the second pair use some
560       // element of the first pair (to allow for splatting).
561
562       std::multimap<ValuePair, ValuePair> ConnectedPairs;
563       computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
564       if (ConnectedPairs.empty()) continue;
565
566       // Build the pairable-instruction dependency map
567       DenseSet<ValuePair> PairableInstUsers;
568       buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
569
570       // There is now a graph of the connected pairs. For each variable, pick
571       // the pairing with the largest tree meeting the depth requirement on at
572       // least one branch. Then select all pairings that are part of that tree
573       // and remove them from the list of available pairings and pairable
574       // variables.
575
576       DenseMap<Value *, Value *> ChosenPairs;
577       choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
578         PairableInstUsers, ChosenPairs);
579
580       if (ChosenPairs.empty()) continue;
581       AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
582                               PairableInsts.end());
583       AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
584     } while (ShouldContinue);
585
586     if (AllChosenPairs.empty()) return false;
587     NumFusedOps += AllChosenPairs.size();
588
589     // A set of pairs has now been selected. It is now necessary to replace the
590     // paired instructions with vector instructions. For this procedure each
591     // operand must be replaced with a vector operand. This vector is formed
592     // by using build_vector on the old operands. The replaced values are then
593     // replaced with a vector_extract on the result.  Subsequent optimization
594     // passes should coalesce the build/extract combinations.
595
596     fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
597
598     // It is important to cleanup here so that future iterations of this
599     // function have less work to do.
600     (void) SimplifyInstructionsInBlock(&BB, TD);
601     return true;
602   }
603
604   // This function returns true if the provided instruction is capable of being
605   // fused into a vector instruction. This determination is based only on the
606   // type and other attributes of the instruction.
607   bool BBVectorize::isInstVectorizable(Instruction *I,
608                                          bool &IsSimpleLoadStore) {
609     IsSimpleLoadStore = false;
610
611     if (CallInst *C = dyn_cast<CallInst>(I)) {
612       if (!isVectorizableIntrinsic(C))
613         return false;
614     } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
615       // Vectorize simple loads if possbile:
616       IsSimpleLoadStore = L->isSimple();
617       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
618         return false;
619     } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
620       // Vectorize simple stores if possbile:
621       IsSimpleLoadStore = S->isSimple();
622       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
623         return false;
624     } else if (CastInst *C = dyn_cast<CastInst>(I)) {
625       // We can vectorize casts, but not casts of pointer types, etc.
626       if (!Config.VectorizeCasts)
627         return false;
628
629       Type *SrcTy = C->getSrcTy();
630       if (!SrcTy->isSingleValueType())
631         return false;
632
633       Type *DestTy = C->getDestTy();
634       if (!DestTy->isSingleValueType())
635         return false;
636     } else if (isa<SelectInst>(I)) {
637       if (!Config.VectorizeSelect)
638         return false;
639     } else if (isa<CmpInst>(I)) {
640       if (!Config.VectorizeCmp)
641         return false;
642     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
643       if (!Config.VectorizeGEP)
644         return false;
645
646       // Currently, vector GEPs exist only with one index.
647       if (G->getNumIndices() != 1)
648         return false;
649     } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
650         isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
651       return false;
652     }
653
654     // We can't vectorize memory operations without target data
655     if (TD == 0 && IsSimpleLoadStore)
656       return false;
657
658     Type *T1, *T2;
659     getInstructionTypes(I, T1, T2);
660
661     // Not every type can be vectorized...
662     if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
663         !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
664       return false;
665
666     if (T1->getScalarSizeInBits() == 1 && T2->getScalarSizeInBits() == 1) {
667       if (!Config.VectorizeBools)
668         return false;
669     } else {
670       if (!Config.VectorizeInts
671           && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
672         return false;
673     }
674   
675     if (!Config.VectorizeFloats
676         && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
677       return false;
678
679     // Don't vectorize target-specific types.
680     if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
681       return false;
682     if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
683       return false;
684
685     if ((!Config.VectorizePointers || TD == 0) &&
686         (T1->getScalarType()->isPointerTy() ||
687          T2->getScalarType()->isPointerTy()))
688       return false;
689
690     if (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
691         T2->getPrimitiveSizeInBits() >= Config.VectorBits)
692       return false;
693
694     return true;
695   }
696
697   // This function returns true if the two provided instructions are compatible
698   // (meaning that they can be fused into a vector instruction). This assumes
699   // that I has already been determined to be vectorizable and that J is not
700   // in the use tree of I.
701   bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
702                        bool IsSimpleLoadStore, bool NonPow2Len) {
703     DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
704                      " <-> " << *J << "\n");
705
706     // Loads and stores can be merged if they have different alignments,
707     // but are otherwise the same.
708     if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
709                       (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
710       return false;
711
712     Type *IT1, *IT2, *JT1, *JT2;
713     getInstructionTypes(I, IT1, IT2);
714     getInstructionTypes(J, JT1, JT2);
715     unsigned MaxTypeBits = std::max(
716       IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
717       IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
718     if (MaxTypeBits > Config.VectorBits)
719       return false;
720
721     // FIXME: handle addsub-type operations!
722
723     if (IsSimpleLoadStore) {
724       Value *IPtr, *JPtr;
725       unsigned IAlignment, JAlignment;
726       int64_t OffsetInElmts = 0;
727       if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
728             OffsetInElmts) && abs64(OffsetInElmts) == 1) {
729         if (Config.AlignedOnly) {
730           Type *aTypeI = isa<StoreInst>(I) ?
731             cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
732           Type *aTypeJ = isa<StoreInst>(J) ?
733             cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
734
735           // An aligned load or store is possible only if the instruction
736           // with the lower offset has an alignment suitable for the
737           // vector type.
738
739           unsigned BottomAlignment = IAlignment;
740           if (OffsetInElmts < 0) BottomAlignment = JAlignment;
741
742           Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
743           unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
744           if (BottomAlignment < VecAlignment)
745             return false;
746         }
747       } else {
748         return false;
749       }
750     } else if (isa<ShuffleVectorInst>(I)) {
751       // Only merge two shuffles if they're both constant
752       return isa<Constant>(I->getOperand(2)) &&
753              isa<Constant>(J->getOperand(2));
754       // FIXME: We may want to vectorize non-constant shuffles also.
755     }
756
757     // The powi intrinsic is special because only the first argument is
758     // vectorized, the second arguments must be equal.
759     CallInst *CI = dyn_cast<CallInst>(I);
760     Function *FI;
761     if (CI && (FI = CI->getCalledFunction()) &&
762         FI->getIntrinsicID() == Intrinsic::powi) {
763
764       Value *A1I = CI->getArgOperand(1),
765             *A1J = cast<CallInst>(J)->getArgOperand(1);
766       const SCEV *A1ISCEV = SE->getSCEV(A1I),
767                  *A1JSCEV = SE->getSCEV(A1J);
768       return (A1ISCEV == A1JSCEV);
769     }
770
771     return true;
772   }
773
774   // Figure out whether or not J uses I and update the users and write-set
775   // structures associated with I. Specifically, Users represents the set of
776   // instructions that depend on I. WriteSet represents the set
777   // of memory locations that are dependent on I. If UpdateUsers is true,
778   // and J uses I, then Users is updated to contain J and WriteSet is updated
779   // to contain any memory locations to which J writes. The function returns
780   // true if J uses I. By default, alias analysis is used to determine
781   // whether J reads from memory that overlaps with a location in WriteSet.
782   // If LoadMoveSet is not null, then it is a previously-computed multimap
783   // where the key is the memory-based user instruction and the value is
784   // the instruction to be compared with I. So, if LoadMoveSet is provided,
785   // then the alias analysis is not used. This is necessary because this
786   // function is called during the process of moving instructions during
787   // vectorization and the results of the alias analysis are not stable during
788   // that process.
789   bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
790                        AliasSetTracker &WriteSet, Instruction *I,
791                        Instruction *J, bool UpdateUsers,
792                        std::multimap<Value *, Value *> *LoadMoveSet) {
793     bool UsesI = false;
794
795     // This instruction may already be marked as a user due, for example, to
796     // being a member of a selected pair.
797     if (Users.count(J))
798       UsesI = true;
799
800     if (!UsesI)
801       for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
802            JU != JE; ++JU) {
803         Value *V = *JU;
804         if (I == V || Users.count(V)) {
805           UsesI = true;
806           break;
807         }
808       }
809     if (!UsesI && J->mayReadFromMemory()) {
810       if (LoadMoveSet) {
811         VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
812         UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
813       } else {
814         for (AliasSetTracker::iterator W = WriteSet.begin(),
815              WE = WriteSet.end(); W != WE; ++W) {
816           if (W->aliasesUnknownInst(J, *AA)) {
817             UsesI = true;
818             break;
819           }
820         }
821       }
822     }
823
824     if (UsesI && UpdateUsers) {
825       if (J->mayWriteToMemory()) WriteSet.add(J);
826       Users.insert(J);
827     }
828
829     return UsesI;
830   }
831
832   // This function iterates over all instruction pairs in the provided
833   // basic block and collects all candidate pairs for vectorization.
834   bool BBVectorize::getCandidatePairs(BasicBlock &BB,
835                        BasicBlock::iterator &Start,
836                        std::multimap<Value *, Value *> &CandidatePairs,
837                        std::vector<Value *> &PairableInsts, bool NonPow2Len) {
838     BasicBlock::iterator E = BB.end();
839     if (Start == E) return false;
840
841     bool ShouldContinue = false, IAfterStart = false;
842     for (BasicBlock::iterator I = Start++; I != E; ++I) {
843       if (I == Start) IAfterStart = true;
844
845       bool IsSimpleLoadStore;
846       if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
847
848       // Look for an instruction with which to pair instruction *I...
849       DenseSet<Value *> Users;
850       AliasSetTracker WriteSet(*AA);
851       bool JAfterStart = IAfterStart;
852       BasicBlock::iterator J = llvm::next(I);
853       for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
854         if (J == Start) JAfterStart = true;
855
856         // Determine if J uses I, if so, exit the loop.
857         bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
858         if (Config.FastDep) {
859           // Note: For this heuristic to be effective, independent operations
860           // must tend to be intermixed. This is likely to be true from some
861           // kinds of grouped loop unrolling (but not the generic LLVM pass),
862           // but otherwise may require some kind of reordering pass.
863
864           // When using fast dependency analysis,
865           // stop searching after first use:
866           if (UsesI) break;
867         } else {
868           if (UsesI) continue;
869         }
870
871         // J does not use I, and comes before the first use of I, so it can be
872         // merged with I if the instructions are compatible.
873         if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len)) continue;
874
875         // J is a candidate for merging with I.
876         if (!PairableInsts.size() ||
877              PairableInsts[PairableInsts.size()-1] != I) {
878           PairableInsts.push_back(I);
879         }
880
881         CandidatePairs.insert(ValuePair(I, J));
882
883         // The next call to this function must start after the last instruction
884         // selected during this invocation.
885         if (JAfterStart) {
886           Start = llvm::next(J);
887           IAfterStart = JAfterStart = false;
888         }
889
890         DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
891                      << *I << " <-> " << *J << "\n");
892
893         // If we have already found too many pairs, break here and this function
894         // will be called again starting after the last instruction selected
895         // during this invocation.
896         if (PairableInsts.size() >= Config.MaxInsts) {
897           ShouldContinue = true;
898           break;
899         }
900       }
901
902       if (ShouldContinue)
903         break;
904     }
905
906     DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
907            << " instructions with candidate pairs\n");
908
909     return ShouldContinue;
910   }
911
912   // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
913   // it looks for pairs such that both members have an input which is an
914   // output of PI or PJ.
915   void BBVectorize::computePairsConnectedTo(
916                       std::multimap<Value *, Value *> &CandidatePairs,
917                       std::vector<Value *> &PairableInsts,
918                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
919                       ValuePair P) {
920     StoreInst *SI, *SJ;
921
922     // For each possible pairing for this variable, look at the uses of
923     // the first value...
924     for (Value::use_iterator I = P.first->use_begin(),
925          E = P.first->use_end(); I != E; ++I) {
926       if (isa<LoadInst>(*I)) {
927         // A pair cannot be connected to a load because the load only takes one
928         // operand (the address) and it is a scalar even after vectorization.
929         continue;
930       } else if ((SI = dyn_cast<StoreInst>(*I)) &&
931                  P.first == SI->getPointerOperand()) {
932         // Similarly, a pair cannot be connected to a store through its
933         // pointer operand.
934         continue;
935       }
936
937       VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
938
939       // For each use of the first variable, look for uses of the second
940       // variable...
941       for (Value::use_iterator J = P.second->use_begin(),
942            E2 = P.second->use_end(); J != E2; ++J) {
943         if ((SJ = dyn_cast<StoreInst>(*J)) &&
944             P.second == SJ->getPointerOperand())
945           continue;
946
947         VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
948
949         // Look for <I, J>:
950         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
951           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
952
953         // Look for <J, I>:
954         if (isSecondInIteratorPair<Value*>(*I, JPairRange))
955           ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
956       }
957
958       if (Config.SplatBreaksChain) continue;
959       // Look for cases where just the first value in the pair is used by
960       // both members of another pair (splatting).
961       for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
962         if ((SJ = dyn_cast<StoreInst>(*J)) &&
963             P.first == SJ->getPointerOperand())
964           continue;
965
966         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
967           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
968       }
969     }
970
971     if (Config.SplatBreaksChain) return;
972     // Look for cases where just the second value in the pair is used by
973     // both members of another pair (splatting).
974     for (Value::use_iterator I = P.second->use_begin(),
975          E = P.second->use_end(); I != E; ++I) {
976       if (isa<LoadInst>(*I))
977         continue;
978       else if ((SI = dyn_cast<StoreInst>(*I)) &&
979                P.second == SI->getPointerOperand())
980         continue;
981
982       VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
983
984       for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
985         if ((SJ = dyn_cast<StoreInst>(*J)) &&
986             P.second == SJ->getPointerOperand())
987           continue;
988
989         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
990           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
991       }
992     }
993   }
994
995   // This function figures out which pairs are connected.  Two pairs are
996   // connected if some output of the first pair forms an input to both members
997   // of the second pair.
998   void BBVectorize::computeConnectedPairs(
999                       std::multimap<Value *, Value *> &CandidatePairs,
1000                       std::vector<Value *> &PairableInsts,
1001                       std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
1002
1003     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1004          PE = PairableInsts.end(); PI != PE; ++PI) {
1005       VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1006
1007       for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1008            P != choiceRange.second; ++P)
1009         computePairsConnectedTo(CandidatePairs, PairableInsts,
1010                                 ConnectedPairs, *P);
1011     }
1012
1013     DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1014                  << " pair connections.\n");
1015   }
1016
1017   // This function builds a set of use tuples such that <A, B> is in the set
1018   // if B is in the use tree of A. If B is in the use tree of A, then B
1019   // depends on the output of A.
1020   void BBVectorize::buildDepMap(
1021                       BasicBlock &BB,
1022                       std::multimap<Value *, Value *> &CandidatePairs,
1023                       std::vector<Value *> &PairableInsts,
1024                       DenseSet<ValuePair> &PairableInstUsers) {
1025     DenseSet<Value *> IsInPair;
1026     for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1027          E = CandidatePairs.end(); C != E; ++C) {
1028       IsInPair.insert(C->first);
1029       IsInPair.insert(C->second);
1030     }
1031
1032     // Iterate through the basic block, recording all Users of each
1033     // pairable instruction.
1034
1035     BasicBlock::iterator E = BB.end();
1036     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1037       if (IsInPair.find(I) == IsInPair.end()) continue;
1038
1039       DenseSet<Value *> Users;
1040       AliasSetTracker WriteSet(*AA);
1041       for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1042         (void) trackUsesOfI(Users, WriteSet, I, J);
1043
1044       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1045            U != E; ++U)
1046         PairableInstUsers.insert(ValuePair(I, *U));
1047     }
1048   }
1049
1050   // Returns true if an input to pair P is an output of pair Q and also an
1051   // input of pair Q is an output of pair P. If this is the case, then these
1052   // two pairs cannot be simultaneously fused.
1053   bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1054                      DenseSet<ValuePair> &PairableInstUsers,
1055                      std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1056     // Two pairs are in conflict if they are mutual Users of eachother.
1057     bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
1058                   PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
1059                   PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
1060                   PairableInstUsers.count(ValuePair(P.second, Q.second));
1061     bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
1062                   PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
1063                   PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
1064                   PairableInstUsers.count(ValuePair(Q.second, P.second));
1065     if (PairableInstUserMap) {
1066       // FIXME: The expensive part of the cycle check is not so much the cycle
1067       // check itself but this edge insertion procedure. This needs some
1068       // profiling and probably a different data structure (same is true of
1069       // most uses of std::multimap).
1070       if (PUsesQ) {
1071         VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1072         if (!isSecondInIteratorPair(P, QPairRange))
1073           PairableInstUserMap->insert(VPPair(Q, P));
1074       }
1075       if (QUsesP) {
1076         VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1077         if (!isSecondInIteratorPair(Q, PPairRange))
1078           PairableInstUserMap->insert(VPPair(P, Q));
1079       }
1080     }
1081
1082     return (QUsesP && PUsesQ);
1083   }
1084
1085   // This function walks the use graph of current pairs to see if, starting
1086   // from P, the walk returns to P.
1087   bool BBVectorize::pairWillFormCycle(ValuePair P,
1088                        std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1089                        DenseSet<ValuePair> &CurrentPairs) {
1090     DEBUG(if (DebugCycleCheck)
1091             dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1092                    << *P.second << "\n");
1093     // A lookup table of visisted pairs is kept because the PairableInstUserMap
1094     // contains non-direct associations.
1095     DenseSet<ValuePair> Visited;
1096     SmallVector<ValuePair, 32> Q;
1097     // General depth-first post-order traversal:
1098     Q.push_back(P);
1099     do {
1100       ValuePair QTop = Q.pop_back_val();
1101       Visited.insert(QTop);
1102
1103       DEBUG(if (DebugCycleCheck)
1104               dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1105                      << *QTop.second << "\n");
1106       VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1107       for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1108            C != QPairRange.second; ++C) {
1109         if (C->second == P) {
1110           DEBUG(dbgs()
1111                  << "BBV: rejected to prevent non-trivial cycle formation: "
1112                  << *C->first.first << " <-> " << *C->first.second << "\n");
1113           return true;
1114         }
1115
1116         if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1117           Q.push_back(C->second);
1118       }
1119     } while (!Q.empty());
1120
1121     return false;
1122   }
1123
1124   // This function builds the initial tree of connected pairs with the
1125   // pair J at the root.
1126   void BBVectorize::buildInitialTreeFor(
1127                       std::multimap<Value *, Value *> &CandidatePairs,
1128                       std::vector<Value *> &PairableInsts,
1129                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1130                       DenseSet<ValuePair> &PairableInstUsers,
1131                       DenseMap<Value *, Value *> &ChosenPairs,
1132                       DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1133     // Each of these pairs is viewed as the root node of a Tree. The Tree
1134     // is then walked (depth-first). As this happens, we keep track of
1135     // the pairs that compose the Tree and the maximum depth of the Tree.
1136     SmallVector<ValuePairWithDepth, 32> Q;
1137     // General depth-first post-order traversal:
1138     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1139     do {
1140       ValuePairWithDepth QTop = Q.back();
1141
1142       // Push each child onto the queue:
1143       bool MoreChildren = false;
1144       size_t MaxChildDepth = QTop.second;
1145       VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1146       for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1147            k != qtRange.second; ++k) {
1148         // Make sure that this child pair is still a candidate:
1149         bool IsStillCand = false;
1150         VPIteratorPair checkRange =
1151           CandidatePairs.equal_range(k->second.first);
1152         for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1153              m != checkRange.second; ++m) {
1154           if (m->second == k->second.second) {
1155             IsStillCand = true;
1156             break;
1157           }
1158         }
1159
1160         if (IsStillCand) {
1161           DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1162           if (C == Tree.end()) {
1163             size_t d = getDepthFactor(k->second.first);
1164             Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1165             MoreChildren = true;
1166           } else {
1167             MaxChildDepth = std::max(MaxChildDepth, C->second);
1168           }
1169         }
1170       }
1171
1172       if (!MoreChildren) {
1173         // Record the current pair as part of the Tree:
1174         Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1175         Q.pop_back();
1176       }
1177     } while (!Q.empty());
1178   }
1179
1180   // Given some initial tree, prune it by removing conflicting pairs (pairs
1181   // that cannot be simultaneously chosen for vectorization).
1182   void BBVectorize::pruneTreeFor(
1183                       std::multimap<Value *, Value *> &CandidatePairs,
1184                       std::vector<Value *> &PairableInsts,
1185                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1186                       DenseSet<ValuePair> &PairableInstUsers,
1187                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1188                       DenseMap<Value *, Value *> &ChosenPairs,
1189                       DenseMap<ValuePair, size_t> &Tree,
1190                       DenseSet<ValuePair> &PrunedTree, ValuePair J,
1191                       bool UseCycleCheck) {
1192     SmallVector<ValuePairWithDepth, 32> Q;
1193     // General depth-first post-order traversal:
1194     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1195     do {
1196       ValuePairWithDepth QTop = Q.pop_back_val();
1197       PrunedTree.insert(QTop.first);
1198
1199       // Visit each child, pruning as necessary...
1200       DenseMap<ValuePair, size_t> BestChildren;
1201       VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1202       for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1203            K != QTopRange.second; ++K) {
1204         DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1205         if (C == Tree.end()) continue;
1206
1207         // This child is in the Tree, now we need to make sure it is the
1208         // best of any conflicting children. There could be multiple
1209         // conflicting children, so first, determine if we're keeping
1210         // this child, then delete conflicting children as necessary.
1211
1212         // It is also necessary to guard against pairing-induced
1213         // dependencies. Consider instructions a .. x .. y .. b
1214         // such that (a,b) are to be fused and (x,y) are to be fused
1215         // but a is an input to x and b is an output from y. This
1216         // means that y cannot be moved after b but x must be moved
1217         // after b for (a,b) to be fused. In other words, after
1218         // fusing (a,b) we have y .. a/b .. x where y is an input
1219         // to a/b and x is an output to a/b: x and y can no longer
1220         // be legally fused. To prevent this condition, we must
1221         // make sure that a child pair added to the Tree is not
1222         // both an input and output of an already-selected pair.
1223
1224         // Pairing-induced dependencies can also form from more complicated
1225         // cycles. The pair vs. pair conflicts are easy to check, and so
1226         // that is done explicitly for "fast rejection", and because for
1227         // child vs. child conflicts, we may prefer to keep the current
1228         // pair in preference to the already-selected child.
1229         DenseSet<ValuePair> CurrentPairs;
1230
1231         bool CanAdd = true;
1232         for (DenseMap<ValuePair, size_t>::iterator C2
1233               = BestChildren.begin(), E2 = BestChildren.end();
1234              C2 != E2; ++C2) {
1235           if (C2->first.first == C->first.first ||
1236               C2->first.first == C->first.second ||
1237               C2->first.second == C->first.first ||
1238               C2->first.second == C->first.second ||
1239               pairsConflict(C2->first, C->first, PairableInstUsers,
1240                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1241             if (C2->second >= C->second) {
1242               CanAdd = false;
1243               break;
1244             }
1245
1246             CurrentPairs.insert(C2->first);
1247           }
1248         }
1249         if (!CanAdd) continue;
1250
1251         // Even worse, this child could conflict with another node already
1252         // selected for the Tree. If that is the case, ignore this child.
1253         for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1254              E2 = PrunedTree.end(); T != E2; ++T) {
1255           if (T->first == C->first.first ||
1256               T->first == C->first.second ||
1257               T->second == C->first.first ||
1258               T->second == C->first.second ||
1259               pairsConflict(*T, C->first, PairableInstUsers,
1260                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1261             CanAdd = false;
1262             break;
1263           }
1264
1265           CurrentPairs.insert(*T);
1266         }
1267         if (!CanAdd) continue;
1268
1269         // And check the queue too...
1270         for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1271              E2 = Q.end(); C2 != E2; ++C2) {
1272           if (C2->first.first == C->first.first ||
1273               C2->first.first == C->first.second ||
1274               C2->first.second == C->first.first ||
1275               C2->first.second == C->first.second ||
1276               pairsConflict(C2->first, C->first, PairableInstUsers,
1277                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1278             CanAdd = false;
1279             break;
1280           }
1281
1282           CurrentPairs.insert(C2->first);
1283         }
1284         if (!CanAdd) continue;
1285
1286         // Last but not least, check for a conflict with any of the
1287         // already-chosen pairs.
1288         for (DenseMap<Value *, Value *>::iterator C2 =
1289               ChosenPairs.begin(), E2 = ChosenPairs.end();
1290              C2 != E2; ++C2) {
1291           if (pairsConflict(*C2, C->first, PairableInstUsers,
1292                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1293             CanAdd = false;
1294             break;
1295           }
1296
1297           CurrentPairs.insert(*C2);
1298         }
1299         if (!CanAdd) continue;
1300
1301         // To check for non-trivial cycles formed by the addition of the
1302         // current pair we've formed a list of all relevant pairs, now use a
1303         // graph walk to check for a cycle. We start from the current pair and
1304         // walk the use tree to see if we again reach the current pair. If we
1305         // do, then the current pair is rejected.
1306
1307         // FIXME: It may be more efficient to use a topological-ordering
1308         // algorithm to improve the cycle check. This should be investigated.
1309         if (UseCycleCheck &&
1310             pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1311           continue;
1312
1313         // This child can be added, but we may have chosen it in preference
1314         // to an already-selected child. Check for this here, and if a
1315         // conflict is found, then remove the previously-selected child
1316         // before adding this one in its place.
1317         for (DenseMap<ValuePair, size_t>::iterator C2
1318               = BestChildren.begin(); C2 != BestChildren.end();) {
1319           if (C2->first.first == C->first.first ||
1320               C2->first.first == C->first.second ||
1321               C2->first.second == C->first.first ||
1322               C2->first.second == C->first.second ||
1323               pairsConflict(C2->first, C->first, PairableInstUsers))
1324             BestChildren.erase(C2++);
1325           else
1326             ++C2;
1327         }
1328
1329         BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1330       }
1331
1332       for (DenseMap<ValuePair, size_t>::iterator C
1333             = BestChildren.begin(), E2 = BestChildren.end();
1334            C != E2; ++C) {
1335         size_t DepthF = getDepthFactor(C->first.first);
1336         Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1337       }
1338     } while (!Q.empty());
1339   }
1340
1341   // This function finds the best tree of mututally-compatible connected
1342   // pairs, given the choice of root pairs as an iterator range.
1343   void BBVectorize::findBestTreeFor(
1344                       std::multimap<Value *, Value *> &CandidatePairs,
1345                       std::vector<Value *> &PairableInsts,
1346                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1347                       DenseSet<ValuePair> &PairableInstUsers,
1348                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1349                       DenseMap<Value *, Value *> &ChosenPairs,
1350                       DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1351                       size_t &BestEffSize, VPIteratorPair ChoiceRange,
1352                       bool UseCycleCheck) {
1353     for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1354          J != ChoiceRange.second; ++J) {
1355
1356       // Before going any further, make sure that this pair does not
1357       // conflict with any already-selected pairs (see comment below
1358       // near the Tree pruning for more details).
1359       DenseSet<ValuePair> ChosenPairSet;
1360       bool DoesConflict = false;
1361       for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1362            E = ChosenPairs.end(); C != E; ++C) {
1363         if (pairsConflict(*C, *J, PairableInstUsers,
1364                           UseCycleCheck ? &PairableInstUserMap : 0)) {
1365           DoesConflict = true;
1366           break;
1367         }
1368
1369         ChosenPairSet.insert(*C);
1370       }
1371       if (DoesConflict) continue;
1372
1373       if (UseCycleCheck &&
1374           pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1375         continue;
1376
1377       DenseMap<ValuePair, size_t> Tree;
1378       buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1379                           PairableInstUsers, ChosenPairs, Tree, *J);
1380
1381       // Because we'll keep the child with the largest depth, the largest
1382       // depth is still the same in the unpruned Tree.
1383       size_t MaxDepth = Tree.lookup(*J);
1384
1385       DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1386                    << *J->first << " <-> " << *J->second << "} of depth " <<
1387                    MaxDepth << " and size " << Tree.size() << "\n");
1388
1389       // At this point the Tree has been constructed, but, may contain
1390       // contradictory children (meaning that different children of
1391       // some tree node may be attempting to fuse the same instruction).
1392       // So now we walk the tree again, in the case of a conflict,
1393       // keep only the child with the largest depth. To break a tie,
1394       // favor the first child.
1395
1396       DenseSet<ValuePair> PrunedTree;
1397       pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1398                    PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1399                    PrunedTree, *J, UseCycleCheck);
1400
1401       size_t EffSize = 0;
1402       for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1403            E = PrunedTree.end(); S != E; ++S)
1404         EffSize += getDepthFactor(S->first);
1405
1406       DEBUG(if (DebugPairSelection)
1407              dbgs() << "BBV: found pruned Tree for pair {"
1408              << *J->first << " <-> " << *J->second << "} of depth " <<
1409              MaxDepth << " and size " << PrunedTree.size() <<
1410             " (effective size: " << EffSize << ")\n");
1411       if (MaxDepth >= Config.ReqChainDepth && EffSize > BestEffSize) {
1412         BestMaxDepth = MaxDepth;
1413         BestEffSize = EffSize;
1414         BestTree = PrunedTree;
1415       }
1416     }
1417   }
1418
1419   // Given the list of candidate pairs, this function selects those
1420   // that will be fused into vector instructions.
1421   void BBVectorize::choosePairs(
1422                       std::multimap<Value *, Value *> &CandidatePairs,
1423                       std::vector<Value *> &PairableInsts,
1424                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1425                       DenseSet<ValuePair> &PairableInstUsers,
1426                       DenseMap<Value *, Value *>& ChosenPairs) {
1427     bool UseCycleCheck =
1428      CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1429     std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1430     for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1431          E = PairableInsts.end(); I != E; ++I) {
1432       // The number of possible pairings for this variable:
1433       size_t NumChoices = CandidatePairs.count(*I);
1434       if (!NumChoices) continue;
1435
1436       VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1437
1438       // The best pair to choose and its tree:
1439       size_t BestMaxDepth = 0, BestEffSize = 0;
1440       DenseSet<ValuePair> BestTree;
1441       findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1442                       PairableInstUsers, PairableInstUserMap, ChosenPairs,
1443                       BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1444                       UseCycleCheck);
1445
1446       // A tree has been chosen (or not) at this point. If no tree was
1447       // chosen, then this instruction, I, cannot be paired (and is no longer
1448       // considered).
1449
1450       DEBUG(if (BestTree.size() > 0)
1451               dbgs() << "BBV: selected pairs in the best tree for: "
1452                      << *cast<Instruction>(*I) << "\n");
1453
1454       for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1455            SE2 = BestTree.end(); S != SE2; ++S) {
1456         // Insert the members of this tree into the list of chosen pairs.
1457         ChosenPairs.insert(ValuePair(S->first, S->second));
1458         DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1459                *S->second << "\n");
1460
1461         // Remove all candidate pairs that have values in the chosen tree.
1462         for (std::multimap<Value *, Value *>::iterator K =
1463                CandidatePairs.begin(); K != CandidatePairs.end();) {
1464           if (K->first == S->first || K->second == S->first ||
1465               K->second == S->second || K->first == S->second) {
1466             // Don't remove the actual pair chosen so that it can be used
1467             // in subsequent tree selections.
1468             if (!(K->first == S->first && K->second == S->second))
1469               CandidatePairs.erase(K++);
1470             else
1471               ++K;
1472           } else {
1473             ++K;
1474           }
1475         }
1476       }
1477     }
1478
1479     DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1480   }
1481
1482   std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1483                      unsigned n = 0) {
1484     if (!I->hasName())
1485       return "";
1486
1487     return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1488              (n > 0 ? "." + utostr(n) : "")).str();
1489   }
1490
1491   // Returns the value that is to be used as the pointer input to the vector
1492   // instruction that fuses I with J.
1493   Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1494                      Instruction *I, Instruction *J, unsigned o,
1495                      bool &FlipMemInputs) {
1496     Value *IPtr, *JPtr;
1497     unsigned IAlignment, JAlignment;
1498     int64_t OffsetInElmts;
1499     (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1500                           OffsetInElmts);
1501
1502     // The pointer value is taken to be the one with the lowest offset.
1503     Value *VPtr;
1504     if (OffsetInElmts > 0) {
1505       VPtr = IPtr;
1506     } else {
1507       FlipMemInputs = true;
1508       VPtr = JPtr;
1509     }
1510
1511     Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
1512     Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
1513     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1514     Type *VArgPtrType = PointerType::get(VArgType,
1515       cast<PointerType>(IPtr->getType())->getAddressSpace());
1516     return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1517                         /* insert before */ FlipMemInputs ? J : I);
1518   }
1519
1520   void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1521                      unsigned MaskOffset, unsigned NumInElem,
1522                      unsigned NumInElem1, unsigned IdxOffset,
1523                      std::vector<Constant*> &Mask) {
1524     unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
1525     for (unsigned v = 0; v < NumElem1; ++v) {
1526       int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1527       if (m < 0) {
1528         Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1529       } else {
1530         unsigned mm = m + (int) IdxOffset;
1531         if (m >= (int) NumInElem1)
1532           mm += (int) NumInElem;
1533
1534         Mask[v+MaskOffset] =
1535           ConstantInt::get(Type::getInt32Ty(Context), mm);
1536       }
1537     }
1538   }
1539
1540   // Returns the value that is to be used as the vector-shuffle mask to the
1541   // vector instruction that fuses I with J.
1542   Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1543                      Instruction *I, Instruction *J) {
1544     // This is the shuffle mask. We need to append the second
1545     // mask to the first, and the numbers need to be adjusted.
1546
1547     Type *ArgTypeI = I->getType();
1548     Type *ArgTypeJ = J->getType();
1549     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1550
1551     unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
1552
1553     // Get the total number of elements in the fused vector type.
1554     // By definition, this must equal the number of elements in
1555     // the final mask.
1556     unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1557     std::vector<Constant*> Mask(NumElem);
1558
1559     Type *OpTypeI = I->getOperand(0)->getType();
1560     unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
1561     Type *OpTypeJ = J->getOperand(0)->getType();
1562     unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
1563
1564     // The fused vector will be:
1565     // -----------------------------------------------------
1566     // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
1567     // -----------------------------------------------------
1568     // from which we'll extract NumElem total elements (where the first NumElemI
1569     // of them come from the mask in I and the remainder come from the mask
1570     // in J.
1571
1572     // For the mask from the first pair...
1573     fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
1574                        0,          Mask);
1575
1576     // For the mask from the second pair...
1577     fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
1578                        NumInElemI, Mask);
1579
1580     return ConstantVector::get(Mask);
1581   }
1582
1583   bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
1584                                   Instruction *J, unsigned o, Value *&LOp,
1585                                   unsigned numElemL,
1586                                   Type *ArgTypeL, Type *ArgTypeH,
1587                                   unsigned IdxOff) {
1588     bool ExpandedIEChain = false;
1589     if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
1590       // If we have a pure insertelement chain, then this can be rewritten
1591       // into a chain that directly builds the larger type.
1592       bool PureChain = true;
1593       InsertElementInst *LIENext = LIE;
1594       do {
1595         if (!isa<UndefValue>(LIENext->getOperand(0)) &&
1596             !isa<InsertElementInst>(LIENext->getOperand(0))) {
1597           PureChain = false;
1598           break;
1599         }
1600       } while ((LIENext =
1601                  dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1602
1603       if (PureChain) {
1604         SmallVector<Value *, 8> VectElemts(numElemL,
1605           UndefValue::get(ArgTypeL->getScalarType()));
1606         InsertElementInst *LIENext = LIE;
1607         do {
1608           unsigned Idx =
1609             cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
1610           VectElemts[Idx] = LIENext->getOperand(1);
1611         } while ((LIENext =
1612                    dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1613
1614         LIENext = 0;
1615         Value *LIEPrev = UndefValue::get(ArgTypeH);
1616         for (unsigned i = 0; i < numElemL; ++i) {
1617           if (isa<UndefValue>(VectElemts[i])) continue;
1618           LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
1619                              ConstantInt::get(Type::getInt32Ty(Context),
1620                                               i + IdxOff),
1621                              getReplacementName(I, true, o, i+1));
1622           LIENext->insertBefore(J);
1623           LIEPrev = LIENext;
1624         }
1625
1626         LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
1627         ExpandedIEChain = true;
1628       }
1629     }
1630
1631     return ExpandedIEChain;
1632   }
1633
1634   // Returns the value to be used as the specified operand of the vector
1635   // instruction that fuses I with J.
1636   Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1637                      Instruction *J, unsigned o, bool FlipMemInputs) {
1638     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1639     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1640
1641     // Compute the fused vector type for this operand
1642     Type *ArgTypeI = I->getOperand(o)->getType();
1643     Type *ArgTypeJ = J->getOperand(o)->getType();
1644     VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1645
1646     Instruction *L = I, *H = J;
1647     Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
1648     if (FlipMemInputs) {
1649       L = J;
1650       H = I;
1651       ArgTypeL = ArgTypeJ;
1652       ArgTypeH = ArgTypeI;
1653     }
1654
1655     unsigned numElemL;
1656     if (ArgTypeL->isVectorTy())
1657       numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
1658     else
1659       numElemL = 1;
1660
1661     unsigned numElemH;
1662     if (ArgTypeH->isVectorTy())
1663       numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
1664     else
1665       numElemH = 1;
1666
1667     Value *LOp = L->getOperand(o);
1668     Value *HOp = H->getOperand(o);
1669     unsigned numElem = VArgType->getNumElements();
1670
1671     // First, we check if we can reuse the "original" vector outputs (if these
1672     // exist). We might need a shuffle.
1673     ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
1674     ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
1675     ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
1676     ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
1677
1678     // FIXME: If we're fusing shuffle instructions, then we can't apply this
1679     // optimization. The input vectors to the shuffle might be a different
1680     // length from the shuffle outputs. Unfortunately, the replacement
1681     // shuffle mask has already been formed, and the mask entries are sensitive
1682     // to the sizes of the inputs.
1683     bool IsSizeChangeShuffle =
1684       isa<ShuffleVectorInst>(L) &&
1685         (LOp->getType() != L->getType() || HOp->getType() != H->getType());
1686
1687     if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
1688       // We can have at most two unique vector inputs.
1689       bool CanUseInputs = true;
1690       Value *I1, *I2 = 0;
1691       if (LEE) {
1692         I1 = LEE->getOperand(0);
1693       } else {
1694         I1 = LSV->getOperand(0);
1695         I2 = LSV->getOperand(1);
1696         if (I2 == I1 || isa<UndefValue>(I2))
1697           I2 = 0;
1698       }
1699   
1700       if (HEE) {
1701         Value *I3 = HEE->getOperand(0);
1702         if (!I2 && I3 != I1)
1703           I2 = I3;
1704         else if (I3 != I1 && I3 != I2)
1705           CanUseInputs = false;
1706       } else {
1707         Value *I3 = HSV->getOperand(0);
1708         if (!I2 && I3 != I1)
1709           I2 = I3;
1710         else if (I3 != I1 && I3 != I2)
1711           CanUseInputs = false;
1712
1713         if (CanUseInputs) {
1714           Value *I4 = HSV->getOperand(1);
1715           if (!isa<UndefValue>(I4)) {
1716             if (!I2 && I4 != I1)
1717               I2 = I4;
1718             else if (I4 != I1 && I4 != I2)
1719               CanUseInputs = false;
1720           }
1721         }
1722       }
1723
1724       if (CanUseInputs) {
1725         unsigned LOpElem =
1726           cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
1727             ->getNumElements();
1728         unsigned HOpElem =
1729           cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
1730             ->getNumElements();
1731
1732         // We have one or two input vectors. We need to map each index of the
1733         // operands to the index of the original vector.
1734         SmallVector<std::pair<int, int>, 8>  II(numElem);
1735         for (unsigned i = 0; i < numElemL; ++i) {
1736           int Idx, INum;
1737           if (LEE) {
1738             Idx =
1739               cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
1740             INum = LEE->getOperand(0) == I1 ? 0 : 1;
1741           } else {
1742             Idx = LSV->getMaskValue(i);
1743             if (Idx < (int) LOpElem) {
1744               INum = LSV->getOperand(0) == I1 ? 0 : 1;
1745             } else {
1746               Idx -= LOpElem;
1747               INum = LSV->getOperand(1) == I1 ? 0 : 1;
1748             }
1749           }
1750
1751           II[i] = std::pair<int, int>(Idx, INum);
1752         }
1753         for (unsigned i = 0; i < numElemH; ++i) {
1754           int Idx, INum;
1755           if (HEE) {
1756             Idx =
1757               cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
1758             INum = HEE->getOperand(0) == I1 ? 0 : 1;
1759           } else {
1760             Idx = HSV->getMaskValue(i);
1761             if (Idx < (int) HOpElem) {
1762               INum = HSV->getOperand(0) == I1 ? 0 : 1;
1763             } else {
1764               Idx -= HOpElem;
1765               INum = HSV->getOperand(1) == I1 ? 0 : 1;
1766             }
1767           }
1768
1769           II[i + numElemL] = std::pair<int, int>(Idx, INum);
1770         }
1771
1772         // We now have an array which tells us from which index of which
1773         // input vector each element of the operand comes.
1774         VectorType *I1T = cast<VectorType>(I1->getType());
1775         unsigned I1Elem = I1T->getNumElements();
1776
1777         if (!I2) {
1778           // In this case there is only one underlying vector input. Check for
1779           // the trivial case where we can use the input directly.
1780           if (I1Elem == numElem) {
1781             bool ElemInOrder = true;
1782             for (unsigned i = 0; i < numElem; ++i) {
1783               if (II[i].first != (int) i && II[i].first != -1) {
1784                 ElemInOrder = false;
1785                 break;
1786               }
1787             }
1788
1789             if (ElemInOrder)
1790               return I1;
1791           }
1792
1793           // A shuffle is needed.
1794           std::vector<Constant *> Mask(numElem);
1795           for (unsigned i = 0; i < numElem; ++i) {
1796             int Idx = II[i].first;
1797             if (Idx == -1)
1798               Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
1799             else
1800               Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1801           }
1802
1803           Instruction *S =
1804             new ShuffleVectorInst(I1, UndefValue::get(I1T),
1805                                   ConstantVector::get(Mask),
1806                                   getReplacementName(I, true, o));
1807           S->insertBefore(J);
1808           return S;
1809         }
1810
1811         VectorType *I2T = cast<VectorType>(I2->getType());
1812         unsigned I2Elem = I2T->getNumElements();
1813
1814         // This input comes from two distinct vectors. The first step is to
1815         // make sure that both vectors are the same length. If not, the
1816         // smaller one will need to grow before they can be shuffled together.
1817         if (I1Elem < I2Elem) {
1818           std::vector<Constant *> Mask(I2Elem);
1819           unsigned v = 0;
1820           for (; v < I1Elem; ++v)
1821             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1822           for (; v < I2Elem; ++v)
1823             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1824
1825           Instruction *NewI1 =
1826             new ShuffleVectorInst(I1, UndefValue::get(I1T),
1827                                   ConstantVector::get(Mask),
1828                                   getReplacementName(I, true, o, 1));
1829           NewI1->insertBefore(J);
1830           I1 = NewI1;
1831           I1T = I2T;
1832           I1Elem = I2Elem;
1833         } else if (I1Elem > I2Elem) {
1834           std::vector<Constant *> Mask(I1Elem);
1835           unsigned v = 0;
1836           for (; v < I2Elem; ++v)
1837             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1838           for (; v < I1Elem; ++v)
1839             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1840
1841           Instruction *NewI2 =
1842             new ShuffleVectorInst(I2, UndefValue::get(I2T),
1843                                   ConstantVector::get(Mask),
1844                                   getReplacementName(I, true, o, 1));
1845           NewI2->insertBefore(J);
1846           I2 = NewI2;
1847           I2T = I1T;
1848           I2Elem = I1Elem;
1849         }
1850
1851         // Now that both I1 and I2 are the same length we can shuffle them
1852         // together (and use the result).
1853         std::vector<Constant *> Mask(numElem);
1854         for (unsigned v = 0; v < numElem; ++v) {
1855           if (II[v].first == -1) {
1856             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1857           } else {
1858             int Idx = II[v].first + II[v].second * I1Elem;
1859             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1860           }
1861         }
1862
1863         Instruction *NewOp =
1864           new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
1865                                 getReplacementName(I, true, o));
1866         NewOp->insertBefore(J);
1867         return NewOp;
1868       }
1869     }
1870
1871     Type *ArgType = ArgTypeL;
1872     if (numElemL < numElemH) {
1873       if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
1874                                          ArgTypeL, VArgType, 1)) {
1875         // This is another short-circuit case: we're combining a scalar into
1876         // a vector that is formed by an IE chain. We've just expanded the IE
1877         // chain, now insert the scalar and we're done.
1878
1879         Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
1880                                                getReplacementName(I, true, o));
1881         S->insertBefore(J);
1882         return S;
1883       } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
1884                                 ArgTypeH)) {
1885         // The two vector inputs to the shuffle must be the same length,
1886         // so extend the smaller vector to be the same length as the larger one.
1887         Instruction *NLOp;
1888         if (numElemL > 1) {
1889   
1890           std::vector<Constant *> Mask(numElemH);
1891           unsigned v = 0;
1892           for (; v < numElemL; ++v)
1893             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1894           for (; v < numElemH; ++v)
1895             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1896     
1897           NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
1898                                        ConstantVector::get(Mask),
1899                                        getReplacementName(I, true, o, 1));
1900         } else {
1901           NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
1902                                            getReplacementName(I, true, o, 1));
1903         }
1904   
1905         NLOp->insertBefore(J);
1906         LOp = NLOp;
1907       }
1908
1909       ArgType = ArgTypeH;
1910     } else if (numElemL > numElemH) {
1911       if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
1912                                          ArgTypeH, VArgType)) {
1913         Instruction *S =
1914           InsertElementInst::Create(LOp, HOp, 
1915                                     ConstantInt::get(Type::getInt32Ty(Context),
1916                                                      numElemL),
1917                                     getReplacementName(I, true, o));
1918         S->insertBefore(J);
1919         return S;
1920       } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
1921                                 ArgTypeL)) {
1922         Instruction *NHOp;
1923         if (numElemH > 1) {
1924           std::vector<Constant *> Mask(numElemL);
1925           unsigned v = 0;
1926           for (; v < numElemH; ++v)
1927             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1928           for (; v < numElemL; ++v)
1929             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1930     
1931           NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
1932                                        ConstantVector::get(Mask),
1933                                        getReplacementName(I, true, o, 1));
1934         } else {
1935           NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
1936                                            getReplacementName(I, true, o, 1));
1937         }
1938   
1939         NHOp->insertBefore(J);
1940         HOp = NHOp;
1941       }
1942     }
1943
1944     if (ArgType->isVectorTy()) {
1945       unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1946       std::vector<Constant*> Mask(numElem);
1947       for (unsigned v = 0; v < numElem; ++v) {
1948         unsigned Idx = v;
1949         // If the low vector was expanded, we need to skip the extra
1950         // undefined entries.
1951         if (v >= numElemL && numElemH > numElemL)
1952           Idx += (numElemH - numElemL);
1953         Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1954       }
1955
1956       Instruction *BV = new ShuffleVectorInst(LOp, HOp,
1957                                               ConstantVector::get(Mask),
1958                                               getReplacementName(I, true, o));
1959       BV->insertBefore(J);
1960       return BV;
1961     }
1962
1963     Instruction *BV1 = InsertElementInst::Create(
1964                                           UndefValue::get(VArgType), LOp, CV0,
1965                                           getReplacementName(I, true, o, 1));
1966     BV1->insertBefore(I);
1967     Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
1968                                           getReplacementName(I, true, o, 2));
1969     BV2->insertBefore(J);
1970     return BV2;
1971   }
1972
1973   // This function creates an array of values that will be used as the inputs
1974   // to the vector instruction that fuses I with J.
1975   void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1976                      Instruction *I, Instruction *J,
1977                      SmallVector<Value *, 3> &ReplacedOperands,
1978                      bool &FlipMemInputs) {
1979     FlipMemInputs = false;
1980     unsigned NumOperands = I->getNumOperands();
1981
1982     for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1983       // Iterate backward so that we look at the store pointer
1984       // first and know whether or not we need to flip the inputs.
1985
1986       if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1987         // This is the pointer for a load/store instruction.
1988         ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1989                                 FlipMemInputs);
1990         continue;
1991       } else if (isa<CallInst>(I)) {
1992         Function *F = cast<CallInst>(I)->getCalledFunction();
1993         unsigned IID = F->getIntrinsicID();
1994         if (o == NumOperands-1) {
1995           BasicBlock &BB = *I->getParent();
1996
1997           Module *M = BB.getParent()->getParent();
1998           Type *ArgTypeI = I->getType();
1999           Type *ArgTypeJ = J->getType();
2000           Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2001
2002           ReplacedOperands[o] = Intrinsic::getDeclaration(M,
2003             (Intrinsic::ID) IID, VArgType);
2004           continue;
2005         } else if (IID == Intrinsic::powi && o == 1) {
2006           // The second argument of powi is a single integer and we've already
2007           // checked that both arguments are equal. As a result, we just keep
2008           // I's second argument.
2009           ReplacedOperands[o] = I->getOperand(o);
2010           continue;
2011         }
2012       } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2013         ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2014         continue;
2015       }
2016
2017       ReplacedOperands[o] =
2018         getReplacementInput(Context, I, J, o, FlipMemInputs);
2019     }
2020   }
2021
2022   // This function creates two values that represent the outputs of the
2023   // original I and J instructions. These are generally vector shuffles
2024   // or extracts. In many cases, these will end up being unused and, thus,
2025   // eliminated by later passes.
2026   void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2027                      Instruction *J, Instruction *K,
2028                      Instruction *&InsertionPt,
2029                      Instruction *&K1, Instruction *&K2,
2030                      bool &FlipMemInputs) {
2031     if (isa<StoreInst>(I)) {
2032       AA->replaceWithNewValue(I, K);
2033       AA->replaceWithNewValue(J, K);
2034     } else {
2035       Type *IType = I->getType();
2036       Type *JType = J->getType();
2037
2038       VectorType *VType = getVecTypeForPair(IType, JType);
2039       unsigned numElem = VType->getNumElements();
2040
2041       unsigned numElemI, numElemJ;
2042       if (IType->isVectorTy())
2043         numElemI = cast<VectorType>(IType)->getNumElements();
2044       else
2045         numElemI = 1;
2046
2047       if (JType->isVectorTy())
2048         numElemJ = cast<VectorType>(JType)->getNumElements();
2049       else
2050         numElemJ = 1;
2051
2052       if (IType->isVectorTy()) {
2053         std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2054         for (unsigned v = 0; v < numElemI; ++v) {
2055           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2056           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2057         }
2058
2059         K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2060                                    ConstantVector::get(
2061                                      FlipMemInputs ? Mask2 : Mask1),
2062                                    getReplacementName(K, false, 1));
2063       } else {
2064         Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2065         Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2066         K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
2067                                           getReplacementName(K, false, 1));
2068       }
2069
2070       if (JType->isVectorTy()) {
2071         std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2072         for (unsigned v = 0; v < numElemJ; ++v) {
2073           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2074           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2075         }
2076
2077         K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2078                                    ConstantVector::get(
2079                                      FlipMemInputs ? Mask1 : Mask2),
2080                                    getReplacementName(K, false, 2));
2081       } else {
2082         Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2083         Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2084         K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
2085                                           getReplacementName(K, false, 2));
2086       }
2087
2088       K1->insertAfter(K);
2089       K2->insertAfter(K1);
2090       InsertionPt = K2;
2091     }
2092   }
2093
2094   // Move all uses of the function I (including pairing-induced uses) after J.
2095   bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2096                      std::multimap<Value *, Value *> &LoadMoveSet,
2097                      Instruction *I, Instruction *J) {
2098     // Skip to the first instruction past I.
2099     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2100
2101     DenseSet<Value *> Users;
2102     AliasSetTracker WriteSet(*AA);
2103     for (; cast<Instruction>(L) != J; ++L)
2104       (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
2105
2106     assert(cast<Instruction>(L) == J &&
2107       "Tracking has not proceeded far enough to check for dependencies");
2108     // If J is now in the use set of I, then trackUsesOfI will return true
2109     // and we have a dependency cycle (and the fusing operation must abort).
2110     return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
2111   }
2112
2113   // Move all uses of the function I (including pairing-induced uses) after J.
2114   void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2115                      std::multimap<Value *, Value *> &LoadMoveSet,
2116                      Instruction *&InsertionPt,
2117                      Instruction *I, Instruction *J) {
2118     // Skip to the first instruction past I.
2119     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2120
2121     DenseSet<Value *> Users;
2122     AliasSetTracker WriteSet(*AA);
2123     for (; cast<Instruction>(L) != J;) {
2124       if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
2125         // Move this instruction
2126         Instruction *InstToMove = L; ++L;
2127
2128         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2129                         " to after " << *InsertionPt << "\n");
2130         InstToMove->removeFromParent();
2131         InstToMove->insertAfter(InsertionPt);
2132         InsertionPt = InstToMove;
2133       } else {
2134         ++L;
2135       }
2136     }
2137   }
2138
2139   // Collect all load instruction that are in the move set of a given first
2140   // pair member.  These loads depend on the first instruction, I, and so need
2141   // to be moved after J (the second instruction) when the pair is fused.
2142   void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2143                      DenseMap<Value *, Value *> &ChosenPairs,
2144                      std::multimap<Value *, Value *> &LoadMoveSet,
2145                      Instruction *I) {
2146     // Skip to the first instruction past I.
2147     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2148
2149     DenseSet<Value *> Users;
2150     AliasSetTracker WriteSet(*AA);
2151
2152     // Note: We cannot end the loop when we reach J because J could be moved
2153     // farther down the use chain by another instruction pairing. Also, J
2154     // could be before I if this is an inverted input.
2155     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2156       if (trackUsesOfI(Users, WriteSet, I, L)) {
2157         if (L->mayReadFromMemory())
2158           LoadMoveSet.insert(ValuePair(L, I));
2159       }
2160     }
2161   }
2162
2163   // In cases where both load/stores and the computation of their pointers
2164   // are chosen for vectorization, we can end up in a situation where the
2165   // aliasing analysis starts returning different query results as the
2166   // process of fusing instruction pairs continues. Because the algorithm
2167   // relies on finding the same use trees here as were found earlier, we'll
2168   // need to precompute the necessary aliasing information here and then
2169   // manually update it during the fusion process.
2170   void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2171                      std::vector<Value *> &PairableInsts,
2172                      DenseMap<Value *, Value *> &ChosenPairs,
2173                      std::multimap<Value *, Value *> &LoadMoveSet) {
2174     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2175          PIE = PairableInsts.end(); PI != PIE; ++PI) {
2176       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2177       if (P == ChosenPairs.end()) continue;
2178
2179       Instruction *I = cast<Instruction>(P->first);
2180       collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
2181     }
2182   }
2183
2184   // When the first instruction in each pair is cloned, it will inherit its
2185   // parent's metadata. This metadata must be combined with that of the other
2186   // instruction in a safe way.
2187   void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2188     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2189     K->getAllMetadataOtherThanDebugLoc(Metadata);
2190     for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2191       unsigned Kind = Metadata[i].first;
2192       MDNode *JMD = J->getMetadata(Kind);
2193       MDNode *KMD = Metadata[i].second;
2194
2195       switch (Kind) {
2196       default:
2197         K->setMetadata(Kind, 0); // Remove unknown metadata
2198         break;
2199       case LLVMContext::MD_tbaa:
2200         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2201         break;
2202       case LLVMContext::MD_fpmath:
2203         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2204         break;
2205       }
2206     }
2207   }
2208
2209   // This function fuses the chosen instruction pairs into vector instructions,
2210   // taking care preserve any needed scalar outputs and, then, it reorders the
2211   // remaining instructions as needed (users of the first member of the pair
2212   // need to be moved to after the location of the second member of the pair
2213   // because the vector instruction is inserted in the location of the pair's
2214   // second member).
2215   void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2216                      std::vector<Value *> &PairableInsts,
2217                      DenseMap<Value *, Value *> &ChosenPairs) {
2218     LLVMContext& Context = BB.getContext();
2219
2220     // During the vectorization process, the order of the pairs to be fused
2221     // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2222     // list. After a pair is fused, the flipped pair is removed from the list.
2223     std::vector<ValuePair> FlippedPairs;
2224     FlippedPairs.reserve(ChosenPairs.size());
2225     for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2226          E = ChosenPairs.end(); P != E; ++P)
2227       FlippedPairs.push_back(ValuePair(P->second, P->first));
2228     for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
2229          E = FlippedPairs.end(); P != E; ++P)
2230       ChosenPairs.insert(*P);
2231
2232     std::multimap<Value *, Value *> LoadMoveSet;
2233     collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2234
2235     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2236
2237     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2238       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2239       if (P == ChosenPairs.end()) {
2240         ++PI;
2241         continue;
2242       }
2243
2244       if (getDepthFactor(P->first) == 0) {
2245         // These instructions are not really fused, but are tracked as though
2246         // they are. Any case in which it would be interesting to fuse them
2247         // will be taken care of by InstCombine.
2248         --NumFusedOps;
2249         ++PI;
2250         continue;
2251       }
2252
2253       Instruction *I = cast<Instruction>(P->first),
2254         *J = cast<Instruction>(P->second);
2255
2256       DEBUG(dbgs() << "BBV: fusing: " << *I <<
2257              " <-> " << *J << "\n");
2258
2259       // Remove the pair and flipped pair from the list.
2260       DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2261       assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2262       ChosenPairs.erase(FP);
2263       ChosenPairs.erase(P);
2264
2265       if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2266         DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2267                " <-> " << *J <<
2268                " aborted because of non-trivial dependency cycle\n");
2269         --NumFusedOps;
2270         ++PI;
2271         continue;
2272       }
2273
2274       bool FlipMemInputs;
2275       unsigned NumOperands = I->getNumOperands();
2276       SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2277       getReplacementInputsForPair(Context, I, J, ReplacedOperands,
2278         FlipMemInputs);
2279
2280       // Make a copy of the original operation, change its type to the vector
2281       // type and replace its operands with the vector operands.
2282       Instruction *K = I->clone();
2283       if (I->hasName()) K->takeName(I);
2284
2285       if (!isa<StoreInst>(K))
2286         K->mutateType(getVecTypeForPair(I->getType(), J->getType()));
2287
2288       combineMetadata(K, J);
2289
2290       for (unsigned o = 0; o < NumOperands; ++o)
2291         K->setOperand(o, ReplacedOperands[o]);
2292
2293       // If we've flipped the memory inputs, make sure that we take the correct
2294       // alignment.
2295       if (FlipMemInputs) {
2296         if (isa<StoreInst>(K))
2297           cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
2298         else
2299           cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
2300       }
2301
2302       K->insertAfter(J);
2303
2304       // Instruction insertion point:
2305       Instruction *InsertionPt = K;
2306       Instruction *K1 = 0, *K2 = 0;
2307       replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
2308         FlipMemInputs);
2309
2310       // The use tree of the first original instruction must be moved to after
2311       // the location of the second instruction. The entire use tree of the
2312       // first instruction is disjoint from the input tree of the second
2313       // (by definition), and so commutes with it.
2314
2315       moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2316
2317       if (!isa<StoreInst>(I)) {
2318         I->replaceAllUsesWith(K1);
2319         J->replaceAllUsesWith(K2);
2320         AA->replaceWithNewValue(I, K1);
2321         AA->replaceWithNewValue(J, K2);
2322       }
2323
2324       // Instructions that may read from memory may be in the load move set.
2325       // Once an instruction is fused, we no longer need its move set, and so
2326       // the values of the map never need to be updated. However, when a load
2327       // is fused, we need to merge the entries from both instructions in the
2328       // pair in case those instructions were in the move set of some other
2329       // yet-to-be-fused pair. The loads in question are the keys of the map.
2330       if (I->mayReadFromMemory()) {
2331         std::vector<ValuePair> NewSetMembers;
2332         VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
2333         VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
2334         for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
2335              N != IPairRange.second; ++N)
2336           NewSetMembers.push_back(ValuePair(K, N->second));
2337         for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
2338              N != JPairRange.second; ++N)
2339           NewSetMembers.push_back(ValuePair(K, N->second));
2340         for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
2341              AE = NewSetMembers.end(); A != AE; ++A)
2342           LoadMoveSet.insert(*A);
2343       }
2344
2345       // Before removing I, set the iterator to the next instruction.
2346       PI = llvm::next(BasicBlock::iterator(I));
2347       if (cast<Instruction>(PI) == J)
2348         ++PI;
2349
2350       SE->forgetValue(I);
2351       SE->forgetValue(J);
2352       I->eraseFromParent();
2353       J->eraseFromParent();
2354     }
2355
2356     DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
2357   }
2358 }
2359
2360 char BBVectorize::ID = 0;
2361 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
2362 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2363 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2364 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2365 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2366
2367 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
2368   return new BBVectorize(C);
2369 }
2370
2371 bool
2372 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
2373   BBVectorize BBVectorizer(P, C);
2374   return BBVectorizer.vectorizeBB(BB);
2375 }
2376
2377 //===----------------------------------------------------------------------===//
2378 VectorizeConfig::VectorizeConfig() {
2379   VectorBits = ::VectorBits;
2380   VectorizeBools = !::NoBools;
2381   VectorizeInts = !::NoInts;
2382   VectorizeFloats = !::NoFloats;
2383   VectorizePointers = !::NoPointers;
2384   VectorizeCasts = !::NoCasts;
2385   VectorizeMath = !::NoMath;
2386   VectorizeFMA = !::NoFMA;
2387   VectorizeSelect = !::NoSelect;
2388   VectorizeCmp = !::NoCmp;
2389   VectorizeGEP = !::NoGEP;
2390   VectorizeMemOps = !::NoMemOps;
2391   AlignedOnly = ::AlignedOnly;
2392   ReqChainDepth= ::ReqChainDepth;
2393   SearchLimit = ::SearchLimit;
2394   MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
2395   SplatBreaksChain = ::SplatBreaksChain;
2396   MaxInsts = ::MaxInsts;
2397   MaxIter = ::MaxIter;
2398   Pow2LenOnly = ::Pow2LenOnly;
2399   NoMemOpBoost = ::NoMemOpBoost;
2400   FastDep = ::FastDep;
2401 }