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