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