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