LLVM API Documentation

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