OSDN Git Service

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