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