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