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 DenseSet<ValuePair> &CandidatePairsSet,
244 std::vector<Value *> &PairableInsts,
245 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
246 DenseMap<VPPair, unsigned> &PairConnectionTypes);
248 void buildDepMap(BasicBlock &BB,
249 std::multimap<Value *, Value *> &CandidatePairs,
250 std::vector<Value *> &PairableInsts,
251 DenseSet<ValuePair> &PairableInstUsers);
253 void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
254 DenseSet<ValuePair> &CandidatePairsSet,
255 DenseMap<ValuePair, int> &CandidatePairCostSavings,
256 std::vector<Value *> &PairableInsts,
257 DenseSet<ValuePair> &FixedOrderPairs,
258 DenseMap<VPPair, unsigned> &PairConnectionTypes,
259 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
260 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
261 DenseSet<ValuePair> &PairableInstUsers,
262 DenseMap<Value *, Value *>& ChosenPairs);
264 void fuseChosenPairs(BasicBlock &BB,
265 std::vector<Value *> &PairableInsts,
266 DenseMap<Value *, Value *>& ChosenPairs,
267 DenseSet<ValuePair> &FixedOrderPairs,
268 DenseMap<VPPair, unsigned> &PairConnectionTypes,
269 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
270 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps);
273 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
275 bool areInstsCompatible(Instruction *I, Instruction *J,
276 bool IsSimpleLoadStore, bool NonPow2Len,
277 int &CostSavings, int &FixedOrder);
279 bool trackUsesOfI(DenseSet<Value *> &Users,
280 AliasSetTracker &WriteSet, Instruction *I,
281 Instruction *J, bool UpdateUsers = true,
282 DenseSet<ValuePair> *LoadMoveSetPairs = 0);
284 void computePairsConnectedTo(
285 std::multimap<Value *, Value *> &CandidatePairs,
286 DenseSet<ValuePair> &CandidatePairsSet,
287 std::vector<Value *> &PairableInsts,
288 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
289 DenseMap<VPPair, unsigned> &PairConnectionTypes,
292 bool pairsConflict(ValuePair P, ValuePair Q,
293 DenseSet<ValuePair> &PairableInstUsers,
294 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0,
295 DenseSet<VPPair> *PairableInstUserPairSet = 0);
297 bool pairWillFormCycle(ValuePair P,
298 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
299 DenseSet<ValuePair> &CurrentPairs);
302 std::multimap<Value *, Value *> &CandidatePairs,
303 std::vector<Value *> &PairableInsts,
304 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
305 DenseSet<ValuePair> &PairableInstUsers,
306 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
307 DenseSet<VPPair> &PairableInstUserPairSet,
308 DenseMap<Value *, Value *> &ChosenPairs,
309 DenseMap<ValuePair, size_t> &Tree,
310 DenseSet<ValuePair> &PrunedTree, ValuePair J,
313 void buildInitialTreeFor(
314 std::multimap<Value *, Value *> &CandidatePairs,
315 DenseSet<ValuePair> &CandidatePairsSet,
316 std::vector<Value *> &PairableInsts,
317 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
318 DenseSet<ValuePair> &PairableInstUsers,
319 DenseMap<Value *, Value *> &ChosenPairs,
320 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
322 void findBestTreeFor(
323 std::multimap<Value *, Value *> &CandidatePairs,
324 DenseSet<ValuePair> &CandidatePairsSet,
325 DenseMap<ValuePair, int> &CandidatePairCostSavings,
326 std::vector<Value *> &PairableInsts,
327 DenseSet<ValuePair> &FixedOrderPairs,
328 DenseMap<VPPair, unsigned> &PairConnectionTypes,
329 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
330 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
331 DenseSet<ValuePair> &PairableInstUsers,
332 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
333 DenseSet<VPPair> &PairableInstUserPairSet,
334 DenseMap<Value *, Value *> &ChosenPairs,
335 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
336 int &BestEffSize, VPIteratorPair ChoiceRange,
339 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
340 Instruction *J, unsigned o);
342 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
343 unsigned MaskOffset, unsigned NumInElem,
344 unsigned NumInElem1, unsigned IdxOffset,
345 std::vector<Constant*> &Mask);
347 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
350 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
351 unsigned o, Value *&LOp, unsigned numElemL,
352 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
353 unsigned IdxOff = 0);
355 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
356 Instruction *J, unsigned o, bool IBeforeJ);
358 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
359 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
362 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
363 Instruction *J, Instruction *K,
364 Instruction *&InsertionPt, Instruction *&K1,
367 void collectPairLoadMoveSet(BasicBlock &BB,
368 DenseMap<Value *, Value *> &ChosenPairs,
369 std::multimap<Value *, Value *> &LoadMoveSet,
370 DenseSet<ValuePair> &LoadMoveSetPairs,
373 void collectLoadMoveSet(BasicBlock &BB,
374 std::vector<Value *> &PairableInsts,
375 DenseMap<Value *, Value *> &ChosenPairs,
376 std::multimap<Value *, Value *> &LoadMoveSet,
377 DenseSet<ValuePair> &LoadMoveSetPairs);
379 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
380 DenseSet<ValuePair> &LoadMoveSetPairs,
381 Instruction *I, Instruction *J);
383 void moveUsesOfIAfterJ(BasicBlock &BB,
384 DenseSet<ValuePair> &LoadMoveSetPairs,
385 Instruction *&InsertionPt,
386 Instruction *I, Instruction *J);
388 void combineMetadata(Instruction *K, const Instruction *J);
390 bool vectorizeBB(BasicBlock &BB) {
391 if (!DT->isReachableFromEntry(&BB)) {
392 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
393 " in " << BB.getParent()->getName() << "\n");
397 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
399 bool changed = false;
400 // Iterate a sufficient number of times to merge types of size 1 bit,
401 // then 2 bits, then 4, etc. up to half of the target vector width of the
402 // target vector register.
405 (TTI || v <= Config.VectorBits) &&
406 (!Config.MaxIter || n <= Config.MaxIter);
408 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
409 " for " << BB.getName() << " in " <<
410 BB.getParent()->getName() << "...\n");
411 if (vectorizePairs(BB))
417 if (changed && !Pow2LenOnly) {
419 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
420 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
421 n << " for " << BB.getName() << " in " <<
422 BB.getParent()->getName() << "...\n");
423 if (!vectorizePairs(BB, true)) break;
427 DEBUG(dbgs() << "BBV: done!\n");
431 virtual bool runOnBasicBlock(BasicBlock &BB) {
432 AA = &getAnalysis<AliasAnalysis>();
433 DT = &getAnalysis<DominatorTree>();
434 SE = &getAnalysis<ScalarEvolution>();
435 TD = getAnalysisIfAvailable<DataLayout>();
436 TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
438 return vectorizeBB(BB);
441 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
442 BasicBlockPass::getAnalysisUsage(AU);
443 AU.addRequired<AliasAnalysis>();
444 AU.addRequired<DominatorTree>();
445 AU.addRequired<ScalarEvolution>();
446 AU.addRequired<TargetTransformInfo>();
447 AU.addPreserved<AliasAnalysis>();
448 AU.addPreserved<DominatorTree>();
449 AU.addPreserved<ScalarEvolution>();
450 AU.setPreservesCFG();
453 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
454 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
455 "Cannot form vector from incompatible scalar types");
456 Type *STy = ElemTy->getScalarType();
459 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
460 numElem = VTy->getNumElements();
465 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
466 numElem += VTy->getNumElements();
471 return VectorType::get(STy, numElem);
474 static inline void getInstructionTypes(Instruction *I,
475 Type *&T1, Type *&T2) {
476 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
477 // For stores, it is the value type, not the pointer type that matters
478 // because the value is what will come from a vector register.
480 Value *IVal = SI->getValueOperand();
481 T1 = IVal->getType();
486 if (CastInst *CI = dyn_cast<CastInst>(I))
491 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
492 T2 = SI->getCondition()->getType();
493 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
494 T2 = SI->getOperand(0)->getType();
495 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
496 T2 = CI->getOperand(0)->getType();
500 // Returns the weight associated with the provided value. A chain of
501 // candidate pairs has a length given by the sum of the weights of its
502 // members (one weight per pair; the weight of each member of the pair
503 // is assumed to be the same). This length is then compared to the
504 // chain-length threshold to determine if a given chain is significant
505 // enough to be vectorized. The length is also used in comparing
506 // candidate chains where longer chains are considered to be better.
507 // Note: when this function returns 0, the resulting instructions are
508 // not actually fused.
509 inline size_t getDepthFactor(Value *V) {
510 // InsertElement and ExtractElement have a depth factor of zero. This is
511 // for two reasons: First, they cannot be usefully fused. Second, because
512 // the pass generates a lot of these, they can confuse the simple metric
513 // used to compare the trees in the next iteration. Thus, giving them a
514 // weight of zero allows the pass to essentially ignore them in
515 // subsequent iterations when looking for vectorization opportunities
516 // while still tracking dependency chains that flow through those
518 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
521 // Give a load or store half of the required depth so that load/store
522 // pairs will vectorize.
523 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
524 return Config.ReqChainDepth/2;
529 // Returns the cost of the provided instruction using TTI.
530 // This does not handle loads and stores.
531 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
534 case Instruction::GetElementPtr:
535 // We mark this instruction as zero-cost because scalar GEPs are usually
536 // lowered to the intruction addressing mode. At the moment we don't
537 // generate vector GEPs.
539 case Instruction::Br:
540 return TTI->getCFInstrCost(Opcode);
541 case Instruction::PHI:
543 case Instruction::Add:
544 case Instruction::FAdd:
545 case Instruction::Sub:
546 case Instruction::FSub:
547 case Instruction::Mul:
548 case Instruction::FMul:
549 case Instruction::UDiv:
550 case Instruction::SDiv:
551 case Instruction::FDiv:
552 case Instruction::URem:
553 case Instruction::SRem:
554 case Instruction::FRem:
555 case Instruction::Shl:
556 case Instruction::LShr:
557 case Instruction::AShr:
558 case Instruction::And:
559 case Instruction::Or:
560 case Instruction::Xor:
561 return TTI->getArithmeticInstrCost(Opcode, T1);
562 case Instruction::Select:
563 case Instruction::ICmp:
564 case Instruction::FCmp:
565 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
566 case Instruction::ZExt:
567 case Instruction::SExt:
568 case Instruction::FPToUI:
569 case Instruction::FPToSI:
570 case Instruction::FPExt:
571 case Instruction::PtrToInt:
572 case Instruction::IntToPtr:
573 case Instruction::SIToFP:
574 case Instruction::UIToFP:
575 case Instruction::Trunc:
576 case Instruction::FPTrunc:
577 case Instruction::BitCast:
578 case Instruction::ShuffleVector:
579 return TTI->getCastInstrCost(Opcode, T1, T2);
585 // This determines the relative offset of two loads or stores, returning
586 // true if the offset could be determined to be some constant value.
587 // For example, if OffsetInElmts == 1, then J accesses the memory directly
588 // after I; if OffsetInElmts == -1 then I accesses the memory
590 bool getPairPtrInfo(Instruction *I, Instruction *J,
591 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
592 unsigned &IAddressSpace, unsigned &JAddressSpace,
593 int64_t &OffsetInElmts, bool ComputeOffset = true) {
595 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
596 LoadInst *LJ = cast<LoadInst>(J);
597 IPtr = LI->getPointerOperand();
598 JPtr = LJ->getPointerOperand();
599 IAlignment = LI->getAlignment();
600 JAlignment = LJ->getAlignment();
601 IAddressSpace = LI->getPointerAddressSpace();
602 JAddressSpace = LJ->getPointerAddressSpace();
604 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
605 IPtr = SI->getPointerOperand();
606 JPtr = SJ->getPointerOperand();
607 IAlignment = SI->getAlignment();
608 JAlignment = SJ->getAlignment();
609 IAddressSpace = SI->getPointerAddressSpace();
610 JAddressSpace = SJ->getPointerAddressSpace();
616 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
617 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
619 // If this is a trivial offset, then we'll get something like
620 // 1*sizeof(type). With target data, which we need anyway, this will get
621 // constant folded into a number.
622 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
623 if (const SCEVConstant *ConstOffSCEV =
624 dyn_cast<SCEVConstant>(OffsetSCEV)) {
625 ConstantInt *IntOff = ConstOffSCEV->getValue();
626 int64_t Offset = IntOff->getSExtValue();
628 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
629 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
631 Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
632 if (VTy != VTy2 && Offset < 0) {
633 int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
634 OffsetInElmts = Offset/VTy2TSS;
635 return (abs64(Offset) % VTy2TSS) == 0;
638 OffsetInElmts = Offset/VTyTSS;
639 return (abs64(Offset) % VTyTSS) == 0;
645 // Returns true if the provided CallInst represents an intrinsic that can
647 bool isVectorizableIntrinsic(CallInst* I) {
648 Function *F = I->getCalledFunction();
649 if (!F) return false;
651 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
652 if (!IID) return false;
657 case Intrinsic::sqrt:
658 case Intrinsic::powi:
662 case Intrinsic::log2:
663 case Intrinsic::log10:
665 case Intrinsic::exp2:
667 return Config.VectorizeMath;
669 case Intrinsic::fmuladd:
670 return Config.VectorizeFMA;
674 bool isPureIEChain(InsertElementInst *IE) {
675 InsertElementInst *IENext = IE;
677 if (!isa<UndefValue>(IENext->getOperand(0)) &&
678 !isa<InsertElementInst>(IENext->getOperand(0))) {
682 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
688 // This function implements one vectorization iteration on the provided
689 // basic block. It returns true if the block is changed.
690 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
692 BasicBlock::iterator Start = BB.getFirstInsertionPt();
694 std::vector<Value *> AllPairableInsts;
695 DenseMap<Value *, Value *> AllChosenPairs;
696 DenseSet<ValuePair> AllFixedOrderPairs;
697 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
698 std::multimap<ValuePair, ValuePair> AllConnectedPairs, AllConnectedPairDeps;
701 std::vector<Value *> PairableInsts;
702 std::multimap<Value *, Value *> CandidatePairs;
703 DenseSet<ValuePair> FixedOrderPairs;
704 DenseMap<ValuePair, int> CandidatePairCostSavings;
705 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
707 CandidatePairCostSavings,
708 PairableInsts, NonPow2Len);
709 if (PairableInsts.empty()) continue;
711 // Build the candidate pair set for faster lookups.
712 DenseSet<ValuePair> CandidatePairsSet;
713 for (std::multimap<Value *, Value *>::iterator I = CandidatePairs.begin(),
714 E = CandidatePairs.end(); I != E; ++I)
715 CandidatePairsSet.insert(*I);
717 // Now we have a map of all of the pairable instructions and we need to
718 // select the best possible pairing. A good pairing is one such that the
719 // users of the pair are also paired. This defines a (directed) forest
720 // over the pairs such that two pairs are connected iff the second pair
723 // Note that it only matters that both members of the second pair use some
724 // element of the first pair (to allow for splatting).
726 std::multimap<ValuePair, ValuePair> ConnectedPairs, ConnectedPairDeps;
727 DenseMap<VPPair, unsigned> PairConnectionTypes;
728 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
729 PairableInsts, ConnectedPairs, PairConnectionTypes);
730 if (ConnectedPairs.empty()) continue;
732 for (std::multimap<ValuePair, ValuePair>::iterator
733 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
735 ConnectedPairDeps.insert(VPPair(I->second, I->first));
738 // Build the pairable-instruction dependency map
739 DenseSet<ValuePair> PairableInstUsers;
740 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
742 // There is now a graph of the connected pairs. For each variable, pick
743 // the pairing with the largest tree meeting the depth requirement on at
744 // least one branch. Then select all pairings that are part of that tree
745 // and remove them from the list of available pairings and pairable
748 DenseMap<Value *, Value *> ChosenPairs;
749 choosePairs(CandidatePairs, CandidatePairsSet,
750 CandidatePairCostSavings,
751 PairableInsts, FixedOrderPairs, PairConnectionTypes,
752 ConnectedPairs, ConnectedPairDeps,
753 PairableInstUsers, ChosenPairs);
755 if (ChosenPairs.empty()) continue;
756 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
757 PairableInsts.end());
758 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
760 // Only for the chosen pairs, propagate information on fixed-order pairs,
761 // pair connections, and their types to the data structures used by the
762 // pair fusion procedures.
763 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
764 IE = ChosenPairs.end(); I != IE; ++I) {
765 if (FixedOrderPairs.count(*I))
766 AllFixedOrderPairs.insert(*I);
767 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
768 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
770 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
772 DenseMap<VPPair, unsigned>::iterator K =
773 PairConnectionTypes.find(VPPair(*I, *J));
774 if (K != PairConnectionTypes.end()) {
775 AllPairConnectionTypes.insert(*K);
777 K = PairConnectionTypes.find(VPPair(*J, *I));
778 if (K != PairConnectionTypes.end())
779 AllPairConnectionTypes.insert(*K);
784 for (std::multimap<ValuePair, ValuePair>::iterator
785 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
787 if (AllPairConnectionTypes.count(*I)) {
788 AllConnectedPairs.insert(*I);
789 AllConnectedPairDeps.insert(VPPair(I->second, I->first));
792 } while (ShouldContinue);
794 if (AllChosenPairs.empty()) return false;
795 NumFusedOps += AllChosenPairs.size();
797 // A set of pairs has now been selected. It is now necessary to replace the
798 // paired instructions with vector instructions. For this procedure each
799 // operand must be replaced with a vector operand. This vector is formed
800 // by using build_vector on the old operands. The replaced values are then
801 // replaced with a vector_extract on the result. Subsequent optimization
802 // passes should coalesce the build/extract combinations.
804 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
805 AllPairConnectionTypes,
806 AllConnectedPairs, AllConnectedPairDeps);
808 // It is important to cleanup here so that future iterations of this
809 // function have less work to do.
810 (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
814 // This function returns true if the provided instruction is capable of being
815 // fused into a vector instruction. This determination is based only on the
816 // type and other attributes of the instruction.
817 bool BBVectorize::isInstVectorizable(Instruction *I,
818 bool &IsSimpleLoadStore) {
819 IsSimpleLoadStore = false;
821 if (CallInst *C = dyn_cast<CallInst>(I)) {
822 if (!isVectorizableIntrinsic(C))
824 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
825 // Vectorize simple loads if possbile:
826 IsSimpleLoadStore = L->isSimple();
827 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
829 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
830 // Vectorize simple stores if possbile:
831 IsSimpleLoadStore = S->isSimple();
832 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
834 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
835 // We can vectorize casts, but not casts of pointer types, etc.
836 if (!Config.VectorizeCasts)
839 Type *SrcTy = C->getSrcTy();
840 if (!SrcTy->isSingleValueType())
843 Type *DestTy = C->getDestTy();
844 if (!DestTy->isSingleValueType())
846 } else if (isa<SelectInst>(I)) {
847 if (!Config.VectorizeSelect)
849 } else if (isa<CmpInst>(I)) {
850 if (!Config.VectorizeCmp)
852 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
853 if (!Config.VectorizeGEP)
856 // Currently, vector GEPs exist only with one index.
857 if (G->getNumIndices() != 1)
859 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
860 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
864 // We can't vectorize memory operations without target data
865 if (TD == 0 && IsSimpleLoadStore)
869 getInstructionTypes(I, T1, T2);
871 // Not every type can be vectorized...
872 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
873 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
876 if (T1->getScalarSizeInBits() == 1) {
877 if (!Config.VectorizeBools)
880 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
884 if (T2->getScalarSizeInBits() == 1) {
885 if (!Config.VectorizeBools)
888 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
892 if (!Config.VectorizeFloats
893 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
896 // Don't vectorize target-specific types.
897 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
899 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
902 if ((!Config.VectorizePointers || TD == 0) &&
903 (T1->getScalarType()->isPointerTy() ||
904 T2->getScalarType()->isPointerTy()))
907 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
908 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
914 // This function returns true if the two provided instructions are compatible
915 // (meaning that they can be fused into a vector instruction). This assumes
916 // that I has already been determined to be vectorizable and that J is not
917 // in the use tree of I.
918 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
919 bool IsSimpleLoadStore, bool NonPow2Len,
920 int &CostSavings, int &FixedOrder) {
921 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
922 " <-> " << *J << "\n");
927 // Loads and stores can be merged if they have different alignments,
928 // but are otherwise the same.
929 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
930 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
933 Type *IT1, *IT2, *JT1, *JT2;
934 getInstructionTypes(I, IT1, IT2);
935 getInstructionTypes(J, JT1, JT2);
936 unsigned MaxTypeBits = std::max(
937 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
938 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
939 if (!TTI && MaxTypeBits > Config.VectorBits)
942 // FIXME: handle addsub-type operations!
944 if (IsSimpleLoadStore) {
946 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
947 int64_t OffsetInElmts = 0;
948 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
949 IAddressSpace, JAddressSpace,
950 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
951 FixedOrder = (int) OffsetInElmts;
952 unsigned BottomAlignment = IAlignment;
953 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
955 Type *aTypeI = isa<StoreInst>(I) ?
956 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
957 Type *aTypeJ = isa<StoreInst>(J) ?
958 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
959 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
961 if (Config.AlignedOnly) {
962 // An aligned load or store is possible only if the instruction
963 // with the lower offset has an alignment suitable for the
966 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
967 if (BottomAlignment < VecAlignment)
972 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
973 IAlignment, IAddressSpace);
974 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
975 JAlignment, JAddressSpace);
976 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
980 ICost += TTI->getAddressComputationCost(aTypeI);
981 JCost += TTI->getAddressComputationCost(aTypeJ);
982 VCost += TTI->getAddressComputationCost(VType);
984 if (VCost > ICost + JCost)
987 // We don't want to fuse to a type that will be split, even
988 // if the two input types will also be split and there is no other
990 unsigned VParts = TTI->getNumberOfParts(VType);
993 else if (!VParts && VCost == ICost + JCost)
996 CostSavings = ICost + JCost - VCost;
1002 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1003 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1004 Type *VT1 = getVecTypeForPair(IT1, JT1),
1005 *VT2 = getVecTypeForPair(IT2, JT2);
1007 // Note that this procedure is incorrect for insert and extract element
1008 // instructions (because combining these often results in a shuffle),
1009 // but this cost is ignored (because insert and extract element
1010 // instructions are assigned a zero depth factor and are not really
1011 // fused in general).
1012 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
1014 if (VCost > ICost + JCost)
1017 // We don't want to fuse to a type that will be split, even
1018 // if the two input types will also be split and there is no other
1020 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1021 VParts2 = TTI->getNumberOfParts(VT2);
1022 if (VParts1 > 1 || VParts2 > 1)
1024 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1027 CostSavings = ICost + JCost - VCost;
1030 // The powi intrinsic is special because only the first argument is
1031 // vectorized, the second arguments must be equal.
1032 CallInst *CI = dyn_cast<CallInst>(I);
1034 if (CI && (FI = CI->getCalledFunction())) {
1035 Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1036 if (IID == Intrinsic::powi) {
1037 Value *A1I = CI->getArgOperand(1),
1038 *A1J = cast<CallInst>(J)->getArgOperand(1);
1039 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1040 *A1JSCEV = SE->getSCEV(A1J);
1041 return (A1ISCEV == A1JSCEV);
1045 SmallVector<Type*, 4> Tys;
1046 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1047 Tys.push_back(CI->getArgOperand(i)->getType());
1048 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1051 CallInst *CJ = cast<CallInst>(J);
1052 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1053 Tys.push_back(CJ->getArgOperand(i)->getType());
1054 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1057 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1058 "Intrinsic argument counts differ");
1059 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1060 if (IID == Intrinsic::powi && i == 1)
1061 Tys.push_back(CI->getArgOperand(i)->getType());
1063 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1064 CJ->getArgOperand(i)->getType()));
1067 Type *RetTy = getVecTypeForPair(IT1, JT1);
1068 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1070 if (VCost > ICost + JCost)
1073 // We don't want to fuse to a type that will be split, even
1074 // if the two input types will also be split and there is no other
1076 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1079 else if (!RetParts && VCost == ICost + JCost)
1082 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1083 if (!Tys[i]->isVectorTy())
1086 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1089 else if (!NumParts && VCost == ICost + JCost)
1093 CostSavings = ICost + JCost - VCost;
1100 // Figure out whether or not J uses I and update the users and write-set
1101 // structures associated with I. Specifically, Users represents the set of
1102 // instructions that depend on I. WriteSet represents the set
1103 // of memory locations that are dependent on I. If UpdateUsers is true,
1104 // and J uses I, then Users is updated to contain J and WriteSet is updated
1105 // to contain any memory locations to which J writes. The function returns
1106 // true if J uses I. By default, alias analysis is used to determine
1107 // whether J reads from memory that overlaps with a location in WriteSet.
1108 // If LoadMoveSet is not null, then it is a previously-computed multimap
1109 // where the key is the memory-based user instruction and the value is
1110 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1111 // then the alias analysis is not used. This is necessary because this
1112 // function is called during the process of moving instructions during
1113 // vectorization and the results of the alias analysis are not stable during
1115 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1116 AliasSetTracker &WriteSet, Instruction *I,
1117 Instruction *J, bool UpdateUsers,
1118 DenseSet<ValuePair> *LoadMoveSetPairs) {
1121 // This instruction may already be marked as a user due, for example, to
1122 // being a member of a selected pair.
1127 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1130 if (I == V || Users.count(V)) {
1135 if (!UsesI && J->mayReadFromMemory()) {
1136 if (LoadMoveSetPairs) {
1137 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1139 for (AliasSetTracker::iterator W = WriteSet.begin(),
1140 WE = WriteSet.end(); W != WE; ++W) {
1141 if (W->aliasesUnknownInst(J, *AA)) {
1149 if (UsesI && UpdateUsers) {
1150 if (J->mayWriteToMemory()) WriteSet.add(J);
1157 // This function iterates over all instruction pairs in the provided
1158 // basic block and collects all candidate pairs for vectorization.
1159 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1160 BasicBlock::iterator &Start,
1161 std::multimap<Value *, Value *> &CandidatePairs,
1162 DenseSet<ValuePair> &FixedOrderPairs,
1163 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1164 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1165 BasicBlock::iterator E = BB.end();
1166 if (Start == E) return false;
1168 bool ShouldContinue = false, IAfterStart = false;
1169 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1170 if (I == Start) IAfterStart = true;
1172 bool IsSimpleLoadStore;
1173 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1175 // Look for an instruction with which to pair instruction *I...
1176 DenseSet<Value *> Users;
1177 AliasSetTracker WriteSet(*AA);
1178 bool JAfterStart = IAfterStart;
1179 BasicBlock::iterator J = llvm::next(I);
1180 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1181 if (J == Start) JAfterStart = true;
1183 // Determine if J uses I, if so, exit the loop.
1184 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1185 if (Config.FastDep) {
1186 // Note: For this heuristic to be effective, independent operations
1187 // must tend to be intermixed. This is likely to be true from some
1188 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1189 // but otherwise may require some kind of reordering pass.
1191 // When using fast dependency analysis,
1192 // stop searching after first use:
1195 if (UsesI) continue;
1198 // J does not use I, and comes before the first use of I, so it can be
1199 // merged with I if the instructions are compatible.
1200 int CostSavings, FixedOrder;
1201 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1202 CostSavings, FixedOrder)) continue;
1204 // J is a candidate for merging with I.
1205 if (!PairableInsts.size() ||
1206 PairableInsts[PairableInsts.size()-1] != I) {
1207 PairableInsts.push_back(I);
1210 CandidatePairs.insert(ValuePair(I, J));
1212 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1215 if (FixedOrder == 1)
1216 FixedOrderPairs.insert(ValuePair(I, J));
1217 else if (FixedOrder == -1)
1218 FixedOrderPairs.insert(ValuePair(J, I));
1220 // The next call to this function must start after the last instruction
1221 // selected during this invocation.
1223 Start = llvm::next(J);
1224 IAfterStart = JAfterStart = false;
1227 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1228 << *I << " <-> " << *J << " (cost savings: " <<
1229 CostSavings << ")\n");
1231 // If we have already found too many pairs, break here and this function
1232 // will be called again starting after the last instruction selected
1233 // during this invocation.
1234 if (PairableInsts.size() >= Config.MaxInsts) {
1235 ShouldContinue = true;
1244 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1245 << " instructions with candidate pairs\n");
1247 return ShouldContinue;
1250 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1251 // it looks for pairs such that both members have an input which is an
1252 // output of PI or PJ.
1253 void BBVectorize::computePairsConnectedTo(
1254 std::multimap<Value *, Value *> &CandidatePairs,
1255 DenseSet<ValuePair> &CandidatePairsSet,
1256 std::vector<Value *> &PairableInsts,
1257 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1258 DenseMap<VPPair, unsigned> &PairConnectionTypes,
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 // For each use of the first variable, look for uses of the second
1279 for (Value::use_iterator J = P.second->use_begin(),
1280 E2 = P.second->use_end(); J != E2; ++J) {
1281 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1282 P.second == SJ->getPointerOperand())
1286 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1287 VPPair VP(P, ValuePair(*I, *J));
1288 ConnectedPairs.insert(VP);
1289 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1293 if (CandidatePairsSet.count(ValuePair(*J, *I))) {
1294 VPPair VP(P, ValuePair(*J, *I));
1295 ConnectedPairs.insert(VP);
1296 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1300 if (Config.SplatBreaksChain) continue;
1301 // Look for cases where just the first value in the pair is used by
1302 // both members of another pair (splatting).
1303 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1304 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1305 P.first == SJ->getPointerOperand())
1308 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1309 VPPair VP(P, ValuePair(*I, *J));
1310 ConnectedPairs.insert(VP);
1311 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1316 if (Config.SplatBreaksChain) return;
1317 // Look for cases where just the second value in the pair is used by
1318 // both members of another pair (splatting).
1319 for (Value::use_iterator I = P.second->use_begin(),
1320 E = P.second->use_end(); I != E; ++I) {
1321 if (isa<LoadInst>(*I))
1323 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1324 P.second == SI->getPointerOperand())
1327 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1328 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1329 P.second == SJ->getPointerOperand())
1332 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1333 VPPair VP(P, ValuePair(*I, *J));
1334 ConnectedPairs.insert(VP);
1335 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1341 // This function figures out which pairs are connected. Two pairs are
1342 // connected if some output of the first pair forms an input to both members
1343 // of the second pair.
1344 void BBVectorize::computeConnectedPairs(
1345 std::multimap<Value *, Value *> &CandidatePairs,
1346 DenseSet<ValuePair> &CandidatePairsSet,
1347 std::vector<Value *> &PairableInsts,
1348 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1349 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1350 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1351 PE = PairableInsts.end(); PI != PE; ++PI) {
1352 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1354 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1355 P != choiceRange.second; ++P)
1356 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1357 PairableInsts, ConnectedPairs,
1358 PairConnectionTypes, *P);
1361 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1362 << " pair connections.\n");
1365 // This function builds a set of use tuples such that <A, B> is in the set
1366 // if B is in the use tree of A. If B is in the use tree of A, then B
1367 // depends on the output of A.
1368 void BBVectorize::buildDepMap(
1370 std::multimap<Value *, Value *> &CandidatePairs,
1371 std::vector<Value *> &PairableInsts,
1372 DenseSet<ValuePair> &PairableInstUsers) {
1373 DenseSet<Value *> IsInPair;
1374 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1375 E = CandidatePairs.end(); C != E; ++C) {
1376 IsInPair.insert(C->first);
1377 IsInPair.insert(C->second);
1380 // Iterate through the basic block, recording all users of each
1381 // pairable instruction.
1383 BasicBlock::iterator E = BB.end(), EL =
1384 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1385 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1386 if (IsInPair.find(I) == IsInPair.end()) continue;
1388 DenseSet<Value *> Users;
1389 AliasSetTracker WriteSet(*AA);
1390 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J) {
1391 (void) trackUsesOfI(Users, WriteSet, I, J);
1397 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1399 if (IsInPair.find(*U) == IsInPair.end()) continue;
1400 PairableInstUsers.insert(ValuePair(I, *U));
1408 // Returns true if an input to pair P is an output of pair Q and also an
1409 // input of pair Q is an output of pair P. If this is the case, then these
1410 // two pairs cannot be simultaneously fused.
1411 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1412 DenseSet<ValuePair> &PairableInstUsers,
1413 std::multimap<ValuePair, ValuePair> *PairableInstUserMap,
1414 DenseSet<VPPair> *PairableInstUserPairSet) {
1415 // Two pairs are in conflict if they are mutual Users of eachother.
1416 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1417 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1418 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1419 PairableInstUsers.count(ValuePair(P.second, Q.second));
1420 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1421 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1422 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1423 PairableInstUsers.count(ValuePair(Q.second, P.second));
1424 if (PairableInstUserMap) {
1425 // FIXME: The expensive part of the cycle check is not so much the cycle
1426 // check itself but this edge insertion procedure. This needs some
1427 // profiling and probably a different data structure (same is true of
1428 // most uses of std::multimap).
1430 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1431 PairableInstUserMap->insert(VPPair(Q, P));
1434 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1435 PairableInstUserMap->insert(VPPair(P, Q));
1439 return (QUsesP && PUsesQ);
1442 // This function walks the use graph of current pairs to see if, starting
1443 // from P, the walk returns to P.
1444 bool BBVectorize::pairWillFormCycle(ValuePair P,
1445 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1446 DenseSet<ValuePair> &CurrentPairs) {
1447 DEBUG(if (DebugCycleCheck)
1448 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1449 << *P.second << "\n");
1450 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1451 // contains non-direct associations.
1452 DenseSet<ValuePair> Visited;
1453 SmallVector<ValuePair, 32> Q;
1454 // General depth-first post-order traversal:
1457 ValuePair QTop = Q.pop_back_val();
1458 Visited.insert(QTop);
1460 DEBUG(if (DebugCycleCheck)
1461 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1462 << *QTop.second << "\n");
1463 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1464 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1465 C != QPairRange.second; ++C) {
1466 if (C->second == P) {
1468 << "BBV: rejected to prevent non-trivial cycle formation: "
1469 << *C->first.first << " <-> " << *C->first.second << "\n");
1473 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1474 Q.push_back(C->second);
1476 } while (!Q.empty());
1481 // This function builds the initial tree of connected pairs with the
1482 // pair J at the root.
1483 void BBVectorize::buildInitialTreeFor(
1484 std::multimap<Value *, Value *> &CandidatePairs,
1485 DenseSet<ValuePair> &CandidatePairsSet,
1486 std::vector<Value *> &PairableInsts,
1487 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1488 DenseSet<ValuePair> &PairableInstUsers,
1489 DenseMap<Value *, Value *> &ChosenPairs,
1490 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1491 // Each of these pairs is viewed as the root node of a Tree. The Tree
1492 // is then walked (depth-first). As this happens, we keep track of
1493 // the pairs that compose the Tree and the maximum depth of the Tree.
1494 SmallVector<ValuePairWithDepth, 32> Q;
1495 // General depth-first post-order traversal:
1496 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1498 ValuePairWithDepth QTop = Q.back();
1500 // Push each child onto the queue:
1501 bool MoreChildren = false;
1502 size_t MaxChildDepth = QTop.second;
1503 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1504 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1505 k != qtRange.second; ++k) {
1506 // Make sure that this child pair is still a candidate:
1507 if (CandidatePairsSet.count(ValuePair(k->second))) {
1508 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1509 if (C == Tree.end()) {
1510 size_t d = getDepthFactor(k->second.first);
1511 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1512 MoreChildren = true;
1514 MaxChildDepth = std::max(MaxChildDepth, C->second);
1519 if (!MoreChildren) {
1520 // Record the current pair as part of the Tree:
1521 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1524 } while (!Q.empty());
1527 // Given some initial tree, prune it by removing conflicting pairs (pairs
1528 // that cannot be simultaneously chosen for vectorization).
1529 void BBVectorize::pruneTreeFor(
1530 std::multimap<Value *, Value *> &CandidatePairs,
1531 std::vector<Value *> &PairableInsts,
1532 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1533 DenseSet<ValuePair> &PairableInstUsers,
1534 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1535 DenseSet<VPPair> &PairableInstUserPairSet,
1536 DenseMap<Value *, Value *> &ChosenPairs,
1537 DenseMap<ValuePair, size_t> &Tree,
1538 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1539 bool UseCycleCheck) {
1540 SmallVector<ValuePairWithDepth, 32> Q;
1541 // General depth-first post-order traversal:
1542 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1544 ValuePairWithDepth QTop = Q.pop_back_val();
1545 PrunedTree.insert(QTop.first);
1547 // Visit each child, pruning as necessary...
1548 SmallVector<ValuePairWithDepth, 8> BestChildren;
1549 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1550 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1551 K != QTopRange.second; ++K) {
1552 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1553 if (C == Tree.end()) continue;
1555 // This child is in the Tree, now we need to make sure it is the
1556 // best of any conflicting children. There could be multiple
1557 // conflicting children, so first, determine if we're keeping
1558 // this child, then delete conflicting children as necessary.
1560 // It is also necessary to guard against pairing-induced
1561 // dependencies. Consider instructions a .. x .. y .. b
1562 // such that (a,b) are to be fused and (x,y) are to be fused
1563 // but a is an input to x and b is an output from y. This
1564 // means that y cannot be moved after b but x must be moved
1565 // after b for (a,b) to be fused. In other words, after
1566 // fusing (a,b) we have y .. a/b .. x where y is an input
1567 // to a/b and x is an output to a/b: x and y can no longer
1568 // be legally fused. To prevent this condition, we must
1569 // make sure that a child pair added to the Tree is not
1570 // both an input and output of an already-selected pair.
1572 // Pairing-induced dependencies can also form from more complicated
1573 // cycles. The pair vs. pair conflicts are easy to check, and so
1574 // that is done explicitly for "fast rejection", and because for
1575 // child vs. child conflicts, we may prefer to keep the current
1576 // pair in preference to the already-selected child.
1577 DenseSet<ValuePair> CurrentPairs;
1580 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1581 = BestChildren.begin(), E2 = BestChildren.end();
1583 if (C2->first.first == C->first.first ||
1584 C2->first.first == C->first.second ||
1585 C2->first.second == C->first.first ||
1586 C2->first.second == C->first.second ||
1587 pairsConflict(C2->first, C->first, PairableInstUsers,
1588 UseCycleCheck ? &PairableInstUserMap : 0,
1589 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1590 if (C2->second >= C->second) {
1595 CurrentPairs.insert(C2->first);
1598 if (!CanAdd) continue;
1600 // Even worse, this child could conflict with another node already
1601 // selected for the Tree. If that is the case, ignore this child.
1602 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1603 E2 = PrunedTree.end(); T != E2; ++T) {
1604 if (T->first == C->first.first ||
1605 T->first == C->first.second ||
1606 T->second == C->first.first ||
1607 T->second == C->first.second ||
1608 pairsConflict(*T, C->first, PairableInstUsers,
1609 UseCycleCheck ? &PairableInstUserMap : 0,
1610 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1615 CurrentPairs.insert(*T);
1617 if (!CanAdd) continue;
1619 // And check the queue too...
1620 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1621 E2 = Q.end(); C2 != E2; ++C2) {
1622 if (C2->first.first == C->first.first ||
1623 C2->first.first == C->first.second ||
1624 C2->first.second == C->first.first ||
1625 C2->first.second == C->first.second ||
1626 pairsConflict(C2->first, C->first, PairableInstUsers,
1627 UseCycleCheck ? &PairableInstUserMap : 0,
1628 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1633 CurrentPairs.insert(C2->first);
1635 if (!CanAdd) continue;
1637 // Last but not least, check for a conflict with any of the
1638 // already-chosen pairs.
1639 for (DenseMap<Value *, Value *>::iterator C2 =
1640 ChosenPairs.begin(), E2 = ChosenPairs.end();
1642 if (pairsConflict(*C2, C->first, PairableInstUsers,
1643 UseCycleCheck ? &PairableInstUserMap : 0,
1644 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1649 CurrentPairs.insert(*C2);
1651 if (!CanAdd) continue;
1653 // To check for non-trivial cycles formed by the addition of the
1654 // current pair we've formed a list of all relevant pairs, now use a
1655 // graph walk to check for a cycle. We start from the current pair and
1656 // walk the use tree to see if we again reach the current pair. If we
1657 // do, then the current pair is rejected.
1659 // FIXME: It may be more efficient to use a topological-ordering
1660 // algorithm to improve the cycle check. This should be investigated.
1661 if (UseCycleCheck &&
1662 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1665 // This child can be added, but we may have chosen it in preference
1666 // to an already-selected child. Check for this here, and if a
1667 // conflict is found, then remove the previously-selected child
1668 // before adding this one in its place.
1669 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1670 = BestChildren.begin(); C2 != BestChildren.end();) {
1671 if (C2->first.first == C->first.first ||
1672 C2->first.first == C->first.second ||
1673 C2->first.second == C->first.first ||
1674 C2->first.second == C->first.second ||
1675 pairsConflict(C2->first, C->first, PairableInstUsers))
1676 C2 = BestChildren.erase(C2);
1681 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1684 for (SmallVector<ValuePairWithDepth, 8>::iterator C
1685 = BestChildren.begin(), E2 = BestChildren.end();
1687 size_t DepthF = getDepthFactor(C->first.first);
1688 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1690 } while (!Q.empty());
1693 // This function finds the best tree of mututally-compatible connected
1694 // pairs, given the choice of root pairs as an iterator range.
1695 void BBVectorize::findBestTreeFor(
1696 std::multimap<Value *, Value *> &CandidatePairs,
1697 DenseSet<ValuePair> &CandidatePairsSet,
1698 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1699 std::vector<Value *> &PairableInsts,
1700 DenseSet<ValuePair> &FixedOrderPairs,
1701 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1702 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1703 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
1704 DenseSet<ValuePair> &PairableInstUsers,
1705 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1706 DenseSet<VPPair> &PairableInstUserPairSet,
1707 DenseMap<Value *, Value *> &ChosenPairs,
1708 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1709 int &BestEffSize, VPIteratorPair ChoiceRange,
1710 bool UseCycleCheck) {
1711 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1712 J != ChoiceRange.second; ++J) {
1714 // Before going any further, make sure that this pair does not
1715 // conflict with any already-selected pairs (see comment below
1716 // near the Tree pruning for more details).
1717 DenseSet<ValuePair> ChosenPairSet;
1718 bool DoesConflict = false;
1719 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1720 E = ChosenPairs.end(); C != E; ++C) {
1721 if (pairsConflict(*C, *J, PairableInstUsers,
1722 UseCycleCheck ? &PairableInstUserMap : 0,
1723 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1724 DoesConflict = true;
1728 ChosenPairSet.insert(*C);
1730 if (DoesConflict) continue;
1732 if (UseCycleCheck &&
1733 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1736 DenseMap<ValuePair, size_t> Tree;
1737 buildInitialTreeFor(CandidatePairs, CandidatePairsSet,
1738 PairableInsts, ConnectedPairs,
1739 PairableInstUsers, ChosenPairs, Tree, *J);
1741 // Because we'll keep the child with the largest depth, the largest
1742 // depth is still the same in the unpruned Tree.
1743 size_t MaxDepth = Tree.lookup(*J);
1745 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1746 << *J->first << " <-> " << *J->second << "} of depth " <<
1747 MaxDepth << " and size " << Tree.size() << "\n");
1749 // At this point the Tree has been constructed, but, may contain
1750 // contradictory children (meaning that different children of
1751 // some tree node may be attempting to fuse the same instruction).
1752 // So now we walk the tree again, in the case of a conflict,
1753 // keep only the child with the largest depth. To break a tie,
1754 // favor the first child.
1756 DenseSet<ValuePair> PrunedTree;
1757 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1758 PairableInstUsers, PairableInstUserMap,
1759 PairableInstUserPairSet,
1760 ChosenPairs, Tree, PrunedTree, *J, UseCycleCheck);
1764 DenseSet<Value *> PrunedTreeInstrs;
1765 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1766 E = PrunedTree.end(); S != E; ++S) {
1767 PrunedTreeInstrs.insert(S->first);
1768 PrunedTreeInstrs.insert(S->second);
1771 // The set of pairs that have already contributed to the total cost.
1772 DenseSet<ValuePair> IncomingPairs;
1774 // If the cost model were perfect, this might not be necessary; but we
1775 // need to make sure that we don't get stuck vectorizing our own
1777 bool HasNontrivialInsts = false;
1779 // The node weights represent the cost savings associated with
1780 // fusing the pair of instructions.
1781 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1782 E = PrunedTree.end(); S != E; ++S) {
1783 if (!isa<ShuffleVectorInst>(S->first) &&
1784 !isa<InsertElementInst>(S->first) &&
1785 !isa<ExtractElementInst>(S->first))
1786 HasNontrivialInsts = true;
1788 bool FlipOrder = false;
1790 if (getDepthFactor(S->first)) {
1791 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1792 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1793 << *S->first << " <-> " << *S->second << "} = " <<
1795 EffSize += ESContrib;
1798 // The edge weights contribute in a negative sense: they represent
1799 // the cost of shuffles.
1800 VPPIteratorPair IP = ConnectedPairDeps.equal_range(*S);
1801 if (IP.first != ConnectedPairDeps.end()) {
1802 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1803 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1804 Q != IP.second; ++Q) {
1805 if (!PrunedTree.count(Q->second))
1807 DenseMap<VPPair, unsigned>::iterator R =
1808 PairConnectionTypes.find(VPPair(Q->second, Q->first));
1809 assert(R != PairConnectionTypes.end() &&
1810 "Cannot find pair connection type");
1811 if (R->second == PairConnectionDirect)
1813 else if (R->second == PairConnectionSwap)
1817 // If there are more swaps than direct connections, then
1818 // the pair order will be flipped during fusion. So the real
1819 // number of swaps is the minimum number.
1820 FlipOrder = !FixedOrderPairs.count(*S) &&
1821 ((NumDepsSwap > NumDepsDirect) ||
1822 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1824 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1825 Q != IP.second; ++Q) {
1826 if (!PrunedTree.count(Q->second))
1828 DenseMap<VPPair, unsigned>::iterator R =
1829 PairConnectionTypes.find(VPPair(Q->second, Q->first));
1830 assert(R != PairConnectionTypes.end() &&
1831 "Cannot find pair connection type");
1832 Type *Ty1 = Q->second.first->getType(),
1833 *Ty2 = Q->second.second->getType();
1834 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1835 if ((R->second == PairConnectionDirect && FlipOrder) ||
1836 (R->second == PairConnectionSwap && !FlipOrder) ||
1837 R->second == PairConnectionSplat) {
1838 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1841 if (VTy->getVectorNumElements() == 2) {
1842 if (R->second == PairConnectionSplat)
1843 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1844 TargetTransformInfo::SK_Broadcast, VTy));
1846 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1847 TargetTransformInfo::SK_Reverse, VTy));
1850 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1851 *Q->second.first << " <-> " << *Q->second.second <<
1853 *S->first << " <-> " << *S->second << "} = " <<
1855 EffSize -= ESContrib;
1860 // Compute the cost of outgoing edges. We assume that edges outgoing
1861 // to shuffles, inserts or extracts can be merged, and so contribute
1862 // no additional cost.
1863 if (!S->first->getType()->isVoidTy()) {
1864 Type *Ty1 = S->first->getType(),
1865 *Ty2 = S->second->getType();
1866 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1868 bool NeedsExtraction = false;
1869 for (Value::use_iterator I = S->first->use_begin(),
1870 IE = S->first->use_end(); I != IE; ++I) {
1871 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1872 // Shuffle can be folded if it has no other input
1873 if (isa<UndefValue>(SI->getOperand(1)))
1876 if (isa<ExtractElementInst>(*I))
1878 if (PrunedTreeInstrs.count(*I))
1880 NeedsExtraction = true;
1884 if (NeedsExtraction) {
1886 if (Ty1->isVectorTy()) {
1887 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1889 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1890 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1892 ESContrib = (int) TTI->getVectorInstrCost(
1893 Instruction::ExtractElement, VTy, 0);
1895 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1896 *S->first << "} = " << ESContrib << "\n");
1897 EffSize -= ESContrib;
1900 NeedsExtraction = false;
1901 for (Value::use_iterator I = S->second->use_begin(),
1902 IE = S->second->use_end(); I != IE; ++I) {
1903 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1904 // Shuffle can be folded if it has no other input
1905 if (isa<UndefValue>(SI->getOperand(1)))
1908 if (isa<ExtractElementInst>(*I))
1910 if (PrunedTreeInstrs.count(*I))
1912 NeedsExtraction = true;
1916 if (NeedsExtraction) {
1918 if (Ty2->isVectorTy()) {
1919 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1921 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1922 TargetTransformInfo::SK_ExtractSubvector, VTy,
1923 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
1925 ESContrib = (int) TTI->getVectorInstrCost(
1926 Instruction::ExtractElement, VTy, 1);
1927 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1928 *S->second << "} = " << ESContrib << "\n");
1929 EffSize -= ESContrib;
1933 // Compute the cost of incoming edges.
1934 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
1935 Instruction *S1 = cast<Instruction>(S->first),
1936 *S2 = cast<Instruction>(S->second);
1937 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
1938 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
1940 // Combining constants into vector constants (or small vector
1941 // constants into larger ones are assumed free).
1942 if (isa<Constant>(O1) && isa<Constant>(O2))
1948 ValuePair VP = ValuePair(O1, O2);
1949 ValuePair VPR = ValuePair(O2, O1);
1951 // Internal edges are not handled here.
1952 if (PrunedTree.count(VP) || PrunedTree.count(VPR))
1955 Type *Ty1 = O1->getType(),
1956 *Ty2 = O2->getType();
1957 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1959 // Combining vector operations of the same type is also assumed
1960 // folded with other operations.
1962 // If both are insert elements, then both can be widened.
1963 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
1964 *IEO2 = dyn_cast<InsertElementInst>(O2);
1965 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
1967 // If both are extract elements, and both have the same input
1968 // type, then they can be replaced with a shuffle
1969 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
1970 *EIO2 = dyn_cast<ExtractElementInst>(O2);
1972 EIO1->getOperand(0)->getType() ==
1973 EIO2->getOperand(0)->getType())
1975 // If both are a shuffle with equal operand types and only two
1976 // unqiue operands, then they can be replaced with a single
1978 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
1979 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
1981 SIO1->getOperand(0)->getType() ==
1982 SIO2->getOperand(0)->getType()) {
1983 SmallSet<Value *, 4> SIOps;
1984 SIOps.insert(SIO1->getOperand(0));
1985 SIOps.insert(SIO1->getOperand(1));
1986 SIOps.insert(SIO2->getOperand(0));
1987 SIOps.insert(SIO2->getOperand(1));
1988 if (SIOps.size() <= 2)
1994 // This pair has already been formed.
1995 if (IncomingPairs.count(VP)) {
1997 } else if (IncomingPairs.count(VPR)) {
1998 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2001 if (VTy->getVectorNumElements() == 2)
2002 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2003 TargetTransformInfo::SK_Reverse, VTy));
2004 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2005 ESContrib = (int) TTI->getVectorInstrCost(
2006 Instruction::InsertElement, VTy, 0);
2007 ESContrib += (int) TTI->getVectorInstrCost(
2008 Instruction::InsertElement, VTy, 1);
2009 } else if (!Ty1->isVectorTy()) {
2010 // O1 needs to be inserted into a vector of size O2, and then
2011 // both need to be shuffled together.
2012 ESContrib = (int) TTI->getVectorInstrCost(
2013 Instruction::InsertElement, Ty2, 0);
2014 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2016 } else if (!Ty2->isVectorTy()) {
2017 // O2 needs to be inserted into a vector of size O1, and then
2018 // both need to be shuffled together.
2019 ESContrib = (int) TTI->getVectorInstrCost(
2020 Instruction::InsertElement, Ty1, 0);
2021 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2024 Type *TyBig = Ty1, *TySmall = Ty2;
2025 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2026 std::swap(TyBig, TySmall);
2028 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2030 if (TyBig != TySmall)
2031 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2035 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2036 << *O1 << " <-> " << *O2 << "} = " <<
2038 EffSize -= ESContrib;
2039 IncomingPairs.insert(VP);
2044 if (!HasNontrivialInsts) {
2045 DEBUG(if (DebugPairSelection) dbgs() <<
2046 "\tNo non-trivial instructions in tree;"
2047 " override to zero effective size\n");
2051 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
2052 E = PrunedTree.end(); S != E; ++S)
2053 EffSize += (int) getDepthFactor(S->first);
2056 DEBUG(if (DebugPairSelection)
2057 dbgs() << "BBV: found pruned Tree for pair {"
2058 << *J->first << " <-> " << *J->second << "} of depth " <<
2059 MaxDepth << " and size " << PrunedTree.size() <<
2060 " (effective size: " << EffSize << ")\n");
2061 if (((TTI && !UseChainDepthWithTI) ||
2062 MaxDepth >= Config.ReqChainDepth) &&
2063 EffSize > 0 && EffSize > BestEffSize) {
2064 BestMaxDepth = MaxDepth;
2065 BestEffSize = EffSize;
2066 BestTree = PrunedTree;
2071 // Given the list of candidate pairs, this function selects those
2072 // that will be fused into vector instructions.
2073 void BBVectorize::choosePairs(
2074 std::multimap<Value *, Value *> &CandidatePairs,
2075 DenseSet<ValuePair> &CandidatePairsSet,
2076 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2077 std::vector<Value *> &PairableInsts,
2078 DenseSet<ValuePair> &FixedOrderPairs,
2079 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2080 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2081 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
2082 DenseSet<ValuePair> &PairableInstUsers,
2083 DenseMap<Value *, Value *>& ChosenPairs) {
2084 bool UseCycleCheck =
2085 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
2086 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
2087 DenseSet<VPPair> PairableInstUserPairSet;
2088 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2089 E = PairableInsts.end(); I != E; ++I) {
2090 // The number of possible pairings for this variable:
2091 size_t NumChoices = CandidatePairs.count(*I);
2092 if (!NumChoices) continue;
2094 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
2096 // The best pair to choose and its tree:
2097 size_t BestMaxDepth = 0;
2098 int BestEffSize = 0;
2099 DenseSet<ValuePair> BestTree;
2100 findBestTreeFor(CandidatePairs, CandidatePairsSet,
2101 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 CandidatePairsSet.erase(*K);
2133 CandidatePairs.erase(K++);
2143 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2146 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2151 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2152 (n > 0 ? "." + utostr(n) : "")).str();
2155 // Returns the value that is to be used as the pointer input to the vector
2156 // instruction that fuses I with J.
2157 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2158 Instruction *I, Instruction *J, unsigned o) {
2160 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2161 int64_t OffsetInElmts;
2163 // Note: the analysis might fail here, that is why the pair order has
2164 // been precomputed (OffsetInElmts must be unused here).
2165 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2166 IAddressSpace, JAddressSpace,
2167 OffsetInElmts, false);
2169 // The pointer value is taken to be the one with the lowest offset.
2172 Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
2173 Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
2174 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2175 Type *VArgPtrType = PointerType::get(VArgType,
2176 cast<PointerType>(IPtr->getType())->getAddressSpace());
2177 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2178 /* insert before */ I);
2181 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2182 unsigned MaskOffset, unsigned NumInElem,
2183 unsigned NumInElem1, unsigned IdxOffset,
2184 std::vector<Constant*> &Mask) {
2185 unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
2186 for (unsigned v = 0; v < NumElem1; ++v) {
2187 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2189 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2191 unsigned mm = m + (int) IdxOffset;
2192 if (m >= (int) NumInElem1)
2193 mm += (int) NumInElem;
2195 Mask[v+MaskOffset] =
2196 ConstantInt::get(Type::getInt32Ty(Context), mm);
2201 // Returns the value that is to be used as the vector-shuffle mask to the
2202 // vector instruction that fuses I with J.
2203 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2204 Instruction *I, Instruction *J) {
2205 // This is the shuffle mask. We need to append the second
2206 // mask to the first, and the numbers need to be adjusted.
2208 Type *ArgTypeI = I->getType();
2209 Type *ArgTypeJ = J->getType();
2210 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2212 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
2214 // Get the total number of elements in the fused vector type.
2215 // By definition, this must equal the number of elements in
2217 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
2218 std::vector<Constant*> Mask(NumElem);
2220 Type *OpTypeI = I->getOperand(0)->getType();
2221 unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
2222 Type *OpTypeJ = J->getOperand(0)->getType();
2223 unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
2225 // The fused vector will be:
2226 // -----------------------------------------------------
2227 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2228 // -----------------------------------------------------
2229 // from which we'll extract NumElem total elements (where the first NumElemI
2230 // of them come from the mask in I and the remainder come from the mask
2233 // For the mask from the first pair...
2234 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2237 // For the mask from the second pair...
2238 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2241 return ConstantVector::get(Mask);
2244 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2245 Instruction *J, unsigned o, Value *&LOp,
2247 Type *ArgTypeL, Type *ArgTypeH,
2248 bool IBeforeJ, unsigned IdxOff) {
2249 bool ExpandedIEChain = false;
2250 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2251 // If we have a pure insertelement chain, then this can be rewritten
2252 // into a chain that directly builds the larger type.
2253 if (isPureIEChain(LIE)) {
2254 SmallVector<Value *, 8> VectElemts(numElemL,
2255 UndefValue::get(ArgTypeL->getScalarType()));
2256 InsertElementInst *LIENext = LIE;
2259 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2260 VectElemts[Idx] = LIENext->getOperand(1);
2262 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2265 Value *LIEPrev = UndefValue::get(ArgTypeH);
2266 for (unsigned i = 0; i < numElemL; ++i) {
2267 if (isa<UndefValue>(VectElemts[i])) continue;
2268 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2269 ConstantInt::get(Type::getInt32Ty(Context),
2271 getReplacementName(IBeforeJ ? I : J,
2273 LIENext->insertBefore(IBeforeJ ? J : I);
2277 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2278 ExpandedIEChain = true;
2282 return ExpandedIEChain;
2285 // Returns the value to be used as the specified operand of the vector
2286 // instruction that fuses I with J.
2287 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2288 Instruction *J, unsigned o, bool IBeforeJ) {
2289 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2290 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2292 // Compute the fused vector type for this operand
2293 Type *ArgTypeI = I->getOperand(o)->getType();
2294 Type *ArgTypeJ = J->getOperand(o)->getType();
2295 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2297 Instruction *L = I, *H = J;
2298 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2301 if (ArgTypeL->isVectorTy())
2302 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
2307 if (ArgTypeH->isVectorTy())
2308 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
2312 Value *LOp = L->getOperand(o);
2313 Value *HOp = H->getOperand(o);
2314 unsigned numElem = VArgType->getNumElements();
2316 // First, we check if we can reuse the "original" vector outputs (if these
2317 // exist). We might need a shuffle.
2318 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2319 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2320 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2321 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2323 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2324 // optimization. The input vectors to the shuffle might be a different
2325 // length from the shuffle outputs. Unfortunately, the replacement
2326 // shuffle mask has already been formed, and the mask entries are sensitive
2327 // to the sizes of the inputs.
2328 bool IsSizeChangeShuffle =
2329 isa<ShuffleVectorInst>(L) &&
2330 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2332 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2333 // We can have at most two unique vector inputs.
2334 bool CanUseInputs = true;
2337 I1 = LEE->getOperand(0);
2339 I1 = LSV->getOperand(0);
2340 I2 = LSV->getOperand(1);
2341 if (I2 == I1 || isa<UndefValue>(I2))
2346 Value *I3 = HEE->getOperand(0);
2347 if (!I2 && I3 != I1)
2349 else if (I3 != I1 && I3 != I2)
2350 CanUseInputs = false;
2352 Value *I3 = HSV->getOperand(0);
2353 if (!I2 && I3 != I1)
2355 else if (I3 != I1 && I3 != I2)
2356 CanUseInputs = false;
2359 Value *I4 = HSV->getOperand(1);
2360 if (!isa<UndefValue>(I4)) {
2361 if (!I2 && I4 != I1)
2363 else if (I4 != I1 && I4 != I2)
2364 CanUseInputs = false;
2371 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2374 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2377 // We have one or two input vectors. We need to map each index of the
2378 // operands to the index of the original vector.
2379 SmallVector<std::pair<int, int>, 8> II(numElem);
2380 for (unsigned i = 0; i < numElemL; ++i) {
2384 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2385 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2387 Idx = LSV->getMaskValue(i);
2388 if (Idx < (int) LOpElem) {
2389 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2392 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2396 II[i] = std::pair<int, int>(Idx, INum);
2398 for (unsigned i = 0; i < numElemH; ++i) {
2402 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2403 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2405 Idx = HSV->getMaskValue(i);
2406 if (Idx < (int) HOpElem) {
2407 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2410 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2414 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2417 // We now have an array which tells us from which index of which
2418 // input vector each element of the operand comes.
2419 VectorType *I1T = cast<VectorType>(I1->getType());
2420 unsigned I1Elem = I1T->getNumElements();
2423 // In this case there is only one underlying vector input. Check for
2424 // the trivial case where we can use the input directly.
2425 if (I1Elem == numElem) {
2426 bool ElemInOrder = true;
2427 for (unsigned i = 0; i < numElem; ++i) {
2428 if (II[i].first != (int) i && II[i].first != -1) {
2429 ElemInOrder = false;
2438 // A shuffle is needed.
2439 std::vector<Constant *> Mask(numElem);
2440 for (unsigned i = 0; i < numElem; ++i) {
2441 int Idx = II[i].first;
2443 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2445 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2449 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2450 ConstantVector::get(Mask),
2451 getReplacementName(IBeforeJ ? I : J,
2453 S->insertBefore(IBeforeJ ? J : I);
2457 VectorType *I2T = cast<VectorType>(I2->getType());
2458 unsigned I2Elem = I2T->getNumElements();
2460 // This input comes from two distinct vectors. The first step is to
2461 // make sure that both vectors are the same length. If not, the
2462 // smaller one will need to grow before they can be shuffled together.
2463 if (I1Elem < I2Elem) {
2464 std::vector<Constant *> Mask(I2Elem);
2466 for (; v < I1Elem; ++v)
2467 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2468 for (; v < I2Elem; ++v)
2469 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2471 Instruction *NewI1 =
2472 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2473 ConstantVector::get(Mask),
2474 getReplacementName(IBeforeJ ? I : J,
2476 NewI1->insertBefore(IBeforeJ ? J : I);
2480 } else if (I1Elem > I2Elem) {
2481 std::vector<Constant *> Mask(I1Elem);
2483 for (; v < I2Elem; ++v)
2484 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2485 for (; v < I1Elem; ++v)
2486 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2488 Instruction *NewI2 =
2489 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2490 ConstantVector::get(Mask),
2491 getReplacementName(IBeforeJ ? I : J,
2493 NewI2->insertBefore(IBeforeJ ? J : I);
2499 // Now that both I1 and I2 are the same length we can shuffle them
2500 // together (and use the result).
2501 std::vector<Constant *> Mask(numElem);
2502 for (unsigned v = 0; v < numElem; ++v) {
2503 if (II[v].first == -1) {
2504 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2506 int Idx = II[v].first + II[v].second * I1Elem;
2507 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2511 Instruction *NewOp =
2512 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2513 getReplacementName(IBeforeJ ? I : J, true, o));
2514 NewOp->insertBefore(IBeforeJ ? J : I);
2519 Type *ArgType = ArgTypeL;
2520 if (numElemL < numElemH) {
2521 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2522 ArgTypeL, VArgType, IBeforeJ, 1)) {
2523 // This is another short-circuit case: we're combining a scalar into
2524 // a vector that is formed by an IE chain. We've just expanded the IE
2525 // chain, now insert the scalar and we're done.
2527 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2528 getReplacementName(IBeforeJ ? I : J, true, o));
2529 S->insertBefore(IBeforeJ ? J : I);
2531 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2532 ArgTypeH, IBeforeJ)) {
2533 // The two vector inputs to the shuffle must be the same length,
2534 // so extend the smaller vector to be the same length as the larger one.
2538 std::vector<Constant *> Mask(numElemH);
2540 for (; v < numElemL; ++v)
2541 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2542 for (; v < numElemH; ++v)
2543 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2545 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2546 ConstantVector::get(Mask),
2547 getReplacementName(IBeforeJ ? I : J,
2550 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2551 getReplacementName(IBeforeJ ? I : J,
2555 NLOp->insertBefore(IBeforeJ ? J : I);
2560 } else if (numElemL > numElemH) {
2561 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2562 ArgTypeH, VArgType, IBeforeJ)) {
2564 InsertElementInst::Create(LOp, HOp,
2565 ConstantInt::get(Type::getInt32Ty(Context),
2567 getReplacementName(IBeforeJ ? I : J,
2569 S->insertBefore(IBeforeJ ? J : I);
2571 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2572 ArgTypeL, IBeforeJ)) {
2575 std::vector<Constant *> Mask(numElemL);
2577 for (; v < numElemH; ++v)
2578 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2579 for (; v < numElemL; ++v)
2580 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2582 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2583 ConstantVector::get(Mask),
2584 getReplacementName(IBeforeJ ? I : J,
2587 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2588 getReplacementName(IBeforeJ ? I : J,
2592 NHOp->insertBefore(IBeforeJ ? J : I);
2597 if (ArgType->isVectorTy()) {
2598 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2599 std::vector<Constant*> Mask(numElem);
2600 for (unsigned v = 0; v < numElem; ++v) {
2602 // If the low vector was expanded, we need to skip the extra
2603 // undefined entries.
2604 if (v >= numElemL && numElemH > numElemL)
2605 Idx += (numElemH - numElemL);
2606 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2609 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2610 ConstantVector::get(Mask),
2611 getReplacementName(IBeforeJ ? I : J, true, o));
2612 BV->insertBefore(IBeforeJ ? J : I);
2616 Instruction *BV1 = InsertElementInst::Create(
2617 UndefValue::get(VArgType), LOp, CV0,
2618 getReplacementName(IBeforeJ ? I : J,
2620 BV1->insertBefore(IBeforeJ ? J : I);
2621 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2622 getReplacementName(IBeforeJ ? I : J,
2624 BV2->insertBefore(IBeforeJ ? J : I);
2628 // This function creates an array of values that will be used as the inputs
2629 // to the vector instruction that fuses I with J.
2630 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2631 Instruction *I, Instruction *J,
2632 SmallVector<Value *, 3> &ReplacedOperands,
2634 unsigned NumOperands = I->getNumOperands();
2636 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2637 // Iterate backward so that we look at the store pointer
2638 // first and know whether or not we need to flip the inputs.
2640 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2641 // This is the pointer for a load/store instruction.
2642 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2644 } else if (isa<CallInst>(I)) {
2645 Function *F = cast<CallInst>(I)->getCalledFunction();
2646 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2647 if (o == NumOperands-1) {
2648 BasicBlock &BB = *I->getParent();
2650 Module *M = BB.getParent()->getParent();
2651 Type *ArgTypeI = I->getType();
2652 Type *ArgTypeJ = J->getType();
2653 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2655 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2657 } else if (IID == Intrinsic::powi && o == 1) {
2658 // The second argument of powi is a single integer and we've already
2659 // checked that both arguments are equal. As a result, we just keep
2660 // I's second argument.
2661 ReplacedOperands[o] = I->getOperand(o);
2664 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2665 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2669 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2673 // This function creates two values that represent the outputs of the
2674 // original I and J instructions. These are generally vector shuffles
2675 // or extracts. In many cases, these will end up being unused and, thus,
2676 // eliminated by later passes.
2677 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2678 Instruction *J, Instruction *K,
2679 Instruction *&InsertionPt,
2680 Instruction *&K1, Instruction *&K2) {
2681 if (isa<StoreInst>(I)) {
2682 AA->replaceWithNewValue(I, K);
2683 AA->replaceWithNewValue(J, K);
2685 Type *IType = I->getType();
2686 Type *JType = J->getType();
2688 VectorType *VType = getVecTypeForPair(IType, JType);
2689 unsigned numElem = VType->getNumElements();
2691 unsigned numElemI, numElemJ;
2692 if (IType->isVectorTy())
2693 numElemI = cast<VectorType>(IType)->getNumElements();
2697 if (JType->isVectorTy())
2698 numElemJ = cast<VectorType>(JType)->getNumElements();
2702 if (IType->isVectorTy()) {
2703 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2704 for (unsigned v = 0; v < numElemI; ++v) {
2705 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2706 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2709 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2710 ConstantVector::get( Mask1),
2711 getReplacementName(K, false, 1));
2713 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2714 K1 = ExtractElementInst::Create(K, CV0,
2715 getReplacementName(K, false, 1));
2718 if (JType->isVectorTy()) {
2719 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2720 for (unsigned v = 0; v < numElemJ; ++v) {
2721 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2722 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2725 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2726 ConstantVector::get( Mask2),
2727 getReplacementName(K, false, 2));
2729 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2730 K2 = ExtractElementInst::Create(K, CV1,
2731 getReplacementName(K, false, 2));
2735 K2->insertAfter(K1);
2740 // Move all uses of the function I (including pairing-induced uses) after J.
2741 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2742 DenseSet<ValuePair> &LoadMoveSetPairs,
2743 Instruction *I, Instruction *J) {
2744 // Skip to the first instruction past I.
2745 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2747 DenseSet<Value *> Users;
2748 AliasSetTracker WriteSet(*AA);
2749 for (; cast<Instruction>(L) != J; ++L)
2750 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2752 assert(cast<Instruction>(L) == J &&
2753 "Tracking has not proceeded far enough to check for dependencies");
2754 // If J is now in the use set of I, then trackUsesOfI will return true
2755 // and we have a dependency cycle (and the fusing operation must abort).
2756 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2759 // Move all uses of the function I (including pairing-induced uses) after J.
2760 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2761 DenseSet<ValuePair> &LoadMoveSetPairs,
2762 Instruction *&InsertionPt,
2763 Instruction *I, Instruction *J) {
2764 // Skip to the first instruction past I.
2765 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2767 DenseSet<Value *> Users;
2768 AliasSetTracker WriteSet(*AA);
2769 for (; cast<Instruction>(L) != J;) {
2770 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2771 // Move this instruction
2772 Instruction *InstToMove = L; ++L;
2774 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2775 " to after " << *InsertionPt << "\n");
2776 InstToMove->removeFromParent();
2777 InstToMove->insertAfter(InsertionPt);
2778 InsertionPt = InstToMove;
2785 // Collect all load instruction that are in the move set of a given first
2786 // pair member. These loads depend on the first instruction, I, and so need
2787 // to be moved after J (the second instruction) when the pair is fused.
2788 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2789 DenseMap<Value *, Value *> &ChosenPairs,
2790 std::multimap<Value *, Value *> &LoadMoveSet,
2791 DenseSet<ValuePair> &LoadMoveSetPairs,
2793 // Skip to the first instruction past I.
2794 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2796 DenseSet<Value *> Users;
2797 AliasSetTracker WriteSet(*AA);
2799 // Note: We cannot end the loop when we reach J because J could be moved
2800 // farther down the use chain by another instruction pairing. Also, J
2801 // could be before I if this is an inverted input.
2802 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2803 if (trackUsesOfI(Users, WriteSet, I, L)) {
2804 if (L->mayReadFromMemory()) {
2805 LoadMoveSet.insert(ValuePair(L, I));
2806 LoadMoveSetPairs.insert(ValuePair(L, I));
2812 // In cases where both load/stores and the computation of their pointers
2813 // are chosen for vectorization, we can end up in a situation where the
2814 // aliasing analysis starts returning different query results as the
2815 // process of fusing instruction pairs continues. Because the algorithm
2816 // relies on finding the same use trees here as were found earlier, we'll
2817 // need to precompute the necessary aliasing information here and then
2818 // manually update it during the fusion process.
2819 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2820 std::vector<Value *> &PairableInsts,
2821 DenseMap<Value *, Value *> &ChosenPairs,
2822 std::multimap<Value *, Value *> &LoadMoveSet,
2823 DenseSet<ValuePair> &LoadMoveSetPairs) {
2824 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2825 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2826 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2827 if (P == ChosenPairs.end()) continue;
2829 Instruction *I = cast<Instruction>(P->first);
2830 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2831 LoadMoveSetPairs, I);
2835 // When the first instruction in each pair is cloned, it will inherit its
2836 // parent's metadata. This metadata must be combined with that of the other
2837 // instruction in a safe way.
2838 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2839 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2840 K->getAllMetadataOtherThanDebugLoc(Metadata);
2841 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2842 unsigned Kind = Metadata[i].first;
2843 MDNode *JMD = J->getMetadata(Kind);
2844 MDNode *KMD = Metadata[i].second;
2848 K->setMetadata(Kind, 0); // Remove unknown metadata
2850 case LLVMContext::MD_tbaa:
2851 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2853 case LLVMContext::MD_fpmath:
2854 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2860 // This function fuses the chosen instruction pairs into vector instructions,
2861 // taking care preserve any needed scalar outputs and, then, it reorders the
2862 // remaining instructions as needed (users of the first member of the pair
2863 // need to be moved to after the location of the second member of the pair
2864 // because the vector instruction is inserted in the location of the pair's
2866 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2867 std::vector<Value *> &PairableInsts,
2868 DenseMap<Value *, Value *> &ChosenPairs,
2869 DenseSet<ValuePair> &FixedOrderPairs,
2870 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2871 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2872 std::multimap<ValuePair, ValuePair> &ConnectedPairDeps) {
2873 LLVMContext& Context = BB.getContext();
2875 // During the vectorization process, the order of the pairs to be fused
2876 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2877 // list. After a pair is fused, the flipped pair is removed from the list.
2878 DenseSet<ValuePair> FlippedPairs;
2879 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2880 E = ChosenPairs.end(); P != E; ++P)
2881 FlippedPairs.insert(ValuePair(P->second, P->first));
2882 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2883 E = FlippedPairs.end(); P != E; ++P)
2884 ChosenPairs.insert(*P);
2886 std::multimap<Value *, Value *> LoadMoveSet;
2887 DenseSet<ValuePair> LoadMoveSetPairs;
2888 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2889 LoadMoveSet, LoadMoveSetPairs);
2891 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2893 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2894 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2895 if (P == ChosenPairs.end()) {
2900 if (getDepthFactor(P->first) == 0) {
2901 // These instructions are not really fused, but are tracked as though
2902 // they are. Any case in which it would be interesting to fuse them
2903 // will be taken care of by InstCombine.
2909 Instruction *I = cast<Instruction>(P->first),
2910 *J = cast<Instruction>(P->second);
2912 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2913 " <-> " << *J << "\n");
2915 // Remove the pair and flipped pair from the list.
2916 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2917 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2918 ChosenPairs.erase(FP);
2919 ChosenPairs.erase(P);
2921 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
2922 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2924 " aborted because of non-trivial dependency cycle\n");
2930 // If the pair must have the other order, then flip it.
2931 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2932 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2933 // This pair does not have a fixed order, and so we might want to
2934 // flip it if that will yield fewer shuffles. We count the number
2935 // of dependencies connected via swaps, and those directly connected,
2936 // and flip the order if the number of swaps is greater.
2937 bool OrigOrder = true;
2938 VPPIteratorPair IP = ConnectedPairDeps.equal_range(ValuePair(I, J));
2939 if (IP.first == ConnectedPairDeps.end()) {
2940 IP = ConnectedPairDeps.equal_range(ValuePair(J, I));
2944 if (IP.first != ConnectedPairDeps.end()) {
2945 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
2946 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2947 Q != IP.second; ++Q) {
2948 DenseMap<VPPair, unsigned>::iterator R =
2949 PairConnectionTypes.find(VPPair(Q->second, Q->first));
2950 assert(R != PairConnectionTypes.end() &&
2951 "Cannot find pair connection type");
2952 if (R->second == PairConnectionDirect)
2954 else if (R->second == PairConnectionSwap)
2959 std::swap(NumDepsDirect, NumDepsSwap);
2961 if (NumDepsSwap > NumDepsDirect) {
2962 FlipPairOrder = true;
2963 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
2964 " <-> " << *J << "\n");
2969 Instruction *L = I, *H = J;
2973 // If the pair being fused uses the opposite order from that in the pair
2974 // connection map, then we need to flip the types.
2975 VPPIteratorPair IP = ConnectedPairs.equal_range(ValuePair(H, L));
2976 for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2977 Q != IP.second; ++Q) {
2978 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(*Q);
2979 assert(R != PairConnectionTypes.end() &&
2980 "Cannot find pair connection type");
2981 if (R->second == PairConnectionDirect)
2982 R->second = PairConnectionSwap;
2983 else if (R->second == PairConnectionSwap)
2984 R->second = PairConnectionDirect;
2987 bool LBeforeH = !FlipPairOrder;
2988 unsigned NumOperands = I->getNumOperands();
2989 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2990 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
2993 // Make a copy of the original operation, change its type to the vector
2994 // type and replace its operands with the vector operands.
2995 Instruction *K = L->clone();
2998 else if (H->hasName())
3001 if (!isa<StoreInst>(K))
3002 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3004 combineMetadata(K, H);
3005 K->intersectOptionalDataWith(H);
3007 for (unsigned o = 0; o < NumOperands; ++o)
3008 K->setOperand(o, ReplacedOperands[o]);
3012 // Instruction insertion point:
3013 Instruction *InsertionPt = K;
3014 Instruction *K1 = 0, *K2 = 0;
3015 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3017 // The use tree of the first original instruction must be moved to after
3018 // the location of the second instruction. The entire use tree of the
3019 // first instruction is disjoint from the input tree of the second
3020 // (by definition), and so commutes with it.
3022 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3024 if (!isa<StoreInst>(I)) {
3025 L->replaceAllUsesWith(K1);
3026 H->replaceAllUsesWith(K2);
3027 AA->replaceWithNewValue(L, K1);
3028 AA->replaceWithNewValue(H, K2);
3031 // Instructions that may read from memory may be in the load move set.
3032 // Once an instruction is fused, we no longer need its move set, and so
3033 // the values of the map never need to be updated. However, when a load
3034 // is fused, we need to merge the entries from both instructions in the
3035 // pair in case those instructions were in the move set of some other
3036 // yet-to-be-fused pair. The loads in question are the keys of the map.
3037 if (I->mayReadFromMemory()) {
3038 std::vector<ValuePair> NewSetMembers;
3039 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
3040 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
3041 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
3042 N != IPairRange.second; ++N)
3043 NewSetMembers.push_back(ValuePair(K, N->second));
3044 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
3045 N != JPairRange.second; ++N)
3046 NewSetMembers.push_back(ValuePair(K, N->second));
3047 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3048 AE = NewSetMembers.end(); A != AE; ++A) {
3049 LoadMoveSet.insert(*A);
3050 LoadMoveSetPairs.insert(*A);
3054 // Before removing I, set the iterator to the next instruction.
3055 PI = llvm::next(BasicBlock::iterator(I));
3056 if (cast<Instruction>(PI) == J)
3061 I->eraseFromParent();
3062 J->eraseFromParent();
3064 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3068 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3072 char BBVectorize::ID = 0;
3073 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3074 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3075 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3076 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3077 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3078 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3079 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3081 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3082 return new BBVectorize(C);
3086 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3087 BBVectorize BBVectorizer(P, C);
3088 return BBVectorizer.vectorizeBB(BB);
3091 //===----------------------------------------------------------------------===//
3092 VectorizeConfig::VectorizeConfig() {
3093 VectorBits = ::VectorBits;
3094 VectorizeBools = !::NoBools;
3095 VectorizeInts = !::NoInts;
3096 VectorizeFloats = !::NoFloats;
3097 VectorizePointers = !::NoPointers;
3098 VectorizeCasts = !::NoCasts;
3099 VectorizeMath = !::NoMath;
3100 VectorizeFMA = !::NoFMA;
3101 VectorizeSelect = !::NoSelect;
3102 VectorizeCmp = !::NoCmp;
3103 VectorizeGEP = !::NoGEP;
3104 VectorizeMemOps = !::NoMemOps;
3105 AlignedOnly = ::AlignedOnly;
3106 ReqChainDepth= ::ReqChainDepth;
3107 SearchLimit = ::SearchLimit;
3108 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3109 SplatBreaksChain = ::SplatBreaksChain;
3110 MaxInsts = ::MaxInsts;
3111 MaxIter = ::MaxIter;
3112 Pow2LenOnly = ::Pow2LenOnly;
3113 NoMemOpBoost = ::NoMemOpBoost;
3114 FastDep = ::FastDep;