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