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