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