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/TargetLibraryInfo.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/ValueHandle.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Utils/Local.h"
54 #define DEBUG_TYPE BBV_NAME
57 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
58 cl::Hidden, cl::desc("Ignore target information"));
60 static cl::opt<unsigned>
61 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
62 cl::desc("The required chain depth for vectorization"));
65 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
66 cl::Hidden, cl::desc("Use the chain depth requirement with"
67 " target information"));
69 static cl::opt<unsigned>
70 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
71 cl::desc("The maximum search distance for instruction pairs"));
74 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
75 cl::desc("Replicating one element to a pair breaks the chain"));
77 static cl::opt<unsigned>
78 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
79 cl::desc("The size of the native vector registers"));
81 static cl::opt<unsigned>
82 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
83 cl::desc("The maximum number of pairing iterations"));
86 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
87 cl::desc("Don't try to form non-2^n-length vectors"));
89 static cl::opt<unsigned>
90 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
91 cl::desc("The maximum number of pairable instructions per group"));
93 static cl::opt<unsigned>
94 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
95 cl::desc("The maximum number of candidate instruction pairs per group"));
97 static cl::opt<unsigned>
98 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
99 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
100 " a full cycle check"));
103 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
104 cl::desc("Don't try to vectorize boolean (i1) values"));
107 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
108 cl::desc("Don't try to vectorize integer values"));
111 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
112 cl::desc("Don't try to vectorize floating-point values"));
114 // FIXME: This should default to false once pointer vector support works.
116 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
117 cl::desc("Don't try to vectorize pointer values"));
120 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
121 cl::desc("Don't try to vectorize casting (conversion) operations"));
124 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
125 cl::desc("Don't try to vectorize floating-point math intrinsics"));
128 NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden,
129 cl::desc("Don't try to vectorize BitManipulation intrinsics"));
132 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
133 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
136 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
137 cl::desc("Don't try to vectorize select instructions"));
140 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
141 cl::desc("Don't try to vectorize comparison instructions"));
144 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
145 cl::desc("Don't try to vectorize getelementptr instructions"));
148 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
149 cl::desc("Don't try to vectorize loads and stores"));
152 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
153 cl::desc("Only generate aligned loads and stores"));
156 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
157 cl::init(false), cl::Hidden,
158 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
161 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
162 cl::desc("Use a fast instruction dependency analysis"));
166 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
167 cl::init(false), cl::Hidden,
168 cl::desc("When debugging is enabled, output information on the"
169 " instruction-examination process"));
171 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
172 cl::init(false), cl::Hidden,
173 cl::desc("When debugging is enabled, output information on the"
174 " candidate-selection process"));
176 DebugPairSelection("bb-vectorize-debug-pair-selection",
177 cl::init(false), cl::Hidden,
178 cl::desc("When debugging is enabled, output information on the"
179 " pair-selection process"));
181 DebugCycleCheck("bb-vectorize-debug-cycle-check",
182 cl::init(false), cl::Hidden,
183 cl::desc("When debugging is enabled, output information on the"
184 " cycle-checking process"));
187 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
188 cl::init(false), cl::Hidden,
189 cl::desc("When debugging is enabled, dump the basic block after"
190 " every pair is fused"));
193 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
196 struct BBVectorize : public BasicBlockPass {
197 static char ID; // Pass identification, replacement for typeid
199 const VectorizeConfig Config;
201 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
202 : BasicBlockPass(ID), Config(C) {
203 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
206 BBVectorize(Pass *P, Function &F, const VectorizeConfig &C)
207 : BasicBlockPass(ID), Config(C) {
208 AA = &P->getAnalysis<AliasAnalysis>();
209 DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
210 SE = &P->getAnalysis<ScalarEvolutionWrapperPass>().getSE();
211 TLI = &P->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
212 TTI = IgnoreTargetInfo
214 : &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
217 typedef std::pair<Value *, Value *> ValuePair;
218 typedef std::pair<ValuePair, int> ValuePairWithCost;
219 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
220 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
221 typedef std::pair<VPPair, unsigned> VPPairWithType;
226 const TargetLibraryInfo *TLI;
227 const TargetTransformInfo *TTI;
229 // FIXME: const correct?
231 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
233 bool getCandidatePairs(BasicBlock &BB,
234 BasicBlock::iterator &Start,
235 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
236 DenseSet<ValuePair> &FixedOrderPairs,
237 DenseMap<ValuePair, int> &CandidatePairCostSavings,
238 std::vector<Value *> &PairableInsts, bool NonPow2Len);
240 // FIXME: The current implementation does not account for pairs that
241 // are connected in multiple ways. For example:
242 // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
243 enum PairConnectionType {
244 PairConnectionDirect,
249 void computeConnectedPairs(
250 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
251 DenseSet<ValuePair> &CandidatePairsSet,
252 std::vector<Value *> &PairableInsts,
253 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
254 DenseMap<VPPair, unsigned> &PairConnectionTypes);
256 void buildDepMap(BasicBlock &BB,
257 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
258 std::vector<Value *> &PairableInsts,
259 DenseSet<ValuePair> &PairableInstUsers);
261 void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
262 DenseSet<ValuePair> &CandidatePairsSet,
263 DenseMap<ValuePair, int> &CandidatePairCostSavings,
264 std::vector<Value *> &PairableInsts,
265 DenseSet<ValuePair> &FixedOrderPairs,
266 DenseMap<VPPair, unsigned> &PairConnectionTypes,
267 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
268 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
269 DenseSet<ValuePair> &PairableInstUsers,
270 DenseMap<Value *, Value *>& ChosenPairs);
272 void fuseChosenPairs(BasicBlock &BB,
273 std::vector<Value *> &PairableInsts,
274 DenseMap<Value *, Value *>& ChosenPairs,
275 DenseSet<ValuePair> &FixedOrderPairs,
276 DenseMap<VPPair, unsigned> &PairConnectionTypes,
277 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
278 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
281 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
283 bool areInstsCompatible(Instruction *I, Instruction *J,
284 bool IsSimpleLoadStore, bool NonPow2Len,
285 int &CostSavings, int &FixedOrder);
287 bool trackUsesOfI(DenseSet<Value *> &Users,
288 AliasSetTracker &WriteSet, Instruction *I,
289 Instruction *J, bool UpdateUsers = true,
290 DenseSet<ValuePair> *LoadMoveSetPairs = nullptr);
292 void computePairsConnectedTo(
293 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
294 DenseSet<ValuePair> &CandidatePairsSet,
295 std::vector<Value *> &PairableInsts,
296 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
297 DenseMap<VPPair, unsigned> &PairConnectionTypes,
300 bool pairsConflict(ValuePair P, ValuePair Q,
301 DenseSet<ValuePair> &PairableInstUsers,
302 DenseMap<ValuePair, std::vector<ValuePair> >
303 *PairableInstUserMap = nullptr,
304 DenseSet<VPPair> *PairableInstUserPairSet = nullptr);
306 bool pairWillFormCycle(ValuePair P,
307 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
308 DenseSet<ValuePair> &CurrentPairs);
311 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
312 std::vector<Value *> &PairableInsts,
313 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
314 DenseSet<ValuePair> &PairableInstUsers,
315 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
316 DenseSet<VPPair> &PairableInstUserPairSet,
317 DenseMap<Value *, Value *> &ChosenPairs,
318 DenseMap<ValuePair, size_t> &DAG,
319 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
322 void buildInitialDAGFor(
323 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
324 DenseSet<ValuePair> &CandidatePairsSet,
325 std::vector<Value *> &PairableInsts,
326 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
327 DenseSet<ValuePair> &PairableInstUsers,
328 DenseMap<Value *, Value *> &ChosenPairs,
329 DenseMap<ValuePair, size_t> &DAG, ValuePair J);
332 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
333 DenseSet<ValuePair> &CandidatePairsSet,
334 DenseMap<ValuePair, int> &CandidatePairCostSavings,
335 std::vector<Value *> &PairableInsts,
336 DenseSet<ValuePair> &FixedOrderPairs,
337 DenseMap<VPPair, unsigned> &PairConnectionTypes,
338 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
339 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
340 DenseSet<ValuePair> &PairableInstUsers,
341 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
342 DenseSet<VPPair> &PairableInstUserPairSet,
343 DenseMap<Value *, Value *> &ChosenPairs,
344 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
345 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
348 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
349 Instruction *J, unsigned o);
351 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
352 unsigned MaskOffset, unsigned NumInElem,
353 unsigned NumInElem1, unsigned IdxOffset,
354 std::vector<Constant*> &Mask);
356 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
359 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
360 unsigned o, Value *&LOp, unsigned numElemL,
361 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
362 unsigned IdxOff = 0);
364 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
365 Instruction *J, unsigned o, bool IBeforeJ);
367 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
368 Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
371 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
372 Instruction *J, Instruction *K,
373 Instruction *&InsertionPt, Instruction *&K1,
376 void collectPairLoadMoveSet(BasicBlock &BB,
377 DenseMap<Value *, Value *> &ChosenPairs,
378 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
379 DenseSet<ValuePair> &LoadMoveSetPairs,
382 void collectLoadMoveSet(BasicBlock &BB,
383 std::vector<Value *> &PairableInsts,
384 DenseMap<Value *, Value *> &ChosenPairs,
385 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
386 DenseSet<ValuePair> &LoadMoveSetPairs);
388 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
389 DenseSet<ValuePair> &LoadMoveSetPairs,
390 Instruction *I, Instruction *J);
392 void moveUsesOfIAfterJ(BasicBlock &BB,
393 DenseSet<ValuePair> &LoadMoveSetPairs,
394 Instruction *&InsertionPt,
395 Instruction *I, Instruction *J);
397 bool vectorizeBB(BasicBlock &BB) {
398 if (skipOptnoneFunction(BB))
400 if (!DT->isReachableFromEntry(&BB)) {
401 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
402 " in " << BB.getParent()->getName() << "\n");
406 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
408 bool changed = false;
409 // Iterate a sufficient number of times to merge types of size 1 bit,
410 // then 2 bits, then 4, etc. up to half of the target vector width of the
411 // target vector register.
414 (TTI || v <= Config.VectorBits) &&
415 (!Config.MaxIter || n <= Config.MaxIter);
417 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
418 " for " << BB.getName() << " in " <<
419 BB.getParent()->getName() << "...\n");
420 if (vectorizePairs(BB))
426 if (changed && !Pow2LenOnly) {
428 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
429 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
430 n << " for " << BB.getName() << " in " <<
431 BB.getParent()->getName() << "...\n");
432 if (!vectorizePairs(BB, true)) break;
436 DEBUG(dbgs() << "BBV: done!\n");
440 bool runOnBasicBlock(BasicBlock &BB) override {
441 // OptimizeNone check deferred to vectorizeBB().
443 AA = &getAnalysis<AliasAnalysis>();
444 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
445 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
446 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
447 TTI = IgnoreTargetInfo
449 : &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
452 return vectorizeBB(BB);
455 void getAnalysisUsage(AnalysisUsage &AU) const override {
456 BasicBlockPass::getAnalysisUsage(AU);
457 AU.addRequired<AliasAnalysis>();
458 AU.addRequired<DominatorTreeWrapperPass>();
459 AU.addRequired<ScalarEvolutionWrapperPass>();
460 AU.addRequired<TargetLibraryInfoWrapperPass>();
461 AU.addRequired<TargetTransformInfoWrapperPass>();
462 AU.addPreserved<AliasAnalysis>();
463 AU.addPreserved<DominatorTreeWrapperPass>();
464 AU.addPreserved<ScalarEvolutionWrapperPass>();
465 AU.setPreservesCFG();
468 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
469 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
470 "Cannot form vector from incompatible scalar types");
471 Type *STy = ElemTy->getScalarType();
474 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
475 numElem = VTy->getNumElements();
480 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
481 numElem += VTy->getNumElements();
486 return VectorType::get(STy, numElem);
489 static inline void getInstructionTypes(Instruction *I,
490 Type *&T1, Type *&T2) {
491 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
492 // For stores, it is the value type, not the pointer type that matters
493 // because the value is what will come from a vector register.
495 Value *IVal = SI->getValueOperand();
496 T1 = IVal->getType();
501 if (CastInst *CI = dyn_cast<CastInst>(I))
506 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
507 T2 = SI->getCondition()->getType();
508 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
509 T2 = SI->getOperand(0)->getType();
510 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
511 T2 = CI->getOperand(0)->getType();
515 // Returns the weight associated with the provided value. A chain of
516 // candidate pairs has a length given by the sum of the weights of its
517 // members (one weight per pair; the weight of each member of the pair
518 // is assumed to be the same). This length is then compared to the
519 // chain-length threshold to determine if a given chain is significant
520 // enough to be vectorized. The length is also used in comparing
521 // candidate chains where longer chains are considered to be better.
522 // Note: when this function returns 0, the resulting instructions are
523 // not actually fused.
524 inline size_t getDepthFactor(Value *V) {
525 // InsertElement and ExtractElement have a depth factor of zero. This is
526 // for two reasons: First, they cannot be usefully fused. Second, because
527 // the pass generates a lot of these, they can confuse the simple metric
528 // used to compare the dags in the next iteration. Thus, giving them a
529 // weight of zero allows the pass to essentially ignore them in
530 // subsequent iterations when looking for vectorization opportunities
531 // while still tracking dependency chains that flow through those
533 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
536 // Give a load or store half of the required depth so that load/store
537 // pairs will vectorize.
538 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
539 return Config.ReqChainDepth/2;
544 // Returns the cost of the provided instruction using TTI.
545 // This does not handle loads and stores.
546 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
547 TargetTransformInfo::OperandValueKind Op1VK =
548 TargetTransformInfo::OK_AnyValue,
549 TargetTransformInfo::OperandValueKind Op2VK =
550 TargetTransformInfo::OK_AnyValue) {
553 case Instruction::GetElementPtr:
554 // We mark this instruction as zero-cost because scalar GEPs are usually
555 // lowered to the instruction addressing mode. At the moment we don't
556 // generate vector GEPs.
558 case Instruction::Br:
559 return TTI->getCFInstrCost(Opcode);
560 case Instruction::PHI:
562 case Instruction::Add:
563 case Instruction::FAdd:
564 case Instruction::Sub:
565 case Instruction::FSub:
566 case Instruction::Mul:
567 case Instruction::FMul:
568 case Instruction::UDiv:
569 case Instruction::SDiv:
570 case Instruction::FDiv:
571 case Instruction::URem:
572 case Instruction::SRem:
573 case Instruction::FRem:
574 case Instruction::Shl:
575 case Instruction::LShr:
576 case Instruction::AShr:
577 case Instruction::And:
578 case Instruction::Or:
579 case Instruction::Xor:
580 return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
581 case Instruction::Select:
582 case Instruction::ICmp:
583 case Instruction::FCmp:
584 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
585 case Instruction::ZExt:
586 case Instruction::SExt:
587 case Instruction::FPToUI:
588 case Instruction::FPToSI:
589 case Instruction::FPExt:
590 case Instruction::PtrToInt:
591 case Instruction::IntToPtr:
592 case Instruction::SIToFP:
593 case Instruction::UIToFP:
594 case Instruction::Trunc:
595 case Instruction::FPTrunc:
596 case Instruction::BitCast:
597 case Instruction::ShuffleVector:
598 return TTI->getCastInstrCost(Opcode, T1, T2);
604 // This determines the relative offset of two loads or stores, returning
605 // true if the offset could be determined to be some constant value.
606 // For example, if OffsetInElmts == 1, then J accesses the memory directly
607 // after I; if OffsetInElmts == -1 then I accesses the memory
609 bool getPairPtrInfo(Instruction *I, Instruction *J,
610 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
611 unsigned &IAddressSpace, unsigned &JAddressSpace,
612 int64_t &OffsetInElmts, bool ComputeOffset = true) {
614 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
615 LoadInst *LJ = cast<LoadInst>(J);
616 IPtr = LI->getPointerOperand();
617 JPtr = LJ->getPointerOperand();
618 IAlignment = LI->getAlignment();
619 JAlignment = LJ->getAlignment();
620 IAddressSpace = LI->getPointerAddressSpace();
621 JAddressSpace = LJ->getPointerAddressSpace();
623 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
624 IPtr = SI->getPointerOperand();
625 JPtr = SJ->getPointerOperand();
626 IAlignment = SI->getAlignment();
627 JAlignment = SJ->getAlignment();
628 IAddressSpace = SI->getPointerAddressSpace();
629 JAddressSpace = SJ->getPointerAddressSpace();
635 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
636 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
638 // If this is a trivial offset, then we'll get something like
639 // 1*sizeof(type). With target data, which we need anyway, this will get
640 // constant folded into a number.
641 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
642 if (const SCEVConstant *ConstOffSCEV =
643 dyn_cast<SCEVConstant>(OffsetSCEV)) {
644 ConstantInt *IntOff = ConstOffSCEV->getValue();
645 int64_t Offset = IntOff->getSExtValue();
646 const DataLayout &DL = I->getModule()->getDataLayout();
647 Type *VTy = IPtr->getType()->getPointerElementType();
648 int64_t VTyTSS = (int64_t)DL.getTypeStoreSize(VTy);
650 Type *VTy2 = JPtr->getType()->getPointerElementType();
651 if (VTy != VTy2 && Offset < 0) {
652 int64_t VTy2TSS = (int64_t)DL.getTypeStoreSize(VTy2);
653 OffsetInElmts = Offset/VTy2TSS;
654 return (std::abs(Offset) % VTy2TSS) == 0;
657 OffsetInElmts = Offset/VTyTSS;
658 return (std::abs(Offset) % VTyTSS) == 0;
664 // Returns true if the provided CallInst represents an intrinsic that can
666 bool isVectorizableIntrinsic(CallInst* I) {
667 Function *F = I->getCalledFunction();
668 if (!F) return false;
670 Intrinsic::ID IID = F->getIntrinsicID();
671 if (!IID) return false;
676 case Intrinsic::sqrt:
677 case Intrinsic::powi:
681 case Intrinsic::log2:
682 case Intrinsic::log10:
684 case Intrinsic::exp2:
686 case Intrinsic::round:
687 case Intrinsic::copysign:
688 case Intrinsic::ceil:
689 case Intrinsic::nearbyint:
690 case Intrinsic::rint:
691 case Intrinsic::trunc:
692 case Intrinsic::floor:
693 case Intrinsic::fabs:
694 case Intrinsic::minnum:
695 case Intrinsic::maxnum:
696 return Config.VectorizeMath;
697 case Intrinsic::bswap:
698 case Intrinsic::ctpop:
699 case Intrinsic::ctlz:
700 case Intrinsic::cttz:
701 return Config.VectorizeBitManipulations;
703 case Intrinsic::fmuladd:
704 return Config.VectorizeFMA;
708 bool isPureIEChain(InsertElementInst *IE) {
709 InsertElementInst *IENext = IE;
711 if (!isa<UndefValue>(IENext->getOperand(0)) &&
712 !isa<InsertElementInst>(IENext->getOperand(0))) {
716 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
722 // This function implements one vectorization iteration on the provided
723 // basic block. It returns true if the block is changed.
724 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
726 BasicBlock::iterator Start = BB.getFirstInsertionPt();
728 std::vector<Value *> AllPairableInsts;
729 DenseMap<Value *, Value *> AllChosenPairs;
730 DenseSet<ValuePair> AllFixedOrderPairs;
731 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
732 DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
733 AllConnectedPairDeps;
736 std::vector<Value *> PairableInsts;
737 DenseMap<Value *, std::vector<Value *> > CandidatePairs;
738 DenseSet<ValuePair> FixedOrderPairs;
739 DenseMap<ValuePair, int> CandidatePairCostSavings;
740 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
742 CandidatePairCostSavings,
743 PairableInsts, NonPow2Len);
744 if (PairableInsts.empty()) continue;
746 // Build the candidate pair set for faster lookups.
747 DenseSet<ValuePair> CandidatePairsSet;
748 for (DenseMap<Value *, std::vector<Value *> >::iterator I =
749 CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
750 for (std::vector<Value *>::iterator J = I->second.begin(),
751 JE = I->second.end(); J != JE; ++J)
752 CandidatePairsSet.insert(ValuePair(I->first, *J));
754 // Now we have a map of all of the pairable instructions and we need to
755 // select the best possible pairing. A good pairing is one such that the
756 // users of the pair are also paired. This defines a (directed) forest
757 // over the pairs such that two pairs are connected iff the second pair
760 // Note that it only matters that both members of the second pair use some
761 // element of the first pair (to allow for splatting).
763 DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
765 DenseMap<VPPair, unsigned> PairConnectionTypes;
766 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
767 PairableInsts, ConnectedPairs, PairConnectionTypes);
768 if (ConnectedPairs.empty()) continue;
770 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
771 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
773 for (std::vector<ValuePair>::iterator J = I->second.begin(),
774 JE = I->second.end(); J != JE; ++J)
775 ConnectedPairDeps[*J].push_back(I->first);
777 // Build the pairable-instruction dependency map
778 DenseSet<ValuePair> PairableInstUsers;
779 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
781 // There is now a graph of the connected pairs. For each variable, pick
782 // the pairing with the largest dag meeting the depth requirement on at
783 // least one branch. Then select all pairings that are part of that dag
784 // and remove them from the list of available pairings and pairable
787 DenseMap<Value *, Value *> ChosenPairs;
788 choosePairs(CandidatePairs, CandidatePairsSet,
789 CandidatePairCostSavings,
790 PairableInsts, FixedOrderPairs, PairConnectionTypes,
791 ConnectedPairs, ConnectedPairDeps,
792 PairableInstUsers, ChosenPairs);
794 if (ChosenPairs.empty()) continue;
795 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
796 PairableInsts.end());
797 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
799 // Only for the chosen pairs, propagate information on fixed-order pairs,
800 // pair connections, and their types to the data structures used by the
801 // pair fusion procedures.
802 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
803 IE = ChosenPairs.end(); I != IE; ++I) {
804 if (FixedOrderPairs.count(*I))
805 AllFixedOrderPairs.insert(*I);
806 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
807 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
809 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
811 DenseMap<VPPair, unsigned>::iterator K =
812 PairConnectionTypes.find(VPPair(*I, *J));
813 if (K != PairConnectionTypes.end()) {
814 AllPairConnectionTypes.insert(*K);
816 K = PairConnectionTypes.find(VPPair(*J, *I));
817 if (K != PairConnectionTypes.end())
818 AllPairConnectionTypes.insert(*K);
823 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
824 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
826 for (std::vector<ValuePair>::iterator J = I->second.begin(),
827 JE = I->second.end(); J != JE; ++J)
828 if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
829 AllConnectedPairs[I->first].push_back(*J);
830 AllConnectedPairDeps[*J].push_back(I->first);
832 } while (ShouldContinue);
834 if (AllChosenPairs.empty()) return false;
835 NumFusedOps += AllChosenPairs.size();
837 // A set of pairs has now been selected. It is now necessary to replace the
838 // paired instructions with vector instructions. For this procedure each
839 // operand must be replaced with a vector operand. This vector is formed
840 // by using build_vector on the old operands. The replaced values are then
841 // replaced with a vector_extract on the result. Subsequent optimization
842 // passes should coalesce the build/extract combinations.
844 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
845 AllPairConnectionTypes,
846 AllConnectedPairs, AllConnectedPairDeps);
848 // It is important to cleanup here so that future iterations of this
849 // function have less work to do.
850 (void)SimplifyInstructionsInBlock(&BB, TLI);
854 // This function returns true if the provided instruction is capable of being
855 // fused into a vector instruction. This determination is based only on the
856 // type and other attributes of the instruction.
857 bool BBVectorize::isInstVectorizable(Instruction *I,
858 bool &IsSimpleLoadStore) {
859 IsSimpleLoadStore = false;
861 if (CallInst *C = dyn_cast<CallInst>(I)) {
862 if (!isVectorizableIntrinsic(C))
864 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
865 // Vectorize simple loads if possbile:
866 IsSimpleLoadStore = L->isSimple();
867 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
869 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
870 // Vectorize simple stores if possbile:
871 IsSimpleLoadStore = S->isSimple();
872 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
874 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
875 // We can vectorize casts, but not casts of pointer types, etc.
876 if (!Config.VectorizeCasts)
879 Type *SrcTy = C->getSrcTy();
880 if (!SrcTy->isSingleValueType())
883 Type *DestTy = C->getDestTy();
884 if (!DestTy->isSingleValueType())
886 } else if (isa<SelectInst>(I)) {
887 if (!Config.VectorizeSelect)
889 } else if (isa<CmpInst>(I)) {
890 if (!Config.VectorizeCmp)
892 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
893 if (!Config.VectorizeGEP)
896 // Currently, vector GEPs exist only with one index.
897 if (G->getNumIndices() != 1)
899 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
900 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
905 getInstructionTypes(I, T1, T2);
907 // Not every type can be vectorized...
908 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
909 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
912 if (T1->getScalarSizeInBits() == 1) {
913 if (!Config.VectorizeBools)
916 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
920 if (T2->getScalarSizeInBits() == 1) {
921 if (!Config.VectorizeBools)
924 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
928 if (!Config.VectorizeFloats
929 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
932 // Don't vectorize target-specific types.
933 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
935 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
938 if (!Config.VectorizePointers && (T1->getScalarType()->isPointerTy() ||
939 T2->getScalarType()->isPointerTy()))
942 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
943 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
949 // This function returns true if the two provided instructions are compatible
950 // (meaning that they can be fused into a vector instruction). This assumes
951 // that I has already been determined to be vectorizable and that J is not
952 // in the use dag of I.
953 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
954 bool IsSimpleLoadStore, bool NonPow2Len,
955 int &CostSavings, int &FixedOrder) {
956 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
957 " <-> " << *J << "\n");
962 // Loads and stores can be merged if they have different alignments,
963 // but are otherwise the same.
964 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
965 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
968 Type *IT1, *IT2, *JT1, *JT2;
969 getInstructionTypes(I, IT1, IT2);
970 getInstructionTypes(J, JT1, JT2);
971 unsigned MaxTypeBits = std::max(
972 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
973 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
974 if (!TTI && MaxTypeBits > Config.VectorBits)
977 // FIXME: handle addsub-type operations!
979 if (IsSimpleLoadStore) {
981 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
982 int64_t OffsetInElmts = 0;
983 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
984 IAddressSpace, JAddressSpace, OffsetInElmts) &&
985 std::abs(OffsetInElmts) == 1) {
986 FixedOrder = (int) OffsetInElmts;
987 unsigned BottomAlignment = IAlignment;
988 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
990 Type *aTypeI = isa<StoreInst>(I) ?
991 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
992 Type *aTypeJ = isa<StoreInst>(J) ?
993 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
994 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
996 if (Config.AlignedOnly) {
997 // An aligned load or store is possible only if the instruction
998 // with the lower offset has an alignment suitable for the
1000 const DataLayout &DL = I->getModule()->getDataLayout();
1001 unsigned VecAlignment = DL.getPrefTypeAlignment(VType);
1002 if (BottomAlignment < VecAlignment)
1007 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
1008 IAlignment, IAddressSpace);
1009 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
1010 JAlignment, JAddressSpace);
1011 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
1015 ICost += TTI->getAddressComputationCost(aTypeI);
1016 JCost += TTI->getAddressComputationCost(aTypeJ);
1017 VCost += TTI->getAddressComputationCost(VType);
1019 if (VCost > ICost + JCost)
1022 // We don't want to fuse to a type that will be split, even
1023 // if the two input types will also be split and there is no other
1025 unsigned VParts = TTI->getNumberOfParts(VType);
1028 else if (!VParts && VCost == ICost + JCost)
1031 CostSavings = ICost + JCost - VCost;
1037 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1038 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1039 Type *VT1 = getVecTypeForPair(IT1, JT1),
1040 *VT2 = getVecTypeForPair(IT2, JT2);
1041 TargetTransformInfo::OperandValueKind Op1VK =
1042 TargetTransformInfo::OK_AnyValue;
1043 TargetTransformInfo::OperandValueKind Op2VK =
1044 TargetTransformInfo::OK_AnyValue;
1046 // On some targets (example X86) the cost of a vector shift may vary
1047 // depending on whether the second operand is a Uniform or
1048 // NonUniform Constant.
1049 switch (I->getOpcode()) {
1051 case Instruction::Shl:
1052 case Instruction::LShr:
1053 case Instruction::AShr:
1055 // If both I and J are scalar shifts by constant, then the
1056 // merged vector shift count would be either a constant splat value
1057 // or a non-uniform vector of constants.
1058 if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
1059 if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
1060 Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
1061 TargetTransformInfo::OK_NonUniformConstantValue;
1063 // Check for a splat of a constant or for a non uniform vector
1065 Value *IOp = I->getOperand(1);
1066 Value *JOp = J->getOperand(1);
1067 if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
1068 (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
1069 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1070 Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
1071 if (SplatValue != nullptr &&
1072 SplatValue == cast<Constant>(JOp)->getSplatValue())
1073 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
1078 // Note that this procedure is incorrect for insert and extract element
1079 // instructions (because combining these often results in a shuffle),
1080 // but this cost is ignored (because insert and extract element
1081 // instructions are assigned a zero depth factor and are not really
1082 // fused in general).
1083 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
1085 if (VCost > ICost + JCost)
1088 // We don't want to fuse to a type that will be split, even
1089 // if the two input types will also be split and there is no other
1091 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1092 VParts2 = TTI->getNumberOfParts(VT2);
1093 if (VParts1 > 1 || VParts2 > 1)
1095 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1098 CostSavings = ICost + JCost - VCost;
1101 // The powi,ctlz,cttz intrinsics are special because only the first
1102 // argument is vectorized, the second arguments must be equal.
1103 CallInst *CI = dyn_cast<CallInst>(I);
1105 if (CI && (FI = CI->getCalledFunction())) {
1106 Intrinsic::ID IID = FI->getIntrinsicID();
1107 if (IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1108 IID == Intrinsic::cttz) {
1109 Value *A1I = CI->getArgOperand(1),
1110 *A1J = cast<CallInst>(J)->getArgOperand(1);
1111 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1112 *A1JSCEV = SE->getSCEV(A1J);
1113 return (A1ISCEV == A1JSCEV);
1117 SmallVector<Type*, 4> Tys;
1118 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1119 Tys.push_back(CI->getArgOperand(i)->getType());
1120 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1123 CallInst *CJ = cast<CallInst>(J);
1124 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1125 Tys.push_back(CJ->getArgOperand(i)->getType());
1126 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1129 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1130 "Intrinsic argument counts differ");
1131 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1132 if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1133 IID == Intrinsic::cttz) && i == 1)
1134 Tys.push_back(CI->getArgOperand(i)->getType());
1136 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1137 CJ->getArgOperand(i)->getType()));
1140 Type *RetTy = getVecTypeForPair(IT1, JT1);
1141 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1143 if (VCost > ICost + JCost)
1146 // We don't want to fuse to a type that will be split, even
1147 // if the two input types will also be split and there is no other
1149 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1152 else if (!RetParts && VCost == ICost + JCost)
1155 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1156 if (!Tys[i]->isVectorTy())
1159 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1162 else if (!NumParts && VCost == ICost + JCost)
1166 CostSavings = ICost + JCost - VCost;
1173 // Figure out whether or not J uses I and update the users and write-set
1174 // structures associated with I. Specifically, Users represents the set of
1175 // instructions that depend on I. WriteSet represents the set
1176 // of memory locations that are dependent on I. If UpdateUsers is true,
1177 // and J uses I, then Users is updated to contain J and WriteSet is updated
1178 // to contain any memory locations to which J writes. The function returns
1179 // true if J uses I. By default, alias analysis is used to determine
1180 // whether J reads from memory that overlaps with a location in WriteSet.
1181 // If LoadMoveSet is not null, then it is a previously-computed map
1182 // where the key is the memory-based user instruction and the value is
1183 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1184 // then the alias analysis is not used. This is necessary because this
1185 // function is called during the process of moving instructions during
1186 // vectorization and the results of the alias analysis are not stable during
1188 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1189 AliasSetTracker &WriteSet, Instruction *I,
1190 Instruction *J, bool UpdateUsers,
1191 DenseSet<ValuePair> *LoadMoveSetPairs) {
1194 // This instruction may already be marked as a user due, for example, to
1195 // being a member of a selected pair.
1200 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1203 if (I == V || Users.count(V)) {
1208 if (!UsesI && J->mayReadFromMemory()) {
1209 if (LoadMoveSetPairs) {
1210 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1212 for (AliasSetTracker::iterator W = WriteSet.begin(),
1213 WE = WriteSet.end(); W != WE; ++W) {
1214 if (W->aliasesUnknownInst(J, *AA)) {
1222 if (UsesI && UpdateUsers) {
1223 if (J->mayWriteToMemory()) WriteSet.add(J);
1230 // This function iterates over all instruction pairs in the provided
1231 // basic block and collects all candidate pairs for vectorization.
1232 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1233 BasicBlock::iterator &Start,
1234 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1235 DenseSet<ValuePair> &FixedOrderPairs,
1236 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1237 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1238 size_t TotalPairs = 0;
1239 BasicBlock::iterator E = BB.end();
1240 if (Start == E) return false;
1242 bool ShouldContinue = false, IAfterStart = false;
1243 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1244 if (I == Start) IAfterStart = true;
1246 bool IsSimpleLoadStore;
1247 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1249 // Look for an instruction with which to pair instruction *I...
1250 DenseSet<Value *> Users;
1251 AliasSetTracker WriteSet(*AA);
1252 if (I->mayWriteToMemory()) WriteSet.add(I);
1254 bool JAfterStart = IAfterStart;
1255 BasicBlock::iterator J = std::next(I);
1256 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1257 if (J == Start) JAfterStart = true;
1259 // Determine if J uses I, if so, exit the loop.
1260 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1261 if (Config.FastDep) {
1262 // Note: For this heuristic to be effective, independent operations
1263 // must tend to be intermixed. This is likely to be true from some
1264 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1265 // but otherwise may require some kind of reordering pass.
1267 // When using fast dependency analysis,
1268 // stop searching after first use:
1271 if (UsesI) continue;
1274 // J does not use I, and comes before the first use of I, so it can be
1275 // merged with I if the instructions are compatible.
1276 int CostSavings, FixedOrder;
1277 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1278 CostSavings, FixedOrder)) continue;
1280 // J is a candidate for merging with I.
1281 if (PairableInsts.empty() ||
1282 PairableInsts[PairableInsts.size()-1] != I) {
1283 PairableInsts.push_back(I);
1286 CandidatePairs[I].push_back(J);
1289 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1292 if (FixedOrder == 1)
1293 FixedOrderPairs.insert(ValuePair(I, J));
1294 else if (FixedOrder == -1)
1295 FixedOrderPairs.insert(ValuePair(J, I));
1297 // The next call to this function must start after the last instruction
1298 // selected during this invocation.
1300 Start = std::next(J);
1301 IAfterStart = JAfterStart = false;
1304 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1305 << *I << " <-> " << *J << " (cost savings: " <<
1306 CostSavings << ")\n");
1308 // If we have already found too many pairs, break here and this function
1309 // will be called again starting after the last instruction selected
1310 // during this invocation.
1311 if (PairableInsts.size() >= Config.MaxInsts ||
1312 TotalPairs >= Config.MaxPairs) {
1313 ShouldContinue = true;
1322 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1323 << " instructions with candidate pairs\n");
1325 return ShouldContinue;
1328 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1329 // it looks for pairs such that both members have an input which is an
1330 // output of PI or PJ.
1331 void BBVectorize::computePairsConnectedTo(
1332 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1333 DenseSet<ValuePair> &CandidatePairsSet,
1334 std::vector<Value *> &PairableInsts,
1335 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1336 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1340 // For each possible pairing for this variable, look at the uses of
1341 // the first value...
1342 for (Value::user_iterator I = P.first->user_begin(),
1343 E = P.first->user_end();
1346 if (isa<LoadInst>(UI)) {
1347 // A pair cannot be connected to a load because the load only takes one
1348 // operand (the address) and it is a scalar even after vectorization.
1350 } else if ((SI = dyn_cast<StoreInst>(UI)) &&
1351 P.first == SI->getPointerOperand()) {
1352 // Similarly, a pair cannot be connected to a store through its
1357 // For each use of the first variable, look for uses of the second
1359 for (User *UJ : P.second->users()) {
1360 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1361 P.second == SJ->getPointerOperand())
1365 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1366 VPPair VP(P, ValuePair(UI, UJ));
1367 ConnectedPairs[VP.first].push_back(VP.second);
1368 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1372 if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
1373 VPPair VP(P, ValuePair(UJ, UI));
1374 ConnectedPairs[VP.first].push_back(VP.second);
1375 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1379 if (Config.SplatBreaksChain) continue;
1380 // Look for cases where just the first value in the pair is used by
1381 // both members of another pair (splatting).
1382 for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
1384 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1385 P.first == SJ->getPointerOperand())
1388 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1389 VPPair VP(P, ValuePair(UI, UJ));
1390 ConnectedPairs[VP.first].push_back(VP.second);
1391 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1396 if (Config.SplatBreaksChain) return;
1397 // Look for cases where just the second value in the pair is used by
1398 // both members of another pair (splatting).
1399 for (Value::user_iterator I = P.second->user_begin(),
1400 E = P.second->user_end();
1403 if (isa<LoadInst>(UI))
1405 else if ((SI = dyn_cast<StoreInst>(UI)) &&
1406 P.second == SI->getPointerOperand())
1409 for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
1411 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1412 P.second == SJ->getPointerOperand())
1415 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1416 VPPair VP(P, ValuePair(UI, UJ));
1417 ConnectedPairs[VP.first].push_back(VP.second);
1418 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1424 // This function figures out which pairs are connected. Two pairs are
1425 // connected if some output of the first pair forms an input to both members
1426 // of the second pair.
1427 void BBVectorize::computeConnectedPairs(
1428 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1429 DenseSet<ValuePair> &CandidatePairsSet,
1430 std::vector<Value *> &PairableInsts,
1431 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1432 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1433 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1434 PE = PairableInsts.end(); PI != PE; ++PI) {
1435 DenseMap<Value *, std::vector<Value *> >::iterator PP =
1436 CandidatePairs.find(*PI);
1437 if (PP == CandidatePairs.end())
1440 for (std::vector<Value *>::iterator P = PP->second.begin(),
1441 E = PP->second.end(); P != E; ++P)
1442 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1443 PairableInsts, ConnectedPairs,
1444 PairConnectionTypes, ValuePair(*PI, *P));
1447 DEBUG(size_t TotalPairs = 0;
1448 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1449 ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1450 TotalPairs += I->second.size();
1451 dbgs() << "BBV: found " << TotalPairs
1452 << " pair connections.\n");
1455 // This function builds a set of use tuples such that <A, B> is in the set
1456 // if B is in the use dag of A. If B is in the use dag of A, then B
1457 // depends on the output of A.
1458 void BBVectorize::buildDepMap(
1460 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1461 std::vector<Value *> &PairableInsts,
1462 DenseSet<ValuePair> &PairableInstUsers) {
1463 DenseSet<Value *> IsInPair;
1464 for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1465 CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1466 IsInPair.insert(C->first);
1467 IsInPair.insert(C->second.begin(), C->second.end());
1470 // Iterate through the basic block, recording all users of each
1471 // pairable instruction.
1473 BasicBlock::iterator E = BB.end(), EL =
1474 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1475 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1476 if (IsInPair.find(I) == IsInPair.end()) continue;
1478 DenseSet<Value *> Users;
1479 AliasSetTracker WriteSet(*AA);
1480 if (I->mayWriteToMemory()) WriteSet.add(I);
1482 for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
1483 (void) trackUsesOfI(Users, WriteSet, I, J);
1489 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1491 if (IsInPair.find(*U) == IsInPair.end()) continue;
1492 PairableInstUsers.insert(ValuePair(I, *U));
1500 // Returns true if an input to pair P is an output of pair Q and also an
1501 // input of pair Q is an output of pair P. If this is the case, then these
1502 // two pairs cannot be simultaneously fused.
1503 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1504 DenseSet<ValuePair> &PairableInstUsers,
1505 DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1506 DenseSet<VPPair> *PairableInstUserPairSet) {
1507 // Two pairs are in conflict if they are mutual Users of eachother.
1508 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1509 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1510 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1511 PairableInstUsers.count(ValuePair(P.second, Q.second));
1512 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1513 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1514 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1515 PairableInstUsers.count(ValuePair(Q.second, P.second));
1516 if (PairableInstUserMap) {
1517 // FIXME: The expensive part of the cycle check is not so much the cycle
1518 // check itself but this edge insertion procedure. This needs some
1519 // profiling and probably a different data structure.
1521 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1522 (*PairableInstUserMap)[Q].push_back(P);
1525 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1526 (*PairableInstUserMap)[P].push_back(Q);
1530 return (QUsesP && PUsesQ);
1533 // This function walks the use graph of current pairs to see if, starting
1534 // from P, the walk returns to P.
1535 bool BBVectorize::pairWillFormCycle(ValuePair P,
1536 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1537 DenseSet<ValuePair> &CurrentPairs) {
1538 DEBUG(if (DebugCycleCheck)
1539 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1540 << *P.second << "\n");
1541 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1542 // contains non-direct associations.
1543 DenseSet<ValuePair> Visited;
1544 SmallVector<ValuePair, 32> Q;
1545 // General depth-first post-order traversal:
1548 ValuePair QTop = Q.pop_back_val();
1549 Visited.insert(QTop);
1551 DEBUG(if (DebugCycleCheck)
1552 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1553 << *QTop.second << "\n");
1554 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1555 PairableInstUserMap.find(QTop);
1556 if (QQ == PairableInstUserMap.end())
1559 for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1560 CE = QQ->second.end(); C != CE; ++C) {
1563 << "BBV: rejected to prevent non-trivial cycle formation: "
1564 << QTop.first << " <-> " << C->second << "\n");
1568 if (CurrentPairs.count(*C) && !Visited.count(*C))
1571 } while (!Q.empty());
1576 // This function builds the initial dag of connected pairs with the
1577 // pair J at the root.
1578 void BBVectorize::buildInitialDAGFor(
1579 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1580 DenseSet<ValuePair> &CandidatePairsSet,
1581 std::vector<Value *> &PairableInsts,
1582 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1583 DenseSet<ValuePair> &PairableInstUsers,
1584 DenseMap<Value *, Value *> &ChosenPairs,
1585 DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1586 // Each of these pairs is viewed as the root node of a DAG. The DAG
1587 // is then walked (depth-first). As this happens, we keep track of
1588 // the pairs that compose the DAG and the maximum depth of the DAG.
1589 SmallVector<ValuePairWithDepth, 32> Q;
1590 // General depth-first post-order traversal:
1591 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1593 ValuePairWithDepth QTop = Q.back();
1595 // Push each child onto the queue:
1596 bool MoreChildren = false;
1597 size_t MaxChildDepth = QTop.second;
1598 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1599 ConnectedPairs.find(QTop.first);
1600 if (QQ != ConnectedPairs.end())
1601 for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1602 ke = QQ->second.end(); k != ke; ++k) {
1603 // Make sure that this child pair is still a candidate:
1604 if (CandidatePairsSet.count(*k)) {
1605 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
1606 if (C == DAG.end()) {
1607 size_t d = getDepthFactor(k->first);
1608 Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1609 MoreChildren = true;
1611 MaxChildDepth = std::max(MaxChildDepth, C->second);
1616 if (!MoreChildren) {
1617 // Record the current pair as part of the DAG:
1618 DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1621 } while (!Q.empty());
1624 // Given some initial dag, prune it by removing conflicting pairs (pairs
1625 // that cannot be simultaneously chosen for vectorization).
1626 void BBVectorize::pruneDAGFor(
1627 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1628 std::vector<Value *> &PairableInsts,
1629 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1630 DenseSet<ValuePair> &PairableInstUsers,
1631 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1632 DenseSet<VPPair> &PairableInstUserPairSet,
1633 DenseMap<Value *, Value *> &ChosenPairs,
1634 DenseMap<ValuePair, size_t> &DAG,
1635 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1636 bool UseCycleCheck) {
1637 SmallVector<ValuePairWithDepth, 32> Q;
1638 // General depth-first post-order traversal:
1639 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1641 ValuePairWithDepth QTop = Q.pop_back_val();
1642 PrunedDAG.insert(QTop.first);
1644 // Visit each child, pruning as necessary...
1645 SmallVector<ValuePairWithDepth, 8> BestChildren;
1646 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1647 ConnectedPairs.find(QTop.first);
1648 if (QQ == ConnectedPairs.end())
1651 for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1652 KE = QQ->second.end(); K != KE; ++K) {
1653 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
1654 if (C == DAG.end()) continue;
1656 // This child is in the DAG, now we need to make sure it is the
1657 // best of any conflicting children. There could be multiple
1658 // conflicting children, so first, determine if we're keeping
1659 // this child, then delete conflicting children as necessary.
1661 // It is also necessary to guard against pairing-induced
1662 // dependencies. Consider instructions a .. x .. y .. b
1663 // such that (a,b) are to be fused and (x,y) are to be fused
1664 // but a is an input to x and b is an output from y. This
1665 // means that y cannot be moved after b but x must be moved
1666 // after b for (a,b) to be fused. In other words, after
1667 // fusing (a,b) we have y .. a/b .. x where y is an input
1668 // to a/b and x is an output to a/b: x and y can no longer
1669 // be legally fused. To prevent this condition, we must
1670 // make sure that a child pair added to the DAG is not
1671 // both an input and output of an already-selected pair.
1673 // Pairing-induced dependencies can also form from more complicated
1674 // cycles. The pair vs. pair conflicts are easy to check, and so
1675 // that is done explicitly for "fast rejection", and because for
1676 // child vs. child conflicts, we may prefer to keep the current
1677 // pair in preference to the already-selected child.
1678 DenseSet<ValuePair> CurrentPairs;
1681 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1682 = BestChildren.begin(), E2 = BestChildren.end();
1684 if (C2->first.first == C->first.first ||
1685 C2->first.first == C->first.second ||
1686 C2->first.second == C->first.first ||
1687 C2->first.second == C->first.second ||
1688 pairsConflict(C2->first, C->first, PairableInstUsers,
1689 UseCycleCheck ? &PairableInstUserMap : nullptr,
1690 UseCycleCheck ? &PairableInstUserPairSet
1692 if (C2->second >= C->second) {
1697 CurrentPairs.insert(C2->first);
1700 if (!CanAdd) continue;
1702 // Even worse, this child could conflict with another node already
1703 // selected for the DAG. If that is the case, ignore this child.
1704 for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1705 E2 = PrunedDAG.end(); T != E2; ++T) {
1706 if (T->first == C->first.first ||
1707 T->first == C->first.second ||
1708 T->second == C->first.first ||
1709 T->second == C->first.second ||
1710 pairsConflict(*T, C->first, PairableInstUsers,
1711 UseCycleCheck ? &PairableInstUserMap : nullptr,
1712 UseCycleCheck ? &PairableInstUserPairSet
1718 CurrentPairs.insert(*T);
1720 if (!CanAdd) continue;
1722 // And check the queue too...
1723 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
1724 E2 = Q.end(); C2 != E2; ++C2) {
1725 if (C2->first.first == C->first.first ||
1726 C2->first.first == C->first.second ||
1727 C2->first.second == C->first.first ||
1728 C2->first.second == C->first.second ||
1729 pairsConflict(C2->first, C->first, PairableInstUsers,
1730 UseCycleCheck ? &PairableInstUserMap : nullptr,
1731 UseCycleCheck ? &PairableInstUserPairSet
1737 CurrentPairs.insert(C2->first);
1739 if (!CanAdd) continue;
1741 // Last but not least, check for a conflict with any of the
1742 // already-chosen pairs.
1743 for (DenseMap<Value *, Value *>::iterator C2 =
1744 ChosenPairs.begin(), E2 = ChosenPairs.end();
1746 if (pairsConflict(*C2, C->first, PairableInstUsers,
1747 UseCycleCheck ? &PairableInstUserMap : nullptr,
1748 UseCycleCheck ? &PairableInstUserPairSet
1754 CurrentPairs.insert(*C2);
1756 if (!CanAdd) continue;
1758 // To check for non-trivial cycles formed by the addition of the
1759 // current pair we've formed a list of all relevant pairs, now use a
1760 // graph walk to check for a cycle. We start from the current pair and
1761 // walk the use dag to see if we again reach the current pair. If we
1762 // do, then the current pair is rejected.
1764 // FIXME: It may be more efficient to use a topological-ordering
1765 // algorithm to improve the cycle check. This should be investigated.
1766 if (UseCycleCheck &&
1767 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1770 // This child can be added, but we may have chosen it in preference
1771 // to an already-selected child. Check for this here, and if a
1772 // conflict is found, then remove the previously-selected child
1773 // before adding this one in its place.
1774 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1775 = BestChildren.begin(); C2 != BestChildren.end();) {
1776 if (C2->first.first == C->first.first ||
1777 C2->first.first == C->first.second ||
1778 C2->first.second == C->first.first ||
1779 C2->first.second == C->first.second ||
1780 pairsConflict(C2->first, C->first, PairableInstUsers))
1781 C2 = BestChildren.erase(C2);
1786 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1789 for (SmallVectorImpl<ValuePairWithDepth>::iterator C
1790 = BestChildren.begin(), E2 = BestChildren.end();
1792 size_t DepthF = getDepthFactor(C->first.first);
1793 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1795 } while (!Q.empty());
1798 // This function finds the best dag of mututally-compatible connected
1799 // pairs, given the choice of root pairs as an iterator range.
1800 void BBVectorize::findBestDAGFor(
1801 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1802 DenseSet<ValuePair> &CandidatePairsSet,
1803 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1804 std::vector<Value *> &PairableInsts,
1805 DenseSet<ValuePair> &FixedOrderPairs,
1806 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1807 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1808 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1809 DenseSet<ValuePair> &PairableInstUsers,
1810 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1811 DenseSet<VPPair> &PairableInstUserPairSet,
1812 DenseMap<Value *, Value *> &ChosenPairs,
1813 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1814 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1815 bool UseCycleCheck) {
1816 for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1818 ValuePair IJ(II, *J);
1819 if (!CandidatePairsSet.count(IJ))
1822 // Before going any further, make sure that this pair does not
1823 // conflict with any already-selected pairs (see comment below
1824 // near the DAG pruning for more details).
1825 DenseSet<ValuePair> ChosenPairSet;
1826 bool DoesConflict = false;
1827 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1828 E = ChosenPairs.end(); C != E; ++C) {
1829 if (pairsConflict(*C, IJ, PairableInstUsers,
1830 UseCycleCheck ? &PairableInstUserMap : nullptr,
1831 UseCycleCheck ? &PairableInstUserPairSet : nullptr)) {
1832 DoesConflict = true;
1836 ChosenPairSet.insert(*C);
1838 if (DoesConflict) continue;
1840 if (UseCycleCheck &&
1841 pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1844 DenseMap<ValuePair, size_t> DAG;
1845 buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1846 PairableInsts, ConnectedPairs,
1847 PairableInstUsers, ChosenPairs, DAG, IJ);
1849 // Because we'll keep the child with the largest depth, the largest
1850 // depth is still the same in the unpruned DAG.
1851 size_t MaxDepth = DAG.lookup(IJ);
1853 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1854 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1855 MaxDepth << " and size " << DAG.size() << "\n");
1857 // At this point the DAG has been constructed, but, may contain
1858 // contradictory children (meaning that different children of
1859 // some dag node may be attempting to fuse the same instruction).
1860 // So now we walk the dag again, in the case of a conflict,
1861 // keep only the child with the largest depth. To break a tie,
1862 // favor the first child.
1864 DenseSet<ValuePair> PrunedDAG;
1865 pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1866 PairableInstUsers, PairableInstUserMap,
1867 PairableInstUserPairSet,
1868 ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1872 DenseSet<Value *> PrunedDAGInstrs;
1873 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1874 E = PrunedDAG.end(); S != E; ++S) {
1875 PrunedDAGInstrs.insert(S->first);
1876 PrunedDAGInstrs.insert(S->second);
1879 // The set of pairs that have already contributed to the total cost.
1880 DenseSet<ValuePair> IncomingPairs;
1882 // If the cost model were perfect, this might not be necessary; but we
1883 // need to make sure that we don't get stuck vectorizing our own
1885 bool HasNontrivialInsts = false;
1887 // The node weights represent the cost savings associated with
1888 // fusing the pair of instructions.
1889 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1890 E = PrunedDAG.end(); S != E; ++S) {
1891 if (!isa<ShuffleVectorInst>(S->first) &&
1892 !isa<InsertElementInst>(S->first) &&
1893 !isa<ExtractElementInst>(S->first))
1894 HasNontrivialInsts = true;
1896 bool FlipOrder = false;
1898 if (getDepthFactor(S->first)) {
1899 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1900 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1901 << *S->first << " <-> " << *S->second << "} = " <<
1903 EffSize += ESContrib;
1906 // The edge weights contribute in a negative sense: they represent
1907 // the cost of shuffles.
1908 DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1909 ConnectedPairDeps.find(*S);
1910 if (SS != ConnectedPairDeps.end()) {
1911 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1912 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1913 TE = SS->second.end(); T != TE; ++T) {
1915 if (!PrunedDAG.count(Q.second))
1917 DenseMap<VPPair, unsigned>::iterator R =
1918 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1919 assert(R != PairConnectionTypes.end() &&
1920 "Cannot find pair connection type");
1921 if (R->second == PairConnectionDirect)
1923 else if (R->second == PairConnectionSwap)
1927 // If there are more swaps than direct connections, then
1928 // the pair order will be flipped during fusion. So the real
1929 // number of swaps is the minimum number.
1930 FlipOrder = !FixedOrderPairs.count(*S) &&
1931 ((NumDepsSwap > NumDepsDirect) ||
1932 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1934 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1935 TE = SS->second.end(); T != TE; ++T) {
1937 if (!PrunedDAG.count(Q.second))
1939 DenseMap<VPPair, unsigned>::iterator R =
1940 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1941 assert(R != PairConnectionTypes.end() &&
1942 "Cannot find pair connection type");
1943 Type *Ty1 = Q.second.first->getType(),
1944 *Ty2 = Q.second.second->getType();
1945 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1946 if ((R->second == PairConnectionDirect && FlipOrder) ||
1947 (R->second == PairConnectionSwap && !FlipOrder) ||
1948 R->second == PairConnectionSplat) {
1949 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1952 if (VTy->getVectorNumElements() == 2) {
1953 if (R->second == PairConnectionSplat)
1954 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1955 TargetTransformInfo::SK_Broadcast, VTy));
1957 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1958 TargetTransformInfo::SK_Reverse, VTy));
1961 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1962 *Q.second.first << " <-> " << *Q.second.second <<
1964 *S->first << " <-> " << *S->second << "} = " <<
1966 EffSize -= ESContrib;
1971 // Compute the cost of outgoing edges. We assume that edges outgoing
1972 // to shuffles, inserts or extracts can be merged, and so contribute
1973 // no additional cost.
1974 if (!S->first->getType()->isVoidTy()) {
1975 Type *Ty1 = S->first->getType(),
1976 *Ty2 = S->second->getType();
1977 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1979 bool NeedsExtraction = false;
1980 for (User *U : S->first->users()) {
1981 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
1982 // Shuffle can be folded if it has no other input
1983 if (isa<UndefValue>(SI->getOperand(1)))
1986 if (isa<ExtractElementInst>(U))
1988 if (PrunedDAGInstrs.count(U))
1990 NeedsExtraction = true;
1994 if (NeedsExtraction) {
1996 if (Ty1->isVectorTy()) {
1997 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1999 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2000 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
2002 ESContrib = (int) TTI->getVectorInstrCost(
2003 Instruction::ExtractElement, VTy, 0);
2005 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2006 *S->first << "} = " << ESContrib << "\n");
2007 EffSize -= ESContrib;
2010 NeedsExtraction = false;
2011 for (User *U : S->second->users()) {
2012 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
2013 // Shuffle can be folded if it has no other input
2014 if (isa<UndefValue>(SI->getOperand(1)))
2017 if (isa<ExtractElementInst>(U))
2019 if (PrunedDAGInstrs.count(U))
2021 NeedsExtraction = true;
2025 if (NeedsExtraction) {
2027 if (Ty2->isVectorTy()) {
2028 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2030 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2031 TargetTransformInfo::SK_ExtractSubvector, VTy,
2032 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
2034 ESContrib = (int) TTI->getVectorInstrCost(
2035 Instruction::ExtractElement, VTy, 1);
2036 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2037 *S->second << "} = " << ESContrib << "\n");
2038 EffSize -= ESContrib;
2042 // Compute the cost of incoming edges.
2043 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
2044 Instruction *S1 = cast<Instruction>(S->first),
2045 *S2 = cast<Instruction>(S->second);
2046 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
2047 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
2049 // Combining constants into vector constants (or small vector
2050 // constants into larger ones are assumed free).
2051 if (isa<Constant>(O1) && isa<Constant>(O2))
2057 ValuePair VP = ValuePair(O1, O2);
2058 ValuePair VPR = ValuePair(O2, O1);
2060 // Internal edges are not handled here.
2061 if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
2064 Type *Ty1 = O1->getType(),
2065 *Ty2 = O2->getType();
2066 Type *VTy = getVecTypeForPair(Ty1, Ty2);
2068 // Combining vector operations of the same type is also assumed
2069 // folded with other operations.
2071 // If both are insert elements, then both can be widened.
2072 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
2073 *IEO2 = dyn_cast<InsertElementInst>(O2);
2074 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
2076 // If both are extract elements, and both have the same input
2077 // type, then they can be replaced with a shuffle
2078 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2079 *EIO2 = dyn_cast<ExtractElementInst>(O2);
2081 EIO1->getOperand(0)->getType() ==
2082 EIO2->getOperand(0)->getType())
2084 // If both are a shuffle with equal operand types and only two
2085 // unqiue operands, then they can be replaced with a single
2087 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2088 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2090 SIO1->getOperand(0)->getType() ==
2091 SIO2->getOperand(0)->getType()) {
2092 SmallSet<Value *, 4> SIOps;
2093 SIOps.insert(SIO1->getOperand(0));
2094 SIOps.insert(SIO1->getOperand(1));
2095 SIOps.insert(SIO2->getOperand(0));
2096 SIOps.insert(SIO2->getOperand(1));
2097 if (SIOps.size() <= 2)
2103 // This pair has already been formed.
2104 if (IncomingPairs.count(VP)) {
2106 } else if (IncomingPairs.count(VPR)) {
2107 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2110 if (VTy->getVectorNumElements() == 2)
2111 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2112 TargetTransformInfo::SK_Reverse, VTy));
2113 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2114 ESContrib = (int) TTI->getVectorInstrCost(
2115 Instruction::InsertElement, VTy, 0);
2116 ESContrib += (int) TTI->getVectorInstrCost(
2117 Instruction::InsertElement, VTy, 1);
2118 } else if (!Ty1->isVectorTy()) {
2119 // O1 needs to be inserted into a vector of size O2, and then
2120 // both need to be shuffled together.
2121 ESContrib = (int) TTI->getVectorInstrCost(
2122 Instruction::InsertElement, Ty2, 0);
2123 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2125 } else if (!Ty2->isVectorTy()) {
2126 // O2 needs to be inserted into a vector of size O1, and then
2127 // both need to be shuffled together.
2128 ESContrib = (int) TTI->getVectorInstrCost(
2129 Instruction::InsertElement, Ty1, 0);
2130 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2133 Type *TyBig = Ty1, *TySmall = Ty2;
2134 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2135 std::swap(TyBig, TySmall);
2137 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2139 if (TyBig != TySmall)
2140 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2144 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2145 << *O1 << " <-> " << *O2 << "} = " <<
2147 EffSize -= ESContrib;
2148 IncomingPairs.insert(VP);
2153 if (!HasNontrivialInsts) {
2154 DEBUG(if (DebugPairSelection) dbgs() <<
2155 "\tNo non-trivial instructions in DAG;"
2156 " override to zero effective size\n");
2160 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2161 E = PrunedDAG.end(); S != E; ++S)
2162 EffSize += (int) getDepthFactor(S->first);
2165 DEBUG(if (DebugPairSelection)
2166 dbgs() << "BBV: found pruned DAG for pair {"
2167 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2168 MaxDepth << " and size " << PrunedDAG.size() <<
2169 " (effective size: " << EffSize << ")\n");
2170 if (((TTI && !UseChainDepthWithTI) ||
2171 MaxDepth >= Config.ReqChainDepth) &&
2172 EffSize > 0 && EffSize > BestEffSize) {
2173 BestMaxDepth = MaxDepth;
2174 BestEffSize = EffSize;
2175 BestDAG = PrunedDAG;
2180 // Given the list of candidate pairs, this function selects those
2181 // that will be fused into vector instructions.
2182 void BBVectorize::choosePairs(
2183 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2184 DenseSet<ValuePair> &CandidatePairsSet,
2185 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2186 std::vector<Value *> &PairableInsts,
2187 DenseSet<ValuePair> &FixedOrderPairs,
2188 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2189 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2190 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2191 DenseSet<ValuePair> &PairableInstUsers,
2192 DenseMap<Value *, Value *>& ChosenPairs) {
2193 bool UseCycleCheck =
2194 CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2196 DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2197 for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2198 E = CandidatePairsSet.end(); I != E; ++I) {
2199 std::vector<Value *> &JJ = CandidatePairs2[I->second];
2200 if (JJ.empty()) JJ.reserve(32);
2201 JJ.push_back(I->first);
2204 DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2205 DenseSet<VPPair> PairableInstUserPairSet;
2206 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2207 E = PairableInsts.end(); I != E; ++I) {
2208 // The number of possible pairings for this variable:
2209 size_t NumChoices = CandidatePairs.lookup(*I).size();
2210 if (!NumChoices) continue;
2212 std::vector<Value *> &JJ = CandidatePairs[*I];
2214 // The best pair to choose and its dag:
2215 size_t BestMaxDepth = 0;
2216 int BestEffSize = 0;
2217 DenseSet<ValuePair> BestDAG;
2218 findBestDAGFor(CandidatePairs, CandidatePairsSet,
2219 CandidatePairCostSavings,
2220 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2221 ConnectedPairs, ConnectedPairDeps,
2222 PairableInstUsers, PairableInstUserMap,
2223 PairableInstUserPairSet, ChosenPairs,
2224 BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2227 if (BestDAG.empty())
2230 // A dag has been chosen (or not) at this point. If no dag was
2231 // chosen, then this instruction, I, cannot be paired (and is no longer
2234 DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2235 << *cast<Instruction>(*I) << "\n");
2237 for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2238 SE2 = BestDAG.end(); S != SE2; ++S) {
2239 // Insert the members of this dag into the list of chosen pairs.
2240 ChosenPairs.insert(ValuePair(S->first, S->second));
2241 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2242 *S->second << "\n");
2244 // Remove all candidate pairs that have values in the chosen dag.
2245 std::vector<Value *> &KK = CandidatePairs[S->first];
2246 for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2248 if (*K == S->second)
2251 CandidatePairsSet.erase(ValuePair(S->first, *K));
2254 std::vector<Value *> &LL = CandidatePairs2[S->second];
2255 for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2260 CandidatePairsSet.erase(ValuePair(*L, S->second));
2263 std::vector<Value *> &MM = CandidatePairs[S->second];
2264 for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2266 assert(*M != S->first && "Flipped pair in candidate list?");
2267 CandidatePairsSet.erase(ValuePair(S->second, *M));
2270 std::vector<Value *> &NN = CandidatePairs2[S->first];
2271 for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2273 assert(*N != S->second && "Flipped pair in candidate list?");
2274 CandidatePairsSet.erase(ValuePair(*N, S->first));
2279 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2282 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2287 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2288 (n > 0 ? "." + utostr(n) : "")).str();
2291 // Returns the value that is to be used as the pointer input to the vector
2292 // instruction that fuses I with J.
2293 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2294 Instruction *I, Instruction *J, unsigned o) {
2296 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2297 int64_t OffsetInElmts;
2299 // Note: the analysis might fail here, that is why the pair order has
2300 // been precomputed (OffsetInElmts must be unused here).
2301 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2302 IAddressSpace, JAddressSpace,
2303 OffsetInElmts, false);
2305 // The pointer value is taken to be the one with the lowest offset.
2308 Type *ArgTypeI = IPtr->getType()->getPointerElementType();
2309 Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
2310 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2312 = PointerType::get(VArgType,
2313 IPtr->getType()->getPointerAddressSpace());
2314 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2315 /* insert before */ I);
2318 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2319 unsigned MaskOffset, unsigned NumInElem,
2320 unsigned NumInElem1, unsigned IdxOffset,
2321 std::vector<Constant*> &Mask) {
2322 unsigned NumElem1 = J->getType()->getVectorNumElements();
2323 for (unsigned v = 0; v < NumElem1; ++v) {
2324 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2326 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2328 unsigned mm = m + (int) IdxOffset;
2329 if (m >= (int) NumInElem1)
2330 mm += (int) NumInElem;
2332 Mask[v+MaskOffset] =
2333 ConstantInt::get(Type::getInt32Ty(Context), mm);
2338 // Returns the value that is to be used as the vector-shuffle mask to the
2339 // vector instruction that fuses I with J.
2340 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2341 Instruction *I, Instruction *J) {
2342 // This is the shuffle mask. We need to append the second
2343 // mask to the first, and the numbers need to be adjusted.
2345 Type *ArgTypeI = I->getType();
2346 Type *ArgTypeJ = J->getType();
2347 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2349 unsigned NumElemI = ArgTypeI->getVectorNumElements();
2351 // Get the total number of elements in the fused vector type.
2352 // By definition, this must equal the number of elements in
2354 unsigned NumElem = VArgType->getVectorNumElements();
2355 std::vector<Constant*> Mask(NumElem);
2357 Type *OpTypeI = I->getOperand(0)->getType();
2358 unsigned NumInElemI = OpTypeI->getVectorNumElements();
2359 Type *OpTypeJ = J->getOperand(0)->getType();
2360 unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
2362 // The fused vector will be:
2363 // -----------------------------------------------------
2364 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2365 // -----------------------------------------------------
2366 // from which we'll extract NumElem total elements (where the first NumElemI
2367 // of them come from the mask in I and the remainder come from the mask
2370 // For the mask from the first pair...
2371 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2374 // For the mask from the second pair...
2375 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2378 return ConstantVector::get(Mask);
2381 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2382 Instruction *J, unsigned o, Value *&LOp,
2384 Type *ArgTypeL, Type *ArgTypeH,
2385 bool IBeforeJ, unsigned IdxOff) {
2386 bool ExpandedIEChain = false;
2387 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2388 // If we have a pure insertelement chain, then this can be rewritten
2389 // into a chain that directly builds the larger type.
2390 if (isPureIEChain(LIE)) {
2391 SmallVector<Value *, 8> VectElemts(numElemL,
2392 UndefValue::get(ArgTypeL->getScalarType()));
2393 InsertElementInst *LIENext = LIE;
2396 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2397 VectElemts[Idx] = LIENext->getOperand(1);
2399 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2402 Value *LIEPrev = UndefValue::get(ArgTypeH);
2403 for (unsigned i = 0; i < numElemL; ++i) {
2404 if (isa<UndefValue>(VectElemts[i])) continue;
2405 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2406 ConstantInt::get(Type::getInt32Ty(Context),
2408 getReplacementName(IBeforeJ ? I : J,
2410 LIENext->insertBefore(IBeforeJ ? J : I);
2414 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2415 ExpandedIEChain = true;
2419 return ExpandedIEChain;
2422 static unsigned getNumScalarElements(Type *Ty) {
2423 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
2424 return VecTy->getNumElements();
2428 // Returns the value to be used as the specified operand of the vector
2429 // instruction that fuses I with J.
2430 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2431 Instruction *J, unsigned o, bool IBeforeJ) {
2432 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2433 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2435 // Compute the fused vector type for this operand
2436 Type *ArgTypeI = I->getOperand(o)->getType();
2437 Type *ArgTypeJ = J->getOperand(o)->getType();
2438 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2440 Instruction *L = I, *H = J;
2441 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2443 unsigned numElemL = getNumScalarElements(ArgTypeL);
2444 unsigned numElemH = getNumScalarElements(ArgTypeH);
2446 Value *LOp = L->getOperand(o);
2447 Value *HOp = H->getOperand(o);
2448 unsigned numElem = VArgType->getNumElements();
2450 // First, we check if we can reuse the "original" vector outputs (if these
2451 // exist). We might need a shuffle.
2452 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2453 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2454 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2455 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2457 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2458 // optimization. The input vectors to the shuffle might be a different
2459 // length from the shuffle outputs. Unfortunately, the replacement
2460 // shuffle mask has already been formed, and the mask entries are sensitive
2461 // to the sizes of the inputs.
2462 bool IsSizeChangeShuffle =
2463 isa<ShuffleVectorInst>(L) &&
2464 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2466 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2467 // We can have at most two unique vector inputs.
2468 bool CanUseInputs = true;
2469 Value *I1, *I2 = nullptr;
2471 I1 = LEE->getOperand(0);
2473 I1 = LSV->getOperand(0);
2474 I2 = LSV->getOperand(1);
2475 if (I2 == I1 || isa<UndefValue>(I2))
2480 Value *I3 = HEE->getOperand(0);
2481 if (!I2 && I3 != I1)
2483 else if (I3 != I1 && I3 != I2)
2484 CanUseInputs = false;
2486 Value *I3 = HSV->getOperand(0);
2487 if (!I2 && I3 != I1)
2489 else if (I3 != I1 && I3 != I2)
2490 CanUseInputs = false;
2493 Value *I4 = HSV->getOperand(1);
2494 if (!isa<UndefValue>(I4)) {
2495 if (!I2 && I4 != I1)
2497 else if (I4 != I1 && I4 != I2)
2498 CanUseInputs = false;
2505 cast<Instruction>(LOp)->getOperand(0)->getType()
2506 ->getVectorNumElements();
2509 cast<Instruction>(HOp)->getOperand(0)->getType()
2510 ->getVectorNumElements();
2512 // We have one or two input vectors. We need to map each index of the
2513 // operands to the index of the original vector.
2514 SmallVector<std::pair<int, int>, 8> II(numElem);
2515 for (unsigned i = 0; i < numElemL; ++i) {
2519 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2520 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2522 Idx = LSV->getMaskValue(i);
2523 if (Idx < (int) LOpElem) {
2524 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2527 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2531 II[i] = std::pair<int, int>(Idx, INum);
2533 for (unsigned i = 0; i < numElemH; ++i) {
2537 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2538 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2540 Idx = HSV->getMaskValue(i);
2541 if (Idx < (int) HOpElem) {
2542 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2545 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2549 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2552 // We now have an array which tells us from which index of which
2553 // input vector each element of the operand comes.
2554 VectorType *I1T = cast<VectorType>(I1->getType());
2555 unsigned I1Elem = I1T->getNumElements();
2558 // In this case there is only one underlying vector input. Check for
2559 // the trivial case where we can use the input directly.
2560 if (I1Elem == numElem) {
2561 bool ElemInOrder = true;
2562 for (unsigned i = 0; i < numElem; ++i) {
2563 if (II[i].first != (int) i && II[i].first != -1) {
2564 ElemInOrder = false;
2573 // A shuffle is needed.
2574 std::vector<Constant *> Mask(numElem);
2575 for (unsigned i = 0; i < numElem; ++i) {
2576 int Idx = II[i].first;
2578 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2580 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2584 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2585 ConstantVector::get(Mask),
2586 getReplacementName(IBeforeJ ? I : J,
2588 S->insertBefore(IBeforeJ ? J : I);
2592 VectorType *I2T = cast<VectorType>(I2->getType());
2593 unsigned I2Elem = I2T->getNumElements();
2595 // This input comes from two distinct vectors. The first step is to
2596 // make sure that both vectors are the same length. If not, the
2597 // smaller one will need to grow before they can be shuffled together.
2598 if (I1Elem < I2Elem) {
2599 std::vector<Constant *> Mask(I2Elem);
2601 for (; v < I1Elem; ++v)
2602 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2603 for (; v < I2Elem; ++v)
2604 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2606 Instruction *NewI1 =
2607 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2608 ConstantVector::get(Mask),
2609 getReplacementName(IBeforeJ ? I : J,
2611 NewI1->insertBefore(IBeforeJ ? J : I);
2614 } else if (I1Elem > I2Elem) {
2615 std::vector<Constant *> Mask(I1Elem);
2617 for (; v < I2Elem; ++v)
2618 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2619 for (; v < I1Elem; ++v)
2620 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2622 Instruction *NewI2 =
2623 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2624 ConstantVector::get(Mask),
2625 getReplacementName(IBeforeJ ? I : J,
2627 NewI2->insertBefore(IBeforeJ ? J : I);
2631 // Now that both I1 and I2 are the same length we can shuffle them
2632 // together (and use the result).
2633 std::vector<Constant *> Mask(numElem);
2634 for (unsigned v = 0; v < numElem; ++v) {
2635 if (II[v].first == -1) {
2636 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2638 int Idx = II[v].first + II[v].second * I1Elem;
2639 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2643 Instruction *NewOp =
2644 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2645 getReplacementName(IBeforeJ ? I : J, true, o));
2646 NewOp->insertBefore(IBeforeJ ? J : I);
2651 Type *ArgType = ArgTypeL;
2652 if (numElemL < numElemH) {
2653 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2654 ArgTypeL, VArgType, IBeforeJ, 1)) {
2655 // This is another short-circuit case: we're combining a scalar into
2656 // a vector that is formed by an IE chain. We've just expanded the IE
2657 // chain, now insert the scalar and we're done.
2659 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2660 getReplacementName(IBeforeJ ? I : J, true, o));
2661 S->insertBefore(IBeforeJ ? J : I);
2663 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2664 ArgTypeH, IBeforeJ)) {
2665 // The two vector inputs to the shuffle must be the same length,
2666 // so extend the smaller vector to be the same length as the larger one.
2670 std::vector<Constant *> Mask(numElemH);
2672 for (; v < numElemL; ++v)
2673 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2674 for (; v < numElemH; ++v)
2675 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2677 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2678 ConstantVector::get(Mask),
2679 getReplacementName(IBeforeJ ? I : J,
2682 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2683 getReplacementName(IBeforeJ ? I : J,
2687 NLOp->insertBefore(IBeforeJ ? J : I);
2692 } else if (numElemL > numElemH) {
2693 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2694 ArgTypeH, VArgType, IBeforeJ)) {
2696 InsertElementInst::Create(LOp, HOp,
2697 ConstantInt::get(Type::getInt32Ty(Context),
2699 getReplacementName(IBeforeJ ? I : J,
2701 S->insertBefore(IBeforeJ ? J : I);
2703 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2704 ArgTypeL, IBeforeJ)) {
2707 std::vector<Constant *> Mask(numElemL);
2709 for (; v < numElemH; ++v)
2710 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2711 for (; v < numElemL; ++v)
2712 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2714 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2715 ConstantVector::get(Mask),
2716 getReplacementName(IBeforeJ ? I : J,
2719 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2720 getReplacementName(IBeforeJ ? I : J,
2724 NHOp->insertBefore(IBeforeJ ? J : I);
2729 if (ArgType->isVectorTy()) {
2730 unsigned numElem = VArgType->getVectorNumElements();
2731 std::vector<Constant*> Mask(numElem);
2732 for (unsigned v = 0; v < numElem; ++v) {
2734 // If the low vector was expanded, we need to skip the extra
2735 // undefined entries.
2736 if (v >= numElemL && numElemH > numElemL)
2737 Idx += (numElemH - numElemL);
2738 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2741 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2742 ConstantVector::get(Mask),
2743 getReplacementName(IBeforeJ ? I : J, true, o));
2744 BV->insertBefore(IBeforeJ ? J : I);
2748 Instruction *BV1 = InsertElementInst::Create(
2749 UndefValue::get(VArgType), LOp, CV0,
2750 getReplacementName(IBeforeJ ? I : J,
2752 BV1->insertBefore(IBeforeJ ? J : I);
2753 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2754 getReplacementName(IBeforeJ ? I : J,
2756 BV2->insertBefore(IBeforeJ ? J : I);
2760 // This function creates an array of values that will be used as the inputs
2761 // to the vector instruction that fuses I with J.
2762 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2763 Instruction *I, Instruction *J,
2764 SmallVectorImpl<Value *> &ReplacedOperands,
2766 unsigned NumOperands = I->getNumOperands();
2768 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2769 // Iterate backward so that we look at the store pointer
2770 // first and know whether or not we need to flip the inputs.
2772 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2773 // This is the pointer for a load/store instruction.
2774 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2776 } else if (isa<CallInst>(I)) {
2777 Function *F = cast<CallInst>(I)->getCalledFunction();
2778 Intrinsic::ID IID = F->getIntrinsicID();
2779 if (o == NumOperands-1) {
2780 BasicBlock &BB = *I->getParent();
2782 Module *M = BB.getParent()->getParent();
2783 Type *ArgTypeI = I->getType();
2784 Type *ArgTypeJ = J->getType();
2785 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2787 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2789 } else if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
2790 IID == Intrinsic::cttz) && o == 1) {
2791 // The second argument of powi/ctlz/cttz is a single integer/constant
2792 // and we've already checked that both arguments are equal.
2793 // As a result, we just keep I's second argument.
2794 ReplacedOperands[o] = I->getOperand(o);
2797 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2798 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2802 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2806 // This function creates two values that represent the outputs of the
2807 // original I and J instructions. These are generally vector shuffles
2808 // or extracts. In many cases, these will end up being unused and, thus,
2809 // eliminated by later passes.
2810 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2811 Instruction *J, Instruction *K,
2812 Instruction *&InsertionPt,
2813 Instruction *&K1, Instruction *&K2) {
2814 if (isa<StoreInst>(I))
2817 Type *IType = I->getType();
2818 Type *JType = J->getType();
2820 VectorType *VType = getVecTypeForPair(IType, JType);
2821 unsigned numElem = VType->getNumElements();
2823 unsigned numElemI = getNumScalarElements(IType);
2824 unsigned numElemJ = getNumScalarElements(JType);
2826 if (IType->isVectorTy()) {
2827 std::vector<Constant *> Mask1(numElemI), Mask2(numElemI);
2828 for (unsigned v = 0; v < numElemI; ++v) {
2829 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2830 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ + v);
2833 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2834 ConstantVector::get(Mask1),
2835 getReplacementName(K, false, 1));
2837 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2838 K1 = ExtractElementInst::Create(K, CV0, 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, getReplacementName(K, false, 2));
2857 K2->insertAfter(K1);
2861 // Move all uses of the function I (including pairing-induced uses) after J.
2862 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2863 DenseSet<ValuePair> &LoadMoveSetPairs,
2864 Instruction *I, Instruction *J) {
2865 // Skip to the first instruction past I.
2866 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2868 DenseSet<Value *> Users;
2869 AliasSetTracker WriteSet(*AA);
2870 if (I->mayWriteToMemory()) WriteSet.add(I);
2872 for (; cast<Instruction>(L) != J; ++L)
2873 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2875 assert(cast<Instruction>(L) == J &&
2876 "Tracking has not proceeded far enough to check for dependencies");
2877 // If J is now in the use set of I, then trackUsesOfI will return true
2878 // and we have a dependency cycle (and the fusing operation must abort).
2879 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2882 // Move all uses of the function I (including pairing-induced uses) after J.
2883 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2884 DenseSet<ValuePair> &LoadMoveSetPairs,
2885 Instruction *&InsertionPt,
2886 Instruction *I, Instruction *J) {
2887 // Skip to the first instruction past I.
2888 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2890 DenseSet<Value *> Users;
2891 AliasSetTracker WriteSet(*AA);
2892 if (I->mayWriteToMemory()) WriteSet.add(I);
2894 for (; cast<Instruction>(L) != J;) {
2895 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2896 // Move this instruction
2897 Instruction *InstToMove = L; ++L;
2899 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2900 " to after " << *InsertionPt << "\n");
2901 InstToMove->removeFromParent();
2902 InstToMove->insertAfter(InsertionPt);
2903 InsertionPt = InstToMove;
2910 // Collect all load instruction that are in the move set of a given first
2911 // pair member. These loads depend on the first instruction, I, and so need
2912 // to be moved after J (the second instruction) when the pair is fused.
2913 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2914 DenseMap<Value *, Value *> &ChosenPairs,
2915 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2916 DenseSet<ValuePair> &LoadMoveSetPairs,
2918 // Skip to the first instruction past I.
2919 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2921 DenseSet<Value *> Users;
2922 AliasSetTracker WriteSet(*AA);
2923 if (I->mayWriteToMemory()) WriteSet.add(I);
2925 // Note: We cannot end the loop when we reach J because J could be moved
2926 // farther down the use chain by another instruction pairing. Also, J
2927 // could be before I if this is an inverted input.
2928 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2929 if (trackUsesOfI(Users, WriteSet, I, L)) {
2930 if (L->mayReadFromMemory()) {
2931 LoadMoveSet[L].push_back(I);
2932 LoadMoveSetPairs.insert(ValuePair(L, I));
2938 // In cases where both load/stores and the computation of their pointers
2939 // are chosen for vectorization, we can end up in a situation where the
2940 // aliasing analysis starts returning different query results as the
2941 // process of fusing instruction pairs continues. Because the algorithm
2942 // relies on finding the same use dags here as were found earlier, we'll
2943 // need to precompute the necessary aliasing information here and then
2944 // manually update it during the fusion process.
2945 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2946 std::vector<Value *> &PairableInsts,
2947 DenseMap<Value *, Value *> &ChosenPairs,
2948 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2949 DenseSet<ValuePair> &LoadMoveSetPairs) {
2950 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2951 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2952 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2953 if (P == ChosenPairs.end()) continue;
2955 Instruction *I = cast<Instruction>(P->first);
2956 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2957 LoadMoveSetPairs, I);
2961 // This function fuses the chosen instruction pairs into vector instructions,
2962 // taking care preserve any needed scalar outputs and, then, it reorders the
2963 // remaining instructions as needed (users of the first member of the pair
2964 // need to be moved to after the location of the second member of the pair
2965 // because the vector instruction is inserted in the location of the pair's
2967 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2968 std::vector<Value *> &PairableInsts,
2969 DenseMap<Value *, Value *> &ChosenPairs,
2970 DenseSet<ValuePair> &FixedOrderPairs,
2971 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2972 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2973 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
2974 LLVMContext& Context = BB.getContext();
2976 // During the vectorization process, the order of the pairs to be fused
2977 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2978 // list. After a pair is fused, the flipped pair is removed from the list.
2979 DenseSet<ValuePair> FlippedPairs;
2980 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2981 E = ChosenPairs.end(); P != E; ++P)
2982 FlippedPairs.insert(ValuePair(P->second, P->first));
2983 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2984 E = FlippedPairs.end(); P != E; ++P)
2985 ChosenPairs.insert(*P);
2987 DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
2988 DenseSet<ValuePair> LoadMoveSetPairs;
2989 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2990 LoadMoveSet, LoadMoveSetPairs);
2992 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2994 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2995 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2996 if (P == ChosenPairs.end()) {
3001 if (getDepthFactor(P->first) == 0) {
3002 // These instructions are not really fused, but are tracked as though
3003 // they are. Any case in which it would be interesting to fuse them
3004 // will be taken care of by InstCombine.
3010 Instruction *I = cast<Instruction>(P->first),
3011 *J = cast<Instruction>(P->second);
3013 DEBUG(dbgs() << "BBV: fusing: " << *I <<
3014 " <-> " << *J << "\n");
3016 // Remove the pair and flipped pair from the list.
3017 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
3018 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
3019 ChosenPairs.erase(FP);
3020 ChosenPairs.erase(P);
3022 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
3023 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
3025 " aborted because of non-trivial dependency cycle\n");
3031 // If the pair must have the other order, then flip it.
3032 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
3033 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
3034 // This pair does not have a fixed order, and so we might want to
3035 // flip it if that will yield fewer shuffles. We count the number
3036 // of dependencies connected via swaps, and those directly connected,
3037 // and flip the order if the number of swaps is greater.
3038 bool OrigOrder = true;
3039 DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
3040 ConnectedPairDeps.find(ValuePair(I, J));
3041 if (IJ == ConnectedPairDeps.end()) {
3042 IJ = ConnectedPairDeps.find(ValuePair(J, I));
3046 if (IJ != ConnectedPairDeps.end()) {
3047 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3048 for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3049 TE = IJ->second.end(); T != TE; ++T) {
3050 VPPair Q(IJ->first, *T);
3051 DenseMap<VPPair, unsigned>::iterator R =
3052 PairConnectionTypes.find(VPPair(Q.second, Q.first));
3053 assert(R != PairConnectionTypes.end() &&
3054 "Cannot find pair connection type");
3055 if (R->second == PairConnectionDirect)
3057 else if (R->second == PairConnectionSwap)
3062 std::swap(NumDepsDirect, NumDepsSwap);
3064 if (NumDepsSwap > NumDepsDirect) {
3065 FlipPairOrder = true;
3066 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3067 " <-> " << *J << "\n");
3072 Instruction *L = I, *H = J;
3076 // If the pair being fused uses the opposite order from that in the pair
3077 // connection map, then we need to flip the types.
3078 DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3079 ConnectedPairs.find(ValuePair(H, L));
3080 if (HL != ConnectedPairs.end())
3081 for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3082 TE = HL->second.end(); T != TE; ++T) {
3083 VPPair Q(HL->first, *T);
3084 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3085 assert(R != PairConnectionTypes.end() &&
3086 "Cannot find pair connection type");
3087 if (R->second == PairConnectionDirect)
3088 R->second = PairConnectionSwap;
3089 else if (R->second == PairConnectionSwap)
3090 R->second = PairConnectionDirect;
3093 bool LBeforeH = !FlipPairOrder;
3094 unsigned NumOperands = I->getNumOperands();
3095 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3096 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3099 // Make a copy of the original operation, change its type to the vector
3100 // type and replace its operands with the vector operands.
3101 Instruction *K = L->clone();
3104 else if (H->hasName())
3107 if (auto CS = CallSite(K)) {
3108 SmallVector<Type *, 3> Tys;
3109 FunctionType *Old = CS.getFunctionType();
3110 unsigned NumOld = Old->getNumParams();
3111 assert(NumOld <= ReplacedOperands.size());
3112 for (unsigned i = 0; i != NumOld; ++i)
3113 Tys.push_back(ReplacedOperands[i]->getType());
3114 CS.mutateFunctionType(
3115 FunctionType::get(getVecTypeForPair(L->getType(), H->getType()),
3116 Tys, Old->isVarArg()));
3117 } else if (!isa<StoreInst>(K))
3118 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3120 unsigned KnownIDs[] = {
3121 LLVMContext::MD_tbaa,
3122 LLVMContext::MD_alias_scope,
3123 LLVMContext::MD_noalias,
3124 LLVMContext::MD_fpmath
3126 combineMetadata(K, H, KnownIDs);
3127 K->intersectOptionalDataWith(H);
3129 for (unsigned o = 0; o < NumOperands; ++o)
3130 K->setOperand(o, ReplacedOperands[o]);
3134 // Instruction insertion point:
3135 Instruction *InsertionPt = K;
3136 Instruction *K1 = nullptr, *K2 = nullptr;
3137 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3139 // The use dag of the first original instruction must be moved to after
3140 // the location of the second instruction. The entire use dag of the
3141 // first instruction is disjoint from the input dag of the second
3142 // (by definition), and so commutes with it.
3144 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3146 if (!isa<StoreInst>(I)) {
3147 L->replaceAllUsesWith(K1);
3148 H->replaceAllUsesWith(K2);
3151 // Instructions that may read from memory may be in the load move set.
3152 // Once an instruction is fused, we no longer need its move set, and so
3153 // the values of the map never need to be updated. However, when a load
3154 // is fused, we need to merge the entries from both instructions in the
3155 // pair in case those instructions were in the move set of some other
3156 // yet-to-be-fused pair. The loads in question are the keys of the map.
3157 if (I->mayReadFromMemory()) {
3158 std::vector<ValuePair> NewSetMembers;
3159 DenseMap<Value *, std::vector<Value *> >::iterator II =
3160 LoadMoveSet.find(I);
3161 if (II != LoadMoveSet.end())
3162 for (std::vector<Value *>::iterator N = II->second.begin(),
3163 NE = II->second.end(); N != NE; ++N)
3164 NewSetMembers.push_back(ValuePair(K, *N));
3165 DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3166 LoadMoveSet.find(J);
3167 if (JJ != LoadMoveSet.end())
3168 for (std::vector<Value *>::iterator N = JJ->second.begin(),
3169 NE = JJ->second.end(); N != NE; ++N)
3170 NewSetMembers.push_back(ValuePair(K, *N));
3171 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3172 AE = NewSetMembers.end(); A != AE; ++A) {
3173 LoadMoveSet[A->first].push_back(A->second);
3174 LoadMoveSetPairs.insert(*A);
3178 // Before removing I, set the iterator to the next instruction.
3179 PI = std::next(BasicBlock::iterator(I));
3180 if (cast<Instruction>(PI) == J)
3185 I->eraseFromParent();
3186 J->eraseFromParent();
3188 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3192 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3196 char BBVectorize::ID = 0;
3197 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3198 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3199 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3200 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3201 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3203 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
3204 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3206 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3207 return new BBVectorize(C);
3211 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3212 BBVectorize BBVectorizer(P, *BB.getParent(), C);
3213 return BBVectorizer.vectorizeBB(BB);
3216 //===----------------------------------------------------------------------===//
3217 VectorizeConfig::VectorizeConfig() {
3218 VectorBits = ::VectorBits;
3219 VectorizeBools = !::NoBools;
3220 VectorizeInts = !::NoInts;
3221 VectorizeFloats = !::NoFloats;
3222 VectorizePointers = !::NoPointers;
3223 VectorizeCasts = !::NoCasts;
3224 VectorizeMath = !::NoMath;
3225 VectorizeBitManipulations = !::NoBitManipulation;
3226 VectorizeFMA = !::NoFMA;
3227 VectorizeSelect = !::NoSelect;
3228 VectorizeCmp = !::NoCmp;
3229 VectorizeGEP = !::NoGEP;
3230 VectorizeMemOps = !::NoMemOps;
3231 AlignedOnly = ::AlignedOnly;
3232 ReqChainDepth= ::ReqChainDepth;
3233 SearchLimit = ::SearchLimit;
3234 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3235 SplatBreaksChain = ::SplatBreaksChain;
3236 MaxInsts = ::MaxInsts;
3237 MaxPairs = ::MaxPairs;
3238 MaxIter = ::MaxIter;
3239 Pow2LenOnly = ::Pow2LenOnly;
3240 NoMemOpBoost = ::NoMemOpBoost;
3241 FastDep = ::FastDep;