1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a basic-block vectorization pass. The algorithm was
11 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12 // et al. It works by looking for chains of pairable operations and then
15 //===----------------------------------------------------------------------===//
17 #define BBV_NAME "bb-vectorize"
18 #define DEBUG_TYPE BBV_NAME
19 #include "llvm/Transforms/Vectorize.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/AliasSetTracker.h"
29 #include "llvm/Analysis/ScalarEvolution.h"
30 #include "llvm/Analysis/ScalarEvolutionExpressions.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/Type.h"
44 #include "llvm/IR/ValueHandle.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Utils/Local.h"
54 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
55 cl::Hidden, cl::desc("Ignore target information"));
57 static cl::opt<unsigned>
58 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
59 cl::desc("The required chain depth for vectorization"));
62 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
63 cl::Hidden, cl::desc("Use the chain depth requirement with"
64 " target information"));
66 static cl::opt<unsigned>
67 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
68 cl::desc("The maximum search distance for instruction pairs"));
71 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
72 cl::desc("Replicating one element to a pair breaks the chain"));
74 static cl::opt<unsigned>
75 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
76 cl::desc("The size of the native vector registers"));
78 static cl::opt<unsigned>
79 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
80 cl::desc("The maximum number of pairing iterations"));
83 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
84 cl::desc("Don't try to form non-2^n-length vectors"));
86 static cl::opt<unsigned>
87 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
88 cl::desc("The maximum number of pairable instructions per group"));
90 static cl::opt<unsigned>
91 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
92 cl::desc("The maximum number of candidate instruction pairs per group"));
94 static cl::opt<unsigned>
95 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
96 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
97 " a full cycle check"));
100 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
101 cl::desc("Don't try to vectorize boolean (i1) values"));
104 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
105 cl::desc("Don't try to vectorize integer values"));
108 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
109 cl::desc("Don't try to vectorize floating-point values"));
111 // FIXME: This should default to false once pointer vector support works.
113 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
114 cl::desc("Don't try to vectorize pointer values"));
117 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
118 cl::desc("Don't try to vectorize casting (conversion) operations"));
121 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
122 cl::desc("Don't try to vectorize floating-point math intrinsics"));
125 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
126 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
129 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
130 cl::desc("Don't try to vectorize select instructions"));
133 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
134 cl::desc("Don't try to vectorize comparison instructions"));
137 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
138 cl::desc("Don't try to vectorize getelementptr instructions"));
141 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
142 cl::desc("Don't try to vectorize loads and stores"));
145 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
146 cl::desc("Only generate aligned loads and stores"));
149 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
150 cl::init(false), cl::Hidden,
151 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
154 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
155 cl::desc("Use a fast instruction dependency analysis"));
159 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
160 cl::init(false), cl::Hidden,
161 cl::desc("When debugging is enabled, output information on the"
162 " instruction-examination process"));
164 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
165 cl::init(false), cl::Hidden,
166 cl::desc("When debugging is enabled, output information on the"
167 " candidate-selection process"));
169 DebugPairSelection("bb-vectorize-debug-pair-selection",
170 cl::init(false), cl::Hidden,
171 cl::desc("When debugging is enabled, output information on the"
172 " pair-selection process"));
174 DebugCycleCheck("bb-vectorize-debug-cycle-check",
175 cl::init(false), cl::Hidden,
176 cl::desc("When debugging is enabled, output information on the"
177 " cycle-checking process"));
180 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
181 cl::init(false), cl::Hidden,
182 cl::desc("When debugging is enabled, dump the basic block after"
183 " every pair is fused"));
186 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
189 struct BBVectorize : public BasicBlockPass {
190 static char ID; // Pass identification, replacement for typeid
192 const VectorizeConfig Config;
194 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
195 : BasicBlockPass(ID), Config(C) {
196 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
199 BBVectorize(Pass *P, const VectorizeConfig &C)
200 : BasicBlockPass(ID), Config(C) {
201 AA = &P->getAnalysis<AliasAnalysis>();
202 DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
203 SE = &P->getAnalysis<ScalarEvolution>();
204 DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
205 DL = DLP ? &DLP->getDataLayout() : 0;
206 TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
209 typedef std::pair<Value *, Value *> ValuePair;
210 typedef std::pair<ValuePair, int> ValuePairWithCost;
211 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
212 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
213 typedef std::pair<VPPair, unsigned> VPPairWithType;
218 const DataLayout *DL;
219 const TargetTransformInfo *TTI;
221 // FIXME: const correct?
223 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
225 bool getCandidatePairs(BasicBlock &BB,
226 BasicBlock::iterator &Start,
227 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
228 DenseSet<ValuePair> &FixedOrderPairs,
229 DenseMap<ValuePair, int> &CandidatePairCostSavings,
230 std::vector<Value *> &PairableInsts, bool NonPow2Len);
232 // FIXME: The current implementation does not account for pairs that
233 // are connected in multiple ways. For example:
234 // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
235 enum PairConnectionType {
236 PairConnectionDirect,
241 void computeConnectedPairs(
242 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
243 DenseSet<ValuePair> &CandidatePairsSet,
244 std::vector<Value *> &PairableInsts,
245 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
246 DenseMap<VPPair, unsigned> &PairConnectionTypes);
248 void buildDepMap(BasicBlock &BB,
249 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
250 std::vector<Value *> &PairableInsts,
251 DenseSet<ValuePair> &PairableInstUsers);
253 void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
254 DenseSet<ValuePair> &CandidatePairsSet,
255 DenseMap<ValuePair, int> &CandidatePairCostSavings,
256 std::vector<Value *> &PairableInsts,
257 DenseSet<ValuePair> &FixedOrderPairs,
258 DenseMap<VPPair, unsigned> &PairConnectionTypes,
259 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
260 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
261 DenseSet<ValuePair> &PairableInstUsers,
262 DenseMap<Value *, Value *>& ChosenPairs);
264 void fuseChosenPairs(BasicBlock &BB,
265 std::vector<Value *> &PairableInsts,
266 DenseMap<Value *, Value *>& ChosenPairs,
267 DenseSet<ValuePair> &FixedOrderPairs,
268 DenseMap<VPPair, unsigned> &PairConnectionTypes,
269 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
270 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
273 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
275 bool areInstsCompatible(Instruction *I, Instruction *J,
276 bool IsSimpleLoadStore, bool NonPow2Len,
277 int &CostSavings, int &FixedOrder);
279 bool trackUsesOfI(DenseSet<Value *> &Users,
280 AliasSetTracker &WriteSet, Instruction *I,
281 Instruction *J, bool UpdateUsers = true,
282 DenseSet<ValuePair> *LoadMoveSetPairs = 0);
284 void computePairsConnectedTo(
285 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
286 DenseSet<ValuePair> &CandidatePairsSet,
287 std::vector<Value *> &PairableInsts,
288 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
289 DenseMap<VPPair, unsigned> &PairConnectionTypes,
292 bool pairsConflict(ValuePair P, ValuePair Q,
293 DenseSet<ValuePair> &PairableInstUsers,
294 DenseMap<ValuePair, std::vector<ValuePair> >
295 *PairableInstUserMap = 0,
296 DenseSet<VPPair> *PairableInstUserPairSet = 0);
298 bool pairWillFormCycle(ValuePair P,
299 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
300 DenseSet<ValuePair> &CurrentPairs);
303 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
304 std::vector<Value *> &PairableInsts,
305 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
306 DenseSet<ValuePair> &PairableInstUsers,
307 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
308 DenseSet<VPPair> &PairableInstUserPairSet,
309 DenseMap<Value *, Value *> &ChosenPairs,
310 DenseMap<ValuePair, size_t> &DAG,
311 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
314 void buildInitialDAGFor(
315 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
316 DenseSet<ValuePair> &CandidatePairsSet,
317 std::vector<Value *> &PairableInsts,
318 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
319 DenseSet<ValuePair> &PairableInstUsers,
320 DenseMap<Value *, Value *> &ChosenPairs,
321 DenseMap<ValuePair, size_t> &DAG, ValuePair J);
324 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
325 DenseSet<ValuePair> &CandidatePairsSet,
326 DenseMap<ValuePair, int> &CandidatePairCostSavings,
327 std::vector<Value *> &PairableInsts,
328 DenseSet<ValuePair> &FixedOrderPairs,
329 DenseMap<VPPair, unsigned> &PairConnectionTypes,
330 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
331 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
332 DenseSet<ValuePair> &PairableInstUsers,
333 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
334 DenseSet<VPPair> &PairableInstUserPairSet,
335 DenseMap<Value *, Value *> &ChosenPairs,
336 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
337 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
340 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
341 Instruction *J, unsigned o);
343 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
344 unsigned MaskOffset, unsigned NumInElem,
345 unsigned NumInElem1, unsigned IdxOffset,
346 std::vector<Constant*> &Mask);
348 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
351 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
352 unsigned o, Value *&LOp, unsigned numElemL,
353 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
354 unsigned IdxOff = 0);
356 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
357 Instruction *J, unsigned o, bool IBeforeJ);
359 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
360 Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
363 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
364 Instruction *J, Instruction *K,
365 Instruction *&InsertionPt, Instruction *&K1,
368 void collectPairLoadMoveSet(BasicBlock &BB,
369 DenseMap<Value *, Value *> &ChosenPairs,
370 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
371 DenseSet<ValuePair> &LoadMoveSetPairs,
374 void collectLoadMoveSet(BasicBlock &BB,
375 std::vector<Value *> &PairableInsts,
376 DenseMap<Value *, Value *> &ChosenPairs,
377 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
378 DenseSet<ValuePair> &LoadMoveSetPairs);
380 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
381 DenseSet<ValuePair> &LoadMoveSetPairs,
382 Instruction *I, Instruction *J);
384 void moveUsesOfIAfterJ(BasicBlock &BB,
385 DenseSet<ValuePair> &LoadMoveSetPairs,
386 Instruction *&InsertionPt,
387 Instruction *I, Instruction *J);
389 void combineMetadata(Instruction *K, const Instruction *J);
391 bool vectorizeBB(BasicBlock &BB) {
392 if (skipOptnoneFunction(BB))
394 if (!DT->isReachableFromEntry(&BB)) {
395 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
396 " in " << BB.getParent()->getName() << "\n");
400 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
402 bool changed = false;
403 // Iterate a sufficient number of times to merge types of size 1 bit,
404 // then 2 bits, then 4, etc. up to half of the target vector width of the
405 // target vector register.
408 (TTI || v <= Config.VectorBits) &&
409 (!Config.MaxIter || n <= Config.MaxIter);
411 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
412 " for " << BB.getName() << " in " <<
413 BB.getParent()->getName() << "...\n");
414 if (vectorizePairs(BB))
420 if (changed && !Pow2LenOnly) {
422 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
423 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
424 n << " for " << BB.getName() << " in " <<
425 BB.getParent()->getName() << "...\n");
426 if (!vectorizePairs(BB, true)) break;
430 DEBUG(dbgs() << "BBV: done!\n");
434 bool runOnBasicBlock(BasicBlock &BB) override {
435 // OptimizeNone check deferred to vectorizeBB().
437 AA = &getAnalysis<AliasAnalysis>();
438 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
439 SE = &getAnalysis<ScalarEvolution>();
440 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
441 DL = DLP ? &DLP->getDataLayout() : 0;
442 TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
444 return vectorizeBB(BB);
447 void getAnalysisUsage(AnalysisUsage &AU) const override {
448 BasicBlockPass::getAnalysisUsage(AU);
449 AU.addRequired<AliasAnalysis>();
450 AU.addRequired<DominatorTreeWrapperPass>();
451 AU.addRequired<ScalarEvolution>();
452 AU.addRequired<TargetTransformInfo>();
453 AU.addPreserved<AliasAnalysis>();
454 AU.addPreserved<DominatorTreeWrapperPass>();
455 AU.addPreserved<ScalarEvolution>();
456 AU.setPreservesCFG();
459 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
460 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
461 "Cannot form vector from incompatible scalar types");
462 Type *STy = ElemTy->getScalarType();
465 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
466 numElem = VTy->getNumElements();
471 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
472 numElem += VTy->getNumElements();
477 return VectorType::get(STy, numElem);
480 static inline void getInstructionTypes(Instruction *I,
481 Type *&T1, Type *&T2) {
482 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
483 // For stores, it is the value type, not the pointer type that matters
484 // because the value is what will come from a vector register.
486 Value *IVal = SI->getValueOperand();
487 T1 = IVal->getType();
492 if (CastInst *CI = dyn_cast<CastInst>(I))
497 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
498 T2 = SI->getCondition()->getType();
499 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
500 T2 = SI->getOperand(0)->getType();
501 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
502 T2 = CI->getOperand(0)->getType();
506 // Returns the weight associated with the provided value. A chain of
507 // candidate pairs has a length given by the sum of the weights of its
508 // members (one weight per pair; the weight of each member of the pair
509 // is assumed to be the same). This length is then compared to the
510 // chain-length threshold to determine if a given chain is significant
511 // enough to be vectorized. The length is also used in comparing
512 // candidate chains where longer chains are considered to be better.
513 // Note: when this function returns 0, the resulting instructions are
514 // not actually fused.
515 inline size_t getDepthFactor(Value *V) {
516 // InsertElement and ExtractElement have a depth factor of zero. This is
517 // for two reasons: First, they cannot be usefully fused. Second, because
518 // the pass generates a lot of these, they can confuse the simple metric
519 // used to compare the dags in the next iteration. Thus, giving them a
520 // weight of zero allows the pass to essentially ignore them in
521 // subsequent iterations when looking for vectorization opportunities
522 // while still tracking dependency chains that flow through those
524 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
527 // Give a load or store half of the required depth so that load/store
528 // pairs will vectorize.
529 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
530 return Config.ReqChainDepth/2;
535 // Returns the cost of the provided instruction using TTI.
536 // This does not handle loads and stores.
537 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
538 TargetTransformInfo::OperandValueKind Op1VK =
539 TargetTransformInfo::OK_AnyValue,
540 TargetTransformInfo::OperandValueKind Op2VK =
541 TargetTransformInfo::OK_AnyValue) {
544 case Instruction::GetElementPtr:
545 // We mark this instruction as zero-cost because scalar GEPs are usually
546 // lowered to the instruction addressing mode. At the moment we don't
547 // generate vector GEPs.
549 case Instruction::Br:
550 return TTI->getCFInstrCost(Opcode);
551 case Instruction::PHI:
553 case Instruction::Add:
554 case Instruction::FAdd:
555 case Instruction::Sub:
556 case Instruction::FSub:
557 case Instruction::Mul:
558 case Instruction::FMul:
559 case Instruction::UDiv:
560 case Instruction::SDiv:
561 case Instruction::FDiv:
562 case Instruction::URem:
563 case Instruction::SRem:
564 case Instruction::FRem:
565 case Instruction::Shl:
566 case Instruction::LShr:
567 case Instruction::AShr:
568 case Instruction::And:
569 case Instruction::Or:
570 case Instruction::Xor:
571 return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
572 case Instruction::Select:
573 case Instruction::ICmp:
574 case Instruction::FCmp:
575 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
576 case Instruction::ZExt:
577 case Instruction::SExt:
578 case Instruction::FPToUI:
579 case Instruction::FPToSI:
580 case Instruction::FPExt:
581 case Instruction::PtrToInt:
582 case Instruction::IntToPtr:
583 case Instruction::SIToFP:
584 case Instruction::UIToFP:
585 case Instruction::Trunc:
586 case Instruction::FPTrunc:
587 case Instruction::BitCast:
588 case Instruction::ShuffleVector:
589 return TTI->getCastInstrCost(Opcode, T1, T2);
595 // This determines the relative offset of two loads or stores, returning
596 // true if the offset could be determined to be some constant value.
597 // For example, if OffsetInElmts == 1, then J accesses the memory directly
598 // after I; if OffsetInElmts == -1 then I accesses the memory
600 bool getPairPtrInfo(Instruction *I, Instruction *J,
601 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
602 unsigned &IAddressSpace, unsigned &JAddressSpace,
603 int64_t &OffsetInElmts, bool ComputeOffset = true) {
605 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
606 LoadInst *LJ = cast<LoadInst>(J);
607 IPtr = LI->getPointerOperand();
608 JPtr = LJ->getPointerOperand();
609 IAlignment = LI->getAlignment();
610 JAlignment = LJ->getAlignment();
611 IAddressSpace = LI->getPointerAddressSpace();
612 JAddressSpace = LJ->getPointerAddressSpace();
614 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
615 IPtr = SI->getPointerOperand();
616 JPtr = SJ->getPointerOperand();
617 IAlignment = SI->getAlignment();
618 JAlignment = SJ->getAlignment();
619 IAddressSpace = SI->getPointerAddressSpace();
620 JAddressSpace = SJ->getPointerAddressSpace();
626 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
627 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
629 // If this is a trivial offset, then we'll get something like
630 // 1*sizeof(type). With target data, which we need anyway, this will get
631 // constant folded into a number.
632 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
633 if (const SCEVConstant *ConstOffSCEV =
634 dyn_cast<SCEVConstant>(OffsetSCEV)) {
635 ConstantInt *IntOff = ConstOffSCEV->getValue();
636 int64_t Offset = IntOff->getSExtValue();
638 Type *VTy = IPtr->getType()->getPointerElementType();
639 int64_t VTyTSS = (int64_t) DL->getTypeStoreSize(VTy);
641 Type *VTy2 = JPtr->getType()->getPointerElementType();
642 if (VTy != VTy2 && Offset < 0) {
643 int64_t VTy2TSS = (int64_t) DL->getTypeStoreSize(VTy2);
644 OffsetInElmts = Offset/VTy2TSS;
645 return (abs64(Offset) % VTy2TSS) == 0;
648 OffsetInElmts = Offset/VTyTSS;
649 return (abs64(Offset) % VTyTSS) == 0;
655 // Returns true if the provided CallInst represents an intrinsic that can
657 bool isVectorizableIntrinsic(CallInst* I) {
658 Function *F = I->getCalledFunction();
659 if (!F) return false;
661 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
662 if (!IID) return false;
667 case Intrinsic::sqrt:
668 case Intrinsic::powi:
672 case Intrinsic::log2:
673 case Intrinsic::log10:
675 case Intrinsic::exp2:
677 return Config.VectorizeMath;
679 case Intrinsic::fmuladd:
680 return Config.VectorizeFMA;
684 bool isPureIEChain(InsertElementInst *IE) {
685 InsertElementInst *IENext = IE;
687 if (!isa<UndefValue>(IENext->getOperand(0)) &&
688 !isa<InsertElementInst>(IENext->getOperand(0))) {
692 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
698 // This function implements one vectorization iteration on the provided
699 // basic block. It returns true if the block is changed.
700 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
702 BasicBlock::iterator Start = BB.getFirstInsertionPt();
704 std::vector<Value *> AllPairableInsts;
705 DenseMap<Value *, Value *> AllChosenPairs;
706 DenseSet<ValuePair> AllFixedOrderPairs;
707 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
708 DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
709 AllConnectedPairDeps;
712 std::vector<Value *> PairableInsts;
713 DenseMap<Value *, std::vector<Value *> > CandidatePairs;
714 DenseSet<ValuePair> FixedOrderPairs;
715 DenseMap<ValuePair, int> CandidatePairCostSavings;
716 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
718 CandidatePairCostSavings,
719 PairableInsts, NonPow2Len);
720 if (PairableInsts.empty()) continue;
722 // Build the candidate pair set for faster lookups.
723 DenseSet<ValuePair> CandidatePairsSet;
724 for (DenseMap<Value *, std::vector<Value *> >::iterator I =
725 CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
726 for (std::vector<Value *>::iterator J = I->second.begin(),
727 JE = I->second.end(); J != JE; ++J)
728 CandidatePairsSet.insert(ValuePair(I->first, *J));
730 // Now we have a map of all of the pairable instructions and we need to
731 // select the best possible pairing. A good pairing is one such that the
732 // users of the pair are also paired. This defines a (directed) forest
733 // over the pairs such that two pairs are connected iff the second pair
736 // Note that it only matters that both members of the second pair use some
737 // element of the first pair (to allow for splatting).
739 DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
741 DenseMap<VPPair, unsigned> PairConnectionTypes;
742 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
743 PairableInsts, ConnectedPairs, PairConnectionTypes);
744 if (ConnectedPairs.empty()) continue;
746 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
747 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
749 for (std::vector<ValuePair>::iterator J = I->second.begin(),
750 JE = I->second.end(); J != JE; ++J)
751 ConnectedPairDeps[*J].push_back(I->first);
753 // Build the pairable-instruction dependency map
754 DenseSet<ValuePair> PairableInstUsers;
755 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
757 // There is now a graph of the connected pairs. For each variable, pick
758 // the pairing with the largest dag meeting the depth requirement on at
759 // least one branch. Then select all pairings that are part of that dag
760 // and remove them from the list of available pairings and pairable
763 DenseMap<Value *, Value *> ChosenPairs;
764 choosePairs(CandidatePairs, CandidatePairsSet,
765 CandidatePairCostSavings,
766 PairableInsts, FixedOrderPairs, PairConnectionTypes,
767 ConnectedPairs, ConnectedPairDeps,
768 PairableInstUsers, ChosenPairs);
770 if (ChosenPairs.empty()) continue;
771 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
772 PairableInsts.end());
773 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
775 // Only for the chosen pairs, propagate information on fixed-order pairs,
776 // pair connections, and their types to the data structures used by the
777 // pair fusion procedures.
778 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
779 IE = ChosenPairs.end(); I != IE; ++I) {
780 if (FixedOrderPairs.count(*I))
781 AllFixedOrderPairs.insert(*I);
782 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
783 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
785 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
787 DenseMap<VPPair, unsigned>::iterator K =
788 PairConnectionTypes.find(VPPair(*I, *J));
789 if (K != PairConnectionTypes.end()) {
790 AllPairConnectionTypes.insert(*K);
792 K = PairConnectionTypes.find(VPPair(*J, *I));
793 if (K != PairConnectionTypes.end())
794 AllPairConnectionTypes.insert(*K);
799 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
800 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
802 for (std::vector<ValuePair>::iterator J = I->second.begin(),
803 JE = I->second.end(); J != JE; ++J)
804 if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
805 AllConnectedPairs[I->first].push_back(*J);
806 AllConnectedPairDeps[*J].push_back(I->first);
808 } while (ShouldContinue);
810 if (AllChosenPairs.empty()) return false;
811 NumFusedOps += AllChosenPairs.size();
813 // A set of pairs has now been selected. It is now necessary to replace the
814 // paired instructions with vector instructions. For this procedure each
815 // operand must be replaced with a vector operand. This vector is formed
816 // by using build_vector on the old operands. The replaced values are then
817 // replaced with a vector_extract on the result. Subsequent optimization
818 // passes should coalesce the build/extract combinations.
820 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
821 AllPairConnectionTypes,
822 AllConnectedPairs, AllConnectedPairDeps);
824 // It is important to cleanup here so that future iterations of this
825 // function have less work to do.
826 (void) SimplifyInstructionsInBlock(&BB, DL, AA->getTargetLibraryInfo());
830 // This function returns true if the provided instruction is capable of being
831 // fused into a vector instruction. This determination is based only on the
832 // type and other attributes of the instruction.
833 bool BBVectorize::isInstVectorizable(Instruction *I,
834 bool &IsSimpleLoadStore) {
835 IsSimpleLoadStore = false;
837 if (CallInst *C = dyn_cast<CallInst>(I)) {
838 if (!isVectorizableIntrinsic(C))
840 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
841 // Vectorize simple loads if possbile:
842 IsSimpleLoadStore = L->isSimple();
843 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
845 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
846 // Vectorize simple stores if possbile:
847 IsSimpleLoadStore = S->isSimple();
848 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
850 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
851 // We can vectorize casts, but not casts of pointer types, etc.
852 if (!Config.VectorizeCasts)
855 Type *SrcTy = C->getSrcTy();
856 if (!SrcTy->isSingleValueType())
859 Type *DestTy = C->getDestTy();
860 if (!DestTy->isSingleValueType())
862 } else if (isa<SelectInst>(I)) {
863 if (!Config.VectorizeSelect)
865 } else if (isa<CmpInst>(I)) {
866 if (!Config.VectorizeCmp)
868 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
869 if (!Config.VectorizeGEP)
872 // Currently, vector GEPs exist only with one index.
873 if (G->getNumIndices() != 1)
875 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
876 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
880 // We can't vectorize memory operations without target data
881 if (DL == 0 && IsSimpleLoadStore)
885 getInstructionTypes(I, T1, T2);
887 // Not every type can be vectorized...
888 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
889 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
892 if (T1->getScalarSizeInBits() == 1) {
893 if (!Config.VectorizeBools)
896 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
900 if (T2->getScalarSizeInBits() == 1) {
901 if (!Config.VectorizeBools)
904 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
908 if (!Config.VectorizeFloats
909 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
912 // Don't vectorize target-specific types.
913 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
915 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
918 if ((!Config.VectorizePointers || DL == 0) &&
919 (T1->getScalarType()->isPointerTy() ||
920 T2->getScalarType()->isPointerTy()))
923 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
924 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
930 // This function returns true if the two provided instructions are compatible
931 // (meaning that they can be fused into a vector instruction). This assumes
932 // that I has already been determined to be vectorizable and that J is not
933 // in the use dag of I.
934 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
935 bool IsSimpleLoadStore, bool NonPow2Len,
936 int &CostSavings, int &FixedOrder) {
937 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
938 " <-> " << *J << "\n");
943 // Loads and stores can be merged if they have different alignments,
944 // but are otherwise the same.
945 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
946 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
949 Type *IT1, *IT2, *JT1, *JT2;
950 getInstructionTypes(I, IT1, IT2);
951 getInstructionTypes(J, JT1, JT2);
952 unsigned MaxTypeBits = std::max(
953 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
954 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
955 if (!TTI && MaxTypeBits > Config.VectorBits)
958 // FIXME: handle addsub-type operations!
960 if (IsSimpleLoadStore) {
962 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
963 int64_t OffsetInElmts = 0;
964 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
965 IAddressSpace, JAddressSpace,
966 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
967 FixedOrder = (int) OffsetInElmts;
968 unsigned BottomAlignment = IAlignment;
969 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
971 Type *aTypeI = isa<StoreInst>(I) ?
972 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
973 Type *aTypeJ = isa<StoreInst>(J) ?
974 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
975 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
977 if (Config.AlignedOnly) {
978 // An aligned load or store is possible only if the instruction
979 // with the lower offset has an alignment suitable for the
982 unsigned VecAlignment = DL->getPrefTypeAlignment(VType);
983 if (BottomAlignment < VecAlignment)
988 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
989 IAlignment, IAddressSpace);
990 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
991 JAlignment, JAddressSpace);
992 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
996 ICost += TTI->getAddressComputationCost(aTypeI);
997 JCost += TTI->getAddressComputationCost(aTypeJ);
998 VCost += TTI->getAddressComputationCost(VType);
1000 if (VCost > ICost + JCost)
1003 // We don't want to fuse to a type that will be split, even
1004 // if the two input types will also be split and there is no other
1006 unsigned VParts = TTI->getNumberOfParts(VType);
1009 else if (!VParts && VCost == ICost + JCost)
1012 CostSavings = ICost + JCost - VCost;
1018 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1019 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1020 Type *VT1 = getVecTypeForPair(IT1, JT1),
1021 *VT2 = getVecTypeForPair(IT2, JT2);
1022 TargetTransformInfo::OperandValueKind Op1VK =
1023 TargetTransformInfo::OK_AnyValue;
1024 TargetTransformInfo::OperandValueKind Op2VK =
1025 TargetTransformInfo::OK_AnyValue;
1027 // On some targets (example X86) the cost of a vector shift may vary
1028 // depending on whether the second operand is a Uniform or
1029 // NonUniform Constant.
1030 switch (I->getOpcode()) {
1032 case Instruction::Shl:
1033 case Instruction::LShr:
1034 case Instruction::AShr:
1036 // If both I and J are scalar shifts by constant, then the
1037 // merged vector shift count would be either a constant splat value
1038 // or a non-uniform vector of constants.
1039 if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
1040 if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
1041 Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
1042 TargetTransformInfo::OK_NonUniformConstantValue;
1044 // Check for a splat of a constant or for a non uniform vector
1046 Value *IOp = I->getOperand(1);
1047 Value *JOp = J->getOperand(1);
1048 if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
1049 (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
1050 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1051 Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
1052 if (SplatValue != NULL &&
1053 SplatValue == cast<Constant>(JOp)->getSplatValue())
1054 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
1059 // Note that this procedure is incorrect for insert and extract element
1060 // instructions (because combining these often results in a shuffle),
1061 // but this cost is ignored (because insert and extract element
1062 // instructions are assigned a zero depth factor and are not really
1063 // fused in general).
1064 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
1066 if (VCost > ICost + JCost)
1069 // We don't want to fuse to a type that will be split, even
1070 // if the two input types will also be split and there is no other
1072 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1073 VParts2 = TTI->getNumberOfParts(VT2);
1074 if (VParts1 > 1 || VParts2 > 1)
1076 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1079 CostSavings = ICost + JCost - VCost;
1082 // The powi intrinsic is special because only the first argument is
1083 // vectorized, the second arguments must be equal.
1084 CallInst *CI = dyn_cast<CallInst>(I);
1086 if (CI && (FI = CI->getCalledFunction())) {
1087 Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
1088 if (IID == Intrinsic::powi) {
1089 Value *A1I = CI->getArgOperand(1),
1090 *A1J = cast<CallInst>(J)->getArgOperand(1);
1091 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1092 *A1JSCEV = SE->getSCEV(A1J);
1093 return (A1ISCEV == A1JSCEV);
1097 SmallVector<Type*, 4> Tys;
1098 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1099 Tys.push_back(CI->getArgOperand(i)->getType());
1100 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1103 CallInst *CJ = cast<CallInst>(J);
1104 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1105 Tys.push_back(CJ->getArgOperand(i)->getType());
1106 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1109 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1110 "Intrinsic argument counts differ");
1111 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1112 if (IID == Intrinsic::powi && i == 1)
1113 Tys.push_back(CI->getArgOperand(i)->getType());
1115 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1116 CJ->getArgOperand(i)->getType()));
1119 Type *RetTy = getVecTypeForPair(IT1, JT1);
1120 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1122 if (VCost > ICost + JCost)
1125 // We don't want to fuse to a type that will be split, even
1126 // if the two input types will also be split and there is no other
1128 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1131 else if (!RetParts && VCost == ICost + JCost)
1134 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1135 if (!Tys[i]->isVectorTy())
1138 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1141 else if (!NumParts && VCost == ICost + JCost)
1145 CostSavings = ICost + JCost - VCost;
1152 // Figure out whether or not J uses I and update the users and write-set
1153 // structures associated with I. Specifically, Users represents the set of
1154 // instructions that depend on I. WriteSet represents the set
1155 // of memory locations that are dependent on I. If UpdateUsers is true,
1156 // and J uses I, then Users is updated to contain J and WriteSet is updated
1157 // to contain any memory locations to which J writes. The function returns
1158 // true if J uses I. By default, alias analysis is used to determine
1159 // whether J reads from memory that overlaps with a location in WriteSet.
1160 // If LoadMoveSet is not null, then it is a previously-computed map
1161 // where the key is the memory-based user instruction and the value is
1162 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1163 // then the alias analysis is not used. This is necessary because this
1164 // function is called during the process of moving instructions during
1165 // vectorization and the results of the alias analysis are not stable during
1167 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1168 AliasSetTracker &WriteSet, Instruction *I,
1169 Instruction *J, bool UpdateUsers,
1170 DenseSet<ValuePair> *LoadMoveSetPairs) {
1173 // This instruction may already be marked as a user due, for example, to
1174 // being a member of a selected pair.
1179 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1182 if (I == V || Users.count(V)) {
1187 if (!UsesI && J->mayReadFromMemory()) {
1188 if (LoadMoveSetPairs) {
1189 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1191 for (AliasSetTracker::iterator W = WriteSet.begin(),
1192 WE = WriteSet.end(); W != WE; ++W) {
1193 if (W->aliasesUnknownInst(J, *AA)) {
1201 if (UsesI && UpdateUsers) {
1202 if (J->mayWriteToMemory()) WriteSet.add(J);
1209 // This function iterates over all instruction pairs in the provided
1210 // basic block and collects all candidate pairs for vectorization.
1211 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1212 BasicBlock::iterator &Start,
1213 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1214 DenseSet<ValuePair> &FixedOrderPairs,
1215 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1216 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1217 size_t TotalPairs = 0;
1218 BasicBlock::iterator E = BB.end();
1219 if (Start == E) return false;
1221 bool ShouldContinue = false, IAfterStart = false;
1222 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1223 if (I == Start) IAfterStart = true;
1225 bool IsSimpleLoadStore;
1226 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1228 // Look for an instruction with which to pair instruction *I...
1229 DenseSet<Value *> Users;
1230 AliasSetTracker WriteSet(*AA);
1231 if (I->mayWriteToMemory()) WriteSet.add(I);
1233 bool JAfterStart = IAfterStart;
1234 BasicBlock::iterator J = std::next(I);
1235 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1236 if (J == Start) JAfterStart = true;
1238 // Determine if J uses I, if so, exit the loop.
1239 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1240 if (Config.FastDep) {
1241 // Note: For this heuristic to be effective, independent operations
1242 // must tend to be intermixed. This is likely to be true from some
1243 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1244 // but otherwise may require some kind of reordering pass.
1246 // When using fast dependency analysis,
1247 // stop searching after first use:
1250 if (UsesI) continue;
1253 // J does not use I, and comes before the first use of I, so it can be
1254 // merged with I if the instructions are compatible.
1255 int CostSavings, FixedOrder;
1256 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1257 CostSavings, FixedOrder)) continue;
1259 // J is a candidate for merging with I.
1260 if (!PairableInsts.size() ||
1261 PairableInsts[PairableInsts.size()-1] != I) {
1262 PairableInsts.push_back(I);
1265 CandidatePairs[I].push_back(J);
1268 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1271 if (FixedOrder == 1)
1272 FixedOrderPairs.insert(ValuePair(I, J));
1273 else if (FixedOrder == -1)
1274 FixedOrderPairs.insert(ValuePair(J, I));
1276 // The next call to this function must start after the last instruction
1277 // selected during this invocation.
1279 Start = std::next(J);
1280 IAfterStart = JAfterStart = false;
1283 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1284 << *I << " <-> " << *J << " (cost savings: " <<
1285 CostSavings << ")\n");
1287 // If we have already found too many pairs, break here and this function
1288 // will be called again starting after the last instruction selected
1289 // during this invocation.
1290 if (PairableInsts.size() >= Config.MaxInsts ||
1291 TotalPairs >= Config.MaxPairs) {
1292 ShouldContinue = true;
1301 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1302 << " instructions with candidate pairs\n");
1304 return ShouldContinue;
1307 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1308 // it looks for pairs such that both members have an input which is an
1309 // output of PI or PJ.
1310 void BBVectorize::computePairsConnectedTo(
1311 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1312 DenseSet<ValuePair> &CandidatePairsSet,
1313 std::vector<Value *> &PairableInsts,
1314 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1315 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1319 // For each possible pairing for this variable, look at the uses of
1320 // the first value...
1321 for (Value::user_iterator I = P.first->user_begin(),
1322 E = P.first->user_end();
1325 if (isa<LoadInst>(UI)) {
1326 // A pair cannot be connected to a load because the load only takes one
1327 // operand (the address) and it is a scalar even after vectorization.
1329 } else if ((SI = dyn_cast<StoreInst>(UI)) &&
1330 P.first == SI->getPointerOperand()) {
1331 // Similarly, a pair cannot be connected to a store through its
1336 // For each use of the first variable, look for uses of the second
1338 for (User *UJ : P.second->users()) {
1339 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1340 P.second == SJ->getPointerOperand())
1344 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1345 VPPair VP(P, ValuePair(UI, UJ));
1346 ConnectedPairs[VP.first].push_back(VP.second);
1347 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1351 if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
1352 VPPair VP(P, ValuePair(UJ, UI));
1353 ConnectedPairs[VP.first].push_back(VP.second);
1354 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1358 if (Config.SplatBreaksChain) continue;
1359 // Look for cases where just the first value in the pair is used by
1360 // both members of another pair (splatting).
1361 for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
1363 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1364 P.first == SJ->getPointerOperand())
1367 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1368 VPPair VP(P, ValuePair(UI, UJ));
1369 ConnectedPairs[VP.first].push_back(VP.second);
1370 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1375 if (Config.SplatBreaksChain) return;
1376 // Look for cases where just the second value in the pair is used by
1377 // both members of another pair (splatting).
1378 for (Value::user_iterator I = P.second->user_begin(),
1379 E = P.second->user_end();
1382 if (isa<LoadInst>(UI))
1384 else if ((SI = dyn_cast<StoreInst>(UI)) &&
1385 P.second == SI->getPointerOperand())
1388 for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
1390 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1391 P.second == SJ->getPointerOperand())
1394 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1395 VPPair VP(P, ValuePair(UI, UJ));
1396 ConnectedPairs[VP.first].push_back(VP.second);
1397 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1403 // This function figures out which pairs are connected. Two pairs are
1404 // connected if some output of the first pair forms an input to both members
1405 // of the second pair.
1406 void BBVectorize::computeConnectedPairs(
1407 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1408 DenseSet<ValuePair> &CandidatePairsSet,
1409 std::vector<Value *> &PairableInsts,
1410 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1411 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1412 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1413 PE = PairableInsts.end(); PI != PE; ++PI) {
1414 DenseMap<Value *, std::vector<Value *> >::iterator PP =
1415 CandidatePairs.find(*PI);
1416 if (PP == CandidatePairs.end())
1419 for (std::vector<Value *>::iterator P = PP->second.begin(),
1420 E = PP->second.end(); P != E; ++P)
1421 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1422 PairableInsts, ConnectedPairs,
1423 PairConnectionTypes, ValuePair(*PI, *P));
1426 DEBUG(size_t TotalPairs = 0;
1427 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1428 ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1429 TotalPairs += I->second.size();
1430 dbgs() << "BBV: found " << TotalPairs
1431 << " pair connections.\n");
1434 // This function builds a set of use tuples such that <A, B> is in the set
1435 // if B is in the use dag of A. If B is in the use dag of A, then B
1436 // depends on the output of A.
1437 void BBVectorize::buildDepMap(
1439 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1440 std::vector<Value *> &PairableInsts,
1441 DenseSet<ValuePair> &PairableInstUsers) {
1442 DenseSet<Value *> IsInPair;
1443 for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1444 CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1445 IsInPair.insert(C->first);
1446 IsInPair.insert(C->second.begin(), C->second.end());
1449 // Iterate through the basic block, recording all users of each
1450 // pairable instruction.
1452 BasicBlock::iterator E = BB.end(), EL =
1453 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1454 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1455 if (IsInPair.find(I) == IsInPair.end()) continue;
1457 DenseSet<Value *> Users;
1458 AliasSetTracker WriteSet(*AA);
1459 if (I->mayWriteToMemory()) WriteSet.add(I);
1461 for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
1462 (void) trackUsesOfI(Users, WriteSet, I, J);
1468 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1470 if (IsInPair.find(*U) == IsInPair.end()) continue;
1471 PairableInstUsers.insert(ValuePair(I, *U));
1479 // Returns true if an input to pair P is an output of pair Q and also an
1480 // input of pair Q is an output of pair P. If this is the case, then these
1481 // two pairs cannot be simultaneously fused.
1482 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1483 DenseSet<ValuePair> &PairableInstUsers,
1484 DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1485 DenseSet<VPPair> *PairableInstUserPairSet) {
1486 // Two pairs are in conflict if they are mutual Users of eachother.
1487 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1488 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1489 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1490 PairableInstUsers.count(ValuePair(P.second, Q.second));
1491 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1492 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1493 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1494 PairableInstUsers.count(ValuePair(Q.second, P.second));
1495 if (PairableInstUserMap) {
1496 // FIXME: The expensive part of the cycle check is not so much the cycle
1497 // check itself but this edge insertion procedure. This needs some
1498 // profiling and probably a different data structure.
1500 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1501 (*PairableInstUserMap)[Q].push_back(P);
1504 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1505 (*PairableInstUserMap)[P].push_back(Q);
1509 return (QUsesP && PUsesQ);
1512 // This function walks the use graph of current pairs to see if, starting
1513 // from P, the walk returns to P.
1514 bool BBVectorize::pairWillFormCycle(ValuePair P,
1515 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1516 DenseSet<ValuePair> &CurrentPairs) {
1517 DEBUG(if (DebugCycleCheck)
1518 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1519 << *P.second << "\n");
1520 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1521 // contains non-direct associations.
1522 DenseSet<ValuePair> Visited;
1523 SmallVector<ValuePair, 32> Q;
1524 // General depth-first post-order traversal:
1527 ValuePair QTop = Q.pop_back_val();
1528 Visited.insert(QTop);
1530 DEBUG(if (DebugCycleCheck)
1531 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1532 << *QTop.second << "\n");
1533 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1534 PairableInstUserMap.find(QTop);
1535 if (QQ == PairableInstUserMap.end())
1538 for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1539 CE = QQ->second.end(); C != CE; ++C) {
1542 << "BBV: rejected to prevent non-trivial cycle formation: "
1543 << QTop.first << " <-> " << C->second << "\n");
1547 if (CurrentPairs.count(*C) && !Visited.count(*C))
1550 } while (!Q.empty());
1555 // This function builds the initial dag of connected pairs with the
1556 // pair J at the root.
1557 void BBVectorize::buildInitialDAGFor(
1558 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1559 DenseSet<ValuePair> &CandidatePairsSet,
1560 std::vector<Value *> &PairableInsts,
1561 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1562 DenseSet<ValuePair> &PairableInstUsers,
1563 DenseMap<Value *, Value *> &ChosenPairs,
1564 DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1565 // Each of these pairs is viewed as the root node of a DAG. The DAG
1566 // is then walked (depth-first). As this happens, we keep track of
1567 // the pairs that compose the DAG and the maximum depth of the DAG.
1568 SmallVector<ValuePairWithDepth, 32> Q;
1569 // General depth-first post-order traversal:
1570 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1572 ValuePairWithDepth QTop = Q.back();
1574 // Push each child onto the queue:
1575 bool MoreChildren = false;
1576 size_t MaxChildDepth = QTop.second;
1577 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1578 ConnectedPairs.find(QTop.first);
1579 if (QQ != ConnectedPairs.end())
1580 for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1581 ke = QQ->second.end(); k != ke; ++k) {
1582 // Make sure that this child pair is still a candidate:
1583 if (CandidatePairsSet.count(*k)) {
1584 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
1585 if (C == DAG.end()) {
1586 size_t d = getDepthFactor(k->first);
1587 Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1588 MoreChildren = true;
1590 MaxChildDepth = std::max(MaxChildDepth, C->second);
1595 if (!MoreChildren) {
1596 // Record the current pair as part of the DAG:
1597 DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1600 } while (!Q.empty());
1603 // Given some initial dag, prune it by removing conflicting pairs (pairs
1604 // that cannot be simultaneously chosen for vectorization).
1605 void BBVectorize::pruneDAGFor(
1606 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1607 std::vector<Value *> &PairableInsts,
1608 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1609 DenseSet<ValuePair> &PairableInstUsers,
1610 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1611 DenseSet<VPPair> &PairableInstUserPairSet,
1612 DenseMap<Value *, Value *> &ChosenPairs,
1613 DenseMap<ValuePair, size_t> &DAG,
1614 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1615 bool UseCycleCheck) {
1616 SmallVector<ValuePairWithDepth, 32> Q;
1617 // General depth-first post-order traversal:
1618 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1620 ValuePairWithDepth QTop = Q.pop_back_val();
1621 PrunedDAG.insert(QTop.first);
1623 // Visit each child, pruning as necessary...
1624 SmallVector<ValuePairWithDepth, 8> BestChildren;
1625 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1626 ConnectedPairs.find(QTop.first);
1627 if (QQ == ConnectedPairs.end())
1630 for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1631 KE = QQ->second.end(); K != KE; ++K) {
1632 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
1633 if (C == DAG.end()) continue;
1635 // This child is in the DAG, now we need to make sure it is the
1636 // best of any conflicting children. There could be multiple
1637 // conflicting children, so first, determine if we're keeping
1638 // this child, then delete conflicting children as necessary.
1640 // It is also necessary to guard against pairing-induced
1641 // dependencies. Consider instructions a .. x .. y .. b
1642 // such that (a,b) are to be fused and (x,y) are to be fused
1643 // but a is an input to x and b is an output from y. This
1644 // means that y cannot be moved after b but x must be moved
1645 // after b for (a,b) to be fused. In other words, after
1646 // fusing (a,b) we have y .. a/b .. x where y is an input
1647 // to a/b and x is an output to a/b: x and y can no longer
1648 // be legally fused. To prevent this condition, we must
1649 // make sure that a child pair added to the DAG is not
1650 // both an input and output of an already-selected pair.
1652 // Pairing-induced dependencies can also form from more complicated
1653 // cycles. The pair vs. pair conflicts are easy to check, and so
1654 // that is done explicitly for "fast rejection", and because for
1655 // child vs. child conflicts, we may prefer to keep the current
1656 // pair in preference to the already-selected child.
1657 DenseSet<ValuePair> CurrentPairs;
1660 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1661 = BestChildren.begin(), E2 = BestChildren.end();
1663 if (C2->first.first == C->first.first ||
1664 C2->first.first == C->first.second ||
1665 C2->first.second == C->first.first ||
1666 C2->first.second == C->first.second ||
1667 pairsConflict(C2->first, C->first, PairableInstUsers,
1668 UseCycleCheck ? &PairableInstUserMap : 0,
1669 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1670 if (C2->second >= C->second) {
1675 CurrentPairs.insert(C2->first);
1678 if (!CanAdd) continue;
1680 // Even worse, this child could conflict with another node already
1681 // selected for the DAG. If that is the case, ignore this child.
1682 for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1683 E2 = PrunedDAG.end(); T != E2; ++T) {
1684 if (T->first == C->first.first ||
1685 T->first == C->first.second ||
1686 T->second == C->first.first ||
1687 T->second == C->first.second ||
1688 pairsConflict(*T, C->first, PairableInstUsers,
1689 UseCycleCheck ? &PairableInstUserMap : 0,
1690 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1695 CurrentPairs.insert(*T);
1697 if (!CanAdd) continue;
1699 // And check the queue too...
1700 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
1701 E2 = Q.end(); C2 != E2; ++C2) {
1702 if (C2->first.first == C->first.first ||
1703 C2->first.first == C->first.second ||
1704 C2->first.second == C->first.first ||
1705 C2->first.second == C->first.second ||
1706 pairsConflict(C2->first, C->first, PairableInstUsers,
1707 UseCycleCheck ? &PairableInstUserMap : 0,
1708 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1713 CurrentPairs.insert(C2->first);
1715 if (!CanAdd) continue;
1717 // Last but not least, check for a conflict with any of the
1718 // already-chosen pairs.
1719 for (DenseMap<Value *, Value *>::iterator C2 =
1720 ChosenPairs.begin(), E2 = ChosenPairs.end();
1722 if (pairsConflict(*C2, C->first, PairableInstUsers,
1723 UseCycleCheck ? &PairableInstUserMap : 0,
1724 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1729 CurrentPairs.insert(*C2);
1731 if (!CanAdd) continue;
1733 // To check for non-trivial cycles formed by the addition of the
1734 // current pair we've formed a list of all relevant pairs, now use a
1735 // graph walk to check for a cycle. We start from the current pair and
1736 // walk the use dag to see if we again reach the current pair. If we
1737 // do, then the current pair is rejected.
1739 // FIXME: It may be more efficient to use a topological-ordering
1740 // algorithm to improve the cycle check. This should be investigated.
1741 if (UseCycleCheck &&
1742 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1745 // This child can be added, but we may have chosen it in preference
1746 // to an already-selected child. Check for this here, and if a
1747 // conflict is found, then remove the previously-selected child
1748 // before adding this one in its place.
1749 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1750 = BestChildren.begin(); C2 != BestChildren.end();) {
1751 if (C2->first.first == C->first.first ||
1752 C2->first.first == C->first.second ||
1753 C2->first.second == C->first.first ||
1754 C2->first.second == C->first.second ||
1755 pairsConflict(C2->first, C->first, PairableInstUsers))
1756 C2 = BestChildren.erase(C2);
1761 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1764 for (SmallVectorImpl<ValuePairWithDepth>::iterator C
1765 = BestChildren.begin(), E2 = BestChildren.end();
1767 size_t DepthF = getDepthFactor(C->first.first);
1768 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1770 } while (!Q.empty());
1773 // This function finds the best dag of mututally-compatible connected
1774 // pairs, given the choice of root pairs as an iterator range.
1775 void BBVectorize::findBestDAGFor(
1776 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1777 DenseSet<ValuePair> &CandidatePairsSet,
1778 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1779 std::vector<Value *> &PairableInsts,
1780 DenseSet<ValuePair> &FixedOrderPairs,
1781 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1782 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1783 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1784 DenseSet<ValuePair> &PairableInstUsers,
1785 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1786 DenseSet<VPPair> &PairableInstUserPairSet,
1787 DenseMap<Value *, Value *> &ChosenPairs,
1788 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1789 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1790 bool UseCycleCheck) {
1791 for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1793 ValuePair IJ(II, *J);
1794 if (!CandidatePairsSet.count(IJ))
1797 // Before going any further, make sure that this pair does not
1798 // conflict with any already-selected pairs (see comment below
1799 // near the DAG pruning for more details).
1800 DenseSet<ValuePair> ChosenPairSet;
1801 bool DoesConflict = false;
1802 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1803 E = ChosenPairs.end(); C != E; ++C) {
1804 if (pairsConflict(*C, IJ, PairableInstUsers,
1805 UseCycleCheck ? &PairableInstUserMap : 0,
1806 UseCycleCheck ? &PairableInstUserPairSet : 0)) {
1807 DoesConflict = true;
1811 ChosenPairSet.insert(*C);
1813 if (DoesConflict) continue;
1815 if (UseCycleCheck &&
1816 pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1819 DenseMap<ValuePair, size_t> DAG;
1820 buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1821 PairableInsts, ConnectedPairs,
1822 PairableInstUsers, ChosenPairs, DAG, IJ);
1824 // Because we'll keep the child with the largest depth, the largest
1825 // depth is still the same in the unpruned DAG.
1826 size_t MaxDepth = DAG.lookup(IJ);
1828 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1829 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1830 MaxDepth << " and size " << DAG.size() << "\n");
1832 // At this point the DAG has been constructed, but, may contain
1833 // contradictory children (meaning that different children of
1834 // some dag node may be attempting to fuse the same instruction).
1835 // So now we walk the dag again, in the case of a conflict,
1836 // keep only the child with the largest depth. To break a tie,
1837 // favor the first child.
1839 DenseSet<ValuePair> PrunedDAG;
1840 pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1841 PairableInstUsers, PairableInstUserMap,
1842 PairableInstUserPairSet,
1843 ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1847 DenseSet<Value *> PrunedDAGInstrs;
1848 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1849 E = PrunedDAG.end(); S != E; ++S) {
1850 PrunedDAGInstrs.insert(S->first);
1851 PrunedDAGInstrs.insert(S->second);
1854 // The set of pairs that have already contributed to the total cost.
1855 DenseSet<ValuePair> IncomingPairs;
1857 // If the cost model were perfect, this might not be necessary; but we
1858 // need to make sure that we don't get stuck vectorizing our own
1860 bool HasNontrivialInsts = false;
1862 // The node weights represent the cost savings associated with
1863 // fusing the pair of instructions.
1864 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1865 E = PrunedDAG.end(); S != E; ++S) {
1866 if (!isa<ShuffleVectorInst>(S->first) &&
1867 !isa<InsertElementInst>(S->first) &&
1868 !isa<ExtractElementInst>(S->first))
1869 HasNontrivialInsts = true;
1871 bool FlipOrder = false;
1873 if (getDepthFactor(S->first)) {
1874 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1875 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1876 << *S->first << " <-> " << *S->second << "} = " <<
1878 EffSize += ESContrib;
1881 // The edge weights contribute in a negative sense: they represent
1882 // the cost of shuffles.
1883 DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1884 ConnectedPairDeps.find(*S);
1885 if (SS != ConnectedPairDeps.end()) {
1886 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1887 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1888 TE = SS->second.end(); T != TE; ++T) {
1890 if (!PrunedDAG.count(Q.second))
1892 DenseMap<VPPair, unsigned>::iterator R =
1893 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1894 assert(R != PairConnectionTypes.end() &&
1895 "Cannot find pair connection type");
1896 if (R->second == PairConnectionDirect)
1898 else if (R->second == PairConnectionSwap)
1902 // If there are more swaps than direct connections, then
1903 // the pair order will be flipped during fusion. So the real
1904 // number of swaps is the minimum number.
1905 FlipOrder = !FixedOrderPairs.count(*S) &&
1906 ((NumDepsSwap > NumDepsDirect) ||
1907 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1909 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1910 TE = SS->second.end(); T != TE; ++T) {
1912 if (!PrunedDAG.count(Q.second))
1914 DenseMap<VPPair, unsigned>::iterator R =
1915 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1916 assert(R != PairConnectionTypes.end() &&
1917 "Cannot find pair connection type");
1918 Type *Ty1 = Q.second.first->getType(),
1919 *Ty2 = Q.second.second->getType();
1920 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1921 if ((R->second == PairConnectionDirect && FlipOrder) ||
1922 (R->second == PairConnectionSwap && !FlipOrder) ||
1923 R->second == PairConnectionSplat) {
1924 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1927 if (VTy->getVectorNumElements() == 2) {
1928 if (R->second == PairConnectionSplat)
1929 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1930 TargetTransformInfo::SK_Broadcast, VTy));
1932 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1933 TargetTransformInfo::SK_Reverse, VTy));
1936 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1937 *Q.second.first << " <-> " << *Q.second.second <<
1939 *S->first << " <-> " << *S->second << "} = " <<
1941 EffSize -= ESContrib;
1946 // Compute the cost of outgoing edges. We assume that edges outgoing
1947 // to shuffles, inserts or extracts can be merged, and so contribute
1948 // no additional cost.
1949 if (!S->first->getType()->isVoidTy()) {
1950 Type *Ty1 = S->first->getType(),
1951 *Ty2 = S->second->getType();
1952 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1954 bool NeedsExtraction = false;
1955 for (User *U : S->first->users()) {
1956 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
1957 // Shuffle can be folded if it has no other input
1958 if (isa<UndefValue>(SI->getOperand(1)))
1961 if (isa<ExtractElementInst>(U))
1963 if (PrunedDAGInstrs.count(U))
1965 NeedsExtraction = true;
1969 if (NeedsExtraction) {
1971 if (Ty1->isVectorTy()) {
1972 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1974 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1975 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
1977 ESContrib = (int) TTI->getVectorInstrCost(
1978 Instruction::ExtractElement, VTy, 0);
1980 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1981 *S->first << "} = " << ESContrib << "\n");
1982 EffSize -= ESContrib;
1985 NeedsExtraction = false;
1986 for (User *U : S->second->users()) {
1987 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
1988 // Shuffle can be folded if it has no other input
1989 if (isa<UndefValue>(SI->getOperand(1)))
1992 if (isa<ExtractElementInst>(U))
1994 if (PrunedDAGInstrs.count(U))
1996 NeedsExtraction = true;
2000 if (NeedsExtraction) {
2002 if (Ty2->isVectorTy()) {
2003 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2005 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2006 TargetTransformInfo::SK_ExtractSubvector, VTy,
2007 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
2009 ESContrib = (int) TTI->getVectorInstrCost(
2010 Instruction::ExtractElement, VTy, 1);
2011 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2012 *S->second << "} = " << ESContrib << "\n");
2013 EffSize -= ESContrib;
2017 // Compute the cost of incoming edges.
2018 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
2019 Instruction *S1 = cast<Instruction>(S->first),
2020 *S2 = cast<Instruction>(S->second);
2021 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
2022 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
2024 // Combining constants into vector constants (or small vector
2025 // constants into larger ones are assumed free).
2026 if (isa<Constant>(O1) && isa<Constant>(O2))
2032 ValuePair VP = ValuePair(O1, O2);
2033 ValuePair VPR = ValuePair(O2, O1);
2035 // Internal edges are not handled here.
2036 if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
2039 Type *Ty1 = O1->getType(),
2040 *Ty2 = O2->getType();
2041 Type *VTy = getVecTypeForPair(Ty1, Ty2);
2043 // Combining vector operations of the same type is also assumed
2044 // folded with other operations.
2046 // If both are insert elements, then both can be widened.
2047 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
2048 *IEO2 = dyn_cast<InsertElementInst>(O2);
2049 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
2051 // If both are extract elements, and both have the same input
2052 // type, then they can be replaced with a shuffle
2053 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2054 *EIO2 = dyn_cast<ExtractElementInst>(O2);
2056 EIO1->getOperand(0)->getType() ==
2057 EIO2->getOperand(0)->getType())
2059 // If both are a shuffle with equal operand types and only two
2060 // unqiue operands, then they can be replaced with a single
2062 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2063 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2065 SIO1->getOperand(0)->getType() ==
2066 SIO2->getOperand(0)->getType()) {
2067 SmallSet<Value *, 4> SIOps;
2068 SIOps.insert(SIO1->getOperand(0));
2069 SIOps.insert(SIO1->getOperand(1));
2070 SIOps.insert(SIO2->getOperand(0));
2071 SIOps.insert(SIO2->getOperand(1));
2072 if (SIOps.size() <= 2)
2078 // This pair has already been formed.
2079 if (IncomingPairs.count(VP)) {
2081 } else if (IncomingPairs.count(VPR)) {
2082 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2085 if (VTy->getVectorNumElements() == 2)
2086 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2087 TargetTransformInfo::SK_Reverse, VTy));
2088 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2089 ESContrib = (int) TTI->getVectorInstrCost(
2090 Instruction::InsertElement, VTy, 0);
2091 ESContrib += (int) TTI->getVectorInstrCost(
2092 Instruction::InsertElement, VTy, 1);
2093 } else if (!Ty1->isVectorTy()) {
2094 // O1 needs to be inserted into a vector of size O2, and then
2095 // both need to be shuffled together.
2096 ESContrib = (int) TTI->getVectorInstrCost(
2097 Instruction::InsertElement, Ty2, 0);
2098 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2100 } else if (!Ty2->isVectorTy()) {
2101 // O2 needs to be inserted into a vector of size O1, and then
2102 // both need to be shuffled together.
2103 ESContrib = (int) TTI->getVectorInstrCost(
2104 Instruction::InsertElement, Ty1, 0);
2105 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2108 Type *TyBig = Ty1, *TySmall = Ty2;
2109 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2110 std::swap(TyBig, TySmall);
2112 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2114 if (TyBig != TySmall)
2115 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2119 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2120 << *O1 << " <-> " << *O2 << "} = " <<
2122 EffSize -= ESContrib;
2123 IncomingPairs.insert(VP);
2128 if (!HasNontrivialInsts) {
2129 DEBUG(if (DebugPairSelection) dbgs() <<
2130 "\tNo non-trivial instructions in DAG;"
2131 " override to zero effective size\n");
2135 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2136 E = PrunedDAG.end(); S != E; ++S)
2137 EffSize += (int) getDepthFactor(S->first);
2140 DEBUG(if (DebugPairSelection)
2141 dbgs() << "BBV: found pruned DAG for pair {"
2142 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2143 MaxDepth << " and size " << PrunedDAG.size() <<
2144 " (effective size: " << EffSize << ")\n");
2145 if (((TTI && !UseChainDepthWithTI) ||
2146 MaxDepth >= Config.ReqChainDepth) &&
2147 EffSize > 0 && EffSize > BestEffSize) {
2148 BestMaxDepth = MaxDepth;
2149 BestEffSize = EffSize;
2150 BestDAG = PrunedDAG;
2155 // Given the list of candidate pairs, this function selects those
2156 // that will be fused into vector instructions.
2157 void BBVectorize::choosePairs(
2158 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2159 DenseSet<ValuePair> &CandidatePairsSet,
2160 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2161 std::vector<Value *> &PairableInsts,
2162 DenseSet<ValuePair> &FixedOrderPairs,
2163 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2164 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2165 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2166 DenseSet<ValuePair> &PairableInstUsers,
2167 DenseMap<Value *, Value *>& ChosenPairs) {
2168 bool UseCycleCheck =
2169 CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2171 DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2172 for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2173 E = CandidatePairsSet.end(); I != E; ++I) {
2174 std::vector<Value *> &JJ = CandidatePairs2[I->second];
2175 if (JJ.empty()) JJ.reserve(32);
2176 JJ.push_back(I->first);
2179 DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2180 DenseSet<VPPair> PairableInstUserPairSet;
2181 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2182 E = PairableInsts.end(); I != E; ++I) {
2183 // The number of possible pairings for this variable:
2184 size_t NumChoices = CandidatePairs.lookup(*I).size();
2185 if (!NumChoices) continue;
2187 std::vector<Value *> &JJ = CandidatePairs[*I];
2189 // The best pair to choose and its dag:
2190 size_t BestMaxDepth = 0;
2191 int BestEffSize = 0;
2192 DenseSet<ValuePair> BestDAG;
2193 findBestDAGFor(CandidatePairs, CandidatePairsSet,
2194 CandidatePairCostSavings,
2195 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2196 ConnectedPairs, ConnectedPairDeps,
2197 PairableInstUsers, PairableInstUserMap,
2198 PairableInstUserPairSet, ChosenPairs,
2199 BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2202 if (BestDAG.empty())
2205 // A dag has been chosen (or not) at this point. If no dag was
2206 // chosen, then this instruction, I, cannot be paired (and is no longer
2209 DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2210 << *cast<Instruction>(*I) << "\n");
2212 for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2213 SE2 = BestDAG.end(); S != SE2; ++S) {
2214 // Insert the members of this dag into the list of chosen pairs.
2215 ChosenPairs.insert(ValuePair(S->first, S->second));
2216 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2217 *S->second << "\n");
2219 // Remove all candidate pairs that have values in the chosen dag.
2220 std::vector<Value *> &KK = CandidatePairs[S->first];
2221 for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2223 if (*K == S->second)
2226 CandidatePairsSet.erase(ValuePair(S->first, *K));
2229 std::vector<Value *> &LL = CandidatePairs2[S->second];
2230 for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2235 CandidatePairsSet.erase(ValuePair(*L, S->second));
2238 std::vector<Value *> &MM = CandidatePairs[S->second];
2239 for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2241 assert(*M != S->first && "Flipped pair in candidate list?");
2242 CandidatePairsSet.erase(ValuePair(S->second, *M));
2245 std::vector<Value *> &NN = CandidatePairs2[S->first];
2246 for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2248 assert(*N != S->second && "Flipped pair in candidate list?");
2249 CandidatePairsSet.erase(ValuePair(*N, S->first));
2254 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2257 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2262 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2263 (n > 0 ? "." + utostr(n) : "")).str();
2266 // Returns the value that is to be used as the pointer input to the vector
2267 // instruction that fuses I with J.
2268 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2269 Instruction *I, Instruction *J, unsigned o) {
2271 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2272 int64_t OffsetInElmts;
2274 // Note: the analysis might fail here, that is why the pair order has
2275 // been precomputed (OffsetInElmts must be unused here).
2276 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2277 IAddressSpace, JAddressSpace,
2278 OffsetInElmts, false);
2280 // The pointer value is taken to be the one with the lowest offset.
2283 Type *ArgTypeI = IPtr->getType()->getPointerElementType();
2284 Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
2285 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2287 = PointerType::get(VArgType,
2288 IPtr->getType()->getPointerAddressSpace());
2289 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2290 /* insert before */ I);
2293 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2294 unsigned MaskOffset, unsigned NumInElem,
2295 unsigned NumInElem1, unsigned IdxOffset,
2296 std::vector<Constant*> &Mask) {
2297 unsigned NumElem1 = J->getType()->getVectorNumElements();
2298 for (unsigned v = 0; v < NumElem1; ++v) {
2299 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2301 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2303 unsigned mm = m + (int) IdxOffset;
2304 if (m >= (int) NumInElem1)
2305 mm += (int) NumInElem;
2307 Mask[v+MaskOffset] =
2308 ConstantInt::get(Type::getInt32Ty(Context), mm);
2313 // Returns the value that is to be used as the vector-shuffle mask to the
2314 // vector instruction that fuses I with J.
2315 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2316 Instruction *I, Instruction *J) {
2317 // This is the shuffle mask. We need to append the second
2318 // mask to the first, and the numbers need to be adjusted.
2320 Type *ArgTypeI = I->getType();
2321 Type *ArgTypeJ = J->getType();
2322 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2324 unsigned NumElemI = ArgTypeI->getVectorNumElements();
2326 // Get the total number of elements in the fused vector type.
2327 // By definition, this must equal the number of elements in
2329 unsigned NumElem = VArgType->getVectorNumElements();
2330 std::vector<Constant*> Mask(NumElem);
2332 Type *OpTypeI = I->getOperand(0)->getType();
2333 unsigned NumInElemI = OpTypeI->getVectorNumElements();
2334 Type *OpTypeJ = J->getOperand(0)->getType();
2335 unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
2337 // The fused vector will be:
2338 // -----------------------------------------------------
2339 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2340 // -----------------------------------------------------
2341 // from which we'll extract NumElem total elements (where the first NumElemI
2342 // of them come from the mask in I and the remainder come from the mask
2345 // For the mask from the first pair...
2346 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2349 // For the mask from the second pair...
2350 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2353 return ConstantVector::get(Mask);
2356 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2357 Instruction *J, unsigned o, Value *&LOp,
2359 Type *ArgTypeL, Type *ArgTypeH,
2360 bool IBeforeJ, unsigned IdxOff) {
2361 bool ExpandedIEChain = false;
2362 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2363 // If we have a pure insertelement chain, then this can be rewritten
2364 // into a chain that directly builds the larger type.
2365 if (isPureIEChain(LIE)) {
2366 SmallVector<Value *, 8> VectElemts(numElemL,
2367 UndefValue::get(ArgTypeL->getScalarType()));
2368 InsertElementInst *LIENext = LIE;
2371 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2372 VectElemts[Idx] = LIENext->getOperand(1);
2374 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2377 Value *LIEPrev = UndefValue::get(ArgTypeH);
2378 for (unsigned i = 0; i < numElemL; ++i) {
2379 if (isa<UndefValue>(VectElemts[i])) continue;
2380 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2381 ConstantInt::get(Type::getInt32Ty(Context),
2383 getReplacementName(IBeforeJ ? I : J,
2385 LIENext->insertBefore(IBeforeJ ? J : I);
2389 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2390 ExpandedIEChain = true;
2394 return ExpandedIEChain;
2397 static unsigned getNumScalarElements(Type *Ty) {
2398 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
2399 return VecTy->getNumElements();
2403 // Returns the value to be used as the specified operand of the vector
2404 // instruction that fuses I with J.
2405 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2406 Instruction *J, unsigned o, bool IBeforeJ) {
2407 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2408 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2410 // Compute the fused vector type for this operand
2411 Type *ArgTypeI = I->getOperand(o)->getType();
2412 Type *ArgTypeJ = J->getOperand(o)->getType();
2413 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2415 Instruction *L = I, *H = J;
2416 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2418 unsigned numElemL = getNumScalarElements(ArgTypeL);
2419 unsigned numElemH = getNumScalarElements(ArgTypeH);
2421 Value *LOp = L->getOperand(o);
2422 Value *HOp = H->getOperand(o);
2423 unsigned numElem = VArgType->getNumElements();
2425 // First, we check if we can reuse the "original" vector outputs (if these
2426 // exist). We might need a shuffle.
2427 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2428 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2429 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2430 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2432 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2433 // optimization. The input vectors to the shuffle might be a different
2434 // length from the shuffle outputs. Unfortunately, the replacement
2435 // shuffle mask has already been formed, and the mask entries are sensitive
2436 // to the sizes of the inputs.
2437 bool IsSizeChangeShuffle =
2438 isa<ShuffleVectorInst>(L) &&
2439 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2441 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2442 // We can have at most two unique vector inputs.
2443 bool CanUseInputs = true;
2446 I1 = LEE->getOperand(0);
2448 I1 = LSV->getOperand(0);
2449 I2 = LSV->getOperand(1);
2450 if (I2 == I1 || isa<UndefValue>(I2))
2455 Value *I3 = HEE->getOperand(0);
2456 if (!I2 && I3 != I1)
2458 else if (I3 != I1 && I3 != I2)
2459 CanUseInputs = false;
2461 Value *I3 = HSV->getOperand(0);
2462 if (!I2 && I3 != I1)
2464 else if (I3 != I1 && I3 != I2)
2465 CanUseInputs = false;
2468 Value *I4 = HSV->getOperand(1);
2469 if (!isa<UndefValue>(I4)) {
2470 if (!I2 && I4 != I1)
2472 else if (I4 != I1 && I4 != I2)
2473 CanUseInputs = false;
2480 cast<Instruction>(LOp)->getOperand(0)->getType()
2481 ->getVectorNumElements();
2484 cast<Instruction>(HOp)->getOperand(0)->getType()
2485 ->getVectorNumElements();
2487 // We have one or two input vectors. We need to map each index of the
2488 // operands to the index of the original vector.
2489 SmallVector<std::pair<int, int>, 8> II(numElem);
2490 for (unsigned i = 0; i < numElemL; ++i) {
2494 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2495 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2497 Idx = LSV->getMaskValue(i);
2498 if (Idx < (int) LOpElem) {
2499 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2502 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2506 II[i] = std::pair<int, int>(Idx, INum);
2508 for (unsigned i = 0; i < numElemH; ++i) {
2512 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2513 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2515 Idx = HSV->getMaskValue(i);
2516 if (Idx < (int) HOpElem) {
2517 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2520 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2524 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2527 // We now have an array which tells us from which index of which
2528 // input vector each element of the operand comes.
2529 VectorType *I1T = cast<VectorType>(I1->getType());
2530 unsigned I1Elem = I1T->getNumElements();
2533 // In this case there is only one underlying vector input. Check for
2534 // the trivial case where we can use the input directly.
2535 if (I1Elem == numElem) {
2536 bool ElemInOrder = true;
2537 for (unsigned i = 0; i < numElem; ++i) {
2538 if (II[i].first != (int) i && II[i].first != -1) {
2539 ElemInOrder = false;
2548 // A shuffle is needed.
2549 std::vector<Constant *> Mask(numElem);
2550 for (unsigned i = 0; i < numElem; ++i) {
2551 int Idx = II[i].first;
2553 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2555 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2559 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2560 ConstantVector::get(Mask),
2561 getReplacementName(IBeforeJ ? I : J,
2563 S->insertBefore(IBeforeJ ? J : I);
2567 VectorType *I2T = cast<VectorType>(I2->getType());
2568 unsigned I2Elem = I2T->getNumElements();
2570 // This input comes from two distinct vectors. The first step is to
2571 // make sure that both vectors are the same length. If not, the
2572 // smaller one will need to grow before they can be shuffled together.
2573 if (I1Elem < I2Elem) {
2574 std::vector<Constant *> Mask(I2Elem);
2576 for (; v < I1Elem; ++v)
2577 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2578 for (; v < I2Elem; ++v)
2579 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2581 Instruction *NewI1 =
2582 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2583 ConstantVector::get(Mask),
2584 getReplacementName(IBeforeJ ? I : J,
2586 NewI1->insertBefore(IBeforeJ ? J : I);
2590 } else if (I1Elem > I2Elem) {
2591 std::vector<Constant *> Mask(I1Elem);
2593 for (; v < I2Elem; ++v)
2594 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2595 for (; v < I1Elem; ++v)
2596 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2598 Instruction *NewI2 =
2599 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2600 ConstantVector::get(Mask),
2601 getReplacementName(IBeforeJ ? I : J,
2603 NewI2->insertBefore(IBeforeJ ? J : I);
2609 // Now that both I1 and I2 are the same length we can shuffle them
2610 // together (and use the result).
2611 std::vector<Constant *> Mask(numElem);
2612 for (unsigned v = 0; v < numElem; ++v) {
2613 if (II[v].first == -1) {
2614 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2616 int Idx = II[v].first + II[v].second * I1Elem;
2617 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2621 Instruction *NewOp =
2622 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2623 getReplacementName(IBeforeJ ? I : J, true, o));
2624 NewOp->insertBefore(IBeforeJ ? J : I);
2629 Type *ArgType = ArgTypeL;
2630 if (numElemL < numElemH) {
2631 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2632 ArgTypeL, VArgType, IBeforeJ, 1)) {
2633 // This is another short-circuit case: we're combining a scalar into
2634 // a vector that is formed by an IE chain. We've just expanded the IE
2635 // chain, now insert the scalar and we're done.
2637 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2638 getReplacementName(IBeforeJ ? I : J, true, o));
2639 S->insertBefore(IBeforeJ ? J : I);
2641 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2642 ArgTypeH, IBeforeJ)) {
2643 // The two vector inputs to the shuffle must be the same length,
2644 // so extend the smaller vector to be the same length as the larger one.
2648 std::vector<Constant *> Mask(numElemH);
2650 for (; v < numElemL; ++v)
2651 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2652 for (; v < numElemH; ++v)
2653 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2655 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2656 ConstantVector::get(Mask),
2657 getReplacementName(IBeforeJ ? I : J,
2660 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2661 getReplacementName(IBeforeJ ? I : J,
2665 NLOp->insertBefore(IBeforeJ ? J : I);
2670 } else if (numElemL > numElemH) {
2671 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2672 ArgTypeH, VArgType, IBeforeJ)) {
2674 InsertElementInst::Create(LOp, HOp,
2675 ConstantInt::get(Type::getInt32Ty(Context),
2677 getReplacementName(IBeforeJ ? I : J,
2679 S->insertBefore(IBeforeJ ? J : I);
2681 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2682 ArgTypeL, IBeforeJ)) {
2685 std::vector<Constant *> Mask(numElemL);
2687 for (; v < numElemH; ++v)
2688 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2689 for (; v < numElemL; ++v)
2690 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2692 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2693 ConstantVector::get(Mask),
2694 getReplacementName(IBeforeJ ? I : J,
2697 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2698 getReplacementName(IBeforeJ ? I : J,
2702 NHOp->insertBefore(IBeforeJ ? J : I);
2707 if (ArgType->isVectorTy()) {
2708 unsigned numElem = VArgType->getVectorNumElements();
2709 std::vector<Constant*> Mask(numElem);
2710 for (unsigned v = 0; v < numElem; ++v) {
2712 // If the low vector was expanded, we need to skip the extra
2713 // undefined entries.
2714 if (v >= numElemL && numElemH > numElemL)
2715 Idx += (numElemH - numElemL);
2716 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2719 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2720 ConstantVector::get(Mask),
2721 getReplacementName(IBeforeJ ? I : J, true, o));
2722 BV->insertBefore(IBeforeJ ? J : I);
2726 Instruction *BV1 = InsertElementInst::Create(
2727 UndefValue::get(VArgType), LOp, CV0,
2728 getReplacementName(IBeforeJ ? I : J,
2730 BV1->insertBefore(IBeforeJ ? J : I);
2731 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2732 getReplacementName(IBeforeJ ? I : J,
2734 BV2->insertBefore(IBeforeJ ? J : I);
2738 // This function creates an array of values that will be used as the inputs
2739 // to the vector instruction that fuses I with J.
2740 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2741 Instruction *I, Instruction *J,
2742 SmallVectorImpl<Value *> &ReplacedOperands,
2744 unsigned NumOperands = I->getNumOperands();
2746 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2747 // Iterate backward so that we look at the store pointer
2748 // first and know whether or not we need to flip the inputs.
2750 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2751 // This is the pointer for a load/store instruction.
2752 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2754 } else if (isa<CallInst>(I)) {
2755 Function *F = cast<CallInst>(I)->getCalledFunction();
2756 Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
2757 if (o == NumOperands-1) {
2758 BasicBlock &BB = *I->getParent();
2760 Module *M = BB.getParent()->getParent();
2761 Type *ArgTypeI = I->getType();
2762 Type *ArgTypeJ = J->getType();
2763 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2765 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2767 } else if (IID == Intrinsic::powi && o == 1) {
2768 // The second argument of powi is a single integer and we've already
2769 // checked that both arguments are equal. As a result, we just keep
2770 // I's second argument.
2771 ReplacedOperands[o] = I->getOperand(o);
2774 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2775 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2779 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2783 // This function creates two values that represent the outputs of the
2784 // original I and J instructions. These are generally vector shuffles
2785 // or extracts. In many cases, these will end up being unused and, thus,
2786 // eliminated by later passes.
2787 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2788 Instruction *J, Instruction *K,
2789 Instruction *&InsertionPt,
2790 Instruction *&K1, Instruction *&K2) {
2791 if (isa<StoreInst>(I)) {
2792 AA->replaceWithNewValue(I, K);
2793 AA->replaceWithNewValue(J, K);
2795 Type *IType = I->getType();
2796 Type *JType = J->getType();
2798 VectorType *VType = getVecTypeForPair(IType, JType);
2799 unsigned numElem = VType->getNumElements();
2801 unsigned numElemI = getNumScalarElements(IType);
2802 unsigned numElemJ = getNumScalarElements(JType);
2804 if (IType->isVectorTy()) {
2805 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2806 for (unsigned v = 0; v < numElemI; ++v) {
2807 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2808 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2811 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2812 ConstantVector::get( Mask1),
2813 getReplacementName(K, false, 1));
2815 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2816 K1 = ExtractElementInst::Create(K, CV0,
2817 getReplacementName(K, false, 1));
2820 if (JType->isVectorTy()) {
2821 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2822 for (unsigned v = 0; v < numElemJ; ++v) {
2823 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2824 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2827 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2828 ConstantVector::get( Mask2),
2829 getReplacementName(K, false, 2));
2831 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2832 K2 = ExtractElementInst::Create(K, CV1,
2833 getReplacementName(K, false, 2));
2837 K2->insertAfter(K1);
2842 // Move all uses of the function I (including pairing-induced uses) after J.
2843 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2844 DenseSet<ValuePair> &LoadMoveSetPairs,
2845 Instruction *I, Instruction *J) {
2846 // Skip to the first instruction past I.
2847 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2849 DenseSet<Value *> Users;
2850 AliasSetTracker WriteSet(*AA);
2851 if (I->mayWriteToMemory()) WriteSet.add(I);
2853 for (; cast<Instruction>(L) != J; ++L)
2854 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2856 assert(cast<Instruction>(L) == J &&
2857 "Tracking has not proceeded far enough to check for dependencies");
2858 // If J is now in the use set of I, then trackUsesOfI will return true
2859 // and we have a dependency cycle (and the fusing operation must abort).
2860 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2863 // Move all uses of the function I (including pairing-induced uses) after J.
2864 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2865 DenseSet<ValuePair> &LoadMoveSetPairs,
2866 Instruction *&InsertionPt,
2867 Instruction *I, Instruction *J) {
2868 // Skip to the first instruction past I.
2869 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2871 DenseSet<Value *> Users;
2872 AliasSetTracker WriteSet(*AA);
2873 if (I->mayWriteToMemory()) WriteSet.add(I);
2875 for (; cast<Instruction>(L) != J;) {
2876 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2877 // Move this instruction
2878 Instruction *InstToMove = L; ++L;
2880 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2881 " to after " << *InsertionPt << "\n");
2882 InstToMove->removeFromParent();
2883 InstToMove->insertAfter(InsertionPt);
2884 InsertionPt = InstToMove;
2891 // Collect all load instruction that are in the move set of a given first
2892 // pair member. These loads depend on the first instruction, I, and so need
2893 // to be moved after J (the second instruction) when the pair is fused.
2894 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2895 DenseMap<Value *, Value *> &ChosenPairs,
2896 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2897 DenseSet<ValuePair> &LoadMoveSetPairs,
2899 // Skip to the first instruction past I.
2900 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2902 DenseSet<Value *> Users;
2903 AliasSetTracker WriteSet(*AA);
2904 if (I->mayWriteToMemory()) WriteSet.add(I);
2906 // Note: We cannot end the loop when we reach J because J could be moved
2907 // farther down the use chain by another instruction pairing. Also, J
2908 // could be before I if this is an inverted input.
2909 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2910 if (trackUsesOfI(Users, WriteSet, I, L)) {
2911 if (L->mayReadFromMemory()) {
2912 LoadMoveSet[L].push_back(I);
2913 LoadMoveSetPairs.insert(ValuePair(L, I));
2919 // In cases where both load/stores and the computation of their pointers
2920 // are chosen for vectorization, we can end up in a situation where the
2921 // aliasing analysis starts returning different query results as the
2922 // process of fusing instruction pairs continues. Because the algorithm
2923 // relies on finding the same use dags here as were found earlier, we'll
2924 // need to precompute the necessary aliasing information here and then
2925 // manually update it during the fusion process.
2926 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2927 std::vector<Value *> &PairableInsts,
2928 DenseMap<Value *, Value *> &ChosenPairs,
2929 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2930 DenseSet<ValuePair> &LoadMoveSetPairs) {
2931 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2932 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2933 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2934 if (P == ChosenPairs.end()) continue;
2936 Instruction *I = cast<Instruction>(P->first);
2937 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2938 LoadMoveSetPairs, I);
2942 // When the first instruction in each pair is cloned, it will inherit its
2943 // parent's metadata. This metadata must be combined with that of the other
2944 // instruction in a safe way.
2945 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2946 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2947 K->getAllMetadataOtherThanDebugLoc(Metadata);
2948 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2949 unsigned Kind = Metadata[i].first;
2950 MDNode *JMD = J->getMetadata(Kind);
2951 MDNode *KMD = Metadata[i].second;
2955 K->setMetadata(Kind, 0); // Remove unknown metadata
2957 case LLVMContext::MD_tbaa:
2958 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2960 case LLVMContext::MD_fpmath:
2961 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2967 // This function fuses the chosen instruction pairs into vector instructions,
2968 // taking care preserve any needed scalar outputs and, then, it reorders the
2969 // remaining instructions as needed (users of the first member of the pair
2970 // need to be moved to after the location of the second member of the pair
2971 // because the vector instruction is inserted in the location of the pair's
2973 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2974 std::vector<Value *> &PairableInsts,
2975 DenseMap<Value *, Value *> &ChosenPairs,
2976 DenseSet<ValuePair> &FixedOrderPairs,
2977 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2978 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2979 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
2980 LLVMContext& Context = BB.getContext();
2982 // During the vectorization process, the order of the pairs to be fused
2983 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2984 // list. After a pair is fused, the flipped pair is removed from the list.
2985 DenseSet<ValuePair> FlippedPairs;
2986 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2987 E = ChosenPairs.end(); P != E; ++P)
2988 FlippedPairs.insert(ValuePair(P->second, P->first));
2989 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2990 E = FlippedPairs.end(); P != E; ++P)
2991 ChosenPairs.insert(*P);
2993 DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
2994 DenseSet<ValuePair> LoadMoveSetPairs;
2995 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2996 LoadMoveSet, LoadMoveSetPairs);
2998 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
3000 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
3001 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
3002 if (P == ChosenPairs.end()) {
3007 if (getDepthFactor(P->first) == 0) {
3008 // These instructions are not really fused, but are tracked as though
3009 // they are. Any case in which it would be interesting to fuse them
3010 // will be taken care of by InstCombine.
3016 Instruction *I = cast<Instruction>(P->first),
3017 *J = cast<Instruction>(P->second);
3019 DEBUG(dbgs() << "BBV: fusing: " << *I <<
3020 " <-> " << *J << "\n");
3022 // Remove the pair and flipped pair from the list.
3023 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
3024 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
3025 ChosenPairs.erase(FP);
3026 ChosenPairs.erase(P);
3028 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
3029 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
3031 " aborted because of non-trivial dependency cycle\n");
3037 // If the pair must have the other order, then flip it.
3038 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
3039 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
3040 // This pair does not have a fixed order, and so we might want to
3041 // flip it if that will yield fewer shuffles. We count the number
3042 // of dependencies connected via swaps, and those directly connected,
3043 // and flip the order if the number of swaps is greater.
3044 bool OrigOrder = true;
3045 DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
3046 ConnectedPairDeps.find(ValuePair(I, J));
3047 if (IJ == ConnectedPairDeps.end()) {
3048 IJ = ConnectedPairDeps.find(ValuePair(J, I));
3052 if (IJ != ConnectedPairDeps.end()) {
3053 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3054 for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3055 TE = IJ->second.end(); T != TE; ++T) {
3056 VPPair Q(IJ->first, *T);
3057 DenseMap<VPPair, unsigned>::iterator R =
3058 PairConnectionTypes.find(VPPair(Q.second, Q.first));
3059 assert(R != PairConnectionTypes.end() &&
3060 "Cannot find pair connection type");
3061 if (R->second == PairConnectionDirect)
3063 else if (R->second == PairConnectionSwap)
3068 std::swap(NumDepsDirect, NumDepsSwap);
3070 if (NumDepsSwap > NumDepsDirect) {
3071 FlipPairOrder = true;
3072 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3073 " <-> " << *J << "\n");
3078 Instruction *L = I, *H = J;
3082 // If the pair being fused uses the opposite order from that in the pair
3083 // connection map, then we need to flip the types.
3084 DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3085 ConnectedPairs.find(ValuePair(H, L));
3086 if (HL != ConnectedPairs.end())
3087 for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3088 TE = HL->second.end(); T != TE; ++T) {
3089 VPPair Q(HL->first, *T);
3090 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3091 assert(R != PairConnectionTypes.end() &&
3092 "Cannot find pair connection type");
3093 if (R->second == PairConnectionDirect)
3094 R->second = PairConnectionSwap;
3095 else if (R->second == PairConnectionSwap)
3096 R->second = PairConnectionDirect;
3099 bool LBeforeH = !FlipPairOrder;
3100 unsigned NumOperands = I->getNumOperands();
3101 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3102 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3105 // Make a copy of the original operation, change its type to the vector
3106 // type and replace its operands with the vector operands.
3107 Instruction *K = L->clone();
3110 else if (H->hasName())
3113 if (!isa<StoreInst>(K))
3114 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3116 combineMetadata(K, H);
3117 K->intersectOptionalDataWith(H);
3119 for (unsigned o = 0; o < NumOperands; ++o)
3120 K->setOperand(o, ReplacedOperands[o]);
3124 // Instruction insertion point:
3125 Instruction *InsertionPt = K;
3126 Instruction *K1 = 0, *K2 = 0;
3127 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3129 // The use dag of the first original instruction must be moved to after
3130 // the location of the second instruction. The entire use dag of the
3131 // first instruction is disjoint from the input dag of the second
3132 // (by definition), and so commutes with it.
3134 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3136 if (!isa<StoreInst>(I)) {
3137 L->replaceAllUsesWith(K1);
3138 H->replaceAllUsesWith(K2);
3139 AA->replaceWithNewValue(L, K1);
3140 AA->replaceWithNewValue(H, K2);
3143 // Instructions that may read from memory may be in the load move set.
3144 // Once an instruction is fused, we no longer need its move set, and so
3145 // the values of the map never need to be updated. However, when a load
3146 // is fused, we need to merge the entries from both instructions in the
3147 // pair in case those instructions were in the move set of some other
3148 // yet-to-be-fused pair. The loads in question are the keys of the map.
3149 if (I->mayReadFromMemory()) {
3150 std::vector<ValuePair> NewSetMembers;
3151 DenseMap<Value *, std::vector<Value *> >::iterator II =
3152 LoadMoveSet.find(I);
3153 if (II != LoadMoveSet.end())
3154 for (std::vector<Value *>::iterator N = II->second.begin(),
3155 NE = II->second.end(); N != NE; ++N)
3156 NewSetMembers.push_back(ValuePair(K, *N));
3157 DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3158 LoadMoveSet.find(J);
3159 if (JJ != LoadMoveSet.end())
3160 for (std::vector<Value *>::iterator N = JJ->second.begin(),
3161 NE = JJ->second.end(); N != NE; ++N)
3162 NewSetMembers.push_back(ValuePair(K, *N));
3163 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3164 AE = NewSetMembers.end(); A != AE; ++A) {
3165 LoadMoveSet[A->first].push_back(A->second);
3166 LoadMoveSetPairs.insert(*A);
3170 // Before removing I, set the iterator to the next instruction.
3171 PI = std::next(BasicBlock::iterator(I));
3172 if (cast<Instruction>(PI) == J)
3177 I->eraseFromParent();
3178 J->eraseFromParent();
3180 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3184 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3188 char BBVectorize::ID = 0;
3189 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3190 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3191 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3192 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3193 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3195 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3197 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3198 return new BBVectorize(C);
3202 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3203 BBVectorize BBVectorizer(P, C);
3204 return BBVectorizer.vectorizeBB(BB);
3207 //===----------------------------------------------------------------------===//
3208 VectorizeConfig::VectorizeConfig() {
3209 VectorBits = ::VectorBits;
3210 VectorizeBools = !::NoBools;
3211 VectorizeInts = !::NoInts;
3212 VectorizeFloats = !::NoFloats;
3213 VectorizePointers = !::NoPointers;
3214 VectorizeCasts = !::NoCasts;
3215 VectorizeMath = !::NoMath;
3216 VectorizeFMA = !::NoFMA;
3217 VectorizeSelect = !::NoSelect;
3218 VectorizeCmp = !::NoCmp;
3219 VectorizeGEP = !::NoGEP;
3220 VectorizeMemOps = !::NoMemOps;
3221 AlignedOnly = ::AlignedOnly;
3222 ReqChainDepth= ::ReqChainDepth;
3223 SearchLimit = ::SearchLimit;
3224 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3225 SplatBreaksChain = ::SplatBreaksChain;
3226 MaxInsts = ::MaxInsts;
3227 MaxPairs = ::MaxPairs;
3228 MaxIter = ::MaxIter;
3229 Pow2LenOnly = ::Pow2LenOnly;
3230 NoMemOpBoost = ::NoMemOpBoost;
3231 FastDep = ::FastDep;