LLVM API Documentation

BBVectorize.cpp
Go to the documentation of this file.
00001 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a basic-block vectorization pass. The algorithm was
00011 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
00012 // et al. It works by looking for chains of pairable operations and then
00013 // pairing them.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define BBV_NAME "bb-vectorize"
00018 #define DEBUG_TYPE BBV_NAME
00019 #include "llvm/Transforms/Vectorize.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/DenseSet.h"
00022 #include "llvm/ADT/STLExtras.h"
00023 #include "llvm/ADT/SmallSet.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include "llvm/Analysis/AliasAnalysis.h"
00028 #include "llvm/Analysis/AliasSetTracker.h"
00029 #include "llvm/Analysis/ScalarEvolution.h"
00030 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00031 #include "llvm/Analysis/TargetTransformInfo.h"
00032 #include "llvm/Analysis/ValueTracking.h"
00033 #include "llvm/IR/Constants.h"
00034 #include "llvm/IR/DataLayout.h"
00035 #include "llvm/IR/DerivedTypes.h"
00036 #include "llvm/IR/Dominators.h"
00037 #include "llvm/IR/Function.h"
00038 #include "llvm/IR/Instructions.h"
00039 #include "llvm/IR/IntrinsicInst.h"
00040 #include "llvm/IR/Intrinsics.h"
00041 #include "llvm/IR/LLVMContext.h"
00042 #include "llvm/IR/Metadata.h"
00043 #include "llvm/IR/Type.h"
00044 #include "llvm/IR/ValueHandle.h"
00045 #include "llvm/Pass.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/Support/raw_ostream.h"
00049 #include "llvm/Transforms/Utils/Local.h"
00050 #include <algorithm>
00051 using namespace llvm;
00052 
00053 static cl::opt<bool>
00054 IgnoreTargetInfo("bb-vectorize-ignore-target-info",  cl::init(false),
00055   cl::Hidden, cl::desc("Ignore target information"));
00056 
00057 static cl::opt<unsigned>
00058 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
00059   cl::desc("The required chain depth for vectorization"));
00060 
00061 static cl::opt<bool>
00062 UseChainDepthWithTI("bb-vectorize-use-chain-depth",  cl::init(false),
00063   cl::Hidden, cl::desc("Use the chain depth requirement with"
00064                        " target information"));
00065 
00066 static cl::opt<unsigned>
00067 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
00068   cl::desc("The maximum search distance for instruction pairs"));
00069 
00070 static cl::opt<bool>
00071 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
00072   cl::desc("Replicating one element to a pair breaks the chain"));
00073 
00074 static cl::opt<unsigned>
00075 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
00076   cl::desc("The size of the native vector registers"));
00077 
00078 static cl::opt<unsigned>
00079 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
00080   cl::desc("The maximum number of pairing iterations"));
00081 
00082 static cl::opt<bool>
00083 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
00084   cl::desc("Don't try to form non-2^n-length vectors"));
00085 
00086 static cl::opt<unsigned>
00087 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
00088   cl::desc("The maximum number of pairable instructions per group"));
00089 
00090 static cl::opt<unsigned>
00091 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
00092   cl::desc("The maximum number of candidate instruction pairs per group"));
00093 
00094 static cl::opt<unsigned>
00095 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
00096   cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
00097                        " a full cycle check"));
00098 
00099 static cl::opt<bool>
00100 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
00101   cl::desc("Don't try to vectorize boolean (i1) values"));
00102 
00103 static cl::opt<bool>
00104 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
00105   cl::desc("Don't try to vectorize integer values"));
00106 
00107 static cl::opt<bool>
00108 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
00109   cl::desc("Don't try to vectorize floating-point values"));
00110 
00111 // FIXME: This should default to false once pointer vector support works.
00112 static cl::opt<bool>
00113 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
00114   cl::desc("Don't try to vectorize pointer values"));
00115 
00116 static cl::opt<bool>
00117 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
00118   cl::desc("Don't try to vectorize casting (conversion) operations"));
00119 
00120 static cl::opt<bool>
00121 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
00122   cl::desc("Don't try to vectorize floating-point math intrinsics"));
00123 
00124 static cl::opt<bool>
00125 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
00126   cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
00127 
00128 static cl::opt<bool>
00129 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
00130   cl::desc("Don't try to vectorize select instructions"));
00131 
00132 static cl::opt<bool>
00133 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
00134   cl::desc("Don't try to vectorize comparison instructions"));
00135 
00136 static cl::opt<bool>
00137 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
00138   cl::desc("Don't try to vectorize getelementptr instructions"));
00139 
00140 static cl::opt<bool>
00141 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
00142   cl::desc("Don't try to vectorize loads and stores"));
00143 
00144 static cl::opt<bool>
00145 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
00146   cl::desc("Only generate aligned loads and stores"));
00147 
00148 static cl::opt<bool>
00149 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
00150   cl::init(false), cl::Hidden,
00151   cl::desc("Don't boost the chain-depth contribution of loads and stores"));
00152 
00153 static cl::opt<bool>
00154 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
00155   cl::desc("Use a fast instruction dependency analysis"));
00156 
00157 #ifndef NDEBUG
00158 static cl::opt<bool>
00159 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
00160   cl::init(false), cl::Hidden,
00161   cl::desc("When debugging is enabled, output information on the"
00162            " instruction-examination process"));
00163 static cl::opt<bool>
00164 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
00165   cl::init(false), cl::Hidden,
00166   cl::desc("When debugging is enabled, output information on the"
00167            " candidate-selection process"));
00168 static cl::opt<bool>
00169 DebugPairSelection("bb-vectorize-debug-pair-selection",
00170   cl::init(false), cl::Hidden,
00171   cl::desc("When debugging is enabled, output information on the"
00172            " pair-selection process"));
00173 static cl::opt<bool>
00174 DebugCycleCheck("bb-vectorize-debug-cycle-check",
00175   cl::init(false), cl::Hidden,
00176   cl::desc("When debugging is enabled, output information on the"
00177            " cycle-checking process"));
00178 
00179 static cl::opt<bool>
00180 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
00181   cl::init(false), cl::Hidden,
00182   cl::desc("When debugging is enabled, dump the basic block after"
00183            " every pair is fused"));
00184 #endif
00185 
00186 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
00187 
00188 namespace {
00189   struct BBVectorize : public BasicBlockPass {
00190     static char ID; // Pass identification, replacement for typeid
00191 
00192     const VectorizeConfig Config;
00193 
00194     BBVectorize(const VectorizeConfig &C = VectorizeConfig())
00195       : BasicBlockPass(ID), Config(C) {
00196       initializeBBVectorizePass(*PassRegistry::getPassRegistry());
00197     }
00198 
00199     BBVectorize(Pass *P, const VectorizeConfig &C)
00200       : BasicBlockPass(ID), Config(C) {
00201       AA = &P->getAnalysis<AliasAnalysis>();
00202       DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00203       SE = &P->getAnalysis<ScalarEvolution>();
00204       DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
00205       DL = DLP ? &DLP->getDataLayout() : 0;
00206       TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
00207     }
00208 
00209     typedef std::pair<Value *, Value *> ValuePair;
00210     typedef std::pair<ValuePair, int> ValuePairWithCost;
00211     typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
00212     typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
00213     typedef std::pair<VPPair, unsigned> VPPairWithType;
00214 
00215     AliasAnalysis *AA;
00216     DominatorTree *DT;
00217     ScalarEvolution *SE;
00218     const DataLayout *DL;
00219     const TargetTransformInfo *TTI;
00220 
00221     // FIXME: const correct?
00222 
00223     bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
00224 
00225     bool getCandidatePairs(BasicBlock &BB,
00226                        BasicBlock::iterator &Start,
00227                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00228                        DenseSet<ValuePair> &FixedOrderPairs,
00229                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
00230                        std::vector<Value *> &PairableInsts, bool NonPow2Len);
00231 
00232     // FIXME: The current implementation does not account for pairs that
00233     // are connected in multiple ways. For example:
00234     //   C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
00235     enum PairConnectionType {
00236       PairConnectionDirect,
00237       PairConnectionSwap,
00238       PairConnectionSplat
00239     };
00240 
00241     void computeConnectedPairs(
00242              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00243              DenseSet<ValuePair> &CandidatePairsSet,
00244              std::vector<Value *> &PairableInsts,
00245              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00246              DenseMap<VPPair, unsigned> &PairConnectionTypes);
00247 
00248     void buildDepMap(BasicBlock &BB,
00249              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00250              std::vector<Value *> &PairableInsts,
00251              DenseSet<ValuePair> &PairableInstUsers);
00252 
00253     void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00254              DenseSet<ValuePair> &CandidatePairsSet,
00255              DenseMap<ValuePair, int> &CandidatePairCostSavings,
00256              std::vector<Value *> &PairableInsts,
00257              DenseSet<ValuePair> &FixedOrderPairs,
00258              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00259              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00260              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
00261              DenseSet<ValuePair> &PairableInstUsers,
00262              DenseMap<Value *, Value *>& ChosenPairs);
00263 
00264     void fuseChosenPairs(BasicBlock &BB,
00265              std::vector<Value *> &PairableInsts,
00266              DenseMap<Value *, Value *>& ChosenPairs,
00267              DenseSet<ValuePair> &FixedOrderPairs,
00268              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00269              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00270              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
00271 
00272 
00273     bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
00274 
00275     bool areInstsCompatible(Instruction *I, Instruction *J,
00276                        bool IsSimpleLoadStore, bool NonPow2Len,
00277                        int &CostSavings, int &FixedOrder);
00278 
00279     bool trackUsesOfI(DenseSet<Value *> &Users,
00280                       AliasSetTracker &WriteSet, Instruction *I,
00281                       Instruction *J, bool UpdateUsers = true,
00282                       DenseSet<ValuePair> *LoadMoveSetPairs = 0);
00283 
00284   void computePairsConnectedTo(
00285              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00286              DenseSet<ValuePair> &CandidatePairsSet,
00287              std::vector<Value *> &PairableInsts,
00288              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00289              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00290              ValuePair P);
00291 
00292     bool pairsConflict(ValuePair P, ValuePair Q,
00293              DenseSet<ValuePair> &PairableInstUsers,
00294              DenseMap<ValuePair, std::vector<ValuePair> >
00295                *PairableInstUserMap = 0,
00296              DenseSet<VPPair> *PairableInstUserPairSet = 0);
00297 
00298     bool pairWillFormCycle(ValuePair P,
00299              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
00300              DenseSet<ValuePair> &CurrentPairs);
00301 
00302     void pruneDAGFor(
00303              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00304              std::vector<Value *> &PairableInsts,
00305              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00306              DenseSet<ValuePair> &PairableInstUsers,
00307              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
00308              DenseSet<VPPair> &PairableInstUserPairSet,
00309              DenseMap<Value *, Value *> &ChosenPairs,
00310              DenseMap<ValuePair, size_t> &DAG,
00311              DenseSet<ValuePair> &PrunedDAG, ValuePair J,
00312              bool UseCycleCheck);
00313 
00314     void buildInitialDAGFor(
00315              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00316              DenseSet<ValuePair> &CandidatePairsSet,
00317              std::vector<Value *> &PairableInsts,
00318              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00319              DenseSet<ValuePair> &PairableInstUsers,
00320              DenseMap<Value *, Value *> &ChosenPairs,
00321              DenseMap<ValuePair, size_t> &DAG, ValuePair J);
00322 
00323     void findBestDAGFor(
00324              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00325              DenseSet<ValuePair> &CandidatePairsSet,
00326              DenseMap<ValuePair, int> &CandidatePairCostSavings,
00327              std::vector<Value *> &PairableInsts,
00328              DenseSet<ValuePair> &FixedOrderPairs,
00329              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00330              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00331              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
00332              DenseSet<ValuePair> &PairableInstUsers,
00333              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
00334              DenseSet<VPPair> &PairableInstUserPairSet,
00335              DenseMap<Value *, Value *> &ChosenPairs,
00336              DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
00337              int &BestEffSize, Value *II, std::vector<Value *>&JJ,
00338              bool UseCycleCheck);
00339 
00340     Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
00341                      Instruction *J, unsigned o);
00342 
00343     void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
00344                      unsigned MaskOffset, unsigned NumInElem,
00345                      unsigned NumInElem1, unsigned IdxOffset,
00346                      std::vector<Constant*> &Mask);
00347 
00348     Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
00349                      Instruction *J);
00350 
00351     bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
00352                        unsigned o, Value *&LOp, unsigned numElemL,
00353                        Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
00354                        unsigned IdxOff = 0);
00355 
00356     Value *getReplacementInput(LLVMContext& Context, Instruction *I,
00357                      Instruction *J, unsigned o, bool IBeforeJ);
00358 
00359     void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
00360                      Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
00361                      bool IBeforeJ);
00362 
00363     void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
00364                      Instruction *J, Instruction *K,
00365                      Instruction *&InsertionPt, Instruction *&K1,
00366                      Instruction *&K2);
00367 
00368     void collectPairLoadMoveSet(BasicBlock &BB,
00369                      DenseMap<Value *, Value *> &ChosenPairs,
00370                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
00371                      DenseSet<ValuePair> &LoadMoveSetPairs,
00372                      Instruction *I);
00373 
00374     void collectLoadMoveSet(BasicBlock &BB,
00375                      std::vector<Value *> &PairableInsts,
00376                      DenseMap<Value *, Value *> &ChosenPairs,
00377                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
00378                      DenseSet<ValuePair> &LoadMoveSetPairs);
00379 
00380     bool canMoveUsesOfIAfterJ(BasicBlock &BB,
00381                      DenseSet<ValuePair> &LoadMoveSetPairs,
00382                      Instruction *I, Instruction *J);
00383 
00384     void moveUsesOfIAfterJ(BasicBlock &BB,
00385                      DenseSet<ValuePair> &LoadMoveSetPairs,
00386                      Instruction *&InsertionPt,
00387                      Instruction *I, Instruction *J);
00388 
00389     void combineMetadata(Instruction *K, const Instruction *J);
00390 
00391     bool vectorizeBB(BasicBlock &BB) {
00392       if (skipOptnoneFunction(BB))
00393         return false;
00394       if (!DT->isReachableFromEntry(&BB)) {
00395         DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
00396               " in " << BB.getParent()->getName() << "\n");
00397         return false;
00398       }
00399 
00400       DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
00401 
00402       bool changed = false;
00403       // Iterate a sufficient number of times to merge types of size 1 bit,
00404       // then 2 bits, then 4, etc. up to half of the target vector width of the
00405       // target vector register.
00406       unsigned n = 1;
00407       for (unsigned v = 2;
00408            (TTI || v <= Config.VectorBits) &&
00409            (!Config.MaxIter || n <= Config.MaxIter);
00410            v *= 2, ++n) {
00411         DEBUG(dbgs() << "BBV: fusing loop #" << n <<
00412               " for " << BB.getName() << " in " <<
00413               BB.getParent()->getName() << "...\n");
00414         if (vectorizePairs(BB))
00415           changed = true;
00416         else
00417           break;
00418       }
00419 
00420       if (changed && !Pow2LenOnly) {
00421         ++n;
00422         for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
00423           DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
00424                 n << " for " << BB.getName() << " in " <<
00425                 BB.getParent()->getName() << "...\n");
00426           if (!vectorizePairs(BB, true)) break;
00427         }
00428       }
00429 
00430       DEBUG(dbgs() << "BBV: done!\n");
00431       return changed;
00432     }
00433 
00434     bool runOnBasicBlock(BasicBlock &BB) override {
00435       // OptimizeNone check deferred to vectorizeBB().
00436 
00437       AA = &getAnalysis<AliasAnalysis>();
00438       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00439       SE = &getAnalysis<ScalarEvolution>();
00440       DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00441       DL = DLP ? &DLP->getDataLayout() : 0;
00442       TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
00443 
00444       return vectorizeBB(BB);
00445     }
00446 
00447     void getAnalysisUsage(AnalysisUsage &AU) const override {
00448       BasicBlockPass::getAnalysisUsage(AU);
00449       AU.addRequired<AliasAnalysis>();
00450       AU.addRequired<DominatorTreeWrapperPass>();
00451       AU.addRequired<ScalarEvolution>();
00452       AU.addRequired<TargetTransformInfo>();
00453       AU.addPreserved<AliasAnalysis>();
00454       AU.addPreserved<DominatorTreeWrapperPass>();
00455       AU.addPreserved<ScalarEvolution>();
00456       AU.setPreservesCFG();
00457     }
00458 
00459     static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
00460       assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
00461              "Cannot form vector from incompatible scalar types");
00462       Type *STy = ElemTy->getScalarType();
00463 
00464       unsigned numElem;
00465       if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
00466         numElem = VTy->getNumElements();
00467       } else {
00468         numElem = 1;
00469       }
00470 
00471       if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
00472         numElem += VTy->getNumElements();
00473       } else {
00474         numElem += 1;
00475       }
00476 
00477       return VectorType::get(STy, numElem);
00478     }
00479 
00480     static inline void getInstructionTypes(Instruction *I,
00481                                            Type *&T1, Type *&T2) {
00482       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00483         // For stores, it is the value type, not the pointer type that matters
00484         // because the value is what will come from a vector register.
00485   
00486         Value *IVal = SI->getValueOperand();
00487         T1 = IVal->getType();
00488       } else {
00489         T1 = I->getType();
00490       }
00491   
00492       if (CastInst *CI = dyn_cast<CastInst>(I))
00493         T2 = CI->getSrcTy();
00494       else
00495         T2 = T1;
00496 
00497       if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00498         T2 = SI->getCondition()->getType();
00499       } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
00500         T2 = SI->getOperand(0)->getType();
00501       } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
00502         T2 = CI->getOperand(0)->getType();
00503       }
00504     }
00505 
00506     // Returns the weight associated with the provided value. A chain of
00507     // candidate pairs has a length given by the sum of the weights of its
00508     // members (one weight per pair; the weight of each member of the pair
00509     // is assumed to be the same). This length is then compared to the
00510     // chain-length threshold to determine if a given chain is significant
00511     // enough to be vectorized. The length is also used in comparing
00512     // candidate chains where longer chains are considered to be better.
00513     // Note: when this function returns 0, the resulting instructions are
00514     // not actually fused.
00515     inline size_t getDepthFactor(Value *V) {
00516       // InsertElement and ExtractElement have a depth factor of zero. This is
00517       // for two reasons: First, they cannot be usefully fused. Second, because
00518       // the pass generates a lot of these, they can confuse the simple metric
00519       // used to compare the dags in the next iteration. Thus, giving them a
00520       // weight of zero allows the pass to essentially ignore them in
00521       // subsequent iterations when looking for vectorization opportunities
00522       // while still tracking dependency chains that flow through those
00523       // instructions.
00524       if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
00525         return 0;
00526 
00527       // Give a load or store half of the required depth so that load/store
00528       // pairs will vectorize.
00529       if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
00530         return Config.ReqChainDepth/2;
00531 
00532       return 1;
00533     }
00534 
00535     // Returns the cost of the provided instruction using TTI.
00536     // This does not handle loads and stores.
00537     unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
00538                           TargetTransformInfo::OperandValueKind Op1VK = 
00539                               TargetTransformInfo::OK_AnyValue,
00540                           TargetTransformInfo::OperandValueKind Op2VK =
00541                               TargetTransformInfo::OK_AnyValue) {
00542       switch (Opcode) {
00543       default: break;
00544       case Instruction::GetElementPtr:
00545         // We mark this instruction as zero-cost because scalar GEPs are usually
00546         // lowered to the instruction addressing mode. At the moment we don't
00547         // generate vector GEPs.
00548         return 0;
00549       case Instruction::Br:
00550         return TTI->getCFInstrCost(Opcode);
00551       case Instruction::PHI:
00552         return 0;
00553       case Instruction::Add:
00554       case Instruction::FAdd:
00555       case Instruction::Sub:
00556       case Instruction::FSub:
00557       case Instruction::Mul:
00558       case Instruction::FMul:
00559       case Instruction::UDiv:
00560       case Instruction::SDiv:
00561       case Instruction::FDiv:
00562       case Instruction::URem:
00563       case Instruction::SRem:
00564       case Instruction::FRem:
00565       case Instruction::Shl:
00566       case Instruction::LShr:
00567       case Instruction::AShr:
00568       case Instruction::And:
00569       case Instruction::Or:
00570       case Instruction::Xor:
00571         return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
00572       case Instruction::Select:
00573       case Instruction::ICmp:
00574       case Instruction::FCmp:
00575         return TTI->getCmpSelInstrCost(Opcode, T1, T2);
00576       case Instruction::ZExt:
00577       case Instruction::SExt:
00578       case Instruction::FPToUI:
00579       case Instruction::FPToSI:
00580       case Instruction::FPExt:
00581       case Instruction::PtrToInt:
00582       case Instruction::IntToPtr:
00583       case Instruction::SIToFP:
00584       case Instruction::UIToFP:
00585       case Instruction::Trunc:
00586       case Instruction::FPTrunc:
00587       case Instruction::BitCast:
00588       case Instruction::ShuffleVector:
00589         return TTI->getCastInstrCost(Opcode, T1, T2);
00590       }
00591 
00592       return 1;
00593     }
00594 
00595     // This determines the relative offset of two loads or stores, returning
00596     // true if the offset could be determined to be some constant value.
00597     // For example, if OffsetInElmts == 1, then J accesses the memory directly
00598     // after I; if OffsetInElmts == -1 then I accesses the memory
00599     // directly after J.
00600     bool getPairPtrInfo(Instruction *I, Instruction *J,
00601         Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
00602         unsigned &IAddressSpace, unsigned &JAddressSpace,
00603         int64_t &OffsetInElmts, bool ComputeOffset = true) {
00604       OffsetInElmts = 0;
00605       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00606         LoadInst *LJ = cast<LoadInst>(J);
00607         IPtr = LI->getPointerOperand();
00608         JPtr = LJ->getPointerOperand();
00609         IAlignment = LI->getAlignment();
00610         JAlignment = LJ->getAlignment();
00611         IAddressSpace = LI->getPointerAddressSpace();
00612         JAddressSpace = LJ->getPointerAddressSpace();
00613       } else {
00614         StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
00615         IPtr = SI->getPointerOperand();
00616         JPtr = SJ->getPointerOperand();
00617         IAlignment = SI->getAlignment();
00618         JAlignment = SJ->getAlignment();
00619         IAddressSpace = SI->getPointerAddressSpace();
00620         JAddressSpace = SJ->getPointerAddressSpace();
00621       }
00622 
00623       if (!ComputeOffset)
00624         return true;
00625 
00626       const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
00627       const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
00628 
00629       // If this is a trivial offset, then we'll get something like
00630       // 1*sizeof(type). With target data, which we need anyway, this will get
00631       // constant folded into a number.
00632       const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
00633       if (const SCEVConstant *ConstOffSCEV =
00634             dyn_cast<SCEVConstant>(OffsetSCEV)) {
00635         ConstantInt *IntOff = ConstOffSCEV->getValue();
00636         int64_t Offset = IntOff->getSExtValue();
00637 
00638         Type *VTy = IPtr->getType()->getPointerElementType();
00639         int64_t VTyTSS = (int64_t) DL->getTypeStoreSize(VTy);
00640 
00641         Type *VTy2 = JPtr->getType()->getPointerElementType();
00642         if (VTy != VTy2 && Offset < 0) {
00643           int64_t VTy2TSS = (int64_t) DL->getTypeStoreSize(VTy2);
00644           OffsetInElmts = Offset/VTy2TSS;
00645           return (abs64(Offset) % VTy2TSS) == 0;
00646         }
00647 
00648         OffsetInElmts = Offset/VTyTSS;
00649         return (abs64(Offset) % VTyTSS) == 0;
00650       }
00651 
00652       return false;
00653     }
00654 
00655     // Returns true if the provided CallInst represents an intrinsic that can
00656     // be vectorized.
00657     bool isVectorizableIntrinsic(CallInst* I) {
00658       Function *F = I->getCalledFunction();
00659       if (!F) return false;
00660 
00661       Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
00662       if (!IID) return false;
00663 
00664       switch(IID) {
00665       default:
00666         return false;
00667       case Intrinsic::sqrt:
00668       case Intrinsic::powi:
00669       case Intrinsic::sin:
00670       case Intrinsic::cos:
00671       case Intrinsic::log:
00672       case Intrinsic::log2:
00673       case Intrinsic::log10:
00674       case Intrinsic::exp:
00675       case Intrinsic::exp2:
00676       case Intrinsic::pow:
00677         return Config.VectorizeMath;
00678       case Intrinsic::fma:
00679       case Intrinsic::fmuladd:
00680         return Config.VectorizeFMA;
00681       }
00682     }
00683 
00684     bool isPureIEChain(InsertElementInst *IE) {
00685       InsertElementInst *IENext = IE;
00686       do {
00687         if (!isa<UndefValue>(IENext->getOperand(0)) &&
00688             !isa<InsertElementInst>(IENext->getOperand(0))) {
00689           return false;
00690         }
00691       } while ((IENext =
00692                  dyn_cast<InsertElementInst>(IENext->getOperand(0))));
00693 
00694       return true;
00695     }
00696   };
00697 
00698   // This function implements one vectorization iteration on the provided
00699   // basic block. It returns true if the block is changed.
00700   bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
00701     bool ShouldContinue;
00702     BasicBlock::iterator Start = BB.getFirstInsertionPt();
00703 
00704     std::vector<Value *> AllPairableInsts;
00705     DenseMap<Value *, Value *> AllChosenPairs;
00706     DenseSet<ValuePair> AllFixedOrderPairs;
00707     DenseMap<VPPair, unsigned> AllPairConnectionTypes;
00708     DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
00709                                                  AllConnectedPairDeps;
00710 
00711     do {
00712       std::vector<Value *> PairableInsts;
00713       DenseMap<Value *, std::vector<Value *> > CandidatePairs;
00714       DenseSet<ValuePair> FixedOrderPairs;
00715       DenseMap<ValuePair, int> CandidatePairCostSavings;
00716       ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
00717                                          FixedOrderPairs,
00718                                          CandidatePairCostSavings,
00719                                          PairableInsts, NonPow2Len);
00720       if (PairableInsts.empty()) continue;
00721 
00722       // Build the candidate pair set for faster lookups.
00723       DenseSet<ValuePair> CandidatePairsSet;
00724       for (DenseMap<Value *, std::vector<Value *> >::iterator I =
00725            CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
00726         for (std::vector<Value *>::iterator J = I->second.begin(),
00727              JE = I->second.end(); J != JE; ++J)
00728           CandidatePairsSet.insert(ValuePair(I->first, *J));
00729 
00730       // Now we have a map of all of the pairable instructions and we need to
00731       // select the best possible pairing. A good pairing is one such that the
00732       // users of the pair are also paired. This defines a (directed) forest
00733       // over the pairs such that two pairs are connected iff the second pair
00734       // uses the first.
00735 
00736       // Note that it only matters that both members of the second pair use some
00737       // element of the first pair (to allow for splatting).
00738 
00739       DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
00740                                                    ConnectedPairDeps;
00741       DenseMap<VPPair, unsigned> PairConnectionTypes;
00742       computeConnectedPairs(CandidatePairs, CandidatePairsSet,
00743                             PairableInsts, ConnectedPairs, PairConnectionTypes);
00744       if (ConnectedPairs.empty()) continue;
00745 
00746       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
00747            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
00748            I != IE; ++I)
00749         for (std::vector<ValuePair>::iterator J = I->second.begin(),
00750              JE = I->second.end(); J != JE; ++J)
00751           ConnectedPairDeps[*J].push_back(I->first);
00752 
00753       // Build the pairable-instruction dependency map
00754       DenseSet<ValuePair> PairableInstUsers;
00755       buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
00756 
00757       // There is now a graph of the connected pairs. For each variable, pick
00758       // the pairing with the largest dag meeting the depth requirement on at
00759       // least one branch. Then select all pairings that are part of that dag
00760       // and remove them from the list of available pairings and pairable
00761       // variables.
00762 
00763       DenseMap<Value *, Value *> ChosenPairs;
00764       choosePairs(CandidatePairs, CandidatePairsSet,
00765         CandidatePairCostSavings,
00766         PairableInsts, FixedOrderPairs, PairConnectionTypes,
00767         ConnectedPairs, ConnectedPairDeps,
00768         PairableInstUsers, ChosenPairs);
00769 
00770       if (ChosenPairs.empty()) continue;
00771       AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
00772                               PairableInsts.end());
00773       AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
00774 
00775       // Only for the chosen pairs, propagate information on fixed-order pairs,
00776       // pair connections, and their types to the data structures used by the
00777       // pair fusion procedures.
00778       for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
00779            IE = ChosenPairs.end(); I != IE; ++I) {
00780         if (FixedOrderPairs.count(*I))
00781           AllFixedOrderPairs.insert(*I);
00782         else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
00783           AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
00784 
00785         for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
00786              J != IE; ++J) {
00787           DenseMap<VPPair, unsigned>::iterator K =
00788             PairConnectionTypes.find(VPPair(*I, *J));
00789           if (K != PairConnectionTypes.end()) {
00790             AllPairConnectionTypes.insert(*K);
00791           } else {
00792             K = PairConnectionTypes.find(VPPair(*J, *I));
00793             if (K != PairConnectionTypes.end())
00794               AllPairConnectionTypes.insert(*K);
00795           }
00796         }
00797       }
00798 
00799       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
00800            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
00801            I != IE; ++I)
00802         for (std::vector<ValuePair>::iterator J = I->second.begin(),
00803           JE = I->second.end(); J != JE; ++J)
00804           if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
00805             AllConnectedPairs[I->first].push_back(*J);
00806             AllConnectedPairDeps[*J].push_back(I->first);
00807           }
00808     } while (ShouldContinue);
00809 
00810     if (AllChosenPairs.empty()) return false;
00811     NumFusedOps += AllChosenPairs.size();
00812 
00813     // A set of pairs has now been selected. It is now necessary to replace the
00814     // paired instructions with vector instructions. For this procedure each
00815     // operand must be replaced with a vector operand. This vector is formed
00816     // by using build_vector on the old operands. The replaced values are then
00817     // replaced with a vector_extract on the result.  Subsequent optimization
00818     // passes should coalesce the build/extract combinations.
00819 
00820     fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
00821                     AllPairConnectionTypes,
00822                     AllConnectedPairs, AllConnectedPairDeps);
00823 
00824     // It is important to cleanup here so that future iterations of this
00825     // function have less work to do.
00826     (void) SimplifyInstructionsInBlock(&BB, DL, AA->getTargetLibraryInfo());
00827     return true;
00828   }
00829 
00830   // This function returns true if the provided instruction is capable of being
00831   // fused into a vector instruction. This determination is based only on the
00832   // type and other attributes of the instruction.
00833   bool BBVectorize::isInstVectorizable(Instruction *I,
00834                                          bool &IsSimpleLoadStore) {
00835     IsSimpleLoadStore = false;
00836 
00837     if (CallInst *C = dyn_cast<CallInst>(I)) {
00838       if (!isVectorizableIntrinsic(C))
00839         return false;
00840     } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00841       // Vectorize simple loads if possbile:
00842       IsSimpleLoadStore = L->isSimple();
00843       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
00844         return false;
00845     } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
00846       // Vectorize simple stores if possbile:
00847       IsSimpleLoadStore = S->isSimple();
00848       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
00849         return false;
00850     } else if (CastInst *C = dyn_cast<CastInst>(I)) {
00851       // We can vectorize casts, but not casts of pointer types, etc.
00852       if (!Config.VectorizeCasts)
00853         return false;
00854 
00855       Type *SrcTy = C->getSrcTy();
00856       if (!SrcTy->isSingleValueType())
00857         return false;
00858 
00859       Type *DestTy = C->getDestTy();
00860       if (!DestTy->isSingleValueType())
00861         return false;
00862     } else if (isa<SelectInst>(I)) {
00863       if (!Config.VectorizeSelect)
00864         return false;
00865     } else if (isa<CmpInst>(I)) {
00866       if (!Config.VectorizeCmp)
00867         return false;
00868     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
00869       if (!Config.VectorizeGEP)
00870         return false;
00871 
00872       // Currently, vector GEPs exist only with one index.
00873       if (G->getNumIndices() != 1)
00874         return false;
00875     } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
00876         isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
00877       return false;
00878     }
00879 
00880     // We can't vectorize memory operations without target data
00881     if (DL == 0 && IsSimpleLoadStore)
00882       return false;
00883 
00884     Type *T1, *T2;
00885     getInstructionTypes(I, T1, T2);
00886 
00887     // Not every type can be vectorized...
00888     if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
00889         !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
00890       return false;
00891 
00892     if (T1->getScalarSizeInBits() == 1) {
00893       if (!Config.VectorizeBools)
00894         return false;
00895     } else {
00896       if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
00897         return false;
00898     }
00899 
00900     if (T2->getScalarSizeInBits() == 1) {
00901       if (!Config.VectorizeBools)
00902         return false;
00903     } else {
00904       if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
00905         return false;
00906     }
00907 
00908     if (!Config.VectorizeFloats
00909         && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
00910       return false;
00911 
00912     // Don't vectorize target-specific types.
00913     if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
00914       return false;
00915     if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
00916       return false;
00917 
00918     if ((!Config.VectorizePointers || DL == 0) &&
00919         (T1->getScalarType()->isPointerTy() ||
00920          T2->getScalarType()->isPointerTy()))
00921       return false;
00922 
00923     if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
00924                  T2->getPrimitiveSizeInBits() >= Config.VectorBits))
00925       return false;
00926 
00927     return true;
00928   }
00929 
00930   // This function returns true if the two provided instructions are compatible
00931   // (meaning that they can be fused into a vector instruction). This assumes
00932   // that I has already been determined to be vectorizable and that J is not
00933   // in the use dag of I.
00934   bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
00935                        bool IsSimpleLoadStore, bool NonPow2Len,
00936                        int &CostSavings, int &FixedOrder) {
00937     DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
00938                      " <-> " << *J << "\n");
00939 
00940     CostSavings = 0;
00941     FixedOrder = 0;
00942 
00943     // Loads and stores can be merged if they have different alignments,
00944     // but are otherwise the same.
00945     if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
00946                       (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
00947       return false;
00948 
00949     Type *IT1, *IT2, *JT1, *JT2;
00950     getInstructionTypes(I, IT1, IT2);
00951     getInstructionTypes(J, JT1, JT2);
00952     unsigned MaxTypeBits = std::max(
00953       IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
00954       IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
00955     if (!TTI && MaxTypeBits > Config.VectorBits)
00956       return false;
00957 
00958     // FIXME: handle addsub-type operations!
00959 
00960     if (IsSimpleLoadStore) {
00961       Value *IPtr, *JPtr;
00962       unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
00963       int64_t OffsetInElmts = 0;
00964       if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
00965             IAddressSpace, JAddressSpace,
00966             OffsetInElmts) && abs64(OffsetInElmts) == 1) {
00967         FixedOrder = (int) OffsetInElmts;
00968         unsigned BottomAlignment = IAlignment;
00969         if (OffsetInElmts < 0) BottomAlignment = JAlignment;
00970 
00971         Type *aTypeI = isa<StoreInst>(I) ?
00972           cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
00973         Type *aTypeJ = isa<StoreInst>(J) ?
00974           cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
00975         Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
00976 
00977         if (Config.AlignedOnly) {
00978           // An aligned load or store is possible only if the instruction
00979           // with the lower offset has an alignment suitable for the
00980           // vector type.
00981 
00982           unsigned VecAlignment = DL->getPrefTypeAlignment(VType);
00983           if (BottomAlignment < VecAlignment)
00984             return false;
00985         }
00986 
00987         if (TTI) {
00988           unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
00989                                                 IAlignment, IAddressSpace);
00990           unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
00991                                                 JAlignment, JAddressSpace);
00992           unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
00993                                                 BottomAlignment,
00994                                                 IAddressSpace);
00995 
00996           ICost += TTI->getAddressComputationCost(aTypeI);
00997           JCost += TTI->getAddressComputationCost(aTypeJ);
00998           VCost += TTI->getAddressComputationCost(VType);
00999 
01000           if (VCost > ICost + JCost)
01001             return false;
01002 
01003           // We don't want to fuse to a type that will be split, even
01004           // if the two input types will also be split and there is no other
01005           // associated cost.
01006           unsigned VParts = TTI->getNumberOfParts(VType);
01007           if (VParts > 1)
01008             return false;
01009           else if (!VParts && VCost == ICost + JCost)
01010             return false;
01011 
01012           CostSavings = ICost + JCost - VCost;
01013         }
01014       } else {
01015         return false;
01016       }
01017     } else if (TTI) {
01018       unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
01019       unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
01020       Type *VT1 = getVecTypeForPair(IT1, JT1),
01021            *VT2 = getVecTypeForPair(IT2, JT2);
01022       TargetTransformInfo::OperandValueKind Op1VK =
01023           TargetTransformInfo::OK_AnyValue;
01024       TargetTransformInfo::OperandValueKind Op2VK =
01025           TargetTransformInfo::OK_AnyValue;
01026 
01027       // On some targets (example X86) the cost of a vector shift may vary
01028       // depending on whether the second operand is a Uniform or
01029       // NonUniform Constant.
01030       switch (I->getOpcode()) {
01031       default : break;
01032       case Instruction::Shl:
01033       case Instruction::LShr:
01034       case Instruction::AShr:
01035 
01036         // If both I and J are scalar shifts by constant, then the
01037         // merged vector shift count would be either a constant splat value
01038         // or a non-uniform vector of constants.
01039         if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
01040           if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
01041             Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
01042                                TargetTransformInfo::OK_NonUniformConstantValue;
01043         } else {
01044           // Check for a splat of a constant or for a non uniform vector
01045           // of constants.
01046           Value *IOp = I->getOperand(1);
01047           Value *JOp = J->getOperand(1);
01048           if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
01049               (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
01050             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
01051             Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
01052             if (SplatValue != NULL &&
01053                 SplatValue == cast<Constant>(JOp)->getSplatValue())
01054               Op2VK = TargetTransformInfo::OK_UniformConstantValue;
01055           }
01056         }
01057       }
01058 
01059       // Note that this procedure is incorrect for insert and extract element
01060       // instructions (because combining these often results in a shuffle),
01061       // but this cost is ignored (because insert and extract element
01062       // instructions are assigned a zero depth factor and are not really
01063       // fused in general).
01064       unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
01065 
01066       if (VCost > ICost + JCost)
01067         return false;
01068 
01069       // We don't want to fuse to a type that will be split, even
01070       // if the two input types will also be split and there is no other
01071       // associated cost.
01072       unsigned VParts1 = TTI->getNumberOfParts(VT1),
01073                VParts2 = TTI->getNumberOfParts(VT2);
01074       if (VParts1 > 1 || VParts2 > 1)
01075         return false;
01076       else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
01077         return false;
01078 
01079       CostSavings = ICost + JCost - VCost;
01080     }
01081 
01082     // The powi intrinsic is special because only the first argument is
01083     // vectorized, the second arguments must be equal.
01084     CallInst *CI = dyn_cast<CallInst>(I);
01085     Function *FI;
01086     if (CI && (FI = CI->getCalledFunction())) {
01087       Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
01088       if (IID == Intrinsic::powi) {
01089         Value *A1I = CI->getArgOperand(1),
01090               *A1J = cast<CallInst>(J)->getArgOperand(1);
01091         const SCEV *A1ISCEV = SE->getSCEV(A1I),
01092                    *A1JSCEV = SE->getSCEV(A1J);
01093         return (A1ISCEV == A1JSCEV);
01094       }
01095 
01096       if (IID && TTI) {
01097         SmallVector<Type*, 4> Tys;
01098         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
01099           Tys.push_back(CI->getArgOperand(i)->getType());
01100         unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
01101 
01102         Tys.clear();
01103         CallInst *CJ = cast<CallInst>(J);
01104         for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
01105           Tys.push_back(CJ->getArgOperand(i)->getType());
01106         unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
01107 
01108         Tys.clear();
01109         assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
01110                "Intrinsic argument counts differ");
01111         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
01112           if (IID == Intrinsic::powi && i == 1)
01113             Tys.push_back(CI->getArgOperand(i)->getType());
01114           else
01115             Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
01116                                             CJ->getArgOperand(i)->getType()));
01117         }
01118 
01119         Type *RetTy = getVecTypeForPair(IT1, JT1);
01120         unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
01121 
01122         if (VCost > ICost + JCost)
01123           return false;
01124 
01125         // We don't want to fuse to a type that will be split, even
01126         // if the two input types will also be split and there is no other
01127         // associated cost.
01128         unsigned RetParts = TTI->getNumberOfParts(RetTy);
01129         if (RetParts > 1)
01130           return false;
01131         else if (!RetParts && VCost == ICost + JCost)
01132           return false;
01133 
01134         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
01135           if (!Tys[i]->isVectorTy())
01136             continue;
01137 
01138           unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
01139           if (NumParts > 1)
01140             return false;
01141           else if (!NumParts && VCost == ICost + JCost)
01142             return false;
01143         }
01144 
01145         CostSavings = ICost + JCost - VCost;
01146       }
01147     }
01148 
01149     return true;
01150   }
01151 
01152   // Figure out whether or not J uses I and update the users and write-set
01153   // structures associated with I. Specifically, Users represents the set of
01154   // instructions that depend on I. WriteSet represents the set
01155   // of memory locations that are dependent on I. If UpdateUsers is true,
01156   // and J uses I, then Users is updated to contain J and WriteSet is updated
01157   // to contain any memory locations to which J writes. The function returns
01158   // true if J uses I. By default, alias analysis is used to determine
01159   // whether J reads from memory that overlaps with a location in WriteSet.
01160   // If LoadMoveSet is not null, then it is a previously-computed map
01161   // where the key is the memory-based user instruction and the value is
01162   // the instruction to be compared with I. So, if LoadMoveSet is provided,
01163   // then the alias analysis is not used. This is necessary because this
01164   // function is called during the process of moving instructions during
01165   // vectorization and the results of the alias analysis are not stable during
01166   // that process.
01167   bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
01168                        AliasSetTracker &WriteSet, Instruction *I,
01169                        Instruction *J, bool UpdateUsers,
01170                        DenseSet<ValuePair> *LoadMoveSetPairs) {
01171     bool UsesI = false;
01172 
01173     // This instruction may already be marked as a user due, for example, to
01174     // being a member of a selected pair.
01175     if (Users.count(J))
01176       UsesI = true;
01177 
01178     if (!UsesI)
01179       for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
01180            JU != JE; ++JU) {
01181         Value *V = *JU;
01182         if (I == V || Users.count(V)) {
01183           UsesI = true;
01184           break;
01185         }
01186       }
01187     if (!UsesI && J->mayReadFromMemory()) {
01188       if (LoadMoveSetPairs) {
01189         UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
01190       } else {
01191         for (AliasSetTracker::iterator W = WriteSet.begin(),
01192              WE = WriteSet.end(); W != WE; ++W) {
01193           if (W->aliasesUnknownInst(J, *AA)) {
01194             UsesI = true;
01195             break;
01196           }
01197         }
01198       }
01199     }
01200 
01201     if (UsesI && UpdateUsers) {
01202       if (J->mayWriteToMemory()) WriteSet.add(J);
01203       Users.insert(J);
01204     }
01205 
01206     return UsesI;
01207   }
01208 
01209   // This function iterates over all instruction pairs in the provided
01210   // basic block and collects all candidate pairs for vectorization.
01211   bool BBVectorize::getCandidatePairs(BasicBlock &BB,
01212                        BasicBlock::iterator &Start,
01213                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01214                        DenseSet<ValuePair> &FixedOrderPairs,
01215                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
01216                        std::vector<Value *> &PairableInsts, bool NonPow2Len) {
01217     size_t TotalPairs = 0;
01218     BasicBlock::iterator E = BB.end();
01219     if (Start == E) return false;
01220 
01221     bool ShouldContinue = false, IAfterStart = false;
01222     for (BasicBlock::iterator I = Start++; I != E; ++I) {
01223       if (I == Start) IAfterStart = true;
01224 
01225       bool IsSimpleLoadStore;
01226       if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
01227 
01228       // Look for an instruction with which to pair instruction *I...
01229       DenseSet<Value *> Users;
01230       AliasSetTracker WriteSet(*AA);
01231       if (I->mayWriteToMemory()) WriteSet.add(I);
01232 
01233       bool JAfterStart = IAfterStart;
01234       BasicBlock::iterator J = std::next(I);
01235       for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
01236         if (J == Start) JAfterStart = true;
01237 
01238         // Determine if J uses I, if so, exit the loop.
01239         bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
01240         if (Config.FastDep) {
01241           // Note: For this heuristic to be effective, independent operations
01242           // must tend to be intermixed. This is likely to be true from some
01243           // kinds of grouped loop unrolling (but not the generic LLVM pass),
01244           // but otherwise may require some kind of reordering pass.
01245 
01246           // When using fast dependency analysis,
01247           // stop searching after first use:
01248           if (UsesI) break;
01249         } else {
01250           if (UsesI) continue;
01251         }
01252 
01253         // J does not use I, and comes before the first use of I, so it can be
01254         // merged with I if the instructions are compatible.
01255         int CostSavings, FixedOrder;
01256         if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
01257             CostSavings, FixedOrder)) continue;
01258 
01259         // J is a candidate for merging with I.
01260         if (!PairableInsts.size() ||
01261              PairableInsts[PairableInsts.size()-1] != I) {
01262           PairableInsts.push_back(I);
01263         }
01264 
01265         CandidatePairs[I].push_back(J);
01266         ++TotalPairs;
01267         if (TTI)
01268           CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
01269                                                             CostSavings));
01270 
01271         if (FixedOrder == 1)
01272           FixedOrderPairs.insert(ValuePair(I, J));
01273         else if (FixedOrder == -1)
01274           FixedOrderPairs.insert(ValuePair(J, I));
01275 
01276         // The next call to this function must start after the last instruction
01277         // selected during this invocation.
01278         if (JAfterStart) {
01279           Start = std::next(J);
01280           IAfterStart = JAfterStart = false;
01281         }
01282 
01283         DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
01284                      << *I << " <-> " << *J << " (cost savings: " <<
01285                      CostSavings << ")\n");
01286 
01287         // If we have already found too many pairs, break here and this function
01288         // will be called again starting after the last instruction selected
01289         // during this invocation.
01290         if (PairableInsts.size() >= Config.MaxInsts ||
01291             TotalPairs >= Config.MaxPairs) {
01292           ShouldContinue = true;
01293           break;
01294         }
01295       }
01296 
01297       if (ShouldContinue)
01298         break;
01299     }
01300 
01301     DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
01302            << " instructions with candidate pairs\n");
01303 
01304     return ShouldContinue;
01305   }
01306 
01307   // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
01308   // it looks for pairs such that both members have an input which is an
01309   // output of PI or PJ.
01310   void BBVectorize::computePairsConnectedTo(
01311                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01312                   DenseSet<ValuePair> &CandidatePairsSet,
01313                   std::vector<Value *> &PairableInsts,
01314                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01315                   DenseMap<VPPair, unsigned> &PairConnectionTypes,
01316                   ValuePair P) {
01317     StoreInst *SI, *SJ;
01318 
01319     // For each possible pairing for this variable, look at the uses of
01320     // the first value...
01321     for (Value::user_iterator I = P.first->user_begin(),
01322                               E = P.first->user_end();
01323          I != E; ++I) {
01324       User *UI = *I;
01325       if (isa<LoadInst>(UI)) {
01326         // A pair cannot be connected to a load because the load only takes one
01327         // operand (the address) and it is a scalar even after vectorization.
01328         continue;
01329       } else if ((SI = dyn_cast<StoreInst>(UI)) &&
01330                  P.first == SI->getPointerOperand()) {
01331         // Similarly, a pair cannot be connected to a store through its
01332         // pointer operand.
01333         continue;
01334       }
01335 
01336       // For each use of the first variable, look for uses of the second
01337       // variable...
01338       for (User *UJ : P.second->users()) {
01339         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01340             P.second == SJ->getPointerOperand())
01341           continue;
01342 
01343         // Look for <I, J>:
01344         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01345           VPPair VP(P, ValuePair(UI, UJ));
01346           ConnectedPairs[VP.first].push_back(VP.second);
01347           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
01348         }
01349 
01350         // Look for <J, I>:
01351         if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
01352           VPPair VP(P, ValuePair(UJ, UI));
01353           ConnectedPairs[VP.first].push_back(VP.second);
01354           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
01355         }
01356       }
01357 
01358       if (Config.SplatBreaksChain) continue;
01359       // Look for cases where just the first value in the pair is used by
01360       // both members of another pair (splatting).
01361       for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
01362         User *UJ = *J;
01363         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01364             P.first == SJ->getPointerOperand())
01365           continue;
01366 
01367         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01368           VPPair VP(P, ValuePair(UI, UJ));
01369           ConnectedPairs[VP.first].push_back(VP.second);
01370           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
01371         }
01372       }
01373     }
01374 
01375     if (Config.SplatBreaksChain) return;
01376     // Look for cases where just the second value in the pair is used by
01377     // both members of another pair (splatting).
01378     for (Value::user_iterator I = P.second->user_begin(),
01379                               E = P.second->user_end();
01380          I != E; ++I) {
01381       User *UI = *I;
01382       if (isa<LoadInst>(UI))
01383         continue;
01384       else if ((SI = dyn_cast<StoreInst>(UI)) &&
01385                P.second == SI->getPointerOperand())
01386         continue;
01387 
01388       for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
01389         User *UJ = *J;
01390         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01391             P.second == SJ->getPointerOperand())
01392           continue;
01393 
01394         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01395           VPPair VP(P, ValuePair(UI, UJ));
01396           ConnectedPairs[VP.first].push_back(VP.second);
01397           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
01398         }
01399       }
01400     }
01401   }
01402 
01403   // This function figures out which pairs are connected.  Two pairs are
01404   // connected if some output of the first pair forms an input to both members
01405   // of the second pair.
01406   void BBVectorize::computeConnectedPairs(
01407                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01408                   DenseSet<ValuePair> &CandidatePairsSet,
01409                   std::vector<Value *> &PairableInsts,
01410                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01411                   DenseMap<VPPair, unsigned> &PairConnectionTypes) {
01412     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
01413          PE = PairableInsts.end(); PI != PE; ++PI) {
01414       DenseMap<Value *, std::vector<Value *> >::iterator PP =
01415         CandidatePairs.find(*PI);
01416       if (PP == CandidatePairs.end())
01417         continue;
01418 
01419       for (std::vector<Value *>::iterator P = PP->second.begin(),
01420            E = PP->second.end(); P != E; ++P)
01421         computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
01422                                 PairableInsts, ConnectedPairs,
01423                                 PairConnectionTypes, ValuePair(*PI, *P));
01424     }
01425 
01426     DEBUG(size_t TotalPairs = 0;
01427           for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
01428                ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
01429             TotalPairs += I->second.size();
01430           dbgs() << "BBV: found " << TotalPairs
01431                  << " pair connections.\n");
01432   }
01433 
01434   // This function builds a set of use tuples such that <A, B> is in the set
01435   // if B is in the use dag of A. If B is in the use dag of A, then B
01436   // depends on the output of A.
01437   void BBVectorize::buildDepMap(
01438                       BasicBlock &BB,
01439                       DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01440                       std::vector<Value *> &PairableInsts,
01441                       DenseSet<ValuePair> &PairableInstUsers) {
01442     DenseSet<Value *> IsInPair;
01443     for (DenseMap<Value *, std::vector<Value *> >::iterator C =
01444          CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
01445       IsInPair.insert(C->first);
01446       IsInPair.insert(C->second.begin(), C->second.end());
01447     }
01448 
01449     // Iterate through the basic block, recording all users of each
01450     // pairable instruction.
01451 
01452     BasicBlock::iterator E = BB.end(), EL =
01453       BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
01454     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
01455       if (IsInPair.find(I) == IsInPair.end()) continue;
01456 
01457       DenseSet<Value *> Users;
01458       AliasSetTracker WriteSet(*AA);
01459       if (I->mayWriteToMemory()) WriteSet.add(I);
01460 
01461       for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
01462         (void) trackUsesOfI(Users, WriteSet, I, J);
01463 
01464         if (J == EL)
01465           break;
01466       }
01467 
01468       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
01469            U != E; ++U) {
01470         if (IsInPair.find(*U) == IsInPair.end()) continue;
01471         PairableInstUsers.insert(ValuePair(I, *U));
01472       }
01473 
01474       if (I == EL)
01475         break;
01476     }
01477   }
01478 
01479   // Returns true if an input to pair P is an output of pair Q and also an
01480   // input of pair Q is an output of pair P. If this is the case, then these
01481   // two pairs cannot be simultaneously fused.
01482   bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
01483              DenseSet<ValuePair> &PairableInstUsers,
01484              DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
01485              DenseSet<VPPair> *PairableInstUserPairSet) {
01486     // Two pairs are in conflict if they are mutual Users of eachother.
01487     bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
01488                   PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
01489                   PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
01490                   PairableInstUsers.count(ValuePair(P.second, Q.second));
01491     bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
01492                   PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
01493                   PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
01494                   PairableInstUsers.count(ValuePair(Q.second, P.second));
01495     if (PairableInstUserMap) {
01496       // FIXME: The expensive part of the cycle check is not so much the cycle
01497       // check itself but this edge insertion procedure. This needs some
01498       // profiling and probably a different data structure.
01499       if (PUsesQ) {
01500         if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
01501           (*PairableInstUserMap)[Q].push_back(P);
01502       }
01503       if (QUsesP) {
01504         if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
01505           (*PairableInstUserMap)[P].push_back(Q);
01506       }
01507     }
01508 
01509     return (QUsesP && PUsesQ);
01510   }
01511 
01512   // This function walks the use graph of current pairs to see if, starting
01513   // from P, the walk returns to P.
01514   bool BBVectorize::pairWillFormCycle(ValuePair P,
01515              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01516              DenseSet<ValuePair> &CurrentPairs) {
01517     DEBUG(if (DebugCycleCheck)
01518             dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
01519                    << *P.second << "\n");
01520     // A lookup table of visisted pairs is kept because the PairableInstUserMap
01521     // contains non-direct associations.
01522     DenseSet<ValuePair> Visited;
01523     SmallVector<ValuePair, 32> Q;
01524     // General depth-first post-order traversal:
01525     Q.push_back(P);
01526     do {
01527       ValuePair QTop = Q.pop_back_val();
01528       Visited.insert(QTop);
01529 
01530       DEBUG(if (DebugCycleCheck)
01531               dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
01532                      << *QTop.second << "\n");
01533       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01534         PairableInstUserMap.find(QTop);
01535       if (QQ == PairableInstUserMap.end())
01536         continue;
01537 
01538       for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
01539            CE = QQ->second.end(); C != CE; ++C) {
01540         if (*C == P) {
01541           DEBUG(dbgs()
01542                  << "BBV: rejected to prevent non-trivial cycle formation: "
01543                  << QTop.first << " <-> " << C->second << "\n");
01544           return true;
01545         }
01546 
01547         if (CurrentPairs.count(*C) && !Visited.count(*C))
01548           Q.push_back(*C);
01549       }
01550     } while (!Q.empty());
01551 
01552     return false;
01553   }
01554 
01555   // This function builds the initial dag of connected pairs with the
01556   // pair J at the root.
01557   void BBVectorize::buildInitialDAGFor(
01558                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01559                   DenseSet<ValuePair> &CandidatePairsSet,
01560                   std::vector<Value *> &PairableInsts,
01561                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01562                   DenseSet<ValuePair> &PairableInstUsers,
01563                   DenseMap<Value *, Value *> &ChosenPairs,
01564                   DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
01565     // Each of these pairs is viewed as the root node of a DAG. The DAG
01566     // is then walked (depth-first). As this happens, we keep track of
01567     // the pairs that compose the DAG and the maximum depth of the DAG.
01568     SmallVector<ValuePairWithDepth, 32> Q;
01569     // General depth-first post-order traversal:
01570     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
01571     do {
01572       ValuePairWithDepth QTop = Q.back();
01573 
01574       // Push each child onto the queue:
01575       bool MoreChildren = false;
01576       size_t MaxChildDepth = QTop.second;
01577       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01578         ConnectedPairs.find(QTop.first);
01579       if (QQ != ConnectedPairs.end())
01580         for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
01581              ke = QQ->second.end(); k != ke; ++k) {
01582           // Make sure that this child pair is still a candidate:
01583           if (CandidatePairsSet.count(*k)) {
01584             DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
01585             if (C == DAG.end()) {
01586               size_t d = getDepthFactor(k->first);
01587               Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
01588               MoreChildren = true;
01589             } else {
01590               MaxChildDepth = std::max(MaxChildDepth, C->second);
01591             }
01592           }
01593         }
01594 
01595       if (!MoreChildren) {
01596         // Record the current pair as part of the DAG:
01597         DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
01598         Q.pop_back();
01599       }
01600     } while (!Q.empty());
01601   }
01602 
01603   // Given some initial dag, prune it by removing conflicting pairs (pairs
01604   // that cannot be simultaneously chosen for vectorization).
01605   void BBVectorize::pruneDAGFor(
01606               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01607               std::vector<Value *> &PairableInsts,
01608               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01609               DenseSet<ValuePair> &PairableInstUsers,
01610               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01611               DenseSet<VPPair> &PairableInstUserPairSet,
01612               DenseMap<Value *, Value *> &ChosenPairs,
01613               DenseMap<ValuePair, size_t> &DAG,
01614               DenseSet<ValuePair> &PrunedDAG, ValuePair J,
01615               bool UseCycleCheck) {
01616     SmallVector<ValuePairWithDepth, 32> Q;
01617     // General depth-first post-order traversal:
01618     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
01619     do {
01620       ValuePairWithDepth QTop = Q.pop_back_val();
01621       PrunedDAG.insert(QTop.first);
01622 
01623       // Visit each child, pruning as necessary...
01624       SmallVector<ValuePairWithDepth, 8> BestChildren;
01625       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01626         ConnectedPairs.find(QTop.first);
01627       if (QQ == ConnectedPairs.end())
01628         continue;
01629 
01630       for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
01631            KE = QQ->second.end(); K != KE; ++K) {
01632         DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
01633         if (C == DAG.end()) continue;
01634 
01635         // This child is in the DAG, now we need to make sure it is the
01636         // best of any conflicting children. There could be multiple
01637         // conflicting children, so first, determine if we're keeping
01638         // this child, then delete conflicting children as necessary.
01639 
01640         // It is also necessary to guard against pairing-induced
01641         // dependencies. Consider instructions a .. x .. y .. b
01642         // such that (a,b) are to be fused and (x,y) are to be fused
01643         // but a is an input to x and b is an output from y. This
01644         // means that y cannot be moved after b but x must be moved
01645         // after b for (a,b) to be fused. In other words, after
01646         // fusing (a,b) we have y .. a/b .. x where y is an input
01647         // to a/b and x is an output to a/b: x and y can no longer
01648         // be legally fused. To prevent this condition, we must
01649         // make sure that a child pair added to the DAG is not
01650         // both an input and output of an already-selected pair.
01651 
01652         // Pairing-induced dependencies can also form from more complicated
01653         // cycles. The pair vs. pair conflicts are easy to check, and so
01654         // that is done explicitly for "fast rejection", and because for
01655         // child vs. child conflicts, we may prefer to keep the current
01656         // pair in preference to the already-selected child.
01657         DenseSet<ValuePair> CurrentPairs;
01658 
01659         bool CanAdd = true;
01660         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
01661               = BestChildren.begin(), E2 = BestChildren.end();
01662              C2 != E2; ++C2) {
01663           if (C2->first.first == C->first.first ||
01664               C2->first.first == C->first.second ||
01665               C2->first.second == C->first.first ||
01666               C2->first.second == C->first.second ||
01667               pairsConflict(C2->first, C->first, PairableInstUsers,
01668                             UseCycleCheck ? &PairableInstUserMap : 0,
01669                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01670             if (C2->second >= C->second) {
01671               CanAdd = false;
01672               break;
01673             }
01674 
01675             CurrentPairs.insert(C2->first);
01676           }
01677         }
01678         if (!CanAdd) continue;
01679 
01680         // Even worse, this child could conflict with another node already
01681         // selected for the DAG. If that is the case, ignore this child.
01682         for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
01683              E2 = PrunedDAG.end(); T != E2; ++T) {
01684           if (T->first == C->first.first ||
01685               T->first == C->first.second ||
01686               T->second == C->first.first ||
01687               T->second == C->first.second ||
01688               pairsConflict(*T, C->first, PairableInstUsers,
01689                             UseCycleCheck ? &PairableInstUserMap : 0,
01690                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01691             CanAdd = false;
01692             break;
01693           }
01694 
01695           CurrentPairs.insert(*T);
01696         }
01697         if (!CanAdd) continue;
01698 
01699         // And check the queue too...
01700         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
01701              E2 = Q.end(); C2 != E2; ++C2) {
01702           if (C2->first.first == C->first.first ||
01703               C2->first.first == C->first.second ||
01704               C2->first.second == C->first.first ||
01705               C2->first.second == C->first.second ||
01706               pairsConflict(C2->first, C->first, PairableInstUsers,
01707                             UseCycleCheck ? &PairableInstUserMap : 0,
01708                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01709             CanAdd = false;
01710             break;
01711           }
01712 
01713           CurrentPairs.insert(C2->first);
01714         }
01715         if (!CanAdd) continue;
01716 
01717         // Last but not least, check for a conflict with any of the
01718         // already-chosen pairs.
01719         for (DenseMap<Value *, Value *>::iterator C2 =
01720               ChosenPairs.begin(), E2 = ChosenPairs.end();
01721              C2 != E2; ++C2) {
01722           if (pairsConflict(*C2, C->first, PairableInstUsers,
01723                             UseCycleCheck ? &PairableInstUserMap : 0,
01724                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01725             CanAdd = false;
01726             break;
01727           }
01728 
01729           CurrentPairs.insert(*C2);
01730         }
01731         if (!CanAdd) continue;
01732 
01733         // To check for non-trivial cycles formed by the addition of the
01734         // current pair we've formed a list of all relevant pairs, now use a
01735         // graph walk to check for a cycle. We start from the current pair and
01736         // walk the use dag to see if we again reach the current pair. If we
01737         // do, then the current pair is rejected.
01738 
01739         // FIXME: It may be more efficient to use a topological-ordering
01740         // algorithm to improve the cycle check. This should be investigated.
01741         if (UseCycleCheck &&
01742             pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
01743           continue;
01744 
01745         // This child can be added, but we may have chosen it in preference
01746         // to an already-selected child. Check for this here, and if a
01747         // conflict is found, then remove the previously-selected child
01748         // before adding this one in its place.
01749         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
01750               = BestChildren.begin(); C2 != BestChildren.end();) {
01751           if (C2->first.first == C->first.first ||
01752               C2->first.first == C->first.second ||
01753               C2->first.second == C->first.first ||
01754               C2->first.second == C->first.second ||
01755               pairsConflict(C2->first, C->first, PairableInstUsers))
01756             C2 = BestChildren.erase(C2);
01757           else
01758             ++C2;
01759         }
01760 
01761         BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
01762       }
01763 
01764       for (SmallVectorImpl<ValuePairWithDepth>::iterator C
01765             = BestChildren.begin(), E2 = BestChildren.end();
01766            C != E2; ++C) {
01767         size_t DepthF = getDepthFactor(C->first.first);
01768         Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
01769       }
01770     } while (!Q.empty());
01771   }
01772 
01773   // This function finds the best dag of mututally-compatible connected
01774   // pairs, given the choice of root pairs as an iterator range.
01775   void BBVectorize::findBestDAGFor(
01776               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01777               DenseSet<ValuePair> &CandidatePairsSet,
01778               DenseMap<ValuePair, int> &CandidatePairCostSavings,
01779               std::vector<Value *> &PairableInsts,
01780               DenseSet<ValuePair> &FixedOrderPairs,
01781               DenseMap<VPPair, unsigned> &PairConnectionTypes,
01782               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01783               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
01784               DenseSet<ValuePair> &PairableInstUsers,
01785               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01786               DenseSet<VPPair> &PairableInstUserPairSet,
01787               DenseMap<Value *, Value *> &ChosenPairs,
01788               DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
01789               int &BestEffSize, Value *II, std::vector<Value *>&JJ,
01790               bool UseCycleCheck) {
01791     for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
01792          J != JE; ++J) {
01793       ValuePair IJ(II, *J);
01794       if (!CandidatePairsSet.count(IJ))
01795         continue;
01796 
01797       // Before going any further, make sure that this pair does not
01798       // conflict with any already-selected pairs (see comment below
01799       // near the DAG pruning for more details).
01800       DenseSet<ValuePair> ChosenPairSet;
01801       bool DoesConflict = false;
01802       for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
01803            E = ChosenPairs.end(); C != E; ++C) {
01804         if (pairsConflict(*C, IJ, PairableInstUsers,
01805                           UseCycleCheck ? &PairableInstUserMap : 0,
01806                           UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01807           DoesConflict = true;
01808           break;
01809         }
01810 
01811         ChosenPairSet.insert(*C);
01812       }
01813       if (DoesConflict) continue;
01814 
01815       if (UseCycleCheck &&
01816           pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
01817         continue;
01818 
01819       DenseMap<ValuePair, size_t> DAG;
01820       buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
01821                           PairableInsts, ConnectedPairs,
01822                           PairableInstUsers, ChosenPairs, DAG, IJ);
01823 
01824       // Because we'll keep the child with the largest depth, the largest
01825       // depth is still the same in the unpruned DAG.
01826       size_t MaxDepth = DAG.lookup(IJ);
01827 
01828       DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
01829                    << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
01830                    MaxDepth << " and size " << DAG.size() << "\n");
01831 
01832       // At this point the DAG has been constructed, but, may contain
01833       // contradictory children (meaning that different children of
01834       // some dag node may be attempting to fuse the same instruction).
01835       // So now we walk the dag again, in the case of a conflict,
01836       // keep only the child with the largest depth. To break a tie,
01837       // favor the first child.
01838 
01839       DenseSet<ValuePair> PrunedDAG;
01840       pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
01841                    PairableInstUsers, PairableInstUserMap,
01842                    PairableInstUserPairSet,
01843                    ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
01844 
01845       int EffSize = 0;
01846       if (TTI) {
01847         DenseSet<Value *> PrunedDAGInstrs;
01848         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
01849              E = PrunedDAG.end(); S != E; ++S) {
01850           PrunedDAGInstrs.insert(S->first);
01851           PrunedDAGInstrs.insert(S->second);
01852         }
01853 
01854         // The set of pairs that have already contributed to the total cost.
01855         DenseSet<ValuePair> IncomingPairs;
01856 
01857         // If the cost model were perfect, this might not be necessary; but we
01858         // need to make sure that we don't get stuck vectorizing our own
01859         // shuffle chains.
01860         bool HasNontrivialInsts = false;
01861 
01862         // The node weights represent the cost savings associated with
01863         // fusing the pair of instructions.
01864         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
01865              E = PrunedDAG.end(); S != E; ++S) {
01866           if (!isa<ShuffleVectorInst>(S->first) &&
01867               !isa<InsertElementInst>(S->first) &&
01868               !isa<ExtractElementInst>(S->first))
01869             HasNontrivialInsts = true;
01870 
01871           bool FlipOrder = false;
01872 
01873           if (getDepthFactor(S->first)) {
01874             int ESContrib = CandidatePairCostSavings.find(*S)->second;
01875             DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
01876                    << *S->first << " <-> " << *S->second << "} = " <<
01877                    ESContrib << "\n");
01878             EffSize += ESContrib;
01879           }
01880 
01881           // The edge weights contribute in a negative sense: they represent
01882           // the cost of shuffles.
01883           DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
01884             ConnectedPairDeps.find(*S);
01885           if (SS != ConnectedPairDeps.end()) {
01886             unsigned NumDepsDirect = 0, NumDepsSwap = 0;
01887             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
01888                  TE = SS->second.end(); T != TE; ++T) {
01889               VPPair Q(*S, *T);
01890               if (!PrunedDAG.count(Q.second))
01891                 continue;
01892               DenseMap<VPPair, unsigned>::iterator R =
01893                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
01894               assert(R != PairConnectionTypes.end() &&
01895                      "Cannot find pair connection type");
01896               if (R->second == PairConnectionDirect)
01897                 ++NumDepsDirect;
01898               else if (R->second == PairConnectionSwap)
01899                 ++NumDepsSwap;
01900             }
01901 
01902             // If there are more swaps than direct connections, then
01903             // the pair order will be flipped during fusion. So the real
01904             // number of swaps is the minimum number.
01905             FlipOrder = !FixedOrderPairs.count(*S) &&
01906               ((NumDepsSwap > NumDepsDirect) ||
01907                 FixedOrderPairs.count(ValuePair(S->second, S->first)));
01908 
01909             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
01910                  TE = SS->second.end(); T != TE; ++T) {
01911               VPPair Q(*S, *T);
01912               if (!PrunedDAG.count(Q.second))
01913                 continue;
01914               DenseMap<VPPair, unsigned>::iterator R =
01915                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
01916               assert(R != PairConnectionTypes.end() &&
01917                      "Cannot find pair connection type");
01918               Type *Ty1 = Q.second.first->getType(),
01919                    *Ty2 = Q.second.second->getType();
01920               Type *VTy = getVecTypeForPair(Ty1, Ty2);
01921               if ((R->second == PairConnectionDirect && FlipOrder) ||
01922                   (R->second == PairConnectionSwap && !FlipOrder)  ||
01923                   R->second == PairConnectionSplat) {
01924                 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
01925                                                    VTy, VTy);
01926 
01927                 if (VTy->getVectorNumElements() == 2) {
01928                   if (R->second == PairConnectionSplat)
01929                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01930                       TargetTransformInfo::SK_Broadcast, VTy));
01931                   else
01932                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01933                       TargetTransformInfo::SK_Reverse, VTy));
01934                 }
01935 
01936                 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
01937                   *Q.second.first << " <-> " << *Q.second.second <<
01938                     "} -> {" <<
01939                   *S->first << " <-> " << *S->second << "} = " <<
01940                    ESContrib << "\n");
01941                 EffSize -= ESContrib;
01942               }
01943             }
01944           }
01945 
01946           // Compute the cost of outgoing edges. We assume that edges outgoing
01947           // to shuffles, inserts or extracts can be merged, and so contribute
01948           // no additional cost.
01949           if (!S->first->getType()->isVoidTy()) {
01950             Type *Ty1 = S->first->getType(),
01951                  *Ty2 = S->second->getType();
01952             Type *VTy = getVecTypeForPair(Ty1, Ty2);
01953 
01954             bool NeedsExtraction = false;
01955             for (User *U : S->first->users()) {
01956               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
01957                 // Shuffle can be folded if it has no other input
01958                 if (isa<UndefValue>(SI->getOperand(1)))
01959                   continue;
01960               }
01961               if (isa<ExtractElementInst>(U))
01962                 continue;
01963               if (PrunedDAGInstrs.count(U))
01964                 continue;
01965               NeedsExtraction = true;
01966               break;
01967             }
01968 
01969             if (NeedsExtraction) {
01970               int ESContrib;
01971               if (Ty1->isVectorTy()) {
01972                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
01973                                                Ty1, VTy);
01974                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01975                   TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
01976               } else
01977                 ESContrib = (int) TTI->getVectorInstrCost(
01978                                     Instruction::ExtractElement, VTy, 0);
01979 
01980               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
01981                 *S->first << "} = " << ESContrib << "\n");
01982               EffSize -= ESContrib;
01983             }
01984 
01985             NeedsExtraction = false;
01986             for (User *U : S->second->users()) {
01987               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
01988                 // Shuffle can be folded if it has no other input
01989                 if (isa<UndefValue>(SI->getOperand(1)))
01990                   continue;
01991               }
01992               if (isa<ExtractElementInst>(U))
01993                 continue;
01994               if (PrunedDAGInstrs.count(U))
01995                 continue;
01996               NeedsExtraction = true;
01997               break;
01998             }
01999 
02000             if (NeedsExtraction) {
02001               int ESContrib;
02002               if (Ty2->isVectorTy()) {
02003                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02004                                                Ty2, VTy);
02005                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
02006                   TargetTransformInfo::SK_ExtractSubvector, VTy,
02007                   Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
02008               } else
02009                 ESContrib = (int) TTI->getVectorInstrCost(
02010                                     Instruction::ExtractElement, VTy, 1);
02011               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
02012                 *S->second << "} = " << ESContrib << "\n");
02013               EffSize -= ESContrib;
02014             }
02015           }
02016 
02017           // Compute the cost of incoming edges.
02018           if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
02019             Instruction *S1 = cast<Instruction>(S->first),
02020                         *S2 = cast<Instruction>(S->second);
02021             for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
02022               Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
02023 
02024               // Combining constants into vector constants (or small vector
02025               // constants into larger ones are assumed free).
02026               if (isa<Constant>(O1) && isa<Constant>(O2))
02027                 continue;
02028 
02029               if (FlipOrder)
02030                 std::swap(O1, O2);
02031 
02032               ValuePair VP  = ValuePair(O1, O2);
02033               ValuePair VPR = ValuePair(O2, O1);
02034 
02035               // Internal edges are not handled here.
02036               if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
02037                 continue;
02038 
02039               Type *Ty1 = O1->getType(),
02040                    *Ty2 = O2->getType();
02041               Type *VTy = getVecTypeForPair(Ty1, Ty2);
02042 
02043               // Combining vector operations of the same type is also assumed
02044               // folded with other operations.
02045               if (Ty1 == Ty2) {
02046                 // If both are insert elements, then both can be widened.
02047                 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
02048                                   *IEO2 = dyn_cast<InsertElementInst>(O2);
02049                 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
02050                   continue;
02051                 // If both are extract elements, and both have the same input
02052                 // type, then they can be replaced with a shuffle
02053                 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
02054                                    *EIO2 = dyn_cast<ExtractElementInst>(O2);
02055                 if (EIO1 && EIO2 &&
02056                     EIO1->getOperand(0)->getType() ==
02057                       EIO2->getOperand(0)->getType())
02058                   continue;
02059                 // If both are a shuffle with equal operand types and only two
02060                 // unqiue operands, then they can be replaced with a single
02061                 // shuffle
02062                 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
02063                                   *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
02064                 if (SIO1 && SIO2 &&
02065                     SIO1->getOperand(0)->getType() ==
02066                       SIO2->getOperand(0)->getType()) {
02067                   SmallSet<Value *, 4> SIOps;
02068                   SIOps.insert(SIO1->getOperand(0));
02069                   SIOps.insert(SIO1->getOperand(1));
02070                   SIOps.insert(SIO2->getOperand(0));
02071                   SIOps.insert(SIO2->getOperand(1));
02072                   if (SIOps.size() <= 2)
02073                     continue;
02074                 }
02075               }
02076 
02077               int ESContrib;
02078               // This pair has already been formed.
02079               if (IncomingPairs.count(VP)) {
02080                 continue;
02081               } else if (IncomingPairs.count(VPR)) {
02082                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02083                                                VTy, VTy);
02084 
02085                 if (VTy->getVectorNumElements() == 2)
02086                   ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
02087                     TargetTransformInfo::SK_Reverse, VTy));
02088               } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
02089                 ESContrib = (int) TTI->getVectorInstrCost(
02090                                     Instruction::InsertElement, VTy, 0);
02091                 ESContrib += (int) TTI->getVectorInstrCost(
02092                                      Instruction::InsertElement, VTy, 1);
02093               } else if (!Ty1->isVectorTy()) {
02094                 // O1 needs to be inserted into a vector of size O2, and then
02095                 // both need to be shuffled together.
02096                 ESContrib = (int) TTI->getVectorInstrCost(
02097                                     Instruction::InsertElement, Ty2, 0);
02098                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02099                                                 VTy, Ty2);
02100               } else if (!Ty2->isVectorTy()) {
02101                 // O2 needs to be inserted into a vector of size O1, and then
02102                 // both need to be shuffled together.
02103                 ESContrib = (int) TTI->getVectorInstrCost(
02104                                     Instruction::InsertElement, Ty1, 0);
02105                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02106                                                 VTy, Ty1);
02107               } else {
02108                 Type *TyBig = Ty1, *TySmall = Ty2;
02109                 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
02110                   std::swap(TyBig, TySmall);
02111 
02112                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02113                                                VTy, TyBig);
02114                 if (TyBig != TySmall)
02115                   ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02116                                                   TyBig, TySmall);
02117               }
02118 
02119               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
02120                      << *O1 << " <-> " << *O2 << "} = " <<
02121                      ESContrib << "\n");
02122               EffSize -= ESContrib;
02123               IncomingPairs.insert(VP);
02124             }
02125           }
02126         }
02127 
02128         if (!HasNontrivialInsts) {
02129           DEBUG(if (DebugPairSelection) dbgs() <<
02130                 "\tNo non-trivial instructions in DAG;"
02131                 " override to zero effective size\n");
02132           EffSize = 0;
02133         }
02134       } else {
02135         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
02136              E = PrunedDAG.end(); S != E; ++S)
02137           EffSize += (int) getDepthFactor(S->first);
02138       }
02139 
02140       DEBUG(if (DebugPairSelection)
02141              dbgs() << "BBV: found pruned DAG for pair {"
02142              << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
02143              MaxDepth << " and size " << PrunedDAG.size() <<
02144             " (effective size: " << EffSize << ")\n");
02145       if (((TTI && !UseChainDepthWithTI) ||
02146             MaxDepth >= Config.ReqChainDepth) &&
02147           EffSize > 0 && EffSize > BestEffSize) {
02148         BestMaxDepth = MaxDepth;
02149         BestEffSize = EffSize;
02150         BestDAG = PrunedDAG;
02151       }
02152     }
02153   }
02154 
02155   // Given the list of candidate pairs, this function selects those
02156   // that will be fused into vector instructions.
02157   void BBVectorize::choosePairs(
02158                 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
02159                 DenseSet<ValuePair> &CandidatePairsSet,
02160                 DenseMap<ValuePair, int> &CandidatePairCostSavings,
02161                 std::vector<Value *> &PairableInsts,
02162                 DenseSet<ValuePair> &FixedOrderPairs,
02163                 DenseMap<VPPair, unsigned> &PairConnectionTypes,
02164                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
02165                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
02166                 DenseSet<ValuePair> &PairableInstUsers,
02167                 DenseMap<Value *, Value *>& ChosenPairs) {
02168     bool UseCycleCheck =
02169      CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
02170 
02171     DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
02172     for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
02173          E = CandidatePairsSet.end(); I != E; ++I) {
02174       std::vector<Value *> &JJ = CandidatePairs2[I->second];
02175       if (JJ.empty()) JJ.reserve(32);
02176       JJ.push_back(I->first);
02177     }
02178 
02179     DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
02180     DenseSet<VPPair> PairableInstUserPairSet;
02181     for (std::vector<Value *>::iterator I = PairableInsts.begin(),
02182          E = PairableInsts.end(); I != E; ++I) {
02183       // The number of possible pairings for this variable:
02184       size_t NumChoices = CandidatePairs.lookup(*I).size();
02185       if (!NumChoices) continue;
02186 
02187       std::vector<Value *> &JJ = CandidatePairs[*I];
02188 
02189       // The best pair to choose and its dag:
02190       size_t BestMaxDepth = 0;
02191       int BestEffSize = 0;
02192       DenseSet<ValuePair> BestDAG;
02193       findBestDAGFor(CandidatePairs, CandidatePairsSet,
02194                       CandidatePairCostSavings,
02195                       PairableInsts, FixedOrderPairs, PairConnectionTypes,
02196                       ConnectedPairs, ConnectedPairDeps,
02197                       PairableInstUsers, PairableInstUserMap,
02198                       PairableInstUserPairSet, ChosenPairs,
02199                       BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
02200                       UseCycleCheck);
02201 
02202       if (BestDAG.empty())
02203         continue;
02204 
02205       // A dag has been chosen (or not) at this point. If no dag was
02206       // chosen, then this instruction, I, cannot be paired (and is no longer
02207       // considered).
02208 
02209       DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
02210                    << *cast<Instruction>(*I) << "\n");
02211 
02212       for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
02213            SE2 = BestDAG.end(); S != SE2; ++S) {
02214         // Insert the members of this dag into the list of chosen pairs.
02215         ChosenPairs.insert(ValuePair(S->first, S->second));
02216         DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
02217                *S->second << "\n");
02218 
02219         // Remove all candidate pairs that have values in the chosen dag.
02220         std::vector<Value *> &KK = CandidatePairs[S->first];
02221         for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
02222              K != KE; ++K) {
02223           if (*K == S->second)
02224             continue;
02225 
02226           CandidatePairsSet.erase(ValuePair(S->first, *K));
02227         }
02228 
02229         std::vector<Value *> &LL = CandidatePairs2[S->second];
02230         for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
02231              L != LE; ++L) {
02232           if (*L == S->first)
02233             continue;
02234 
02235           CandidatePairsSet.erase(ValuePair(*L, S->second));
02236         }
02237 
02238         std::vector<Value *> &MM = CandidatePairs[S->second];
02239         for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
02240              M != ME; ++M) {
02241           assert(*M != S->first && "Flipped pair in candidate list?");
02242           CandidatePairsSet.erase(ValuePair(S->second, *M));
02243         }
02244 
02245         std::vector<Value *> &NN = CandidatePairs2[S->first];
02246         for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
02247              N != NE; ++N) {
02248           assert(*N != S->second && "Flipped pair in candidate list?");
02249           CandidatePairsSet.erase(ValuePair(*N, S->first));
02250         }
02251       }
02252     }
02253 
02254     DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
02255   }
02256 
02257   std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
02258                      unsigned n = 0) {
02259     if (!I->hasName())
02260       return "";
02261 
02262     return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
02263              (n > 0 ? "." + utostr(n) : "")).str();
02264   }
02265 
02266   // Returns the value that is to be used as the pointer input to the vector
02267   // instruction that fuses I with J.
02268   Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
02269                      Instruction *I, Instruction *J, unsigned o) {
02270     Value *IPtr, *JPtr;
02271     unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
02272     int64_t OffsetInElmts;
02273 
02274     // Note: the analysis might fail here, that is why the pair order has
02275     // been precomputed (OffsetInElmts must be unused here).
02276     (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
02277                           IAddressSpace, JAddressSpace,
02278                           OffsetInElmts, false);
02279 
02280     // The pointer value is taken to be the one with the lowest offset.
02281     Value *VPtr = IPtr;
02282 
02283     Type *ArgTypeI = IPtr->getType()->getPointerElementType();
02284     Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
02285     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02286     Type *VArgPtrType
02287       = PointerType::get(VArgType,
02288                          IPtr->getType()->getPointerAddressSpace());
02289     return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
02290                         /* insert before */ I);
02291   }
02292 
02293   void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
02294                      unsigned MaskOffset, unsigned NumInElem,
02295                      unsigned NumInElem1, unsigned IdxOffset,
02296                      std::vector<Constant*> &Mask) {
02297     unsigned NumElem1 = J->getType()->getVectorNumElements();
02298     for (unsigned v = 0; v < NumElem1; ++v) {
02299       int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
02300       if (m < 0) {
02301         Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
02302       } else {
02303         unsigned mm = m + (int) IdxOffset;
02304         if (m >= (int) NumInElem1)
02305           mm += (int) NumInElem;
02306 
02307         Mask[v+MaskOffset] =
02308           ConstantInt::get(Type::getInt32Ty(Context), mm);
02309       }
02310     }
02311   }
02312 
02313   // Returns the value that is to be used as the vector-shuffle mask to the
02314   // vector instruction that fuses I with J.
02315   Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
02316                      Instruction *I, Instruction *J) {
02317     // This is the shuffle mask. We need to append the second
02318     // mask to the first, and the numbers need to be adjusted.
02319 
02320     Type *ArgTypeI = I->getType();
02321     Type *ArgTypeJ = J->getType();
02322     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02323 
02324     unsigned NumElemI = ArgTypeI->getVectorNumElements();
02325 
02326     // Get the total number of elements in the fused vector type.
02327     // By definition, this must equal the number of elements in
02328     // the final mask.
02329     unsigned NumElem = VArgType->getVectorNumElements();
02330     std::vector<Constant*> Mask(NumElem);
02331 
02332     Type *OpTypeI = I->getOperand(0)->getType();
02333     unsigned NumInElemI = OpTypeI->getVectorNumElements();
02334     Type *OpTypeJ = J->getOperand(0)->getType();
02335     unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
02336 
02337     // The fused vector will be:
02338     // -----------------------------------------------------
02339     // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
02340     // -----------------------------------------------------
02341     // from which we'll extract NumElem total elements (where the first NumElemI
02342     // of them come from the mask in I and the remainder come from the mask
02343     // in J.
02344 
02345     // For the mask from the first pair...
02346     fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
02347                        0,          Mask);
02348 
02349     // For the mask from the second pair...
02350     fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
02351                        NumInElemI, Mask);
02352 
02353     return ConstantVector::get(Mask);
02354   }
02355 
02356   bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
02357                                   Instruction *J, unsigned o, Value *&LOp,
02358                                   unsigned numElemL,
02359                                   Type *ArgTypeL, Type *ArgTypeH,
02360                                   bool IBeforeJ, unsigned IdxOff) {
02361     bool ExpandedIEChain = false;
02362     if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
02363       // If we have a pure insertelement chain, then this can be rewritten
02364       // into a chain that directly builds the larger type.
02365       if (isPureIEChain(LIE)) {
02366         SmallVector<Value *, 8> VectElemts(numElemL,
02367           UndefValue::get(ArgTypeL->getScalarType()));
02368         InsertElementInst *LIENext = LIE;
02369         do {
02370           unsigned Idx =
02371             cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
02372           VectElemts[Idx] = LIENext->getOperand(1);
02373         } while ((LIENext =
02374                    dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
02375 
02376         LIENext = 0;
02377         Value *LIEPrev = UndefValue::get(ArgTypeH);
02378         for (unsigned i = 0; i < numElemL; ++i) {
02379           if (isa<UndefValue>(VectElemts[i])) continue;
02380           LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
02381                              ConstantInt::get(Type::getInt32Ty(Context),
02382                                               i + IdxOff),
02383                              getReplacementName(IBeforeJ ? I : J,
02384                                                 true, o, i+1));
02385           LIENext->insertBefore(IBeforeJ ? J : I);
02386           LIEPrev = LIENext;
02387         }
02388 
02389         LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
02390         ExpandedIEChain = true;
02391       }
02392     }
02393 
02394     return ExpandedIEChain;
02395   }
02396 
02397   static unsigned getNumScalarElements(Type *Ty) {
02398     if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
02399       return VecTy->getNumElements();
02400     return 1;
02401   }
02402 
02403   // Returns the value to be used as the specified operand of the vector
02404   // instruction that fuses I with J.
02405   Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
02406                      Instruction *J, unsigned o, bool IBeforeJ) {
02407     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
02408     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
02409 
02410     // Compute the fused vector type for this operand
02411     Type *ArgTypeI = I->getOperand(o)->getType();
02412     Type *ArgTypeJ = J->getOperand(o)->getType();
02413     VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02414 
02415     Instruction *L = I, *H = J;
02416     Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
02417 
02418     unsigned numElemL = getNumScalarElements(ArgTypeL);
02419     unsigned numElemH = getNumScalarElements(ArgTypeH);
02420 
02421     Value *LOp = L->getOperand(o);
02422     Value *HOp = H->getOperand(o);
02423     unsigned numElem = VArgType->getNumElements();
02424 
02425     // First, we check if we can reuse the "original" vector outputs (if these
02426     // exist). We might need a shuffle.
02427     ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
02428     ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
02429     ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
02430     ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
02431 
02432     // FIXME: If we're fusing shuffle instructions, then we can't apply this
02433     // optimization. The input vectors to the shuffle might be a different
02434     // length from the shuffle outputs. Unfortunately, the replacement
02435     // shuffle mask has already been formed, and the mask entries are sensitive
02436     // to the sizes of the inputs.
02437     bool IsSizeChangeShuffle =
02438       isa<ShuffleVectorInst>(L) &&
02439         (LOp->getType() != L->getType() || HOp->getType() != H->getType());
02440 
02441     if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
02442       // We can have at most two unique vector inputs.
02443       bool CanUseInputs = true;
02444       Value *I1, *I2 = 0;
02445       if (LEE) {
02446         I1 = LEE->getOperand(0);
02447       } else {
02448         I1 = LSV->getOperand(0);
02449         I2 = LSV->getOperand(1);
02450         if (I2 == I1 || isa<UndefValue>(I2))
02451           I2 = 0;
02452       }
02453   
02454       if (HEE) {
02455         Value *I3 = HEE->getOperand(0);
02456         if (!I2 && I3 != I1)
02457           I2 = I3;
02458         else if (I3 != I1 && I3 != I2)
02459           CanUseInputs = false;
02460       } else {
02461         Value *I3 = HSV->getOperand(0);
02462         if (!I2 && I3 != I1)
02463           I2 = I3;
02464         else if (I3 != I1 && I3 != I2)
02465           CanUseInputs = false;
02466 
02467         if (CanUseInputs) {
02468           Value *I4 = HSV->getOperand(1);
02469           if (!isa<UndefValue>(I4)) {
02470             if (!I2 && I4 != I1)
02471               I2 = I4;
02472             else if (I4 != I1 && I4 != I2)
02473               CanUseInputs = false;
02474           }
02475         }
02476       }
02477 
02478       if (CanUseInputs) {
02479         unsigned LOpElem =
02480           cast<Instruction>(LOp)->getOperand(0)->getType()
02481             ->getVectorNumElements();
02482 
02483         unsigned HOpElem =
02484           cast<Instruction>(HOp)->getOperand(0)->getType()
02485             ->getVectorNumElements();
02486 
02487         // We have one or two input vectors. We need to map each index of the
02488         // operands to the index of the original vector.
02489         SmallVector<std::pair<int, int>, 8>  II(numElem);
02490         for (unsigned i = 0; i < numElemL; ++i) {
02491           int Idx, INum;
02492           if (LEE) {
02493             Idx =
02494               cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
02495             INum = LEE->getOperand(0) == I1 ? 0 : 1;
02496           } else {
02497             Idx = LSV->getMaskValue(i);
02498             if (Idx < (int) LOpElem) {
02499               INum = LSV->getOperand(0) == I1 ? 0 : 1;
02500             } else {
02501               Idx -= LOpElem;
02502               INum = LSV->getOperand(1) == I1 ? 0 : 1;
02503             }
02504           }
02505 
02506           II[i] = std::pair<int, int>(Idx, INum);
02507         }
02508         for (unsigned i = 0; i < numElemH; ++i) {
02509           int Idx, INum;
02510           if (HEE) {
02511             Idx =
02512               cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
02513             INum = HEE->getOperand(0) == I1 ? 0 : 1;
02514           } else {
02515             Idx = HSV->getMaskValue(i);
02516             if (Idx < (int) HOpElem) {
02517               INum = HSV->getOperand(0) == I1 ? 0 : 1;
02518             } else {
02519               Idx -= HOpElem;
02520               INum = HSV->getOperand(1) == I1 ? 0 : 1;
02521             }
02522           }
02523 
02524           II[i + numElemL] = std::pair<int, int>(Idx, INum);
02525         }
02526 
02527         // We now have an array which tells us from which index of which
02528         // input vector each element of the operand comes.
02529         VectorType *I1T = cast<VectorType>(I1->getType());
02530         unsigned I1Elem = I1T->getNumElements();
02531 
02532         if (!I2) {
02533           // In this case there is only one underlying vector input. Check for
02534           // the trivial case where we can use the input directly.
02535           if (I1Elem == numElem) {
02536             bool ElemInOrder = true;
02537             for (unsigned i = 0; i < numElem; ++i) {
02538               if (II[i].first != (int) i && II[i].first != -1) {
02539                 ElemInOrder = false;
02540                 break;
02541               }
02542             }
02543 
02544             if (ElemInOrder)
02545               return I1;
02546           }
02547 
02548           // A shuffle is needed.
02549           std::vector<Constant *> Mask(numElem);
02550           for (unsigned i = 0; i < numElem; ++i) {
02551             int Idx = II[i].first;
02552             if (Idx == -1)
02553               Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
02554             else
02555               Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02556           }
02557 
02558           Instruction *S =
02559             new ShuffleVectorInst(I1, UndefValue::get(I1T),
02560                                   ConstantVector::get(Mask),
02561                                   getReplacementName(IBeforeJ ? I : J,
02562                                                      true, o));
02563           S->insertBefore(IBeforeJ ? J : I);
02564           return S;
02565         }
02566 
02567         VectorType *I2T = cast<VectorType>(I2->getType());
02568         unsigned I2Elem = I2T->getNumElements();
02569 
02570         // This input comes from two distinct vectors. The first step is to
02571         // make sure that both vectors are the same length. If not, the
02572         // smaller one will need to grow before they can be shuffled together.
02573         if (I1Elem < I2Elem) {
02574           std::vector<Constant *> Mask(I2Elem);
02575           unsigned v = 0;
02576           for (; v < I1Elem; ++v)
02577             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02578           for (; v < I2Elem; ++v)
02579             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02580 
02581           Instruction *NewI1 =
02582             new ShuffleVectorInst(I1, UndefValue::get(I1T),
02583                                   ConstantVector::get(Mask),
02584                                   getReplacementName(IBeforeJ ? I : J,
02585                                                      true, o, 1));
02586           NewI1->insertBefore(IBeforeJ ? J : I);
02587           I1 = NewI1;
02588           I1T = I2T;
02589           I1Elem = I2Elem;
02590         } else if (I1Elem > I2Elem) {
02591           std::vector<Constant *> Mask(I1Elem);
02592           unsigned v = 0;
02593           for (; v < I2Elem; ++v)
02594             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02595           for (; v < I1Elem; ++v)
02596             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02597 
02598           Instruction *NewI2 =
02599             new ShuffleVectorInst(I2, UndefValue::get(I2T),
02600                                   ConstantVector::get(Mask),
02601                                   getReplacementName(IBeforeJ ? I : J,
02602                                                      true, o, 1));
02603           NewI2->insertBefore(IBeforeJ ? J : I);
02604           I2 = NewI2;
02605           I2T = I1T;
02606           I2Elem = I1Elem;
02607         }
02608 
02609         // Now that both I1 and I2 are the same length we can shuffle them
02610         // together (and use the result).
02611         std::vector<Constant *> Mask(numElem);
02612         for (unsigned v = 0; v < numElem; ++v) {
02613           if (II[v].first == -1) {
02614             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02615           } else {
02616             int Idx = II[v].first + II[v].second * I1Elem;
02617             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02618           }
02619         }
02620 
02621         Instruction *NewOp =
02622           new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
02623                                 getReplacementName(IBeforeJ ? I : J, true, o));
02624         NewOp->insertBefore(IBeforeJ ? J : I);
02625         return NewOp;
02626       }
02627     }
02628 
02629     Type *ArgType = ArgTypeL;
02630     if (numElemL < numElemH) {
02631       if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
02632                                          ArgTypeL, VArgType, IBeforeJ, 1)) {
02633         // This is another short-circuit case: we're combining a scalar into
02634         // a vector that is formed by an IE chain. We've just expanded the IE
02635         // chain, now insert the scalar and we're done.
02636 
02637         Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
02638                            getReplacementName(IBeforeJ ? I : J, true, o));
02639         S->insertBefore(IBeforeJ ? J : I);
02640         return S;
02641       } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
02642                                 ArgTypeH, IBeforeJ)) {
02643         // The two vector inputs to the shuffle must be the same length,
02644         // so extend the smaller vector to be the same length as the larger one.
02645         Instruction *NLOp;
02646         if (numElemL > 1) {
02647   
02648           std::vector<Constant *> Mask(numElemH);
02649           unsigned v = 0;
02650           for (; v < numElemL; ++v)
02651             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02652           for (; v < numElemH; ++v)
02653             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02654     
02655           NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
02656                                        ConstantVector::get(Mask),
02657                                        getReplacementName(IBeforeJ ? I : J,
02658                                                           true, o, 1));
02659         } else {
02660           NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
02661                                            getReplacementName(IBeforeJ ? I : J,
02662                                                               true, o, 1));
02663         }
02664   
02665         NLOp->insertBefore(IBeforeJ ? J : I);
02666         LOp = NLOp;
02667       }
02668 
02669       ArgType = ArgTypeH;
02670     } else if (numElemL > numElemH) {
02671       if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
02672                                          ArgTypeH, VArgType, IBeforeJ)) {
02673         Instruction *S =
02674           InsertElementInst::Create(LOp, HOp, 
02675                                     ConstantInt::get(Type::getInt32Ty(Context),
02676                                                      numElemL),
02677                                     getReplacementName(IBeforeJ ? I : J,
02678                                                        true, o));
02679         S->insertBefore(IBeforeJ ? J : I);
02680         return S;
02681       } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
02682                                 ArgTypeL, IBeforeJ)) {
02683         Instruction *NHOp;
02684         if (numElemH > 1) {
02685           std::vector<Constant *> Mask(numElemL);
02686           unsigned v = 0;
02687           for (; v < numElemH; ++v)
02688             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02689           for (; v < numElemL; ++v)
02690             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02691     
02692           NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
02693                                        ConstantVector::get(Mask),
02694                                        getReplacementName(IBeforeJ ? I : J,
02695                                                           true, o, 1));
02696         } else {
02697           NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
02698                                            getReplacementName(IBeforeJ ? I : J,
02699                                                               true, o, 1));
02700         }
02701 
02702         NHOp->insertBefore(IBeforeJ ? J : I);
02703         HOp = NHOp;
02704       }
02705     }
02706 
02707     if (ArgType->isVectorTy()) {
02708       unsigned numElem = VArgType->getVectorNumElements();
02709       std::vector<Constant*> Mask(numElem);
02710       for (unsigned v = 0; v < numElem; ++v) {
02711         unsigned Idx = v;
02712         // If the low vector was expanded, we need to skip the extra
02713         // undefined entries.
02714         if (v >= numElemL && numElemH > numElemL)
02715           Idx += (numElemH - numElemL);
02716         Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02717       }
02718 
02719       Instruction *BV = new ShuffleVectorInst(LOp, HOp,
02720                           ConstantVector::get(Mask),
02721                           getReplacementName(IBeforeJ ? I : J, true, o));
02722       BV->insertBefore(IBeforeJ ? J : I);
02723       return BV;
02724     }
02725 
02726     Instruction *BV1 = InsertElementInst::Create(
02727                                           UndefValue::get(VArgType), LOp, CV0,
02728                                           getReplacementName(IBeforeJ ? I : J,
02729                                                              true, o, 1));
02730     BV1->insertBefore(IBeforeJ ? J : I);
02731     Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
02732                                           getReplacementName(IBeforeJ ? I : J,
02733                                                              true, o, 2));
02734     BV2->insertBefore(IBeforeJ ? J : I);
02735     return BV2;
02736   }
02737 
02738   // This function creates an array of values that will be used as the inputs
02739   // to the vector instruction that fuses I with J.
02740   void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
02741                      Instruction *I, Instruction *J,
02742                      SmallVectorImpl<Value *> &ReplacedOperands,
02743                      bool IBeforeJ) {
02744     unsigned NumOperands = I->getNumOperands();
02745 
02746     for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
02747       // Iterate backward so that we look at the store pointer
02748       // first and know whether or not we need to flip the inputs.
02749 
02750       if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
02751         // This is the pointer for a load/store instruction.
02752         ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
02753         continue;
02754       } else if (isa<CallInst>(I)) {
02755         Function *F = cast<CallInst>(I)->getCalledFunction();
02756         Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
02757         if (o == NumOperands-1) {
02758           BasicBlock &BB = *I->getParent();
02759 
02760           Module *M = BB.getParent()->getParent();
02761           Type *ArgTypeI = I->getType();
02762           Type *ArgTypeJ = J->getType();
02763           Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02764 
02765           ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
02766           continue;
02767         } else if (IID == Intrinsic::powi && o == 1) {
02768           // The second argument of powi is a single integer and we've already
02769           // checked that both arguments are equal. As a result, we just keep
02770           // I's second argument.
02771           ReplacedOperands[o] = I->getOperand(o);
02772           continue;
02773         }
02774       } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
02775         ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
02776         continue;
02777       }
02778 
02779       ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
02780     }
02781   }
02782 
02783   // This function creates two values that represent the outputs of the
02784   // original I and J instructions. These are generally vector shuffles
02785   // or extracts. In many cases, these will end up being unused and, thus,
02786   // eliminated by later passes.
02787   void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
02788                      Instruction *J, Instruction *K,
02789                      Instruction *&InsertionPt,
02790                      Instruction *&K1, Instruction *&K2) {
02791     if (isa<StoreInst>(I)) {
02792       AA->replaceWithNewValue(I, K);
02793       AA->replaceWithNewValue(J, K);
02794     } else {
02795       Type *IType = I->getType();
02796       Type *JType = J->getType();
02797 
02798       VectorType *VType = getVecTypeForPair(IType, JType);
02799       unsigned numElem = VType->getNumElements();
02800 
02801       unsigned numElemI = getNumScalarElements(IType);
02802       unsigned numElemJ = getNumScalarElements(JType);
02803 
02804       if (IType->isVectorTy()) {
02805         std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
02806         for (unsigned v = 0; v < numElemI; ++v) {
02807           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02808           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
02809         }
02810 
02811         K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
02812                                    ConstantVector::get( Mask1),
02813                                    getReplacementName(K, false, 1));
02814       } else {
02815         Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
02816         K1 = ExtractElementInst::Create(K, CV0,
02817                                           getReplacementName(K, false, 1));
02818       }
02819 
02820       if (JType->isVectorTy()) {
02821         std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
02822         for (unsigned v = 0; v < numElemJ; ++v) {
02823           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02824           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
02825         }
02826 
02827         K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
02828                                    ConstantVector::get( Mask2),
02829                                    getReplacementName(K, false, 2));
02830       } else {
02831         Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
02832         K2 = ExtractElementInst::Create(K, CV1,
02833                                           getReplacementName(K, false, 2));
02834       }
02835 
02836       K1->insertAfter(K);
02837       K2->insertAfter(K1);
02838       InsertionPt = K2;
02839     }
02840   }
02841 
02842   // Move all uses of the function I (including pairing-induced uses) after J.
02843   bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
02844                      DenseSet<ValuePair> &LoadMoveSetPairs,
02845                      Instruction *I, Instruction *J) {
02846     // Skip to the first instruction past I.
02847     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02848 
02849     DenseSet<Value *> Users;
02850     AliasSetTracker WriteSet(*AA);
02851     if (I->mayWriteToMemory()) WriteSet.add(I);
02852 
02853     for (; cast<Instruction>(L) != J; ++L)
02854       (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
02855 
02856     assert(cast<Instruction>(L) == J &&
02857       "Tracking has not proceeded far enough to check for dependencies");
02858     // If J is now in the use set of I, then trackUsesOfI will return true
02859     // and we have a dependency cycle (and the fusing operation must abort).
02860     return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
02861   }
02862 
02863   // Move all uses of the function I (including pairing-induced uses) after J.
02864   void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
02865                      DenseSet<ValuePair> &LoadMoveSetPairs,
02866                      Instruction *&InsertionPt,
02867                      Instruction *I, Instruction *J) {
02868     // Skip to the first instruction past I.
02869     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02870 
02871     DenseSet<Value *> Users;
02872     AliasSetTracker WriteSet(*AA);
02873     if (I->mayWriteToMemory()) WriteSet.add(I);
02874 
02875     for (; cast<Instruction>(L) != J;) {
02876       if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
02877         // Move this instruction
02878         Instruction *InstToMove = L; ++L;
02879 
02880         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
02881                         " to after " << *InsertionPt << "\n");
02882         InstToMove->removeFromParent();
02883         InstToMove->insertAfter(InsertionPt);
02884         InsertionPt = InstToMove;
02885       } else {
02886         ++L;
02887       }
02888     }
02889   }
02890 
02891   // Collect all load instruction that are in the move set of a given first
02892   // pair member.  These loads depend on the first instruction, I, and so need
02893   // to be moved after J (the second instruction) when the pair is fused.
02894   void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
02895                      DenseMap<Value *, Value *> &ChosenPairs,
02896                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
02897                      DenseSet<ValuePair> &LoadMoveSetPairs,
02898                      Instruction *I) {
02899     // Skip to the first instruction past I.
02900     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02901 
02902     DenseSet<Value *> Users;
02903     AliasSetTracker WriteSet(*AA);
02904     if (I->mayWriteToMemory()) WriteSet.add(I);
02905 
02906     // Note: We cannot end the loop when we reach J because J could be moved
02907     // farther down the use chain by another instruction pairing. Also, J
02908     // could be before I if this is an inverted input.
02909     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
02910       if (trackUsesOfI(Users, WriteSet, I, L)) {
02911         if (L->mayReadFromMemory()) {
02912           LoadMoveSet[L].push_back(I);
02913           LoadMoveSetPairs.insert(ValuePair(L, I));
02914         }
02915       }
02916     }
02917   }
02918 
02919   // In cases where both load/stores and the computation of their pointers
02920   // are chosen for vectorization, we can end up in a situation where the
02921   // aliasing analysis starts returning different query results as the
02922   // process of fusing instruction pairs continues. Because the algorithm
02923   // relies on finding the same use dags here as were found earlier, we'll
02924   // need to precompute the necessary aliasing information here and then
02925   // manually update it during the fusion process.
02926   void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
02927                      std::vector<Value *> &PairableInsts,
02928                      DenseMap<Value *, Value *> &ChosenPairs,
02929                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
02930                      DenseSet<ValuePair> &LoadMoveSetPairs) {
02931     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
02932          PIE = PairableInsts.end(); PI != PIE; ++PI) {
02933       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
02934       if (P == ChosenPairs.end()) continue;
02935 
02936       Instruction *I = cast<Instruction>(P->first);
02937       collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
02938                              LoadMoveSetPairs, I);
02939     }
02940   }
02941 
02942   // When the first instruction in each pair is cloned, it will inherit its
02943   // parent's metadata. This metadata must be combined with that of the other
02944   // instruction in a safe way.
02945   void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
02946     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
02947     K->getAllMetadataOtherThanDebugLoc(Metadata);
02948     for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
02949       unsigned Kind = Metadata[i].first;
02950       MDNode *JMD = J->getMetadata(Kind);
02951       MDNode *KMD = Metadata[i].second;
02952 
02953       switch (Kind) {
02954       default:
02955         K->setMetadata(Kind, 0); // Remove unknown metadata
02956         break;
02957       case LLVMContext::MD_tbaa:
02958         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
02959         break;
02960       case LLVMContext::MD_fpmath:
02961         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
02962         break;
02963       }
02964     }
02965   }
02966 
02967   // This function fuses the chosen instruction pairs into vector instructions,
02968   // taking care preserve any needed scalar outputs and, then, it reorders the
02969   // remaining instructions as needed (users of the first member of the pair
02970   // need to be moved to after the location of the second member of the pair
02971   // because the vector instruction is inserted in the location of the pair's
02972   // second member).
02973   void BBVectorize::fuseChosenPairs(BasicBlock &BB,
02974              std::vector<Value *> &PairableInsts,
02975              DenseMap<Value *, Value *> &ChosenPairs,
02976              DenseSet<ValuePair> &FixedOrderPairs,
02977              DenseMap<VPPair, unsigned> &PairConnectionTypes,
02978              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
02979              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
02980     LLVMContext& Context = BB.getContext();
02981 
02982     // During the vectorization process, the order of the pairs to be fused
02983     // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
02984     // list. After a pair is fused, the flipped pair is removed from the list.
02985     DenseSet<ValuePair> FlippedPairs;
02986     for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
02987          E = ChosenPairs.end(); P != E; ++P)
02988       FlippedPairs.insert(ValuePair(P->second, P->first));
02989     for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
02990          E = FlippedPairs.end(); P != E; ++P)
02991       ChosenPairs.insert(*P);
02992 
02993     DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
02994     DenseSet<ValuePair> LoadMoveSetPairs;
02995     collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
02996                        LoadMoveSet, LoadMoveSetPairs);
02997 
02998     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
02999 
03000     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
03001       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
03002       if (P == ChosenPairs.end()) {
03003         ++PI;
03004         continue;
03005       }
03006 
03007       if (getDepthFactor(P->first) == 0) {
03008         // These instructions are not really fused, but are tracked as though
03009         // they are. Any case in which it would be interesting to fuse them
03010         // will be taken care of by InstCombine.
03011         --NumFusedOps;
03012         ++PI;
03013         continue;
03014       }
03015 
03016       Instruction *I = cast<Instruction>(P->first),
03017         *J = cast<Instruction>(P->second);
03018 
03019       DEBUG(dbgs() << "BBV: fusing: " << *I <<
03020              " <-> " << *J << "\n");
03021 
03022       // Remove the pair and flipped pair from the list.
03023       DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
03024       assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
03025       ChosenPairs.erase(FP);
03026       ChosenPairs.erase(P);
03027 
03028       if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
03029         DEBUG(dbgs() << "BBV: fusion of: " << *I <<
03030                " <-> " << *J <<
03031                " aborted because of non-trivial dependency cycle\n");
03032         --NumFusedOps;
03033         ++PI;
03034         continue;
03035       }
03036 
03037       // If the pair must have the other order, then flip it.
03038       bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
03039       if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
03040         // This pair does not have a fixed order, and so we might want to
03041         // flip it if that will yield fewer shuffles. We count the number
03042         // of dependencies connected via swaps, and those directly connected,
03043         // and flip the order if the number of swaps is greater.
03044         bool OrigOrder = true;
03045         DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
03046           ConnectedPairDeps.find(ValuePair(I, J));
03047         if (IJ == ConnectedPairDeps.end()) {
03048           IJ = ConnectedPairDeps.find(ValuePair(J, I));
03049           OrigOrder = false;
03050         }
03051 
03052         if (IJ != ConnectedPairDeps.end()) {
03053           unsigned NumDepsDirect = 0, NumDepsSwap = 0;
03054           for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
03055                TE = IJ->second.end(); T != TE; ++T) {
03056             VPPair Q(IJ->first, *T);
03057             DenseMap<VPPair, unsigned>::iterator R =
03058               PairConnectionTypes.find(VPPair(Q.second, Q.first));
03059             assert(R != PairConnectionTypes.end() &&
03060                    "Cannot find pair connection type");
03061             if (R->second == PairConnectionDirect)
03062               ++NumDepsDirect;
03063             else if (R->second == PairConnectionSwap)
03064               ++NumDepsSwap;
03065           }
03066 
03067           if (!OrigOrder)
03068             std::swap(NumDepsDirect, NumDepsSwap);
03069 
03070           if (NumDepsSwap > NumDepsDirect) {
03071             FlipPairOrder = true;
03072             DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
03073                             " <-> " << *J << "\n");
03074           }
03075         }
03076       }
03077 
03078       Instruction *L = I, *H = J;
03079       if (FlipPairOrder)
03080         std::swap(H, L);
03081 
03082       // If the pair being fused uses the opposite order from that in the pair
03083       // connection map, then we need to flip the types.
03084       DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
03085         ConnectedPairs.find(ValuePair(H, L));
03086       if (HL != ConnectedPairs.end())
03087         for (std::vector<ValuePair>::iterator T = HL->second.begin(),
03088              TE = HL->second.end(); T != TE; ++T) {
03089           VPPair Q(HL->first, *T);
03090           DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
03091           assert(R != PairConnectionTypes.end() &&
03092                  "Cannot find pair connection type");
03093           if (R->second == PairConnectionDirect)
03094             R->second = PairConnectionSwap;
03095           else if (R->second == PairConnectionSwap)
03096             R->second = PairConnectionDirect;
03097         }
03098 
03099       bool LBeforeH = !FlipPairOrder;
03100       unsigned NumOperands = I->getNumOperands();
03101       SmallVector<Value *, 3> ReplacedOperands(NumOperands);
03102       getReplacementInputsForPair(Context, L, H, ReplacedOperands,
03103                                   LBeforeH);
03104 
03105       // Make a copy of the original operation, change its type to the vector
03106       // type and replace its operands with the vector operands.
03107       Instruction *K = L->clone();
03108       if (L->hasName())
03109         K->takeName(L);
03110       else if (H->hasName())
03111         K->takeName(H);
03112 
03113       if (!isa<StoreInst>(K))
03114         K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
03115 
03116       combineMetadata(K, H);
03117       K->intersectOptionalDataWith(H);
03118 
03119       for (unsigned o = 0; o < NumOperands; ++o)
03120         K->setOperand(o, ReplacedOperands[o]);
03121 
03122       K->insertAfter(J);
03123 
03124       // Instruction insertion point:
03125       Instruction *InsertionPt = K;
03126       Instruction *K1 = 0, *K2 = 0;
03127       replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
03128 
03129       // The use dag of the first original instruction must be moved to after
03130       // the location of the second instruction. The entire use dag of the
03131       // first instruction is disjoint from the input dag of the second
03132       // (by definition), and so commutes with it.
03133 
03134       moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
03135 
03136       if (!isa<StoreInst>(I)) {
03137         L->replaceAllUsesWith(K1);
03138         H->replaceAllUsesWith(K2);
03139         AA->replaceWithNewValue(L, K1);
03140         AA->replaceWithNewValue(H, K2);
03141       }
03142 
03143       // Instructions that may read from memory may be in the load move set.
03144       // Once an instruction is fused, we no longer need its move set, and so
03145       // the values of the map never need to be updated. However, when a load
03146       // is fused, we need to merge the entries from both instructions in the
03147       // pair in case those instructions were in the move set of some other
03148       // yet-to-be-fused pair. The loads in question are the keys of the map.
03149       if (I->mayReadFromMemory()) {
03150         std::vector<ValuePair> NewSetMembers;
03151         DenseMap<Value *, std::vector<Value *> >::iterator II =
03152           LoadMoveSet.find(I);
03153         if (II != LoadMoveSet.end())
03154           for (std::vector<Value *>::iterator N = II->second.begin(),
03155                NE = II->second.end(); N != NE; ++N)
03156             NewSetMembers.push_back(ValuePair(K, *N));
03157         DenseMap<Value *, std::vector<Value *> >::iterator JJ =
03158           LoadMoveSet.find(J);
03159         if (JJ != LoadMoveSet.end())
03160           for (std::vector<Value *>::iterator N = JJ->second.begin(),
03161                NE = JJ->second.end(); N != NE; ++N)
03162             NewSetMembers.push_back(ValuePair(K, *N));
03163         for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
03164              AE = NewSetMembers.end(); A != AE; ++A) {
03165           LoadMoveSet[A->first].push_back(A->second);
03166           LoadMoveSetPairs.insert(*A);
03167         }
03168       }
03169 
03170       // Before removing I, set the iterator to the next instruction.
03171       PI = std::next(BasicBlock::iterator(I));
03172       if (cast<Instruction>(PI) == J)
03173         ++PI;
03174 
03175       SE->forgetValue(I);
03176       SE->forgetValue(J);
03177       I->eraseFromParent();
03178       J->eraseFromParent();
03179 
03180       DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
03181                                                BB << "\n");
03182     }
03183 
03184     DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
03185   }
03186 }
03187 
03188 char BBVectorize::ID = 0;
03189 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
03190 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
03191 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
03192 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
03193 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
03194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
03195 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
03196 
03197 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
03198   return new BBVectorize(C);
03199 }
03200 
03201 bool
03202 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
03203   BBVectorize BBVectorizer(P, C);
03204   return BBVectorizer.vectorizeBB(BB);
03205 }
03206 
03207 //===----------------------------------------------------------------------===//
03208 VectorizeConfig::VectorizeConfig() {
03209   VectorBits = ::VectorBits;
03210   VectorizeBools = !::NoBools;
03211   VectorizeInts = !::NoInts;
03212   VectorizeFloats = !::NoFloats;
03213   VectorizePointers = !::NoPointers;
03214   VectorizeCasts = !::NoCasts;
03215   VectorizeMath = !::NoMath;
03216   VectorizeFMA = !::NoFMA;
03217   VectorizeSelect = !::NoSelect;
03218   VectorizeCmp = !::NoCmp;
03219   VectorizeGEP = !::NoGEP;
03220   VectorizeMemOps = !::NoMemOps;
03221   AlignedOnly = ::AlignedOnly;
03222   ReqChainDepth= ::ReqChainDepth;
03223   SearchLimit = ::SearchLimit;
03224   MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
03225   SplatBreaksChain = ::SplatBreaksChain;
03226   MaxInsts = ::MaxInsts;
03227   MaxPairs = ::MaxPairs;
03228   MaxIter = ::MaxIter;
03229   Pow2LenOnly = ::Pow2LenOnly;
03230   NoMemOpBoost = ::NoMemOpBoost;
03231   FastDep = ::FastDep;
03232 }