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/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/AliasSetTracker.h"
36 #include "llvm/Analysis/ScalarEvolution.h"
37 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Vectorize.h"
49 static cl::opt<unsigned>
50 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
51 cl::desc("The required chain depth for vectorization"));
53 static cl::opt<unsigned>
54 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
55 cl::desc("The maximum search distance for instruction pairs"));
58 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
59 cl::desc("Replicating one element to a pair breaks the chain"));
61 static cl::opt<unsigned>
62 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
63 cl::desc("The size of the native vector registers"));
65 static cl::opt<unsigned>
66 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
67 cl::desc("The maximum number of pairing iterations"));
69 static cl::opt<unsigned>
70 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
71 cl::desc("The maximum number of pairable instructions per group"));
73 static cl::opt<unsigned>
74 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
75 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
76 " a full cycle check"));
79 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
80 cl::desc("Don't try to vectorize integer values"));
83 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
84 cl::desc("Don't try to vectorize floating-point values"));
87 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
88 cl::desc("Don't try to vectorize casting (conversion) operations"));
91 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
92 cl::desc("Don't try to vectorize floating-point math intrinsics"));
95 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
96 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
99 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
100 cl::desc("Don't try to vectorize select instructions"));
103 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
104 cl::desc("Don't try to vectorize loads and stores"));
107 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
108 cl::desc("Only generate aligned loads and stores"));
111 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
112 cl::init(false), cl::Hidden,
113 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
116 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
117 cl::desc("Use a fast instruction dependency analysis"));
121 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
122 cl::init(false), cl::Hidden,
123 cl::desc("When debugging is enabled, output information on the"
124 " instruction-examination process"));
126 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
127 cl::init(false), cl::Hidden,
128 cl::desc("When debugging is enabled, output information on the"
129 " candidate-selection process"));
131 DebugPairSelection("bb-vectorize-debug-pair-selection",
132 cl::init(false), cl::Hidden,
133 cl::desc("When debugging is enabled, output information on the"
134 " pair-selection process"));
136 DebugCycleCheck("bb-vectorize-debug-cycle-check",
137 cl::init(false), cl::Hidden,
138 cl::desc("When debugging is enabled, output information on the"
139 " cycle-checking process"));
142 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
145 struct BBVectorize : public BasicBlockPass {
146 static char ID; // Pass identification, replacement for typeid
148 const VectorizeConfig Config;
150 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
151 : BasicBlockPass(ID), Config(C) {
152 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
155 BBVectorize(Pass *P, const VectorizeConfig &C)
156 : BasicBlockPass(ID), Config(C) {
157 AA = &P->getAnalysis<AliasAnalysis>();
158 SE = &P->getAnalysis<ScalarEvolution>();
159 TD = P->getAnalysisIfAvailable<TargetData>();
162 typedef std::pair<Value *, Value *> ValuePair;
163 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
164 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
165 typedef std::pair<std::multimap<Value *, Value *>::iterator,
166 std::multimap<Value *, Value *>::iterator> VPIteratorPair;
167 typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
168 std::multimap<ValuePair, ValuePair>::iterator>
175 // FIXME: const correct?
177 bool vectorizePairs(BasicBlock &BB);
179 bool getCandidatePairs(BasicBlock &BB,
180 BasicBlock::iterator &Start,
181 std::multimap<Value *, Value *> &CandidatePairs,
182 std::vector<Value *> &PairableInsts);
184 void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
185 std::vector<Value *> &PairableInsts,
186 std::multimap<ValuePair, ValuePair> &ConnectedPairs);
188 void buildDepMap(BasicBlock &BB,
189 std::multimap<Value *, Value *> &CandidatePairs,
190 std::vector<Value *> &PairableInsts,
191 DenseSet<ValuePair> &PairableInstUsers);
193 void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
194 std::vector<Value *> &PairableInsts,
195 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
196 DenseSet<ValuePair> &PairableInstUsers,
197 DenseMap<Value *, Value *>& ChosenPairs);
199 void fuseChosenPairs(BasicBlock &BB,
200 std::vector<Value *> &PairableInsts,
201 DenseMap<Value *, Value *>& ChosenPairs);
203 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
205 bool areInstsCompatible(Instruction *I, Instruction *J,
206 bool IsSimpleLoadStore);
208 bool trackUsesOfI(DenseSet<Value *> &Users,
209 AliasSetTracker &WriteSet, Instruction *I,
210 Instruction *J, bool UpdateUsers = true,
211 std::multimap<Value *, Value *> *LoadMoveSet = 0);
213 void computePairsConnectedTo(
214 std::multimap<Value *, Value *> &CandidatePairs,
215 std::vector<Value *> &PairableInsts,
216 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
219 bool pairsConflict(ValuePair P, ValuePair Q,
220 DenseSet<ValuePair> &PairableInstUsers,
221 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
223 bool pairWillFormCycle(ValuePair P,
224 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
225 DenseSet<ValuePair> &CurrentPairs);
228 std::multimap<Value *, Value *> &CandidatePairs,
229 std::vector<Value *> &PairableInsts,
230 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
231 DenseSet<ValuePair> &PairableInstUsers,
232 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
233 DenseMap<Value *, Value *> &ChosenPairs,
234 DenseMap<ValuePair, size_t> &Tree,
235 DenseSet<ValuePair> &PrunedTree, ValuePair J,
238 void buildInitialTreeFor(
239 std::multimap<Value *, Value *> &CandidatePairs,
240 std::vector<Value *> &PairableInsts,
241 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
242 DenseSet<ValuePair> &PairableInstUsers,
243 DenseMap<Value *, Value *> &ChosenPairs,
244 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
246 void findBestTreeFor(
247 std::multimap<Value *, Value *> &CandidatePairs,
248 std::vector<Value *> &PairableInsts,
249 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
250 DenseSet<ValuePair> &PairableInstUsers,
251 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
252 DenseMap<Value *, Value *> &ChosenPairs,
253 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
254 size_t &BestEffSize, VPIteratorPair ChoiceRange,
257 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
258 Instruction *J, unsigned o, bool &FlipMemInputs);
260 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
261 unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
262 unsigned IdxOffset, std::vector<Constant*> &Mask);
264 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
267 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
268 Instruction *J, unsigned o, bool FlipMemInputs);
270 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
271 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
272 bool &FlipMemInputs);
274 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
275 Instruction *J, Instruction *K,
276 Instruction *&InsertionPt, Instruction *&K1,
277 Instruction *&K2, bool &FlipMemInputs);
279 void collectPairLoadMoveSet(BasicBlock &BB,
280 DenseMap<Value *, Value *> &ChosenPairs,
281 std::multimap<Value *, Value *> &LoadMoveSet,
284 void collectLoadMoveSet(BasicBlock &BB,
285 std::vector<Value *> &PairableInsts,
286 DenseMap<Value *, Value *> &ChosenPairs,
287 std::multimap<Value *, Value *> &LoadMoveSet);
289 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
290 std::multimap<Value *, Value *> &LoadMoveSet,
291 Instruction *I, Instruction *J);
293 void moveUsesOfIAfterJ(BasicBlock &BB,
294 std::multimap<Value *, Value *> &LoadMoveSet,
295 Instruction *&InsertionPt,
296 Instruction *I, Instruction *J);
298 bool vectorizeBB(BasicBlock &BB) {
299 bool changed = false;
300 // Iterate a sufficient number of times to merge types of size 1 bit,
301 // then 2 bits, then 4, etc. up to half of the target vector width of the
302 // target vector register.
303 for (unsigned v = 2, n = 1;
304 v <= Config.VectorBits && (!Config.MaxIter || n <= Config.MaxIter);
306 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
307 " for " << BB.getName() << " in " <<
308 BB.getParent()->getName() << "...\n");
309 if (vectorizePairs(BB))
315 DEBUG(dbgs() << "BBV: done!\n");
319 virtual bool runOnBasicBlock(BasicBlock &BB) {
320 AA = &getAnalysis<AliasAnalysis>();
321 SE = &getAnalysis<ScalarEvolution>();
322 TD = getAnalysisIfAvailable<TargetData>();
324 return vectorizeBB(BB);
327 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
328 BasicBlockPass::getAnalysisUsage(AU);
329 AU.addRequired<AliasAnalysis>();
330 AU.addRequired<ScalarEvolution>();
331 AU.addPreserved<AliasAnalysis>();
332 AU.addPreserved<ScalarEvolution>();
333 AU.setPreservesCFG();
336 // This returns the vector type that holds a pair of the provided type.
337 // If the provided type is already a vector, then its length is doubled.
338 static inline VectorType *getVecTypeForPair(Type *ElemTy) {
339 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
340 unsigned numElem = VTy->getNumElements();
341 return VectorType::get(ElemTy->getScalarType(), numElem*2);
344 return VectorType::get(ElemTy, 2);
347 // Returns the weight associated with the provided value. A chain of
348 // candidate pairs has a length given by the sum of the weights of its
349 // members (one weight per pair; the weight of each member of the pair
350 // is assumed to be the same). This length is then compared to the
351 // chain-length threshold to determine if a given chain is significant
352 // enough to be vectorized. The length is also used in comparing
353 // candidate chains where longer chains are considered to be better.
354 // Note: when this function returns 0, the resulting instructions are
355 // not actually fused.
356 inline size_t getDepthFactor(Value *V) {
357 // InsertElement and ExtractElement have a depth factor of zero. This is
358 // for two reasons: First, they cannot be usefully fused. Second, because
359 // the pass generates a lot of these, they can confuse the simple metric
360 // used to compare the trees in the next iteration. Thus, giving them a
361 // weight of zero allows the pass to essentially ignore them in
362 // subsequent iterations when looking for vectorization opportunities
363 // while still tracking dependency chains that flow through those
365 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
368 // Give a load or store half of the required depth so that load/store
369 // pairs will vectorize.
370 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
371 return Config.ReqChainDepth/2;
376 // This determines the relative offset of two loads or stores, returning
377 // true if the offset could be determined to be some constant value.
378 // For example, if OffsetInElmts == 1, then J accesses the memory directly
379 // after I; if OffsetInElmts == -1 then I accesses the memory
380 // directly after J. This function assumes that both instructions
381 // have the same type.
382 bool getPairPtrInfo(Instruction *I, Instruction *J,
383 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
384 int64_t &OffsetInElmts) {
386 if (isa<LoadInst>(I)) {
387 IPtr = cast<LoadInst>(I)->getPointerOperand();
388 JPtr = cast<LoadInst>(J)->getPointerOperand();
389 IAlignment = cast<LoadInst>(I)->getAlignment();
390 JAlignment = cast<LoadInst>(J)->getAlignment();
392 IPtr = cast<StoreInst>(I)->getPointerOperand();
393 JPtr = cast<StoreInst>(J)->getPointerOperand();
394 IAlignment = cast<StoreInst>(I)->getAlignment();
395 JAlignment = cast<StoreInst>(J)->getAlignment();
398 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
399 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
401 // If this is a trivial offset, then we'll get something like
402 // 1*sizeof(type). With target data, which we need anyway, this will get
403 // constant folded into a number.
404 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
405 if (const SCEVConstant *ConstOffSCEV =
406 dyn_cast<SCEVConstant>(OffsetSCEV)) {
407 ConstantInt *IntOff = ConstOffSCEV->getValue();
408 int64_t Offset = IntOff->getSExtValue();
410 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
411 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
413 assert(VTy == cast<PointerType>(JPtr->getType())->getElementType());
415 OffsetInElmts = Offset/VTyTSS;
416 return (abs64(Offset) % VTyTSS) == 0;
422 // Returns true if the provided CallInst represents an intrinsic that can
424 bool isVectorizableIntrinsic(CallInst* I) {
425 Function *F = I->getCalledFunction();
426 if (!F) return false;
428 unsigned IID = F->getIntrinsicID();
429 if (!IID) return false;
434 case Intrinsic::sqrt:
435 case Intrinsic::powi:
439 case Intrinsic::log2:
440 case Intrinsic::log10:
442 case Intrinsic::exp2:
444 return Config.VectorizeMath;
446 return Config.VectorizeFMA;
450 // Returns true if J is the second element in some pair referenced by
451 // some multimap pair iterator pair.
452 template <typename V>
453 bool isSecondInIteratorPair(V J, std::pair<
454 typename std::multimap<V, V>::iterator,
455 typename std::multimap<V, V>::iterator> PairRange) {
456 for (typename std::multimap<V, V>::iterator K = PairRange.first;
457 K != PairRange.second; ++K)
458 if (K->second == J) return true;
464 // This function implements one vectorization iteration on the provided
465 // basic block. It returns true if the block is changed.
466 bool BBVectorize::vectorizePairs(BasicBlock &BB) {
468 BasicBlock::iterator Start = BB.getFirstInsertionPt();
470 std::vector<Value *> AllPairableInsts;
471 DenseMap<Value *, Value *> AllChosenPairs;
474 std::vector<Value *> PairableInsts;
475 std::multimap<Value *, Value *> CandidatePairs;
476 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
478 if (PairableInsts.empty()) continue;
480 // Now we have a map of all of the pairable instructions and we need to
481 // select the best possible pairing. A good pairing is one such that the
482 // users of the pair are also paired. This defines a (directed) forest
483 // over the pairs such that two pairs are connected iff the second pair
486 // Note that it only matters that both members of the second pair use some
487 // element of the first pair (to allow for splatting).
489 std::multimap<ValuePair, ValuePair> ConnectedPairs;
490 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
491 if (ConnectedPairs.empty()) continue;
493 // Build the pairable-instruction dependency map
494 DenseSet<ValuePair> PairableInstUsers;
495 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
497 // There is now a graph of the connected pairs. For each variable, pick
498 // the pairing with the largest tree meeting the depth requirement on at
499 // least one branch. Then select all pairings that are part of that tree
500 // and remove them from the list of available pairings and pairable
503 DenseMap<Value *, Value *> ChosenPairs;
504 choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
505 PairableInstUsers, ChosenPairs);
507 if (ChosenPairs.empty()) continue;
508 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
509 PairableInsts.end());
510 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
511 } while (ShouldContinue);
513 if (AllChosenPairs.empty()) return false;
514 NumFusedOps += AllChosenPairs.size();
516 // A set of pairs has now been selected. It is now necessary to replace the
517 // paired instructions with vector instructions. For this procedure each
518 // operand must be replaced with a vector operand. This vector is formed
519 // by using build_vector on the old operands. The replaced values are then
520 // replaced with a vector_extract on the result. Subsequent optimization
521 // passes should coalesce the build/extract combinations.
523 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
527 // This function returns true if the provided instruction is capable of being
528 // fused into a vector instruction. This determination is based only on the
529 // type and other attributes of the instruction.
530 bool BBVectorize::isInstVectorizable(Instruction *I,
531 bool &IsSimpleLoadStore) {
532 IsSimpleLoadStore = false;
534 if (CallInst *C = dyn_cast<CallInst>(I)) {
535 if (!isVectorizableIntrinsic(C))
537 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
538 // Vectorize simple loads if possbile:
539 IsSimpleLoadStore = L->isSimple();
540 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
542 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
543 // Vectorize simple stores if possbile:
544 IsSimpleLoadStore = S->isSimple();
545 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
547 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
548 // We can vectorize casts, but not casts of pointer types, etc.
549 if (!Config.VectorizeCasts)
552 Type *SrcTy = C->getSrcTy();
553 if (!SrcTy->isSingleValueType() || SrcTy->isPointerTy())
556 Type *DestTy = C->getDestTy();
557 if (!DestTy->isSingleValueType() || DestTy->isPointerTy())
559 } else if (isa<SelectInst>(I)) {
560 if (!Config.VectorizeSelect)
562 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
563 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
567 // We can't vectorize memory operations without target data
568 if (TD == 0 && IsSimpleLoadStore)
572 if (isa<StoreInst>(I)) {
573 // For stores, it is the value type, not the pointer type that matters
574 // because the value is what will come from a vector register.
576 Value *IVal = cast<StoreInst>(I)->getValueOperand();
577 T1 = IVal->getType();
583 T2 = cast<CastInst>(I)->getSrcTy();
587 // Not every type can be vectorized...
588 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
589 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
592 if (!Config.VectorizeInts
593 && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
596 if (!Config.VectorizeFloats
597 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
600 if (T1->getPrimitiveSizeInBits() > Config.VectorBits/2 ||
601 T2->getPrimitiveSizeInBits() > Config.VectorBits/2)
607 // This function returns true if the two provided instructions are compatible
608 // (meaning that they can be fused into a vector instruction). This assumes
609 // that I has already been determined to be vectorizable and that J is not
610 // in the use tree of I.
611 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
612 bool IsSimpleLoadStore) {
613 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
614 " <-> " << *J << "\n");
616 // Loads and stores can be merged if they have different alignments,
617 // but are otherwise the same.
620 if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
621 if (I->getType() != J->getType())
624 if (LI->getPointerOperand()->getType() !=
625 LJ->getPointerOperand()->getType() ||
626 LI->isVolatile() != LJ->isVolatile() ||
627 LI->getOrdering() != LJ->getOrdering() ||
628 LI->getSynchScope() != LJ->getSynchScope())
630 } else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
631 if (SI->getValueOperand()->getType() !=
632 SJ->getValueOperand()->getType() ||
633 SI->getPointerOperand()->getType() !=
634 SJ->getPointerOperand()->getType() ||
635 SI->isVolatile() != SJ->isVolatile() ||
636 SI->getOrdering() != SJ->getOrdering() ||
637 SI->getSynchScope() != SJ->getSynchScope())
639 } else if (!J->isSameOperationAs(I)) {
642 // FIXME: handle addsub-type operations!
644 if (IsSimpleLoadStore) {
646 unsigned IAlignment, JAlignment;
647 int64_t OffsetInElmts = 0;
648 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
649 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
650 if (Config.AlignedOnly) {
651 Type *aType = isa<StoreInst>(I) ?
652 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
653 // An aligned load or store is possible only if the instruction
654 // with the lower offset has an alignment suitable for the
657 unsigned BottomAlignment = IAlignment;
658 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
660 Type *VType = getVecTypeForPair(aType);
661 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
662 if (BottomAlignment < VecAlignment)
668 } else if (isa<ShuffleVectorInst>(I)) {
669 // Only merge two shuffles if they're both constant
670 return isa<Constant>(I->getOperand(2)) &&
671 isa<Constant>(J->getOperand(2));
672 // FIXME: We may want to vectorize non-constant shuffles also.
675 // The powi intrinsic is special because only the first argument is
676 // vectorized, the second arguments must be equal.
677 CallInst *CI = dyn_cast<CallInst>(I);
679 if (CI && (FI = CI->getCalledFunction()) &&
680 FI->getIntrinsicID() == Intrinsic::powi) {
682 Value *A1I = CI->getArgOperand(1),
683 *A1J = cast<CallInst>(J)->getArgOperand(1);
684 const SCEV *A1ISCEV = SE->getSCEV(A1I),
685 *A1JSCEV = SE->getSCEV(A1J);
686 return (A1ISCEV == A1JSCEV);
692 // Figure out whether or not J uses I and update the users and write-set
693 // structures associated with I. Specifically, Users represents the set of
694 // instructions that depend on I. WriteSet represents the set
695 // of memory locations that are dependent on I. If UpdateUsers is true,
696 // and J uses I, then Users is updated to contain J and WriteSet is updated
697 // to contain any memory locations to which J writes. The function returns
698 // true if J uses I. By default, alias analysis is used to determine
699 // whether J reads from memory that overlaps with a location in WriteSet.
700 // If LoadMoveSet is not null, then it is a previously-computed multimap
701 // where the key is the memory-based user instruction and the value is
702 // the instruction to be compared with I. So, if LoadMoveSet is provided,
703 // then the alias analysis is not used. This is necessary because this
704 // function is called during the process of moving instructions during
705 // vectorization and the results of the alias analysis are not stable during
707 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
708 AliasSetTracker &WriteSet, Instruction *I,
709 Instruction *J, bool UpdateUsers,
710 std::multimap<Value *, Value *> *LoadMoveSet) {
713 // This instruction may already be marked as a user due, for example, to
714 // being a member of a selected pair.
719 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
722 if (I == V || Users.count(V)) {
727 if (!UsesI && J->mayReadFromMemory()) {
729 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
730 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
732 for (AliasSetTracker::iterator W = WriteSet.begin(),
733 WE = WriteSet.end(); W != WE; ++W) {
734 if (W->aliasesUnknownInst(J, *AA)) {
742 if (UsesI && UpdateUsers) {
743 if (J->mayWriteToMemory()) WriteSet.add(J);
750 // This function iterates over all instruction pairs in the provided
751 // basic block and collects all candidate pairs for vectorization.
752 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
753 BasicBlock::iterator &Start,
754 std::multimap<Value *, Value *> &CandidatePairs,
755 std::vector<Value *> &PairableInsts) {
756 BasicBlock::iterator E = BB.end();
757 if (Start == E) return false;
759 bool ShouldContinue = false, IAfterStart = false;
760 for (BasicBlock::iterator I = Start++; I != E; ++I) {
761 if (I == Start) IAfterStart = true;
763 bool IsSimpleLoadStore;
764 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
766 // Look for an instruction with which to pair instruction *I...
767 DenseSet<Value *> Users;
768 AliasSetTracker WriteSet(*AA);
769 bool JAfterStart = IAfterStart;
770 BasicBlock::iterator J = llvm::next(I);
771 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
772 if (J == Start) JAfterStart = true;
774 // Determine if J uses I, if so, exit the loop.
775 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
776 if (Config.FastDep) {
777 // Note: For this heuristic to be effective, independent operations
778 // must tend to be intermixed. This is likely to be true from some
779 // kinds of grouped loop unrolling (but not the generic LLVM pass),
780 // but otherwise may require some kind of reordering pass.
782 // When using fast dependency analysis,
783 // stop searching after first use:
789 // J does not use I, and comes before the first use of I, so it can be
790 // merged with I if the instructions are compatible.
791 if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
793 // J is a candidate for merging with I.
794 if (!PairableInsts.size() ||
795 PairableInsts[PairableInsts.size()-1] != I) {
796 PairableInsts.push_back(I);
799 CandidatePairs.insert(ValuePair(I, J));
801 // The next call to this function must start after the last instruction
802 // selected during this invocation.
804 Start = llvm::next(J);
805 IAfterStart = JAfterStart = false;
808 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
809 << *I << " <-> " << *J << "\n");
811 // If we have already found too many pairs, break here and this function
812 // will be called again starting after the last instruction selected
813 // during this invocation.
814 if (PairableInsts.size() >= Config.MaxInsts) {
815 ShouldContinue = true;
824 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
825 << " instructions with candidate pairs\n");
827 return ShouldContinue;
830 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
831 // it looks for pairs such that both members have an input which is an
832 // output of PI or PJ.
833 void BBVectorize::computePairsConnectedTo(
834 std::multimap<Value *, Value *> &CandidatePairs,
835 std::vector<Value *> &PairableInsts,
836 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
838 // For each possible pairing for this variable, look at the uses of
839 // the first value...
840 for (Value::use_iterator I = P.first->use_begin(),
841 E = P.first->use_end(); I != E; ++I) {
842 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
844 // For each use of the first variable, look for uses of the second
846 for (Value::use_iterator J = P.second->use_begin(),
847 E2 = P.second->use_end(); J != E2; ++J) {
848 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
851 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
852 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
855 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
856 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
859 if (Config.SplatBreaksChain) continue;
860 // Look for cases where just the first value in the pair is used by
861 // both members of another pair (splatting).
862 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
863 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
864 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
868 if (Config.SplatBreaksChain) return;
869 // Look for cases where just the second value in the pair is used by
870 // both members of another pair (splatting).
871 for (Value::use_iterator I = P.second->use_begin(),
872 E = P.second->use_end(); I != E; ++I) {
873 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
875 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
876 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
877 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
882 // This function figures out which pairs are connected. Two pairs are
883 // connected if some output of the first pair forms an input to both members
884 // of the second pair.
885 void BBVectorize::computeConnectedPairs(
886 std::multimap<Value *, Value *> &CandidatePairs,
887 std::vector<Value *> &PairableInsts,
888 std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
890 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
891 PE = PairableInsts.end(); PI != PE; ++PI) {
892 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
894 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
895 P != choiceRange.second; ++P)
896 computePairsConnectedTo(CandidatePairs, PairableInsts,
900 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
901 << " pair connections.\n");
904 // This function builds a set of use tuples such that <A, B> is in the set
905 // if B is in the use tree of A. If B is in the use tree of A, then B
906 // depends on the output of A.
907 void BBVectorize::buildDepMap(
909 std::multimap<Value *, Value *> &CandidatePairs,
910 std::vector<Value *> &PairableInsts,
911 DenseSet<ValuePair> &PairableInstUsers) {
912 DenseSet<Value *> IsInPair;
913 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
914 E = CandidatePairs.end(); C != E; ++C) {
915 IsInPair.insert(C->first);
916 IsInPair.insert(C->second);
919 // Iterate through the basic block, recording all Users of each
920 // pairable instruction.
922 BasicBlock::iterator E = BB.end();
923 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
924 if (IsInPair.find(I) == IsInPair.end()) continue;
926 DenseSet<Value *> Users;
927 AliasSetTracker WriteSet(*AA);
928 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
929 (void) trackUsesOfI(Users, WriteSet, I, J);
931 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
933 PairableInstUsers.insert(ValuePair(I, *U));
937 // Returns true if an input to pair P is an output of pair Q and also an
938 // input of pair Q is an output of pair P. If this is the case, then these
939 // two pairs cannot be simultaneously fused.
940 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
941 DenseSet<ValuePair> &PairableInstUsers,
942 std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
943 // Two pairs are in conflict if they are mutual Users of eachother.
944 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
945 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
946 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
947 PairableInstUsers.count(ValuePair(P.second, Q.second));
948 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
949 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
950 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
951 PairableInstUsers.count(ValuePair(Q.second, P.second));
952 if (PairableInstUserMap) {
953 // FIXME: The expensive part of the cycle check is not so much the cycle
954 // check itself but this edge insertion procedure. This needs some
955 // profiling and probably a different data structure (same is true of
956 // most uses of std::multimap).
958 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
959 if (!isSecondInIteratorPair(P, QPairRange))
960 PairableInstUserMap->insert(VPPair(Q, P));
963 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
964 if (!isSecondInIteratorPair(Q, PPairRange))
965 PairableInstUserMap->insert(VPPair(P, Q));
969 return (QUsesP && PUsesQ);
972 // This function walks the use graph of current pairs to see if, starting
973 // from P, the walk returns to P.
974 bool BBVectorize::pairWillFormCycle(ValuePair P,
975 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
976 DenseSet<ValuePair> &CurrentPairs) {
977 DEBUG(if (DebugCycleCheck)
978 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
979 << *P.second << "\n");
980 // A lookup table of visisted pairs is kept because the PairableInstUserMap
981 // contains non-direct associations.
982 DenseSet<ValuePair> Visited;
983 SmallVector<ValuePair, 32> Q;
984 // General depth-first post-order traversal:
987 ValuePair QTop = Q.pop_back_val();
988 Visited.insert(QTop);
990 DEBUG(if (DebugCycleCheck)
991 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
992 << *QTop.second << "\n");
993 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
994 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
995 C != QPairRange.second; ++C) {
996 if (C->second == P) {
998 << "BBV: rejected to prevent non-trivial cycle formation: "
999 << *C->first.first << " <-> " << *C->first.second << "\n");
1003 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1004 Q.push_back(C->second);
1006 } while (!Q.empty());
1011 // This function builds the initial tree of connected pairs with the
1012 // pair J at the root.
1013 void BBVectorize::buildInitialTreeFor(
1014 std::multimap<Value *, Value *> &CandidatePairs,
1015 std::vector<Value *> &PairableInsts,
1016 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1017 DenseSet<ValuePair> &PairableInstUsers,
1018 DenseMap<Value *, Value *> &ChosenPairs,
1019 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1020 // Each of these pairs is viewed as the root node of a Tree. The Tree
1021 // is then walked (depth-first). As this happens, we keep track of
1022 // the pairs that compose the Tree and the maximum depth of the Tree.
1023 SmallVector<ValuePairWithDepth, 32> Q;
1024 // General depth-first post-order traversal:
1025 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1027 ValuePairWithDepth QTop = Q.back();
1029 // Push each child onto the queue:
1030 bool MoreChildren = false;
1031 size_t MaxChildDepth = QTop.second;
1032 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1033 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1034 k != qtRange.second; ++k) {
1035 // Make sure that this child pair is still a candidate:
1036 bool IsStillCand = false;
1037 VPIteratorPair checkRange =
1038 CandidatePairs.equal_range(k->second.first);
1039 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1040 m != checkRange.second; ++m) {
1041 if (m->second == k->second.second) {
1048 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1049 if (C == Tree.end()) {
1050 size_t d = getDepthFactor(k->second.first);
1051 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1052 MoreChildren = true;
1054 MaxChildDepth = std::max(MaxChildDepth, C->second);
1059 if (!MoreChildren) {
1060 // Record the current pair as part of the Tree:
1061 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1064 } while (!Q.empty());
1067 // Given some initial tree, prune it by removing conflicting pairs (pairs
1068 // that cannot be simultaneously chosen for vectorization).
1069 void BBVectorize::pruneTreeFor(
1070 std::multimap<Value *, Value *> &CandidatePairs,
1071 std::vector<Value *> &PairableInsts,
1072 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1073 DenseSet<ValuePair> &PairableInstUsers,
1074 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1075 DenseMap<Value *, Value *> &ChosenPairs,
1076 DenseMap<ValuePair, size_t> &Tree,
1077 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1078 bool UseCycleCheck) {
1079 SmallVector<ValuePairWithDepth, 32> Q;
1080 // General depth-first post-order traversal:
1081 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1083 ValuePairWithDepth QTop = Q.pop_back_val();
1084 PrunedTree.insert(QTop.first);
1086 // Visit each child, pruning as necessary...
1087 DenseMap<ValuePair, size_t> BestChildren;
1088 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1089 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1090 K != QTopRange.second; ++K) {
1091 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1092 if (C == Tree.end()) continue;
1094 // This child is in the Tree, now we need to make sure it is the
1095 // best of any conflicting children. There could be multiple
1096 // conflicting children, so first, determine if we're keeping
1097 // this child, then delete conflicting children as necessary.
1099 // It is also necessary to guard against pairing-induced
1100 // dependencies. Consider instructions a .. x .. y .. b
1101 // such that (a,b) are to be fused and (x,y) are to be fused
1102 // but a is an input to x and b is an output from y. This
1103 // means that y cannot be moved after b but x must be moved
1104 // after b for (a,b) to be fused. In other words, after
1105 // fusing (a,b) we have y .. a/b .. x where y is an input
1106 // to a/b and x is an output to a/b: x and y can no longer
1107 // be legally fused. To prevent this condition, we must
1108 // make sure that a child pair added to the Tree is not
1109 // both an input and output of an already-selected pair.
1111 // Pairing-induced dependencies can also form from more complicated
1112 // cycles. The pair vs. pair conflicts are easy to check, and so
1113 // that is done explicitly for "fast rejection", and because for
1114 // child vs. child conflicts, we may prefer to keep the current
1115 // pair in preference to the already-selected child.
1116 DenseSet<ValuePair> CurrentPairs;
1119 for (DenseMap<ValuePair, size_t>::iterator C2
1120 = BestChildren.begin(), E2 = BestChildren.end();
1122 if (C2->first.first == C->first.first ||
1123 C2->first.first == C->first.second ||
1124 C2->first.second == C->first.first ||
1125 C2->first.second == C->first.second ||
1126 pairsConflict(C2->first, C->first, PairableInstUsers,
1127 UseCycleCheck ? &PairableInstUserMap : 0)) {
1128 if (C2->second >= C->second) {
1133 CurrentPairs.insert(C2->first);
1136 if (!CanAdd) continue;
1138 // Even worse, this child could conflict with another node already
1139 // selected for the Tree. If that is the case, ignore this child.
1140 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1141 E2 = PrunedTree.end(); T != E2; ++T) {
1142 if (T->first == C->first.first ||
1143 T->first == C->first.second ||
1144 T->second == C->first.first ||
1145 T->second == C->first.second ||
1146 pairsConflict(*T, C->first, PairableInstUsers,
1147 UseCycleCheck ? &PairableInstUserMap : 0)) {
1152 CurrentPairs.insert(*T);
1154 if (!CanAdd) continue;
1156 // And check the queue too...
1157 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1158 E2 = Q.end(); C2 != E2; ++C2) {
1159 if (C2->first.first == C->first.first ||
1160 C2->first.first == C->first.second ||
1161 C2->first.second == C->first.first ||
1162 C2->first.second == C->first.second ||
1163 pairsConflict(C2->first, C->first, PairableInstUsers,
1164 UseCycleCheck ? &PairableInstUserMap : 0)) {
1169 CurrentPairs.insert(C2->first);
1171 if (!CanAdd) continue;
1173 // Last but not least, check for a conflict with any of the
1174 // already-chosen pairs.
1175 for (DenseMap<Value *, Value *>::iterator C2 =
1176 ChosenPairs.begin(), E2 = ChosenPairs.end();
1178 if (pairsConflict(*C2, C->first, PairableInstUsers,
1179 UseCycleCheck ? &PairableInstUserMap : 0)) {
1184 CurrentPairs.insert(*C2);
1186 if (!CanAdd) continue;
1188 // To check for non-trivial cycles formed by the addition of the
1189 // current pair we've formed a list of all relevant pairs, now use a
1190 // graph walk to check for a cycle. We start from the current pair and
1191 // walk the use tree to see if we again reach the current pair. If we
1192 // do, then the current pair is rejected.
1194 // FIXME: It may be more efficient to use a topological-ordering
1195 // algorithm to improve the cycle check. This should be investigated.
1196 if (UseCycleCheck &&
1197 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1200 // This child can be added, but we may have chosen it in preference
1201 // to an already-selected child. Check for this here, and if a
1202 // conflict is found, then remove the previously-selected child
1203 // before adding this one in its place.
1204 for (DenseMap<ValuePair, size_t>::iterator C2
1205 = BestChildren.begin(); C2 != BestChildren.end();) {
1206 if (C2->first.first == C->first.first ||
1207 C2->first.first == C->first.second ||
1208 C2->first.second == C->first.first ||
1209 C2->first.second == C->first.second ||
1210 pairsConflict(C2->first, C->first, PairableInstUsers))
1211 BestChildren.erase(C2++);
1216 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1219 for (DenseMap<ValuePair, size_t>::iterator C
1220 = BestChildren.begin(), E2 = BestChildren.end();
1222 size_t DepthF = getDepthFactor(C->first.first);
1223 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1225 } while (!Q.empty());
1228 // This function finds the best tree of mututally-compatible connected
1229 // pairs, given the choice of root pairs as an iterator range.
1230 void BBVectorize::findBestTreeFor(
1231 std::multimap<Value *, Value *> &CandidatePairs,
1232 std::vector<Value *> &PairableInsts,
1233 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1234 DenseSet<ValuePair> &PairableInstUsers,
1235 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1236 DenseMap<Value *, Value *> &ChosenPairs,
1237 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1238 size_t &BestEffSize, VPIteratorPair ChoiceRange,
1239 bool UseCycleCheck) {
1240 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1241 J != ChoiceRange.second; ++J) {
1243 // Before going any further, make sure that this pair does not
1244 // conflict with any already-selected pairs (see comment below
1245 // near the Tree pruning for more details).
1246 DenseSet<ValuePair> ChosenPairSet;
1247 bool DoesConflict = false;
1248 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1249 E = ChosenPairs.end(); C != E; ++C) {
1250 if (pairsConflict(*C, *J, PairableInstUsers,
1251 UseCycleCheck ? &PairableInstUserMap : 0)) {
1252 DoesConflict = true;
1256 ChosenPairSet.insert(*C);
1258 if (DoesConflict) continue;
1260 if (UseCycleCheck &&
1261 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1264 DenseMap<ValuePair, size_t> Tree;
1265 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1266 PairableInstUsers, ChosenPairs, Tree, *J);
1268 // Because we'll keep the child with the largest depth, the largest
1269 // depth is still the same in the unpruned Tree.
1270 size_t MaxDepth = Tree.lookup(*J);
1272 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1273 << *J->first << " <-> " << *J->second << "} of depth " <<
1274 MaxDepth << " and size " << Tree.size() << "\n");
1276 // At this point the Tree has been constructed, but, may contain
1277 // contradictory children (meaning that different children of
1278 // some tree node may be attempting to fuse the same instruction).
1279 // So now we walk the tree again, in the case of a conflict,
1280 // keep only the child with the largest depth. To break a tie,
1281 // favor the first child.
1283 DenseSet<ValuePair> PrunedTree;
1284 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1285 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1286 PrunedTree, *J, UseCycleCheck);
1289 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1290 E = PrunedTree.end(); S != E; ++S)
1291 EffSize += getDepthFactor(S->first);
1293 DEBUG(if (DebugPairSelection)
1294 dbgs() << "BBV: found pruned Tree for pair {"
1295 << *J->first << " <-> " << *J->second << "} of depth " <<
1296 MaxDepth << " and size " << PrunedTree.size() <<
1297 " (effective size: " << EffSize << ")\n");
1298 if (MaxDepth >= Config.ReqChainDepth && EffSize > BestEffSize) {
1299 BestMaxDepth = MaxDepth;
1300 BestEffSize = EffSize;
1301 BestTree = PrunedTree;
1306 // Given the list of candidate pairs, this function selects those
1307 // that will be fused into vector instructions.
1308 void BBVectorize::choosePairs(
1309 std::multimap<Value *, Value *> &CandidatePairs,
1310 std::vector<Value *> &PairableInsts,
1311 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1312 DenseSet<ValuePair> &PairableInstUsers,
1313 DenseMap<Value *, Value *>& ChosenPairs) {
1314 bool UseCycleCheck =
1315 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1316 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1317 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1318 E = PairableInsts.end(); I != E; ++I) {
1319 // The number of possible pairings for this variable:
1320 size_t NumChoices = CandidatePairs.count(*I);
1321 if (!NumChoices) continue;
1323 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1325 // The best pair to choose and its tree:
1326 size_t BestMaxDepth = 0, BestEffSize = 0;
1327 DenseSet<ValuePair> BestTree;
1328 findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1329 PairableInstUsers, PairableInstUserMap, ChosenPairs,
1330 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1333 // A tree has been chosen (or not) at this point. If no tree was
1334 // chosen, then this instruction, I, cannot be paired (and is no longer
1337 DEBUG(if (BestTree.size() > 0)
1338 dbgs() << "BBV: selected pairs in the best tree for: "
1339 << *cast<Instruction>(*I) << "\n");
1341 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1342 SE2 = BestTree.end(); S != SE2; ++S) {
1343 // Insert the members of this tree into the list of chosen pairs.
1344 ChosenPairs.insert(ValuePair(S->first, S->second));
1345 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1346 *S->second << "\n");
1348 // Remove all candidate pairs that have values in the chosen tree.
1349 for (std::multimap<Value *, Value *>::iterator K =
1350 CandidatePairs.begin(); K != CandidatePairs.end();) {
1351 if (K->first == S->first || K->second == S->first ||
1352 K->second == S->second || K->first == S->second) {
1353 // Don't remove the actual pair chosen so that it can be used
1354 // in subsequent tree selections.
1355 if (!(K->first == S->first && K->second == S->second))
1356 CandidatePairs.erase(K++);
1366 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1369 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1374 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1375 (n > 0 ? "." + utostr(n) : "")).str();
1378 // Returns the value that is to be used as the pointer input to the vector
1379 // instruction that fuses I with J.
1380 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1381 Instruction *I, Instruction *J, unsigned o,
1382 bool &FlipMemInputs) {
1384 unsigned IAlignment, JAlignment;
1385 int64_t OffsetInElmts;
1386 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1389 // The pointer value is taken to be the one with the lowest offset.
1391 if (OffsetInElmts > 0) {
1394 FlipMemInputs = true;
1398 Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1399 Type *VArgType = getVecTypeForPair(ArgType);
1400 Type *VArgPtrType = PointerType::get(VArgType,
1401 cast<PointerType>(IPtr->getType())->getAddressSpace());
1402 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1403 /* insert before */ FlipMemInputs ? J : I);
1406 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1407 unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1408 unsigned IdxOffset, std::vector<Constant*> &Mask) {
1409 for (unsigned v = 0; v < NumElem/2; ++v) {
1410 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1412 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1414 unsigned mm = m + (int) IdxOffset;
1415 if (m >= (int) NumInElem)
1416 mm += (int) NumInElem;
1418 Mask[v+MaskOffset] =
1419 ConstantInt::get(Type::getInt32Ty(Context), mm);
1424 // Returns the value that is to be used as the vector-shuffle mask to the
1425 // vector instruction that fuses I with J.
1426 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1427 Instruction *I, Instruction *J) {
1428 // This is the shuffle mask. We need to append the second
1429 // mask to the first, and the numbers need to be adjusted.
1431 Type *ArgType = I->getType();
1432 Type *VArgType = getVecTypeForPair(ArgType);
1434 // Get the total number of elements in the fused vector type.
1435 // By definition, this must equal the number of elements in
1437 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1438 std::vector<Constant*> Mask(NumElem);
1440 Type *OpType = I->getOperand(0)->getType();
1441 unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1443 // For the mask from the first pair...
1444 fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1446 // For the mask from the second pair...
1447 fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1450 return ConstantVector::get(Mask);
1453 // Returns the value to be used as the specified operand of the vector
1454 // instruction that fuses I with J.
1455 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1456 Instruction *J, unsigned o, bool FlipMemInputs) {
1457 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1458 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1460 // Compute the fused vector type for this operand
1461 Type *ArgType = I->getOperand(o)->getType();
1462 VectorType *VArgType = getVecTypeForPair(ArgType);
1464 Instruction *L = I, *H = J;
1465 if (FlipMemInputs) {
1470 if (ArgType->isVectorTy()) {
1471 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1472 std::vector<Constant*> Mask(numElem);
1473 for (unsigned v = 0; v < numElem; ++v)
1474 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1476 Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1478 ConstantVector::get(Mask),
1479 getReplacementName(I, true, o));
1480 BV->insertBefore(J);
1484 // If these two inputs are the output of another vector instruction,
1485 // then we should use that output directly. It might be necessary to
1486 // permute it first. [When pairings are fused recursively, you can
1487 // end up with cases where a large vector is decomposed into scalars
1488 // using extractelement instructions, then built into size-2
1489 // vectors using insertelement and the into larger vectors using
1490 // shuffles. InstCombine does not simplify all of these cases well,
1491 // and so we make sure that shuffles are generated here when possible.
1492 ExtractElementInst *LEE
1493 = dyn_cast<ExtractElementInst>(L->getOperand(o));
1494 ExtractElementInst *HEE
1495 = dyn_cast<ExtractElementInst>(H->getOperand(o));
1498 LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1499 VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1500 unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1501 unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1502 if (LEE->getOperand(0) == HEE->getOperand(0)) {
1503 if (LowIndx == 0 && HighIndx == 1)
1504 return LEE->getOperand(0);
1506 std::vector<Constant*> Mask(2);
1507 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1508 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1510 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1511 UndefValue::get(EEType),
1512 ConstantVector::get(Mask),
1513 getReplacementName(I, true, o));
1514 BV->insertBefore(J);
1518 std::vector<Constant*> Mask(2);
1519 HighIndx += EEType->getNumElements();
1520 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1521 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1523 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1525 ConstantVector::get(Mask),
1526 getReplacementName(I, true, o));
1527 BV->insertBefore(J);
1531 Instruction *BV1 = InsertElementInst::Create(
1532 UndefValue::get(VArgType),
1533 L->getOperand(o), CV0,
1534 getReplacementName(I, true, o, 1));
1535 BV1->insertBefore(I);
1536 Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1538 getReplacementName(I, true, o, 2));
1539 BV2->insertBefore(J);
1543 // This function creates an array of values that will be used as the inputs
1544 // to the vector instruction that fuses I with J.
1545 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1546 Instruction *I, Instruction *J,
1547 SmallVector<Value *, 3> &ReplacedOperands,
1548 bool &FlipMemInputs) {
1549 FlipMemInputs = false;
1550 unsigned NumOperands = I->getNumOperands();
1552 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1553 // Iterate backward so that we look at the store pointer
1554 // first and know whether or not we need to flip the inputs.
1556 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1557 // This is the pointer for a load/store instruction.
1558 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1561 } else if (isa<CallInst>(I)) {
1562 Function *F = cast<CallInst>(I)->getCalledFunction();
1563 unsigned IID = F->getIntrinsicID();
1564 if (o == NumOperands-1) {
1565 BasicBlock &BB = *I->getParent();
1567 Module *M = BB.getParent()->getParent();
1568 Type *ArgType = I->getType();
1569 Type *VArgType = getVecTypeForPair(ArgType);
1571 // FIXME: is it safe to do this here?
1572 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1573 (Intrinsic::ID) IID, VArgType);
1575 } else if (IID == Intrinsic::powi && o == 1) {
1576 // The second argument of powi is a single integer and we've already
1577 // checked that both arguments are equal. As a result, we just keep
1578 // I's second argument.
1579 ReplacedOperands[o] = I->getOperand(o);
1582 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1583 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1587 ReplacedOperands[o] =
1588 getReplacementInput(Context, I, J, o, FlipMemInputs);
1592 // This function creates two values that represent the outputs of the
1593 // original I and J instructions. These are generally vector shuffles
1594 // or extracts. In many cases, these will end up being unused and, thus,
1595 // eliminated by later passes.
1596 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1597 Instruction *J, Instruction *K,
1598 Instruction *&InsertionPt,
1599 Instruction *&K1, Instruction *&K2,
1600 bool &FlipMemInputs) {
1601 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1602 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1604 if (isa<StoreInst>(I)) {
1605 AA->replaceWithNewValue(I, K);
1606 AA->replaceWithNewValue(J, K);
1608 Type *IType = I->getType();
1609 Type *VType = getVecTypeForPair(IType);
1611 if (IType->isVectorTy()) {
1612 unsigned numElem = cast<VectorType>(IType)->getNumElements();
1613 std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1614 for (unsigned v = 0; v < numElem; ++v) {
1615 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1616 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1619 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1620 ConstantVector::get(
1621 FlipMemInputs ? Mask2 : Mask1),
1622 getReplacementName(K, false, 1));
1623 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1624 ConstantVector::get(
1625 FlipMemInputs ? Mask1 : Mask2),
1626 getReplacementName(K, false, 2));
1628 K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1629 getReplacementName(K, false, 1));
1630 K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1631 getReplacementName(K, false, 2));
1635 K2->insertAfter(K1);
1640 // Move all uses of the function I (including pairing-induced uses) after J.
1641 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1642 std::multimap<Value *, Value *> &LoadMoveSet,
1643 Instruction *I, Instruction *J) {
1644 // Skip to the first instruction past I.
1645 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1647 DenseSet<Value *> Users;
1648 AliasSetTracker WriteSet(*AA);
1649 for (; cast<Instruction>(L) != J; ++L)
1650 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1652 assert(cast<Instruction>(L) == J &&
1653 "Tracking has not proceeded far enough to check for dependencies");
1654 // If J is now in the use set of I, then trackUsesOfI will return true
1655 // and we have a dependency cycle (and the fusing operation must abort).
1656 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1659 // Move all uses of the function I (including pairing-induced uses) after J.
1660 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1661 std::multimap<Value *, Value *> &LoadMoveSet,
1662 Instruction *&InsertionPt,
1663 Instruction *I, Instruction *J) {
1664 // Skip to the first instruction past I.
1665 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1667 DenseSet<Value *> Users;
1668 AliasSetTracker WriteSet(*AA);
1669 for (; cast<Instruction>(L) != J;) {
1670 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1671 // Move this instruction
1672 Instruction *InstToMove = L; ++L;
1674 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1675 " to after " << *InsertionPt << "\n");
1676 InstToMove->removeFromParent();
1677 InstToMove->insertAfter(InsertionPt);
1678 InsertionPt = InstToMove;
1685 // Collect all load instruction that are in the move set of a given first
1686 // pair member. These loads depend on the first instruction, I, and so need
1687 // to be moved after J (the second instruction) when the pair is fused.
1688 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1689 DenseMap<Value *, Value *> &ChosenPairs,
1690 std::multimap<Value *, Value *> &LoadMoveSet,
1692 // Skip to the first instruction past I.
1693 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1695 DenseSet<Value *> Users;
1696 AliasSetTracker WriteSet(*AA);
1698 // Note: We cannot end the loop when we reach J because J could be moved
1699 // farther down the use chain by another instruction pairing. Also, J
1700 // could be before I if this is an inverted input.
1701 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1702 if (trackUsesOfI(Users, WriteSet, I, L)) {
1703 if (L->mayReadFromMemory())
1704 LoadMoveSet.insert(ValuePair(L, I));
1709 // In cases where both load/stores and the computation of their pointers
1710 // are chosen for vectorization, we can end up in a situation where the
1711 // aliasing analysis starts returning different query results as the
1712 // process of fusing instruction pairs continues. Because the algorithm
1713 // relies on finding the same use trees here as were found earlier, we'll
1714 // need to precompute the necessary aliasing information here and then
1715 // manually update it during the fusion process.
1716 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1717 std::vector<Value *> &PairableInsts,
1718 DenseMap<Value *, Value *> &ChosenPairs,
1719 std::multimap<Value *, Value *> &LoadMoveSet) {
1720 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1721 PIE = PairableInsts.end(); PI != PIE; ++PI) {
1722 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1723 if (P == ChosenPairs.end()) continue;
1725 Instruction *I = cast<Instruction>(P->first);
1726 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1730 // This function fuses the chosen instruction pairs into vector instructions,
1731 // taking care preserve any needed scalar outputs and, then, it reorders the
1732 // remaining instructions as needed (users of the first member of the pair
1733 // need to be moved to after the location of the second member of the pair
1734 // because the vector instruction is inserted in the location of the pair's
1736 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1737 std::vector<Value *> &PairableInsts,
1738 DenseMap<Value *, Value *> &ChosenPairs) {
1739 LLVMContext& Context = BB.getContext();
1741 // During the vectorization process, the order of the pairs to be fused
1742 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1743 // list. After a pair is fused, the flipped pair is removed from the list.
1744 std::vector<ValuePair> FlippedPairs;
1745 FlippedPairs.reserve(ChosenPairs.size());
1746 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1747 E = ChosenPairs.end(); P != E; ++P)
1748 FlippedPairs.push_back(ValuePair(P->second, P->first));
1749 for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1750 E = FlippedPairs.end(); P != E; ++P)
1751 ChosenPairs.insert(*P);
1753 std::multimap<Value *, Value *> LoadMoveSet;
1754 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1756 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1758 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1759 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1760 if (P == ChosenPairs.end()) {
1765 if (getDepthFactor(P->first) == 0) {
1766 // These instructions are not really fused, but are tracked as though
1767 // they are. Any case in which it would be interesting to fuse them
1768 // will be taken care of by InstCombine.
1774 Instruction *I = cast<Instruction>(P->first),
1775 *J = cast<Instruction>(P->second);
1777 DEBUG(dbgs() << "BBV: fusing: " << *I <<
1778 " <-> " << *J << "\n");
1780 // Remove the pair and flipped pair from the list.
1781 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1782 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1783 ChosenPairs.erase(FP);
1784 ChosenPairs.erase(P);
1786 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1787 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1789 " aborted because of non-trivial dependency cycle\n");
1796 unsigned NumOperands = I->getNumOperands();
1797 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1798 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1801 // Make a copy of the original operation, change its type to the vector
1802 // type and replace its operands with the vector operands.
1803 Instruction *K = I->clone();
1804 if (I->hasName()) K->takeName(I);
1806 if (!isa<StoreInst>(K))
1807 K->mutateType(getVecTypeForPair(I->getType()));
1809 for (unsigned o = 0; o < NumOperands; ++o)
1810 K->setOperand(o, ReplacedOperands[o]);
1812 // If we've flipped the memory inputs, make sure that we take the correct
1814 if (FlipMemInputs) {
1815 if (isa<StoreInst>(K))
1816 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1818 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1823 // Instruction insertion point:
1824 Instruction *InsertionPt = K;
1825 Instruction *K1 = 0, *K2 = 0;
1826 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1829 // The use tree of the first original instruction must be moved to after
1830 // the location of the second instruction. The entire use tree of the
1831 // first instruction is disjoint from the input tree of the second
1832 // (by definition), and so commutes with it.
1834 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1836 if (!isa<StoreInst>(I)) {
1837 I->replaceAllUsesWith(K1);
1838 J->replaceAllUsesWith(K2);
1839 AA->replaceWithNewValue(I, K1);
1840 AA->replaceWithNewValue(J, K2);
1843 // Instructions that may read from memory may be in the load move set.
1844 // Once an instruction is fused, we no longer need its move set, and so
1845 // the values of the map never need to be updated. However, when a load
1846 // is fused, we need to merge the entries from both instructions in the
1847 // pair in case those instructions were in the move set of some other
1848 // yet-to-be-fused pair. The loads in question are the keys of the map.
1849 if (I->mayReadFromMemory()) {
1850 std::vector<ValuePair> NewSetMembers;
1851 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1852 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1853 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1854 N != IPairRange.second; ++N)
1855 NewSetMembers.push_back(ValuePair(K, N->second));
1856 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1857 N != JPairRange.second; ++N)
1858 NewSetMembers.push_back(ValuePair(K, N->second));
1859 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1860 AE = NewSetMembers.end(); A != AE; ++A)
1861 LoadMoveSet.insert(*A);
1864 // Before removing I, set the iterator to the next instruction.
1865 PI = llvm::next(BasicBlock::iterator(I));
1866 if (cast<Instruction>(PI) == J)
1871 I->eraseFromParent();
1872 J->eraseFromParent();
1875 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1879 char BBVectorize::ID = 0;
1880 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1881 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1882 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1883 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1884 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1886 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
1887 return new BBVectorize(C);
1891 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
1892 BBVectorize BBVectorizer(P, C);
1893 return BBVectorizer.vectorizeBB(BB);
1896 //===----------------------------------------------------------------------===//
1897 VectorizeConfig::VectorizeConfig() {
1898 VectorBits = ::VectorBits;
1899 VectorizeInts = !::NoInts;
1900 VectorizeFloats = !::NoFloats;
1901 VectorizeCasts = !::NoCasts;
1902 VectorizeMath = !::NoMath;
1903 VectorizeFMA = !::NoFMA;
1904 VectorizeSelect = !::NoSelect;
1905 VectorizeMemOps = !::NoMemOps;
1906 AlignedOnly = ::AlignedOnly;
1907 ReqChainDepth= ::ReqChainDepth;
1908 SearchLimit = ::SearchLimit;
1909 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
1910 SplatBreaksChain = ::SplatBreaksChain;
1911 MaxInsts = ::MaxInsts;
1912 MaxIter = ::MaxIter;
1913 NoMemOpBoost = ::NoMemOpBoost;
1914 FastDep = ::FastDep;