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