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