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"
54 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
55 cl::Hidden, cl::desc("Ignore target information"));
57 static cl::opt<unsigned>
58 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
59 cl::desc("The required chain depth for vectorization"));
62 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
63 cl::Hidden, cl::desc("Use the chain depth requirement with"
64 " target information"));
66 static cl::opt<unsigned>
67 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
68 cl::desc("The maximum search distance for instruction pairs"));
71 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
72 cl::desc("Replicating one element to a pair breaks the chain"));
74 static cl::opt<unsigned>
75 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
76 cl::desc("The size of the native vector registers"));
78 static cl::opt<unsigned>
79 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
80 cl::desc("The maximum number of pairing iterations"));
83 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
84 cl::desc("Don't try to form non-2^n-length vectors"));
86 static cl::opt<unsigned>
87 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
88 cl::desc("The maximum number of pairable instructions per group"));
90 static cl::opt<unsigned>
91 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
92 cl::desc("The maximum number of candidate instruction pairs per group"));
94 static cl::opt<unsigned>
95 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
96 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
97 " a full cycle check"));
100 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
101 cl::desc("Don't try to vectorize boolean (i1) values"));
104 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
105 cl::desc("Don't try to vectorize integer values"));
108 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
109 cl::desc("Don't try to vectorize floating-point values"));
111 // FIXME: This should default to false once pointer vector support works.
113 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
114 cl::desc("Don't try to vectorize pointer values"));
117 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
118 cl::desc("Don't try to vectorize casting (conversion) operations"));
121 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
122 cl::desc("Don't try to vectorize floating-point math intrinsics"));
125 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
126 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
129 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
130 cl::desc("Don't try to vectorize select instructions"));
133 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
134 cl::desc("Don't try to vectorize comparison instructions"));
137 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
138 cl::desc("Don't try to vectorize getelementptr instructions"));
141 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
142 cl::desc("Don't try to vectorize loads and stores"));
145 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
146 cl::desc("Only generate aligned loads and stores"));
149 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
150 cl::init(false), cl::Hidden,
151 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
154 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
155 cl::desc("Use a fast instruction dependency analysis"));
159 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
160 cl::init(false), cl::Hidden,
161 cl::desc("When debugging is enabled, output information on the"
162 " instruction-examination process"));
164 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
165 cl::init(false), cl::Hidden,
166 cl::desc("When debugging is enabled, output information on the"
167 " candidate-selection process"));
169 DebugPairSelection("bb-vectorize-debug-pair-selection",
170 cl::init(false), cl::Hidden,
171 cl::desc("When debugging is enabled, output information on the"
172 " pair-selection process"));
174 DebugCycleCheck("bb-vectorize-debug-cycle-check",
175 cl::init(false), cl::Hidden,
176 cl::desc("When debugging is enabled, output information on the"
177 " cycle-checking process"));
180 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
181 cl::init(false), cl::Hidden,
182 cl::desc("When debugging is enabled, dump the basic block after"
183 " every pair is fused"));
186 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
189 struct BBVectorize : public BasicBlockPass {
190 static char ID; // Pass identification, replacement for typeid
192 const VectorizeConfig Config;
194 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
195 : BasicBlockPass(ID), Config(C) {
196 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
199 BBVectorize(Pass *P, const VectorizeConfig &C)
200 : BasicBlockPass(ID), Config(C) {
201 AA = &P->getAnalysis<AliasAnalysis>();
202 DT = &P->getAnalysis<DominatorTree>();
203 SE = &P->getAnalysis<ScalarEvolution>();
204 TD = P->getAnalysisIfAvailable<DataLayout>();
205 TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
208 typedef std::pair<Value *, Value *> ValuePair;
209 typedef std::pair<ValuePair, int> ValuePairWithCost;
210 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
211 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
212 typedef std::pair<VPPair, unsigned> VPPairWithType;
218 const TargetTransformInfo *TTI;
220 // FIXME: const correct?
222 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
224 bool getCandidatePairs(BasicBlock &BB,
225 BasicBlock::iterator &Start,
226 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
227 DenseSet<ValuePair> &FixedOrderPairs,
228 DenseMap<ValuePair, int> &CandidatePairCostSavings,
229 std::vector<Value *> &PairableInsts, bool NonPow2Len);
231 // FIXME: The current implementation does not account for pairs that
232 // are connected in multiple ways. For example:
233 // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
234 enum PairConnectionType {
235 PairConnectionDirect,
240 void computeConnectedPairs(
241 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
242 DenseSet<ValuePair> &CandidatePairsSet,
243 std::vector<Value *> &PairableInsts,
244 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
245 DenseMap<VPPair, unsigned> &PairConnectionTypes);
247 void buildDepMap(BasicBlock &BB,
248 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
249 std::vector<Value *> &PairableInsts,
250 DenseSet<ValuePair> &PairableInstUsers);
252 void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
253 DenseSet<ValuePair> &CandidatePairsSet,
254 DenseMap<ValuePair, int> &CandidatePairCostSavings,
255 std::vector<Value *> &PairableInsts,
256 DenseSet<ValuePair> &FixedOrderPairs,
257 DenseMap<VPPair, unsigned> &PairConnectionTypes,
258 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
259 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
260 DenseSet<ValuePair> &PairableInstUsers,
261 DenseMap<Value *, Value *>& ChosenPairs);
263 void fuseChosenPairs(BasicBlock &BB,
264 std::vector<Value *> &PairableInsts,
265 DenseMap<Value *, Value *>& ChosenPairs,
266 DenseSet<ValuePair> &FixedOrderPairs,
267 DenseMap<VPPair, unsigned> &PairConnectionTypes,
268 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
269 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
272 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
274 bool areInstsCompatible(Instruction *I, Instruction *J,
275 bool IsSimpleLoadStore, bool NonPow2Len,
276 int &CostSavings, int &FixedOrder);
278 bool trackUsesOfI(DenseSet<Value *> &Users,
279 AliasSetTracker &WriteSet, Instruction *I,
280 Instruction *J, bool UpdateUsers = true,
281 DenseSet<ValuePair> *LoadMoveSetPairs = 0);
283 void computePairsConnectedTo(
284 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
285 DenseSet<ValuePair> &CandidatePairsSet,
286 std::vector<Value *> &PairableInsts,
287 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
288 DenseMap<VPPair, unsigned> &PairConnectionTypes,
291 bool pairsConflict(ValuePair P, ValuePair Q,
292 DenseSet<ValuePair> &PairableInstUsers,
293 DenseMap<ValuePair, std::vector<ValuePair> >
294 *PairableInstUserMap = 0,
295 DenseSet<VPPair> *PairableInstUserPairSet = 0);
297 bool pairWillFormCycle(ValuePair P,
298 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
299 DenseSet<ValuePair> &CurrentPairs);
302 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
303 std::vector<Value *> &PairableInsts,
304 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
305 DenseSet<ValuePair> &PairableInstUsers,
306 DenseMap<ValuePair, std::vector<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 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
315 DenseSet<ValuePair> &CandidatePairsSet,
316 std::vector<Value *> &PairableInsts,
317 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
318 DenseSet<ValuePair> &PairableInstUsers,
319 DenseMap<Value *, Value *> &ChosenPairs,
320 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
322 void findBestTreeFor(
323 DenseMap<Value *, std::vector<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 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
330 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
331 DenseSet<ValuePair> &PairableInstUsers,
332 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
333 DenseSet<VPPair> &PairableInstUserPairSet,
334 DenseMap<Value *, Value *> &ChosenPairs,
335 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
336 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
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 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
370 DenseSet<ValuePair> &LoadMoveSetPairs,
373 void collectLoadMoveSet(BasicBlock &BB,
374 std::vector<Value *> &PairableInsts,
375 DenseMap<Value *, Value *> &ChosenPairs,
376 DenseMap<Value *, std::vector<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 DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
699 AllConnectedPairDeps;
702 std::vector<Value *> PairableInsts;
703 DenseMap<Value *, std::vector<Value *> > CandidatePairs;
704 DenseSet<ValuePair> FixedOrderPairs;
705 DenseMap<ValuePair, int> CandidatePairCostSavings;
706 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
708 CandidatePairCostSavings,
709 PairableInsts, NonPow2Len);
710 if (PairableInsts.empty()) continue;
712 // Build the candidate pair set for faster lookups.
713 DenseSet<ValuePair> CandidatePairsSet;
714 for (DenseMap<Value *, std::vector<Value *> >::iterator I =
715 CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
716 for (std::vector<Value *>::iterator J = I->second.begin(),
717 JE = I->second.end(); J != JE; ++J)
718 CandidatePairsSet.insert(ValuePair(I->first, *J));
720 // Now we have a map of all of the pairable instructions and we need to
721 // select the best possible pairing. A good pairing is one such that the
722 // users of the pair are also paired. This defines a (directed) forest
723 // over the pairs such that two pairs are connected iff the second pair
726 // Note that it only matters that both members of the second pair use some
727 // element of the first pair (to allow for splatting).
729 DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
731 DenseMap<VPPair, unsigned> PairConnectionTypes;
732 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
733 PairableInsts, ConnectedPairs, PairConnectionTypes);
734 if (ConnectedPairs.empty()) continue;
736 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
737 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
739 for (std::vector<ValuePair>::iterator J = I->second.begin(),
740 JE = I->second.end(); J != JE; ++J)
741 ConnectedPairDeps[*J].push_back(I->first);
743 // Build the pairable-instruction dependency map
744 DenseSet<ValuePair> PairableInstUsers;
745 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
747 // There is now a graph of the connected pairs. For each variable, pick
748 // the pairing with the largest tree meeting the depth requirement on at
749 // least one branch. Then select all pairings that are part of that tree
750 // and remove them from the list of available pairings and pairable
753 DenseMap<Value *, Value *> ChosenPairs;
754 choosePairs(CandidatePairs, CandidatePairsSet,
755 CandidatePairCostSavings,
756 PairableInsts, FixedOrderPairs, PairConnectionTypes,
757 ConnectedPairs, ConnectedPairDeps,
758 PairableInstUsers, ChosenPairs);
760 if (ChosenPairs.empty()) continue;
761 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
762 PairableInsts.end());
763 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
765 // Only for the chosen pairs, propagate information on fixed-order pairs,
766 // pair connections, and their types to the data structures used by the
767 // pair fusion procedures.
768 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
769 IE = ChosenPairs.end(); I != IE; ++I) {
770 if (FixedOrderPairs.count(*I))
771 AllFixedOrderPairs.insert(*I);
772 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
773 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
775 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
777 DenseMap<VPPair, unsigned>::iterator K =
778 PairConnectionTypes.find(VPPair(*I, *J));
779 if (K != PairConnectionTypes.end()) {
780 AllPairConnectionTypes.insert(*K);
782 K = PairConnectionTypes.find(VPPair(*J, *I));
783 if (K != PairConnectionTypes.end())
784 AllPairConnectionTypes.insert(*K);
789 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
790 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
792 for (std::vector<ValuePair>::iterator J = I->second.begin(),
793 JE = I->second.end(); J != JE; ++J)
794 if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
795 AllConnectedPairs[I->first].push_back(*J);
796 AllConnectedPairDeps[*J].push_back(I->first);
798 } while (ShouldContinue);
800 if (AllChosenPairs.empty()) return false;
801 NumFusedOps += AllChosenPairs.size();
803 // A set of pairs has now been selected. It is now necessary to replace the
804 // paired instructions with vector instructions. For this procedure each
805 // operand must be replaced with a vector operand. This vector is formed
806 // by using build_vector on the old operands. The replaced values are then
807 // replaced with a vector_extract on the result. Subsequent optimization
808 // passes should coalesce the build/extract combinations.
810 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
811 AllPairConnectionTypes,
812 AllConnectedPairs, AllConnectedPairDeps);
814 // It is important to cleanup here so that future iterations of this
815 // function have less work to do.
816 (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
820 // This function returns true if the provided instruction is capable of being
821 // fused into a vector instruction. This determination is based only on the
822 // type and other attributes of the instruction.
823 bool BBVectorize::isInstVectorizable(Instruction *I,
824 bool &IsSimpleLoadStore) {
825 IsSimpleLoadStore = false;
827 if (CallInst *C = dyn_cast<CallInst>(I)) {
828 if (!isVectorizableIntrinsic(C))
830 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
831 // Vectorize simple loads if possbile:
832 IsSimpleLoadStore = L->isSimple();
833 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
835 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
836 // Vectorize simple stores if possbile:
837 IsSimpleLoadStore = S->isSimple();
838 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
840 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
841 // We can vectorize casts, but not casts of pointer types, etc.
842 if (!Config.VectorizeCasts)
845 Type *SrcTy = C->getSrcTy();
846 if (!SrcTy->isSingleValueType())
849 Type *DestTy = C->getDestTy();
850 if (!DestTy->isSingleValueType())
852 } else if (isa<SelectInst>(I)) {
853 if (!Config.VectorizeSelect)
855 } else if (isa<CmpInst>(I)) {
856 if (!Config.VectorizeCmp)
858 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
859 if (!Config.VectorizeGEP)
862 // Currently, vector GEPs exist only with one index.
863 if (G->getNumIndices() != 1)
865 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
866 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
870 // We can't vectorize memory operations without target data
871 if (TD == 0 && IsSimpleLoadStore)
875 getInstructionTypes(I, T1, T2);
877 // Not every type can be vectorized...
878 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
879 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
882 if (T1->getScalarSizeInBits() == 1) {
883 if (!Config.VectorizeBools)
886 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
890 if (T2->getScalarSizeInBits() == 1) {
891 if (!Config.VectorizeBools)
894 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
898 if (!Config.VectorizeFloats
899 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
902 // Don't vectorize target-specific types.
903 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
905 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
908 if ((!Config.VectorizePointers || TD == 0) &&
909 (T1->getScalarType()->isPointerTy() ||
910 T2->getScalarType()->isPointerTy()))
913 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
914 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
920 // This function returns true if the two provided instructions are compatible
921 // (meaning that they can be fused into a vector instruction). This assumes
922 // that I has already been determined to be vectorizable and that J is not
923 // in the use tree of I.
924 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
925 bool IsSimpleLoadStore, bool NonPow2Len,
926 int &CostSavings, int &FixedOrder) {
927 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
928 " <-> " << *J << "\n");
933 // Loads and stores can be merged if they have different alignments,
934 // but are otherwise the same.
935 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
936 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
939 Type *IT1, *IT2, *JT1, *JT2;
940 getInstructionTypes(I, IT1, IT2);
941 getInstructionTypes(J, JT1, JT2);
942 unsigned MaxTypeBits = std::max(
943 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
944 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
945 if (!TTI && MaxTypeBits > Config.VectorBits)
948 // FIXME: handle addsub-type operations!
950 if (IsSimpleLoadStore) {
952 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
953 int64_t OffsetInElmts = 0;
954 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
955 IAddressSpace, JAddressSpace,
956 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
957 FixedOrder = (int) OffsetInElmts;
958 unsigned BottomAlignment = IAlignment;
959 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
961 Type *aTypeI = isa<StoreInst>(I) ?
962 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
963 Type *aTypeJ = isa<StoreInst>(J) ?
964 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
965 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
967 if (Config.AlignedOnly) {
968 // An aligned load or store is possible only if the instruction
969 // with the lower offset has an alignment suitable for the
972 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
973 if (BottomAlignment < VecAlignment)
978 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
979 IAlignment, IAddressSpace);
980 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
981 JAlignment, JAddressSpace);
982 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
986 ICost += TTI->getAddressComputationCost(aTypeI);
987 JCost += TTI->getAddressComputationCost(aTypeJ);
988 VCost += TTI->getAddressComputationCost(VType);
990 if (VCost > ICost + JCost)
993 // We don't want to fuse to a type that will be split, even
994 // if the two input types will also be split and there is no other
996 unsigned VParts = TTI->getNumberOfParts(VType);
999 else if (!VParts && VCost == ICost + JCost)
1002 CostSavings = ICost + JCost - VCost;
1008 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1009 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1010 Type *VT1 = getVecTypeForPair(IT1, JT1),
1011 *VT2 = getVecTypeForPair(IT2, JT2);
1013 // Note that this procedure is incorrect for insert and extract element
1014 // instructions (because combining these often results in a shuffle),
1015 // but this cost is ignored (because insert and extract element
1016 // instructions are assigned a zero depth factor and are not really
1017 // fused in general).
1018 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
1020 if (VCost > ICost + JCost)
1023 // We don't want to fuse to a type that will be split, even
1024 // if the two input types will also be split and there is no other
1026 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1027 VParts2 = TTI->getNumberOfParts(VT2);
1028 if (VParts1 > 1 || VParts2 > 1)
1030 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1033 CostSavings = ICost + JCost - VCost;
1036 // The powi intrinsic is special because only the first argument is
1037 // vectorized, the second arguments must be equal.
1038 CallInst *CI = dyn_cast<CallInst>(I);
1040 if (CI && (FI = CI->getCalledFunction())) {
1041 Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1042 if (IID == Intrinsic::powi) {
1043 Value *A1I = CI->getArgOperand(1),
1044 *A1J = cast<CallInst>(J)->getArgOperand(1);
1045 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1046 *A1JSCEV = SE->getSCEV(A1J);
1047 return (A1ISCEV == A1JSCEV);
1051 SmallVector<Type*, 4> Tys;
1052 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1053 Tys.push_back(CI->getArgOperand(i)->getType());
1054 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1057 CallInst *CJ = cast<CallInst>(J);
1058 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1059 Tys.push_back(CJ->getArgOperand(i)->getType());
1060 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1063 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1064 "Intrinsic argument counts differ");
1065 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1066 if (IID == Intrinsic::powi && i == 1)
1067 Tys.push_back(CI->getArgOperand(i)->getType());
1069 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1070 CJ->getArgOperand(i)->getType()));
1073 Type *RetTy = getVecTypeForPair(IT1, JT1);
1074 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1076 if (VCost > ICost + JCost)
1079 // We don't want to fuse to a type that will be split, even
1080 // if the two input types will also be split and there is no other
1082 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1085 else if (!RetParts && VCost == ICost + JCost)
1088 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1089 if (!Tys[i]->isVectorTy())
1092 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1095 else if (!NumParts && VCost == ICost + JCost)
1099 CostSavings = ICost + JCost - VCost;
1106 // Figure out whether or not J uses I and update the users and write-set
1107 // structures associated with I. Specifically, Users represents the set of
1108 // instructions that depend on I. WriteSet represents the set
1109 // of memory locations that are dependent on I. If UpdateUsers is true,
1110 // and J uses I, then Users is updated to contain J and WriteSet is updated
1111 // to contain any memory locations to which J writes. The function returns
1112 // true if J uses I. By default, alias analysis is used to determine
1113 // whether J reads from memory that overlaps with a location in WriteSet.
1114 // If LoadMoveSet is not null, then it is a previously-computed map
1115 // where the key is the memory-based user instruction and the value is
1116 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1117 // then the alias analysis is not used. This is necessary because this
1118 // function is called during the process of moving instructions during
1119 // vectorization and the results of the alias analysis are not stable during
1121 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1122 AliasSetTracker &WriteSet, Instruction *I,
1123 Instruction *J, bool UpdateUsers,
1124 DenseSet<ValuePair> *LoadMoveSetPairs) {
1127 // This instruction may already be marked as a user due, for example, to
1128 // being a member of a selected pair.
1133 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1136 if (I == V || Users.count(V)) {
1141 if (!UsesI && J->mayReadFromMemory()) {
1142 if (LoadMoveSetPairs) {
1143 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1145 for (AliasSetTracker::iterator W = WriteSet.begin(),
1146 WE = WriteSet.end(); W != WE; ++W) {
1147 if (W->aliasesUnknownInst(J, *AA)) {
1155 if (UsesI && UpdateUsers) {
1156 if (J->mayWriteToMemory()) WriteSet.add(J);
1163 // This function iterates over all instruction pairs in the provided
1164 // basic block and collects all candidate pairs for vectorization.
1165 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1166 BasicBlock::iterator &Start,
1167 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1168 DenseSet<ValuePair> &FixedOrderPairs,
1169 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1170 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1171 size_t TotalPairs = 0;
1172 BasicBlock::iterator E = BB.end();
1173 if (Start == E) return false;
1175 bool ShouldContinue = false, IAfterStart = false;
1176 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1177 if (I == Start) IAfterStart = true;
1179 bool IsSimpleLoadStore;
1180 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1182 // Look for an instruction with which to pair instruction *I...
1183 DenseSet<Value *> Users;
1184 AliasSetTracker WriteSet(*AA);
1185 bool JAfterStart = IAfterStart;
1186 BasicBlock::iterator J = llvm::next(I);
1187 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1188 if (J == Start) JAfterStart = true;
1190 // Determine if J uses I, if so, exit the loop.
1191 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1192 if (Config.FastDep) {
1193 // Note: For this heuristic to be effective, independent operations
1194 // must tend to be intermixed. This is likely to be true from some
1195 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1196 // but otherwise may require some kind of reordering pass.
1198 // When using fast dependency analysis,
1199 // stop searching after first use:
1202 if (UsesI) continue;
1205 // J does not use I, and comes before the first use of I, so it can be
1206 // merged with I if the instructions are compatible.
1207 int CostSavings, FixedOrder;
1208 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1209 CostSavings, FixedOrder)) continue;
1211 // J is a candidate for merging with I.
1212 if (!PairableInsts.size() ||
1213 PairableInsts[PairableInsts.size()-1] != I) {
1214 PairableInsts.push_back(I);
1217 CandidatePairs[I].push_back(J);
1220 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1223 if (FixedOrder == 1)
1224 FixedOrderPairs.insert(ValuePair(I, J));
1225 else if (FixedOrder == -1)
1226 FixedOrderPairs.insert(ValuePair(J, I));
1228 // The next call to this function must start after the last instruction
1229 // selected during this invocation.
1231 Start = llvm::next(J);
1232 IAfterStart = JAfterStart = false;
1235 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1236 << *I << " <-> " << *J << " (cost savings: " <<
1237 CostSavings << ")\n");
1239 // If we have already found too many pairs, break here and this function
1240 // will be called again starting after the last instruction selected
1241 // during this invocation.
1242 if (PairableInsts.size() >= Config.MaxInsts ||
1243 TotalPairs >= Config.MaxPairs) {
1244 ShouldContinue = true;
1253 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1254 << " instructions with candidate pairs\n");
1256 return ShouldContinue;
1259 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1260 // it looks for pairs such that both members have an input which is an
1261 // output of PI or PJ.
1262 void BBVectorize::computePairsConnectedTo(
1263 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1264 DenseSet<ValuePair> &CandidatePairsSet,
1265 std::vector<Value *> &PairableInsts,
1266 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1267 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1271 // For each possible pairing for this variable, look at the uses of
1272 // the first value...
1273 for (Value::use_iterator I = P.first->use_begin(),
1274 E = P.first->use_end(); I != E; ++I) {
1275 if (isa<LoadInst>(*I)) {
1276 // A pair cannot be connected to a load because the load only takes one
1277 // operand (the address) and it is a scalar even after vectorization.
1279 } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1280 P.first == SI->getPointerOperand()) {
1281 // Similarly, a pair cannot be connected to a store through its
1286 // For each use of the first variable, look for uses of the second
1288 for (Value::use_iterator J = P.second->use_begin(),
1289 E2 = P.second->use_end(); J != E2; ++J) {
1290 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1291 P.second == SJ->getPointerOperand())
1295 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1296 VPPair VP(P, ValuePair(*I, *J));
1297 ConnectedPairs[VP.first].push_back(VP.second);
1298 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1302 if (CandidatePairsSet.count(ValuePair(*J, *I))) {
1303 VPPair VP(P, ValuePair(*J, *I));
1304 ConnectedPairs[VP.first].push_back(VP.second);
1305 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1309 if (Config.SplatBreaksChain) continue;
1310 // Look for cases where just the first value in the pair is used by
1311 // both members of another pair (splatting).
1312 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1313 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1314 P.first == SJ->getPointerOperand())
1317 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1318 VPPair VP(P, ValuePair(*I, *J));
1319 ConnectedPairs[VP.first].push_back(VP.second);
1320 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1325 if (Config.SplatBreaksChain) return;
1326 // Look for cases where just the second value in the pair is used by
1327 // both members of another pair (splatting).
1328 for (Value::use_iterator I = P.second->use_begin(),
1329 E = P.second->use_end(); I != E; ++I) {
1330 if (isa<LoadInst>(*I))
1332 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1333 P.second == SI->getPointerOperand())
1336 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1337 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1338 P.second == SJ->getPointerOperand())
1341 if (CandidatePairsSet.count(ValuePair(*I, *J))) {
1342 VPPair VP(P, ValuePair(*I, *J));
1343 ConnectedPairs[VP.first].push_back(VP.second);
1344 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1350 // This function figures out which pairs are connected. Two pairs are
1351 // connected if some output of the first pair forms an input to both members
1352 // of the second pair.
1353 void BBVectorize::computeConnectedPairs(
1354 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1355 DenseSet<ValuePair> &CandidatePairsSet,
1356 std::vector<Value *> &PairableInsts,
1357 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1358 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1359 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1360 PE = PairableInsts.end(); PI != PE; ++PI) {
1361 DenseMap<Value *, std::vector<Value *> >::iterator PP =
1362 CandidatePairs.find(*PI);
1363 if (PP == CandidatePairs.end())
1366 for (std::vector<Value *>::iterator P = PP->second.begin(),
1367 E = PP->second.end(); P != E; ++P)
1368 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1369 PairableInsts, ConnectedPairs,
1370 PairConnectionTypes, ValuePair(*PI, *P));
1373 DEBUG(size_t TotalPairs = 0;
1374 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1375 ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1376 TotalPairs += I->second.size();
1377 dbgs() << "BBV: found " << TotalPairs
1378 << " pair connections.\n");
1381 // This function builds a set of use tuples such that <A, B> is in the set
1382 // if B is in the use tree of A. If B is in the use tree of A, then B
1383 // depends on the output of A.
1384 void BBVectorize::buildDepMap(
1386 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1387 std::vector<Value *> &PairableInsts,
1388 DenseSet<ValuePair> &PairableInstUsers) {
1389 DenseSet<Value *> IsInPair;
1390 for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1391 CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1392 IsInPair.insert(C->first);
1393 IsInPair.insert(C->second.begin(), C->second.end());
1396 // Iterate through the basic block, recording all users of each
1397 // pairable instruction.
1399 BasicBlock::iterator E = BB.end(), EL =
1400 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1401 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1402 if (IsInPair.find(I) == IsInPair.end()) continue;
1404 DenseSet<Value *> Users;
1405 AliasSetTracker WriteSet(*AA);
1406 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J) {
1407 (void) trackUsesOfI(Users, WriteSet, I, J);
1413 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1415 if (IsInPair.find(*U) == IsInPair.end()) continue;
1416 PairableInstUsers.insert(ValuePair(I, *U));
1424 // Returns true if an input to pair P is an output of pair Q and also an
1425 // input of pair Q is an output of pair P. If this is the case, then these
1426 // two pairs cannot be simultaneously fused.
1427 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1428 DenseSet<ValuePair> &PairableInstUsers,
1429 DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1430 DenseSet<VPPair> *PairableInstUserPairSet) {
1431 // Two pairs are in conflict if they are mutual Users of eachother.
1432 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1433 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1434 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1435 PairableInstUsers.count(ValuePair(P.second, Q.second));
1436 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1437 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1438 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1439 PairableInstUsers.count(ValuePair(Q.second, P.second));
1440 if (PairableInstUserMap) {
1441 // FIXME: The expensive part of the cycle check is not so much the cycle
1442 // check itself but this edge insertion procedure. This needs some
1443 // profiling and probably a different data structure.
1445 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1446 (*PairableInstUserMap)[Q].push_back(P);
1449 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1450 (*PairableInstUserMap)[P].push_back(Q);
1454 return (QUsesP && PUsesQ);
1457 // This function walks the use graph of current pairs to see if, starting
1458 // from P, the walk returns to P.
1459 bool BBVectorize::pairWillFormCycle(ValuePair P,
1460 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1461 DenseSet<ValuePair> &CurrentPairs) {
1462 DEBUG(if (DebugCycleCheck)
1463 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1464 << *P.second << "\n");
1465 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1466 // contains non-direct associations.
1467 DenseSet<ValuePair> Visited;
1468 SmallVector<ValuePair, 32> Q;
1469 // General depth-first post-order traversal:
1472 ValuePair QTop = Q.pop_back_val();
1473 Visited.insert(QTop);
1475 DEBUG(if (DebugCycleCheck)
1476 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1477 << *QTop.second << "\n");
1478 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1479 PairableInstUserMap.find(QTop);
1480 if (QQ == PairableInstUserMap.end())
1483 for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1484 CE = QQ->second.end(); C != CE; ++C) {
1487 << "BBV: rejected to prevent non-trivial cycle formation: "
1488 << QTop.first << " <-> " << C->second << "\n");
1492 if (CurrentPairs.count(*C) && !Visited.count(*C))
1495 } while (!Q.empty());
1500 // This function builds the initial tree of connected pairs with the
1501 // pair J at the root.
1502 void BBVectorize::buildInitialTreeFor(
1503 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1504 DenseSet<ValuePair> &CandidatePairsSet,
1505 std::vector<Value *> &PairableInsts,
1506 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1507 DenseSet<ValuePair> &PairableInstUsers,
1508 DenseMap<Value *, Value *> &ChosenPairs,
1509 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1510 // Each of these pairs is viewed as the root node of a Tree. The Tree
1511 // is then walked (depth-first). As this happens, we keep track of
1512 // the pairs that compose the Tree and the maximum depth of the Tree.
1513 SmallVector<ValuePairWithDepth, 32> Q;
1514 // General depth-first post-order traversal:
1515 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1517 ValuePairWithDepth QTop = Q.back();
1519 // Push each child onto the queue:
1520 bool MoreChildren = false;
1521 size_t MaxChildDepth = QTop.second;
1522 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1523 ConnectedPairs.find(QTop.first);
1524 if (QQ != ConnectedPairs.end())
1525 for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1526 ke = QQ->second.end(); k != ke; ++k) {
1527 // Make sure that this child pair is still a candidate:
1528 if (CandidatePairsSet.count(*k)) {
1529 DenseMap<ValuePair, size_t>::iterator C = Tree.find(*k);
1530 if (C == Tree.end()) {
1531 size_t d = getDepthFactor(k->first);
1532 Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1533 MoreChildren = true;
1535 MaxChildDepth = std::max(MaxChildDepth, C->second);
1540 if (!MoreChildren) {
1541 // Record the current pair as part of the Tree:
1542 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1545 } while (!Q.empty());
1548 // Given some initial tree, prune it by removing conflicting pairs (pairs
1549 // that cannot be simultaneously chosen for vectorization).
1550 void BBVectorize::pruneTreeFor(
1551 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1552 std::vector<Value *> &PairableInsts,
1553 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1554 DenseSet<ValuePair> &PairableInstUsers,
1555 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1556 DenseSet<VPPair> &PairableInstUserPairSet,
1557 DenseMap<Value *, Value *> &ChosenPairs,
1558 DenseMap<ValuePair, size_t> &Tree,
1559 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1560 bool UseCycleCheck) {
1561 SmallVector<ValuePairWithDepth, 32> Q;
1562 // General depth-first post-order traversal:
1563 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1565 ValuePairWithDepth QTop = Q.pop_back_val();
1566 PrunedTree.insert(QTop.first);
1568 // Visit each child, pruning as necessary...
1569 SmallVector<ValuePairWithDepth, 8> BestChildren;
1570 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1571 ConnectedPairs.find(QTop.first);
1572 if (QQ == ConnectedPairs.end())
1575 for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1576 KE = QQ->second.end(); K != KE; ++K) {
1577 DenseMap<ValuePair, size_t>::iterator C = Tree.find(*K);
1578 if (C == Tree.end()) continue;
1580 // This child is in the Tree, now we need to make sure it is the
1581 // best of any conflicting children. There could be multiple
1582 // conflicting children, so first, determine if we're keeping
1583 // this child, then delete conflicting children as necessary.
1585 // It is also necessary to guard against pairing-induced
1586 // dependencies. Consider instructions a .. x .. y .. b
1587 // such that (a,b) are to be fused and (x,y) are to be fused
1588 // but a is an input to x and b is an output from y. This
1589 // means that y cannot be moved after b but x must be moved
1590 // after b for (a,b) to be fused. In other words, after
1591 // fusing (a,b) we have y .. a/b .. x where y is an input
1592 // to a/b and x is an output to a/b: x and y can no longer
1593 // be legally fused. To prevent this condition, we must
1594 // make sure that a child pair added to the Tree is not
1595 // both an input and output of an already-selected pair.
1597 // Pairing-induced dependencies can also form from more complicated
1598 // cycles. The pair vs. pair conflicts are easy to check, and so
1599 // that is done explicitly for "fast rejection", and because for
1600 // child vs. child conflicts, we may prefer to keep the current
1601 // pair in preference to the already-selected child.
1602 DenseSet<ValuePair> CurrentPairs;
1605 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1606 = BestChildren.begin(), E2 = BestChildren.end();
1608 if (C2->first.first == C->first.first ||
1609 C2->first.first == C->first.second ||
1610 C2->first.second == C->first.first ||
1611 C2->first.second == C->first.second ||
1612 pairsConflict(C2->first, C->first, PairableInstUsers,
1613 UseCycleCheck ? &PairableInstUserMap : 0,
1614 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1615 if (C2->second >= C->second) {
1620 CurrentPairs.insert(C2->first);
1623 if (!CanAdd) continue;
1625 // Even worse, this child could conflict with another node already
1626 // selected for the Tree. If that is the case, ignore this child.
1627 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1628 E2 = PrunedTree.end(); T != E2; ++T) {
1629 if (T->first == C->first.first ||
1630 T->first == C->first.second ||
1631 T->second == C->first.first ||
1632 T->second == C->first.second ||
1633 pairsConflict(*T, C->first, PairableInstUsers,
1634 UseCycleCheck ? &PairableInstUserMap : 0,
1635 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1640 CurrentPairs.insert(*T);
1642 if (!CanAdd) continue;
1644 // And check the queue too...
1645 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1646 E2 = Q.end(); C2 != E2; ++C2) {
1647 if (C2->first.first == C->first.first ||
1648 C2->first.first == C->first.second ||
1649 C2->first.second == C->first.first ||
1650 C2->first.second == C->first.second ||
1651 pairsConflict(C2->first, C->first, PairableInstUsers,
1652 UseCycleCheck ? &PairableInstUserMap : 0,
1653 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1658 CurrentPairs.insert(C2->first);
1660 if (!CanAdd) continue;
1662 // Last but not least, check for a conflict with any of the
1663 // already-chosen pairs.
1664 for (DenseMap<Value *, Value *>::iterator C2 =
1665 ChosenPairs.begin(), E2 = ChosenPairs.end();
1667 if (pairsConflict(*C2, C->first, PairableInstUsers,
1668 UseCycleCheck ? &PairableInstUserMap : 0,
1669 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1674 CurrentPairs.insert(*C2);
1676 if (!CanAdd) continue;
1678 // To check for non-trivial cycles formed by the addition of the
1679 // current pair we've formed a list of all relevant pairs, now use a
1680 // graph walk to check for a cycle. We start from the current pair and
1681 // walk the use tree to see if we again reach the current pair. If we
1682 // do, then the current pair is rejected.
1684 // FIXME: It may be more efficient to use a topological-ordering
1685 // algorithm to improve the cycle check. This should be investigated.
1686 if (UseCycleCheck &&
1687 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1690 // This child can be added, but we may have chosen it in preference
1691 // to an already-selected child. Check for this here, and if a
1692 // conflict is found, then remove the previously-selected child
1693 // before adding this one in its place.
1694 for (SmallVector<ValuePairWithDepth, 8>::iterator C2
1695 = BestChildren.begin(); C2 != BestChildren.end();) {
1696 if (C2->first.first == C->first.first ||
1697 C2->first.first == C->first.second ||
1698 C2->first.second == C->first.first ||
1699 C2->first.second == C->first.second ||
1700 pairsConflict(C2->first, C->first, PairableInstUsers))
1701 C2 = BestChildren.erase(C2);
1706 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1709 for (SmallVector<ValuePairWithDepth, 8>::iterator C
1710 = BestChildren.begin(), E2 = BestChildren.end();
1712 size_t DepthF = getDepthFactor(C->first.first);
1713 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1715 } while (!Q.empty());
1718 // This function finds the best tree of mututally-compatible connected
1719 // pairs, given the choice of root pairs as an iterator range.
1720 void BBVectorize::findBestTreeFor(
1721 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1722 DenseSet<ValuePair> &CandidatePairsSet,
1723 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1724 std::vector<Value *> &PairableInsts,
1725 DenseSet<ValuePair> &FixedOrderPairs,
1726 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1727 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1728 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1729 DenseSet<ValuePair> &PairableInstUsers,
1730 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1731 DenseSet<VPPair> &PairableInstUserPairSet,
1732 DenseMap<Value *, Value *> &ChosenPairs,
1733 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1734 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1735 bool UseCycleCheck) {
1736 for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1738 ValuePair IJ(II, *J);
1739 if (!CandidatePairsSet.count(IJ))
1742 // Before going any further, make sure that this pair does not
1743 // conflict with any already-selected pairs (see comment below
1744 // near the Tree pruning for more details).
1745 DenseSet<ValuePair> ChosenPairSet;
1746 bool DoesConflict = false;
1747 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1748 E = ChosenPairs.end(); C != E; ++C) {
1749 if (pairsConflict(*C, IJ, PairableInstUsers,
1750 UseCycleCheck ? &PairableInstUserMap : 0,
1751 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1752 DoesConflict = true;
1756 ChosenPairSet.insert(*C);
1758 if (DoesConflict) continue;
1760 if (UseCycleCheck &&
1761 pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1764 DenseMap<ValuePair, size_t> Tree;
1765 buildInitialTreeFor(CandidatePairs, CandidatePairsSet,
1766 PairableInsts, ConnectedPairs,
1767 PairableInstUsers, ChosenPairs, Tree, IJ);
1769 // Because we'll keep the child with the largest depth, the largest
1770 // depth is still the same in the unpruned Tree.
1771 size_t MaxDepth = Tree.lookup(IJ);
1773 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1774 << IJ.first << " <-> " << IJ.second << "} of depth " <<
1775 MaxDepth << " and size " << Tree.size() << "\n");
1777 // At this point the Tree has been constructed, but, may contain
1778 // contradictory children (meaning that different children of
1779 // some tree node may be attempting to fuse the same instruction).
1780 // So now we walk the tree again, in the case of a conflict,
1781 // keep only the child with the largest depth. To break a tie,
1782 // favor the first child.
1784 DenseSet<ValuePair> PrunedTree;
1785 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1786 PairableInstUsers, PairableInstUserMap,
1787 PairableInstUserPairSet,
1788 ChosenPairs, Tree, PrunedTree, IJ, UseCycleCheck);
1792 DenseSet<Value *> PrunedTreeInstrs;
1793 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1794 E = PrunedTree.end(); S != E; ++S) {
1795 PrunedTreeInstrs.insert(S->first);
1796 PrunedTreeInstrs.insert(S->second);
1799 // The set of pairs that have already contributed to the total cost.
1800 DenseSet<ValuePair> IncomingPairs;
1802 // If the cost model were perfect, this might not be necessary; but we
1803 // need to make sure that we don't get stuck vectorizing our own
1805 bool HasNontrivialInsts = false;
1807 // The node weights represent the cost savings associated with
1808 // fusing the pair of instructions.
1809 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1810 E = PrunedTree.end(); S != E; ++S) {
1811 if (!isa<ShuffleVectorInst>(S->first) &&
1812 !isa<InsertElementInst>(S->first) &&
1813 !isa<ExtractElementInst>(S->first))
1814 HasNontrivialInsts = true;
1816 bool FlipOrder = false;
1818 if (getDepthFactor(S->first)) {
1819 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1820 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1821 << *S->first << " <-> " << *S->second << "} = " <<
1823 EffSize += ESContrib;
1826 // The edge weights contribute in a negative sense: they represent
1827 // the cost of shuffles.
1828 DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1829 ConnectedPairDeps.find(*S);
1830 if (SS != ConnectedPairDeps.end()) {
1831 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1832 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1833 TE = SS->second.end(); T != TE; ++T) {
1835 if (!PrunedTree.count(Q.second))
1837 DenseMap<VPPair, unsigned>::iterator R =
1838 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1839 assert(R != PairConnectionTypes.end() &&
1840 "Cannot find pair connection type");
1841 if (R->second == PairConnectionDirect)
1843 else if (R->second == PairConnectionSwap)
1847 // If there are more swaps than direct connections, then
1848 // the pair order will be flipped during fusion. So the real
1849 // number of swaps is the minimum number.
1850 FlipOrder = !FixedOrderPairs.count(*S) &&
1851 ((NumDepsSwap > NumDepsDirect) ||
1852 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1854 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1855 TE = SS->second.end(); T != TE; ++T) {
1857 if (!PrunedTree.count(Q.second))
1859 DenseMap<VPPair, unsigned>::iterator R =
1860 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1861 assert(R != PairConnectionTypes.end() &&
1862 "Cannot find pair connection type");
1863 Type *Ty1 = Q.second.first->getType(),
1864 *Ty2 = Q.second.second->getType();
1865 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1866 if ((R->second == PairConnectionDirect && FlipOrder) ||
1867 (R->second == PairConnectionSwap && !FlipOrder) ||
1868 R->second == PairConnectionSplat) {
1869 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1872 if (VTy->getVectorNumElements() == 2) {
1873 if (R->second == PairConnectionSplat)
1874 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1875 TargetTransformInfo::SK_Broadcast, VTy));
1877 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1878 TargetTransformInfo::SK_Reverse, VTy));
1881 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1882 *Q.second.first << " <-> " << *Q.second.second <<
1884 *S->first << " <-> " << *S->second << "} = " <<
1886 EffSize -= ESContrib;
1891 // Compute the cost of outgoing edges. We assume that edges outgoing
1892 // to shuffles, inserts or extracts can be merged, and so contribute
1893 // no additional cost.
1894 if (!S->first->getType()->isVoidTy()) {
1895 Type *Ty1 = S->first->getType(),
1896 *Ty2 = S->second->getType();
1897 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1899 bool NeedsExtraction = false;
1900 for (Value::use_iterator I = S->first->use_begin(),
1901 IE = S->first->use_end(); I != IE; ++I) {
1902 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1903 // Shuffle can be folded if it has no other input
1904 if (isa<UndefValue>(SI->getOperand(1)))
1907 if (isa<ExtractElementInst>(*I))
1909 if (PrunedTreeInstrs.count(*I))
1911 NeedsExtraction = true;
1915 if (NeedsExtraction) {
1917 if (Ty1->isVectorTy()) {
1918 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1920 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1921 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1923 ESContrib = (int) TTI->getVectorInstrCost(
1924 Instruction::ExtractElement, VTy, 0);
1926 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1927 *S->first << "} = " << ESContrib << "\n");
1928 EffSize -= ESContrib;
1931 NeedsExtraction = false;
1932 for (Value::use_iterator I = S->second->use_begin(),
1933 IE = S->second->use_end(); I != IE; ++I) {
1934 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(*I)) {
1935 // Shuffle can be folded if it has no other input
1936 if (isa<UndefValue>(SI->getOperand(1)))
1939 if (isa<ExtractElementInst>(*I))
1941 if (PrunedTreeInstrs.count(*I))
1943 NeedsExtraction = true;
1947 if (NeedsExtraction) {
1949 if (Ty2->isVectorTy()) {
1950 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1952 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1953 TargetTransformInfo::SK_ExtractSubvector, VTy,
1954 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
1956 ESContrib = (int) TTI->getVectorInstrCost(
1957 Instruction::ExtractElement, VTy, 1);
1958 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1959 *S->second << "} = " << ESContrib << "\n");
1960 EffSize -= ESContrib;
1964 // Compute the cost of incoming edges.
1965 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
1966 Instruction *S1 = cast<Instruction>(S->first),
1967 *S2 = cast<Instruction>(S->second);
1968 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
1969 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
1971 // Combining constants into vector constants (or small vector
1972 // constants into larger ones are assumed free).
1973 if (isa<Constant>(O1) && isa<Constant>(O2))
1979 ValuePair VP = ValuePair(O1, O2);
1980 ValuePair VPR = ValuePair(O2, O1);
1982 // Internal edges are not handled here.
1983 if (PrunedTree.count(VP) || PrunedTree.count(VPR))
1986 Type *Ty1 = O1->getType(),
1987 *Ty2 = O2->getType();
1988 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1990 // Combining vector operations of the same type is also assumed
1991 // folded with other operations.
1993 // If both are insert elements, then both can be widened.
1994 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
1995 *IEO2 = dyn_cast<InsertElementInst>(O2);
1996 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
1998 // If both are extract elements, and both have the same input
1999 // type, then they can be replaced with a shuffle
2000 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2001 *EIO2 = dyn_cast<ExtractElementInst>(O2);
2003 EIO1->getOperand(0)->getType() ==
2004 EIO2->getOperand(0)->getType())
2006 // If both are a shuffle with equal operand types and only two
2007 // unqiue operands, then they can be replaced with a single
2009 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2010 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2012 SIO1->getOperand(0)->getType() ==
2013 SIO2->getOperand(0)->getType()) {
2014 SmallSet<Value *, 4> SIOps;
2015 SIOps.insert(SIO1->getOperand(0));
2016 SIOps.insert(SIO1->getOperand(1));
2017 SIOps.insert(SIO2->getOperand(0));
2018 SIOps.insert(SIO2->getOperand(1));
2019 if (SIOps.size() <= 2)
2025 // This pair has already been formed.
2026 if (IncomingPairs.count(VP)) {
2028 } else if (IncomingPairs.count(VPR)) {
2029 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2032 if (VTy->getVectorNumElements() == 2)
2033 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2034 TargetTransformInfo::SK_Reverse, VTy));
2035 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2036 ESContrib = (int) TTI->getVectorInstrCost(
2037 Instruction::InsertElement, VTy, 0);
2038 ESContrib += (int) TTI->getVectorInstrCost(
2039 Instruction::InsertElement, VTy, 1);
2040 } else if (!Ty1->isVectorTy()) {
2041 // O1 needs to be inserted into a vector of size O2, and then
2042 // both need to be shuffled together.
2043 ESContrib = (int) TTI->getVectorInstrCost(
2044 Instruction::InsertElement, Ty2, 0);
2045 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2047 } else if (!Ty2->isVectorTy()) {
2048 // O2 needs to be inserted into a vector of size O1, and then
2049 // both need to be shuffled together.
2050 ESContrib = (int) TTI->getVectorInstrCost(
2051 Instruction::InsertElement, Ty1, 0);
2052 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2055 Type *TyBig = Ty1, *TySmall = Ty2;
2056 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2057 std::swap(TyBig, TySmall);
2059 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2061 if (TyBig != TySmall)
2062 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2066 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2067 << *O1 << " <-> " << *O2 << "} = " <<
2069 EffSize -= ESContrib;
2070 IncomingPairs.insert(VP);
2075 if (!HasNontrivialInsts) {
2076 DEBUG(if (DebugPairSelection) dbgs() <<
2077 "\tNo non-trivial instructions in tree;"
2078 " override to zero effective size\n");
2082 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
2083 E = PrunedTree.end(); S != E; ++S)
2084 EffSize += (int) getDepthFactor(S->first);
2087 DEBUG(if (DebugPairSelection)
2088 dbgs() << "BBV: found pruned Tree for pair {"
2089 << IJ.first << " <-> " << IJ.second << "} of depth " <<
2090 MaxDepth << " and size " << PrunedTree.size() <<
2091 " (effective size: " << EffSize << ")\n");
2092 if (((TTI && !UseChainDepthWithTI) ||
2093 MaxDepth >= Config.ReqChainDepth) &&
2094 EffSize > 0 && EffSize > BestEffSize) {
2095 BestMaxDepth = MaxDepth;
2096 BestEffSize = EffSize;
2097 BestTree = PrunedTree;
2102 // Given the list of candidate pairs, this function selects those
2103 // that will be fused into vector instructions.
2104 void BBVectorize::choosePairs(
2105 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2106 DenseSet<ValuePair> &CandidatePairsSet,
2107 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2108 std::vector<Value *> &PairableInsts,
2109 DenseSet<ValuePair> &FixedOrderPairs,
2110 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2111 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2112 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2113 DenseSet<ValuePair> &PairableInstUsers,
2114 DenseMap<Value *, Value *>& ChosenPairs) {
2115 bool UseCycleCheck =
2116 CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2118 DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2119 for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2120 E = CandidatePairsSet.end(); I != E; ++I) {
2121 std::vector<Value *> &JJ = CandidatePairs2[I->second];
2122 if (JJ.empty()) JJ.reserve(32);
2123 JJ.push_back(I->first);
2126 DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2127 DenseSet<VPPair> PairableInstUserPairSet;
2128 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2129 E = PairableInsts.end(); I != E; ++I) {
2130 // The number of possible pairings for this variable:
2131 size_t NumChoices = CandidatePairs.lookup(*I).size();
2132 if (!NumChoices) continue;
2134 std::vector<Value *> &JJ = CandidatePairs[*I];
2136 // The best pair to choose and its tree:
2137 size_t BestMaxDepth = 0;
2138 int BestEffSize = 0;
2139 DenseSet<ValuePair> BestTree;
2140 findBestTreeFor(CandidatePairs, CandidatePairsSet,
2141 CandidatePairCostSavings,
2142 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2143 ConnectedPairs, ConnectedPairDeps,
2144 PairableInstUsers, PairableInstUserMap,
2145 PairableInstUserPairSet, ChosenPairs,
2146 BestTree, BestMaxDepth, BestEffSize, *I, JJ,
2149 if (BestTree.empty())
2152 // A tree has been chosen (or not) at this point. If no tree was
2153 // chosen, then this instruction, I, cannot be paired (and is no longer
2156 DEBUG(dbgs() << "BBV: selected pairs in the best tree for: "
2157 << *cast<Instruction>(*I) << "\n");
2159 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
2160 SE2 = BestTree.end(); S != SE2; ++S) {
2161 // Insert the members of this tree into the list of chosen pairs.
2162 ChosenPairs.insert(ValuePair(S->first, S->second));
2163 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2164 *S->second << "\n");
2166 // Remove all candidate pairs that have values in the chosen tree.
2167 std::vector<Value *> &KK = CandidatePairs[S->first],
2168 &LL = CandidatePairs2[S->second],
2169 &MM = CandidatePairs[S->second],
2170 &NN = CandidatePairs2[S->first];
2171 for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2173 if (*K == S->second)
2176 CandidatePairsSet.erase(ValuePair(S->first, *K));
2178 for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2183 CandidatePairsSet.erase(ValuePair(*L, S->second));
2185 for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2187 assert(*M != S->first && "Flipped pair in candidate list?");
2188 CandidatePairsSet.erase(ValuePair(S->second, *M));
2190 for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2192 assert(*N != S->second && "Flipped pair in candidate list?");
2193 CandidatePairsSet.erase(ValuePair(*N, S->first));
2198 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2201 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2206 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2207 (n > 0 ? "." + utostr(n) : "")).str();
2210 // Returns the value that is to be used as the pointer input to the vector
2211 // instruction that fuses I with J.
2212 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2213 Instruction *I, Instruction *J, unsigned o) {
2215 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2216 int64_t OffsetInElmts;
2218 // Note: the analysis might fail here, that is why the pair order has
2219 // been precomputed (OffsetInElmts must be unused here).
2220 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2221 IAddressSpace, JAddressSpace,
2222 OffsetInElmts, false);
2224 // The pointer value is taken to be the one with the lowest offset.
2227 Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
2228 Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
2229 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2230 Type *VArgPtrType = PointerType::get(VArgType,
2231 cast<PointerType>(IPtr->getType())->getAddressSpace());
2232 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2233 /* insert before */ I);
2236 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2237 unsigned MaskOffset, unsigned NumInElem,
2238 unsigned NumInElem1, unsigned IdxOffset,
2239 std::vector<Constant*> &Mask) {
2240 unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
2241 for (unsigned v = 0; v < NumElem1; ++v) {
2242 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2244 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2246 unsigned mm = m + (int) IdxOffset;
2247 if (m >= (int) NumInElem1)
2248 mm += (int) NumInElem;
2250 Mask[v+MaskOffset] =
2251 ConstantInt::get(Type::getInt32Ty(Context), mm);
2256 // Returns the value that is to be used as the vector-shuffle mask to the
2257 // vector instruction that fuses I with J.
2258 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2259 Instruction *I, Instruction *J) {
2260 // This is the shuffle mask. We need to append the second
2261 // mask to the first, and the numbers need to be adjusted.
2263 Type *ArgTypeI = I->getType();
2264 Type *ArgTypeJ = J->getType();
2265 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2267 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
2269 // Get the total number of elements in the fused vector type.
2270 // By definition, this must equal the number of elements in
2272 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
2273 std::vector<Constant*> Mask(NumElem);
2275 Type *OpTypeI = I->getOperand(0)->getType();
2276 unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
2277 Type *OpTypeJ = J->getOperand(0)->getType();
2278 unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
2280 // The fused vector will be:
2281 // -----------------------------------------------------
2282 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2283 // -----------------------------------------------------
2284 // from which we'll extract NumElem total elements (where the first NumElemI
2285 // of them come from the mask in I and the remainder come from the mask
2288 // For the mask from the first pair...
2289 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2292 // For the mask from the second pair...
2293 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2296 return ConstantVector::get(Mask);
2299 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2300 Instruction *J, unsigned o, Value *&LOp,
2302 Type *ArgTypeL, Type *ArgTypeH,
2303 bool IBeforeJ, unsigned IdxOff) {
2304 bool ExpandedIEChain = false;
2305 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2306 // If we have a pure insertelement chain, then this can be rewritten
2307 // into a chain that directly builds the larger type.
2308 if (isPureIEChain(LIE)) {
2309 SmallVector<Value *, 8> VectElemts(numElemL,
2310 UndefValue::get(ArgTypeL->getScalarType()));
2311 InsertElementInst *LIENext = LIE;
2314 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2315 VectElemts[Idx] = LIENext->getOperand(1);
2317 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2320 Value *LIEPrev = UndefValue::get(ArgTypeH);
2321 for (unsigned i = 0; i < numElemL; ++i) {
2322 if (isa<UndefValue>(VectElemts[i])) continue;
2323 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2324 ConstantInt::get(Type::getInt32Ty(Context),
2326 getReplacementName(IBeforeJ ? I : J,
2328 LIENext->insertBefore(IBeforeJ ? J : I);
2332 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2333 ExpandedIEChain = true;
2337 return ExpandedIEChain;
2340 // Returns the value to be used as the specified operand of the vector
2341 // instruction that fuses I with J.
2342 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2343 Instruction *J, unsigned o, bool IBeforeJ) {
2344 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2345 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2347 // Compute the fused vector type for this operand
2348 Type *ArgTypeI = I->getOperand(o)->getType();
2349 Type *ArgTypeJ = J->getOperand(o)->getType();
2350 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2352 Instruction *L = I, *H = J;
2353 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2356 if (ArgTypeL->isVectorTy())
2357 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
2362 if (ArgTypeH->isVectorTy())
2363 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
2367 Value *LOp = L->getOperand(o);
2368 Value *HOp = H->getOperand(o);
2369 unsigned numElem = VArgType->getNumElements();
2371 // First, we check if we can reuse the "original" vector outputs (if these
2372 // exist). We might need a shuffle.
2373 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2374 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2375 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2376 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2378 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2379 // optimization. The input vectors to the shuffle might be a different
2380 // length from the shuffle outputs. Unfortunately, the replacement
2381 // shuffle mask has already been formed, and the mask entries are sensitive
2382 // to the sizes of the inputs.
2383 bool IsSizeChangeShuffle =
2384 isa<ShuffleVectorInst>(L) &&
2385 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2387 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2388 // We can have at most two unique vector inputs.
2389 bool CanUseInputs = true;
2392 I1 = LEE->getOperand(0);
2394 I1 = LSV->getOperand(0);
2395 I2 = LSV->getOperand(1);
2396 if (I2 == I1 || isa<UndefValue>(I2))
2401 Value *I3 = HEE->getOperand(0);
2402 if (!I2 && I3 != I1)
2404 else if (I3 != I1 && I3 != I2)
2405 CanUseInputs = false;
2407 Value *I3 = HSV->getOperand(0);
2408 if (!I2 && I3 != I1)
2410 else if (I3 != I1 && I3 != I2)
2411 CanUseInputs = false;
2414 Value *I4 = HSV->getOperand(1);
2415 if (!isa<UndefValue>(I4)) {
2416 if (!I2 && I4 != I1)
2418 else if (I4 != I1 && I4 != I2)
2419 CanUseInputs = false;
2426 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2429 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2432 // We have one or two input vectors. We need to map each index of the
2433 // operands to the index of the original vector.
2434 SmallVector<std::pair<int, int>, 8> II(numElem);
2435 for (unsigned i = 0; i < numElemL; ++i) {
2439 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2440 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2442 Idx = LSV->getMaskValue(i);
2443 if (Idx < (int) LOpElem) {
2444 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2447 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2451 II[i] = std::pair<int, int>(Idx, INum);
2453 for (unsigned i = 0; i < numElemH; ++i) {
2457 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2458 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2460 Idx = HSV->getMaskValue(i);
2461 if (Idx < (int) HOpElem) {
2462 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2465 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2469 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2472 // We now have an array which tells us from which index of which
2473 // input vector each element of the operand comes.
2474 VectorType *I1T = cast<VectorType>(I1->getType());
2475 unsigned I1Elem = I1T->getNumElements();
2478 // In this case there is only one underlying vector input. Check for
2479 // the trivial case where we can use the input directly.
2480 if (I1Elem == numElem) {
2481 bool ElemInOrder = true;
2482 for (unsigned i = 0; i < numElem; ++i) {
2483 if (II[i].first != (int) i && II[i].first != -1) {
2484 ElemInOrder = false;
2493 // A shuffle is needed.
2494 std::vector<Constant *> Mask(numElem);
2495 for (unsigned i = 0; i < numElem; ++i) {
2496 int Idx = II[i].first;
2498 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2500 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2504 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2505 ConstantVector::get(Mask),
2506 getReplacementName(IBeforeJ ? I : J,
2508 S->insertBefore(IBeforeJ ? J : I);
2512 VectorType *I2T = cast<VectorType>(I2->getType());
2513 unsigned I2Elem = I2T->getNumElements();
2515 // This input comes from two distinct vectors. The first step is to
2516 // make sure that both vectors are the same length. If not, the
2517 // smaller one will need to grow before they can be shuffled together.
2518 if (I1Elem < I2Elem) {
2519 std::vector<Constant *> Mask(I2Elem);
2521 for (; v < I1Elem; ++v)
2522 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2523 for (; v < I2Elem; ++v)
2524 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2526 Instruction *NewI1 =
2527 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2528 ConstantVector::get(Mask),
2529 getReplacementName(IBeforeJ ? I : J,
2531 NewI1->insertBefore(IBeforeJ ? J : I);
2535 } else if (I1Elem > I2Elem) {
2536 std::vector<Constant *> Mask(I1Elem);
2538 for (; v < I2Elem; ++v)
2539 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2540 for (; v < I1Elem; ++v)
2541 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2543 Instruction *NewI2 =
2544 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2545 ConstantVector::get(Mask),
2546 getReplacementName(IBeforeJ ? I : J,
2548 NewI2->insertBefore(IBeforeJ ? J : I);
2554 // Now that both I1 and I2 are the same length we can shuffle them
2555 // together (and use the result).
2556 std::vector<Constant *> Mask(numElem);
2557 for (unsigned v = 0; v < numElem; ++v) {
2558 if (II[v].first == -1) {
2559 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2561 int Idx = II[v].first + II[v].second * I1Elem;
2562 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2566 Instruction *NewOp =
2567 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2568 getReplacementName(IBeforeJ ? I : J, true, o));
2569 NewOp->insertBefore(IBeforeJ ? J : I);
2574 Type *ArgType = ArgTypeL;
2575 if (numElemL < numElemH) {
2576 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2577 ArgTypeL, VArgType, IBeforeJ, 1)) {
2578 // This is another short-circuit case: we're combining a scalar into
2579 // a vector that is formed by an IE chain. We've just expanded the IE
2580 // chain, now insert the scalar and we're done.
2582 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2583 getReplacementName(IBeforeJ ? I : J, true, o));
2584 S->insertBefore(IBeforeJ ? J : I);
2586 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2587 ArgTypeH, IBeforeJ)) {
2588 // The two vector inputs to the shuffle must be the same length,
2589 // so extend the smaller vector to be the same length as the larger one.
2593 std::vector<Constant *> Mask(numElemH);
2595 for (; v < numElemL; ++v)
2596 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2597 for (; v < numElemH; ++v)
2598 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2600 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2601 ConstantVector::get(Mask),
2602 getReplacementName(IBeforeJ ? I : J,
2605 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2606 getReplacementName(IBeforeJ ? I : J,
2610 NLOp->insertBefore(IBeforeJ ? J : I);
2615 } else if (numElemL > numElemH) {
2616 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2617 ArgTypeH, VArgType, IBeforeJ)) {
2619 InsertElementInst::Create(LOp, HOp,
2620 ConstantInt::get(Type::getInt32Ty(Context),
2622 getReplacementName(IBeforeJ ? I : J,
2624 S->insertBefore(IBeforeJ ? J : I);
2626 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2627 ArgTypeL, IBeforeJ)) {
2630 std::vector<Constant *> Mask(numElemL);
2632 for (; v < numElemH; ++v)
2633 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2634 for (; v < numElemL; ++v)
2635 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2637 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2638 ConstantVector::get(Mask),
2639 getReplacementName(IBeforeJ ? I : J,
2642 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2643 getReplacementName(IBeforeJ ? I : J,
2647 NHOp->insertBefore(IBeforeJ ? J : I);
2652 if (ArgType->isVectorTy()) {
2653 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2654 std::vector<Constant*> Mask(numElem);
2655 for (unsigned v = 0; v < numElem; ++v) {
2657 // If the low vector was expanded, we need to skip the extra
2658 // undefined entries.
2659 if (v >= numElemL && numElemH > numElemL)
2660 Idx += (numElemH - numElemL);
2661 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2664 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2665 ConstantVector::get(Mask),
2666 getReplacementName(IBeforeJ ? I : J, true, o));
2667 BV->insertBefore(IBeforeJ ? J : I);
2671 Instruction *BV1 = InsertElementInst::Create(
2672 UndefValue::get(VArgType), LOp, CV0,
2673 getReplacementName(IBeforeJ ? I : J,
2675 BV1->insertBefore(IBeforeJ ? J : I);
2676 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2677 getReplacementName(IBeforeJ ? I : J,
2679 BV2->insertBefore(IBeforeJ ? J : I);
2683 // This function creates an array of values that will be used as the inputs
2684 // to the vector instruction that fuses I with J.
2685 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2686 Instruction *I, Instruction *J,
2687 SmallVector<Value *, 3> &ReplacedOperands,
2689 unsigned NumOperands = I->getNumOperands();
2691 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2692 // Iterate backward so that we look at the store pointer
2693 // first and know whether or not we need to flip the inputs.
2695 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2696 // This is the pointer for a load/store instruction.
2697 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2699 } else if (isa<CallInst>(I)) {
2700 Function *F = cast<CallInst>(I)->getCalledFunction();
2701 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2702 if (o == NumOperands-1) {
2703 BasicBlock &BB = *I->getParent();
2705 Module *M = BB.getParent()->getParent();
2706 Type *ArgTypeI = I->getType();
2707 Type *ArgTypeJ = J->getType();
2708 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2710 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2712 } else if (IID == Intrinsic::powi && o == 1) {
2713 // The second argument of powi is a single integer and we've already
2714 // checked that both arguments are equal. As a result, we just keep
2715 // I's second argument.
2716 ReplacedOperands[o] = I->getOperand(o);
2719 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2720 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2724 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2728 // This function creates two values that represent the outputs of the
2729 // original I and J instructions. These are generally vector shuffles
2730 // or extracts. In many cases, these will end up being unused and, thus,
2731 // eliminated by later passes.
2732 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2733 Instruction *J, Instruction *K,
2734 Instruction *&InsertionPt,
2735 Instruction *&K1, Instruction *&K2) {
2736 if (isa<StoreInst>(I)) {
2737 AA->replaceWithNewValue(I, K);
2738 AA->replaceWithNewValue(J, K);
2740 Type *IType = I->getType();
2741 Type *JType = J->getType();
2743 VectorType *VType = getVecTypeForPair(IType, JType);
2744 unsigned numElem = VType->getNumElements();
2746 unsigned numElemI, numElemJ;
2747 if (IType->isVectorTy())
2748 numElemI = cast<VectorType>(IType)->getNumElements();
2752 if (JType->isVectorTy())
2753 numElemJ = cast<VectorType>(JType)->getNumElements();
2757 if (IType->isVectorTy()) {
2758 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2759 for (unsigned v = 0; v < numElemI; ++v) {
2760 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2761 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2764 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2765 ConstantVector::get( Mask1),
2766 getReplacementName(K, false, 1));
2768 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2769 K1 = ExtractElementInst::Create(K, CV0,
2770 getReplacementName(K, false, 1));
2773 if (JType->isVectorTy()) {
2774 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2775 for (unsigned v = 0; v < numElemJ; ++v) {
2776 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2777 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2780 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2781 ConstantVector::get( Mask2),
2782 getReplacementName(K, false, 2));
2784 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2785 K2 = ExtractElementInst::Create(K, CV1,
2786 getReplacementName(K, false, 2));
2790 K2->insertAfter(K1);
2795 // Move all uses of the function I (including pairing-induced uses) after J.
2796 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2797 DenseSet<ValuePair> &LoadMoveSetPairs,
2798 Instruction *I, Instruction *J) {
2799 // Skip to the first instruction past I.
2800 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2802 DenseSet<Value *> Users;
2803 AliasSetTracker WriteSet(*AA);
2804 for (; cast<Instruction>(L) != J; ++L)
2805 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2807 assert(cast<Instruction>(L) == J &&
2808 "Tracking has not proceeded far enough to check for dependencies");
2809 // If J is now in the use set of I, then trackUsesOfI will return true
2810 // and we have a dependency cycle (and the fusing operation must abort).
2811 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2814 // Move all uses of the function I (including pairing-induced uses) after J.
2815 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2816 DenseSet<ValuePair> &LoadMoveSetPairs,
2817 Instruction *&InsertionPt,
2818 Instruction *I, Instruction *J) {
2819 // Skip to the first instruction past I.
2820 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2822 DenseSet<Value *> Users;
2823 AliasSetTracker WriteSet(*AA);
2824 for (; cast<Instruction>(L) != J;) {
2825 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2826 // Move this instruction
2827 Instruction *InstToMove = L; ++L;
2829 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2830 " to after " << *InsertionPt << "\n");
2831 InstToMove->removeFromParent();
2832 InstToMove->insertAfter(InsertionPt);
2833 InsertionPt = InstToMove;
2840 // Collect all load instruction that are in the move set of a given first
2841 // pair member. These loads depend on the first instruction, I, and so need
2842 // to be moved after J (the second instruction) when the pair is fused.
2843 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2844 DenseMap<Value *, Value *> &ChosenPairs,
2845 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2846 DenseSet<ValuePair> &LoadMoveSetPairs,
2848 // Skip to the first instruction past I.
2849 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2851 DenseSet<Value *> Users;
2852 AliasSetTracker WriteSet(*AA);
2854 // Note: We cannot end the loop when we reach J because J could be moved
2855 // farther down the use chain by another instruction pairing. Also, J
2856 // could be before I if this is an inverted input.
2857 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2858 if (trackUsesOfI(Users, WriteSet, I, L)) {
2859 if (L->mayReadFromMemory()) {
2860 LoadMoveSet[L].push_back(I);
2861 LoadMoveSetPairs.insert(ValuePair(L, I));
2867 // In cases where both load/stores and the computation of their pointers
2868 // are chosen for vectorization, we can end up in a situation where the
2869 // aliasing analysis starts returning different query results as the
2870 // process of fusing instruction pairs continues. Because the algorithm
2871 // relies on finding the same use trees here as were found earlier, we'll
2872 // need to precompute the necessary aliasing information here and then
2873 // manually update it during the fusion process.
2874 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2875 std::vector<Value *> &PairableInsts,
2876 DenseMap<Value *, Value *> &ChosenPairs,
2877 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2878 DenseSet<ValuePair> &LoadMoveSetPairs) {
2879 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2880 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2881 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2882 if (P == ChosenPairs.end()) continue;
2884 Instruction *I = cast<Instruction>(P->first);
2885 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2886 LoadMoveSetPairs, I);
2890 // When the first instruction in each pair is cloned, it will inherit its
2891 // parent's metadata. This metadata must be combined with that of the other
2892 // instruction in a safe way.
2893 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2894 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2895 K->getAllMetadataOtherThanDebugLoc(Metadata);
2896 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2897 unsigned Kind = Metadata[i].first;
2898 MDNode *JMD = J->getMetadata(Kind);
2899 MDNode *KMD = Metadata[i].second;
2903 K->setMetadata(Kind, 0); // Remove unknown metadata
2905 case LLVMContext::MD_tbaa:
2906 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2908 case LLVMContext::MD_fpmath:
2909 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2915 // This function fuses the chosen instruction pairs into vector instructions,
2916 // taking care preserve any needed scalar outputs and, then, it reorders the
2917 // remaining instructions as needed (users of the first member of the pair
2918 // need to be moved to after the location of the second member of the pair
2919 // because the vector instruction is inserted in the location of the pair's
2921 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2922 std::vector<Value *> &PairableInsts,
2923 DenseMap<Value *, Value *> &ChosenPairs,
2924 DenseSet<ValuePair> &FixedOrderPairs,
2925 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2926 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2927 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
2928 LLVMContext& Context = BB.getContext();
2930 // During the vectorization process, the order of the pairs to be fused
2931 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2932 // list. After a pair is fused, the flipped pair is removed from the list.
2933 DenseSet<ValuePair> FlippedPairs;
2934 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2935 E = ChosenPairs.end(); P != E; ++P)
2936 FlippedPairs.insert(ValuePair(P->second, P->first));
2937 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2938 E = FlippedPairs.end(); P != E; ++P)
2939 ChosenPairs.insert(*P);
2941 DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
2942 DenseSet<ValuePair> LoadMoveSetPairs;
2943 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2944 LoadMoveSet, LoadMoveSetPairs);
2946 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2948 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2949 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2950 if (P == ChosenPairs.end()) {
2955 if (getDepthFactor(P->first) == 0) {
2956 // These instructions are not really fused, but are tracked as though
2957 // they are. Any case in which it would be interesting to fuse them
2958 // will be taken care of by InstCombine.
2964 Instruction *I = cast<Instruction>(P->first),
2965 *J = cast<Instruction>(P->second);
2967 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2968 " <-> " << *J << "\n");
2970 // Remove the pair and flipped pair from the list.
2971 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2972 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2973 ChosenPairs.erase(FP);
2974 ChosenPairs.erase(P);
2976 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
2977 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2979 " aborted because of non-trivial dependency cycle\n");
2985 // If the pair must have the other order, then flip it.
2986 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2987 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2988 // This pair does not have a fixed order, and so we might want to
2989 // flip it if that will yield fewer shuffles. We count the number
2990 // of dependencies connected via swaps, and those directly connected,
2991 // and flip the order if the number of swaps is greater.
2992 bool OrigOrder = true;
2993 DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
2994 ConnectedPairDeps.find(ValuePair(I, J));
2995 if (IJ == ConnectedPairDeps.end()) {
2996 IJ = ConnectedPairDeps.find(ValuePair(J, I));
3000 if (IJ != ConnectedPairDeps.end()) {
3001 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3002 for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3003 TE = IJ->second.end(); T != TE; ++T) {
3004 VPPair Q(IJ->first, *T);
3005 DenseMap<VPPair, unsigned>::iterator R =
3006 PairConnectionTypes.find(VPPair(Q.second, Q.first));
3007 assert(R != PairConnectionTypes.end() &&
3008 "Cannot find pair connection type");
3009 if (R->second == PairConnectionDirect)
3011 else if (R->second == PairConnectionSwap)
3016 std::swap(NumDepsDirect, NumDepsSwap);
3018 if (NumDepsSwap > NumDepsDirect) {
3019 FlipPairOrder = true;
3020 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3021 " <-> " << *J << "\n");
3026 Instruction *L = I, *H = J;
3030 // If the pair being fused uses the opposite order from that in the pair
3031 // connection map, then we need to flip the types.
3032 DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3033 ConnectedPairs.find(ValuePair(H, L));
3034 if (HL != ConnectedPairs.end())
3035 for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3036 TE = HL->second.end(); T != TE; ++T) {
3037 VPPair Q(HL->first, *T);
3038 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3039 assert(R != PairConnectionTypes.end() &&
3040 "Cannot find pair connection type");
3041 if (R->second == PairConnectionDirect)
3042 R->second = PairConnectionSwap;
3043 else if (R->second == PairConnectionSwap)
3044 R->second = PairConnectionDirect;
3047 bool LBeforeH = !FlipPairOrder;
3048 unsigned NumOperands = I->getNumOperands();
3049 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3050 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3053 // Make a copy of the original operation, change its type to the vector
3054 // type and replace its operands with the vector operands.
3055 Instruction *K = L->clone();
3058 else if (H->hasName())
3061 if (!isa<StoreInst>(K))
3062 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3064 combineMetadata(K, H);
3065 K->intersectOptionalDataWith(H);
3067 for (unsigned o = 0; o < NumOperands; ++o)
3068 K->setOperand(o, ReplacedOperands[o]);
3072 // Instruction insertion point:
3073 Instruction *InsertionPt = K;
3074 Instruction *K1 = 0, *K2 = 0;
3075 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3077 // The use tree of the first original instruction must be moved to after
3078 // the location of the second instruction. The entire use tree of the
3079 // first instruction is disjoint from the input tree of the second
3080 // (by definition), and so commutes with it.
3082 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3084 if (!isa<StoreInst>(I)) {
3085 L->replaceAllUsesWith(K1);
3086 H->replaceAllUsesWith(K2);
3087 AA->replaceWithNewValue(L, K1);
3088 AA->replaceWithNewValue(H, K2);
3091 // Instructions that may read from memory may be in the load move set.
3092 // Once an instruction is fused, we no longer need its move set, and so
3093 // the values of the map never need to be updated. However, when a load
3094 // is fused, we need to merge the entries from both instructions in the
3095 // pair in case those instructions were in the move set of some other
3096 // yet-to-be-fused pair. The loads in question are the keys of the map.
3097 if (I->mayReadFromMemory()) {
3098 std::vector<ValuePair> NewSetMembers;
3099 DenseMap<Value *, std::vector<Value *> >::iterator II =
3100 LoadMoveSet.find(I);
3101 if (II != LoadMoveSet.end())
3102 for (std::vector<Value *>::iterator N = II->second.begin(),
3103 NE = II->second.end(); N != NE; ++N)
3104 NewSetMembers.push_back(ValuePair(K, *N));
3105 DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3106 LoadMoveSet.find(J);
3107 if (JJ != LoadMoveSet.end())
3108 for (std::vector<Value *>::iterator N = JJ->second.begin(),
3109 NE = JJ->second.end(); N != NE; ++N)
3110 NewSetMembers.push_back(ValuePair(K, *N));
3111 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3112 AE = NewSetMembers.end(); A != AE; ++A) {
3113 LoadMoveSet[A->first].push_back(A->second);
3114 LoadMoveSetPairs.insert(*A);
3118 // Before removing I, set the iterator to the next instruction.
3119 PI = llvm::next(BasicBlock::iterator(I));
3120 if (cast<Instruction>(PI) == J)
3125 I->eraseFromParent();
3126 J->eraseFromParent();
3128 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3132 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3136 char BBVectorize::ID = 0;
3137 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3138 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3139 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3140 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3141 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3142 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3143 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3145 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3146 return new BBVectorize(C);
3150 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3151 BBVectorize BBVectorizer(P, C);
3152 return BBVectorizer.vectorizeBB(BB);
3155 //===----------------------------------------------------------------------===//
3156 VectorizeConfig::VectorizeConfig() {
3157 VectorBits = ::VectorBits;
3158 VectorizeBools = !::NoBools;
3159 VectorizeInts = !::NoInts;
3160 VectorizeFloats = !::NoFloats;
3161 VectorizePointers = !::NoPointers;
3162 VectorizeCasts = !::NoCasts;
3163 VectorizeMath = !::NoMath;
3164 VectorizeFMA = !::NoFMA;
3165 VectorizeSelect = !::NoSelect;
3166 VectorizeCmp = !::NoCmp;
3167 VectorizeGEP = !::NoGEP;
3168 VectorizeMemOps = !::NoMemOps;
3169 AlignedOnly = ::AlignedOnly;
3170 ReqChainDepth= ::ReqChainDepth;
3171 SearchLimit = ::SearchLimit;
3172 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3173 SplatBreaksChain = ::SplatBreaksChain;
3174 MaxInsts = ::MaxInsts;
3175 MaxPairs = ::MaxPairs;
3176 MaxIter = ::MaxIter;
3177 Pow2LenOnly = ::Pow2LenOnly;
3178 NoMemOpBoost = ::NoMemOpBoost;
3179 FastDep = ::FastDep;