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