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 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/ValueHandle.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Utils/Local.h"
52 #define DEBUG_TYPE BBV_NAME
55 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
56 cl::Hidden, cl::desc("Ignore target information"));
58 static cl::opt<unsigned>
59 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
60 cl::desc("The required chain depth for vectorization"));
63 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
64 cl::Hidden, cl::desc("Use the chain depth requirement with"
65 " target information"));
67 static cl::opt<unsigned>
68 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
69 cl::desc("The maximum search distance for instruction pairs"));
72 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
73 cl::desc("Replicating one element to a pair breaks the chain"));
75 static cl::opt<unsigned>
76 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
77 cl::desc("The size of the native vector registers"));
79 static cl::opt<unsigned>
80 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
81 cl::desc("The maximum number of pairing iterations"));
84 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
85 cl::desc("Don't try to form non-2^n-length vectors"));
87 static cl::opt<unsigned>
88 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
89 cl::desc("The maximum number of pairable instructions per group"));
91 static cl::opt<unsigned>
92 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
93 cl::desc("The maximum number of candidate instruction pairs per group"));
95 static cl::opt<unsigned>
96 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
97 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
98 " a full cycle check"));
101 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
102 cl::desc("Don't try to vectorize boolean (i1) values"));
105 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
106 cl::desc("Don't try to vectorize integer values"));
109 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
110 cl::desc("Don't try to vectorize floating-point values"));
112 // FIXME: This should default to false once pointer vector support works.
114 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
115 cl::desc("Don't try to vectorize pointer values"));
118 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
119 cl::desc("Don't try to vectorize casting (conversion) operations"));
122 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
123 cl::desc("Don't try to vectorize floating-point math intrinsics"));
126 NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden,
127 cl::desc("Don't try to vectorize BitManipulation intrinsics"));
130 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
131 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
134 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
135 cl::desc("Don't try to vectorize select instructions"));
138 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
139 cl::desc("Don't try to vectorize comparison instructions"));
142 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
143 cl::desc("Don't try to vectorize getelementptr instructions"));
146 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
147 cl::desc("Don't try to vectorize loads and stores"));
150 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
151 cl::desc("Only generate aligned loads and stores"));
154 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
155 cl::init(false), cl::Hidden,
156 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
159 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
160 cl::desc("Use a fast instruction dependency analysis"));
164 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
165 cl::init(false), cl::Hidden,
166 cl::desc("When debugging is enabled, output information on the"
167 " instruction-examination process"));
169 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
170 cl::init(false), cl::Hidden,
171 cl::desc("When debugging is enabled, output information on the"
172 " candidate-selection process"));
174 DebugPairSelection("bb-vectorize-debug-pair-selection",
175 cl::init(false), cl::Hidden,
176 cl::desc("When debugging is enabled, output information on the"
177 " pair-selection process"));
179 DebugCycleCheck("bb-vectorize-debug-cycle-check",
180 cl::init(false), cl::Hidden,
181 cl::desc("When debugging is enabled, output information on the"
182 " cycle-checking process"));
185 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
186 cl::init(false), cl::Hidden,
187 cl::desc("When debugging is enabled, dump the basic block after"
188 " every pair is fused"));
191 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
194 struct BBVectorize : public BasicBlockPass {
195 static char ID; // Pass identification, replacement for typeid
197 const VectorizeConfig Config;
199 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
200 : BasicBlockPass(ID), Config(C) {
201 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
204 BBVectorize(Pass *P, const VectorizeConfig &C)
205 : BasicBlockPass(ID), Config(C) {
206 AA = &P->getAnalysis<AliasAnalysis>();
207 DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
208 SE = &P->getAnalysis<ScalarEvolution>();
209 DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
210 DL = DLP ? &DLP->getDataLayout() : 0;
211 TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
214 typedef std::pair<Value *, Value *> ValuePair;
215 typedef std::pair<ValuePair, int> ValuePairWithCost;
216 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
217 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
218 typedef std::pair<VPPair, unsigned> VPPairWithType;
223 const DataLayout *DL;
224 const TargetTransformInfo *TTI;
226 // FIXME: const correct?
228 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
230 bool getCandidatePairs(BasicBlock &BB,
231 BasicBlock::iterator &Start,
232 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
233 DenseSet<ValuePair> &FixedOrderPairs,
234 DenseMap<ValuePair, int> &CandidatePairCostSavings,
235 std::vector<Value *> &PairableInsts, bool NonPow2Len);
237 // FIXME: The current implementation does not account for pairs that
238 // are connected in multiple ways. For example:
239 // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
240 enum PairConnectionType {
241 PairConnectionDirect,
246 void computeConnectedPairs(
247 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
248 DenseSet<ValuePair> &CandidatePairsSet,
249 std::vector<Value *> &PairableInsts,
250 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
251 DenseMap<VPPair, unsigned> &PairConnectionTypes);
253 void buildDepMap(BasicBlock &BB,
254 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
255 std::vector<Value *> &PairableInsts,
256 DenseSet<ValuePair> &PairableInstUsers);
258 void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
259 DenseSet<ValuePair> &CandidatePairsSet,
260 DenseMap<ValuePair, int> &CandidatePairCostSavings,
261 std::vector<Value *> &PairableInsts,
262 DenseSet<ValuePair> &FixedOrderPairs,
263 DenseMap<VPPair, unsigned> &PairConnectionTypes,
264 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
265 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
266 DenseSet<ValuePair> &PairableInstUsers,
267 DenseMap<Value *, Value *>& ChosenPairs);
269 void fuseChosenPairs(BasicBlock &BB,
270 std::vector<Value *> &PairableInsts,
271 DenseMap<Value *, Value *>& ChosenPairs,
272 DenseSet<ValuePair> &FixedOrderPairs,
273 DenseMap<VPPair, unsigned> &PairConnectionTypes,
274 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
275 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
278 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
280 bool areInstsCompatible(Instruction *I, Instruction *J,
281 bool IsSimpleLoadStore, bool NonPow2Len,
282 int &CostSavings, int &FixedOrder);
284 bool trackUsesOfI(DenseSet<Value *> &Users,
285 AliasSetTracker &WriteSet, Instruction *I,
286 Instruction *J, bool UpdateUsers = true,
287 DenseSet<ValuePair> *LoadMoveSetPairs = 0);
289 void computePairsConnectedTo(
290 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
291 DenseSet<ValuePair> &CandidatePairsSet,
292 std::vector<Value *> &PairableInsts,
293 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
294 DenseMap<VPPair, unsigned> &PairConnectionTypes,
297 bool pairsConflict(ValuePair P, ValuePair Q,
298 DenseSet<ValuePair> &PairableInstUsers,
299 DenseMap<ValuePair, std::vector<ValuePair> >
300 *PairableInstUserMap = 0,
301 DenseSet<VPPair> *PairableInstUserPairSet = 0);
303 bool pairWillFormCycle(ValuePair P,
304 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
305 DenseSet<ValuePair> &CurrentPairs);
308 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
309 std::vector<Value *> &PairableInsts,
310 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
311 DenseSet<ValuePair> &PairableInstUsers,
312 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
313 DenseSet<VPPair> &PairableInstUserPairSet,
314 DenseMap<Value *, Value *> &ChosenPairs,
315 DenseMap<ValuePair, size_t> &DAG,
316 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
319 void buildInitialDAGFor(
320 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
321 DenseSet<ValuePair> &CandidatePairsSet,
322 std::vector<Value *> &PairableInsts,
323 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
324 DenseSet<ValuePair> &PairableInstUsers,
325 DenseMap<Value *, Value *> &ChosenPairs,
326 DenseMap<ValuePair, size_t> &DAG, ValuePair J);
329 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
330 DenseSet<ValuePair> &CandidatePairsSet,
331 DenseMap<ValuePair, int> &CandidatePairCostSavings,
332 std::vector<Value *> &PairableInsts,
333 DenseSet<ValuePair> &FixedOrderPairs,
334 DenseMap<VPPair, unsigned> &PairConnectionTypes,
335 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
336 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
337 DenseSet<ValuePair> &PairableInstUsers,
338 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
339 DenseSet<VPPair> &PairableInstUserPairSet,
340 DenseMap<Value *, Value *> &ChosenPairs,
341 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
342 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
345 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
346 Instruction *J, unsigned o);
348 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
349 unsigned MaskOffset, unsigned NumInElem,
350 unsigned NumInElem1, unsigned IdxOffset,
351 std::vector<Constant*> &Mask);
353 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
356 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
357 unsigned o, Value *&LOp, unsigned numElemL,
358 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
359 unsigned IdxOff = 0);
361 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
362 Instruction *J, unsigned o, bool IBeforeJ);
364 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
365 Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
368 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
369 Instruction *J, Instruction *K,
370 Instruction *&InsertionPt, Instruction *&K1,
373 void collectPairLoadMoveSet(BasicBlock &BB,
374 DenseMap<Value *, Value *> &ChosenPairs,
375 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
376 DenseSet<ValuePair> &LoadMoveSetPairs,
379 void collectLoadMoveSet(BasicBlock &BB,
380 std::vector<Value *> &PairableInsts,
381 DenseMap<Value *, Value *> &ChosenPairs,
382 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
383 DenseSet<ValuePair> &LoadMoveSetPairs);
385 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
386 DenseSet<ValuePair> &LoadMoveSetPairs,
387 Instruction *I, Instruction *J);
389 void moveUsesOfIAfterJ(BasicBlock &BB,
390 DenseSet<ValuePair> &LoadMoveSetPairs,
391 Instruction *&InsertionPt,
392 Instruction *I, Instruction *J);
394 void combineMetadata(Instruction *K, const Instruction *J);
396 bool vectorizeBB(BasicBlock &BB) {
397 if (skipOptnoneFunction(BB))
399 if (!DT->isReachableFromEntry(&BB)) {
400 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
401 " in " << BB.getParent()->getName() << "\n");
405 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
407 bool changed = false;
408 // Iterate a sufficient number of times to merge types of size 1 bit,
409 // then 2 bits, then 4, etc. up to half of the target vector width of the
410 // target vector register.
413 (TTI || v <= Config.VectorBits) &&
414 (!Config.MaxIter || n <= Config.MaxIter);
416 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
417 " for " << BB.getName() << " in " <<
418 BB.getParent()->getName() << "...\n");
419 if (vectorizePairs(BB))
425 if (changed && !Pow2LenOnly) {
427 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
428 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
429 n << " for " << BB.getName() << " in " <<
430 BB.getParent()->getName() << "...\n");
431 if (!vectorizePairs(BB, true)) break;
435 DEBUG(dbgs() << "BBV: done!\n");
439 bool runOnBasicBlock(BasicBlock &BB) override {
440 // OptimizeNone check deferred to vectorizeBB().
442 AA = &getAnalysis<AliasAnalysis>();
443 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
444 SE = &getAnalysis<ScalarEvolution>();
445 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
446 DL = DLP ? &DLP->getDataLayout() : 0;
447 TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
449 return vectorizeBB(BB);
452 void getAnalysisUsage(AnalysisUsage &AU) const override {
453 BasicBlockPass::getAnalysisUsage(AU);
454 AU.addRequired<AliasAnalysis>();
455 AU.addRequired<DominatorTreeWrapperPass>();
456 AU.addRequired<ScalarEvolution>();
457 AU.addRequired<TargetTransformInfo>();
458 AU.addPreserved<AliasAnalysis>();
459 AU.addPreserved<DominatorTreeWrapperPass>();
460 AU.addPreserved<ScalarEvolution>();
461 AU.setPreservesCFG();
464 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
465 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
466 "Cannot form vector from incompatible scalar types");
467 Type *STy = ElemTy->getScalarType();
470 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
471 numElem = VTy->getNumElements();
476 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
477 numElem += VTy->getNumElements();
482 return VectorType::get(STy, numElem);
485 static inline void getInstructionTypes(Instruction *I,
486 Type *&T1, Type *&T2) {
487 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
488 // For stores, it is the value type, not the pointer type that matters
489 // because the value is what will come from a vector register.
491 Value *IVal = SI->getValueOperand();
492 T1 = IVal->getType();
497 if (CastInst *CI = dyn_cast<CastInst>(I))
502 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
503 T2 = SI->getCondition()->getType();
504 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
505 T2 = SI->getOperand(0)->getType();
506 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
507 T2 = CI->getOperand(0)->getType();
511 // Returns the weight associated with the provided value. A chain of
512 // candidate pairs has a length given by the sum of the weights of its
513 // members (one weight per pair; the weight of each member of the pair
514 // is assumed to be the same). This length is then compared to the
515 // chain-length threshold to determine if a given chain is significant
516 // enough to be vectorized. The length is also used in comparing
517 // candidate chains where longer chains are considered to be better.
518 // Note: when this function returns 0, the resulting instructions are
519 // not actually fused.
520 inline size_t getDepthFactor(Value *V) {
521 // InsertElement and ExtractElement have a depth factor of zero. This is
522 // for two reasons: First, they cannot be usefully fused. Second, because
523 // the pass generates a lot of these, they can confuse the simple metric
524 // used to compare the dags in the next iteration. Thus, giving them a
525 // weight of zero allows the pass to essentially ignore them in
526 // subsequent iterations when looking for vectorization opportunities
527 // while still tracking dependency chains that flow through those
529 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
532 // Give a load or store half of the required depth so that load/store
533 // pairs will vectorize.
534 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
535 return Config.ReqChainDepth/2;
540 // Returns the cost of the provided instruction using TTI.
541 // This does not handle loads and stores.
542 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
543 TargetTransformInfo::OperandValueKind Op1VK =
544 TargetTransformInfo::OK_AnyValue,
545 TargetTransformInfo::OperandValueKind Op2VK =
546 TargetTransformInfo::OK_AnyValue) {
549 case Instruction::GetElementPtr:
550 // We mark this instruction as zero-cost because scalar GEPs are usually
551 // lowered to the instruction addressing mode. At the moment we don't
552 // generate vector GEPs.
554 case Instruction::Br:
555 return TTI->getCFInstrCost(Opcode);
556 case Instruction::PHI:
558 case Instruction::Add:
559 case Instruction::FAdd:
560 case Instruction::Sub:
561 case Instruction::FSub:
562 case Instruction::Mul:
563 case Instruction::FMul:
564 case Instruction::UDiv:
565 case Instruction::SDiv:
566 case Instruction::FDiv:
567 case Instruction::URem:
568 case Instruction::SRem:
569 case Instruction::FRem:
570 case Instruction::Shl:
571 case Instruction::LShr:
572 case Instruction::AShr:
573 case Instruction::And:
574 case Instruction::Or:
575 case Instruction::Xor:
576 return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
577 case Instruction::Select:
578 case Instruction::ICmp:
579 case Instruction::FCmp:
580 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
581 case Instruction::ZExt:
582 case Instruction::SExt:
583 case Instruction::FPToUI:
584 case Instruction::FPToSI:
585 case Instruction::FPExt:
586 case Instruction::PtrToInt:
587 case Instruction::IntToPtr:
588 case Instruction::SIToFP:
589 case Instruction::UIToFP:
590 case Instruction::Trunc:
591 case Instruction::FPTrunc:
592 case Instruction::BitCast:
593 case Instruction::ShuffleVector:
594 return TTI->getCastInstrCost(Opcode, T1, T2);
600 // This determines the relative offset of two loads or stores, returning
601 // true if the offset could be determined to be some constant value.
602 // For example, if OffsetInElmts == 1, then J accesses the memory directly
603 // after I; if OffsetInElmts == -1 then I accesses the memory
605 bool getPairPtrInfo(Instruction *I, Instruction *J,
606 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
607 unsigned &IAddressSpace, unsigned &JAddressSpace,
608 int64_t &OffsetInElmts, bool ComputeOffset = true) {
610 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
611 LoadInst *LJ = cast<LoadInst>(J);
612 IPtr = LI->getPointerOperand();
613 JPtr = LJ->getPointerOperand();
614 IAlignment = LI->getAlignment();
615 JAlignment = LJ->getAlignment();
616 IAddressSpace = LI->getPointerAddressSpace();
617 JAddressSpace = LJ->getPointerAddressSpace();
619 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
620 IPtr = SI->getPointerOperand();
621 JPtr = SJ->getPointerOperand();
622 IAlignment = SI->getAlignment();
623 JAlignment = SJ->getAlignment();
624 IAddressSpace = SI->getPointerAddressSpace();
625 JAddressSpace = SJ->getPointerAddressSpace();
631 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
632 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
634 // If this is a trivial offset, then we'll get something like
635 // 1*sizeof(type). With target data, which we need anyway, this will get
636 // constant folded into a number.
637 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
638 if (const SCEVConstant *ConstOffSCEV =
639 dyn_cast<SCEVConstant>(OffsetSCEV)) {
640 ConstantInt *IntOff = ConstOffSCEV->getValue();
641 int64_t Offset = IntOff->getSExtValue();
643 Type *VTy = IPtr->getType()->getPointerElementType();
644 int64_t VTyTSS = (int64_t) DL->getTypeStoreSize(VTy);
646 Type *VTy2 = JPtr->getType()->getPointerElementType();
647 if (VTy != VTy2 && Offset < 0) {
648 int64_t VTy2TSS = (int64_t) DL->getTypeStoreSize(VTy2);
649 OffsetInElmts = Offset/VTy2TSS;
650 return (abs64(Offset) % VTy2TSS) == 0;
653 OffsetInElmts = Offset/VTyTSS;
654 return (abs64(Offset) % VTyTSS) == 0;
660 // Returns true if the provided CallInst represents an intrinsic that can
662 bool isVectorizableIntrinsic(CallInst* I) {
663 Function *F = I->getCalledFunction();
664 if (!F) return false;
666 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
667 if (!IID) return false;
672 case Intrinsic::sqrt:
673 case Intrinsic::powi:
677 case Intrinsic::log2:
678 case Intrinsic::log10:
680 case Intrinsic::exp2:
682 case Intrinsic::round:
683 case Intrinsic::copysign:
684 case Intrinsic::ceil:
685 case Intrinsic::nearbyint:
686 case Intrinsic::rint:
687 case Intrinsic::trunc:
688 case Intrinsic::floor:
689 case Intrinsic::fabs:
690 return Config.VectorizeMath;
691 case Intrinsic::bswap:
692 case Intrinsic::ctpop:
693 case Intrinsic::ctlz:
694 case Intrinsic::cttz:
695 return Config.VectorizeBitManipulations;
697 case Intrinsic::fmuladd:
698 return Config.VectorizeFMA;
702 bool isPureIEChain(InsertElementInst *IE) {
703 InsertElementInst *IENext = IE;
705 if (!isa<UndefValue>(IENext->getOperand(0)) &&
706 !isa<InsertElementInst>(IENext->getOperand(0))) {
710 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
716 // This function implements one vectorization iteration on the provided
717 // basic block. It returns true if the block is changed.
718 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
720 BasicBlock::iterator Start = BB.getFirstInsertionPt();
722 std::vector<Value *> AllPairableInsts;
723 DenseMap<Value *, Value *> AllChosenPairs;
724 DenseSet<ValuePair> AllFixedOrderPairs;
725 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
726 DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
727 AllConnectedPairDeps;
730 std::vector<Value *> PairableInsts;
731 DenseMap<Value *, std::vector<Value *> > CandidatePairs;
732 DenseSet<ValuePair> FixedOrderPairs;
733 DenseMap<ValuePair, int> CandidatePairCostSavings;
734 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
736 CandidatePairCostSavings,
737 PairableInsts, NonPow2Len);
738 if (PairableInsts.empty()) continue;
740 // Build the candidate pair set for faster lookups.
741 DenseSet<ValuePair> CandidatePairsSet;
742 for (DenseMap<Value *, std::vector<Value *> >::iterator I =
743 CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
744 for (std::vector<Value *>::iterator J = I->second.begin(),
745 JE = I->second.end(); J != JE; ++J)
746 CandidatePairsSet.insert(ValuePair(I->first, *J));
748 // Now we have a map of all of the pairable instructions and we need to
749 // select the best possible pairing. A good pairing is one such that the
750 // users of the pair are also paired. This defines a (directed) forest
751 // over the pairs such that two pairs are connected iff the second pair
754 // Note that it only matters that both members of the second pair use some
755 // element of the first pair (to allow for splatting).
757 DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
759 DenseMap<VPPair, unsigned> PairConnectionTypes;
760 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
761 PairableInsts, ConnectedPairs, PairConnectionTypes);
762 if (ConnectedPairs.empty()) continue;
764 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
765 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
767 for (std::vector<ValuePair>::iterator J = I->second.begin(),
768 JE = I->second.end(); J != JE; ++J)
769 ConnectedPairDeps[*J].push_back(I->first);
771 // Build the pairable-instruction dependency map
772 DenseSet<ValuePair> PairableInstUsers;
773 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
775 // There is now a graph of the connected pairs. For each variable, pick
776 // the pairing with the largest dag meeting the depth requirement on at
777 // least one branch. Then select all pairings that are part of that dag
778 // and remove them from the list of available pairings and pairable
781 DenseMap<Value *, Value *> ChosenPairs;
782 choosePairs(CandidatePairs, CandidatePairsSet,
783 CandidatePairCostSavings,
784 PairableInsts, FixedOrderPairs, PairConnectionTypes,
785 ConnectedPairs, ConnectedPairDeps,
786 PairableInstUsers, ChosenPairs);
788 if (ChosenPairs.empty()) continue;
789 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
790 PairableInsts.end());
791 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
793 // Only for the chosen pairs, propagate information on fixed-order pairs,
794 // pair connections, and their types to the data structures used by the
795 // pair fusion procedures.
796 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
797 IE = ChosenPairs.end(); I != IE; ++I) {
798 if (FixedOrderPairs.count(*I))
799 AllFixedOrderPairs.insert(*I);
800 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
801 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
803 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
805 DenseMap<VPPair, unsigned>::iterator K =
806 PairConnectionTypes.find(VPPair(*I, *J));
807 if (K != PairConnectionTypes.end()) {
808 AllPairConnectionTypes.insert(*K);
810 K = PairConnectionTypes.find(VPPair(*J, *I));
811 if (K != PairConnectionTypes.end())
812 AllPairConnectionTypes.insert(*K);
817 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
818 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
820 for (std::vector<ValuePair>::iterator J = I->second.begin(),
821 JE = I->second.end(); J != JE; ++J)
822 if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
823 AllConnectedPairs[I->first].push_back(*J);
824 AllConnectedPairDeps[*J].push_back(I->first);
826 } while (ShouldContinue);
828 if (AllChosenPairs.empty()) return false;
829 NumFusedOps += AllChosenPairs.size();
831 // A set of pairs has now been selected. It is now necessary to replace the
832 // paired instructions with vector instructions. For this procedure each
833 // operand must be replaced with a vector operand. This vector is formed
834 // by using build_vector on the old operands. The replaced values are then
835 // replaced with a vector_extract on the result. Subsequent optimization
836 // passes should coalesce the build/extract combinations.
838 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
839 AllPairConnectionTypes,
840 AllConnectedPairs, AllConnectedPairDeps);
842 // It is important to cleanup here so that future iterations of this
843 // function have less work to do.
844 (void) SimplifyInstructionsInBlock(&BB, DL, AA->getTargetLibraryInfo());
848 // This function returns true if the provided instruction is capable of being
849 // fused into a vector instruction. This determination is based only on the
850 // type and other attributes of the instruction.
851 bool BBVectorize::isInstVectorizable(Instruction *I,
852 bool &IsSimpleLoadStore) {
853 IsSimpleLoadStore = false;
855 if (CallInst *C = dyn_cast<CallInst>(I)) {
856 if (!isVectorizableIntrinsic(C))
858 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
859 // Vectorize simple loads if possbile:
860 IsSimpleLoadStore = L->isSimple();
861 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
863 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
864 // Vectorize simple stores if possbile:
865 IsSimpleLoadStore = S->isSimple();
866 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
868 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
869 // We can vectorize casts, but not casts of pointer types, etc.
870 if (!Config.VectorizeCasts)
873 Type *SrcTy = C->getSrcTy();
874 if (!SrcTy->isSingleValueType())
877 Type *DestTy = C->getDestTy();
878 if (!DestTy->isSingleValueType())
880 } else if (isa<SelectInst>(I)) {
881 if (!Config.VectorizeSelect)
883 } else if (isa<CmpInst>(I)) {
884 if (!Config.VectorizeCmp)
886 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
887 if (!Config.VectorizeGEP)
890 // Currently, vector GEPs exist only with one index.
891 if (G->getNumIndices() != 1)
893 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
894 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
898 // We can't vectorize memory operations without target data
899 if (DL == 0 && IsSimpleLoadStore)
903 getInstructionTypes(I, T1, T2);
905 // Not every type can be vectorized...
906 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
907 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
910 if (T1->getScalarSizeInBits() == 1) {
911 if (!Config.VectorizeBools)
914 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
918 if (T2->getScalarSizeInBits() == 1) {
919 if (!Config.VectorizeBools)
922 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
926 if (!Config.VectorizeFloats
927 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
930 // Don't vectorize target-specific types.
931 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
933 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
936 if ((!Config.VectorizePointers || DL == 0) &&
937 (T1->getScalarType()->isPointerTy() ||
938 T2->getScalarType()->isPointerTy()))
941 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
942 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
948 // This function returns true if the two provided instructions are compatible
949 // (meaning that they can be fused into a vector instruction). This assumes
950 // that I has already been determined to be vectorizable and that J is not
951 // in the use dag of I.
952 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
953 bool IsSimpleLoadStore, bool NonPow2Len,
954 int &CostSavings, int &FixedOrder) {
955 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
956 " <-> " << *J << "\n");
961 // Loads and stores can be merged if they have different alignments,
962 // but are otherwise the same.
963 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
964 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
967 Type *IT1, *IT2, *JT1, *JT2;
968 getInstructionTypes(I, IT1, IT2);
969 getInstructionTypes(J, JT1, JT2);
970 unsigned MaxTypeBits = std::max(
971 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
972 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
973 if (!TTI && MaxTypeBits > Config.VectorBits)
976 // FIXME: handle addsub-type operations!
978 if (IsSimpleLoadStore) {
980 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
981 int64_t OffsetInElmts = 0;
982 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
983 IAddressSpace, JAddressSpace,
984 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
985 FixedOrder = (int) OffsetInElmts;
986 unsigned BottomAlignment = IAlignment;
987 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
989 Type *aTypeI = isa<StoreInst>(I) ?
990 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
991 Type *aTypeJ = isa<StoreInst>(J) ?
992 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
993 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
995 if (Config.AlignedOnly) {
996 // An aligned load or store is possible only if the instruction
997 // with the lower offset has an alignment suitable for the
1000 unsigned VecAlignment = DL->getPrefTypeAlignment(VType);
1001 if (BottomAlignment < VecAlignment)
1006 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
1007 IAlignment, IAddressSpace);
1008 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
1009 JAlignment, JAddressSpace);
1010 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
1014 ICost += TTI->getAddressComputationCost(aTypeI);
1015 JCost += TTI->getAddressComputationCost(aTypeJ);
1016 VCost += TTI->getAddressComputationCost(VType);
1018 if (VCost > ICost + JCost)
1021 // We don't want to fuse to a type that will be split, even
1022 // if the two input types will also be split and there is no other
1024 unsigned VParts = TTI->getNumberOfParts(VType);
1027 else if (!VParts && VCost == ICost + JCost)
1030 CostSavings = ICost + JCost - VCost;
1036 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1037 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1038 Type *VT1 = getVecTypeForPair(IT1, JT1),
1039 *VT2 = getVecTypeForPair(IT2, JT2);
1040 TargetTransformInfo::OperandValueKind Op1VK =
1041 TargetTransformInfo::OK_AnyValue;
1042 TargetTransformInfo::OperandValueKind Op2VK =
1043 TargetTransformInfo::OK_AnyValue;
1045 // On some targets (example X86) the cost of a vector shift may vary
1046 // depending on whether the second operand is a Uniform or
1047 // NonUniform Constant.
1048 switch (I->getOpcode()) {
1050 case Instruction::Shl:
1051 case Instruction::LShr:
1052 case Instruction::AShr:
1054 // If both I and J are scalar shifts by constant, then the
1055 // merged vector shift count would be either a constant splat value
1056 // or a non-uniform vector of constants.
1057 if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
1058 if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
1059 Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
1060 TargetTransformInfo::OK_NonUniformConstantValue;
1062 // Check for a splat of a constant or for a non uniform vector
1064 Value *IOp = I->getOperand(1);
1065 Value *JOp = J->getOperand(1);
1066 if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
1067 (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
1068 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1069 Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
1070 if (SplatValue != NULL &&
1071 SplatValue == cast<Constant>(JOp)->getSplatValue())
1072 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
1077 // Note that this procedure is incorrect for insert and extract element
1078 // instructions (because combining these often results in a shuffle),
1079 // but this cost is ignored (because insert and extract element
1080 // instructions are assigned a zero depth factor and are not really
1081 // fused in general).
1082 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
1084 if (VCost > ICost + JCost)
1087 // We don't want to fuse to a type that will be split, even
1088 // if the two input types will also be split and there is no other
1090 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1091 VParts2 = TTI->getNumberOfParts(VT2);
1092 if (VParts1 > 1 || VParts2 > 1)
1094 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1097 CostSavings = ICost + JCost - VCost;
1100 // The powi,ctlz,cttz intrinsics are special because only the first
1101 // argument is vectorized, the second arguments must be equal.
1102 CallInst *CI = dyn_cast<CallInst>(I);
1104 if (CI && (FI = CI->getCalledFunction())) {
1105 Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1106 if (IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1107 IID == Intrinsic::cttz) {
1108 Value *A1I = CI->getArgOperand(1),
1109 *A1J = cast<CallInst>(J)->getArgOperand(1);
1110 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1111 *A1JSCEV = SE->getSCEV(A1J);
1112 return (A1ISCEV == A1JSCEV);
1116 SmallVector<Type*, 4> Tys;
1117 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1118 Tys.push_back(CI->getArgOperand(i)->getType());
1119 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1122 CallInst *CJ = cast<CallInst>(J);
1123 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1124 Tys.push_back(CJ->getArgOperand(i)->getType());
1125 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1128 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1129 "Intrinsic argument counts differ");
1130 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1131 if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1132 IID == Intrinsic::cttz) && i == 1)
1133 Tys.push_back(CI->getArgOperand(i)->getType());
1135 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1136 CJ->getArgOperand(i)->getType()));
1139 Type *RetTy = getVecTypeForPair(IT1, JT1);
1140 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1142 if (VCost > ICost + JCost)
1145 // We don't want to fuse to a type that will be split, even
1146 // if the two input types will also be split and there is no other
1148 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1151 else if (!RetParts && VCost == ICost + JCost)
1154 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1155 if (!Tys[i]->isVectorTy())
1158 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1161 else if (!NumParts && VCost == ICost + JCost)
1165 CostSavings = ICost + JCost - VCost;
1172 // Figure out whether or not J uses I and update the users and write-set
1173 // structures associated with I. Specifically, Users represents the set of
1174 // instructions that depend on I. WriteSet represents the set
1175 // of memory locations that are dependent on I. If UpdateUsers is true,
1176 // and J uses I, then Users is updated to contain J and WriteSet is updated
1177 // to contain any memory locations to which J writes. The function returns
1178 // true if J uses I. By default, alias analysis is used to determine
1179 // whether J reads from memory that overlaps with a location in WriteSet.
1180 // If LoadMoveSet is not null, then it is a previously-computed map
1181 // where the key is the memory-based user instruction and the value is
1182 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1183 // then the alias analysis is not used. This is necessary because this
1184 // function is called during the process of moving instructions during
1185 // vectorization and the results of the alias analysis are not stable during
1187 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1188 AliasSetTracker &WriteSet, Instruction *I,
1189 Instruction *J, bool UpdateUsers,
1190 DenseSet<ValuePair> *LoadMoveSetPairs) {
1193 // This instruction may already be marked as a user due, for example, to
1194 // being a member of a selected pair.
1199 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1202 if (I == V || Users.count(V)) {
1207 if (!UsesI && J->mayReadFromMemory()) {
1208 if (LoadMoveSetPairs) {
1209 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1211 for (AliasSetTracker::iterator W = WriteSet.begin(),
1212 WE = WriteSet.end(); W != WE; ++W) {
1213 if (W->aliasesUnknownInst(J, *AA)) {
1221 if (UsesI && UpdateUsers) {
1222 if (J->mayWriteToMemory()) WriteSet.add(J);
1229 // This function iterates over all instruction pairs in the provided
1230 // basic block and collects all candidate pairs for vectorization.
1231 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1232 BasicBlock::iterator &Start,
1233 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1234 DenseSet<ValuePair> &FixedOrderPairs,
1235 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1236 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1237 size_t TotalPairs = 0;
1238 BasicBlock::iterator E = BB.end();
1239 if (Start == E) return false;
1241 bool ShouldContinue = false, IAfterStart = false;
1242 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1243 if (I == Start) IAfterStart = true;
1245 bool IsSimpleLoadStore;
1246 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1248 // Look for an instruction with which to pair instruction *I...
1249 DenseSet<Value *> Users;
1250 AliasSetTracker WriteSet(*AA);
1251 if (I->mayWriteToMemory()) WriteSet.add(I);
1253 bool JAfterStart = IAfterStart;
1254 BasicBlock::iterator J = std::next(I);
1255 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1256 if (J == Start) JAfterStart = true;
1258 // Determine if J uses I, if so, exit the loop.
1259 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1260 if (Config.FastDep) {
1261 // Note: For this heuristic to be effective, independent operations
1262 // must tend to be intermixed. This is likely to be true from some
1263 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1264 // but otherwise may require some kind of reordering pass.
1266 // When using fast dependency analysis,
1267 // stop searching after first use:
1270 if (UsesI) continue;
1273 // J does not use I, and comes before the first use of I, so it can be
1274 // merged with I if the instructions are compatible.
1275 int CostSavings, FixedOrder;
1276 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1277 CostSavings, FixedOrder)) continue;
1279 // J is a candidate for merging with I.
1280 if (!PairableInsts.size() ||
1281 PairableInsts[PairableInsts.size()-1] != I) {
1282 PairableInsts.push_back(I);
1285 CandidatePairs[I].push_back(J);
1288 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1291 if (FixedOrder == 1)
1292 FixedOrderPairs.insert(ValuePair(I, J));
1293 else if (FixedOrder == -1)
1294 FixedOrderPairs.insert(ValuePair(J, I));
1296 // The next call to this function must start after the last instruction
1297 // selected during this invocation.
1299 Start = std::next(J);
1300 IAfterStart = JAfterStart = false;
1303 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1304 << *I << " <-> " << *J << " (cost savings: " <<
1305 CostSavings << ")\n");
1307 // If we have already found too many pairs, break here and this function
1308 // will be called again starting after the last instruction selected
1309 // during this invocation.
1310 if (PairableInsts.size() >= Config.MaxInsts ||
1311 TotalPairs >= Config.MaxPairs) {
1312 ShouldContinue = true;
1321 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1322 << " instructions with candidate pairs\n");
1324 return ShouldContinue;
1327 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1328 // it looks for pairs such that both members have an input which is an
1329 // output of PI or PJ.
1330 void BBVectorize::computePairsConnectedTo(
1331 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1332 DenseSet<ValuePair> &CandidatePairsSet,
1333 std::vector<Value *> &PairableInsts,
1334 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1335 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1339 // For each possible pairing for this variable, look at the uses of
1340 // the first value...
1341 for (Value::user_iterator I = P.first->user_begin(),
1342 E = P.first->user_end();
1345 if (isa<LoadInst>(UI)) {
1346 // A pair cannot be connected to a load because the load only takes one
1347 // operand (the address) and it is a scalar even after vectorization.
1349 } else if ((SI = dyn_cast<StoreInst>(UI)) &&
1350 P.first == SI->getPointerOperand()) {
1351 // Similarly, a pair cannot be connected to a store through its
1356 // For each use of the first variable, look for uses of the second
1358 for (User *UJ : P.second->users()) {
1359 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1360 P.second == SJ->getPointerOperand())
1364 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1365 VPPair VP(P, ValuePair(UI, UJ));
1366 ConnectedPairs[VP.first].push_back(VP.second);
1367 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1371 if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
1372 VPPair VP(P, ValuePair(UJ, UI));
1373 ConnectedPairs[VP.first].push_back(VP.second);
1374 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1378 if (Config.SplatBreaksChain) continue;
1379 // Look for cases where just the first value in the pair is used by
1380 // both members of another pair (splatting).
1381 for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
1383 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1384 P.first == SJ->getPointerOperand())
1387 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1388 VPPair VP(P, ValuePair(UI, UJ));
1389 ConnectedPairs[VP.first].push_back(VP.second);
1390 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1395 if (Config.SplatBreaksChain) return;
1396 // Look for cases where just the second value in the pair is used by
1397 // both members of another pair (splatting).
1398 for (Value::user_iterator I = P.second->user_begin(),
1399 E = P.second->user_end();
1402 if (isa<LoadInst>(UI))
1404 else if ((SI = dyn_cast<StoreInst>(UI)) &&
1405 P.second == SI->getPointerOperand())
1408 for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
1410 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1411 P.second == SJ->getPointerOperand())
1414 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1415 VPPair VP(P, ValuePair(UI, UJ));
1416 ConnectedPairs[VP.first].push_back(VP.second);
1417 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1423 // This function figures out which pairs are connected. Two pairs are
1424 // connected if some output of the first pair forms an input to both members
1425 // of the second pair.
1426 void BBVectorize::computeConnectedPairs(
1427 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1428 DenseSet<ValuePair> &CandidatePairsSet,
1429 std::vector<Value *> &PairableInsts,
1430 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1431 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1432 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1433 PE = PairableInsts.end(); PI != PE; ++PI) {
1434 DenseMap<Value *, std::vector<Value *> >::iterator PP =
1435 CandidatePairs.find(*PI);
1436 if (PP == CandidatePairs.end())
1439 for (std::vector<Value *>::iterator P = PP->second.begin(),
1440 E = PP->second.end(); P != E; ++P)
1441 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1442 PairableInsts, ConnectedPairs,
1443 PairConnectionTypes, ValuePair(*PI, *P));
1446 DEBUG(size_t TotalPairs = 0;
1447 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1448 ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1449 TotalPairs += I->second.size();
1450 dbgs() << "BBV: found " << TotalPairs
1451 << " pair connections.\n");
1454 // This function builds a set of use tuples such that <A, B> is in the set
1455 // if B is in the use dag of A. If B is in the use dag of A, then B
1456 // depends on the output of A.
1457 void BBVectorize::buildDepMap(
1459 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1460 std::vector<Value *> &PairableInsts,
1461 DenseSet<ValuePair> &PairableInstUsers) {
1462 DenseSet<Value *> IsInPair;
1463 for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1464 CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1465 IsInPair.insert(C->first);
1466 IsInPair.insert(C->second.begin(), C->second.end());
1469 // Iterate through the basic block, recording all users of each
1470 // pairable instruction.
1472 BasicBlock::iterator E = BB.end(), EL =
1473 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1474 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1475 if (IsInPair.find(I) == IsInPair.end()) continue;
1477 DenseSet<Value *> Users;
1478 AliasSetTracker WriteSet(*AA);
1479 if (I->mayWriteToMemory()) WriteSet.add(I);
1481 for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
1482 (void) trackUsesOfI(Users, WriteSet, I, J);
1488 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1490 if (IsInPair.find(*U) == IsInPair.end()) continue;
1491 PairableInstUsers.insert(ValuePair(I, *U));
1499 // Returns true if an input to pair P is an output of pair Q and also an
1500 // input of pair Q is an output of pair P. If this is the case, then these
1501 // two pairs cannot be simultaneously fused.
1502 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1503 DenseSet<ValuePair> &PairableInstUsers,
1504 DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1505 DenseSet<VPPair> *PairableInstUserPairSet) {
1506 // Two pairs are in conflict if they are mutual Users of eachother.
1507 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1508 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1509 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1510 PairableInstUsers.count(ValuePair(P.second, Q.second));
1511 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1512 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1513 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1514 PairableInstUsers.count(ValuePair(Q.second, P.second));
1515 if (PairableInstUserMap) {
1516 // FIXME: The expensive part of the cycle check is not so much the cycle
1517 // check itself but this edge insertion procedure. This needs some
1518 // profiling and probably a different data structure.
1520 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1521 (*PairableInstUserMap)[Q].push_back(P);
1524 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1525 (*PairableInstUserMap)[P].push_back(Q);
1529 return (QUsesP && PUsesQ);
1532 // This function walks the use graph of current pairs to see if, starting
1533 // from P, the walk returns to P.
1534 bool BBVectorize::pairWillFormCycle(ValuePair P,
1535 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1536 DenseSet<ValuePair> &CurrentPairs) {
1537 DEBUG(if (DebugCycleCheck)
1538 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1539 << *P.second << "\n");
1540 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1541 // contains non-direct associations.
1542 DenseSet<ValuePair> Visited;
1543 SmallVector<ValuePair, 32> Q;
1544 // General depth-first post-order traversal:
1547 ValuePair QTop = Q.pop_back_val();
1548 Visited.insert(QTop);
1550 DEBUG(if (DebugCycleCheck)
1551 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1552 << *QTop.second << "\n");
1553 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1554 PairableInstUserMap.find(QTop);
1555 if (QQ == PairableInstUserMap.end())
1558 for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1559 CE = QQ->second.end(); C != CE; ++C) {
1562 << "BBV: rejected to prevent non-trivial cycle formation: "
1563 << QTop.first << " <-> " << C->second << "\n");
1567 if (CurrentPairs.count(*C) && !Visited.count(*C))
1570 } while (!Q.empty());
1575 // This function builds the initial dag of connected pairs with the
1576 // pair J at the root.
1577 void BBVectorize::buildInitialDAGFor(
1578 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1579 DenseSet<ValuePair> &CandidatePairsSet,
1580 std::vector<Value *> &PairableInsts,
1581 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1582 DenseSet<ValuePair> &PairableInstUsers,
1583 DenseMap<Value *, Value *> &ChosenPairs,
1584 DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1585 // Each of these pairs is viewed as the root node of a DAG. The DAG
1586 // is then walked (depth-first). As this happens, we keep track of
1587 // the pairs that compose the DAG and the maximum depth of the DAG.
1588 SmallVector<ValuePairWithDepth, 32> Q;
1589 // General depth-first post-order traversal:
1590 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1592 ValuePairWithDepth QTop = Q.back();
1594 // Push each child onto the queue:
1595 bool MoreChildren = false;
1596 size_t MaxChildDepth = QTop.second;
1597 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1598 ConnectedPairs.find(QTop.first);
1599 if (QQ != ConnectedPairs.end())
1600 for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1601 ke = QQ->second.end(); k != ke; ++k) {
1602 // Make sure that this child pair is still a candidate:
1603 if (CandidatePairsSet.count(*k)) {
1604 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
1605 if (C == DAG.end()) {
1606 size_t d = getDepthFactor(k->first);
1607 Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1608 MoreChildren = true;
1610 MaxChildDepth = std::max(MaxChildDepth, C->second);
1615 if (!MoreChildren) {
1616 // Record the current pair as part of the DAG:
1617 DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1620 } while (!Q.empty());
1623 // Given some initial dag, prune it by removing conflicting pairs (pairs
1624 // that cannot be simultaneously chosen for vectorization).
1625 void BBVectorize::pruneDAGFor(
1626 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1627 std::vector<Value *> &PairableInsts,
1628 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1629 DenseSet<ValuePair> &PairableInstUsers,
1630 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1631 DenseSet<VPPair> &PairableInstUserPairSet,
1632 DenseMap<Value *, Value *> &ChosenPairs,
1633 DenseMap<ValuePair, size_t> &DAG,
1634 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1635 bool UseCycleCheck) {
1636 SmallVector<ValuePairWithDepth, 32> Q;
1637 // General depth-first post-order traversal:
1638 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1640 ValuePairWithDepth QTop = Q.pop_back_val();
1641 PrunedDAG.insert(QTop.first);
1643 // Visit each child, pruning as necessary...
1644 SmallVector<ValuePairWithDepth, 8> BestChildren;
1645 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1646 ConnectedPairs.find(QTop.first);
1647 if (QQ == ConnectedPairs.end())
1650 for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1651 KE = QQ->second.end(); K != KE; ++K) {
1652 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
1653 if (C == DAG.end()) continue;
1655 // This child is in the DAG, now we need to make sure it is the
1656 // best of any conflicting children. There could be multiple
1657 // conflicting children, so first, determine if we're keeping
1658 // this child, then delete conflicting children as necessary.
1660 // It is also necessary to guard against pairing-induced
1661 // dependencies. Consider instructions a .. x .. y .. b
1662 // such that (a,b) are to be fused and (x,y) are to be fused
1663 // but a is an input to x and b is an output from y. This
1664 // means that y cannot be moved after b but x must be moved
1665 // after b for (a,b) to be fused. In other words, after
1666 // fusing (a,b) we have y .. a/b .. x where y is an input
1667 // to a/b and x is an output to a/b: x and y can no longer
1668 // be legally fused. To prevent this condition, we must
1669 // make sure that a child pair added to the DAG is not
1670 // both an input and output of an already-selected pair.
1672 // Pairing-induced dependencies can also form from more complicated
1673 // cycles. The pair vs. pair conflicts are easy to check, and so
1674 // that is done explicitly for "fast rejection", and because for
1675 // child vs. child conflicts, we may prefer to keep the current
1676 // pair in preference to the already-selected child.
1677 DenseSet<ValuePair> CurrentPairs;
1680 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1681 = BestChildren.begin(), E2 = BestChildren.end();
1683 if (C2->first.first == C->first.first ||
1684 C2->first.first == C->first.second ||
1685 C2->first.second == C->first.first ||
1686 C2->first.second == C->first.second ||
1687 pairsConflict(C2->first, C->first, PairableInstUsers,
1688 UseCycleCheck ? &PairableInstUserMap : 0,
1689 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1690 if (C2->second >= C->second) {
1695 CurrentPairs.insert(C2->first);
1698 if (!CanAdd) continue;
1700 // Even worse, this child could conflict with another node already
1701 // selected for the DAG. If that is the case, ignore this child.
1702 for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1703 E2 = PrunedDAG.end(); T != E2; ++T) {
1704 if (T->first == C->first.first ||
1705 T->first == C->first.second ||
1706 T->second == C->first.first ||
1707 T->second == C->first.second ||
1708 pairsConflict(*T, C->first, PairableInstUsers,
1709 UseCycleCheck ? &PairableInstUserMap : 0,
1710 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1715 CurrentPairs.insert(*T);
1717 if (!CanAdd) continue;
1719 // And check the queue too...
1720 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
1721 E2 = Q.end(); C2 != E2; ++C2) {
1722 if (C2->first.first == C->first.first ||
1723 C2->first.first == C->first.second ||
1724 C2->first.second == C->first.first ||
1725 C2->first.second == C->first.second ||
1726 pairsConflict(C2->first, C->first, PairableInstUsers,
1727 UseCycleCheck ? &PairableInstUserMap : 0,
1728 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1733 CurrentPairs.insert(C2->first);
1735 if (!CanAdd) continue;
1737 // Last but not least, check for a conflict with any of the
1738 // already-chosen pairs.
1739 for (DenseMap<Value *, Value *>::iterator C2 =
1740 ChosenPairs.begin(), E2 = ChosenPairs.end();
1742 if (pairsConflict(*C2, C->first, PairableInstUsers,
1743 UseCycleCheck ? &PairableInstUserMap : 0,
1744 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1749 CurrentPairs.insert(*C2);
1751 if (!CanAdd) continue;
1753 // To check for non-trivial cycles formed by the addition of the
1754 // current pair we've formed a list of all relevant pairs, now use a
1755 // graph walk to check for a cycle. We start from the current pair and
1756 // walk the use dag to see if we again reach the current pair. If we
1757 // do, then the current pair is rejected.
1759 // FIXME: It may be more efficient to use a topological-ordering
1760 // algorithm to improve the cycle check. This should be investigated.
1761 if (UseCycleCheck &&
1762 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1765 // This child can be added, but we may have chosen it in preference
1766 // to an already-selected child. Check for this here, and if a
1767 // conflict is found, then remove the previously-selected child
1768 // before adding this one in its place.
1769 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1770 = BestChildren.begin(); C2 != BestChildren.end();) {
1771 if (C2->first.first == C->first.first ||
1772 C2->first.first == C->first.second ||
1773 C2->first.second == C->first.first ||
1774 C2->first.second == C->first.second ||
1775 pairsConflict(C2->first, C->first, PairableInstUsers))
1776 C2 = BestChildren.erase(C2);
1781 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1784 for (SmallVectorImpl<ValuePairWithDepth>::iterator C
1785 = BestChildren.begin(), E2 = BestChildren.end();
1787 size_t DepthF = getDepthFactor(C->first.first);
1788 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1790 } while (!Q.empty());
1793 // This function finds the best dag of mututally-compatible connected
1794 // pairs, given the choice of root pairs as an iterator range.
1795 void BBVectorize::findBestDAGFor(
1796 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1797 DenseSet<ValuePair> &CandidatePairsSet,
1798 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1799 std::vector<Value *> &PairableInsts,
1800 DenseSet<ValuePair> &FixedOrderPairs,
1801 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1802 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1803 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1804 DenseSet<ValuePair> &PairableInstUsers,
1805 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1806 DenseSet<VPPair> &PairableInstUserPairSet,
1807 DenseMap<Value *, Value *> &ChosenPairs,
1808 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1809 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1810 bool UseCycleCheck) {
1811 for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1813 ValuePair IJ(II, *J);
1814 if (!CandidatePairsSet.count(IJ))
1817 // Before going any further, make sure that this pair does not
1818 // conflict with any already-selected pairs (see comment below
1819 // near the DAG pruning for more details).
1820 DenseSet<ValuePair> ChosenPairSet;
1821 bool DoesConflict = false;
1822 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1823 E = ChosenPairs.end(); C != E; ++C) {
1824 if (pairsConflict(*C, IJ, PairableInstUsers,
1825 UseCycleCheck ? &PairableInstUserMap : 0,
1826 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1827 DoesConflict = true;
1831 ChosenPairSet.insert(*C);
1833 if (DoesConflict) continue;
1835 if (UseCycleCheck &&
1836 pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1839 DenseMap<ValuePair, size_t> DAG;
1840 buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1841 PairableInsts, ConnectedPairs,
1842 PairableInstUsers, ChosenPairs, DAG, IJ);
1844 // Because we'll keep the child with the largest depth, the largest
1845 // depth is still the same in the unpruned DAG.
1846 size_t MaxDepth = DAG.lookup(IJ);
1848 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1849 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1850 MaxDepth << " and size " << DAG.size() << "\n");
1852 // At this point the DAG has been constructed, but, may contain
1853 // contradictory children (meaning that different children of
1854 // some dag node may be attempting to fuse the same instruction).
1855 // So now we walk the dag again, in the case of a conflict,
1856 // keep only the child with the largest depth. To break a tie,
1857 // favor the first child.
1859 DenseSet<ValuePair> PrunedDAG;
1860 pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1861 PairableInstUsers, PairableInstUserMap,
1862 PairableInstUserPairSet,
1863 ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1867 DenseSet<Value *> PrunedDAGInstrs;
1868 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1869 E = PrunedDAG.end(); S != E; ++S) {
1870 PrunedDAGInstrs.insert(S->first);
1871 PrunedDAGInstrs.insert(S->second);
1874 // The set of pairs that have already contributed to the total cost.
1875 DenseSet<ValuePair> IncomingPairs;
1877 // If the cost model were perfect, this might not be necessary; but we
1878 // need to make sure that we don't get stuck vectorizing our own
1880 bool HasNontrivialInsts = false;
1882 // The node weights represent the cost savings associated with
1883 // fusing the pair of instructions.
1884 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1885 E = PrunedDAG.end(); S != E; ++S) {
1886 if (!isa<ShuffleVectorInst>(S->first) &&
1887 !isa<InsertElementInst>(S->first) &&
1888 !isa<ExtractElementInst>(S->first))
1889 HasNontrivialInsts = true;
1891 bool FlipOrder = false;
1893 if (getDepthFactor(S->first)) {
1894 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1895 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1896 << *S->first << " <-> " << *S->second << "} = " <<
1898 EffSize += ESContrib;
1901 // The edge weights contribute in a negative sense: they represent
1902 // the cost of shuffles.
1903 DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1904 ConnectedPairDeps.find(*S);
1905 if (SS != ConnectedPairDeps.end()) {
1906 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1907 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1908 TE = SS->second.end(); T != TE; ++T) {
1910 if (!PrunedDAG.count(Q.second))
1912 DenseMap<VPPair, unsigned>::iterator R =
1913 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1914 assert(R != PairConnectionTypes.end() &&
1915 "Cannot find pair connection type");
1916 if (R->second == PairConnectionDirect)
1918 else if (R->second == PairConnectionSwap)
1922 // If there are more swaps than direct connections, then
1923 // the pair order will be flipped during fusion. So the real
1924 // number of swaps is the minimum number.
1925 FlipOrder = !FixedOrderPairs.count(*S) &&
1926 ((NumDepsSwap > NumDepsDirect) ||
1927 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1929 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1930 TE = SS->second.end(); T != TE; ++T) {
1932 if (!PrunedDAG.count(Q.second))
1934 DenseMap<VPPair, unsigned>::iterator R =
1935 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1936 assert(R != PairConnectionTypes.end() &&
1937 "Cannot find pair connection type");
1938 Type *Ty1 = Q.second.first->getType(),
1939 *Ty2 = Q.second.second->getType();
1940 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1941 if ((R->second == PairConnectionDirect && FlipOrder) ||
1942 (R->second == PairConnectionSwap && !FlipOrder) ||
1943 R->second == PairConnectionSplat) {
1944 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1947 if (VTy->getVectorNumElements() == 2) {
1948 if (R->second == PairConnectionSplat)
1949 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1950 TargetTransformInfo::SK_Broadcast, VTy));
1952 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1953 TargetTransformInfo::SK_Reverse, VTy));
1956 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1957 *Q.second.first << " <-> " << *Q.second.second <<
1959 *S->first << " <-> " << *S->second << "} = " <<
1961 EffSize -= ESContrib;
1966 // Compute the cost of outgoing edges. We assume that edges outgoing
1967 // to shuffles, inserts or extracts can be merged, and so contribute
1968 // no additional cost.
1969 if (!S->first->getType()->isVoidTy()) {
1970 Type *Ty1 = S->first->getType(),
1971 *Ty2 = S->second->getType();
1972 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1974 bool NeedsExtraction = false;
1975 for (User *U : S->first->users()) {
1976 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
1977 // Shuffle can be folded if it has no other input
1978 if (isa<UndefValue>(SI->getOperand(1)))
1981 if (isa<ExtractElementInst>(U))
1983 if (PrunedDAGInstrs.count(U))
1985 NeedsExtraction = true;
1989 if (NeedsExtraction) {
1991 if (Ty1->isVectorTy()) {
1992 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1994 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1995 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1997 ESContrib = (int) TTI->getVectorInstrCost(
1998 Instruction::ExtractElement, VTy, 0);
2000 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2001 *S->first << "} = " << ESContrib << "\n");
2002 EffSize -= ESContrib;
2005 NeedsExtraction = false;
2006 for (User *U : S->second->users()) {
2007 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
2008 // Shuffle can be folded if it has no other input
2009 if (isa<UndefValue>(SI->getOperand(1)))
2012 if (isa<ExtractElementInst>(U))
2014 if (PrunedDAGInstrs.count(U))
2016 NeedsExtraction = true;
2020 if (NeedsExtraction) {
2022 if (Ty2->isVectorTy()) {
2023 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2025 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2026 TargetTransformInfo::SK_ExtractSubvector, VTy,
2027 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
2029 ESContrib = (int) TTI->getVectorInstrCost(
2030 Instruction::ExtractElement, VTy, 1);
2031 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2032 *S->second << "} = " << ESContrib << "\n");
2033 EffSize -= ESContrib;
2037 // Compute the cost of incoming edges.
2038 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
2039 Instruction *S1 = cast<Instruction>(S->first),
2040 *S2 = cast<Instruction>(S->second);
2041 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
2042 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
2044 // Combining constants into vector constants (or small vector
2045 // constants into larger ones are assumed free).
2046 if (isa<Constant>(O1) && isa<Constant>(O2))
2052 ValuePair VP = ValuePair(O1, O2);
2053 ValuePair VPR = ValuePair(O2, O1);
2055 // Internal edges are not handled here.
2056 if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
2059 Type *Ty1 = O1->getType(),
2060 *Ty2 = O2->getType();
2061 Type *VTy = getVecTypeForPair(Ty1, Ty2);
2063 // Combining vector operations of the same type is also assumed
2064 // folded with other operations.
2066 // If both are insert elements, then both can be widened.
2067 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
2068 *IEO2 = dyn_cast<InsertElementInst>(O2);
2069 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
2071 // If both are extract elements, and both have the same input
2072 // type, then they can be replaced with a shuffle
2073 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2074 *EIO2 = dyn_cast<ExtractElementInst>(O2);
2076 EIO1->getOperand(0)->getType() ==
2077 EIO2->getOperand(0)->getType())
2079 // If both are a shuffle with equal operand types and only two
2080 // unqiue operands, then they can be replaced with a single
2082 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2083 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2085 SIO1->getOperand(0)->getType() ==
2086 SIO2->getOperand(0)->getType()) {
2087 SmallSet<Value *, 4> SIOps;
2088 SIOps.insert(SIO1->getOperand(0));
2089 SIOps.insert(SIO1->getOperand(1));
2090 SIOps.insert(SIO2->getOperand(0));
2091 SIOps.insert(SIO2->getOperand(1));
2092 if (SIOps.size() <= 2)
2098 // This pair has already been formed.
2099 if (IncomingPairs.count(VP)) {
2101 } else if (IncomingPairs.count(VPR)) {
2102 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2105 if (VTy->getVectorNumElements() == 2)
2106 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2107 TargetTransformInfo::SK_Reverse, VTy));
2108 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2109 ESContrib = (int) TTI->getVectorInstrCost(
2110 Instruction::InsertElement, VTy, 0);
2111 ESContrib += (int) TTI->getVectorInstrCost(
2112 Instruction::InsertElement, VTy, 1);
2113 } else if (!Ty1->isVectorTy()) {
2114 // O1 needs to be inserted into a vector of size O2, and then
2115 // both need to be shuffled together.
2116 ESContrib = (int) TTI->getVectorInstrCost(
2117 Instruction::InsertElement, Ty2, 0);
2118 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2120 } else if (!Ty2->isVectorTy()) {
2121 // O2 needs to be inserted into a vector of size O1, and then
2122 // both need to be shuffled together.
2123 ESContrib = (int) TTI->getVectorInstrCost(
2124 Instruction::InsertElement, Ty1, 0);
2125 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2128 Type *TyBig = Ty1, *TySmall = Ty2;
2129 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2130 std::swap(TyBig, TySmall);
2132 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2134 if (TyBig != TySmall)
2135 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2139 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2140 << *O1 << " <-> " << *O2 << "} = " <<
2142 EffSize -= ESContrib;
2143 IncomingPairs.insert(VP);
2148 if (!HasNontrivialInsts) {
2149 DEBUG(if (DebugPairSelection) dbgs() <<
2150 "\tNo non-trivial instructions in DAG;"
2151 " override to zero effective size\n");
2155 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2156 E = PrunedDAG.end(); S != E; ++S)
2157 EffSize += (int) getDepthFactor(S->first);
2160 DEBUG(if (DebugPairSelection)
2161 dbgs() << "BBV: found pruned DAG for pair {"
2162 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2163 MaxDepth << " and size " << PrunedDAG.size() <<
2164 " (effective size: " << EffSize << ")\n");
2165 if (((TTI && !UseChainDepthWithTI) ||
2166 MaxDepth >= Config.ReqChainDepth) &&
2167 EffSize > 0 && EffSize > BestEffSize) {
2168 BestMaxDepth = MaxDepth;
2169 BestEffSize = EffSize;
2170 BestDAG = PrunedDAG;
2175 // Given the list of candidate pairs, this function selects those
2176 // that will be fused into vector instructions.
2177 void BBVectorize::choosePairs(
2178 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2179 DenseSet<ValuePair> &CandidatePairsSet,
2180 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2181 std::vector<Value *> &PairableInsts,
2182 DenseSet<ValuePair> &FixedOrderPairs,
2183 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2184 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2185 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2186 DenseSet<ValuePair> &PairableInstUsers,
2187 DenseMap<Value *, Value *>& ChosenPairs) {
2188 bool UseCycleCheck =
2189 CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2191 DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2192 for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2193 E = CandidatePairsSet.end(); I != E; ++I) {
2194 std::vector<Value *> &JJ = CandidatePairs2[I->second];
2195 if (JJ.empty()) JJ.reserve(32);
2196 JJ.push_back(I->first);
2199 DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2200 DenseSet<VPPair> PairableInstUserPairSet;
2201 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2202 E = PairableInsts.end(); I != E; ++I) {
2203 // The number of possible pairings for this variable:
2204 size_t NumChoices = CandidatePairs.lookup(*I).size();
2205 if (!NumChoices) continue;
2207 std::vector<Value *> &JJ = CandidatePairs[*I];
2209 // The best pair to choose and its dag:
2210 size_t BestMaxDepth = 0;
2211 int BestEffSize = 0;
2212 DenseSet<ValuePair> BestDAG;
2213 findBestDAGFor(CandidatePairs, CandidatePairsSet,
2214 CandidatePairCostSavings,
2215 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2216 ConnectedPairs, ConnectedPairDeps,
2217 PairableInstUsers, PairableInstUserMap,
2218 PairableInstUserPairSet, ChosenPairs,
2219 BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2222 if (BestDAG.empty())
2225 // A dag has been chosen (or not) at this point. If no dag was
2226 // chosen, then this instruction, I, cannot be paired (and is no longer
2229 DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2230 << *cast<Instruction>(*I) << "\n");
2232 for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2233 SE2 = BestDAG.end(); S != SE2; ++S) {
2234 // Insert the members of this dag into the list of chosen pairs.
2235 ChosenPairs.insert(ValuePair(S->first, S->second));
2236 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2237 *S->second << "\n");
2239 // Remove all candidate pairs that have values in the chosen dag.
2240 std::vector<Value *> &KK = CandidatePairs[S->first];
2241 for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2243 if (*K == S->second)
2246 CandidatePairsSet.erase(ValuePair(S->first, *K));
2249 std::vector<Value *> &LL = CandidatePairs2[S->second];
2250 for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2255 CandidatePairsSet.erase(ValuePair(*L, S->second));
2258 std::vector<Value *> &MM = CandidatePairs[S->second];
2259 for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2261 assert(*M != S->first && "Flipped pair in candidate list?");
2262 CandidatePairsSet.erase(ValuePair(S->second, *M));
2265 std::vector<Value *> &NN = CandidatePairs2[S->first];
2266 for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2268 assert(*N != S->second && "Flipped pair in candidate list?");
2269 CandidatePairsSet.erase(ValuePair(*N, S->first));
2274 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2277 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2282 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2283 (n > 0 ? "." + utostr(n) : "")).str();
2286 // Returns the value that is to be used as the pointer input to the vector
2287 // instruction that fuses I with J.
2288 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2289 Instruction *I, Instruction *J, unsigned o) {
2291 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2292 int64_t OffsetInElmts;
2294 // Note: the analysis might fail here, that is why the pair order has
2295 // been precomputed (OffsetInElmts must be unused here).
2296 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2297 IAddressSpace, JAddressSpace,
2298 OffsetInElmts, false);
2300 // The pointer value is taken to be the one with the lowest offset.
2303 Type *ArgTypeI = IPtr->getType()->getPointerElementType();
2304 Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
2305 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2307 = PointerType::get(VArgType,
2308 IPtr->getType()->getPointerAddressSpace());
2309 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2310 /* insert before */ I);
2313 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2314 unsigned MaskOffset, unsigned NumInElem,
2315 unsigned NumInElem1, unsigned IdxOffset,
2316 std::vector<Constant*> &Mask) {
2317 unsigned NumElem1 = J->getType()->getVectorNumElements();
2318 for (unsigned v = 0; v < NumElem1; ++v) {
2319 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2321 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2323 unsigned mm = m + (int) IdxOffset;
2324 if (m >= (int) NumInElem1)
2325 mm += (int) NumInElem;
2327 Mask[v+MaskOffset] =
2328 ConstantInt::get(Type::getInt32Ty(Context), mm);
2333 // Returns the value that is to be used as the vector-shuffle mask to the
2334 // vector instruction that fuses I with J.
2335 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2336 Instruction *I, Instruction *J) {
2337 // This is the shuffle mask. We need to append the second
2338 // mask to the first, and the numbers need to be adjusted.
2340 Type *ArgTypeI = I->getType();
2341 Type *ArgTypeJ = J->getType();
2342 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2344 unsigned NumElemI = ArgTypeI->getVectorNumElements();
2346 // Get the total number of elements in the fused vector type.
2347 // By definition, this must equal the number of elements in
2349 unsigned NumElem = VArgType->getVectorNumElements();
2350 std::vector<Constant*> Mask(NumElem);
2352 Type *OpTypeI = I->getOperand(0)->getType();
2353 unsigned NumInElemI = OpTypeI->getVectorNumElements();
2354 Type *OpTypeJ = J->getOperand(0)->getType();
2355 unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
2357 // The fused vector will be:
2358 // -----------------------------------------------------
2359 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2360 // -----------------------------------------------------
2361 // from which we'll extract NumElem total elements (where the first NumElemI
2362 // of them come from the mask in I and the remainder come from the mask
2365 // For the mask from the first pair...
2366 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2369 // For the mask from the second pair...
2370 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2373 return ConstantVector::get(Mask);
2376 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2377 Instruction *J, unsigned o, Value *&LOp,
2379 Type *ArgTypeL, Type *ArgTypeH,
2380 bool IBeforeJ, unsigned IdxOff) {
2381 bool ExpandedIEChain = false;
2382 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2383 // If we have a pure insertelement chain, then this can be rewritten
2384 // into a chain that directly builds the larger type.
2385 if (isPureIEChain(LIE)) {
2386 SmallVector<Value *, 8> VectElemts(numElemL,
2387 UndefValue::get(ArgTypeL->getScalarType()));
2388 InsertElementInst *LIENext = LIE;
2391 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2392 VectElemts[Idx] = LIENext->getOperand(1);
2394 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2397 Value *LIEPrev = UndefValue::get(ArgTypeH);
2398 for (unsigned i = 0; i < numElemL; ++i) {
2399 if (isa<UndefValue>(VectElemts[i])) continue;
2400 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2401 ConstantInt::get(Type::getInt32Ty(Context),
2403 getReplacementName(IBeforeJ ? I : J,
2405 LIENext->insertBefore(IBeforeJ ? J : I);
2409 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2410 ExpandedIEChain = true;
2414 return ExpandedIEChain;
2417 static unsigned getNumScalarElements(Type *Ty) {
2418 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
2419 return VecTy->getNumElements();
2423 // Returns the value to be used as the specified operand of the vector
2424 // instruction that fuses I with J.
2425 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2426 Instruction *J, unsigned o, bool IBeforeJ) {
2427 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2428 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2430 // Compute the fused vector type for this operand
2431 Type *ArgTypeI = I->getOperand(o)->getType();
2432 Type *ArgTypeJ = J->getOperand(o)->getType();
2433 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2435 Instruction *L = I, *H = J;
2436 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2438 unsigned numElemL = getNumScalarElements(ArgTypeL);
2439 unsigned numElemH = getNumScalarElements(ArgTypeH);
2441 Value *LOp = L->getOperand(o);
2442 Value *HOp = H->getOperand(o);
2443 unsigned numElem = VArgType->getNumElements();
2445 // First, we check if we can reuse the "original" vector outputs (if these
2446 // exist). We might need a shuffle.
2447 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2448 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2449 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2450 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2452 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2453 // optimization. The input vectors to the shuffle might be a different
2454 // length from the shuffle outputs. Unfortunately, the replacement
2455 // shuffle mask has already been formed, and the mask entries are sensitive
2456 // to the sizes of the inputs.
2457 bool IsSizeChangeShuffle =
2458 isa<ShuffleVectorInst>(L) &&
2459 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2461 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2462 // We can have at most two unique vector inputs.
2463 bool CanUseInputs = true;
2466 I1 = LEE->getOperand(0);
2468 I1 = LSV->getOperand(0);
2469 I2 = LSV->getOperand(1);
2470 if (I2 == I1 || isa<UndefValue>(I2))
2475 Value *I3 = HEE->getOperand(0);
2476 if (!I2 && I3 != I1)
2478 else if (I3 != I1 && I3 != I2)
2479 CanUseInputs = false;
2481 Value *I3 = HSV->getOperand(0);
2482 if (!I2 && I3 != I1)
2484 else if (I3 != I1 && I3 != I2)
2485 CanUseInputs = false;
2488 Value *I4 = HSV->getOperand(1);
2489 if (!isa<UndefValue>(I4)) {
2490 if (!I2 && I4 != I1)
2492 else if (I4 != I1 && I4 != I2)
2493 CanUseInputs = false;
2500 cast<Instruction>(LOp)->getOperand(0)->getType()
2501 ->getVectorNumElements();
2504 cast<Instruction>(HOp)->getOperand(0)->getType()
2505 ->getVectorNumElements();
2507 // We have one or two input vectors. We need to map each index of the
2508 // operands to the index of the original vector.
2509 SmallVector<std::pair<int, int>, 8> II(numElem);
2510 for (unsigned i = 0; i < numElemL; ++i) {
2514 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2515 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2517 Idx = LSV->getMaskValue(i);
2518 if (Idx < (int) LOpElem) {
2519 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2522 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2526 II[i] = std::pair<int, int>(Idx, INum);
2528 for (unsigned i = 0; i < numElemH; ++i) {
2532 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2533 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2535 Idx = HSV->getMaskValue(i);
2536 if (Idx < (int) HOpElem) {
2537 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2540 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2544 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2547 // We now have an array which tells us from which index of which
2548 // input vector each element of the operand comes.
2549 VectorType *I1T = cast<VectorType>(I1->getType());
2550 unsigned I1Elem = I1T->getNumElements();
2553 // In this case there is only one underlying vector input. Check for
2554 // the trivial case where we can use the input directly.
2555 if (I1Elem == numElem) {
2556 bool ElemInOrder = true;
2557 for (unsigned i = 0; i < numElem; ++i) {
2558 if (II[i].first != (int) i && II[i].first != -1) {
2559 ElemInOrder = false;
2568 // A shuffle is needed.
2569 std::vector<Constant *> Mask(numElem);
2570 for (unsigned i = 0; i < numElem; ++i) {
2571 int Idx = II[i].first;
2573 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2575 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2579 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2580 ConstantVector::get(Mask),
2581 getReplacementName(IBeforeJ ? I : J,
2583 S->insertBefore(IBeforeJ ? J : I);
2587 VectorType *I2T = cast<VectorType>(I2->getType());
2588 unsigned I2Elem = I2T->getNumElements();
2590 // This input comes from two distinct vectors. The first step is to
2591 // make sure that both vectors are the same length. If not, the
2592 // smaller one will need to grow before they can be shuffled together.
2593 if (I1Elem < I2Elem) {
2594 std::vector<Constant *> Mask(I2Elem);
2596 for (; v < I1Elem; ++v)
2597 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2598 for (; v < I2Elem; ++v)
2599 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2601 Instruction *NewI1 =
2602 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2603 ConstantVector::get(Mask),
2604 getReplacementName(IBeforeJ ? I : J,
2606 NewI1->insertBefore(IBeforeJ ? J : I);
2610 } else if (I1Elem > I2Elem) {
2611 std::vector<Constant *> Mask(I1Elem);
2613 for (; v < I2Elem; ++v)
2614 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2615 for (; v < I1Elem; ++v)
2616 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2618 Instruction *NewI2 =
2619 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2620 ConstantVector::get(Mask),
2621 getReplacementName(IBeforeJ ? I : J,
2623 NewI2->insertBefore(IBeforeJ ? J : I);
2629 // Now that both I1 and I2 are the same length we can shuffle them
2630 // together (and use the result).
2631 std::vector<Constant *> Mask(numElem);
2632 for (unsigned v = 0; v < numElem; ++v) {
2633 if (II[v].first == -1) {
2634 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2636 int Idx = II[v].first + II[v].second * I1Elem;
2637 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2641 Instruction *NewOp =
2642 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2643 getReplacementName(IBeforeJ ? I : J, true, o));
2644 NewOp->insertBefore(IBeforeJ ? J : I);
2649 Type *ArgType = ArgTypeL;
2650 if (numElemL < numElemH) {
2651 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2652 ArgTypeL, VArgType, IBeforeJ, 1)) {
2653 // This is another short-circuit case: we're combining a scalar into
2654 // a vector that is formed by an IE chain. We've just expanded the IE
2655 // chain, now insert the scalar and we're done.
2657 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2658 getReplacementName(IBeforeJ ? I : J, true, o));
2659 S->insertBefore(IBeforeJ ? J : I);
2661 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2662 ArgTypeH, IBeforeJ)) {
2663 // The two vector inputs to the shuffle must be the same length,
2664 // so extend the smaller vector to be the same length as the larger one.
2668 std::vector<Constant *> Mask(numElemH);
2670 for (; v < numElemL; ++v)
2671 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2672 for (; v < numElemH; ++v)
2673 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2675 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2676 ConstantVector::get(Mask),
2677 getReplacementName(IBeforeJ ? I : J,
2680 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2681 getReplacementName(IBeforeJ ? I : J,
2685 NLOp->insertBefore(IBeforeJ ? J : I);
2690 } else if (numElemL > numElemH) {
2691 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2692 ArgTypeH, VArgType, IBeforeJ)) {
2694 InsertElementInst::Create(LOp, HOp,
2695 ConstantInt::get(Type::getInt32Ty(Context),
2697 getReplacementName(IBeforeJ ? I : J,
2699 S->insertBefore(IBeforeJ ? J : I);
2701 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2702 ArgTypeL, IBeforeJ)) {
2705 std::vector<Constant *> Mask(numElemL);
2707 for (; v < numElemH; ++v)
2708 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2709 for (; v < numElemL; ++v)
2710 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2712 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2713 ConstantVector::get(Mask),
2714 getReplacementName(IBeforeJ ? I : J,
2717 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2718 getReplacementName(IBeforeJ ? I : J,
2722 NHOp->insertBefore(IBeforeJ ? J : I);
2727 if (ArgType->isVectorTy()) {
2728 unsigned numElem = VArgType->getVectorNumElements();
2729 std::vector<Constant*> Mask(numElem);
2730 for (unsigned v = 0; v < numElem; ++v) {
2732 // If the low vector was expanded, we need to skip the extra
2733 // undefined entries.
2734 if (v >= numElemL && numElemH > numElemL)
2735 Idx += (numElemH - numElemL);
2736 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2739 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2740 ConstantVector::get(Mask),
2741 getReplacementName(IBeforeJ ? I : J, true, o));
2742 BV->insertBefore(IBeforeJ ? J : I);
2746 Instruction *BV1 = InsertElementInst::Create(
2747 UndefValue::get(VArgType), LOp, CV0,
2748 getReplacementName(IBeforeJ ? I : J,
2750 BV1->insertBefore(IBeforeJ ? J : I);
2751 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2752 getReplacementName(IBeforeJ ? I : J,
2754 BV2->insertBefore(IBeforeJ ? J : I);
2758 // This function creates an array of values that will be used as the inputs
2759 // to the vector instruction that fuses I with J.
2760 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2761 Instruction *I, Instruction *J,
2762 SmallVectorImpl<Value *> &ReplacedOperands,
2764 unsigned NumOperands = I->getNumOperands();
2766 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2767 // Iterate backward so that we look at the store pointer
2768 // first and know whether or not we need to flip the inputs.
2770 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2771 // This is the pointer for a load/store instruction.
2772 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2774 } else if (isa<CallInst>(I)) {
2775 Function *F = cast<CallInst>(I)->getCalledFunction();
2776 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2777 if (o == NumOperands-1) {
2778 BasicBlock &BB = *I->getParent();
2780 Module *M = BB.getParent()->getParent();
2781 Type *ArgTypeI = I->getType();
2782 Type *ArgTypeJ = J->getType();
2783 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2785 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2787 } else if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
2788 IID == Intrinsic::cttz) && o == 1) {
2789 // The second argument of powi/ctlz/cttz is a single integer/constant
2790 // and we've already checked that both arguments are equal.
2791 // As a result, we just keep I's second argument.
2792 ReplacedOperands[o] = I->getOperand(o);
2795 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2796 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2800 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2804 // This function creates two values that represent the outputs of the
2805 // original I and J instructions. These are generally vector shuffles
2806 // or extracts. In many cases, these will end up being unused and, thus,
2807 // eliminated by later passes.
2808 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2809 Instruction *J, Instruction *K,
2810 Instruction *&InsertionPt,
2811 Instruction *&K1, Instruction *&K2) {
2812 if (isa<StoreInst>(I)) {
2813 AA->replaceWithNewValue(I, K);
2814 AA->replaceWithNewValue(J, K);
2816 Type *IType = I->getType();
2817 Type *JType = J->getType();
2819 VectorType *VType = getVecTypeForPair(IType, JType);
2820 unsigned numElem = VType->getNumElements();
2822 unsigned numElemI = getNumScalarElements(IType);
2823 unsigned numElemJ = getNumScalarElements(JType);
2825 if (IType->isVectorTy()) {
2826 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2827 for (unsigned v = 0; v < numElemI; ++v) {
2828 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2829 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2832 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2833 ConstantVector::get( Mask1),
2834 getReplacementName(K, false, 1));
2836 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2837 K1 = ExtractElementInst::Create(K, CV0,
2838 getReplacementName(K, false, 1));
2841 if (JType->isVectorTy()) {
2842 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2843 for (unsigned v = 0; v < numElemJ; ++v) {
2844 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2845 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2848 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2849 ConstantVector::get( Mask2),
2850 getReplacementName(K, false, 2));
2852 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2853 K2 = ExtractElementInst::Create(K, CV1,
2854 getReplacementName(K, false, 2));
2858 K2->insertAfter(K1);
2863 // Move all uses of the function I (including pairing-induced uses) after J.
2864 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2865 DenseSet<ValuePair> &LoadMoveSetPairs,
2866 Instruction *I, Instruction *J) {
2867 // Skip to the first instruction past I.
2868 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2870 DenseSet<Value *> Users;
2871 AliasSetTracker WriteSet(*AA);
2872 if (I->mayWriteToMemory()) WriteSet.add(I);
2874 for (; cast<Instruction>(L) != J; ++L)
2875 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2877 assert(cast<Instruction>(L) == J &&
2878 "Tracking has not proceeded far enough to check for dependencies");
2879 // If J is now in the use set of I, then trackUsesOfI will return true
2880 // and we have a dependency cycle (and the fusing operation must abort).
2881 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2884 // Move all uses of the function I (including pairing-induced uses) after J.
2885 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2886 DenseSet<ValuePair> &LoadMoveSetPairs,
2887 Instruction *&InsertionPt,
2888 Instruction *I, Instruction *J) {
2889 // Skip to the first instruction past I.
2890 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2892 DenseSet<Value *> Users;
2893 AliasSetTracker WriteSet(*AA);
2894 if (I->mayWriteToMemory()) WriteSet.add(I);
2896 for (; cast<Instruction>(L) != J;) {
2897 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2898 // Move this instruction
2899 Instruction *InstToMove = L; ++L;
2901 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2902 " to after " << *InsertionPt << "\n");
2903 InstToMove->removeFromParent();
2904 InstToMove->insertAfter(InsertionPt);
2905 InsertionPt = InstToMove;
2912 // Collect all load instruction that are in the move set of a given first
2913 // pair member. These loads depend on the first instruction, I, and so need
2914 // to be moved after J (the second instruction) when the pair is fused.
2915 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2916 DenseMap<Value *, Value *> &ChosenPairs,
2917 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2918 DenseSet<ValuePair> &LoadMoveSetPairs,
2920 // Skip to the first instruction past I.
2921 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2923 DenseSet<Value *> Users;
2924 AliasSetTracker WriteSet(*AA);
2925 if (I->mayWriteToMemory()) WriteSet.add(I);
2927 // Note: We cannot end the loop when we reach J because J could be moved
2928 // farther down the use chain by another instruction pairing. Also, J
2929 // could be before I if this is an inverted input.
2930 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2931 if (trackUsesOfI(Users, WriteSet, I, L)) {
2932 if (L->mayReadFromMemory()) {
2933 LoadMoveSet[L].push_back(I);
2934 LoadMoveSetPairs.insert(ValuePair(L, I));
2940 // In cases where both load/stores and the computation of their pointers
2941 // are chosen for vectorization, we can end up in a situation where the
2942 // aliasing analysis starts returning different query results as the
2943 // process of fusing instruction pairs continues. Because the algorithm
2944 // relies on finding the same use dags here as were found earlier, we'll
2945 // need to precompute the necessary aliasing information here and then
2946 // manually update it during the fusion process.
2947 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2948 std::vector<Value *> &PairableInsts,
2949 DenseMap<Value *, Value *> &ChosenPairs,
2950 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2951 DenseSet<ValuePair> &LoadMoveSetPairs) {
2952 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2953 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2954 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2955 if (P == ChosenPairs.end()) continue;
2957 Instruction *I = cast<Instruction>(P->first);
2958 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2959 LoadMoveSetPairs, I);
2963 // When the first instruction in each pair is cloned, it will inherit its
2964 // parent's metadata. This metadata must be combined with that of the other
2965 // instruction in a safe way.
2966 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2967 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2968 K->getAllMetadataOtherThanDebugLoc(Metadata);
2969 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2970 unsigned Kind = Metadata[i].first;
2971 MDNode *JMD = J->getMetadata(Kind);
2972 MDNode *KMD = Metadata[i].second;
2976 K->setMetadata(Kind, 0); // Remove unknown metadata
2978 case LLVMContext::MD_tbaa:
2979 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2981 case LLVMContext::MD_fpmath:
2982 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2988 // This function fuses the chosen instruction pairs into vector instructions,
2989 // taking care preserve any needed scalar outputs and, then, it reorders the
2990 // remaining instructions as needed (users of the first member of the pair
2991 // need to be moved to after the location of the second member of the pair
2992 // because the vector instruction is inserted in the location of the pair's
2994 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2995 std::vector<Value *> &PairableInsts,
2996 DenseMap<Value *, Value *> &ChosenPairs,
2997 DenseSet<ValuePair> &FixedOrderPairs,
2998 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2999 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
3000 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
3001 LLVMContext& Context = BB.getContext();
3003 // During the vectorization process, the order of the pairs to be fused
3004 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
3005 // list. After a pair is fused, the flipped pair is removed from the list.
3006 DenseSet<ValuePair> FlippedPairs;
3007 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
3008 E = ChosenPairs.end(); P != E; ++P)
3009 FlippedPairs.insert(ValuePair(P->second, P->first));
3010 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
3011 E = FlippedPairs.end(); P != E; ++P)
3012 ChosenPairs.insert(*P);
3014 DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
3015 DenseSet<ValuePair> LoadMoveSetPairs;
3016 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
3017 LoadMoveSet, LoadMoveSetPairs);
3019 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
3021 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
3022 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
3023 if (P == ChosenPairs.end()) {
3028 if (getDepthFactor(P->first) == 0) {
3029 // These instructions are not really fused, but are tracked as though
3030 // they are. Any case in which it would be interesting to fuse them
3031 // will be taken care of by InstCombine.
3037 Instruction *I = cast<Instruction>(P->first),
3038 *J = cast<Instruction>(P->second);
3040 DEBUG(dbgs() << "BBV: fusing: " << *I <<
3041 " <-> " << *J << "\n");
3043 // Remove the pair and flipped pair from the list.
3044 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
3045 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
3046 ChosenPairs.erase(FP);
3047 ChosenPairs.erase(P);
3049 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
3050 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
3052 " aborted because of non-trivial dependency cycle\n");
3058 // If the pair must have the other order, then flip it.
3059 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
3060 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
3061 // This pair does not have a fixed order, and so we might want to
3062 // flip it if that will yield fewer shuffles. We count the number
3063 // of dependencies connected via swaps, and those directly connected,
3064 // and flip the order if the number of swaps is greater.
3065 bool OrigOrder = true;
3066 DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
3067 ConnectedPairDeps.find(ValuePair(I, J));
3068 if (IJ == ConnectedPairDeps.end()) {
3069 IJ = ConnectedPairDeps.find(ValuePair(J, I));
3073 if (IJ != ConnectedPairDeps.end()) {
3074 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3075 for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3076 TE = IJ->second.end(); T != TE; ++T) {
3077 VPPair Q(IJ->first, *T);
3078 DenseMap<VPPair, unsigned>::iterator R =
3079 PairConnectionTypes.find(VPPair(Q.second, Q.first));
3080 assert(R != PairConnectionTypes.end() &&
3081 "Cannot find pair connection type");
3082 if (R->second == PairConnectionDirect)
3084 else if (R->second == PairConnectionSwap)
3089 std::swap(NumDepsDirect, NumDepsSwap);
3091 if (NumDepsSwap > NumDepsDirect) {
3092 FlipPairOrder = true;
3093 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3094 " <-> " << *J << "\n");
3099 Instruction *L = I, *H = J;
3103 // If the pair being fused uses the opposite order from that in the pair
3104 // connection map, then we need to flip the types.
3105 DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3106 ConnectedPairs.find(ValuePair(H, L));
3107 if (HL != ConnectedPairs.end())
3108 for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3109 TE = HL->second.end(); T != TE; ++T) {
3110 VPPair Q(HL->first, *T);
3111 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3112 assert(R != PairConnectionTypes.end() &&
3113 "Cannot find pair connection type");
3114 if (R->second == PairConnectionDirect)
3115 R->second = PairConnectionSwap;
3116 else if (R->second == PairConnectionSwap)
3117 R->second = PairConnectionDirect;
3120 bool LBeforeH = !FlipPairOrder;
3121 unsigned NumOperands = I->getNumOperands();
3122 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3123 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3126 // Make a copy of the original operation, change its type to the vector
3127 // type and replace its operands with the vector operands.
3128 Instruction *K = L->clone();
3131 else if (H->hasName())
3134 if (!isa<StoreInst>(K))
3135 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3137 combineMetadata(K, H);
3138 K->intersectOptionalDataWith(H);
3140 for (unsigned o = 0; o < NumOperands; ++o)
3141 K->setOperand(o, ReplacedOperands[o]);
3145 // Instruction insertion point:
3146 Instruction *InsertionPt = K;
3147 Instruction *K1 = 0, *K2 = 0;
3148 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3150 // The use dag of the first original instruction must be moved to after
3151 // the location of the second instruction. The entire use dag of the
3152 // first instruction is disjoint from the input dag of the second
3153 // (by definition), and so commutes with it.
3155 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3157 if (!isa<StoreInst>(I)) {
3158 L->replaceAllUsesWith(K1);
3159 H->replaceAllUsesWith(K2);
3160 AA->replaceWithNewValue(L, K1);
3161 AA->replaceWithNewValue(H, K2);
3164 // Instructions that may read from memory may be in the load move set.
3165 // Once an instruction is fused, we no longer need its move set, and so
3166 // the values of the map never need to be updated. However, when a load
3167 // is fused, we need to merge the entries from both instructions in the
3168 // pair in case those instructions were in the move set of some other
3169 // yet-to-be-fused pair. The loads in question are the keys of the map.
3170 if (I->mayReadFromMemory()) {
3171 std::vector<ValuePair> NewSetMembers;
3172 DenseMap<Value *, std::vector<Value *> >::iterator II =
3173 LoadMoveSet.find(I);
3174 if (II != LoadMoveSet.end())
3175 for (std::vector<Value *>::iterator N = II->second.begin(),
3176 NE = II->second.end(); N != NE; ++N)
3177 NewSetMembers.push_back(ValuePair(K, *N));
3178 DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3179 LoadMoveSet.find(J);
3180 if (JJ != LoadMoveSet.end())
3181 for (std::vector<Value *>::iterator N = JJ->second.begin(),
3182 NE = JJ->second.end(); N != NE; ++N)
3183 NewSetMembers.push_back(ValuePair(K, *N));
3184 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3185 AE = NewSetMembers.end(); A != AE; ++A) {
3186 LoadMoveSet[A->first].push_back(A->second);
3187 LoadMoveSetPairs.insert(*A);
3191 // Before removing I, set the iterator to the next instruction.
3192 PI = std::next(BasicBlock::iterator(I));
3193 if (cast<Instruction>(PI) == J)
3198 I->eraseFromParent();
3199 J->eraseFromParent();
3201 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3205 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3209 char BBVectorize::ID = 0;
3210 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3211 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3212 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3213 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3214 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3215 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3216 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3218 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3219 return new BBVectorize(C);
3223 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3224 BBVectorize BBVectorizer(P, C);
3225 return BBVectorizer.vectorizeBB(BB);
3228 //===----------------------------------------------------------------------===//
3229 VectorizeConfig::VectorizeConfig() {
3230 VectorBits = ::VectorBits;
3231 VectorizeBools = !::NoBools;
3232 VectorizeInts = !::NoInts;
3233 VectorizeFloats = !::NoFloats;
3234 VectorizePointers = !::NoPointers;
3235 VectorizeCasts = !::NoCasts;
3236 VectorizeMath = !::NoMath;
3237 VectorizeBitManipulations = !::NoBitManipulation;
3238 VectorizeFMA = !::NoFMA;
3239 VectorizeSelect = !::NoSelect;
3240 VectorizeCmp = !::NoCmp;
3241 VectorizeGEP = !::NoGEP;
3242 VectorizeMemOps = !::NoMemOps;
3243 AlignedOnly = ::AlignedOnly;
3244 ReqChainDepth= ::ReqChainDepth;
3245 SearchLimit = ::SearchLimit;
3246 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3247 SplatBreaksChain = ::SplatBreaksChain;
3248 MaxInsts = ::MaxInsts;
3249 MaxPairs = ::MaxPairs;
3250 MaxIter = ::MaxIter;
3251 Pow2LenOnly = ::Pow2LenOnly;
3252 NoMemOpBoost = ::NoMemOpBoost;
3253 FastDep = ::FastDep;