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