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