1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 //===----------------------------------------------------------------------===//
17 #define BBV_NAME "bb-vectorize"
18 #define DEBUG_TYPE BBV_NAME
19 #include "llvm/Transforms/Vectorize.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/AliasSetTracker.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/ScalarEvolution.h"
31 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ValueHandle.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Utils/Local.h"
55 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
56 cl::Hidden, cl::desc("Ignore target information"));
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"));
63 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
64 cl::Hidden, cl::desc("Use the chain depth requirement with"
65 " target information"));
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"));
72 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
73 cl::desc("Replicating one element to a pair breaks the chain"));
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"));
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"));
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"));
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"));
91 static cl::opt<unsigned>
92 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
93 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
94 " a full cycle check"));
97 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
98 cl::desc("Don't try to vectorize boolean (i1) values"));
101 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
102 cl::desc("Don't try to vectorize integer values"));
105 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
106 cl::desc("Don't try to vectorize floating-point values"));
108 // FIXME: This should default to false once pointer vector support works.
110 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
111 cl::desc("Don't try to vectorize pointer values"));
114 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
115 cl::desc("Don't try to vectorize casting (conversion) operations"));
118 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
119 cl::desc("Don't try to vectorize floating-point math intrinsics"));
122 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
123 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
126 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
127 cl::desc("Don't try to vectorize select instructions"));
130 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
131 cl::desc("Don't try to vectorize comparison instructions"));
134 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
135 cl::desc("Don't try to vectorize getelementptr instructions"));
138 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
139 cl::desc("Don't try to vectorize loads and stores"));
142 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
143 cl::desc("Only generate aligned loads and stores"));
146 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
147 cl::init(false), cl::Hidden,
148 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
151 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
152 cl::desc("Use a fast instruction dependency analysis"));
156 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
157 cl::init(false), cl::Hidden,
158 cl::desc("When debugging is enabled, output information on the"
159 " instruction-examination process"));
161 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
162 cl::init(false), cl::Hidden,
163 cl::desc("When debugging is enabled, output information on the"
164 " candidate-selection process"));
166 DebugPairSelection("bb-vectorize-debug-pair-selection",
167 cl::init(false), cl::Hidden,
168 cl::desc("When debugging is enabled, output information on the"
169 " pair-selection process"));
171 DebugCycleCheck("bb-vectorize-debug-cycle-check",
172 cl::init(false), cl::Hidden,
173 cl::desc("When debugging is enabled, output information on the"
174 " cycle-checking process"));
177 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
178 cl::init(false), cl::Hidden,
179 cl::desc("When debugging is enabled, dump the basic block after"
180 " every pair is fused"));
183 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
186 struct BBVectorize : public BasicBlockPass {
187 static char ID; // Pass identification, replacement for typeid
189 const VectorizeConfig Config;
191 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
192 : BasicBlockPass(ID), Config(C) {
193 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
196 BBVectorize(Pass *P, const VectorizeConfig &C)
197 : BasicBlockPass(ID), Config(C) {
198 AA = &P->getAnalysis<AliasAnalysis>();
199 DT = &P->getAnalysis<DominatorTree>();
200 SE = &P->getAnalysis<ScalarEvolution>();
201 TD = P->getAnalysisIfAvailable<DataLayout>();
202 TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
205 typedef std::pair<Value *, Value *> ValuePair;
206 typedef std::pair<ValuePair, int> ValuePairWithCost;
207 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
208 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
209 typedef std::pair<VPPair, unsigned> VPPairWithType;
210 typedef std::pair<std::multimap<Value *, Value *>::iterator,
211 std::multimap<Value *, Value *>::iterator> VPIteratorPair;
212 typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
213 std::multimap<ValuePair, ValuePair>::iterator>
220 const TargetTransformInfo *TTI;
222 // FIXME: const correct?
224 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
226 bool getCandidatePairs(BasicBlock &BB,
227 BasicBlock::iterator &Start,
228 std::multimap<Value *, Value *> &CandidatePairs,
229 DenseSet<ValuePair> &FixedOrderPairs,
230 DenseMap<ValuePair, int> &CandidatePairCostSavings,
231 std::vector<Value *> &PairableInsts, bool NonPow2Len);
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,
242 void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
243 std::vector<Value *> &PairableInsts,
244 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
245 DenseMap<VPPair, unsigned> &PairConnectionTypes);
247 void buildDepMap(BasicBlock &BB,
248 std::multimap<Value *, Value *> &CandidatePairs,
249 std::vector<Value *> &PairableInsts,
250 DenseSet<ValuePair> &PairableInstUsers);
252 void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
253 DenseMap<ValuePair, int> &CandidatePairCostSavings,
254 std::vector<Value *> &PairableInsts,
255 DenseSet<ValuePair> &FixedOrderPairs,
256 DenseMap<VPPair, unsigned> &PairConnectionTypes,
257 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
258 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
259 DenseSet<ValuePair> &PairableInstUsers,
260 DenseMap<Value *, Value *>& ChosenPairs);
262 void fuseChosenPairs(BasicBlock &BB,
263 std::vector<Value *> &PairableInsts,
264 DenseMap<Value *, Value *>& ChosenPairs,
265 DenseSet<ValuePair> &FixedOrderPairs,
266 DenseMap<VPPair, unsigned> &PairConnectionTypes,
267 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
268 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps);
271 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
273 bool areInstsCompatible(Instruction *I, Instruction *J,
274 bool IsSimpleLoadStore, bool NonPow2Len,
275 int &CostSavings, int &FixedOrder);
277 bool trackUsesOfI(DenseSet<Value *> &Users,
278 AliasSetTracker &WriteSet, Instruction *I,
279 Instruction *J, bool UpdateUsers = true,
280 DenseSet<ValuePair> *LoadMoveSetPairs = 0);
282 void computePairsConnectedTo(
283 std::multimap<Value *, Value *> &CandidatePairs,
284 std::vector<Value *> &PairableInsts,
285 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
286 DenseMap<VPPair, unsigned> &PairConnectionTypes,
289 bool pairsConflict(ValuePair P, ValuePair Q,
290 DenseSet<ValuePair> &PairableInstUsers,
291 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0,
292 DenseSet<VPPair> *PairableInstUserPairSet = 0);
294 bool pairWillFormCycle(ValuePair P,
295 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
296 DenseSet<ValuePair> &CurrentPairs);
299 std::multimap<Value *, Value *> &CandidatePairs,
300 std::vector<Value *> &PairableInsts,
301 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
302 DenseSet<ValuePair> &PairableInstUsers,
303 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
304 DenseSet<VPPair> &PairableInstUserPairSet,
305 DenseMap<Value *, Value *> &ChosenPairs,
306 DenseMap<ValuePair, size_t> &Tree,
307 DenseSet<ValuePair> &PrunedTree, ValuePair J,
310 void buildInitialTreeFor(
311 std::multimap<Value *, Value *> &CandidatePairs,
312 std::vector<Value *> &PairableInsts,
313 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
314 DenseSet<ValuePair> &PairableInstUsers,
315 DenseMap<Value *, Value *> &ChosenPairs,
316 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
318 void findBestTreeFor(
319 std::multimap<Value *, Value *> &CandidatePairs,
320 DenseMap<ValuePair, int> &CandidatePairCostSavings,
321 std::vector<Value *> &PairableInsts,
322 DenseSet<ValuePair> &FixedOrderPairs,
323 DenseMap<VPPair, unsigned> &PairConnectionTypes,
324 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
325 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
326 DenseSet<ValuePair> &PairableInstUsers,
327 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
328 DenseSet<VPPair> &PairableInstUserPairSet,
329 DenseMap<Value *, Value *> &ChosenPairs,
330 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
331 int &BestEffSize, VPIteratorPair ChoiceRange,
334 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
335 Instruction *J, unsigned o);
337 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
338 unsigned MaskOffset, unsigned NumInElem,
339 unsigned NumInElem1, unsigned IdxOffset,
340 std::vector<Constant*> &Mask);
342 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
345 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
346 unsigned o, Value *&LOp, unsigned numElemL,
347 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
348 unsigned IdxOff = 0);
350 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
351 Instruction *J, unsigned o, bool IBeforeJ);
353 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
354 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
357 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
358 Instruction *J, Instruction *K,
359 Instruction *&InsertionPt, Instruction *&K1,
362 void collectPairLoadMoveSet(BasicBlock &BB,
363 DenseMap<Value *, Value *> &ChosenPairs,
364 std::multimap<Value *, Value *> &LoadMoveSet,
365 DenseSet<ValuePair> &LoadMoveSetPairs,
368 void collectLoadMoveSet(BasicBlock &BB,
369 std::vector<Value *> &PairableInsts,
370 DenseMap<Value *, Value *> &ChosenPairs,
371 std::multimap<Value *, Value *> &LoadMoveSet,
372 DenseSet<ValuePair> &LoadMoveSetPairs);
374 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
375 DenseSet<ValuePair> &LoadMoveSetPairs,
376 Instruction *I, Instruction *J);
378 void moveUsesOfIAfterJ(BasicBlock &BB,
379 DenseSet<ValuePair> &LoadMoveSetPairs,
380 Instruction *&InsertionPt,
381 Instruction *I, Instruction *J);
383 void combineMetadata(Instruction *K, const Instruction *J);
385 bool vectorizeBB(BasicBlock &BB) {
386 if (!DT->isReachableFromEntry(&BB)) {
387 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
388 " in " << BB.getParent()->getName() << "\n");
392 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
394 bool changed = false;
395 // Iterate a sufficient number of times to merge types of size 1 bit,
396 // then 2 bits, then 4, etc. up to half of the target vector width of the
397 // target vector register.
400 (TTI || v <= Config.VectorBits) &&
401 (!Config.MaxIter || n <= Config.MaxIter);
403 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
404 " for " << BB.getName() << " in " <<
405 BB.getParent()->getName() << "...\n");
406 if (vectorizePairs(BB))
412 if (changed && !Pow2LenOnly) {
414 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
415 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
416 n << " for " << BB.getName() << " in " <<
417 BB.getParent()->getName() << "...\n");
418 if (!vectorizePairs(BB, true)) break;
422 DEBUG(dbgs() << "BBV: done!\n");
426 virtual bool runOnBasicBlock(BasicBlock &BB) {
427 AA = &getAnalysis<AliasAnalysis>();
428 DT = &getAnalysis<DominatorTree>();
429 SE = &getAnalysis<ScalarEvolution>();
430 TD = getAnalysisIfAvailable<DataLayout>();
431 TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
433 return vectorizeBB(BB);
436 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
437 BasicBlockPass::getAnalysisUsage(AU);
438 AU.addRequired<AliasAnalysis>();
439 AU.addRequired<DominatorTree>();
440 AU.addRequired<ScalarEvolution>();
441 AU.addRequired<TargetTransformInfo>();
442 AU.addPreserved<AliasAnalysis>();
443 AU.addPreserved<DominatorTree>();
444 AU.addPreserved<ScalarEvolution>();
445 AU.setPreservesCFG();
448 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
449 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
450 "Cannot form vector from incompatible scalar types");
451 Type *STy = ElemTy->getScalarType();
454 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
455 numElem = VTy->getNumElements();
460 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
461 numElem += VTy->getNumElements();
466 return VectorType::get(STy, numElem);
469 static inline void getInstructionTypes(Instruction *I,
470 Type *&T1, Type *&T2) {
471 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
472 // For stores, it is the value type, not the pointer type that matters
473 // because the value is what will come from a vector register.
475 Value *IVal = SI->getValueOperand();
476 T1 = IVal->getType();
481 if (CastInst *CI = dyn_cast<CastInst>(I))
486 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
487 T2 = SI->getCondition()->getType();
488 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
489 T2 = SI->getOperand(0)->getType();
490 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
491 T2 = CI->getOperand(0)->getType();
495 // Returns the weight associated with the provided value. A chain of
496 // candidate pairs has a length given by the sum of the weights of its
497 // members (one weight per pair; the weight of each member of the pair
498 // is assumed to be the same). This length is then compared to the
499 // chain-length threshold to determine if a given chain is significant
500 // enough to be vectorized. The length is also used in comparing
501 // candidate chains where longer chains are considered to be better.
502 // Note: when this function returns 0, the resulting instructions are
503 // not actually fused.
504 inline size_t getDepthFactor(Value *V) {
505 // InsertElement and ExtractElement have a depth factor of zero. This is
506 // for two reasons: First, they cannot be usefully fused. Second, because
507 // the pass generates a lot of these, they can confuse the simple metric
508 // used to compare the trees in the next iteration. Thus, giving them a
509 // weight of zero allows the pass to essentially ignore them in
510 // subsequent iterations when looking for vectorization opportunities
511 // while still tracking dependency chains that flow through those
513 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
516 // Give a load or store half of the required depth so that load/store
517 // pairs will vectorize.
518 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
519 return Config.ReqChainDepth/2;
524 // Returns the cost of the provided instruction using TTI.
525 // This does not handle loads and stores.
526 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
529 case Instruction::GetElementPtr:
530 // We mark this instruction as zero-cost because scalar GEPs are usually
531 // lowered to the intruction addressing mode. At the moment we don't
532 // generate vector GEPs.
534 case Instruction::Br:
535 return TTI->getCFInstrCost(Opcode);
536 case Instruction::PHI:
538 case Instruction::Add:
539 case Instruction::FAdd:
540 case Instruction::Sub:
541 case Instruction::FSub:
542 case Instruction::Mul:
543 case Instruction::FMul:
544 case Instruction::UDiv:
545 case Instruction::SDiv:
546 case Instruction::FDiv:
547 case Instruction::URem:
548 case Instruction::SRem:
549 case Instruction::FRem:
550 case Instruction::Shl:
551 case Instruction::LShr:
552 case Instruction::AShr:
553 case Instruction::And:
554 case Instruction::Or:
555 case Instruction::Xor:
556 return TTI->getArithmeticInstrCost(Opcode, T1);
557 case Instruction::Select:
558 case Instruction::ICmp:
559 case Instruction::FCmp:
560 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
561 case Instruction::ZExt:
562 case Instruction::SExt:
563 case Instruction::FPToUI:
564 case Instruction::FPToSI:
565 case Instruction::FPExt:
566 case Instruction::PtrToInt:
567 case Instruction::IntToPtr:
568 case Instruction::SIToFP:
569 case Instruction::UIToFP:
570 case Instruction::Trunc:
571 case Instruction::FPTrunc:
572 case Instruction::BitCast:
573 case Instruction::ShuffleVector:
574 return TTI->getCastInstrCost(Opcode, T1, T2);
580 // This determines the relative offset of two loads or stores, returning
581 // true if the offset could be determined to be some constant value.
582 // For example, if OffsetInElmts == 1, then J accesses the memory directly
583 // after I; if OffsetInElmts == -1 then I accesses the memory
585 bool getPairPtrInfo(Instruction *I, Instruction *J,
586 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
587 unsigned &IAddressSpace, unsigned &JAddressSpace,
588 int64_t &OffsetInElmts, bool ComputeOffset = true) {
590 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
591 LoadInst *LJ = cast<LoadInst>(J);
592 IPtr = LI->getPointerOperand();
593 JPtr = LJ->getPointerOperand();
594 IAlignment = LI->getAlignment();
595 JAlignment = LJ->getAlignment();
596 IAddressSpace = LI->getPointerAddressSpace();
597 JAddressSpace = LJ->getPointerAddressSpace();
599 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
600 IPtr = SI->getPointerOperand();
601 JPtr = SJ->getPointerOperand();
602 IAlignment = SI->getAlignment();
603 JAlignment = SJ->getAlignment();
604 IAddressSpace = SI->getPointerAddressSpace();
605 JAddressSpace = SJ->getPointerAddressSpace();
611 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
612 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
614 // If this is a trivial offset, then we'll get something like
615 // 1*sizeof(type). With target data, which we need anyway, this will get
616 // constant folded into a number.
617 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
618 if (const SCEVConstant *ConstOffSCEV =
619 dyn_cast<SCEVConstant>(OffsetSCEV)) {
620 ConstantInt *IntOff = ConstOffSCEV->getValue();
621 int64_t Offset = IntOff->getSExtValue();
623 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
624 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
626 Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
627 if (VTy != VTy2 && Offset < 0) {
628 int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
629 OffsetInElmts = Offset/VTy2TSS;
630 return (abs64(Offset) % VTy2TSS) == 0;
633 OffsetInElmts = Offset/VTyTSS;
634 return (abs64(Offset) % VTyTSS) == 0;
640 // Returns true if the provided CallInst represents an intrinsic that can
642 bool isVectorizableIntrinsic(CallInst* I) {
643 Function *F = I->getCalledFunction();
644 if (!F) return false;
646 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
647 if (!IID) return false;
652 case Intrinsic::sqrt:
653 case Intrinsic::powi:
657 case Intrinsic::log2:
658 case Intrinsic::log10:
660 case Intrinsic::exp2:
662 return Config.VectorizeMath;
664 case Intrinsic::fmuladd:
665 return Config.VectorizeFMA;
669 // Returns true if J is the second element in some pair referenced by
670 // some multimap pair iterator pair.
671 template <typename V>
672 bool isSecondInIteratorPair(V J, std::pair<
673 typename std::multimap<V, V>::iterator,
674 typename std::multimap<V, V>::iterator> PairRange) {
675 for (typename std::multimap<V, V>::iterator K = PairRange.first;
676 K != PairRange.second; ++K)
677 if (K->second == J) return true;
682 bool isPureIEChain(InsertElementInst *IE) {
683 InsertElementInst *IENext = IE;
685 if (!isa<UndefValue>(IENext->getOperand(0)) &&
686 !isa<InsertElementInst>(IENext->getOperand(0))) {
690 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
696 // This function implements one vectorization iteration on the provided
697 // basic block. It returns true if the block is changed.
698 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
700 BasicBlock::iterator Start = BB.getFirstInsertionPt();
702 std::vector<Value *> AllPairableInsts;
703 DenseMap<Value *, Value *> AllChosenPairs;
704 DenseSet<ValuePair> AllFixedOrderPairs;
705 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
706 std::multimap<ValuePair, ValuePair> AllConnectedPairs, AllConnectedPairDeps;
709 std::vector<Value *> PairableInsts;
710 std::multimap<Value *, Value *> CandidatePairs;
711 DenseSet<ValuePair> FixedOrderPairs;
712 DenseMap<ValuePair, int> CandidatePairCostSavings;
713 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
715 CandidatePairCostSavings,
716 PairableInsts, NonPow2Len);
717 if (PairableInsts.empty()) continue;
719 // Now we have a map of all of the pairable instructions and we need to
720 // select the best possible pairing. A good pairing is one such that the
721 // users of the pair are also paired. This defines a (directed) forest
722 // over the pairs such that two pairs are connected iff the second pair
725 // Note that it only matters that both members of the second pair use some
726 // element of the first pair (to allow for splatting).
728 std::multimap<ValuePair, ValuePair> ConnectedPairs, ConnectedPairDeps;
729 DenseMap<VPPair, unsigned> PairConnectionTypes;
730 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs,
731 PairConnectionTypes);
732 if (ConnectedPairs.empty()) continue;
734 for (std::multimap<ValuePair, ValuePair>::iterator
735 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
737 ConnectedPairDeps.insert(VPPair(I->second, I->first));
740 // Build the pairable-instruction dependency map
741 DenseSet<ValuePair> PairableInstUsers;
742 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
744 // There is now a graph of the connected pairs. For each variable, pick
745 // the pairing with the largest tree meeting the depth requirement on at
746 // least one branch. Then select all pairings that are part of that tree
747 // and remove them from the list of available pairings and pairable
750 DenseMap<Value *, Value *> ChosenPairs;
751 choosePairs(CandidatePairs, CandidatePairCostSavings,
752 PairableInsts, FixedOrderPairs, PairConnectionTypes,
753 ConnectedPairs, ConnectedPairDeps,
754 PairableInstUsers, ChosenPairs);
756 if (ChosenPairs.empty()) continue;
757 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
758 PairableInsts.end());
759 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
761 // Only for the chosen pairs, propagate information on fixed-order pairs,
762 // pair connections, and their types to the data structures used by the
763 // pair fusion procedures.
764 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
765 IE = ChosenPairs.end(); I != IE; ++I) {
766 if (FixedOrderPairs.count(*I))
767 AllFixedOrderPairs.insert(*I);
768 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
769 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
771 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
773 DenseMap<VPPair, unsigned>::iterator K =
774 PairConnectionTypes.find(VPPair(*I, *J));
775 if (K != PairConnectionTypes.end()) {
776 AllPairConnectionTypes.insert(*K);
778 K = PairConnectionTypes.find(VPPair(*J, *I));
779 if (K != PairConnectionTypes.end())
780 AllPairConnectionTypes.insert(*K);
785 for (std::multimap<ValuePair, ValuePair>::iterator
786 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
788 if (AllPairConnectionTypes.count(*I)) {
789 AllConnectedPairs.insert(*I);
790 AllConnectedPairDeps.insert(VPPair(I->second, I->first));
793 } while (ShouldContinue);
795 if (AllChosenPairs.empty()) return false;
796 NumFusedOps += AllChosenPairs.size();
798 // A set of pairs has now been selected. It is now necessary to replace the
799 // paired instructions with vector instructions. For this procedure each
800 // operand must be replaced with a vector operand. This vector is formed
801 // by using build_vector on the old operands. The replaced values are then
802 // replaced with a vector_extract on the result. Subsequent optimization
803 // passes should coalesce the build/extract combinations.
805 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
806 AllPairConnectionTypes,
807 AllConnectedPairs, AllConnectedPairDeps);
809 // It is important to cleanup here so that future iterations of this
810 // function have less work to do.
811 (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
815 // This function returns true if the provided instruction is capable of being
816 // fused into a vector instruction. This determination is based only on the
817 // type and other attributes of the instruction.
818 bool BBVectorize::isInstVectorizable(Instruction *I,
819 bool &IsSimpleLoadStore) {
820 IsSimpleLoadStore = false;
822 if (CallInst *C = dyn_cast<CallInst>(I)) {
823 if (!isVectorizableIntrinsic(C))
825 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
826 // Vectorize simple loads if possbile:
827 IsSimpleLoadStore = L->isSimple();
828 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
830 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
831 // Vectorize simple stores if possbile:
832 IsSimpleLoadStore = S->isSimple();
833 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
835 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
836 // We can vectorize casts, but not casts of pointer types, etc.
837 if (!Config.VectorizeCasts)
840 Type *SrcTy = C->getSrcTy();
841 if (!SrcTy->isSingleValueType())
844 Type *DestTy = C->getDestTy();
845 if (!DestTy->isSingleValueType())
847 } else if (isa<SelectInst>(I)) {
848 if (!Config.VectorizeSelect)
850 } else if (isa<CmpInst>(I)) {
851 if (!Config.VectorizeCmp)
853 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
854 if (!Config.VectorizeGEP)
857 // Currently, vector GEPs exist only with one index.
858 if (G->getNumIndices() != 1)
860 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
861 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
865 // We can't vectorize memory operations without target data
866 if (TD == 0 && IsSimpleLoadStore)
870 getInstructionTypes(I, T1, T2);
872 // Not every type can be vectorized...
873 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
874 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
877 if (T1->getScalarSizeInBits() == 1) {
878 if (!Config.VectorizeBools)
881 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
885 if (T2->getScalarSizeInBits() == 1) {
886 if (!Config.VectorizeBools)
889 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
893 if (!Config.VectorizeFloats
894 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
897 // Don't vectorize target-specific types.
898 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
900 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
903 if ((!Config.VectorizePointers || TD == 0) &&
904 (T1->getScalarType()->isPointerTy() ||
905 T2->getScalarType()->isPointerTy()))
908 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
909 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
915 // This function returns true if the two provided instructions are compatible
916 // (meaning that they can be fused into a vector instruction). This assumes
917 // that I has already been determined to be vectorizable and that J is not
918 // in the use tree of I.
919 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
920 bool IsSimpleLoadStore, bool NonPow2Len,
921 int &CostSavings, int &FixedOrder) {
922 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
923 " <-> " << *J << "\n");
928 // Loads and stores can be merged if they have different alignments,
929 // but are otherwise the same.
930 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
931 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
934 Type *IT1, *IT2, *JT1, *JT2;
935 getInstructionTypes(I, IT1, IT2);
936 getInstructionTypes(J, JT1, JT2);
937 unsigned MaxTypeBits = std::max(
938 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
939 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
940 if (!TTI && MaxTypeBits > Config.VectorBits)
943 // FIXME: handle addsub-type operations!
945 if (IsSimpleLoadStore) {
947 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
948 int64_t OffsetInElmts = 0;
949 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
950 IAddressSpace, JAddressSpace,
951 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
952 FixedOrder = (int) OffsetInElmts;
953 unsigned BottomAlignment = IAlignment;
954 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
956 Type *aTypeI = isa<StoreInst>(I) ?
957 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
958 Type *aTypeJ = isa<StoreInst>(J) ?
959 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
960 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
962 if (Config.AlignedOnly) {
963 // An aligned load or store is possible only if the instruction
964 // with the lower offset has an alignment suitable for the
967 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
968 if (BottomAlignment < VecAlignment)
973 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
974 IAlignment, IAddressSpace);
975 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
976 JAlignment, JAddressSpace);
977 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
981 ICost += TTI->getAddressComputationCost(aTypeI);
982 JCost += TTI->getAddressComputationCost(aTypeJ);
983 VCost += TTI->getAddressComputationCost(VType);
985 if (VCost > ICost + JCost)
988 // We don't want to fuse to a type that will be split, even
989 // if the two input types will also be split and there is no other
991 unsigned VParts = TTI->getNumberOfParts(VType);
994 else if (!VParts && VCost == ICost + JCost)
997 CostSavings = ICost + JCost - VCost;
1003 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1004 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1005 Type *VT1 = getVecTypeForPair(IT1, JT1),
1006 *VT2 = getVecTypeForPair(IT2, JT2);
1008 // Note that this procedure is incorrect for insert and extract element
1009 // instructions (because combining these often results in a shuffle),
1010 // but this cost is ignored (because insert and extract element
1011 // instructions are assigned a zero depth factor and are not really
1012 // fused in general).
1013 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
1015 if (VCost > ICost + JCost)
1018 // We don't want to fuse to a type that will be split, even
1019 // if the two input types will also be split and there is no other
1021 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1022 VParts2 = TTI->getNumberOfParts(VT2);
1023 if (VParts1 > 1 || VParts2 > 1)
1025 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1028 CostSavings = ICost + JCost - VCost;
1031 // The powi intrinsic is special because only the first argument is
1032 // vectorized, the second arguments must be equal.
1033 CallInst *CI = dyn_cast<CallInst>(I);
1035 if (CI && (FI = CI->getCalledFunction())) {
1036 Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1037 if (IID == Intrinsic::powi) {
1038 Value *A1I = CI->getArgOperand(1),
1039 *A1J = cast<CallInst>(J)->getArgOperand(1);
1040 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1041 *A1JSCEV = SE->getSCEV(A1J);
1042 return (A1ISCEV == A1JSCEV);
1046 SmallVector<Type*, 4> Tys;
1047 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1048 Tys.push_back(CI->getArgOperand(i)->getType());
1049 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1052 CallInst *CJ = cast<CallInst>(J);
1053 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1054 Tys.push_back(CJ->getArgOperand(i)->getType());
1055 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1058 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1059 "Intrinsic argument counts differ");
1060 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1061 if (IID == Intrinsic::powi && i == 1)
1062 Tys.push_back(CI->getArgOperand(i)->getType());
1064 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1065 CJ->getArgOperand(i)->getType()));
1068 Type *RetTy = getVecTypeForPair(IT1, JT1);
1069 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1071 if (VCost > ICost + JCost)
1074 // We don't want to fuse to a type that will be split, even
1075 // if the two input types will also be split and there is no other
1077 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1080 else if (!RetParts && VCost == ICost + JCost)
1083 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1084 if (!Tys[i]->isVectorTy())
1087 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1090 else if (!NumParts && VCost == ICost + JCost)
1094 CostSavings = ICost + JCost - VCost;
1101 // Figure out whether or not J uses I and update the users and write-set
1102 // structures associated with I. Specifically, Users represents the set of
1103 // instructions that depend on I. WriteSet represents the set
1104 // of memory locations that are dependent on I. If UpdateUsers is true,
1105 // and J uses I, then Users is updated to contain J and WriteSet is updated
1106 // to contain any memory locations to which J writes. The function returns
1107 // true if J uses I. By default, alias analysis is used to determine
1108 // whether J reads from memory that overlaps with a location in WriteSet.
1109 // If LoadMoveSet is not null, then it is a previously-computed multimap
1110 // where the key is the memory-based user instruction and the value is
1111 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1112 // then the alias analysis is not used. This is necessary because this
1113 // function is called during the process of moving instructions during
1114 // vectorization and the results of the alias analysis are not stable during
1116 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1117 AliasSetTracker &WriteSet, Instruction *I,
1118 Instruction *J, bool UpdateUsers,
1119 DenseSet<ValuePair> *LoadMoveSetPairs) {
1122 // This instruction may already be marked as a user due, for example, to
1123 // being a member of a selected pair.
1128 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1131 if (I == V || Users.count(V)) {
1136 if (!UsesI && J->mayReadFromMemory()) {
1137 if (LoadMoveSetPairs) {
1138 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1140 for (AliasSetTracker::iterator W = WriteSet.begin(),
1141 WE = WriteSet.end(); W != WE; ++W) {
1142 if (W->aliasesUnknownInst(J, *AA)) {
1150 if (UsesI && UpdateUsers) {
1151 if (J->mayWriteToMemory()) WriteSet.add(J);
1158 // This function iterates over all instruction pairs in the provided
1159 // basic block and collects all candidate pairs for vectorization.
1160 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1161 BasicBlock::iterator &Start,
1162 std::multimap<Value *, Value *> &CandidatePairs,
1163 DenseSet<ValuePair> &FixedOrderPairs,
1164 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1165 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1166 BasicBlock::iterator E = BB.end();
1167 if (Start == E) return false;
1169 bool ShouldContinue = false, IAfterStart = false;
1170 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1171 if (I == Start) IAfterStart = true;
1173 bool IsSimpleLoadStore;
1174 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1176 // Look for an instruction with which to pair instruction *I...
1177 DenseSet<Value *> Users;
1178 AliasSetTracker WriteSet(*AA);
1179 bool JAfterStart = IAfterStart;
1180 BasicBlock::iterator J = llvm::next(I);
1181 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1182 if (J == Start) JAfterStart = true;
1184 // Determine if J uses I, if so, exit the loop.
1185 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1186 if (Config.FastDep) {
1187 // Note: For this heuristic to be effective, independent operations
1188 // must tend to be intermixed. This is likely to be true from some
1189 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1190 // but otherwise may require some kind of reordering pass.
1192 // When using fast dependency analysis,
1193 // stop searching after first use:
1196 if (UsesI) continue;
1199 // J does not use I, and comes before the first use of I, so it can be
1200 // merged with I if the instructions are compatible.
1201 int CostSavings, FixedOrder;
1202 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1203 CostSavings, FixedOrder)) continue;
1205 // J is a candidate for merging with I.
1206 if (!PairableInsts.size() ||
1207 PairableInsts[PairableInsts.size()-1] != I) {
1208 PairableInsts.push_back(I);
1211 CandidatePairs.insert(ValuePair(I, J));
1213 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1216 if (FixedOrder == 1)
1217 FixedOrderPairs.insert(ValuePair(I, J));
1218 else if (FixedOrder == -1)
1219 FixedOrderPairs.insert(ValuePair(J, I));
1221 // The next call to this function must start after the last instruction
1222 // selected during this invocation.
1224 Start = llvm::next(J);
1225 IAfterStart = JAfterStart = false;
1228 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1229 << *I << " <-> " << *J << " (cost savings: " <<
1230 CostSavings << ")\n");
1232 // If we have already found too many pairs, break here and this function
1233 // will be called again starting after the last instruction selected
1234 // during this invocation.
1235 if (PairableInsts.size() >= Config.MaxInsts) {
1236 ShouldContinue = true;
1245 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1246 << " instructions with candidate pairs\n");
1248 return ShouldContinue;
1251 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1252 // it looks for pairs such that both members have an input which is an
1253 // output of PI or PJ.
1254 void BBVectorize::computePairsConnectedTo(
1255 std::multimap<Value *, Value *> &CandidatePairs,
1256 std::vector<Value *> &PairableInsts,
1257 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1258 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1262 // For each possible pairing for this variable, look at the uses of
1263 // the first value...
1264 for (Value::use_iterator I = P.first->use_begin(),
1265 E = P.first->use_end(); I != E; ++I) {
1266 if (isa<LoadInst>(*I)) {
1267 // A pair cannot be connected to a load because the load only takes one
1268 // operand (the address) and it is a scalar even after vectorization.
1270 } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1271 P.first == SI->getPointerOperand()) {
1272 // Similarly, a pair cannot be connected to a store through its
1277 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1279 // For each use of the first variable, look for uses of the second
1281 for (Value::use_iterator J = P.second->use_begin(),
1282 E2 = P.second->use_end(); J != E2; ++J) {
1283 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1284 P.second == SJ->getPointerOperand())
1287 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1290 if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1291 VPPair VP(P, ValuePair(*I, *J));
1292 ConnectedPairs.insert(VP);
1293 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1297 if (isSecondInIteratorPair<Value*>(*I, JPairRange)) {
1298 VPPair VP(P, ValuePair(*J, *I));
1299 ConnectedPairs.insert(VP);
1300 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1304 if (Config.SplatBreaksChain) continue;
1305 // Look for cases where just the first value in the pair is used by
1306 // both members of another pair (splatting).
1307 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1308 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1309 P.first == SJ->getPointerOperand())
1312 if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1313 VPPair VP(P, ValuePair(*I, *J));
1314 ConnectedPairs.insert(VP);
1315 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1320 if (Config.SplatBreaksChain) return;
1321 // Look for cases where just the second value in the pair is used by
1322 // both members of another pair (splatting).
1323 for (Value::use_iterator I = P.second->use_begin(),
1324 E = P.second->use_end(); I != E; ++I) {
1325 if (isa<LoadInst>(*I))
1327 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1328 P.second == SI->getPointerOperand())
1331 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1333 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1334 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1335 P.second == SJ->getPointerOperand())
1338 if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1339 VPPair VP(P, ValuePair(*I, *J));
1340 ConnectedPairs.insert(VP);
1341 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1347 // This function figures out which pairs are connected. Two pairs are
1348 // connected if some output of the first pair forms an input to both members
1349 // of the second pair.
1350 void BBVectorize::computeConnectedPairs(
1351 std::multimap<Value *, Value *> &CandidatePairs,
1352 std::vector<Value *> &PairableInsts,
1353 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1354 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1356 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1357 PE = PairableInsts.end(); PI != PE; ++PI) {
1358 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1360 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1361 P != choiceRange.second; ++P)
1362 computePairsConnectedTo(CandidatePairs, PairableInsts,
1363 ConnectedPairs, PairConnectionTypes, *P);
1366 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1367 << " pair connections.\n");
1370 // This function builds a set of use tuples such that <A, B> is in the set
1371 // if B is in the use tree of A. If B is in the use tree of A, then B
1372 // depends on the output of A.
1373 void BBVectorize::buildDepMap(
1375 std::multimap<Value *, Value *> &CandidatePairs,
1376 std::vector<Value *> &PairableInsts,
1377 DenseSet<ValuePair> &PairableInstUsers) {
1378 DenseSet<Value *> IsInPair;
1379 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1380 E = CandidatePairs.end(); C != E; ++C) {
1381 IsInPair.insert(C->first);
1382 IsInPair.insert(C->second);
1385 // Iterate through the basic block, recording all users of each
1386 // pairable instruction.
1388 BasicBlock::iterator E = BB.end();
1389 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1390 if (IsInPair.find(I) == IsInPair.end()) continue;
1392 DenseSet<Value *> Users;
1393 AliasSetTracker WriteSet(*AA);
1394 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1395 (void) trackUsesOfI(Users, WriteSet, I, J);
1397 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1399 PairableInstUsers.insert(ValuePair(I, *U));
1403 // Returns true if an input to pair P is an output of pair Q and also an
1404 // input of pair Q is an output of pair P. If this is the case, then these
1405 // two pairs cannot be simultaneously fused.
1406 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1407 DenseSet<ValuePair> &PairableInstUsers,
1408 std::multimap<ValuePair, ValuePair> *PairableInstUserMap,
1409 DenseSet<VPPair> *PairableInstUserPairSet) {
1410 // Two pairs are in conflict if they are mutual Users of eachother.
1411 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1412 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1413 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1414 PairableInstUsers.count(ValuePair(P.second, Q.second));
1415 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1416 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1417 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1418 PairableInstUsers.count(ValuePair(Q.second, P.second));
1419 if (PairableInstUserMap) {
1420 // FIXME: The expensive part of the cycle check is not so much the cycle
1421 // check itself but this edge insertion procedure. This needs some
1422 // profiling and probably a different data structure (same is true of
1423 // most uses of std::multimap).
1425 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1426 PairableInstUserMap->insert(VPPair(Q, P));
1429 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1430 PairableInstUserMap->insert(VPPair(P, Q));
1434 return (QUsesP && PUsesQ);
1437 // This function walks the use graph of current pairs to see if, starting
1438 // from P, the walk returns to P.
1439 bool BBVectorize::pairWillFormCycle(ValuePair P,
1440 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1441 DenseSet<ValuePair> &CurrentPairs) {
1442 DEBUG(if (DebugCycleCheck)
1443 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1444 << *P.second << "\n");
1445 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1446 // contains non-direct associations.
1447 DenseSet<ValuePair> Visited;
1448 SmallVector<ValuePair, 32> Q;
1449 // General depth-first post-order traversal:
1452 ValuePair QTop = Q.pop_back_val();
1453 Visited.insert(QTop);
1455 DEBUG(if (DebugCycleCheck)
1456 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1457 << *QTop.second << "\n");
1458 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1459 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1460 C != QPairRange.second; ++C) {
1461 if (C->second == P) {
1463 << "BBV: rejected to prevent non-trivial cycle formation: "
1464 << *C->first.first << " <-> " << *C->first.second << "\n");
1468 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1469 Q.push_back(C->second);
1471 } while (!Q.empty());
1476 // This function builds the initial tree of connected pairs with the
1477 // pair J at the root.
1478 void BBVectorize::buildInitialTreeFor(
1479 std::multimap<Value *, Value *> &CandidatePairs,
1480 std::vector<Value *> &PairableInsts,
1481 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1482 DenseSet<ValuePair> &PairableInstUsers,
1483 DenseMap<Value *, Value *> &ChosenPairs,
1484 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1485 // Each of these pairs is viewed as the root node of a Tree. The Tree
1486 // is then walked (depth-first). As this happens, we keep track of
1487 // the pairs that compose the Tree and the maximum depth of the Tree.
1488 SmallVector<ValuePairWithDepth, 32> Q;
1489 // General depth-first post-order traversal:
1490 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1492 ValuePairWithDepth QTop = Q.back();
1494 // Push each child onto the queue:
1495 bool MoreChildren = false;
1496 size_t MaxChildDepth = QTop.second;
1497 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1498 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1499 k != qtRange.second; ++k) {
1500 // Make sure that this child pair is still a candidate:
1501 bool IsStillCand = false;
1502 VPIteratorPair checkRange =
1503 CandidatePairs.equal_range(k->second.first);
1504 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1505 m != checkRange.second; ++m) {
1506 if (m->second == k->second.second) {
1513 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1514 if (C == Tree.end()) {
1515 size_t d = getDepthFactor(k->second.first);
1516 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1517 MoreChildren = true;
1519 MaxChildDepth = std::max(MaxChildDepth, C->second);
1524 if (!MoreChildren) {
1525 // Record the current pair as part of the Tree:
1526 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1529 } while (!Q.empty());
1532 // Given some initial tree, prune it by removing conflicting pairs (pairs
1533 // that cannot be simultaneously chosen for vectorization).
1534 void BBVectorize::pruneTreeFor(
1535 std::multimap<Value *, Value *> &CandidatePairs,
1536 std::vector<Value *> &PairableInsts,
1537 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1538 DenseSet<ValuePair> &PairableInstUsers,
1539 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1540 DenseSet<VPPair> &PairableInstUserPairSet,
1541 DenseMap<Value *, Value *> &ChosenPairs,
1542 DenseMap<ValuePair, size_t> &Tree,
1543 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1544 bool UseCycleCheck) {
1545 SmallVector<ValuePairWithDepth, 32> Q;
1546 // General depth-first post-order traversal:
1547 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1549 ValuePairWithDepth QTop = Q.pop_back_val();
1550 PrunedTree.insert(QTop.first);
1552 // Visit each child, pruning as necessary...
1553 SmallVector<ValuePairWithDepth, 8> BestChildren;
1554 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1555 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1556 K != QTopRange.second; ++K) {
1557 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1558 if (C == Tree.end()) continue;
1560 // This child is in the Tree, now we need to make sure it is the
1561 // best of any conflicting children. There could be multiple
1562 // conflicting children, so first, determine if we're keeping
1563 // this child, then delete conflicting children as necessary.
1565 // It is also necessary to guard against pairing-induced
1566 // dependencies. Consider instructions a .. x .. y .. b
1567 // such that (a,b) are to be fused and (x,y) are to be fused
1568 // but a is an input to x and b is an output from y. This
1569 // means that y cannot be moved after b but x must be moved
1570 // after b for (a,b) to be fused. In other words, after
1571 // fusing (a,b) we have y .. a/b .. x where y is an input
1572 // to a/b and x is an output to a/b: x and y can no longer
1573 // be legally fused. To prevent this condition, we must
1574 // make sure that a child pair added to the Tree is not
1575 // both an input and output of an already-selected pair.
1577 // Pairing-induced dependencies can also form from more complicated
1578 // cycles. The pair vs. pair conflicts are easy to check, and so
1579 // that is done explicitly for "fast rejection", and because for
1580 // child vs. child conflicts, we may prefer to keep the current
1581 // pair in preference to the already-selected child.
1582 DenseSet<ValuePair> CurrentPairs;
1585 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1586 = BestChildren.begin(), E2 = BestChildren.end();
1588 if (C2->first.first == C->first.first ||
1589 C2->first.first == C->first.second ||
1590 C2->first.second == C->first.first ||
1591 C2->first.second == C->first.second ||
1592 pairsConflict(C2->first, C->first, PairableInstUsers,
1593 UseCycleCheck ? &PairableInstUserMap : 0,
1594 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1595 if (C2->second >= C->second) {
1600 CurrentPairs.insert(C2->first);
1603 if (!CanAdd) continue;
1605 // Even worse, this child could conflict with another node already
1606 // selected for the Tree. If that is the case, ignore this child.
1607 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1608 E2 = PrunedTree.end(); T != E2; ++T) {
1609 if (T->first == C->first.first ||
1610 T->first == C->first.second ||
1611 T->second == C->first.first ||
1612 T->second == C->first.second ||
1613 pairsConflict(*T, C->first, PairableInstUsers,
1614 UseCycleCheck ? &PairableInstUserMap : 0,
1615 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1620 CurrentPairs.insert(*T);
1622 if (!CanAdd) continue;
1624 // And check the queue too...
1625 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1626 E2 = Q.end(); C2 != E2; ++C2) {
1627 if (C2->first.first == C->first.first ||
1628 C2->first.first == C->first.second ||
1629 C2->first.second == C->first.first ||
1630 C2->first.second == C->first.second ||
1631 pairsConflict(C2->first, C->first, PairableInstUsers,
1632 UseCycleCheck ? &PairableInstUserMap : 0,
1633 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1638 CurrentPairs.insert(C2->first);
1640 if (!CanAdd) continue;
1642 // Last but not least, check for a conflict with any of the
1643 // already-chosen pairs.
1644 for (DenseMap<Value *, Value *>::iterator C2 =
1645 ChosenPairs.begin(), E2 = ChosenPairs.end();
1647 if (pairsConflict(*C2, C->first, PairableInstUsers,
1648 UseCycleCheck ? &PairableInstUserMap : 0,
1649 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1654 CurrentPairs.insert(*C2);
1656 if (!CanAdd) continue;
1658 // To check for non-trivial cycles formed by the addition of the
1659 // current pair we've formed a list of all relevant pairs, now use a
1660 // graph walk to check for a cycle. We start from the current pair and
1661 // walk the use tree to see if we again reach the current pair. If we
1662 // do, then the current pair is rejected.
1664 // FIXME: It may be more efficient to use a topological-ordering
1665 // algorithm to improve the cycle check. This should be investigated.
1666 if (UseCycleCheck &&
1667 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1670 // This child can be added, but we may have chosen it in preference
1671 // to an already-selected child. Check for this here, and if a
1672 // conflict is found, then remove the previously-selected child
1673 // before adding this one in its place.
1674 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1675 = BestChildren.begin(); C2 != BestChildren.end();) {
1676 if (C2->first.first == C->first.first ||
1677 C2->first.first == C->first.second ||
1678 C2->first.second == C->first.first ||
1679 C2->first.second == C->first.second ||
1680 pairsConflict(C2->first, C->first, PairableInstUsers))
1681 C2 = BestChildren.erase(C2);
1686 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1689 for (SmallVector<ValuePairWithDepth, 8>::iterator C
1690 = BestChildren.begin(), E2 = BestChildren.end();
1692 size_t DepthF = getDepthFactor(C->first.first);
1693 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1695 } while (!Q.empty());
1698 // This function finds the best tree of mututally-compatible connected
1699 // pairs, given the choice of root pairs as an iterator range.
1700 void BBVectorize::findBestTreeFor(
1701 std::multimap<Value *, Value *> &CandidatePairs,
1702 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1703 std::vector<Value *> &PairableInsts,
1704 DenseSet<ValuePair> &FixedOrderPairs,
1705 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1706 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1707 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
1708 DenseSet<ValuePair> &PairableInstUsers,
1709 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1710 DenseSet<VPPair> &PairableInstUserPairSet,
1711 DenseMap<Value *, Value *> &ChosenPairs,
1712 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1713 int &BestEffSize, VPIteratorPair ChoiceRange,
1714 bool UseCycleCheck) {
1715 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1716 J != ChoiceRange.second; ++J) {
1718 // Before going any further, make sure that this pair does not
1719 // conflict with any already-selected pairs (see comment below
1720 // near the Tree pruning for more details).
1721 DenseSet<ValuePair> ChosenPairSet;
1722 bool DoesConflict = false;
1723 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1724 E = ChosenPairs.end(); C != E; ++C) {
1725 if (pairsConflict(*C, *J, PairableInstUsers,
1726 UseCycleCheck ? &PairableInstUserMap : 0,
1727 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1728 DoesConflict = true;
1732 ChosenPairSet.insert(*C);
1734 if (DoesConflict) continue;
1736 if (UseCycleCheck &&
1737 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1740 DenseMap<ValuePair, size_t> Tree;
1741 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1742 PairableInstUsers, ChosenPairs, Tree, *J);
1744 // Because we'll keep the child with the largest depth, the largest
1745 // depth is still the same in the unpruned Tree.
1746 size_t MaxDepth = Tree.lookup(*J);
1748 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1749 << *J->first << " <-> " << *J->second << "} of depth " <<
1750 MaxDepth << " and size " << Tree.size() << "\n");
1752 // At this point the Tree has been constructed, but, may contain
1753 // contradictory children (meaning that different children of
1754 // some tree node may be attempting to fuse the same instruction).
1755 // So now we walk the tree again, in the case of a conflict,
1756 // keep only the child with the largest depth. To break a tie,
1757 // favor the first child.
1759 DenseSet<ValuePair> PrunedTree;
1760 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1761 PairableInstUsers, PairableInstUserMap, PairableInstUserPairSet,
1762 ChosenPairs, Tree, PrunedTree, *J, UseCycleCheck);
1766 DenseSet<Value *> PrunedTreeInstrs;
1767 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1768 E = PrunedTree.end(); S != E; ++S) {
1769 PrunedTreeInstrs.insert(S->first);
1770 PrunedTreeInstrs.insert(S->second);
1773 // The set of pairs that have already contributed to the total cost.
1774 DenseSet<ValuePair> IncomingPairs;
1776 // If the cost model were perfect, this might not be necessary; but we
1777 // need to make sure that we don't get stuck vectorizing our own
1779 bool HasNontrivialInsts = false;
1781 // The node weights represent the cost savings associated with
1782 // fusing the pair of instructions.
1783 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1784 E = PrunedTree.end(); S != E; ++S) {
1785 if (!isa<ShuffleVectorInst>(S->first) &&
1786 !isa<InsertElementInst>(S->first) &&
1787 !isa<ExtractElementInst>(S->first))
1788 HasNontrivialInsts = true;
1790 bool FlipOrder = false;
1792 if (getDepthFactor(S->first)) {
1793 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1794 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1795 << *S->first << " <-> " << *S->second << "} = " <<
1797 EffSize += ESContrib;
1800 // The edge weights contribute in a negative sense: they represent
1801 // the cost of shuffles.
1802 VPPIteratorPair IP = ConnectedPairDeps.equal_range(*S);
1803 if (IP.first != ConnectedPairDeps.end()) {
1804 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1805 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1806 Q != IP.second; ++Q) {
1807 if (!PrunedTree.count(Q->second))
1809 DenseMap<VPPair, unsigned>::iterator R =
1810 PairConnectionTypes.find(VPPair(Q->second, Q->first));
1811 assert(R != PairConnectionTypes.end() &&
1812 "Cannot find pair connection type");
1813 if (R->second == PairConnectionDirect)
1815 else if (R->second == PairConnectionSwap)
1819 // If there are more swaps than direct connections, then
1820 // the pair order will be flipped during fusion. So the real
1821 // number of swaps is the minimum number.
1822 FlipOrder = !FixedOrderPairs.count(*S) &&
1823 ((NumDepsSwap > NumDepsDirect) ||
1824 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1826 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1827 Q != IP.second; ++Q) {
1828 if (!PrunedTree.count(Q->second))
1830 DenseMap<VPPair, unsigned>::iterator R =
1831 PairConnectionTypes.find(VPPair(Q->second, Q->first));
1832 assert(R != PairConnectionTypes.end() &&
1833 "Cannot find pair connection type");
1834 Type *Ty1 = Q->second.first->getType(),
1835 *Ty2 = Q->second.second->getType();
1836 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1837 if ((R->second == PairConnectionDirect && FlipOrder) ||
1838 (R->second == PairConnectionSwap && !FlipOrder) ||
1839 R->second == PairConnectionSplat) {
1840 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1843 if (VTy->getVectorNumElements() == 2) {
1844 if (R->second == PairConnectionSplat)
1845 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1846 TargetTransformInfo::SK_Broadcast, VTy));
1848 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1849 TargetTransformInfo::SK_Reverse, VTy));
1852 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1853 *Q->second.first << " <-> " << *Q->second.second <<
1855 *S->first << " <-> " << *S->second << "} = " <<
1857 EffSize -= ESContrib;
1862 // Compute the cost of outgoing edges. We assume that edges outgoing
1863 // to shuffles, inserts or extracts can be merged, and so contribute
1864 // no additional cost.
1865 if (!S->first->getType()->isVoidTy()) {
1866 Type *Ty1 = S->first->getType(),
1867 *Ty2 = S->second->getType();
1868 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1870 bool NeedsExtraction = false;
1871 for (Value::use_iterator I = S->first->use_begin(),
1872 IE = S->first->use_end(); I != IE; ++I) {
1873 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1874 // Shuffle can be folded if it has no other input
1875 if (isa<UndefValue>(SI->getOperand(1)))
1878 if (isa<ExtractElementInst>(*I))
1880 if (PrunedTreeInstrs.count(*I))
1882 NeedsExtraction = true;
1886 if (NeedsExtraction) {
1888 if (Ty1->isVectorTy()) {
1889 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1891 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1892 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1894 ESContrib = (int) TTI->getVectorInstrCost(
1895 Instruction::ExtractElement, VTy, 0);
1897 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1898 *S->first << "} = " << ESContrib << "\n");
1899 EffSize -= ESContrib;
1902 NeedsExtraction = false;
1903 for (Value::use_iterator I = S->second->use_begin(),
1904 IE = S->second->use_end(); I != IE; ++I) {
1905 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1906 // Shuffle can be folded if it has no other input
1907 if (isa<UndefValue>(SI->getOperand(1)))
1910 if (isa<ExtractElementInst>(*I))
1912 if (PrunedTreeInstrs.count(*I))
1914 NeedsExtraction = true;
1918 if (NeedsExtraction) {
1920 if (Ty2->isVectorTy()) {
1921 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1923 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1924 TargetTransformInfo::SK_ExtractSubvector, VTy,
1925 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
1927 ESContrib = (int) TTI->getVectorInstrCost(
1928 Instruction::ExtractElement, VTy, 1);
1929 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1930 *S->second << "} = " << ESContrib << "\n");
1931 EffSize -= ESContrib;
1935 // Compute the cost of incoming edges.
1936 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
1937 Instruction *S1 = cast<Instruction>(S->first),
1938 *S2 = cast<Instruction>(S->second);
1939 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
1940 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
1942 // Combining constants into vector constants (or small vector
1943 // constants into larger ones are assumed free).
1944 if (isa<Constant>(O1) && isa<Constant>(O2))
1950 ValuePair VP = ValuePair(O1, O2);
1951 ValuePair VPR = ValuePair(O2, O1);
1953 // Internal edges are not handled here.
1954 if (PrunedTree.count(VP) || PrunedTree.count(VPR))
1957 Type *Ty1 = O1->getType(),
1958 *Ty2 = O2->getType();
1959 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1961 // Combining vector operations of the same type is also assumed
1962 // folded with other operations.
1964 // If both are insert elements, then both can be widened.
1965 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
1966 *IEO2 = dyn_cast<InsertElementInst>(O2);
1967 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
1969 // If both are extract elements, and both have the same input
1970 // type, then they can be replaced with a shuffle
1971 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
1972 *EIO2 = dyn_cast<ExtractElementInst>(O2);
1974 EIO1->getOperand(0)->getType() ==
1975 EIO2->getOperand(0)->getType())
1977 // If both are a shuffle with equal operand types and only two
1978 // unqiue operands, then they can be replaced with a single
1980 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
1981 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
1983 SIO1->getOperand(0)->getType() ==
1984 SIO2->getOperand(0)->getType()) {
1985 SmallSet<Value *, 4> SIOps;
1986 SIOps.insert(SIO1->getOperand(0));
1987 SIOps.insert(SIO1->getOperand(1));
1988 SIOps.insert(SIO2->getOperand(0));
1989 SIOps.insert(SIO2->getOperand(1));
1990 if (SIOps.size() <= 2)
1996 // This pair has already been formed.
1997 if (IncomingPairs.count(VP)) {
1999 } else if (IncomingPairs.count(VPR)) {
2000 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2003 if (VTy->getVectorNumElements() == 2)
2004 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2005 TargetTransformInfo::SK_Reverse, VTy));
2006 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2007 ESContrib = (int) TTI->getVectorInstrCost(
2008 Instruction::InsertElement, VTy, 0);
2009 ESContrib += (int) TTI->getVectorInstrCost(
2010 Instruction::InsertElement, VTy, 1);
2011 } else if (!Ty1->isVectorTy()) {
2012 // O1 needs to be inserted into a vector of size O2, and then
2013 // both need to be shuffled together.
2014 ESContrib = (int) TTI->getVectorInstrCost(
2015 Instruction::InsertElement, Ty2, 0);
2016 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2018 } else if (!Ty2->isVectorTy()) {
2019 // O2 needs to be inserted into a vector of size O1, and then
2020 // both need to be shuffled together.
2021 ESContrib = (int) TTI->getVectorInstrCost(
2022 Instruction::InsertElement, Ty1, 0);
2023 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2026 Type *TyBig = Ty1, *TySmall = Ty2;
2027 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2028 std::swap(TyBig, TySmall);
2030 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2032 if (TyBig != TySmall)
2033 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2037 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2038 << *O1 << " <-> " << *O2 << "} = " <<
2040 EffSize -= ESContrib;
2041 IncomingPairs.insert(VP);
2046 if (!HasNontrivialInsts) {
2047 DEBUG(if (DebugPairSelection) dbgs() <<
2048 "\tNo non-trivial instructions in tree;"
2049 " override to zero effective size\n");
2053 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
2054 E = PrunedTree.end(); S != E; ++S)
2055 EffSize += (int) getDepthFactor(S->first);
2058 DEBUG(if (DebugPairSelection)
2059 dbgs() << "BBV: found pruned Tree for pair {"
2060 << *J->first << " <-> " << *J->second << "} of depth " <<
2061 MaxDepth << " and size " << PrunedTree.size() <<
2062 " (effective size: " << EffSize << ")\n");
2063 if (((TTI && !UseChainDepthWithTI) ||
2064 MaxDepth >= Config.ReqChainDepth) &&
2065 EffSize > 0 && EffSize > BestEffSize) {
2066 BestMaxDepth = MaxDepth;
2067 BestEffSize = EffSize;
2068 BestTree = PrunedTree;
2073 // Given the list of candidate pairs, this function selects those
2074 // that will be fused into vector instructions.
2075 void BBVectorize::choosePairs(
2076 std::multimap<Value *, Value *> &CandidatePairs,
2077 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2078 std::vector<Value *> &PairableInsts,
2079 DenseSet<ValuePair> &FixedOrderPairs,
2080 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2081 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2082 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
2083 DenseSet<ValuePair> &PairableInstUsers,
2084 DenseMap<Value *, Value *>& ChosenPairs) {
2085 bool UseCycleCheck =
2086 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
2087 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
2088 DenseSet<VPPair> PairableInstUserPairSet;
2089 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2090 E = PairableInsts.end(); I != E; ++I) {
2091 // The number of possible pairings for this variable:
2092 size_t NumChoices = CandidatePairs.count(*I);
2093 if (!NumChoices) continue;
2095 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
2097 // The best pair to choose and its tree:
2098 size_t BestMaxDepth = 0;
2099 int BestEffSize = 0;
2100 DenseSet<ValuePair> BestTree;
2101 findBestTreeFor(CandidatePairs, CandidatePairCostSavings,
2102 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2103 ConnectedPairs, ConnectedPairDeps,
2104 PairableInstUsers, PairableInstUserMap,
2105 PairableInstUserPairSet, ChosenPairs,
2106 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
2109 // A tree has been chosen (or not) at this point. If no tree was
2110 // chosen, then this instruction, I, cannot be paired (and is no longer
2113 DEBUG(if (BestTree.size() > 0)
2114 dbgs() << "BBV: selected pairs in the best tree for: "
2115 << *cast<Instruction>(*I) << "\n");
2117 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
2118 SE2 = BestTree.end(); S != SE2; ++S) {
2119 // Insert the members of this tree into the list of chosen pairs.
2120 ChosenPairs.insert(ValuePair(S->first, S->second));
2121 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2122 *S->second << "\n");
2124 // Remove all candidate pairs that have values in the chosen tree.
2125 for (std::multimap<Value *, Value *>::iterator K =
2126 CandidatePairs.begin(); K != CandidatePairs.end();) {
2127 if (K->first == S->first || K->second == S->first ||
2128 K->second == S->second || K->first == S->second) {
2129 // Don't remove the actual pair chosen so that it can be used
2130 // in subsequent tree selections.
2131 if (!(K->first == S->first && K->second == S->second))
2132 CandidatePairs.erase(K++);
2142 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2145 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2150 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2151 (n > 0 ? "." + utostr(n) : "")).str();
2154 // Returns the value that is to be used as the pointer input to the vector
2155 // instruction that fuses I with J.
2156 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2157 Instruction *I, Instruction *J, unsigned o) {
2159 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2160 int64_t OffsetInElmts;
2162 // Note: the analysis might fail here, that is why the pair order has
2163 // been precomputed (OffsetInElmts must be unused here).
2164 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2165 IAddressSpace, JAddressSpace,
2166 OffsetInElmts, false);
2168 // The pointer value is taken to be the one with the lowest offset.
2171 Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
2172 Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
2173 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2174 Type *VArgPtrType = PointerType::get(VArgType,
2175 cast<PointerType>(IPtr->getType())->getAddressSpace());
2176 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2177 /* insert before */ I);
2180 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2181 unsigned MaskOffset, unsigned NumInElem,
2182 unsigned NumInElem1, unsigned IdxOffset,
2183 std::vector<Constant*> &Mask) {
2184 unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
2185 for (unsigned v = 0; v < NumElem1; ++v) {
2186 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2188 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2190 unsigned mm = m + (int) IdxOffset;
2191 if (m >= (int) NumInElem1)
2192 mm += (int) NumInElem;
2194 Mask[v+MaskOffset] =
2195 ConstantInt::get(Type::getInt32Ty(Context), mm);
2200 // Returns the value that is to be used as the vector-shuffle mask to the
2201 // vector instruction that fuses I with J.
2202 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2203 Instruction *I, Instruction *J) {
2204 // This is the shuffle mask. We need to append the second
2205 // mask to the first, and the numbers need to be adjusted.
2207 Type *ArgTypeI = I->getType();
2208 Type *ArgTypeJ = J->getType();
2209 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2211 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
2213 // Get the total number of elements in the fused vector type.
2214 // By definition, this must equal the number of elements in
2216 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
2217 std::vector<Constant*> Mask(NumElem);
2219 Type *OpTypeI = I->getOperand(0)->getType();
2220 unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
2221 Type *OpTypeJ = J->getOperand(0)->getType();
2222 unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
2224 // The fused vector will be:
2225 // -----------------------------------------------------
2226 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2227 // -----------------------------------------------------
2228 // from which we'll extract NumElem total elements (where the first NumElemI
2229 // of them come from the mask in I and the remainder come from the mask
2232 // For the mask from the first pair...
2233 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2236 // For the mask from the second pair...
2237 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2240 return ConstantVector::get(Mask);
2243 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2244 Instruction *J, unsigned o, Value *&LOp,
2246 Type *ArgTypeL, Type *ArgTypeH,
2247 bool IBeforeJ, unsigned IdxOff) {
2248 bool ExpandedIEChain = false;
2249 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2250 // If we have a pure insertelement chain, then this can be rewritten
2251 // into a chain that directly builds the larger type.
2252 if (isPureIEChain(LIE)) {
2253 SmallVector<Value *, 8> VectElemts(numElemL,
2254 UndefValue::get(ArgTypeL->getScalarType()));
2255 InsertElementInst *LIENext = LIE;
2258 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2259 VectElemts[Idx] = LIENext->getOperand(1);
2261 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2264 Value *LIEPrev = UndefValue::get(ArgTypeH);
2265 for (unsigned i = 0; i < numElemL; ++i) {
2266 if (isa<UndefValue>(VectElemts[i])) continue;
2267 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2268 ConstantInt::get(Type::getInt32Ty(Context),
2270 getReplacementName(IBeforeJ ? I : J,
2272 LIENext->insertBefore(IBeforeJ ? J : I);
2276 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2277 ExpandedIEChain = true;
2281 return ExpandedIEChain;
2284 // Returns the value to be used as the specified operand of the vector
2285 // instruction that fuses I with J.
2286 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2287 Instruction *J, unsigned o, bool IBeforeJ) {
2288 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2289 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2291 // Compute the fused vector type for this operand
2292 Type *ArgTypeI = I->getOperand(o)->getType();
2293 Type *ArgTypeJ = J->getOperand(o)->getType();
2294 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2296 Instruction *L = I, *H = J;
2297 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2300 if (ArgTypeL->isVectorTy())
2301 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
2306 if (ArgTypeH->isVectorTy())
2307 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
2311 Value *LOp = L->getOperand(o);
2312 Value *HOp = H->getOperand(o);
2313 unsigned numElem = VArgType->getNumElements();
2315 // First, we check if we can reuse the "original" vector outputs (if these
2316 // exist). We might need a shuffle.
2317 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2318 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2319 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2320 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2322 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2323 // optimization. The input vectors to the shuffle might be a different
2324 // length from the shuffle outputs. Unfortunately, the replacement
2325 // shuffle mask has already been formed, and the mask entries are sensitive
2326 // to the sizes of the inputs.
2327 bool IsSizeChangeShuffle =
2328 isa<ShuffleVectorInst>(L) &&
2329 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2331 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2332 // We can have at most two unique vector inputs.
2333 bool CanUseInputs = true;
2336 I1 = LEE->getOperand(0);
2338 I1 = LSV->getOperand(0);
2339 I2 = LSV->getOperand(1);
2340 if (I2 == I1 || isa<UndefValue>(I2))
2345 Value *I3 = HEE->getOperand(0);
2346 if (!I2 && I3 != I1)
2348 else if (I3 != I1 && I3 != I2)
2349 CanUseInputs = false;
2351 Value *I3 = HSV->getOperand(0);
2352 if (!I2 && I3 != I1)
2354 else if (I3 != I1 && I3 != I2)
2355 CanUseInputs = false;
2358 Value *I4 = HSV->getOperand(1);
2359 if (!isa<UndefValue>(I4)) {
2360 if (!I2 && I4 != I1)
2362 else if (I4 != I1 && I4 != I2)
2363 CanUseInputs = false;
2370 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2373 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2376 // We have one or two input vectors. We need to map each index of the
2377 // operands to the index of the original vector.
2378 SmallVector<std::pair<int, int>, 8> II(numElem);
2379 for (unsigned i = 0; i < numElemL; ++i) {
2383 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2384 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2386 Idx = LSV->getMaskValue(i);
2387 if (Idx < (int) LOpElem) {
2388 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2391 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2395 II[i] = std::pair<int, int>(Idx, INum);
2397 for (unsigned i = 0; i < numElemH; ++i) {
2401 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2402 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2404 Idx = HSV->getMaskValue(i);
2405 if (Idx < (int) HOpElem) {
2406 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2409 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2413 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2416 // We now have an array which tells us from which index of which
2417 // input vector each element of the operand comes.
2418 VectorType *I1T = cast<VectorType>(I1->getType());
2419 unsigned I1Elem = I1T->getNumElements();
2422 // In this case there is only one underlying vector input. Check for
2423 // the trivial case where we can use the input directly.
2424 if (I1Elem == numElem) {
2425 bool ElemInOrder = true;
2426 for (unsigned i = 0; i < numElem; ++i) {
2427 if (II[i].first != (int) i && II[i].first != -1) {
2428 ElemInOrder = false;
2437 // A shuffle is needed.
2438 std::vector<Constant *> Mask(numElem);
2439 for (unsigned i = 0; i < numElem; ++i) {
2440 int Idx = II[i].first;
2442 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2444 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2448 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2449 ConstantVector::get(Mask),
2450 getReplacementName(IBeforeJ ? I : J,
2452 S->insertBefore(IBeforeJ ? J : I);
2456 VectorType *I2T = cast<VectorType>(I2->getType());
2457 unsigned I2Elem = I2T->getNumElements();
2459 // This input comes from two distinct vectors. The first step is to
2460 // make sure that both vectors are the same length. If not, the
2461 // smaller one will need to grow before they can be shuffled together.
2462 if (I1Elem < I2Elem) {
2463 std::vector<Constant *> Mask(I2Elem);
2465 for (; v < I1Elem; ++v)
2466 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2467 for (; v < I2Elem; ++v)
2468 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2470 Instruction *NewI1 =
2471 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2472 ConstantVector::get(Mask),
2473 getReplacementName(IBeforeJ ? I : J,
2475 NewI1->insertBefore(IBeforeJ ? J : I);
2479 } else if (I1Elem > I2Elem) {
2480 std::vector<Constant *> Mask(I1Elem);
2482 for (; v < I2Elem; ++v)
2483 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2484 for (; v < I1Elem; ++v)
2485 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2487 Instruction *NewI2 =
2488 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2489 ConstantVector::get(Mask),
2490 getReplacementName(IBeforeJ ? I : J,
2492 NewI2->insertBefore(IBeforeJ ? J : I);
2498 // Now that both I1 and I2 are the same length we can shuffle them
2499 // together (and use the result).
2500 std::vector<Constant *> Mask(numElem);
2501 for (unsigned v = 0; v < numElem; ++v) {
2502 if (II[v].first == -1) {
2503 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2505 int Idx = II[v].first + II[v].second * I1Elem;
2506 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2510 Instruction *NewOp =
2511 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2512 getReplacementName(IBeforeJ ? I : J, true, o));
2513 NewOp->insertBefore(IBeforeJ ? J : I);
2518 Type *ArgType = ArgTypeL;
2519 if (numElemL < numElemH) {
2520 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2521 ArgTypeL, VArgType, IBeforeJ, 1)) {
2522 // This is another short-circuit case: we're combining a scalar into
2523 // a vector that is formed by an IE chain. We've just expanded the IE
2524 // chain, now insert the scalar and we're done.
2526 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2527 getReplacementName(IBeforeJ ? I : J, true, o));
2528 S->insertBefore(IBeforeJ ? J : I);
2530 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2531 ArgTypeH, IBeforeJ)) {
2532 // The two vector inputs to the shuffle must be the same length,
2533 // so extend the smaller vector to be the same length as the larger one.
2537 std::vector<Constant *> Mask(numElemH);
2539 for (; v < numElemL; ++v)
2540 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2541 for (; v < numElemH; ++v)
2542 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2544 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2545 ConstantVector::get(Mask),
2546 getReplacementName(IBeforeJ ? I : J,
2549 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2550 getReplacementName(IBeforeJ ? I : J,
2554 NLOp->insertBefore(IBeforeJ ? J : I);
2559 } else if (numElemL > numElemH) {
2560 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2561 ArgTypeH, VArgType, IBeforeJ)) {
2563 InsertElementInst::Create(LOp, HOp,
2564 ConstantInt::get(Type::getInt32Ty(Context),
2566 getReplacementName(IBeforeJ ? I : J,
2568 S->insertBefore(IBeforeJ ? J : I);
2570 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2571 ArgTypeL, IBeforeJ)) {
2574 std::vector<Constant *> Mask(numElemL);
2576 for (; v < numElemH; ++v)
2577 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2578 for (; v < numElemL; ++v)
2579 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2581 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2582 ConstantVector::get(Mask),
2583 getReplacementName(IBeforeJ ? I : J,
2586 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2587 getReplacementName(IBeforeJ ? I : J,
2591 NHOp->insertBefore(IBeforeJ ? J : I);
2596 if (ArgType->isVectorTy()) {
2597 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2598 std::vector<Constant*> Mask(numElem);
2599 for (unsigned v = 0; v < numElem; ++v) {
2601 // If the low vector was expanded, we need to skip the extra
2602 // undefined entries.
2603 if (v >= numElemL && numElemH > numElemL)
2604 Idx += (numElemH - numElemL);
2605 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2608 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2609 ConstantVector::get(Mask),
2610 getReplacementName(IBeforeJ ? I : J, true, o));
2611 BV->insertBefore(IBeforeJ ? J : I);
2615 Instruction *BV1 = InsertElementInst::Create(
2616 UndefValue::get(VArgType), LOp, CV0,
2617 getReplacementName(IBeforeJ ? I : J,
2619 BV1->insertBefore(IBeforeJ ? J : I);
2620 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2621 getReplacementName(IBeforeJ ? I : J,
2623 BV2->insertBefore(IBeforeJ ? J : I);
2627 // This function creates an array of values that will be used as the inputs
2628 // to the vector instruction that fuses I with J.
2629 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2630 Instruction *I, Instruction *J,
2631 SmallVector<Value *, 3> &ReplacedOperands,
2633 unsigned NumOperands = I->getNumOperands();
2635 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2636 // Iterate backward so that we look at the store pointer
2637 // first and know whether or not we need to flip the inputs.
2639 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2640 // This is the pointer for a load/store instruction.
2641 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2643 } else if (isa<CallInst>(I)) {
2644 Function *F = cast<CallInst>(I)->getCalledFunction();
2645 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2646 if (o == NumOperands-1) {
2647 BasicBlock &BB = *I->getParent();
2649 Module *M = BB.getParent()->getParent();
2650 Type *ArgTypeI = I->getType();
2651 Type *ArgTypeJ = J->getType();
2652 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2654 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2656 } else if (IID == Intrinsic::powi && o == 1) {
2657 // The second argument of powi is a single integer and we've already
2658 // checked that both arguments are equal. As a result, we just keep
2659 // I's second argument.
2660 ReplacedOperands[o] = I->getOperand(o);
2663 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2664 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2668 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2672 // This function creates two values that represent the outputs of the
2673 // original I and J instructions. These are generally vector shuffles
2674 // or extracts. In many cases, these will end up being unused and, thus,
2675 // eliminated by later passes.
2676 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2677 Instruction *J, Instruction *K,
2678 Instruction *&InsertionPt,
2679 Instruction *&K1, Instruction *&K2) {
2680 if (isa<StoreInst>(I)) {
2681 AA->replaceWithNewValue(I, K);
2682 AA->replaceWithNewValue(J, K);
2684 Type *IType = I->getType();
2685 Type *JType = J->getType();
2687 VectorType *VType = getVecTypeForPair(IType, JType);
2688 unsigned numElem = VType->getNumElements();
2690 unsigned numElemI, numElemJ;
2691 if (IType->isVectorTy())
2692 numElemI = cast<VectorType>(IType)->getNumElements();
2696 if (JType->isVectorTy())
2697 numElemJ = cast<VectorType>(JType)->getNumElements();
2701 if (IType->isVectorTy()) {
2702 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2703 for (unsigned v = 0; v < numElemI; ++v) {
2704 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2705 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2708 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2709 ConstantVector::get( Mask1),
2710 getReplacementName(K, false, 1));
2712 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2713 K1 = ExtractElementInst::Create(K, CV0,
2714 getReplacementName(K, false, 1));
2717 if (JType->isVectorTy()) {
2718 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2719 for (unsigned v = 0; v < numElemJ; ++v) {
2720 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2721 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2724 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2725 ConstantVector::get( Mask2),
2726 getReplacementName(K, false, 2));
2728 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2729 K2 = ExtractElementInst::Create(K, CV1,
2730 getReplacementName(K, false, 2));
2734 K2->insertAfter(K1);
2739 // Move all uses of the function I (including pairing-induced uses) after J.
2740 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2741 DenseSet<ValuePair> &LoadMoveSetPairs,
2742 Instruction *I, Instruction *J) {
2743 // Skip to the first instruction past I.
2744 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2746 DenseSet<Value *> Users;
2747 AliasSetTracker WriteSet(*AA);
2748 for (; cast<Instruction>(L) != J; ++L)
2749 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2751 assert(cast<Instruction>(L) == J &&
2752 "Tracking has not proceeded far enough to check for dependencies");
2753 // If J is now in the use set of I, then trackUsesOfI will return true
2754 // and we have a dependency cycle (and the fusing operation must abort).
2755 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2758 // Move all uses of the function I (including pairing-induced uses) after J.
2759 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2760 DenseSet<ValuePair> &LoadMoveSetPairs,
2761 Instruction *&InsertionPt,
2762 Instruction *I, Instruction *J) {
2763 // Skip to the first instruction past I.
2764 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2766 DenseSet<Value *> Users;
2767 AliasSetTracker WriteSet(*AA);
2768 for (; cast<Instruction>(L) != J;) {
2769 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2770 // Move this instruction
2771 Instruction *InstToMove = L; ++L;
2773 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2774 " to after " << *InsertionPt << "\n");
2775 InstToMove->removeFromParent();
2776 InstToMove->insertAfter(InsertionPt);
2777 InsertionPt = InstToMove;
2784 // Collect all load instruction that are in the move set of a given first
2785 // pair member. These loads depend on the first instruction, I, and so need
2786 // to be moved after J (the second instruction) when the pair is fused.
2787 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2788 DenseMap<Value *, Value *> &ChosenPairs,
2789 std::multimap<Value *, Value *> &LoadMoveSet,
2790 DenseSet<ValuePair> &LoadMoveSetPairs,
2792 // Skip to the first instruction past I.
2793 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2795 DenseSet<Value *> Users;
2796 AliasSetTracker WriteSet(*AA);
2798 // Note: We cannot end the loop when we reach J because J could be moved
2799 // farther down the use chain by another instruction pairing. Also, J
2800 // could be before I if this is an inverted input.
2801 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2802 if (trackUsesOfI(Users, WriteSet, I, L)) {
2803 if (L->mayReadFromMemory()) {
2804 LoadMoveSet.insert(ValuePair(L, I));
2805 LoadMoveSetPairs.insert(ValuePair(L, I));
2811 // In cases where both load/stores and the computation of their pointers
2812 // are chosen for vectorization, we can end up in a situation where the
2813 // aliasing analysis starts returning different query results as the
2814 // process of fusing instruction pairs continues. Because the algorithm
2815 // relies on finding the same use trees here as were found earlier, we'll
2816 // need to precompute the necessary aliasing information here and then
2817 // manually update it during the fusion process.
2818 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2819 std::vector<Value *> &PairableInsts,
2820 DenseMap<Value *, Value *> &ChosenPairs,
2821 std::multimap<Value *, Value *> &LoadMoveSet,
2822 DenseSet<ValuePair> &LoadMoveSetPairs) {
2823 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2824 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2825 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2826 if (P == ChosenPairs.end()) continue;
2828 Instruction *I = cast<Instruction>(P->first);
2829 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2830 LoadMoveSetPairs, I);
2834 // When the first instruction in each pair is cloned, it will inherit its
2835 // parent's metadata. This metadata must be combined with that of the other
2836 // instruction in a safe way.
2837 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2838 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2839 K->getAllMetadataOtherThanDebugLoc(Metadata);
2840 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2841 unsigned Kind = Metadata[i].first;
2842 MDNode *JMD = J->getMetadata(Kind);
2843 MDNode *KMD = Metadata[i].second;
2847 K->setMetadata(Kind, 0); // Remove unknown metadata
2849 case LLVMContext::MD_tbaa:
2850 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2852 case LLVMContext::MD_fpmath:
2853 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2859 // This function fuses the chosen instruction pairs into vector instructions,
2860 // taking care preserve any needed scalar outputs and, then, it reorders the
2861 // remaining instructions as needed (users of the first member of the pair
2862 // need to be moved to after the location of the second member of the pair
2863 // because the vector instruction is inserted in the location of the pair's
2865 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2866 std::vector<Value *> &PairableInsts,
2867 DenseMap<Value *, Value *> &ChosenPairs,
2868 DenseSet<ValuePair> &FixedOrderPairs,
2869 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2870 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2871 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps) {
2872 LLVMContext& Context = BB.getContext();
2874 // During the vectorization process, the order of the pairs to be fused
2875 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2876 // list. After a pair is fused, the flipped pair is removed from the list.
2877 DenseSet<ValuePair> FlippedPairs;
2878 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2879 E = ChosenPairs.end(); P != E; ++P)
2880 FlippedPairs.insert(ValuePair(P->second, P->first));
2881 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2882 E = FlippedPairs.end(); P != E; ++P)
2883 ChosenPairs.insert(*P);
2885 std::multimap<Value *, Value *> LoadMoveSet;
2886 DenseSet<ValuePair> LoadMoveSetPairs;
2887 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2888 LoadMoveSet, LoadMoveSetPairs);
2890 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2892 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2893 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2894 if (P == ChosenPairs.end()) {
2899 if (getDepthFactor(P->first) == 0) {
2900 // These instructions are not really fused, but are tracked as though
2901 // they are. Any case in which it would be interesting to fuse them
2902 // will be taken care of by InstCombine.
2908 Instruction *I = cast<Instruction>(P->first),
2909 *J = cast<Instruction>(P->second);
2911 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2912 " <-> " << *J << "\n");
2914 // Remove the pair and flipped pair from the list.
2915 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2916 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2917 ChosenPairs.erase(FP);
2918 ChosenPairs.erase(P);
2920 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
2921 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2923 " aborted because of non-trivial dependency cycle\n");
2929 // If the pair must have the other order, then flip it.
2930 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2931 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2932 // This pair does not have a fixed order, and so we might want to
2933 // flip it if that will yield fewer shuffles. We count the number
2934 // of dependencies connected via swaps, and those directly connected,
2935 // and flip the order if the number of swaps is greater.
2936 bool OrigOrder = true;
2937 VPPIteratorPair IP = ConnectedPairDeps.equal_range(ValuePair(I, J));
2938 if (IP.first == ConnectedPairDeps.end()) {
2939 IP = ConnectedPairDeps.equal_range(ValuePair(J, I));
2943 if (IP.first != ConnectedPairDeps.end()) {
2944 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
2945 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2946 Q != IP.second; ++Q) {
2947 DenseMap<VPPair, unsigned>::iterator R =
2948 PairConnectionTypes.find(VPPair(Q->second, Q->first));
2949 assert(R != PairConnectionTypes.end() &&
2950 "Cannot find pair connection type");
2951 if (R->second == PairConnectionDirect)
2953 else if (R->second == PairConnectionSwap)
2958 std::swap(NumDepsDirect, NumDepsSwap);
2960 if (NumDepsSwap > NumDepsDirect) {
2961 FlipPairOrder = true;
2962 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
2963 " <-> " << *J << "\n");
2968 Instruction *L = I, *H = J;
2972 // If the pair being fused uses the opposite order from that in the pair
2973 // connection map, then we need to flip the types.
2974 VPPIteratorPair IP = ConnectedPairs.equal_range(ValuePair(H, L));
2975 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2976 Q != IP.second; ++Q) {
2977 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(*Q);
2978 assert(R != PairConnectionTypes.end() &&
2979 "Cannot find pair connection type");
2980 if (R->second == PairConnectionDirect)
2981 R->second = PairConnectionSwap;
2982 else if (R->second == PairConnectionSwap)
2983 R->second = PairConnectionDirect;
2986 bool LBeforeH = !FlipPairOrder;
2987 unsigned NumOperands = I->getNumOperands();
2988 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2989 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
2992 // Make a copy of the original operation, change its type to the vector
2993 // type and replace its operands with the vector operands.
2994 Instruction *K = L->clone();
2997 else if (H->hasName())
3000 if (!isa<StoreInst>(K))
3001 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3003 combineMetadata(K, H);
3004 K->intersectOptionalDataWith(H);
3006 for (unsigned o = 0; o < NumOperands; ++o)
3007 K->setOperand(o, ReplacedOperands[o]);
3011 // Instruction insertion point:
3012 Instruction *InsertionPt = K;
3013 Instruction *K1 = 0, *K2 = 0;
3014 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3016 // The use tree of the first original instruction must be moved to after
3017 // the location of the second instruction. The entire use tree of the
3018 // first instruction is disjoint from the input tree of the second
3019 // (by definition), and so commutes with it.
3021 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3023 if (!isa<StoreInst>(I)) {
3024 L->replaceAllUsesWith(K1);
3025 H->replaceAllUsesWith(K2);
3026 AA->replaceWithNewValue(L, K1);
3027 AA->replaceWithNewValue(H, K2);
3030 // Instructions that may read from memory may be in the load move set.
3031 // Once an instruction is fused, we no longer need its move set, and so
3032 // the values of the map never need to be updated. However, when a load
3033 // is fused, we need to merge the entries from both instructions in the
3034 // pair in case those instructions were in the move set of some other
3035 // yet-to-be-fused pair. The loads in question are the keys of the map.
3036 if (I->mayReadFromMemory()) {
3037 std::vector<ValuePair> NewSetMembers;
3038 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
3039 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
3040 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
3041 N != IPairRange.second; ++N)
3042 NewSetMembers.push_back(ValuePair(K, N->second));
3043 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
3044 N != JPairRange.second; ++N)
3045 NewSetMembers.push_back(ValuePair(K, N->second));
3046 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3047 AE = NewSetMembers.end(); A != AE; ++A) {
3048 LoadMoveSet.insert(*A);
3049 LoadMoveSetPairs.insert(*A);
3053 // Before removing I, set the iterator to the next instruction.
3054 PI = llvm::next(BasicBlock::iterator(I));
3055 if (cast<Instruction>(PI) == J)
3060 I->eraseFromParent();
3061 J->eraseFromParent();
3063 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3067 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3071 char BBVectorize::ID = 0;
3072 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3073 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3074 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3075 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3076 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3077 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3078 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3080 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3081 return new BBVectorize(C);
3085 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3086 BBVectorize BBVectorizer(P, C);
3087 return BBVectorizer.vectorizeBB(BB);
3090 //===----------------------------------------------------------------------===//
3091 VectorizeConfig::VectorizeConfig() {
3092 VectorBits = ::VectorBits;
3093 VectorizeBools = !::NoBools;
3094 VectorizeInts = !::NoInts;
3095 VectorizeFloats = !::NoFloats;
3096 VectorizePointers = !::NoPointers;
3097 VectorizeCasts = !::NoCasts;
3098 VectorizeMath = !::NoMath;
3099 VectorizeFMA = !::NoFMA;
3100 VectorizeSelect = !::NoSelect;
3101 VectorizeCmp = !::NoCmp;
3102 VectorizeGEP = !::NoGEP;
3103 VectorizeMemOps = !::NoMemOps;
3104 AlignedOnly = ::AlignedOnly;
3105 ReqChainDepth= ::ReqChainDepth;
3106 SearchLimit = ::SearchLimit;
3107 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3108 SplatBreaksChain = ::SplatBreaksChain;
3109 MaxInsts = ::MaxInsts;
3110 MaxIter = ::MaxIter;
3111 Pow2LenOnly = ::Pow2LenOnly;
3112 NoMemOpBoost = ::NoMemOpBoost;
3113 FastDep = ::FastDep;