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