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