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