BBVectorize.cpp revision 8bd6c52396ab6e7955fdcc1bce099b7cba29a308
1//===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a basic-block vectorization pass. The algorithm was
11// inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12// et al. It works by looking for chains of pairable operations and then
13// pairing them.
14//
15//===----------------------------------------------------------------------===//
16
17#define BBV_NAME "bb-vectorize"
18#define DEBUG_TYPE BBV_NAME
19#include "llvm/Transforms/Vectorize.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Analysis/AliasSetTracker.h"
29#include "llvm/Analysis/Dominators.h"
30#include "llvm/Analysis/ScalarEvolution.h"
31#include "llvm/Analysis/ScalarEvolutionExpressions.h"
32#include "llvm/Analysis/TargetTransformInfo.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DerivedTypes.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Type.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/ValueHandle.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include <algorithm>
51#include <map>
52using namespace llvm;
53
54static cl::opt<bool>
55IgnoreTargetInfo("bb-vectorize-ignore-target-info",  cl::init(false),
56  cl::Hidden, cl::desc("Ignore target information"));
57
58static cl::opt<unsigned>
59ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
60  cl::desc("The required chain depth for vectorization"));
61
62static cl::opt<bool>
63UseChainDepthWithTI("bb-vectorize-use-chain-depth",  cl::init(false),
64  cl::Hidden, cl::desc("Use the chain depth requirement with"
65                       " target information"));
66
67static cl::opt<unsigned>
68SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
69  cl::desc("The maximum search distance for instruction pairs"));
70
71static cl::opt<bool>
72SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
73  cl::desc("Replicating one element to a pair breaks the chain"));
74
75static cl::opt<unsigned>
76VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
77  cl::desc("The size of the native vector registers"));
78
79static cl::opt<unsigned>
80MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
81  cl::desc("The maximum number of pairing iterations"));
82
83static cl::opt<bool>
84Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
85  cl::desc("Don't try to form non-2^n-length vectors"));
86
87static cl::opt<unsigned>
88MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
89  cl::desc("The maximum number of pairable instructions per group"));
90
91static cl::opt<unsigned>
92MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
93  cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
94                       " a full cycle check"));
95
96static cl::opt<bool>
97NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
98  cl::desc("Don't try to vectorize boolean (i1) values"));
99
100static cl::opt<bool>
101NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
102  cl::desc("Don't try to vectorize integer values"));
103
104static cl::opt<bool>
105NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
106  cl::desc("Don't try to vectorize floating-point values"));
107
108// FIXME: This should default to false once pointer vector support works.
109static cl::opt<bool>
110NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
111  cl::desc("Don't try to vectorize pointer values"));
112
113static cl::opt<bool>
114NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
115  cl::desc("Don't try to vectorize casting (conversion) operations"));
116
117static cl::opt<bool>
118NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
119  cl::desc("Don't try to vectorize floating-point math intrinsics"));
120
121static cl::opt<bool>
122NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
123  cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
124
125static cl::opt<bool>
126NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
127  cl::desc("Don't try to vectorize select instructions"));
128
129static cl::opt<bool>
130NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
131  cl::desc("Don't try to vectorize comparison instructions"));
132
133static cl::opt<bool>
134NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
135  cl::desc("Don't try to vectorize getelementptr instructions"));
136
137static cl::opt<bool>
138NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
139  cl::desc("Don't try to vectorize loads and stores"));
140
141static cl::opt<bool>
142AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
143  cl::desc("Only generate aligned loads and stores"));
144
145static cl::opt<bool>
146NoMemOpBoost("bb-vectorize-no-mem-op-boost",
147  cl::init(false), cl::Hidden,
148  cl::desc("Don't boost the chain-depth contribution of loads and stores"));
149
150static cl::opt<bool>
151FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
152  cl::desc("Use a fast instruction dependency analysis"));
153
154#ifndef NDEBUG
155static cl::opt<bool>
156DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
157  cl::init(false), cl::Hidden,
158  cl::desc("When debugging is enabled, output information on the"
159           " instruction-examination process"));
160static cl::opt<bool>
161DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
162  cl::init(false), cl::Hidden,
163  cl::desc("When debugging is enabled, output information on the"
164           " candidate-selection process"));
165static cl::opt<bool>
166DebugPairSelection("bb-vectorize-debug-pair-selection",
167  cl::init(false), cl::Hidden,
168  cl::desc("When debugging is enabled, output information on the"
169           " pair-selection process"));
170static cl::opt<bool>
171DebugCycleCheck("bb-vectorize-debug-cycle-check",
172  cl::init(false), cl::Hidden,
173  cl::desc("When debugging is enabled, output information on the"
174           " cycle-checking process"));
175
176static cl::opt<bool>
177PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
178  cl::init(false), cl::Hidden,
179  cl::desc("When debugging is enabled, dump the basic block after"
180           " every pair is fused"));
181#endif
182
183STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
184
185namespace {
186  struct BBVectorize : public BasicBlockPass {
187    static char ID; // Pass identification, replacement for typeid
188
189    const VectorizeConfig Config;
190
191    BBVectorize(const VectorizeConfig &C = VectorizeConfig())
192      : BasicBlockPass(ID), Config(C) {
193      initializeBBVectorizePass(*PassRegistry::getPassRegistry());
194    }
195
196    BBVectorize(Pass *P, const VectorizeConfig &C)
197      : BasicBlockPass(ID), Config(C) {
198      AA = &P->getAnalysis<AliasAnalysis>();
199      DT = &P->getAnalysis<DominatorTree>();
200      SE = &P->getAnalysis<ScalarEvolution>();
201      TD = P->getAnalysisIfAvailable<DataLayout>();
202      TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
203    }
204
205    typedef std::pair<Value *, Value *> ValuePair;
206    typedef std::pair<ValuePair, int> ValuePairWithCost;
207    typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
208    typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
209    typedef std::pair<VPPair, unsigned> VPPairWithType;
210    typedef std::pair<std::multimap<Value *, Value *>::iterator,
211              std::multimap<Value *, Value *>::iterator> VPIteratorPair;
212    typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
213              std::multimap<ValuePair, ValuePair>::iterator>
214                VPPIteratorPair;
215
216    AliasAnalysis *AA;
217    DominatorTree *DT;
218    ScalarEvolution *SE;
219    DataLayout *TD;
220    const TargetTransformInfo *TTI;
221
222    // FIXME: const correct?
223
224    bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
225
226    bool getCandidatePairs(BasicBlock &BB,
227                       BasicBlock::iterator &Start,
228                       std::multimap<Value *, Value *> &CandidatePairs,
229                       DenseSet<ValuePair> &FixedOrderPairs,
230                       DenseMap<ValuePair, int> &CandidatePairCostSavings,
231                       std::vector<Value *> &PairableInsts, bool NonPow2Len);
232
233    // FIXME: The current implementation does not account for pairs that
234    // are connected in multiple ways. For example:
235    //   C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
236    enum PairConnectionType {
237      PairConnectionDirect,
238      PairConnectionSwap,
239      PairConnectionSplat
240    };
241
242    void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
243                       std::vector<Value *> &PairableInsts,
244                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
245                       DenseMap<VPPair, unsigned> &PairConnectionTypes);
246
247    void buildDepMap(BasicBlock &BB,
248                       std::multimap<Value *, Value *> &CandidatePairs,
249                       std::vector<Value *> &PairableInsts,
250                       DenseSet<ValuePair> &PairableInstUsers);
251
252    void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
253                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
254                        std::vector<Value *> &PairableInsts,
255                        DenseSet<ValuePair> &FixedOrderPairs,
256                        DenseMap<VPPair, unsigned> &PairConnectionTypes,
257                        std::multimap<ValuePair, ValuePair> &ConnectedPairs,
258                        std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
259                        DenseSet<ValuePair> &PairableInstUsers,
260                        DenseMap<Value *, Value *>& ChosenPairs);
261
262    void fuseChosenPairs(BasicBlock &BB,
263                     std::vector<Value *> &PairableInsts,
264                     DenseMap<Value *, Value *>& ChosenPairs,
265                     DenseSet<ValuePair> &FixedOrderPairs,
266                     DenseMap<VPPair, unsigned> &PairConnectionTypes,
267                     std::multimap<ValuePair, ValuePair> &ConnectedPairs,
268                     std::multimap<ValuePair, ValuePair> &ConnectedPairDeps);
269
270
271    bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
272
273    bool areInstsCompatible(Instruction *I, Instruction *J,
274                       bool IsSimpleLoadStore, bool NonPow2Len,
275                       int &CostSavings, int &FixedOrder);
276
277    bool trackUsesOfI(DenseSet<Value *> &Users,
278                      AliasSetTracker &WriteSet, Instruction *I,
279                      Instruction *J, bool UpdateUsers = true,
280                      std::multimap<Value *, Value *> *LoadMoveSet = 0);
281
282    void computePairsConnectedTo(
283                      std::multimap<Value *, Value *> &CandidatePairs,
284                      std::vector<Value *> &PairableInsts,
285                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
286                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
287                      ValuePair P);
288
289    bool pairsConflict(ValuePair P, ValuePair Q,
290                 DenseSet<ValuePair> &PairableInstUsers,
291                 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
292
293    bool pairWillFormCycle(ValuePair P,
294                       std::multimap<ValuePair, ValuePair> &PairableInstUsers,
295                       DenseSet<ValuePair> &CurrentPairs);
296
297    void pruneTreeFor(
298                      std::multimap<Value *, Value *> &CandidatePairs,
299                      std::vector<Value *> &PairableInsts,
300                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
301                      DenseSet<ValuePair> &PairableInstUsers,
302                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
303                      DenseMap<Value *, Value *> &ChosenPairs,
304                      DenseMap<ValuePair, size_t> &Tree,
305                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
306                      bool UseCycleCheck);
307
308    void buildInitialTreeFor(
309                      std::multimap<Value *, Value *> &CandidatePairs,
310                      std::vector<Value *> &PairableInsts,
311                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
312                      DenseSet<ValuePair> &PairableInstUsers,
313                      DenseMap<Value *, Value *> &ChosenPairs,
314                      DenseMap<ValuePair, size_t> &Tree, ValuePair J);
315
316    void findBestTreeFor(
317                      std::multimap<Value *, Value *> &CandidatePairs,
318                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
319                      std::vector<Value *> &PairableInsts,
320                      DenseSet<ValuePair> &FixedOrderPairs,
321                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
322                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
323                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
324                      DenseSet<ValuePair> &PairableInstUsers,
325                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
326                      DenseMap<Value *, Value *> &ChosenPairs,
327                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
328                      int &BestEffSize, VPIteratorPair ChoiceRange,
329                      bool UseCycleCheck);
330
331    Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
332                     Instruction *J, unsigned o);
333
334    void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
335                     unsigned MaskOffset, unsigned NumInElem,
336                     unsigned NumInElem1, unsigned IdxOffset,
337                     std::vector<Constant*> &Mask);
338
339    Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
340                     Instruction *J);
341
342    bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
343                       unsigned o, Value *&LOp, unsigned numElemL,
344                       Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
345                       unsigned IdxOff = 0);
346
347    Value *getReplacementInput(LLVMContext& Context, Instruction *I,
348                     Instruction *J, unsigned o, bool IBeforeJ);
349
350    void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
351                     Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
352                     bool IBeforeJ);
353
354    void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
355                     Instruction *J, Instruction *K,
356                     Instruction *&InsertionPt, Instruction *&K1,
357                     Instruction *&K2);
358
359    void collectPairLoadMoveSet(BasicBlock &BB,
360                     DenseMap<Value *, Value *> &ChosenPairs,
361                     std::multimap<Value *, Value *> &LoadMoveSet,
362                     Instruction *I);
363
364    void collectLoadMoveSet(BasicBlock &BB,
365                     std::vector<Value *> &PairableInsts,
366                     DenseMap<Value *, Value *> &ChosenPairs,
367                     std::multimap<Value *, Value *> &LoadMoveSet);
368
369    bool canMoveUsesOfIAfterJ(BasicBlock &BB,
370                     std::multimap<Value *, Value *> &LoadMoveSet,
371                     Instruction *I, Instruction *J);
372
373    void moveUsesOfIAfterJ(BasicBlock &BB,
374                     std::multimap<Value *, Value *> &LoadMoveSet,
375                     Instruction *&InsertionPt,
376                     Instruction *I, Instruction *J);
377
378    void combineMetadata(Instruction *K, const Instruction *J);
379
380    bool vectorizeBB(BasicBlock &BB) {
381      if (!DT->isReachableFromEntry(&BB)) {
382        DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
383              " in " << BB.getParent()->getName() << "\n");
384        return false;
385      }
386
387      DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
388
389      bool changed = false;
390      // Iterate a sufficient number of times to merge types of size 1 bit,
391      // then 2 bits, then 4, etc. up to half of the target vector width of the
392      // target vector register.
393      unsigned n = 1;
394      for (unsigned v = 2;
395           (TTI || v <= Config.VectorBits) &&
396           (!Config.MaxIter || n <= Config.MaxIter);
397           v *= 2, ++n) {
398        DEBUG(dbgs() << "BBV: fusing loop #" << n <<
399              " for " << BB.getName() << " in " <<
400              BB.getParent()->getName() << "...\n");
401        if (vectorizePairs(BB))
402          changed = true;
403        else
404          break;
405      }
406
407      if (changed && !Pow2LenOnly) {
408        ++n;
409        for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
410          DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
411                n << " for " << BB.getName() << " in " <<
412                BB.getParent()->getName() << "...\n");
413          if (!vectorizePairs(BB, true)) break;
414        }
415      }
416
417      DEBUG(dbgs() << "BBV: done!\n");
418      return changed;
419    }
420
421    virtual bool runOnBasicBlock(BasicBlock &BB) {
422      AA = &getAnalysis<AliasAnalysis>();
423      DT = &getAnalysis<DominatorTree>();
424      SE = &getAnalysis<ScalarEvolution>();
425      TD = getAnalysisIfAvailable<DataLayout>();
426      TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
427
428      return vectorizeBB(BB);
429    }
430
431    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
432      BasicBlockPass::getAnalysisUsage(AU);
433      AU.addRequired<AliasAnalysis>();
434      AU.addRequired<DominatorTree>();
435      AU.addRequired<ScalarEvolution>();
436      AU.addRequired<TargetTransformInfo>();
437      AU.addPreserved<AliasAnalysis>();
438      AU.addPreserved<DominatorTree>();
439      AU.addPreserved<ScalarEvolution>();
440      AU.setPreservesCFG();
441    }
442
443    static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
444      assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
445             "Cannot form vector from incompatible scalar types");
446      Type *STy = ElemTy->getScalarType();
447
448      unsigned numElem;
449      if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
450        numElem = VTy->getNumElements();
451      } else {
452        numElem = 1;
453      }
454
455      if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
456        numElem += VTy->getNumElements();
457      } else {
458        numElem += 1;
459      }
460
461      return VectorType::get(STy, numElem);
462    }
463
464    static inline void getInstructionTypes(Instruction *I,
465                                           Type *&T1, Type *&T2) {
466      if (isa<StoreInst>(I)) {
467        // For stores, it is the value type, not the pointer type that matters
468        // because the value is what will come from a vector register.
469
470        Value *IVal = cast<StoreInst>(I)->getValueOperand();
471        T1 = IVal->getType();
472      } else {
473        T1 = I->getType();
474      }
475
476      if (I->isCast())
477        T2 = cast<CastInst>(I)->getSrcTy();
478      else
479        T2 = T1;
480
481      if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
482        T2 = SI->getCondition()->getType();
483      } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
484        T2 = SI->getOperand(0)->getType();
485      } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
486        T2 = CI->getOperand(0)->getType();
487      }
488    }
489
490    // Returns the weight associated with the provided value. A chain of
491    // candidate pairs has a length given by the sum of the weights of its
492    // members (one weight per pair; the weight of each member of the pair
493    // is assumed to be the same). This length is then compared to the
494    // chain-length threshold to determine if a given chain is significant
495    // enough to be vectorized. The length is also used in comparing
496    // candidate chains where longer chains are considered to be better.
497    // Note: when this function returns 0, the resulting instructions are
498    // not actually fused.
499    inline size_t getDepthFactor(Value *V) {
500      // InsertElement and ExtractElement have a depth factor of zero. This is
501      // for two reasons: First, they cannot be usefully fused. Second, because
502      // the pass generates a lot of these, they can confuse the simple metric
503      // used to compare the trees in the next iteration. Thus, giving them a
504      // weight of zero allows the pass to essentially ignore them in
505      // subsequent iterations when looking for vectorization opportunities
506      // while still tracking dependency chains that flow through those
507      // instructions.
508      if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
509        return 0;
510
511      // Give a load or store half of the required depth so that load/store
512      // pairs will vectorize.
513      if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
514        return Config.ReqChainDepth/2;
515
516      return 1;
517    }
518
519    // Returns the cost of the provided instruction using TTI.
520    // This does not handle loads and stores.
521    unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
522      switch (Opcode) {
523      default: break;
524      case Instruction::GetElementPtr:
525        // We mark this instruction as zero-cost because scalar GEPs are usually
526        // lowered to the intruction addressing mode. At the moment we don't
527        // generate vector GEPs.
528        return 0;
529      case Instruction::Br:
530        return TTI->getCFInstrCost(Opcode);
531      case Instruction::PHI:
532        return 0;
533      case Instruction::Add:
534      case Instruction::FAdd:
535      case Instruction::Sub:
536      case Instruction::FSub:
537      case Instruction::Mul:
538      case Instruction::FMul:
539      case Instruction::UDiv:
540      case Instruction::SDiv:
541      case Instruction::FDiv:
542      case Instruction::URem:
543      case Instruction::SRem:
544      case Instruction::FRem:
545      case Instruction::Shl:
546      case Instruction::LShr:
547      case Instruction::AShr:
548      case Instruction::And:
549      case Instruction::Or:
550      case Instruction::Xor:
551        return TTI->getArithmeticInstrCost(Opcode, T1);
552      case Instruction::Select:
553      case Instruction::ICmp:
554      case Instruction::FCmp:
555        return TTI->getCmpSelInstrCost(Opcode, T1, T2);
556      case Instruction::ZExt:
557      case Instruction::SExt:
558      case Instruction::FPToUI:
559      case Instruction::FPToSI:
560      case Instruction::FPExt:
561      case Instruction::PtrToInt:
562      case Instruction::IntToPtr:
563      case Instruction::SIToFP:
564      case Instruction::UIToFP:
565      case Instruction::Trunc:
566      case Instruction::FPTrunc:
567      case Instruction::BitCast:
568      case Instruction::ShuffleVector:
569        return TTI->getCastInstrCost(Opcode, T1, T2);
570      }
571
572      return 1;
573    }
574
575    // This determines the relative offset of two loads or stores, returning
576    // true if the offset could be determined to be some constant value.
577    // For example, if OffsetInElmts == 1, then J accesses the memory directly
578    // after I; if OffsetInElmts == -1 then I accesses the memory
579    // directly after J.
580    bool getPairPtrInfo(Instruction *I, Instruction *J,
581        Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
582        unsigned &IAddressSpace, unsigned &JAddressSpace,
583        int64_t &OffsetInElmts, bool ComputeOffset = true) {
584      OffsetInElmts = 0;
585      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
586        LoadInst *LJ = cast<LoadInst>(J);
587        IPtr = LI->getPointerOperand();
588        JPtr = LJ->getPointerOperand();
589        IAlignment = LI->getAlignment();
590        JAlignment = LJ->getAlignment();
591        IAddressSpace = LI->getPointerAddressSpace();
592        JAddressSpace = LJ->getPointerAddressSpace();
593      } else {
594        StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
595        IPtr = SI->getPointerOperand();
596        JPtr = SJ->getPointerOperand();
597        IAlignment = SI->getAlignment();
598        JAlignment = SJ->getAlignment();
599        IAddressSpace = SI->getPointerAddressSpace();
600        JAddressSpace = SJ->getPointerAddressSpace();
601      }
602
603      if (!ComputeOffset)
604        return true;
605
606      const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
607      const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
608
609      // If this is a trivial offset, then we'll get something like
610      // 1*sizeof(type). With target data, which we need anyway, this will get
611      // constant folded into a number.
612      const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
613      if (const SCEVConstant *ConstOffSCEV =
614            dyn_cast<SCEVConstant>(OffsetSCEV)) {
615        ConstantInt *IntOff = ConstOffSCEV->getValue();
616        int64_t Offset = IntOff->getSExtValue();
617
618        Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
619        int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
620
621        Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
622        if (VTy != VTy2 && Offset < 0) {
623          int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
624          OffsetInElmts = Offset/VTy2TSS;
625          return (abs64(Offset) % VTy2TSS) == 0;
626        }
627
628        OffsetInElmts = Offset/VTyTSS;
629        return (abs64(Offset) % VTyTSS) == 0;
630      }
631
632      return false;
633    }
634
635    // Returns true if the provided CallInst represents an intrinsic that can
636    // be vectorized.
637    bool isVectorizableIntrinsic(CallInst* I) {
638      Function *F = I->getCalledFunction();
639      if (!F) return false;
640
641      Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
642      if (!IID) return false;
643
644      switch(IID) {
645      default:
646        return false;
647      case Intrinsic::sqrt:
648      case Intrinsic::powi:
649      case Intrinsic::sin:
650      case Intrinsic::cos:
651      case Intrinsic::log:
652      case Intrinsic::log2:
653      case Intrinsic::log10:
654      case Intrinsic::exp:
655      case Intrinsic::exp2:
656      case Intrinsic::pow:
657        return Config.VectorizeMath;
658      case Intrinsic::fma:
659      case Intrinsic::fmuladd:
660        return Config.VectorizeFMA;
661      }
662    }
663
664    // Returns true if J is the second element in some pair referenced by
665    // some multimap pair iterator pair.
666    template <typename V>
667    bool isSecondInIteratorPair(V J, std::pair<
668           typename std::multimap<V, V>::iterator,
669           typename std::multimap<V, V>::iterator> PairRange) {
670      for (typename std::multimap<V, V>::iterator K = PairRange.first;
671           K != PairRange.second; ++K)
672        if (K->second == J) return true;
673
674      return false;
675    }
676
677    bool isPureIEChain(InsertElementInst *IE) {
678      InsertElementInst *IENext = IE;
679      do {
680        if (!isa<UndefValue>(IENext->getOperand(0)) &&
681            !isa<InsertElementInst>(IENext->getOperand(0))) {
682          return false;
683        }
684      } while ((IENext =
685                 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
686
687      return true;
688    }
689  };
690
691  // This function implements one vectorization iteration on the provided
692  // basic block. It returns true if the block is changed.
693  bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
694    bool ShouldContinue;
695    BasicBlock::iterator Start = BB.getFirstInsertionPt();
696
697    std::vector<Value *> AllPairableInsts;
698    DenseMap<Value *, Value *> AllChosenPairs;
699    DenseSet<ValuePair> AllFixedOrderPairs;
700    DenseMap<VPPair, unsigned> AllPairConnectionTypes;
701    std::multimap<ValuePair, ValuePair> AllConnectedPairs, AllConnectedPairDeps;
702
703    do {
704      std::vector<Value *> PairableInsts;
705      std::multimap<Value *, Value *> CandidatePairs;
706      DenseSet<ValuePair> FixedOrderPairs;
707      DenseMap<ValuePair, int> CandidatePairCostSavings;
708      ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
709                                         FixedOrderPairs,
710                                         CandidatePairCostSavings,
711                                         PairableInsts, NonPow2Len);
712      if (PairableInsts.empty()) continue;
713
714      // Now we have a map of all of the pairable instructions and we need to
715      // select the best possible pairing. A good pairing is one such that the
716      // users of the pair are also paired. This defines a (directed) forest
717      // over the pairs such that two pairs are connected iff the second pair
718      // uses the first.
719
720      // Note that it only matters that both members of the second pair use some
721      // element of the first pair (to allow for splatting).
722
723      std::multimap<ValuePair, ValuePair> ConnectedPairs, ConnectedPairDeps;
724      DenseMap<VPPair, unsigned> PairConnectionTypes;
725      computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs,
726                            PairConnectionTypes);
727      if (ConnectedPairs.empty()) continue;
728
729      for (std::multimap<ValuePair, ValuePair>::iterator
730           I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
731           I != IE; ++I) {
732        ConnectedPairDeps.insert(VPPair(I->second, I->first));
733      }
734
735      // Build the pairable-instruction dependency map
736      DenseSet<ValuePair> PairableInstUsers;
737      buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
738
739      // There is now a graph of the connected pairs. For each variable, pick
740      // the pairing with the largest tree meeting the depth requirement on at
741      // least one branch. Then select all pairings that are part of that tree
742      // and remove them from the list of available pairings and pairable
743      // variables.
744
745      DenseMap<Value *, Value *> ChosenPairs;
746      choosePairs(CandidatePairs, CandidatePairCostSavings,
747        PairableInsts, FixedOrderPairs, PairConnectionTypes,
748        ConnectedPairs, ConnectedPairDeps,
749        PairableInstUsers, ChosenPairs);
750
751      if (ChosenPairs.empty()) continue;
752      AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
753                              PairableInsts.end());
754      AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
755
756      // Only for the chosen pairs, propagate information on fixed-order pairs,
757      // pair connections, and their types to the data structures used by the
758      // pair fusion procedures.
759      for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
760           IE = ChosenPairs.end(); I != IE; ++I) {
761        if (FixedOrderPairs.count(*I))
762          AllFixedOrderPairs.insert(*I);
763        else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
764          AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
765
766        for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
767             J != IE; ++J) {
768          DenseMap<VPPair, unsigned>::iterator K =
769            PairConnectionTypes.find(VPPair(*I, *J));
770          if (K != PairConnectionTypes.end()) {
771            AllPairConnectionTypes.insert(*K);
772          } else {
773            K = PairConnectionTypes.find(VPPair(*J, *I));
774            if (K != PairConnectionTypes.end())
775              AllPairConnectionTypes.insert(*K);
776          }
777        }
778      }
779
780      for (std::multimap<ValuePair, ValuePair>::iterator
781           I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
782           I != IE; ++I) {
783        if (AllPairConnectionTypes.count(*I)) {
784          AllConnectedPairs.insert(*I);
785          AllConnectedPairDeps.insert(VPPair(I->second, I->first));
786        }
787      }
788    } while (ShouldContinue);
789
790    if (AllChosenPairs.empty()) return false;
791    NumFusedOps += AllChosenPairs.size();
792
793    // A set of pairs has now been selected. It is now necessary to replace the
794    // paired instructions with vector instructions. For this procedure each
795    // operand must be replaced with a vector operand. This vector is formed
796    // by using build_vector on the old operands. The replaced values are then
797    // replaced with a vector_extract on the result.  Subsequent optimization
798    // passes should coalesce the build/extract combinations.
799
800    fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
801                    AllPairConnectionTypes,
802                    AllConnectedPairs, AllConnectedPairDeps);
803
804    // It is important to cleanup here so that future iterations of this
805    // function have less work to do.
806    (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
807    return true;
808  }
809
810  // This function returns true if the provided instruction is capable of being
811  // fused into a vector instruction. This determination is based only on the
812  // type and other attributes of the instruction.
813  bool BBVectorize::isInstVectorizable(Instruction *I,
814                                         bool &IsSimpleLoadStore) {
815    IsSimpleLoadStore = false;
816
817    if (CallInst *C = dyn_cast<CallInst>(I)) {
818      if (!isVectorizableIntrinsic(C))
819        return false;
820    } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
821      // Vectorize simple loads if possbile:
822      IsSimpleLoadStore = L->isSimple();
823      if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
824        return false;
825    } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
826      // Vectorize simple stores if possbile:
827      IsSimpleLoadStore = S->isSimple();
828      if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
829        return false;
830    } else if (CastInst *C = dyn_cast<CastInst>(I)) {
831      // We can vectorize casts, but not casts of pointer types, etc.
832      if (!Config.VectorizeCasts)
833        return false;
834
835      Type *SrcTy = C->getSrcTy();
836      if (!SrcTy->isSingleValueType())
837        return false;
838
839      Type *DestTy = C->getDestTy();
840      if (!DestTy->isSingleValueType())
841        return false;
842    } else if (isa<SelectInst>(I)) {
843      if (!Config.VectorizeSelect)
844        return false;
845    } else if (isa<CmpInst>(I)) {
846      if (!Config.VectorizeCmp)
847        return false;
848    } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
849      if (!Config.VectorizeGEP)
850        return false;
851
852      // Currently, vector GEPs exist only with one index.
853      if (G->getNumIndices() != 1)
854        return false;
855    } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
856        isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
857      return false;
858    }
859
860    // We can't vectorize memory operations without target data
861    if (TD == 0 && IsSimpleLoadStore)
862      return false;
863
864    Type *T1, *T2;
865    getInstructionTypes(I, T1, T2);
866
867    // Not every type can be vectorized...
868    if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
869        !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
870      return false;
871
872    if (T1->getScalarSizeInBits() == 1) {
873      if (!Config.VectorizeBools)
874        return false;
875    } else {
876      if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
877        return false;
878    }
879
880    if (T2->getScalarSizeInBits() == 1) {
881      if (!Config.VectorizeBools)
882        return false;
883    } else {
884      if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
885        return false;
886    }
887
888    if (!Config.VectorizeFloats
889        && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
890      return false;
891
892    // Don't vectorize target-specific types.
893    if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
894      return false;
895    if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
896      return false;
897
898    if ((!Config.VectorizePointers || TD == 0) &&
899        (T1->getScalarType()->isPointerTy() ||
900         T2->getScalarType()->isPointerTy()))
901      return false;
902
903    if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
904                 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
905      return false;
906
907    return true;
908  }
909
910  // This function returns true if the two provided instructions are compatible
911  // (meaning that they can be fused into a vector instruction). This assumes
912  // that I has already been determined to be vectorizable and that J is not
913  // in the use tree of I.
914  bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
915                       bool IsSimpleLoadStore, bool NonPow2Len,
916                       int &CostSavings, int &FixedOrder) {
917    DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
918                     " <-> " << *J << "\n");
919
920    CostSavings = 0;
921    FixedOrder = 0;
922
923    // Loads and stores can be merged if they have different alignments,
924    // but are otherwise the same.
925    if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
926                      (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
927      return false;
928
929    Type *IT1, *IT2, *JT1, *JT2;
930    getInstructionTypes(I, IT1, IT2);
931    getInstructionTypes(J, JT1, JT2);
932    unsigned MaxTypeBits = std::max(
933      IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
934      IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
935    if (!TTI && MaxTypeBits > Config.VectorBits)
936      return false;
937
938    // FIXME: handle addsub-type operations!
939
940    if (IsSimpleLoadStore) {
941      Value *IPtr, *JPtr;
942      unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
943      int64_t OffsetInElmts = 0;
944      if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
945            IAddressSpace, JAddressSpace,
946            OffsetInElmts) && abs64(OffsetInElmts) == 1) {
947        FixedOrder = (int) OffsetInElmts;
948        unsigned BottomAlignment = IAlignment;
949        if (OffsetInElmts < 0) BottomAlignment = JAlignment;
950
951        Type *aTypeI = isa<StoreInst>(I) ?
952          cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
953        Type *aTypeJ = isa<StoreInst>(J) ?
954          cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
955        Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
956
957        if (Config.AlignedOnly) {
958          // An aligned load or store is possible only if the instruction
959          // with the lower offset has an alignment suitable for the
960          // vector type.
961
962          unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
963          if (BottomAlignment < VecAlignment)
964            return false;
965        }
966
967        if (TTI) {
968          unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
969                                                IAlignment, IAddressSpace);
970          unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
971                                                JAlignment, JAddressSpace);
972          unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
973                                                BottomAlignment,
974                                                IAddressSpace);
975          if (VCost > ICost + JCost)
976            return false;
977
978          // We don't want to fuse to a type that will be split, even
979          // if the two input types will also be split and there is no other
980          // associated cost.
981          unsigned VParts = TTI->getNumberOfParts(VType);
982          if (VParts > 1)
983            return false;
984          else if (!VParts && VCost == ICost + JCost)
985            return false;
986
987          CostSavings = ICost + JCost - VCost;
988        }
989      } else {
990        return false;
991      }
992    } else if (TTI) {
993      unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
994      unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
995      Type *VT1 = getVecTypeForPair(IT1, JT1),
996           *VT2 = getVecTypeForPair(IT2, JT2);
997      unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
998
999      if (VCost > ICost + JCost)
1000        return false;
1001
1002      // We don't want to fuse to a type that will be split, even
1003      // if the two input types will also be split and there is no other
1004      // associated cost.
1005      unsigned VParts1 = TTI->getNumberOfParts(VT1),
1006               VParts2 = TTI->getNumberOfParts(VT2);
1007      if (VParts1 > 1 || VParts2 > 1)
1008        return false;
1009      else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1010        return false;
1011
1012      CostSavings = ICost + JCost - VCost;
1013    }
1014
1015    // The powi intrinsic is special because only the first argument is
1016    // vectorized, the second arguments must be equal.
1017    CallInst *CI = dyn_cast<CallInst>(I);
1018    Function *FI;
1019    if (CI && (FI = CI->getCalledFunction())) {
1020      Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1021      if (IID == Intrinsic::powi) {
1022        Value *A1I = CI->getArgOperand(1),
1023              *A1J = cast<CallInst>(J)->getArgOperand(1);
1024        const SCEV *A1ISCEV = SE->getSCEV(A1I),
1025                   *A1JSCEV = SE->getSCEV(A1J);
1026        return (A1ISCEV == A1JSCEV);
1027      }
1028
1029      if (IID && TTI) {
1030        SmallVector<Type*, 4> Tys;
1031        for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1032          Tys.push_back(CI->getArgOperand(i)->getType());
1033        unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1034
1035        Tys.clear();
1036        CallInst *CJ = cast<CallInst>(J);
1037        for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1038          Tys.push_back(CJ->getArgOperand(i)->getType());
1039        unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1040
1041        Tys.clear();
1042        assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1043               "Intrinsic argument counts differ");
1044        for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1045          if (IID == Intrinsic::powi && i == 1)
1046            Tys.push_back(CI->getArgOperand(i)->getType());
1047          else
1048            Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1049                                            CJ->getArgOperand(i)->getType()));
1050        }
1051
1052        Type *RetTy = getVecTypeForPair(IT1, JT1);
1053        unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1054
1055        if (VCost > ICost + JCost)
1056          return false;
1057
1058        // We don't want to fuse to a type that will be split, even
1059        // if the two input types will also be split and there is no other
1060        // associated cost.
1061        unsigned RetParts = TTI->getNumberOfParts(RetTy);
1062        if (RetParts > 1)
1063          return false;
1064        else if (!RetParts && VCost == ICost + JCost)
1065          return false;
1066
1067        for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1068          if (!Tys[i]->isVectorTy())
1069            continue;
1070
1071          unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1072          if (NumParts > 1)
1073            return false;
1074          else if (!NumParts && VCost == ICost + JCost)
1075            return false;
1076        }
1077
1078        CostSavings = ICost + JCost - VCost;
1079      }
1080    }
1081
1082    return true;
1083  }
1084
1085  // Figure out whether or not J uses I and update the users and write-set
1086  // structures associated with I. Specifically, Users represents the set of
1087  // instructions that depend on I. WriteSet represents the set
1088  // of memory locations that are dependent on I. If UpdateUsers is true,
1089  // and J uses I, then Users is updated to contain J and WriteSet is updated
1090  // to contain any memory locations to which J writes. The function returns
1091  // true if J uses I. By default, alias analysis is used to determine
1092  // whether J reads from memory that overlaps with a location in WriteSet.
1093  // If LoadMoveSet is not null, then it is a previously-computed multimap
1094  // where the key is the memory-based user instruction and the value is
1095  // the instruction to be compared with I. So, if LoadMoveSet is provided,
1096  // then the alias analysis is not used. This is necessary because this
1097  // function is called during the process of moving instructions during
1098  // vectorization and the results of the alias analysis are not stable during
1099  // that process.
1100  bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1101                       AliasSetTracker &WriteSet, Instruction *I,
1102                       Instruction *J, bool UpdateUsers,
1103                       std::multimap<Value *, Value *> *LoadMoveSet) {
1104    bool UsesI = false;
1105
1106    // This instruction may already be marked as a user due, for example, to
1107    // being a member of a selected pair.
1108    if (Users.count(J))
1109      UsesI = true;
1110
1111    if (!UsesI)
1112      for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1113           JU != JE; ++JU) {
1114        Value *V = *JU;
1115        if (I == V || Users.count(V)) {
1116          UsesI = true;
1117          break;
1118        }
1119      }
1120    if (!UsesI && J->mayReadFromMemory()) {
1121      if (LoadMoveSet) {
1122        VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
1123        UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
1124      } else {
1125        for (AliasSetTracker::iterator W = WriteSet.begin(),
1126             WE = WriteSet.end(); W != WE; ++W) {
1127          if (W->aliasesUnknownInst(J, *AA)) {
1128            UsesI = true;
1129            break;
1130          }
1131        }
1132      }
1133    }
1134
1135    if (UsesI && UpdateUsers) {
1136      if (J->mayWriteToMemory()) WriteSet.add(J);
1137      Users.insert(J);
1138    }
1139
1140    return UsesI;
1141  }
1142
1143  // This function iterates over all instruction pairs in the provided
1144  // basic block and collects all candidate pairs for vectorization.
1145  bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1146                       BasicBlock::iterator &Start,
1147                       std::multimap<Value *, Value *> &CandidatePairs,
1148                       DenseSet<ValuePair> &FixedOrderPairs,
1149                       DenseMap<ValuePair, int> &CandidatePairCostSavings,
1150                       std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1151    BasicBlock::iterator E = BB.end();
1152    if (Start == E) return false;
1153
1154    bool ShouldContinue = false, IAfterStart = false;
1155    for (BasicBlock::iterator I = Start++; I != E; ++I) {
1156      if (I == Start) IAfterStart = true;
1157
1158      bool IsSimpleLoadStore;
1159      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1160
1161      // Look for an instruction with which to pair instruction *I...
1162      DenseSet<Value *> Users;
1163      AliasSetTracker WriteSet(*AA);
1164      bool JAfterStart = IAfterStart;
1165      BasicBlock::iterator J = llvm::next(I);
1166      for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1167        if (J == Start) JAfterStart = true;
1168
1169        // Determine if J uses I, if so, exit the loop.
1170        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1171        if (Config.FastDep) {
1172          // Note: For this heuristic to be effective, independent operations
1173          // must tend to be intermixed. This is likely to be true from some
1174          // kinds of grouped loop unrolling (but not the generic LLVM pass),
1175          // but otherwise may require some kind of reordering pass.
1176
1177          // When using fast dependency analysis,
1178          // stop searching after first use:
1179          if (UsesI) break;
1180        } else {
1181          if (UsesI) continue;
1182        }
1183
1184        // J does not use I, and comes before the first use of I, so it can be
1185        // merged with I if the instructions are compatible.
1186        int CostSavings, FixedOrder;
1187        if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1188            CostSavings, FixedOrder)) continue;
1189
1190        // J is a candidate for merging with I.
1191        if (!PairableInsts.size() ||
1192             PairableInsts[PairableInsts.size()-1] != I) {
1193          PairableInsts.push_back(I);
1194        }
1195
1196        CandidatePairs.insert(ValuePair(I, J));
1197        if (TTI)
1198          CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1199                                                            CostSavings));
1200
1201        if (FixedOrder == 1)
1202          FixedOrderPairs.insert(ValuePair(I, J));
1203        else if (FixedOrder == -1)
1204          FixedOrderPairs.insert(ValuePair(J, I));
1205
1206        // The next call to this function must start after the last instruction
1207        // selected during this invocation.
1208        if (JAfterStart) {
1209          Start = llvm::next(J);
1210          IAfterStart = JAfterStart = false;
1211        }
1212
1213        DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1214                     << *I << " <-> " << *J << " (cost savings: " <<
1215                     CostSavings << ")\n");
1216
1217        // If we have already found too many pairs, break here and this function
1218        // will be called again starting after the last instruction selected
1219        // during this invocation.
1220        if (PairableInsts.size() >= Config.MaxInsts) {
1221          ShouldContinue = true;
1222          break;
1223        }
1224      }
1225
1226      if (ShouldContinue)
1227        break;
1228    }
1229
1230    DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1231           << " instructions with candidate pairs\n");
1232
1233    return ShouldContinue;
1234  }
1235
1236  // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1237  // it looks for pairs such that both members have an input which is an
1238  // output of PI or PJ.
1239  void BBVectorize::computePairsConnectedTo(
1240                      std::multimap<Value *, Value *> &CandidatePairs,
1241                      std::vector<Value *> &PairableInsts,
1242                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1243                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
1244                      ValuePair P) {
1245    StoreInst *SI, *SJ;
1246
1247    // For each possible pairing for this variable, look at the uses of
1248    // the first value...
1249    for (Value::use_iterator I = P.first->use_begin(),
1250         E = P.first->use_end(); I != E; ++I) {
1251      if (isa<LoadInst>(*I)) {
1252        // A pair cannot be connected to a load because the load only takes one
1253        // operand (the address) and it is a scalar even after vectorization.
1254        continue;
1255      } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1256                 P.first == SI->getPointerOperand()) {
1257        // Similarly, a pair cannot be connected to a store through its
1258        // pointer operand.
1259        continue;
1260      }
1261
1262      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1263
1264      // For each use of the first variable, look for uses of the second
1265      // variable...
1266      for (Value::use_iterator J = P.second->use_begin(),
1267           E2 = P.second->use_end(); J != E2; ++J) {
1268        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1269            P.second == SJ->getPointerOperand())
1270          continue;
1271
1272        VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1273
1274        // Look for <I, J>:
1275        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1276          VPPair VP(P, ValuePair(*I, *J));
1277          ConnectedPairs.insert(VP);
1278          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1279        }
1280
1281        // Look for <J, I>:
1282        if (isSecondInIteratorPair<Value*>(*I, JPairRange)) {
1283          VPPair VP(P, ValuePair(*J, *I));
1284          ConnectedPairs.insert(VP);
1285          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1286        }
1287      }
1288
1289      if (Config.SplatBreaksChain) continue;
1290      // Look for cases where just the first value in the pair is used by
1291      // both members of another pair (splatting).
1292      for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1293        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1294            P.first == SJ->getPointerOperand())
1295          continue;
1296
1297        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1298          VPPair VP(P, ValuePair(*I, *J));
1299          ConnectedPairs.insert(VP);
1300          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1301        }
1302      }
1303    }
1304
1305    if (Config.SplatBreaksChain) return;
1306    // Look for cases where just the second value in the pair is used by
1307    // both members of another pair (splatting).
1308    for (Value::use_iterator I = P.second->use_begin(),
1309         E = P.second->use_end(); I != E; ++I) {
1310      if (isa<LoadInst>(*I))
1311        continue;
1312      else if ((SI = dyn_cast<StoreInst>(*I)) &&
1313               P.second == SI->getPointerOperand())
1314        continue;
1315
1316      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1317
1318      for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1319        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1320            P.second == SJ->getPointerOperand())
1321          continue;
1322
1323        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1324          VPPair VP(P, ValuePair(*I, *J));
1325          ConnectedPairs.insert(VP);
1326          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1327        }
1328      }
1329    }
1330  }
1331
1332  // This function figures out which pairs are connected.  Two pairs are
1333  // connected if some output of the first pair forms an input to both members
1334  // of the second pair.
1335  void BBVectorize::computeConnectedPairs(
1336                      std::multimap<Value *, Value *> &CandidatePairs,
1337                      std::vector<Value *> &PairableInsts,
1338                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1339                      DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1340
1341    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1342         PE = PairableInsts.end(); PI != PE; ++PI) {
1343      VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1344
1345      for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1346           P != choiceRange.second; ++P)
1347        computePairsConnectedTo(CandidatePairs, PairableInsts,
1348                                ConnectedPairs, PairConnectionTypes, *P);
1349    }
1350
1351    DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1352                 << " pair connections.\n");
1353  }
1354
1355  // This function builds a set of use tuples such that <A, B> is in the set
1356  // if B is in the use tree of A. If B is in the use tree of A, then B
1357  // depends on the output of A.
1358  void BBVectorize::buildDepMap(
1359                      BasicBlock &BB,
1360                      std::multimap<Value *, Value *> &CandidatePairs,
1361                      std::vector<Value *> &PairableInsts,
1362                      DenseSet<ValuePair> &PairableInstUsers) {
1363    DenseSet<Value *> IsInPair;
1364    for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1365         E = CandidatePairs.end(); C != E; ++C) {
1366      IsInPair.insert(C->first);
1367      IsInPair.insert(C->second);
1368    }
1369
1370    // Iterate through the basic block, recording all Users of each
1371    // pairable instruction.
1372
1373    BasicBlock::iterator E = BB.end();
1374    for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1375      if (IsInPair.find(I) == IsInPair.end()) continue;
1376
1377      DenseSet<Value *> Users;
1378      AliasSetTracker WriteSet(*AA);
1379      for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1380        (void) trackUsesOfI(Users, WriteSet, I, J);
1381
1382      for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1383           U != E; ++U)
1384        PairableInstUsers.insert(ValuePair(I, *U));
1385    }
1386  }
1387
1388  // Returns true if an input to pair P is an output of pair Q and also an
1389  // input of pair Q is an output of pair P. If this is the case, then these
1390  // two pairs cannot be simultaneously fused.
1391  bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1392                     DenseSet<ValuePair> &PairableInstUsers,
1393                     std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1394    // Two pairs are in conflict if they are mutual Users of eachother.
1395    bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
1396                  PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
1397                  PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
1398                  PairableInstUsers.count(ValuePair(P.second, Q.second));
1399    bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
1400                  PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
1401                  PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
1402                  PairableInstUsers.count(ValuePair(Q.second, P.second));
1403    if (PairableInstUserMap) {
1404      // FIXME: The expensive part of the cycle check is not so much the cycle
1405      // check itself but this edge insertion procedure. This needs some
1406      // profiling and probably a different data structure (same is true of
1407      // most uses of std::multimap).
1408      if (PUsesQ) {
1409        VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1410        if (!isSecondInIteratorPair(P, QPairRange))
1411          PairableInstUserMap->insert(VPPair(Q, P));
1412      }
1413      if (QUsesP) {
1414        VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1415        if (!isSecondInIteratorPair(Q, PPairRange))
1416          PairableInstUserMap->insert(VPPair(P, Q));
1417      }
1418    }
1419
1420    return (QUsesP && PUsesQ);
1421  }
1422
1423  // This function walks the use graph of current pairs to see if, starting
1424  // from P, the walk returns to P.
1425  bool BBVectorize::pairWillFormCycle(ValuePair P,
1426                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1427                       DenseSet<ValuePair> &CurrentPairs) {
1428    DEBUG(if (DebugCycleCheck)
1429            dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1430                   << *P.second << "\n");
1431    // A lookup table of visisted pairs is kept because the PairableInstUserMap
1432    // contains non-direct associations.
1433    DenseSet<ValuePair> Visited;
1434    SmallVector<ValuePair, 32> Q;
1435    // General depth-first post-order traversal:
1436    Q.push_back(P);
1437    do {
1438      ValuePair QTop = Q.pop_back_val();
1439      Visited.insert(QTop);
1440
1441      DEBUG(if (DebugCycleCheck)
1442              dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1443                     << *QTop.second << "\n");
1444      VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1445      for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1446           C != QPairRange.second; ++C) {
1447        if (C->second == P) {
1448          DEBUG(dbgs()
1449                 << "BBV: rejected to prevent non-trivial cycle formation: "
1450                 << *C->first.first << " <-> " << *C->first.second << "\n");
1451          return true;
1452        }
1453
1454        if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1455          Q.push_back(C->second);
1456      }
1457    } while (!Q.empty());
1458
1459    return false;
1460  }
1461
1462  // This function builds the initial tree of connected pairs with the
1463  // pair J at the root.
1464  void BBVectorize::buildInitialTreeFor(
1465                      std::multimap<Value *, Value *> &CandidatePairs,
1466                      std::vector<Value *> &PairableInsts,
1467                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1468                      DenseSet<ValuePair> &PairableInstUsers,
1469                      DenseMap<Value *, Value *> &ChosenPairs,
1470                      DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1471    // Each of these pairs is viewed as the root node of a Tree. The Tree
1472    // is then walked (depth-first). As this happens, we keep track of
1473    // the pairs that compose the Tree and the maximum depth of the Tree.
1474    SmallVector<ValuePairWithDepth, 32> Q;
1475    // General depth-first post-order traversal:
1476    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1477    do {
1478      ValuePairWithDepth QTop = Q.back();
1479
1480      // Push each child onto the queue:
1481      bool MoreChildren = false;
1482      size_t MaxChildDepth = QTop.second;
1483      VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1484      for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1485           k != qtRange.second; ++k) {
1486        // Make sure that this child pair is still a candidate:
1487        bool IsStillCand = false;
1488        VPIteratorPair checkRange =
1489          CandidatePairs.equal_range(k->second.first);
1490        for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1491             m != checkRange.second; ++m) {
1492          if (m->second == k->second.second) {
1493            IsStillCand = true;
1494            break;
1495          }
1496        }
1497
1498        if (IsStillCand) {
1499          DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1500          if (C == Tree.end()) {
1501            size_t d = getDepthFactor(k->second.first);
1502            Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1503            MoreChildren = true;
1504          } else {
1505            MaxChildDepth = std::max(MaxChildDepth, C->second);
1506          }
1507        }
1508      }
1509
1510      if (!MoreChildren) {
1511        // Record the current pair as part of the Tree:
1512        Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1513        Q.pop_back();
1514      }
1515    } while (!Q.empty());
1516  }
1517
1518  // Given some initial tree, prune it by removing conflicting pairs (pairs
1519  // that cannot be simultaneously chosen for vectorization).
1520  void BBVectorize::pruneTreeFor(
1521                      std::multimap<Value *, Value *> &CandidatePairs,
1522                      std::vector<Value *> &PairableInsts,
1523                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1524                      DenseSet<ValuePair> &PairableInstUsers,
1525                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1526                      DenseMap<Value *, Value *> &ChosenPairs,
1527                      DenseMap<ValuePair, size_t> &Tree,
1528                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
1529                      bool UseCycleCheck) {
1530    SmallVector<ValuePairWithDepth, 32> Q;
1531    // General depth-first post-order traversal:
1532    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1533    do {
1534      ValuePairWithDepth QTop = Q.pop_back_val();
1535      PrunedTree.insert(QTop.first);
1536
1537      // Visit each child, pruning as necessary...
1538      SmallVector<ValuePairWithDepth, 8> BestChildren;
1539      VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1540      for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1541           K != QTopRange.second; ++K) {
1542        DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1543        if (C == Tree.end()) continue;
1544
1545        // This child is in the Tree, now we need to make sure it is the
1546        // best of any conflicting children. There could be multiple
1547        // conflicting children, so first, determine if we're keeping
1548        // this child, then delete conflicting children as necessary.
1549
1550        // It is also necessary to guard against pairing-induced
1551        // dependencies. Consider instructions a .. x .. y .. b
1552        // such that (a,b) are to be fused and (x,y) are to be fused
1553        // but a is an input to x and b is an output from y. This
1554        // means that y cannot be moved after b but x must be moved
1555        // after b for (a,b) to be fused. In other words, after
1556        // fusing (a,b) we have y .. a/b .. x where y is an input
1557        // to a/b and x is an output to a/b: x and y can no longer
1558        // be legally fused. To prevent this condition, we must
1559        // make sure that a child pair added to the Tree is not
1560        // both an input and output of an already-selected pair.
1561
1562        // Pairing-induced dependencies can also form from more complicated
1563        // cycles. The pair vs. pair conflicts are easy to check, and so
1564        // that is done explicitly for "fast rejection", and because for
1565        // child vs. child conflicts, we may prefer to keep the current
1566        // pair in preference to the already-selected child.
1567        DenseSet<ValuePair> CurrentPairs;
1568
1569        bool CanAdd = true;
1570        for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1571              = BestChildren.begin(), E2 = BestChildren.end();
1572             C2 != E2; ++C2) {
1573          if (C2->first.first == C->first.first ||
1574              C2->first.first == C->first.second ||
1575              C2->first.second == C->first.first ||
1576              C2->first.second == C->first.second ||
1577              pairsConflict(C2->first, C->first, PairableInstUsers,
1578                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1579            if (C2->second >= C->second) {
1580              CanAdd = false;
1581              break;
1582            }
1583
1584            CurrentPairs.insert(C2->first);
1585          }
1586        }
1587        if (!CanAdd) continue;
1588
1589        // Even worse, this child could conflict with another node already
1590        // selected for the Tree. If that is the case, ignore this child.
1591        for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1592             E2 = PrunedTree.end(); T != E2; ++T) {
1593          if (T->first == C->first.first ||
1594              T->first == C->first.second ||
1595              T->second == C->first.first ||
1596              T->second == C->first.second ||
1597              pairsConflict(*T, C->first, PairableInstUsers,
1598                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1599            CanAdd = false;
1600            break;
1601          }
1602
1603          CurrentPairs.insert(*T);
1604        }
1605        if (!CanAdd) continue;
1606
1607        // And check the queue too...
1608        for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1609             E2 = Q.end(); C2 != E2; ++C2) {
1610          if (C2->first.first == C->first.first ||
1611              C2->first.first == C->first.second ||
1612              C2->first.second == C->first.first ||
1613              C2->first.second == C->first.second ||
1614              pairsConflict(C2->first, C->first, PairableInstUsers,
1615                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1616            CanAdd = false;
1617            break;
1618          }
1619
1620          CurrentPairs.insert(C2->first);
1621        }
1622        if (!CanAdd) continue;
1623
1624        // Last but not least, check for a conflict with any of the
1625        // already-chosen pairs.
1626        for (DenseMap<Value *, Value *>::iterator C2 =
1627              ChosenPairs.begin(), E2 = ChosenPairs.end();
1628             C2 != E2; ++C2) {
1629          if (pairsConflict(*C2, C->first, PairableInstUsers,
1630                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1631            CanAdd = false;
1632            break;
1633          }
1634
1635          CurrentPairs.insert(*C2);
1636        }
1637        if (!CanAdd) continue;
1638
1639        // To check for non-trivial cycles formed by the addition of the
1640        // current pair we've formed a list of all relevant pairs, now use a
1641        // graph walk to check for a cycle. We start from the current pair and
1642        // walk the use tree to see if we again reach the current pair. If we
1643        // do, then the current pair is rejected.
1644
1645        // FIXME: It may be more efficient to use a topological-ordering
1646        // algorithm to improve the cycle check. This should be investigated.
1647        if (UseCycleCheck &&
1648            pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1649          continue;
1650
1651        // This child can be added, but we may have chosen it in preference
1652        // to an already-selected child. Check for this here, and if a
1653        // conflict is found, then remove the previously-selected child
1654        // before adding this one in its place.
1655        for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1656              = BestChildren.begin(); C2 != BestChildren.end();) {
1657          if (C2->first.first == C->first.first ||
1658              C2->first.first == C->first.second ||
1659              C2->first.second == C->first.first ||
1660              C2->first.second == C->first.second ||
1661              pairsConflict(C2->first, C->first, PairableInstUsers))
1662            C2 = BestChildren.erase(C2);
1663          else
1664            ++C2;
1665        }
1666
1667        BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1668      }
1669
1670      for (SmallVector<ValuePairWithDepth, 8>::iterator C
1671            = BestChildren.begin(), E2 = BestChildren.end();
1672           C != E2; ++C) {
1673        size_t DepthF = getDepthFactor(C->first.first);
1674        Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1675      }
1676    } while (!Q.empty());
1677  }
1678
1679  // This function finds the best tree of mututally-compatible connected
1680  // pairs, given the choice of root pairs as an iterator range.
1681  void BBVectorize::findBestTreeFor(
1682                      std::multimap<Value *, Value *> &CandidatePairs,
1683                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
1684                      std::vector<Value *> &PairableInsts,
1685                      DenseSet<ValuePair> &FixedOrderPairs,
1686                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
1687                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1688                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
1689                      DenseSet<ValuePair> &PairableInstUsers,
1690                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1691                      DenseMap<Value *, Value *> &ChosenPairs,
1692                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1693                      int &BestEffSize, VPIteratorPair ChoiceRange,
1694                      bool UseCycleCheck) {
1695    for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1696         J != ChoiceRange.second; ++J) {
1697
1698      // Before going any further, make sure that this pair does not
1699      // conflict with any already-selected pairs (see comment below
1700      // near the Tree pruning for more details).
1701      DenseSet<ValuePair> ChosenPairSet;
1702      bool DoesConflict = false;
1703      for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1704           E = ChosenPairs.end(); C != E; ++C) {
1705        if (pairsConflict(*C, *J, PairableInstUsers,
1706                          UseCycleCheck ? &PairableInstUserMap : 0)) {
1707          DoesConflict = true;
1708          break;
1709        }
1710
1711        ChosenPairSet.insert(*C);
1712      }
1713      if (DoesConflict) continue;
1714
1715      if (UseCycleCheck &&
1716          pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1717        continue;
1718
1719      DenseMap<ValuePair, size_t> Tree;
1720      buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1721                          PairableInstUsers, ChosenPairs, Tree, *J);
1722
1723      // Because we'll keep the child with the largest depth, the largest
1724      // depth is still the same in the unpruned Tree.
1725      size_t MaxDepth = Tree.lookup(*J);
1726
1727      DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1728                   << *J->first << " <-> " << *J->second << "} of depth " <<
1729                   MaxDepth << " and size " << Tree.size() << "\n");
1730
1731      // At this point the Tree has been constructed, but, may contain
1732      // contradictory children (meaning that different children of
1733      // some tree node may be attempting to fuse the same instruction).
1734      // So now we walk the tree again, in the case of a conflict,
1735      // keep only the child with the largest depth. To break a tie,
1736      // favor the first child.
1737
1738      DenseSet<ValuePair> PrunedTree;
1739      pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1740                   PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1741                   PrunedTree, *J, UseCycleCheck);
1742
1743      int EffSize = 0;
1744      if (TTI) {
1745        DenseSet<Value *> PrunedTreeInstrs;
1746        for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1747             E = PrunedTree.end(); S != E; ++S) {
1748          PrunedTreeInstrs.insert(S->first);
1749          PrunedTreeInstrs.insert(S->second);
1750        }
1751
1752        // The set of pairs that have already contributed to the total cost.
1753        DenseSet<ValuePair> IncomingPairs;
1754
1755        // If the cost model were perfect, this might not be necessary; but we
1756        // need to make sure that we don't get stuck vectorizing our own
1757        // shuffle chains.
1758        bool HasNontrivialInsts = false;
1759
1760        // The node weights represent the cost savings associated with
1761        // fusing the pair of instructions.
1762        for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1763             E = PrunedTree.end(); S != E; ++S) {
1764          if (!isa<ShuffleVectorInst>(S->first) &&
1765              !isa<InsertElementInst>(S->first) &&
1766              !isa<ExtractElementInst>(S->first))
1767            HasNontrivialInsts = true;
1768
1769          bool FlipOrder = false;
1770
1771          if (getDepthFactor(S->first)) {
1772            int ESContrib = CandidatePairCostSavings.find(*S)->second;
1773            DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1774                   << *S->first << " <-> " << *S->second << "} = " <<
1775                   ESContrib << "\n");
1776            EffSize += ESContrib;
1777          }
1778
1779          // The edge weights contribute in a negative sense: they represent
1780          // the cost of shuffles.
1781          VPPIteratorPair IP = ConnectedPairDeps.equal_range(*S);
1782          if (IP.first != ConnectedPairDeps.end()) {
1783            unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1784            for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1785                 Q != IP.second; ++Q) {
1786              if (!PrunedTree.count(Q->second))
1787                continue;
1788              DenseMap<VPPair, unsigned>::iterator R =
1789                PairConnectionTypes.find(VPPair(Q->second, Q->first));
1790              assert(R != PairConnectionTypes.end() &&
1791                     "Cannot find pair connection type");
1792              if (R->second == PairConnectionDirect)
1793                ++NumDepsDirect;
1794              else if (R->second == PairConnectionSwap)
1795                ++NumDepsSwap;
1796            }
1797
1798            // If there are more swaps than direct connections, then
1799            // the pair order will be flipped during fusion. So the real
1800            // number of swaps is the minimum number.
1801            FlipOrder = !FixedOrderPairs.count(*S) &&
1802              ((NumDepsSwap > NumDepsDirect) ||
1803                FixedOrderPairs.count(ValuePair(S->second, S->first)));
1804
1805            for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1806                 Q != IP.second; ++Q) {
1807              if (!PrunedTree.count(Q->second))
1808                continue;
1809              DenseMap<VPPair, unsigned>::iterator R =
1810                PairConnectionTypes.find(VPPair(Q->second, Q->first));
1811              assert(R != PairConnectionTypes.end() &&
1812                     "Cannot find pair connection type");
1813              Type *Ty1 = Q->second.first->getType(),
1814                   *Ty2 = Q->second.second->getType();
1815              Type *VTy = getVecTypeForPair(Ty1, Ty2);
1816              if ((R->second == PairConnectionDirect && FlipOrder) ||
1817                  (R->second == PairConnectionSwap && !FlipOrder)  ||
1818                  R->second == PairConnectionSplat) {
1819                int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1820                                                   VTy, VTy);
1821                DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1822                  *Q->second.first << " <-> " << *Q->second.second <<
1823                    "} -> {" <<
1824                  *S->first << " <-> " << *S->second << "} = " <<
1825                   ESContrib << "\n");
1826                EffSize -= ESContrib;
1827              }
1828            }
1829          }
1830
1831          // Compute the cost of outgoing edges. We assume that edges outgoing
1832          // to shuffles, inserts or extracts can be merged, and so contribute
1833          // no additional cost.
1834          if (!S->first->getType()->isVoidTy()) {
1835            Type *Ty1 = S->first->getType(),
1836                 *Ty2 = S->second->getType();
1837            Type *VTy = getVecTypeForPair(Ty1, Ty2);
1838
1839            bool NeedsExtraction = false;
1840            for (Value::use_iterator I = S->first->use_begin(),
1841                 IE = S->first->use_end(); I != IE; ++I) {
1842              if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1843                // Shuffle can be folded if it has no other input
1844                if (isa<UndefValue>(SI->getOperand(1)))
1845                  continue;
1846              }
1847              if (isa<ExtractElementInst>(*I))
1848                continue;
1849              if (PrunedTreeInstrs.count(*I))
1850                continue;
1851              NeedsExtraction = true;
1852              break;
1853            }
1854
1855            if (NeedsExtraction) {
1856              int ESContrib;
1857              if (Ty1->isVectorTy())
1858                ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1859                                               Ty1, VTy);
1860              else
1861                ESContrib = (int) TTI->getVectorInstrCost(
1862                                    Instruction::ExtractElement, VTy, 0);
1863
1864              DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1865                *S->first << "} = " << ESContrib << "\n");
1866              EffSize -= ESContrib;
1867            }
1868
1869            NeedsExtraction = false;
1870            for (Value::use_iterator I = S->second->use_begin(),
1871                 IE = S->second->use_end(); I != IE; ++I) {
1872              if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1873                // Shuffle can be folded if it has no other input
1874                if (isa<UndefValue>(SI->getOperand(1)))
1875                  continue;
1876              }
1877              if (isa<ExtractElementInst>(*I))
1878                continue;
1879              if (PrunedTreeInstrs.count(*I))
1880                continue;
1881              NeedsExtraction = true;
1882              break;
1883            }
1884
1885            if (NeedsExtraction) {
1886              int ESContrib;
1887              if (Ty2->isVectorTy())
1888                ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1889                                               Ty2, VTy);
1890              else
1891                ESContrib = (int) TTI->getVectorInstrCost(
1892                                    Instruction::ExtractElement, VTy, 1);
1893              DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1894                *S->second << "} = " << ESContrib << "\n");
1895              EffSize -= ESContrib;
1896            }
1897          }
1898
1899          // Compute the cost of incoming edges.
1900          if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
1901            Instruction *S1 = cast<Instruction>(S->first),
1902                        *S2 = cast<Instruction>(S->second);
1903            for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
1904              Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
1905
1906              // Combining constants into vector constants (or small vector
1907              // constants into larger ones are assumed free).
1908              if (isa<Constant>(O1) && isa<Constant>(O2))
1909                continue;
1910
1911              if (FlipOrder)
1912                std::swap(O1, O2);
1913
1914              ValuePair VP  = ValuePair(O1, O2);
1915              ValuePair VPR = ValuePair(O2, O1);
1916
1917              // Internal edges are not handled here.
1918              if (PrunedTree.count(VP) || PrunedTree.count(VPR))
1919                continue;
1920
1921              Type *Ty1 = O1->getType(),
1922                   *Ty2 = O2->getType();
1923              Type *VTy = getVecTypeForPair(Ty1, Ty2);
1924
1925              // Combining vector operations of the same type is also assumed
1926              // folded with other operations.
1927              if (Ty1 == Ty2) {
1928                // If both are insert elements, then both can be widened.
1929                InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
1930                                  *IEO2 = dyn_cast<InsertElementInst>(O2);
1931                if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
1932                  continue;
1933                // If both are extract elements, and both have the same input
1934                // type, then they can be replaced with a shuffle
1935                ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
1936                                   *EIO2 = dyn_cast<ExtractElementInst>(O2);
1937                if (EIO1 && EIO2 &&
1938                    EIO1->getOperand(0)->getType() ==
1939                      EIO2->getOperand(0)->getType())
1940                  continue;
1941                // If both are a shuffle with equal operand types and only two
1942                // unqiue operands, then they can be replaced with a single
1943                // shuffle
1944                ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
1945                                  *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
1946                if (SIO1 && SIO2 &&
1947                    SIO1->getOperand(0)->getType() ==
1948                      SIO2->getOperand(0)->getType()) {
1949                  SmallSet<Value *, 4> SIOps;
1950                  SIOps.insert(SIO1->getOperand(0));
1951                  SIOps.insert(SIO1->getOperand(1));
1952                  SIOps.insert(SIO2->getOperand(0));
1953                  SIOps.insert(SIO2->getOperand(1));
1954                  if (SIOps.size() <= 2)
1955                    continue;
1956                }
1957              }
1958
1959              int ESContrib;
1960              // This pair has already been formed.
1961              if (IncomingPairs.count(VP)) {
1962                continue;
1963              } else if (IncomingPairs.count(VPR)) {
1964                ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1965                                               VTy, VTy);
1966              } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
1967                ESContrib = (int) TTI->getVectorInstrCost(
1968                                    Instruction::InsertElement, VTy, 0);
1969                ESContrib += (int) TTI->getVectorInstrCost(
1970                                     Instruction::InsertElement, VTy, 1);
1971              } else if (!Ty1->isVectorTy()) {
1972                // O1 needs to be inserted into a vector of size O2, and then
1973                // both need to be shuffled together.
1974                ESContrib = (int) TTI->getVectorInstrCost(
1975                                    Instruction::InsertElement, Ty2, 0);
1976                ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
1977                                                VTy, Ty2);
1978              } else if (!Ty2->isVectorTy()) {
1979                // O2 needs to be inserted into a vector of size O1, and then
1980                // both need to be shuffled together.
1981                ESContrib = (int) TTI->getVectorInstrCost(
1982                                    Instruction::InsertElement, Ty1, 0);
1983                ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
1984                                                VTy, Ty1);
1985              } else {
1986                Type *TyBig = Ty1, *TySmall = Ty2;
1987                if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
1988                  std::swap(TyBig, TySmall);
1989
1990                ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1991                                               VTy, TyBig);
1992                if (TyBig != TySmall)
1993                  ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
1994                                                  TyBig, TySmall);
1995              }
1996
1997              DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
1998                     << *O1 << " <-> " << *O2 << "} = " <<
1999                     ESContrib << "\n");
2000              EffSize -= ESContrib;
2001              IncomingPairs.insert(VP);
2002            }
2003          }
2004        }
2005
2006        if (!HasNontrivialInsts) {
2007          DEBUG(if (DebugPairSelection) dbgs() <<
2008                "\tNo non-trivial instructions in tree;"
2009                " override to zero effective size\n");
2010          EffSize = 0;
2011        }
2012      } else {
2013        for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
2014             E = PrunedTree.end(); S != E; ++S)
2015          EffSize += (int) getDepthFactor(S->first);
2016      }
2017
2018      DEBUG(if (DebugPairSelection)
2019             dbgs() << "BBV: found pruned Tree for pair {"
2020             << *J->first << " <-> " << *J->second << "} of depth " <<
2021             MaxDepth << " and size " << PrunedTree.size() <<
2022            " (effective size: " << EffSize << ")\n");
2023      if (((TTI && !UseChainDepthWithTI) ||
2024            MaxDepth >= Config.ReqChainDepth) &&
2025          EffSize > 0 && EffSize > BestEffSize) {
2026        BestMaxDepth = MaxDepth;
2027        BestEffSize = EffSize;
2028        BestTree = PrunedTree;
2029      }
2030    }
2031  }
2032
2033  // Given the list of candidate pairs, this function selects those
2034  // that will be fused into vector instructions.
2035  void BBVectorize::choosePairs(
2036                      std::multimap<Value *, Value *> &CandidatePairs,
2037                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
2038                      std::vector<Value *> &PairableInsts,
2039                      DenseSet<ValuePair> &FixedOrderPairs,
2040                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
2041                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2042                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
2043                      DenseSet<ValuePair> &PairableInstUsers,
2044                      DenseMap<Value *, Value *>& ChosenPairs) {
2045    bool UseCycleCheck =
2046     CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
2047    std::multimap<ValuePair, ValuePair> PairableInstUserMap;
2048    for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2049         E = PairableInsts.end(); I != E; ++I) {
2050      // The number of possible pairings for this variable:
2051      size_t NumChoices = CandidatePairs.count(*I);
2052      if (!NumChoices) continue;
2053
2054      VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
2055
2056      // The best pair to choose and its tree:
2057      size_t BestMaxDepth = 0;
2058      int BestEffSize = 0;
2059      DenseSet<ValuePair> BestTree;
2060      findBestTreeFor(CandidatePairs, CandidatePairCostSavings,
2061                      PairableInsts, FixedOrderPairs, PairConnectionTypes,
2062                      ConnectedPairs, ConnectedPairDeps,
2063                      PairableInstUsers, PairableInstUserMap, ChosenPairs,
2064                      BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
2065                      UseCycleCheck);
2066
2067      // A tree has been chosen (or not) at this point. If no tree was
2068      // chosen, then this instruction, I, cannot be paired (and is no longer
2069      // considered).
2070
2071      DEBUG(if (BestTree.size() > 0)
2072              dbgs() << "BBV: selected pairs in the best tree for: "
2073                     << *cast<Instruction>(*I) << "\n");
2074
2075      for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
2076           SE2 = BestTree.end(); S != SE2; ++S) {
2077        // Insert the members of this tree into the list of chosen pairs.
2078        ChosenPairs.insert(ValuePair(S->first, S->second));
2079        DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2080               *S->second << "\n");
2081
2082        // Remove all candidate pairs that have values in the chosen tree.
2083        for (std::multimap<Value *, Value *>::iterator K =
2084               CandidatePairs.begin(); K != CandidatePairs.end();) {
2085          if (K->first == S->first || K->second == S->first ||
2086              K->second == S->second || K->first == S->second) {
2087            // Don't remove the actual pair chosen so that it can be used
2088            // in subsequent tree selections.
2089            if (!(K->first == S->first && K->second == S->second))
2090              CandidatePairs.erase(K++);
2091            else
2092              ++K;
2093          } else {
2094            ++K;
2095          }
2096        }
2097      }
2098    }
2099
2100    DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2101  }
2102
2103  std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2104                     unsigned n = 0) {
2105    if (!I->hasName())
2106      return "";
2107
2108    return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2109             (n > 0 ? "." + utostr(n) : "")).str();
2110  }
2111
2112  // Returns the value that is to be used as the pointer input to the vector
2113  // instruction that fuses I with J.
2114  Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2115                     Instruction *I, Instruction *J, unsigned o) {
2116    Value *IPtr, *JPtr;
2117    unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2118    int64_t OffsetInElmts;
2119
2120    // Note: the analysis might fail here, that is why the pair order has
2121    // been precomputed (OffsetInElmts must be unused here).
2122    (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2123                          IAddressSpace, JAddressSpace,
2124                          OffsetInElmts, false);
2125
2126    // The pointer value is taken to be the one with the lowest offset.
2127    Value *VPtr = IPtr;
2128
2129    Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
2130    Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
2131    Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2132    Type *VArgPtrType = PointerType::get(VArgType,
2133      cast<PointerType>(IPtr->getType())->getAddressSpace());
2134    return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2135                        /* insert before */ I);
2136  }
2137
2138  void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2139                     unsigned MaskOffset, unsigned NumInElem,
2140                     unsigned NumInElem1, unsigned IdxOffset,
2141                     std::vector<Constant*> &Mask) {
2142    unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
2143    for (unsigned v = 0; v < NumElem1; ++v) {
2144      int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2145      if (m < 0) {
2146        Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2147      } else {
2148        unsigned mm = m + (int) IdxOffset;
2149        if (m >= (int) NumInElem1)
2150          mm += (int) NumInElem;
2151
2152        Mask[v+MaskOffset] =
2153          ConstantInt::get(Type::getInt32Ty(Context), mm);
2154      }
2155    }
2156  }
2157
2158  // Returns the value that is to be used as the vector-shuffle mask to the
2159  // vector instruction that fuses I with J.
2160  Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2161                     Instruction *I, Instruction *J) {
2162    // This is the shuffle mask. We need to append the second
2163    // mask to the first, and the numbers need to be adjusted.
2164
2165    Type *ArgTypeI = I->getType();
2166    Type *ArgTypeJ = J->getType();
2167    Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2168
2169    unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
2170
2171    // Get the total number of elements in the fused vector type.
2172    // By definition, this must equal the number of elements in
2173    // the final mask.
2174    unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
2175    std::vector<Constant*> Mask(NumElem);
2176
2177    Type *OpTypeI = I->getOperand(0)->getType();
2178    unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
2179    Type *OpTypeJ = J->getOperand(0)->getType();
2180    unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
2181
2182    // The fused vector will be:
2183    // -----------------------------------------------------
2184    // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2185    // -----------------------------------------------------
2186    // from which we'll extract NumElem total elements (where the first NumElemI
2187    // of them come from the mask in I and the remainder come from the mask
2188    // in J.
2189
2190    // For the mask from the first pair...
2191    fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
2192                       0,          Mask);
2193
2194    // For the mask from the second pair...
2195    fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2196                       NumInElemI, Mask);
2197
2198    return ConstantVector::get(Mask);
2199  }
2200
2201  bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2202                                  Instruction *J, unsigned o, Value *&LOp,
2203                                  unsigned numElemL,
2204                                  Type *ArgTypeL, Type *ArgTypeH,
2205                                  bool IBeforeJ, unsigned IdxOff) {
2206    bool ExpandedIEChain = false;
2207    if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2208      // If we have a pure insertelement chain, then this can be rewritten
2209      // into a chain that directly builds the larger type.
2210      if (isPureIEChain(LIE)) {
2211        SmallVector<Value *, 8> VectElemts(numElemL,
2212          UndefValue::get(ArgTypeL->getScalarType()));
2213        InsertElementInst *LIENext = LIE;
2214        do {
2215          unsigned Idx =
2216            cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2217          VectElemts[Idx] = LIENext->getOperand(1);
2218        } while ((LIENext =
2219                   dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2220
2221        LIENext = 0;
2222        Value *LIEPrev = UndefValue::get(ArgTypeH);
2223        for (unsigned i = 0; i < numElemL; ++i) {
2224          if (isa<UndefValue>(VectElemts[i])) continue;
2225          LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2226                             ConstantInt::get(Type::getInt32Ty(Context),
2227                                              i + IdxOff),
2228                             getReplacementName(IBeforeJ ? I : J,
2229                                                true, o, i+1));
2230          LIENext->insertBefore(IBeforeJ ? J : I);
2231          LIEPrev = LIENext;
2232        }
2233
2234        LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2235        ExpandedIEChain = true;
2236      }
2237    }
2238
2239    return ExpandedIEChain;
2240  }
2241
2242  // Returns the value to be used as the specified operand of the vector
2243  // instruction that fuses I with J.
2244  Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2245                     Instruction *J, unsigned o, bool IBeforeJ) {
2246    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2247    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2248
2249    // Compute the fused vector type for this operand
2250    Type *ArgTypeI = I->getOperand(o)->getType();
2251    Type *ArgTypeJ = J->getOperand(o)->getType();
2252    VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2253
2254    Instruction *L = I, *H = J;
2255    Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2256
2257    unsigned numElemL;
2258    if (ArgTypeL->isVectorTy())
2259      numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
2260    else
2261      numElemL = 1;
2262
2263    unsigned numElemH;
2264    if (ArgTypeH->isVectorTy())
2265      numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
2266    else
2267      numElemH = 1;
2268
2269    Value *LOp = L->getOperand(o);
2270    Value *HOp = H->getOperand(o);
2271    unsigned numElem = VArgType->getNumElements();
2272
2273    // First, we check if we can reuse the "original" vector outputs (if these
2274    // exist). We might need a shuffle.
2275    ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2276    ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2277    ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2278    ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2279
2280    // FIXME: If we're fusing shuffle instructions, then we can't apply this
2281    // optimization. The input vectors to the shuffle might be a different
2282    // length from the shuffle outputs. Unfortunately, the replacement
2283    // shuffle mask has already been formed, and the mask entries are sensitive
2284    // to the sizes of the inputs.
2285    bool IsSizeChangeShuffle =
2286      isa<ShuffleVectorInst>(L) &&
2287        (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2288
2289    if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2290      // We can have at most two unique vector inputs.
2291      bool CanUseInputs = true;
2292      Value *I1, *I2 = 0;
2293      if (LEE) {
2294        I1 = LEE->getOperand(0);
2295      } else {
2296        I1 = LSV->getOperand(0);
2297        I2 = LSV->getOperand(1);
2298        if (I2 == I1 || isa<UndefValue>(I2))
2299          I2 = 0;
2300      }
2301
2302      if (HEE) {
2303        Value *I3 = HEE->getOperand(0);
2304        if (!I2 && I3 != I1)
2305          I2 = I3;
2306        else if (I3 != I1 && I3 != I2)
2307          CanUseInputs = false;
2308      } else {
2309        Value *I3 = HSV->getOperand(0);
2310        if (!I2 && I3 != I1)
2311          I2 = I3;
2312        else if (I3 != I1 && I3 != I2)
2313          CanUseInputs = false;
2314
2315        if (CanUseInputs) {
2316          Value *I4 = HSV->getOperand(1);
2317          if (!isa<UndefValue>(I4)) {
2318            if (!I2 && I4 != I1)
2319              I2 = I4;
2320            else if (I4 != I1 && I4 != I2)
2321              CanUseInputs = false;
2322          }
2323        }
2324      }
2325
2326      if (CanUseInputs) {
2327        unsigned LOpElem =
2328          cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2329            ->getNumElements();
2330        unsigned HOpElem =
2331          cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2332            ->getNumElements();
2333
2334        // We have one or two input vectors. We need to map each index of the
2335        // operands to the index of the original vector.
2336        SmallVector<std::pair<int, int>, 8>  II(numElem);
2337        for (unsigned i = 0; i < numElemL; ++i) {
2338          int Idx, INum;
2339          if (LEE) {
2340            Idx =
2341              cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2342            INum = LEE->getOperand(0) == I1 ? 0 : 1;
2343          } else {
2344            Idx = LSV->getMaskValue(i);
2345            if (Idx < (int) LOpElem) {
2346              INum = LSV->getOperand(0) == I1 ? 0 : 1;
2347            } else {
2348              Idx -= LOpElem;
2349              INum = LSV->getOperand(1) == I1 ? 0 : 1;
2350            }
2351          }
2352
2353          II[i] = std::pair<int, int>(Idx, INum);
2354        }
2355        for (unsigned i = 0; i < numElemH; ++i) {
2356          int Idx, INum;
2357          if (HEE) {
2358            Idx =
2359              cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2360            INum = HEE->getOperand(0) == I1 ? 0 : 1;
2361          } else {
2362            Idx = HSV->getMaskValue(i);
2363            if (Idx < (int) HOpElem) {
2364              INum = HSV->getOperand(0) == I1 ? 0 : 1;
2365            } else {
2366              Idx -= HOpElem;
2367              INum = HSV->getOperand(1) == I1 ? 0 : 1;
2368            }
2369          }
2370
2371          II[i + numElemL] = std::pair<int, int>(Idx, INum);
2372        }
2373
2374        // We now have an array which tells us from which index of which
2375        // input vector each element of the operand comes.
2376        VectorType *I1T = cast<VectorType>(I1->getType());
2377        unsigned I1Elem = I1T->getNumElements();
2378
2379        if (!I2) {
2380          // In this case there is only one underlying vector input. Check for
2381          // the trivial case where we can use the input directly.
2382          if (I1Elem == numElem) {
2383            bool ElemInOrder = true;
2384            for (unsigned i = 0; i < numElem; ++i) {
2385              if (II[i].first != (int) i && II[i].first != -1) {
2386                ElemInOrder = false;
2387                break;
2388              }
2389            }
2390
2391            if (ElemInOrder)
2392              return I1;
2393          }
2394
2395          // A shuffle is needed.
2396          std::vector<Constant *> Mask(numElem);
2397          for (unsigned i = 0; i < numElem; ++i) {
2398            int Idx = II[i].first;
2399            if (Idx == -1)
2400              Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2401            else
2402              Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2403          }
2404
2405          Instruction *S =
2406            new ShuffleVectorInst(I1, UndefValue::get(I1T),
2407                                  ConstantVector::get(Mask),
2408                                  getReplacementName(IBeforeJ ? I : J,
2409                                                     true, o));
2410          S->insertBefore(IBeforeJ ? J : I);
2411          return S;
2412        }
2413
2414        VectorType *I2T = cast<VectorType>(I2->getType());
2415        unsigned I2Elem = I2T->getNumElements();
2416
2417        // This input comes from two distinct vectors. The first step is to
2418        // make sure that both vectors are the same length. If not, the
2419        // smaller one will need to grow before they can be shuffled together.
2420        if (I1Elem < I2Elem) {
2421          std::vector<Constant *> Mask(I2Elem);
2422          unsigned v = 0;
2423          for (; v < I1Elem; ++v)
2424            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2425          for (; v < I2Elem; ++v)
2426            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2427
2428          Instruction *NewI1 =
2429            new ShuffleVectorInst(I1, UndefValue::get(I1T),
2430                                  ConstantVector::get(Mask),
2431                                  getReplacementName(IBeforeJ ? I : J,
2432                                                     true, o, 1));
2433          NewI1->insertBefore(IBeforeJ ? J : I);
2434          I1 = NewI1;
2435          I1T = I2T;
2436          I1Elem = I2Elem;
2437        } else if (I1Elem > I2Elem) {
2438          std::vector<Constant *> Mask(I1Elem);
2439          unsigned v = 0;
2440          for (; v < I2Elem; ++v)
2441            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2442          for (; v < I1Elem; ++v)
2443            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2444
2445          Instruction *NewI2 =
2446            new ShuffleVectorInst(I2, UndefValue::get(I2T),
2447                                  ConstantVector::get(Mask),
2448                                  getReplacementName(IBeforeJ ? I : J,
2449                                                     true, o, 1));
2450          NewI2->insertBefore(IBeforeJ ? J : I);
2451          I2 = NewI2;
2452          I2T = I1T;
2453          I2Elem = I1Elem;
2454        }
2455
2456        // Now that both I1 and I2 are the same length we can shuffle them
2457        // together (and use the result).
2458        std::vector<Constant *> Mask(numElem);
2459        for (unsigned v = 0; v < numElem; ++v) {
2460          if (II[v].first == -1) {
2461            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2462          } else {
2463            int Idx = II[v].first + II[v].second * I1Elem;
2464            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2465          }
2466        }
2467
2468        Instruction *NewOp =
2469          new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2470                                getReplacementName(IBeforeJ ? I : J, true, o));
2471        NewOp->insertBefore(IBeforeJ ? J : I);
2472        return NewOp;
2473      }
2474    }
2475
2476    Type *ArgType = ArgTypeL;
2477    if (numElemL < numElemH) {
2478      if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2479                                         ArgTypeL, VArgType, IBeforeJ, 1)) {
2480        // This is another short-circuit case: we're combining a scalar into
2481        // a vector that is formed by an IE chain. We've just expanded the IE
2482        // chain, now insert the scalar and we're done.
2483
2484        Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2485                           getReplacementName(IBeforeJ ? I : J, true, o));
2486        S->insertBefore(IBeforeJ ? J : I);
2487        return S;
2488      } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2489                                ArgTypeH, IBeforeJ)) {
2490        // The two vector inputs to the shuffle must be the same length,
2491        // so extend the smaller vector to be the same length as the larger one.
2492        Instruction *NLOp;
2493        if (numElemL > 1) {
2494
2495          std::vector<Constant *> Mask(numElemH);
2496          unsigned v = 0;
2497          for (; v < numElemL; ++v)
2498            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2499          for (; v < numElemH; ++v)
2500            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2501
2502          NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2503                                       ConstantVector::get(Mask),
2504                                       getReplacementName(IBeforeJ ? I : J,
2505                                                          true, o, 1));
2506        } else {
2507          NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2508                                           getReplacementName(IBeforeJ ? I : J,
2509                                                              true, o, 1));
2510        }
2511
2512        NLOp->insertBefore(IBeforeJ ? J : I);
2513        LOp = NLOp;
2514      }
2515
2516      ArgType = ArgTypeH;
2517    } else if (numElemL > numElemH) {
2518      if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2519                                         ArgTypeH, VArgType, IBeforeJ)) {
2520        Instruction *S =
2521          InsertElementInst::Create(LOp, HOp,
2522                                    ConstantInt::get(Type::getInt32Ty(Context),
2523                                                     numElemL),
2524                                    getReplacementName(IBeforeJ ? I : J,
2525                                                       true, o));
2526        S->insertBefore(IBeforeJ ? J : I);
2527        return S;
2528      } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2529                                ArgTypeL, IBeforeJ)) {
2530        Instruction *NHOp;
2531        if (numElemH > 1) {
2532          std::vector<Constant *> Mask(numElemL);
2533          unsigned v = 0;
2534          for (; v < numElemH; ++v)
2535            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2536          for (; v < numElemL; ++v)
2537            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2538
2539          NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2540                                       ConstantVector::get(Mask),
2541                                       getReplacementName(IBeforeJ ? I : J,
2542                                                          true, o, 1));
2543        } else {
2544          NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2545                                           getReplacementName(IBeforeJ ? I : J,
2546                                                              true, o, 1));
2547        }
2548
2549        NHOp->insertBefore(IBeforeJ ? J : I);
2550        HOp = NHOp;
2551      }
2552    }
2553
2554    if (ArgType->isVectorTy()) {
2555      unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2556      std::vector<Constant*> Mask(numElem);
2557      for (unsigned v = 0; v < numElem; ++v) {
2558        unsigned Idx = v;
2559        // If the low vector was expanded, we need to skip the extra
2560        // undefined entries.
2561        if (v >= numElemL && numElemH > numElemL)
2562          Idx += (numElemH - numElemL);
2563        Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2564      }
2565
2566      Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2567                          ConstantVector::get(Mask),
2568                          getReplacementName(IBeforeJ ? I : J, true, o));
2569      BV->insertBefore(IBeforeJ ? J : I);
2570      return BV;
2571    }
2572
2573    Instruction *BV1 = InsertElementInst::Create(
2574                                          UndefValue::get(VArgType), LOp, CV0,
2575                                          getReplacementName(IBeforeJ ? I : J,
2576                                                             true, o, 1));
2577    BV1->insertBefore(IBeforeJ ? J : I);
2578    Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2579                                          getReplacementName(IBeforeJ ? I : J,
2580                                                             true, o, 2));
2581    BV2->insertBefore(IBeforeJ ? J : I);
2582    return BV2;
2583  }
2584
2585  // This function creates an array of values that will be used as the inputs
2586  // to the vector instruction that fuses I with J.
2587  void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2588                     Instruction *I, Instruction *J,
2589                     SmallVector<Value *, 3> &ReplacedOperands,
2590                     bool IBeforeJ) {
2591    unsigned NumOperands = I->getNumOperands();
2592
2593    for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2594      // Iterate backward so that we look at the store pointer
2595      // first and know whether or not we need to flip the inputs.
2596
2597      if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2598        // This is the pointer for a load/store instruction.
2599        ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2600        continue;
2601      } else if (isa<CallInst>(I)) {
2602        Function *F = cast<CallInst>(I)->getCalledFunction();
2603        Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2604        if (o == NumOperands-1) {
2605          BasicBlock &BB = *I->getParent();
2606
2607          Module *M = BB.getParent()->getParent();
2608          Type *ArgTypeI = I->getType();
2609          Type *ArgTypeJ = J->getType();
2610          Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2611
2612          ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2613          continue;
2614        } else if (IID == Intrinsic::powi && o == 1) {
2615          // The second argument of powi is a single integer and we've already
2616          // checked that both arguments are equal. As a result, we just keep
2617          // I's second argument.
2618          ReplacedOperands[o] = I->getOperand(o);
2619          continue;
2620        }
2621      } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2622        ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2623        continue;
2624      }
2625
2626      ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2627    }
2628  }
2629
2630  // This function creates two values that represent the outputs of the
2631  // original I and J instructions. These are generally vector shuffles
2632  // or extracts. In many cases, these will end up being unused and, thus,
2633  // eliminated by later passes.
2634  void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2635                     Instruction *J, Instruction *K,
2636                     Instruction *&InsertionPt,
2637                     Instruction *&K1, Instruction *&K2) {
2638    if (isa<StoreInst>(I)) {
2639      AA->replaceWithNewValue(I, K);
2640      AA->replaceWithNewValue(J, K);
2641    } else {
2642      Type *IType = I->getType();
2643      Type *JType = J->getType();
2644
2645      VectorType *VType = getVecTypeForPair(IType, JType);
2646      unsigned numElem = VType->getNumElements();
2647
2648      unsigned numElemI, numElemJ;
2649      if (IType->isVectorTy())
2650        numElemI = cast<VectorType>(IType)->getNumElements();
2651      else
2652        numElemI = 1;
2653
2654      if (JType->isVectorTy())
2655        numElemJ = cast<VectorType>(JType)->getNumElements();
2656      else
2657        numElemJ = 1;
2658
2659      if (IType->isVectorTy()) {
2660        std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2661        for (unsigned v = 0; v < numElemI; ++v) {
2662          Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2663          Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2664        }
2665
2666        K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2667                                   ConstantVector::get( Mask1),
2668                                   getReplacementName(K, false, 1));
2669      } else {
2670        Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2671        K1 = ExtractElementInst::Create(K, CV0,
2672                                          getReplacementName(K, false, 1));
2673      }
2674
2675      if (JType->isVectorTy()) {
2676        std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2677        for (unsigned v = 0; v < numElemJ; ++v) {
2678          Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2679          Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2680        }
2681
2682        K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2683                                   ConstantVector::get( Mask2),
2684                                   getReplacementName(K, false, 2));
2685      } else {
2686        Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2687        K2 = ExtractElementInst::Create(K, CV1,
2688                                          getReplacementName(K, false, 2));
2689      }
2690
2691      K1->insertAfter(K);
2692      K2->insertAfter(K1);
2693      InsertionPt = K2;
2694    }
2695  }
2696
2697  // Move all uses of the function I (including pairing-induced uses) after J.
2698  bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2699                     std::multimap<Value *, Value *> &LoadMoveSet,
2700                     Instruction *I, Instruction *J) {
2701    // Skip to the first instruction past I.
2702    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2703
2704    DenseSet<Value *> Users;
2705    AliasSetTracker WriteSet(*AA);
2706    for (; cast<Instruction>(L) != J; ++L)
2707      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
2708
2709    assert(cast<Instruction>(L) == J &&
2710      "Tracking has not proceeded far enough to check for dependencies");
2711    // If J is now in the use set of I, then trackUsesOfI will return true
2712    // and we have a dependency cycle (and the fusing operation must abort).
2713    return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
2714  }
2715
2716  // Move all uses of the function I (including pairing-induced uses) after J.
2717  void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2718                     std::multimap<Value *, Value *> &LoadMoveSet,
2719                     Instruction *&InsertionPt,
2720                     Instruction *I, Instruction *J) {
2721    // Skip to the first instruction past I.
2722    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2723
2724    DenseSet<Value *> Users;
2725    AliasSetTracker WriteSet(*AA);
2726    for (; cast<Instruction>(L) != J;) {
2727      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
2728        // Move this instruction
2729        Instruction *InstToMove = L; ++L;
2730
2731        DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2732                        " to after " << *InsertionPt << "\n");
2733        InstToMove->removeFromParent();
2734        InstToMove->insertAfter(InsertionPt);
2735        InsertionPt = InstToMove;
2736      } else {
2737        ++L;
2738      }
2739    }
2740  }
2741
2742  // Collect all load instruction that are in the move set of a given first
2743  // pair member.  These loads depend on the first instruction, I, and so need
2744  // to be moved after J (the second instruction) when the pair is fused.
2745  void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2746                     DenseMap<Value *, Value *> &ChosenPairs,
2747                     std::multimap<Value *, Value *> &LoadMoveSet,
2748                     Instruction *I) {
2749    // Skip to the first instruction past I.
2750    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2751
2752    DenseSet<Value *> Users;
2753    AliasSetTracker WriteSet(*AA);
2754
2755    // Note: We cannot end the loop when we reach J because J could be moved
2756    // farther down the use chain by another instruction pairing. Also, J
2757    // could be before I if this is an inverted input.
2758    for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2759      if (trackUsesOfI(Users, WriteSet, I, L)) {
2760        if (L->mayReadFromMemory())
2761          LoadMoveSet.insert(ValuePair(L, I));
2762      }
2763    }
2764  }
2765
2766  // In cases where both load/stores and the computation of their pointers
2767  // are chosen for vectorization, we can end up in a situation where the
2768  // aliasing analysis starts returning different query results as the
2769  // process of fusing instruction pairs continues. Because the algorithm
2770  // relies on finding the same use trees here as were found earlier, we'll
2771  // need to precompute the necessary aliasing information here and then
2772  // manually update it during the fusion process.
2773  void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2774                     std::vector<Value *> &PairableInsts,
2775                     DenseMap<Value *, Value *> &ChosenPairs,
2776                     std::multimap<Value *, Value *> &LoadMoveSet) {
2777    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2778         PIE = PairableInsts.end(); PI != PIE; ++PI) {
2779      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2780      if (P == ChosenPairs.end()) continue;
2781
2782      Instruction *I = cast<Instruction>(P->first);
2783      collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
2784    }
2785  }
2786
2787  // When the first instruction in each pair is cloned, it will inherit its
2788  // parent's metadata. This metadata must be combined with that of the other
2789  // instruction in a safe way.
2790  void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2791    SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2792    K->getAllMetadataOtherThanDebugLoc(Metadata);
2793    for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2794      unsigned Kind = Metadata[i].first;
2795      MDNode *JMD = J->getMetadata(Kind);
2796      MDNode *KMD = Metadata[i].second;
2797
2798      switch (Kind) {
2799      default:
2800        K->setMetadata(Kind, 0); // Remove unknown metadata
2801        break;
2802      case LLVMContext::MD_tbaa:
2803        K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2804        break;
2805      case LLVMContext::MD_fpmath:
2806        K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2807        break;
2808      }
2809    }
2810  }
2811
2812  // This function fuses the chosen instruction pairs into vector instructions,
2813  // taking care preserve any needed scalar outputs and, then, it reorders the
2814  // remaining instructions as needed (users of the first member of the pair
2815  // need to be moved to after the location of the second member of the pair
2816  // because the vector instruction is inserted in the location of the pair's
2817  // second member).
2818  void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2819                     std::vector<Value *> &PairableInsts,
2820                     DenseMap<Value *, Value *> &ChosenPairs,
2821                     DenseSet<ValuePair> &FixedOrderPairs,
2822                     DenseMap<VPPair, unsigned> &PairConnectionTypes,
2823                     std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2824                     std::multimap<ValuePair, ValuePair> &ConnectedPairDeps) {
2825    LLVMContext& Context = BB.getContext();
2826
2827    // During the vectorization process, the order of the pairs to be fused
2828    // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2829    // list. After a pair is fused, the flipped pair is removed from the list.
2830    DenseSet<ValuePair> FlippedPairs;
2831    for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2832         E = ChosenPairs.end(); P != E; ++P)
2833      FlippedPairs.insert(ValuePair(P->second, P->first));
2834    for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2835         E = FlippedPairs.end(); P != E; ++P)
2836      ChosenPairs.insert(*P);
2837
2838    std::multimap<Value *, Value *> LoadMoveSet;
2839    collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2840
2841    DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2842
2843    for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2844      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2845      if (P == ChosenPairs.end()) {
2846        ++PI;
2847        continue;
2848      }
2849
2850      if (getDepthFactor(P->first) == 0) {
2851        // These instructions are not really fused, but are tracked as though
2852        // they are. Any case in which it would be interesting to fuse them
2853        // will be taken care of by InstCombine.
2854        --NumFusedOps;
2855        ++PI;
2856        continue;
2857      }
2858
2859      Instruction *I = cast<Instruction>(P->first),
2860        *J = cast<Instruction>(P->second);
2861
2862      DEBUG(dbgs() << "BBV: fusing: " << *I <<
2863             " <-> " << *J << "\n");
2864
2865      // Remove the pair and flipped pair from the list.
2866      DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2867      assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2868      ChosenPairs.erase(FP);
2869      ChosenPairs.erase(P);
2870
2871      if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2872        DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2873               " <-> " << *J <<
2874               " aborted because of non-trivial dependency cycle\n");
2875        --NumFusedOps;
2876        ++PI;
2877        continue;
2878      }
2879
2880      // If the pair must have the other order, then flip it.
2881      bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2882      if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2883        // This pair does not have a fixed order, and so we might want to
2884        // flip it if that will yield fewer shuffles. We count the number
2885        // of dependencies connected via swaps, and those directly connected,
2886        // and flip the order if the number of swaps is greater.
2887        bool OrigOrder = true;
2888        VPPIteratorPair IP = ConnectedPairDeps.equal_range(ValuePair(I, J));
2889        if (IP.first == ConnectedPairDeps.end()) {
2890          IP = ConnectedPairDeps.equal_range(ValuePair(J, I));
2891          OrigOrder = false;
2892        }
2893
2894        if (IP.first != ConnectedPairDeps.end()) {
2895          unsigned NumDepsDirect = 0, NumDepsSwap = 0;
2896          for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2897               Q != IP.second; ++Q) {
2898            DenseMap<VPPair, unsigned>::iterator R =
2899              PairConnectionTypes.find(VPPair(Q->second, Q->first));
2900            assert(R != PairConnectionTypes.end() &&
2901                   "Cannot find pair connection type");
2902            if (R->second == PairConnectionDirect)
2903              ++NumDepsDirect;
2904            else if (R->second == PairConnectionSwap)
2905              ++NumDepsSwap;
2906          }
2907
2908          if (!OrigOrder)
2909            std::swap(NumDepsDirect, NumDepsSwap);
2910
2911          if (NumDepsSwap > NumDepsDirect) {
2912            FlipPairOrder = true;
2913            DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
2914                            " <-> " << *J << "\n");
2915          }
2916        }
2917      }
2918
2919      Instruction *L = I, *H = J;
2920      if (FlipPairOrder)
2921        std::swap(H, L);
2922
2923      // If the pair being fused uses the opposite order from that in the pair
2924      // connection map, then we need to flip the types.
2925      VPPIteratorPair IP = ConnectedPairs.equal_range(ValuePair(H, L));
2926      for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2927           Q != IP.second; ++Q) {
2928        DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(*Q);
2929        assert(R != PairConnectionTypes.end() &&
2930               "Cannot find pair connection type");
2931        if (R->second == PairConnectionDirect)
2932          R->second = PairConnectionSwap;
2933        else if (R->second == PairConnectionSwap)
2934          R->second = PairConnectionDirect;
2935      }
2936
2937      bool LBeforeH = !FlipPairOrder;
2938      unsigned NumOperands = I->getNumOperands();
2939      SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2940      getReplacementInputsForPair(Context, L, H, ReplacedOperands,
2941                                  LBeforeH);
2942
2943      // Make a copy of the original operation, change its type to the vector
2944      // type and replace its operands with the vector operands.
2945      Instruction *K = L->clone();
2946      if (L->hasName())
2947        K->takeName(L);
2948      else if (H->hasName())
2949        K->takeName(H);
2950
2951      if (!isa<StoreInst>(K))
2952        K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
2953
2954      combineMetadata(K, H);
2955      K->intersectOptionalDataWith(H);
2956
2957      for (unsigned o = 0; o < NumOperands; ++o)
2958        K->setOperand(o, ReplacedOperands[o]);
2959
2960      K->insertAfter(J);
2961
2962      // Instruction insertion point:
2963      Instruction *InsertionPt = K;
2964      Instruction *K1 = 0, *K2 = 0;
2965      replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
2966
2967      // The use tree of the first original instruction must be moved to after
2968      // the location of the second instruction. The entire use tree of the
2969      // first instruction is disjoint from the input tree of the second
2970      // (by definition), and so commutes with it.
2971
2972      moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2973
2974      if (!isa<StoreInst>(I)) {
2975        L->replaceAllUsesWith(K1);
2976        H->replaceAllUsesWith(K2);
2977        AA->replaceWithNewValue(L, K1);
2978        AA->replaceWithNewValue(H, K2);
2979      }
2980
2981      // Instructions that may read from memory may be in the load move set.
2982      // Once an instruction is fused, we no longer need its move set, and so
2983      // the values of the map never need to be updated. However, when a load
2984      // is fused, we need to merge the entries from both instructions in the
2985      // pair in case those instructions were in the move set of some other
2986      // yet-to-be-fused pair. The loads in question are the keys of the map.
2987      if (I->mayReadFromMemory()) {
2988        std::vector<ValuePair> NewSetMembers;
2989        VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
2990        VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
2991        for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
2992             N != IPairRange.second; ++N)
2993          NewSetMembers.push_back(ValuePair(K, N->second));
2994        for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
2995             N != JPairRange.second; ++N)
2996          NewSetMembers.push_back(ValuePair(K, N->second));
2997        for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
2998             AE = NewSetMembers.end(); A != AE; ++A)
2999          LoadMoveSet.insert(*A);
3000      }
3001
3002      // Before removing I, set the iterator to the next instruction.
3003      PI = llvm::next(BasicBlock::iterator(I));
3004      if (cast<Instruction>(PI) == J)
3005        ++PI;
3006
3007      SE->forgetValue(I);
3008      SE->forgetValue(J);
3009      I->eraseFromParent();
3010      J->eraseFromParent();
3011
3012      DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3013                                               BB << "\n");
3014    }
3015
3016    DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3017  }
3018}
3019
3020char BBVectorize::ID = 0;
3021static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3022INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3023INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3024INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3025INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3026INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3027INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3028
3029BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3030  return new BBVectorize(C);
3031}
3032
3033bool
3034llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3035  BBVectorize BBVectorizer(P, C);
3036  return BBVectorizer.vectorizeBB(BB);
3037}
3038
3039//===----------------------------------------------------------------------===//
3040VectorizeConfig::VectorizeConfig() {
3041  VectorBits = ::VectorBits;
3042  VectorizeBools = !::NoBools;
3043  VectorizeInts = !::NoInts;
3044  VectorizeFloats = !::NoFloats;
3045  VectorizePointers = !::NoPointers;
3046  VectorizeCasts = !::NoCasts;
3047  VectorizeMath = !::NoMath;
3048  VectorizeFMA = !::NoFMA;
3049  VectorizeSelect = !::NoSelect;
3050  VectorizeCmp = !::NoCmp;
3051  VectorizeGEP = !::NoGEP;
3052  VectorizeMemOps = !::NoMemOps;
3053  AlignedOnly = ::AlignedOnly;
3054  ReqChainDepth= ::ReqChainDepth;
3055  SearchLimit = ::SearchLimit;
3056  MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3057  SplatBreaksChain = ::SplatBreaksChain;
3058  MaxInsts = ::MaxInsts;
3059  MaxIter = ::MaxIter;
3060  Pow2LenOnly = ::Pow2LenOnly;
3061  NoMemOpBoost = ::NoMemOpBoost;
3062  FastDep = ::FastDep;
3063}
3064