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 NoPointers("bb-vectorize-no-pointers", cl::init(false), cl::Hidden,
88 cl::desc("Don't try to vectorize pointer values"));
91 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
92 cl::desc("Don't try to vectorize casting (conversion) operations"));
95 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
96 cl::desc("Don't try to vectorize floating-point math intrinsics"));
99 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
100 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
103 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
104 cl::desc("Don't try to vectorize select instructions"));
107 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
108 cl::desc("Don't try to vectorize getelementptr instructions"));
111 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
112 cl::desc("Don't try to vectorize loads and stores"));
115 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
116 cl::desc("Only generate aligned loads and stores"));
119 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
120 cl::init(false), cl::Hidden,
121 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
124 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
125 cl::desc("Use a fast instruction dependency analysis"));
129 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
130 cl::init(false), cl::Hidden,
131 cl::desc("When debugging is enabled, output information on the"
132 " instruction-examination process"));
134 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
135 cl::init(false), cl::Hidden,
136 cl::desc("When debugging is enabled, output information on the"
137 " candidate-selection process"));
139 DebugPairSelection("bb-vectorize-debug-pair-selection",
140 cl::init(false), cl::Hidden,
141 cl::desc("When debugging is enabled, output information on the"
142 " pair-selection process"));
144 DebugCycleCheck("bb-vectorize-debug-cycle-check",
145 cl::init(false), cl::Hidden,
146 cl::desc("When debugging is enabled, output information on the"
147 " cycle-checking process"));
150 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
153 struct BBVectorize : public BasicBlockPass {
154 static char ID; // Pass identification, replacement for typeid
156 const VectorizeConfig Config;
158 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
159 : BasicBlockPass(ID), Config(C) {
160 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
163 BBVectorize(Pass *P, const VectorizeConfig &C)
164 : BasicBlockPass(ID), Config(C) {
165 AA = &P->getAnalysis<AliasAnalysis>();
166 SE = &P->getAnalysis<ScalarEvolution>();
167 TD = P->getAnalysisIfAvailable<TargetData>();
170 typedef std::pair<Value *, Value *> ValuePair;
171 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
172 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
173 typedef std::pair<std::multimap<Value *, Value *>::iterator,
174 std::multimap<Value *, Value *>::iterator> VPIteratorPair;
175 typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
176 std::multimap<ValuePair, ValuePair>::iterator>
183 // FIXME: const correct?
185 bool vectorizePairs(BasicBlock &BB);
187 bool getCandidatePairs(BasicBlock &BB,
188 BasicBlock::iterator &Start,
189 std::multimap<Value *, Value *> &CandidatePairs,
190 std::vector<Value *> &PairableInsts);
192 void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
193 std::vector<Value *> &PairableInsts,
194 std::multimap<ValuePair, ValuePair> &ConnectedPairs);
196 void buildDepMap(BasicBlock &BB,
197 std::multimap<Value *, Value *> &CandidatePairs,
198 std::vector<Value *> &PairableInsts,
199 DenseSet<ValuePair> &PairableInstUsers);
201 void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
202 std::vector<Value *> &PairableInsts,
203 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
204 DenseSet<ValuePair> &PairableInstUsers,
205 DenseMap<Value *, Value *>& ChosenPairs);
207 void fuseChosenPairs(BasicBlock &BB,
208 std::vector<Value *> &PairableInsts,
209 DenseMap<Value *, Value *>& ChosenPairs);
211 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
213 bool areInstsCompatible(Instruction *I, Instruction *J,
214 bool IsSimpleLoadStore);
216 bool trackUsesOfI(DenseSet<Value *> &Users,
217 AliasSetTracker &WriteSet, Instruction *I,
218 Instruction *J, bool UpdateUsers = true,
219 std::multimap<Value *, Value *> *LoadMoveSet = 0);
221 void computePairsConnectedTo(
222 std::multimap<Value *, Value *> &CandidatePairs,
223 std::vector<Value *> &PairableInsts,
224 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
227 bool pairsConflict(ValuePair P, ValuePair Q,
228 DenseSet<ValuePair> &PairableInstUsers,
229 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
231 bool pairWillFormCycle(ValuePair P,
232 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
233 DenseSet<ValuePair> &CurrentPairs);
236 std::multimap<Value *, Value *> &CandidatePairs,
237 std::vector<Value *> &PairableInsts,
238 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
239 DenseSet<ValuePair> &PairableInstUsers,
240 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
241 DenseMap<Value *, Value *> &ChosenPairs,
242 DenseMap<ValuePair, size_t> &Tree,
243 DenseSet<ValuePair> &PrunedTree, ValuePair J,
246 void buildInitialTreeFor(
247 std::multimap<Value *, Value *> &CandidatePairs,
248 std::vector<Value *> &PairableInsts,
249 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
250 DenseSet<ValuePair> &PairableInstUsers,
251 DenseMap<Value *, Value *> &ChosenPairs,
252 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
254 void findBestTreeFor(
255 std::multimap<Value *, Value *> &CandidatePairs,
256 std::vector<Value *> &PairableInsts,
257 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
258 DenseSet<ValuePair> &PairableInstUsers,
259 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
260 DenseMap<Value *, Value *> &ChosenPairs,
261 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
262 size_t &BestEffSize, VPIteratorPair ChoiceRange,
265 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
266 Instruction *J, unsigned o, bool &FlipMemInputs);
268 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
269 unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
270 unsigned IdxOffset, std::vector<Constant*> &Mask);
272 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
275 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
276 Instruction *J, unsigned o, bool FlipMemInputs);
278 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
279 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
280 bool &FlipMemInputs);
282 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
283 Instruction *J, Instruction *K,
284 Instruction *&InsertionPt, Instruction *&K1,
285 Instruction *&K2, bool &FlipMemInputs);
287 void collectPairLoadMoveSet(BasicBlock &BB,
288 DenseMap<Value *, Value *> &ChosenPairs,
289 std::multimap<Value *, Value *> &LoadMoveSet,
292 void collectLoadMoveSet(BasicBlock &BB,
293 std::vector<Value *> &PairableInsts,
294 DenseMap<Value *, Value *> &ChosenPairs,
295 std::multimap<Value *, Value *> &LoadMoveSet);
297 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
298 std::multimap<Value *, Value *> &LoadMoveSet,
299 Instruction *I, Instruction *J);
301 void moveUsesOfIAfterJ(BasicBlock &BB,
302 std::multimap<Value *, Value *> &LoadMoveSet,
303 Instruction *&InsertionPt,
304 Instruction *I, Instruction *J);
306 bool vectorizeBB(BasicBlock &BB) {
307 bool changed = false;
308 // Iterate a sufficient number of times to merge types of size 1 bit,
309 // then 2 bits, then 4, etc. up to half of the target vector width of the
310 // target vector register.
311 for (unsigned v = 2, n = 1;
312 v <= Config.VectorBits && (!Config.MaxIter || n <= Config.MaxIter);
314 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
315 " for " << BB.getName() << " in " <<
316 BB.getParent()->getName() << "...\n");
317 if (vectorizePairs(BB))
323 DEBUG(dbgs() << "BBV: done!\n");
327 virtual bool runOnBasicBlock(BasicBlock &BB) {
328 AA = &getAnalysis<AliasAnalysis>();
329 SE = &getAnalysis<ScalarEvolution>();
330 TD = getAnalysisIfAvailable<TargetData>();
332 return vectorizeBB(BB);
335 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
336 BasicBlockPass::getAnalysisUsage(AU);
337 AU.addRequired<AliasAnalysis>();
338 AU.addRequired<ScalarEvolution>();
339 AU.addPreserved<AliasAnalysis>();
340 AU.addPreserved<ScalarEvolution>();
341 AU.setPreservesCFG();
344 // This returns the vector type that holds a pair of the provided type.
345 // If the provided type is already a vector, then its length is doubled.
346 static inline VectorType *getVecTypeForPair(Type *ElemTy) {
347 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
348 unsigned numElem = VTy->getNumElements();
349 return VectorType::get(ElemTy->getScalarType(), numElem*2);
352 return VectorType::get(ElemTy, 2);
355 // Returns the weight associated with the provided value. A chain of
356 // candidate pairs has a length given by the sum of the weights of its
357 // members (one weight per pair; the weight of each member of the pair
358 // is assumed to be the same). This length is then compared to the
359 // chain-length threshold to determine if a given chain is significant
360 // enough to be vectorized. The length is also used in comparing
361 // candidate chains where longer chains are considered to be better.
362 // Note: when this function returns 0, the resulting instructions are
363 // not actually fused.
364 inline size_t getDepthFactor(Value *V) {
365 // InsertElement and ExtractElement have a depth factor of zero. This is
366 // for two reasons: First, they cannot be usefully fused. Second, because
367 // the pass generates a lot of these, they can confuse the simple metric
368 // used to compare the trees in the next iteration. Thus, giving them a
369 // weight of zero allows the pass to essentially ignore them in
370 // subsequent iterations when looking for vectorization opportunities
371 // while still tracking dependency chains that flow through those
373 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
376 // Give a load or store half of the required depth so that load/store
377 // pairs will vectorize.
378 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
379 return Config.ReqChainDepth/2;
384 // This determines the relative offset of two loads or stores, returning
385 // true if the offset could be determined to be some constant value.
386 // For example, if OffsetInElmts == 1, then J accesses the memory directly
387 // after I; if OffsetInElmts == -1 then I accesses the memory
388 // directly after J. This function assumes that both instructions
389 // have the same type.
390 bool getPairPtrInfo(Instruction *I, Instruction *J,
391 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
392 int64_t &OffsetInElmts) {
394 if (isa<LoadInst>(I)) {
395 IPtr = cast<LoadInst>(I)->getPointerOperand();
396 JPtr = cast<LoadInst>(J)->getPointerOperand();
397 IAlignment = cast<LoadInst>(I)->getAlignment();
398 JAlignment = cast<LoadInst>(J)->getAlignment();
400 IPtr = cast<StoreInst>(I)->getPointerOperand();
401 JPtr = cast<StoreInst>(J)->getPointerOperand();
402 IAlignment = cast<StoreInst>(I)->getAlignment();
403 JAlignment = cast<StoreInst>(J)->getAlignment();
406 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
407 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
409 // If this is a trivial offset, then we'll get something like
410 // 1*sizeof(type). With target data, which we need anyway, this will get
411 // constant folded into a number.
412 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
413 if (const SCEVConstant *ConstOffSCEV =
414 dyn_cast<SCEVConstant>(OffsetSCEV)) {
415 ConstantInt *IntOff = ConstOffSCEV->getValue();
416 int64_t Offset = IntOff->getSExtValue();
418 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
419 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
421 assert(VTy == cast<PointerType>(JPtr->getType())->getElementType());
423 OffsetInElmts = Offset/VTyTSS;
424 return (abs64(Offset) % VTyTSS) == 0;
430 // Returns true if the provided CallInst represents an intrinsic that can
432 bool isVectorizableIntrinsic(CallInst* I) {
433 Function *F = I->getCalledFunction();
434 if (!F) return false;
436 unsigned IID = F->getIntrinsicID();
437 if (!IID) return false;
442 case Intrinsic::sqrt:
443 case Intrinsic::powi:
447 case Intrinsic::log2:
448 case Intrinsic::log10:
450 case Intrinsic::exp2:
452 return Config.VectorizeMath;
454 return Config.VectorizeFMA;
458 // Returns true if J is the second element in some pair referenced by
459 // some multimap pair iterator pair.
460 template <typename V>
461 bool isSecondInIteratorPair(V J, std::pair<
462 typename std::multimap<V, V>::iterator,
463 typename std::multimap<V, V>::iterator> PairRange) {
464 for (typename std::multimap<V, V>::iterator K = PairRange.first;
465 K != PairRange.second; ++K)
466 if (K->second == J) return true;
472 // This function implements one vectorization iteration on the provided
473 // basic block. It returns true if the block is changed.
474 bool BBVectorize::vectorizePairs(BasicBlock &BB) {
476 BasicBlock::iterator Start = BB.getFirstInsertionPt();
478 std::vector<Value *> AllPairableInsts;
479 DenseMap<Value *, Value *> AllChosenPairs;
482 std::vector<Value *> PairableInsts;
483 std::multimap<Value *, Value *> CandidatePairs;
484 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
486 if (PairableInsts.empty()) continue;
488 // Now we have a map of all of the pairable instructions and we need to
489 // select the best possible pairing. A good pairing is one such that the
490 // users of the pair are also paired. This defines a (directed) forest
491 // over the pairs such that two pairs are connected iff the second pair
494 // Note that it only matters that both members of the second pair use some
495 // element of the first pair (to allow for splatting).
497 std::multimap<ValuePair, ValuePair> ConnectedPairs;
498 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
499 if (ConnectedPairs.empty()) continue;
501 // Build the pairable-instruction dependency map
502 DenseSet<ValuePair> PairableInstUsers;
503 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
505 // There is now a graph of the connected pairs. For each variable, pick
506 // the pairing with the largest tree meeting the depth requirement on at
507 // least one branch. Then select all pairings that are part of that tree
508 // and remove them from the list of available pairings and pairable
511 DenseMap<Value *, Value *> ChosenPairs;
512 choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
513 PairableInstUsers, ChosenPairs);
515 if (ChosenPairs.empty()) continue;
516 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
517 PairableInsts.end());
518 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
519 } while (ShouldContinue);
521 if (AllChosenPairs.empty()) return false;
522 NumFusedOps += AllChosenPairs.size();
524 // A set of pairs has now been selected. It is now necessary to replace the
525 // paired instructions with vector instructions. For this procedure each
526 // operand must be replaced with a vector operand. This vector is formed
527 // by using build_vector on the old operands. The replaced values are then
528 // replaced with a vector_extract on the result. Subsequent optimization
529 // passes should coalesce the build/extract combinations.
531 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
535 // This function returns true if the provided instruction is capable of being
536 // fused into a vector instruction. This determination is based only on the
537 // type and other attributes of the instruction.
538 bool BBVectorize::isInstVectorizable(Instruction *I,
539 bool &IsSimpleLoadStore) {
540 IsSimpleLoadStore = false;
542 if (CallInst *C = dyn_cast<CallInst>(I)) {
543 if (!isVectorizableIntrinsic(C))
545 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
546 // Vectorize simple loads if possbile:
547 IsSimpleLoadStore = L->isSimple();
548 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
550 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
551 // Vectorize simple stores if possbile:
552 IsSimpleLoadStore = S->isSimple();
553 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
555 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
556 // We can vectorize casts, but not casts of pointer types, etc.
557 if (!Config.VectorizeCasts)
560 Type *SrcTy = C->getSrcTy();
561 if (!SrcTy->isSingleValueType())
564 Type *DestTy = C->getDestTy();
565 if (!DestTy->isSingleValueType())
567 } else if (isa<SelectInst>(I)) {
568 if (!Config.VectorizeSelect)
570 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
571 if (!Config.VectorizeGEP)
574 // Currently, vector GEPs exist only with one index.
575 if (G->getNumIndices() != 1)
577 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
578 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
582 // We can't vectorize memory operations without target data
583 if (TD == 0 && IsSimpleLoadStore)
587 if (isa<StoreInst>(I)) {
588 // For stores, it is the value type, not the pointer type that matters
589 // because the value is what will come from a vector register.
591 Value *IVal = cast<StoreInst>(I)->getValueOperand();
592 T1 = IVal->getType();
598 T2 = cast<CastInst>(I)->getSrcTy();
602 // Not every type can be vectorized...
603 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
604 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
607 if (!Config.VectorizeInts
608 && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
611 if (!Config.VectorizeFloats
612 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
615 if ((!Config.VectorizePointers || TD == 0)
616 && ((T1->isPointerTy() ||
617 (T1->isVectorTy() && T1->getScalarType()->isPointerTy())) ||
618 (T2->isPointerTy() ||
619 (T2->isVectorTy() && T2->getScalarType()->isPointerTy()))
623 if (T1->getPrimitiveSizeInBits() > Config.VectorBits/2 ||
624 T2->getPrimitiveSizeInBits() > Config.VectorBits/2)
630 // This function returns true if the two provided instructions are compatible
631 // (meaning that they can be fused into a vector instruction). This assumes
632 // that I has already been determined to be vectorizable and that J is not
633 // in the use tree of I.
634 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
635 bool IsSimpleLoadStore) {
636 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
637 " <-> " << *J << "\n");
639 // Loads and stores can be merged if they have different alignments,
640 // but are otherwise the same.
643 if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
644 if (I->getType() != J->getType())
647 if (LI->getPointerOperand()->getType() !=
648 LJ->getPointerOperand()->getType() ||
649 LI->isVolatile() != LJ->isVolatile() ||
650 LI->getOrdering() != LJ->getOrdering() ||
651 LI->getSynchScope() != LJ->getSynchScope())
653 } else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
654 if (SI->getValueOperand()->getType() !=
655 SJ->getValueOperand()->getType() ||
656 SI->getPointerOperand()->getType() !=
657 SJ->getPointerOperand()->getType() ||
658 SI->isVolatile() != SJ->isVolatile() ||
659 SI->getOrdering() != SJ->getOrdering() ||
660 SI->getSynchScope() != SJ->getSynchScope())
662 } else if (!J->isSameOperationAs(I)) {
665 // FIXME: handle addsub-type operations!
667 if (IsSimpleLoadStore) {
669 unsigned IAlignment, JAlignment;
670 int64_t OffsetInElmts = 0;
671 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
672 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
673 if (Config.AlignedOnly) {
674 Type *aType = isa<StoreInst>(I) ?
675 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
676 // An aligned load or store is possible only if the instruction
677 // with the lower offset has an alignment suitable for the
680 unsigned BottomAlignment = IAlignment;
681 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
683 Type *VType = getVecTypeForPair(aType);
684 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
685 if (BottomAlignment < VecAlignment)
691 } else if (isa<ShuffleVectorInst>(I)) {
692 // Only merge two shuffles if they're both constant
693 return isa<Constant>(I->getOperand(2)) &&
694 isa<Constant>(J->getOperand(2));
695 // FIXME: We may want to vectorize non-constant shuffles also.
698 // The powi intrinsic is special because only the first argument is
699 // vectorized, the second arguments must be equal.
700 CallInst *CI = dyn_cast<CallInst>(I);
702 if (CI && (FI = CI->getCalledFunction()) &&
703 FI->getIntrinsicID() == Intrinsic::powi) {
705 Value *A1I = CI->getArgOperand(1),
706 *A1J = cast<CallInst>(J)->getArgOperand(1);
707 const SCEV *A1ISCEV = SE->getSCEV(A1I),
708 *A1JSCEV = SE->getSCEV(A1J);
709 return (A1ISCEV == A1JSCEV);
715 // Figure out whether or not J uses I and update the users and write-set
716 // structures associated with I. Specifically, Users represents the set of
717 // instructions that depend on I. WriteSet represents the set
718 // of memory locations that are dependent on I. If UpdateUsers is true,
719 // and J uses I, then Users is updated to contain J and WriteSet is updated
720 // to contain any memory locations to which J writes. The function returns
721 // true if J uses I. By default, alias analysis is used to determine
722 // whether J reads from memory that overlaps with a location in WriteSet.
723 // If LoadMoveSet is not null, then it is a previously-computed multimap
724 // where the key is the memory-based user instruction and the value is
725 // the instruction to be compared with I. So, if LoadMoveSet is provided,
726 // then the alias analysis is not used. This is necessary because this
727 // function is called during the process of moving instructions during
728 // vectorization and the results of the alias analysis are not stable during
730 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
731 AliasSetTracker &WriteSet, Instruction *I,
732 Instruction *J, bool UpdateUsers,
733 std::multimap<Value *, Value *> *LoadMoveSet) {
736 // This instruction may already be marked as a user due, for example, to
737 // being a member of a selected pair.
742 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
745 if (I == V || Users.count(V)) {
750 if (!UsesI && J->mayReadFromMemory()) {
752 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
753 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
755 for (AliasSetTracker::iterator W = WriteSet.begin(),
756 WE = WriteSet.end(); W != WE; ++W) {
757 if (W->aliasesUnknownInst(J, *AA)) {
765 if (UsesI && UpdateUsers) {
766 if (J->mayWriteToMemory()) WriteSet.add(J);
773 // This function iterates over all instruction pairs in the provided
774 // basic block and collects all candidate pairs for vectorization.
775 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
776 BasicBlock::iterator &Start,
777 std::multimap<Value *, Value *> &CandidatePairs,
778 std::vector<Value *> &PairableInsts) {
779 BasicBlock::iterator E = BB.end();
780 if (Start == E) return false;
782 bool ShouldContinue = false, IAfterStart = false;
783 for (BasicBlock::iterator I = Start++; I != E; ++I) {
784 if (I == Start) IAfterStart = true;
786 bool IsSimpleLoadStore;
787 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
789 // Look for an instruction with which to pair instruction *I...
790 DenseSet<Value *> Users;
791 AliasSetTracker WriteSet(*AA);
792 bool JAfterStart = IAfterStart;
793 BasicBlock::iterator J = llvm::next(I);
794 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
795 if (J == Start) JAfterStart = true;
797 // Determine if J uses I, if so, exit the loop.
798 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
799 if (Config.FastDep) {
800 // Note: For this heuristic to be effective, independent operations
801 // must tend to be intermixed. This is likely to be true from some
802 // kinds of grouped loop unrolling (but not the generic LLVM pass),
803 // but otherwise may require some kind of reordering pass.
805 // When using fast dependency analysis,
806 // stop searching after first use:
812 // J does not use I, and comes before the first use of I, so it can be
813 // merged with I if the instructions are compatible.
814 if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
816 // J is a candidate for merging with I.
817 if (!PairableInsts.size() ||
818 PairableInsts[PairableInsts.size()-1] != I) {
819 PairableInsts.push_back(I);
822 CandidatePairs.insert(ValuePair(I, J));
824 // The next call to this function must start after the last instruction
825 // selected during this invocation.
827 Start = llvm::next(J);
828 IAfterStart = JAfterStart = false;
831 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
832 << *I << " <-> " << *J << "\n");
834 // If we have already found too many pairs, break here and this function
835 // will be called again starting after the last instruction selected
836 // during this invocation.
837 if (PairableInsts.size() >= Config.MaxInsts) {
838 ShouldContinue = true;
847 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
848 << " instructions with candidate pairs\n");
850 return ShouldContinue;
853 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
854 // it looks for pairs such that both members have an input which is an
855 // output of PI or PJ.
856 void BBVectorize::computePairsConnectedTo(
857 std::multimap<Value *, Value *> &CandidatePairs,
858 std::vector<Value *> &PairableInsts,
859 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
861 // For each possible pairing for this variable, look at the uses of
862 // the first value...
863 for (Value::use_iterator I = P.first->use_begin(),
864 E = P.first->use_end(); I != E; ++I) {
865 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
867 // For each use of the first variable, look for uses of the second
869 for (Value::use_iterator J = P.second->use_begin(),
870 E2 = P.second->use_end(); J != E2; ++J) {
871 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
874 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
875 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
878 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
879 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
882 if (Config.SplatBreaksChain) continue;
883 // Look for cases where just the first value in the pair is used by
884 // both members of another pair (splatting).
885 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
886 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
887 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
891 if (Config.SplatBreaksChain) return;
892 // Look for cases where just the second value in the pair is used by
893 // both members of another pair (splatting).
894 for (Value::use_iterator I = P.second->use_begin(),
895 E = P.second->use_end(); I != E; ++I) {
896 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
898 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
899 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
900 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
905 // This function figures out which pairs are connected. Two pairs are
906 // connected if some output of the first pair forms an input to both members
907 // of the second pair.
908 void BBVectorize::computeConnectedPairs(
909 std::multimap<Value *, Value *> &CandidatePairs,
910 std::vector<Value *> &PairableInsts,
911 std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
913 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
914 PE = PairableInsts.end(); PI != PE; ++PI) {
915 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
917 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
918 P != choiceRange.second; ++P)
919 computePairsConnectedTo(CandidatePairs, PairableInsts,
923 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
924 << " pair connections.\n");
927 // This function builds a set of use tuples such that <A, B> is in the set
928 // if B is in the use tree of A. If B is in the use tree of A, then B
929 // depends on the output of A.
930 void BBVectorize::buildDepMap(
932 std::multimap<Value *, Value *> &CandidatePairs,
933 std::vector<Value *> &PairableInsts,
934 DenseSet<ValuePair> &PairableInstUsers) {
935 DenseSet<Value *> IsInPair;
936 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
937 E = CandidatePairs.end(); C != E; ++C) {
938 IsInPair.insert(C->first);
939 IsInPair.insert(C->second);
942 // Iterate through the basic block, recording all Users of each
943 // pairable instruction.
945 BasicBlock::iterator E = BB.end();
946 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
947 if (IsInPair.find(I) == IsInPair.end()) continue;
949 DenseSet<Value *> Users;
950 AliasSetTracker WriteSet(*AA);
951 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
952 (void) trackUsesOfI(Users, WriteSet, I, J);
954 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
956 PairableInstUsers.insert(ValuePair(I, *U));
960 // Returns true if an input to pair P is an output of pair Q and also an
961 // input of pair Q is an output of pair P. If this is the case, then these
962 // two pairs cannot be simultaneously fused.
963 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
964 DenseSet<ValuePair> &PairableInstUsers,
965 std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
966 // Two pairs are in conflict if they are mutual Users of eachother.
967 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
968 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
969 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
970 PairableInstUsers.count(ValuePair(P.second, Q.second));
971 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
972 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
973 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
974 PairableInstUsers.count(ValuePair(Q.second, P.second));
975 if (PairableInstUserMap) {
976 // FIXME: The expensive part of the cycle check is not so much the cycle
977 // check itself but this edge insertion procedure. This needs some
978 // profiling and probably a different data structure (same is true of
979 // most uses of std::multimap).
981 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
982 if (!isSecondInIteratorPair(P, QPairRange))
983 PairableInstUserMap->insert(VPPair(Q, P));
986 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
987 if (!isSecondInIteratorPair(Q, PPairRange))
988 PairableInstUserMap->insert(VPPair(P, Q));
992 return (QUsesP && PUsesQ);
995 // This function walks the use graph of current pairs to see if, starting
996 // from P, the walk returns to P.
997 bool BBVectorize::pairWillFormCycle(ValuePair P,
998 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
999 DenseSet<ValuePair> &CurrentPairs) {
1000 DEBUG(if (DebugCycleCheck)
1001 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1002 << *P.second << "\n");
1003 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1004 // contains non-direct associations.
1005 DenseSet<ValuePair> Visited;
1006 SmallVector<ValuePair, 32> Q;
1007 // General depth-first post-order traversal:
1010 ValuePair QTop = Q.pop_back_val();
1011 Visited.insert(QTop);
1013 DEBUG(if (DebugCycleCheck)
1014 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1015 << *QTop.second << "\n");
1016 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1017 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1018 C != QPairRange.second; ++C) {
1019 if (C->second == P) {
1021 << "BBV: rejected to prevent non-trivial cycle formation: "
1022 << *C->first.first << " <-> " << *C->first.second << "\n");
1026 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1027 Q.push_back(C->second);
1029 } while (!Q.empty());
1034 // This function builds the initial tree of connected pairs with the
1035 // pair J at the root.
1036 void BBVectorize::buildInitialTreeFor(
1037 std::multimap<Value *, Value *> &CandidatePairs,
1038 std::vector<Value *> &PairableInsts,
1039 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1040 DenseSet<ValuePair> &PairableInstUsers,
1041 DenseMap<Value *, Value *> &ChosenPairs,
1042 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1043 // Each of these pairs is viewed as the root node of a Tree. The Tree
1044 // is then walked (depth-first). As this happens, we keep track of
1045 // the pairs that compose the Tree and the maximum depth of the Tree.
1046 SmallVector<ValuePairWithDepth, 32> Q;
1047 // General depth-first post-order traversal:
1048 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1050 ValuePairWithDepth QTop = Q.back();
1052 // Push each child onto the queue:
1053 bool MoreChildren = false;
1054 size_t MaxChildDepth = QTop.second;
1055 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1056 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1057 k != qtRange.second; ++k) {
1058 // Make sure that this child pair is still a candidate:
1059 bool IsStillCand = false;
1060 VPIteratorPair checkRange =
1061 CandidatePairs.equal_range(k->second.first);
1062 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1063 m != checkRange.second; ++m) {
1064 if (m->second == k->second.second) {
1071 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1072 if (C == Tree.end()) {
1073 size_t d = getDepthFactor(k->second.first);
1074 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1075 MoreChildren = true;
1077 MaxChildDepth = std::max(MaxChildDepth, C->second);
1082 if (!MoreChildren) {
1083 // Record the current pair as part of the Tree:
1084 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1087 } while (!Q.empty());
1090 // Given some initial tree, prune it by removing conflicting pairs (pairs
1091 // that cannot be simultaneously chosen for vectorization).
1092 void BBVectorize::pruneTreeFor(
1093 std::multimap<Value *, Value *> &CandidatePairs,
1094 std::vector<Value *> &PairableInsts,
1095 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1096 DenseSet<ValuePair> &PairableInstUsers,
1097 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1098 DenseMap<Value *, Value *> &ChosenPairs,
1099 DenseMap<ValuePair, size_t> &Tree,
1100 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1101 bool UseCycleCheck) {
1102 SmallVector<ValuePairWithDepth, 32> Q;
1103 // General depth-first post-order traversal:
1104 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1106 ValuePairWithDepth QTop = Q.pop_back_val();
1107 PrunedTree.insert(QTop.first);
1109 // Visit each child, pruning as necessary...
1110 DenseMap<ValuePair, size_t> BestChildren;
1111 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1112 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1113 K != QTopRange.second; ++K) {
1114 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1115 if (C == Tree.end()) continue;
1117 // This child is in the Tree, now we need to make sure it is the
1118 // best of any conflicting children. There could be multiple
1119 // conflicting children, so first, determine if we're keeping
1120 // this child, then delete conflicting children as necessary.
1122 // It is also necessary to guard against pairing-induced
1123 // dependencies. Consider instructions a .. x .. y .. b
1124 // such that (a,b) are to be fused and (x,y) are to be fused
1125 // but a is an input to x and b is an output from y. This
1126 // means that y cannot be moved after b but x must be moved
1127 // after b for (a,b) to be fused. In other words, after
1128 // fusing (a,b) we have y .. a/b .. x where y is an input
1129 // to a/b and x is an output to a/b: x and y can no longer
1130 // be legally fused. To prevent this condition, we must
1131 // make sure that a child pair added to the Tree is not
1132 // both an input and output of an already-selected pair.
1134 // Pairing-induced dependencies can also form from more complicated
1135 // cycles. The pair vs. pair conflicts are easy to check, and so
1136 // that is done explicitly for "fast rejection", and because for
1137 // child vs. child conflicts, we may prefer to keep the current
1138 // pair in preference to the already-selected child.
1139 DenseSet<ValuePair> CurrentPairs;
1142 for (DenseMap<ValuePair, size_t>::iterator C2
1143 = BestChildren.begin(), E2 = BestChildren.end();
1145 if (C2->first.first == C->first.first ||
1146 C2->first.first == C->first.second ||
1147 C2->first.second == C->first.first ||
1148 C2->first.second == C->first.second ||
1149 pairsConflict(C2->first, C->first, PairableInstUsers,
1150 UseCycleCheck ? &PairableInstUserMap : 0)) {
1151 if (C2->second >= C->second) {
1156 CurrentPairs.insert(C2->first);
1159 if (!CanAdd) continue;
1161 // Even worse, this child could conflict with another node already
1162 // selected for the Tree. If that is the case, ignore this child.
1163 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1164 E2 = PrunedTree.end(); T != E2; ++T) {
1165 if (T->first == C->first.first ||
1166 T->first == C->first.second ||
1167 T->second == C->first.first ||
1168 T->second == C->first.second ||
1169 pairsConflict(*T, C->first, PairableInstUsers,
1170 UseCycleCheck ? &PairableInstUserMap : 0)) {
1175 CurrentPairs.insert(*T);
1177 if (!CanAdd) continue;
1179 // And check the queue too...
1180 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1181 E2 = Q.end(); C2 != E2; ++C2) {
1182 if (C2->first.first == C->first.first ||
1183 C2->first.first == C->first.second ||
1184 C2->first.second == C->first.first ||
1185 C2->first.second == C->first.second ||
1186 pairsConflict(C2->first, C->first, PairableInstUsers,
1187 UseCycleCheck ? &PairableInstUserMap : 0)) {
1192 CurrentPairs.insert(C2->first);
1194 if (!CanAdd) continue;
1196 // Last but not least, check for a conflict with any of the
1197 // already-chosen pairs.
1198 for (DenseMap<Value *, Value *>::iterator C2 =
1199 ChosenPairs.begin(), E2 = ChosenPairs.end();
1201 if (pairsConflict(*C2, C->first, PairableInstUsers,
1202 UseCycleCheck ? &PairableInstUserMap : 0)) {
1207 CurrentPairs.insert(*C2);
1209 if (!CanAdd) continue;
1211 // To check for non-trivial cycles formed by the addition of the
1212 // current pair we've formed a list of all relevant pairs, now use a
1213 // graph walk to check for a cycle. We start from the current pair and
1214 // walk the use tree to see if we again reach the current pair. If we
1215 // do, then the current pair is rejected.
1217 // FIXME: It may be more efficient to use a topological-ordering
1218 // algorithm to improve the cycle check. This should be investigated.
1219 if (UseCycleCheck &&
1220 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1223 // This child can be added, but we may have chosen it in preference
1224 // to an already-selected child. Check for this here, and if a
1225 // conflict is found, then remove the previously-selected child
1226 // before adding this one in its place.
1227 for (DenseMap<ValuePair, size_t>::iterator C2
1228 = BestChildren.begin(); C2 != BestChildren.end();) {
1229 if (C2->first.first == C->first.first ||
1230 C2->first.first == C->first.second ||
1231 C2->first.second == C->first.first ||
1232 C2->first.second == C->first.second ||
1233 pairsConflict(C2->first, C->first, PairableInstUsers))
1234 BestChildren.erase(C2++);
1239 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1242 for (DenseMap<ValuePair, size_t>::iterator C
1243 = BestChildren.begin(), E2 = BestChildren.end();
1245 size_t DepthF = getDepthFactor(C->first.first);
1246 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1248 } while (!Q.empty());
1251 // This function finds the best tree of mututally-compatible connected
1252 // pairs, given the choice of root pairs as an iterator range.
1253 void BBVectorize::findBestTreeFor(
1254 std::multimap<Value *, Value *> &CandidatePairs,
1255 std::vector<Value *> &PairableInsts,
1256 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1257 DenseSet<ValuePair> &PairableInstUsers,
1258 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1259 DenseMap<Value *, Value *> &ChosenPairs,
1260 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1261 size_t &BestEffSize, VPIteratorPair ChoiceRange,
1262 bool UseCycleCheck) {
1263 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1264 J != ChoiceRange.second; ++J) {
1266 // Before going any further, make sure that this pair does not
1267 // conflict with any already-selected pairs (see comment below
1268 // near the Tree pruning for more details).
1269 DenseSet<ValuePair> ChosenPairSet;
1270 bool DoesConflict = false;
1271 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1272 E = ChosenPairs.end(); C != E; ++C) {
1273 if (pairsConflict(*C, *J, PairableInstUsers,
1274 UseCycleCheck ? &PairableInstUserMap : 0)) {
1275 DoesConflict = true;
1279 ChosenPairSet.insert(*C);
1281 if (DoesConflict) continue;
1283 if (UseCycleCheck &&
1284 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1287 DenseMap<ValuePair, size_t> Tree;
1288 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1289 PairableInstUsers, ChosenPairs, Tree, *J);
1291 // Because we'll keep the child with the largest depth, the largest
1292 // depth is still the same in the unpruned Tree.
1293 size_t MaxDepth = Tree.lookup(*J);
1295 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1296 << *J->first << " <-> " << *J->second << "} of depth " <<
1297 MaxDepth << " and size " << Tree.size() << "\n");
1299 // At this point the Tree has been constructed, but, may contain
1300 // contradictory children (meaning that different children of
1301 // some tree node may be attempting to fuse the same instruction).
1302 // So now we walk the tree again, in the case of a conflict,
1303 // keep only the child with the largest depth. To break a tie,
1304 // favor the first child.
1306 DenseSet<ValuePair> PrunedTree;
1307 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1308 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1309 PrunedTree, *J, UseCycleCheck);
1312 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1313 E = PrunedTree.end(); S != E; ++S)
1314 EffSize += getDepthFactor(S->first);
1316 DEBUG(if (DebugPairSelection)
1317 dbgs() << "BBV: found pruned Tree for pair {"
1318 << *J->first << " <-> " << *J->second << "} of depth " <<
1319 MaxDepth << " and size " << PrunedTree.size() <<
1320 " (effective size: " << EffSize << ")\n");
1321 if (MaxDepth >= Config.ReqChainDepth && EffSize > BestEffSize) {
1322 BestMaxDepth = MaxDepth;
1323 BestEffSize = EffSize;
1324 BestTree = PrunedTree;
1329 // Given the list of candidate pairs, this function selects those
1330 // that will be fused into vector instructions.
1331 void BBVectorize::choosePairs(
1332 std::multimap<Value *, Value *> &CandidatePairs,
1333 std::vector<Value *> &PairableInsts,
1334 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1335 DenseSet<ValuePair> &PairableInstUsers,
1336 DenseMap<Value *, Value *>& ChosenPairs) {
1337 bool UseCycleCheck =
1338 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1339 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1340 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1341 E = PairableInsts.end(); I != E; ++I) {
1342 // The number of possible pairings for this variable:
1343 size_t NumChoices = CandidatePairs.count(*I);
1344 if (!NumChoices) continue;
1346 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1348 // The best pair to choose and its tree:
1349 size_t BestMaxDepth = 0, BestEffSize = 0;
1350 DenseSet<ValuePair> BestTree;
1351 findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1352 PairableInstUsers, PairableInstUserMap, ChosenPairs,
1353 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1356 // A tree has been chosen (or not) at this point. If no tree was
1357 // chosen, then this instruction, I, cannot be paired (and is no longer
1360 DEBUG(if (BestTree.size() > 0)
1361 dbgs() << "BBV: selected pairs in the best tree for: "
1362 << *cast<Instruction>(*I) << "\n");
1364 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1365 SE2 = BestTree.end(); S != SE2; ++S) {
1366 // Insert the members of this tree into the list of chosen pairs.
1367 ChosenPairs.insert(ValuePair(S->first, S->second));
1368 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1369 *S->second << "\n");
1371 // Remove all candidate pairs that have values in the chosen tree.
1372 for (std::multimap<Value *, Value *>::iterator K =
1373 CandidatePairs.begin(); K != CandidatePairs.end();) {
1374 if (K->first == S->first || K->second == S->first ||
1375 K->second == S->second || K->first == S->second) {
1376 // Don't remove the actual pair chosen so that it can be used
1377 // in subsequent tree selections.
1378 if (!(K->first == S->first && K->second == S->second))
1379 CandidatePairs.erase(K++);
1389 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1392 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1397 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1398 (n > 0 ? "." + utostr(n) : "")).str();
1401 // Returns the value that is to be used as the pointer input to the vector
1402 // instruction that fuses I with J.
1403 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1404 Instruction *I, Instruction *J, unsigned o,
1405 bool &FlipMemInputs) {
1407 unsigned IAlignment, JAlignment;
1408 int64_t OffsetInElmts;
1409 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1412 // The pointer value is taken to be the one with the lowest offset.
1414 if (OffsetInElmts > 0) {
1417 FlipMemInputs = true;
1421 Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1422 Type *VArgType = getVecTypeForPair(ArgType);
1423 Type *VArgPtrType = PointerType::get(VArgType,
1424 cast<PointerType>(IPtr->getType())->getAddressSpace());
1425 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1426 /* insert before */ FlipMemInputs ? J : I);
1429 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1430 unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1431 unsigned IdxOffset, std::vector<Constant*> &Mask) {
1432 for (unsigned v = 0; v < NumElem/2; ++v) {
1433 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1435 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1437 unsigned mm = m + (int) IdxOffset;
1438 if (m >= (int) NumInElem)
1439 mm += (int) NumInElem;
1441 Mask[v+MaskOffset] =
1442 ConstantInt::get(Type::getInt32Ty(Context), mm);
1447 // Returns the value that is to be used as the vector-shuffle mask to the
1448 // vector instruction that fuses I with J.
1449 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1450 Instruction *I, Instruction *J) {
1451 // This is the shuffle mask. We need to append the second
1452 // mask to the first, and the numbers need to be adjusted.
1454 Type *ArgType = I->getType();
1455 Type *VArgType = getVecTypeForPair(ArgType);
1457 // Get the total number of elements in the fused vector type.
1458 // By definition, this must equal the number of elements in
1460 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1461 std::vector<Constant*> Mask(NumElem);
1463 Type *OpType = I->getOperand(0)->getType();
1464 unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1466 // For the mask from the first pair...
1467 fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1469 // For the mask from the second pair...
1470 fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1473 return ConstantVector::get(Mask);
1476 // Returns the value to be used as the specified operand of the vector
1477 // instruction that fuses I with J.
1478 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1479 Instruction *J, unsigned o, bool FlipMemInputs) {
1480 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1481 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1483 // Compute the fused vector type for this operand
1484 Type *ArgType = I->getOperand(o)->getType();
1485 VectorType *VArgType = getVecTypeForPair(ArgType);
1487 Instruction *L = I, *H = J;
1488 if (FlipMemInputs) {
1493 if (ArgType->isVectorTy()) {
1494 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1495 std::vector<Constant*> Mask(numElem);
1496 for (unsigned v = 0; v < numElem; ++v)
1497 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1499 Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1501 ConstantVector::get(Mask),
1502 getReplacementName(I, true, o));
1503 BV->insertBefore(J);
1507 // If these two inputs are the output of another vector instruction,
1508 // then we should use that output directly. It might be necessary to
1509 // permute it first. [When pairings are fused recursively, you can
1510 // end up with cases where a large vector is decomposed into scalars
1511 // using extractelement instructions, then built into size-2
1512 // vectors using insertelement and the into larger vectors using
1513 // shuffles. InstCombine does not simplify all of these cases well,
1514 // and so we make sure that shuffles are generated here when possible.
1515 ExtractElementInst *LEE
1516 = dyn_cast<ExtractElementInst>(L->getOperand(o));
1517 ExtractElementInst *HEE
1518 = dyn_cast<ExtractElementInst>(H->getOperand(o));
1521 LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1522 VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1523 unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1524 unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1525 if (LEE->getOperand(0) == HEE->getOperand(0)) {
1526 if (LowIndx == 0 && HighIndx == 1)
1527 return LEE->getOperand(0);
1529 std::vector<Constant*> Mask(2);
1530 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1531 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1533 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1534 UndefValue::get(EEType),
1535 ConstantVector::get(Mask),
1536 getReplacementName(I, true, o));
1537 BV->insertBefore(J);
1541 std::vector<Constant*> Mask(2);
1542 HighIndx += EEType->getNumElements();
1543 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1544 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1546 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1548 ConstantVector::get(Mask),
1549 getReplacementName(I, true, o));
1550 BV->insertBefore(J);
1554 Instruction *BV1 = InsertElementInst::Create(
1555 UndefValue::get(VArgType),
1556 L->getOperand(o), CV0,
1557 getReplacementName(I, true, o, 1));
1558 BV1->insertBefore(I);
1559 Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1561 getReplacementName(I, true, o, 2));
1562 BV2->insertBefore(J);
1566 // This function creates an array of values that will be used as the inputs
1567 // to the vector instruction that fuses I with J.
1568 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1569 Instruction *I, Instruction *J,
1570 SmallVector<Value *, 3> &ReplacedOperands,
1571 bool &FlipMemInputs) {
1572 FlipMemInputs = false;
1573 unsigned NumOperands = I->getNumOperands();
1575 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1576 // Iterate backward so that we look at the store pointer
1577 // first and know whether or not we need to flip the inputs.
1579 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1580 // This is the pointer for a load/store instruction.
1581 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1584 } else if (isa<CallInst>(I)) {
1585 Function *F = cast<CallInst>(I)->getCalledFunction();
1586 unsigned IID = F->getIntrinsicID();
1587 if (o == NumOperands-1) {
1588 BasicBlock &BB = *I->getParent();
1590 Module *M = BB.getParent()->getParent();
1591 Type *ArgType = I->getType();
1592 Type *VArgType = getVecTypeForPair(ArgType);
1594 // FIXME: is it safe to do this here?
1595 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1596 (Intrinsic::ID) IID, VArgType);
1598 } else if (IID == Intrinsic::powi && o == 1) {
1599 // The second argument of powi is a single integer and we've already
1600 // checked that both arguments are equal. As a result, we just keep
1601 // I's second argument.
1602 ReplacedOperands[o] = I->getOperand(o);
1605 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1606 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1610 ReplacedOperands[o] =
1611 getReplacementInput(Context, I, J, o, FlipMemInputs);
1615 // This function creates two values that represent the outputs of the
1616 // original I and J instructions. These are generally vector shuffles
1617 // or extracts. In many cases, these will end up being unused and, thus,
1618 // eliminated by later passes.
1619 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1620 Instruction *J, Instruction *K,
1621 Instruction *&InsertionPt,
1622 Instruction *&K1, Instruction *&K2,
1623 bool &FlipMemInputs) {
1624 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1625 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1627 if (isa<StoreInst>(I)) {
1628 AA->replaceWithNewValue(I, K);
1629 AA->replaceWithNewValue(J, K);
1631 Type *IType = I->getType();
1632 Type *VType = getVecTypeForPair(IType);
1634 if (IType->isVectorTy()) {
1635 unsigned numElem = cast<VectorType>(IType)->getNumElements();
1636 std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1637 for (unsigned v = 0; v < numElem; ++v) {
1638 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1639 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1642 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1643 ConstantVector::get(
1644 FlipMemInputs ? Mask2 : Mask1),
1645 getReplacementName(K, false, 1));
1646 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1647 ConstantVector::get(
1648 FlipMemInputs ? Mask1 : Mask2),
1649 getReplacementName(K, false, 2));
1651 K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1652 getReplacementName(K, false, 1));
1653 K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1654 getReplacementName(K, false, 2));
1658 K2->insertAfter(K1);
1663 // Move all uses of the function I (including pairing-induced uses) after J.
1664 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1665 std::multimap<Value *, Value *> &LoadMoveSet,
1666 Instruction *I, Instruction *J) {
1667 // Skip to the first instruction past I.
1668 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1670 DenseSet<Value *> Users;
1671 AliasSetTracker WriteSet(*AA);
1672 for (; cast<Instruction>(L) != J; ++L)
1673 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1675 assert(cast<Instruction>(L) == J &&
1676 "Tracking has not proceeded far enough to check for dependencies");
1677 // If J is now in the use set of I, then trackUsesOfI will return true
1678 // and we have a dependency cycle (and the fusing operation must abort).
1679 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1682 // Move all uses of the function I (including pairing-induced uses) after J.
1683 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1684 std::multimap<Value *, Value *> &LoadMoveSet,
1685 Instruction *&InsertionPt,
1686 Instruction *I, Instruction *J) {
1687 // Skip to the first instruction past I.
1688 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1690 DenseSet<Value *> Users;
1691 AliasSetTracker WriteSet(*AA);
1692 for (; cast<Instruction>(L) != J;) {
1693 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1694 // Move this instruction
1695 Instruction *InstToMove = L; ++L;
1697 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1698 " to after " << *InsertionPt << "\n");
1699 InstToMove->removeFromParent();
1700 InstToMove->insertAfter(InsertionPt);
1701 InsertionPt = InstToMove;
1708 // Collect all load instruction that are in the move set of a given first
1709 // pair member. These loads depend on the first instruction, I, and so need
1710 // to be moved after J (the second instruction) when the pair is fused.
1711 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1712 DenseMap<Value *, Value *> &ChosenPairs,
1713 std::multimap<Value *, Value *> &LoadMoveSet,
1715 // Skip to the first instruction past I.
1716 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1718 DenseSet<Value *> Users;
1719 AliasSetTracker WriteSet(*AA);
1721 // Note: We cannot end the loop when we reach J because J could be moved
1722 // farther down the use chain by another instruction pairing. Also, J
1723 // could be before I if this is an inverted input.
1724 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1725 if (trackUsesOfI(Users, WriteSet, I, L)) {
1726 if (L->mayReadFromMemory())
1727 LoadMoveSet.insert(ValuePair(L, I));
1732 // In cases where both load/stores and the computation of their pointers
1733 // are chosen for vectorization, we can end up in a situation where the
1734 // aliasing analysis starts returning different query results as the
1735 // process of fusing instruction pairs continues. Because the algorithm
1736 // relies on finding the same use trees here as were found earlier, we'll
1737 // need to precompute the necessary aliasing information here and then
1738 // manually update it during the fusion process.
1739 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1740 std::vector<Value *> &PairableInsts,
1741 DenseMap<Value *, Value *> &ChosenPairs,
1742 std::multimap<Value *, Value *> &LoadMoveSet) {
1743 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1744 PIE = PairableInsts.end(); PI != PIE; ++PI) {
1745 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1746 if (P == ChosenPairs.end()) continue;
1748 Instruction *I = cast<Instruction>(P->first);
1749 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1753 // This function fuses the chosen instruction pairs into vector instructions,
1754 // taking care preserve any needed scalar outputs and, then, it reorders the
1755 // remaining instructions as needed (users of the first member of the pair
1756 // need to be moved to after the location of the second member of the pair
1757 // because the vector instruction is inserted in the location of the pair's
1759 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1760 std::vector<Value *> &PairableInsts,
1761 DenseMap<Value *, Value *> &ChosenPairs) {
1762 LLVMContext& Context = BB.getContext();
1764 // During the vectorization process, the order of the pairs to be fused
1765 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1766 // list. After a pair is fused, the flipped pair is removed from the list.
1767 std::vector<ValuePair> FlippedPairs;
1768 FlippedPairs.reserve(ChosenPairs.size());
1769 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1770 E = ChosenPairs.end(); P != E; ++P)
1771 FlippedPairs.push_back(ValuePair(P->second, P->first));
1772 for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1773 E = FlippedPairs.end(); P != E; ++P)
1774 ChosenPairs.insert(*P);
1776 std::multimap<Value *, Value *> LoadMoveSet;
1777 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1779 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1781 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1782 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1783 if (P == ChosenPairs.end()) {
1788 if (getDepthFactor(P->first) == 0) {
1789 // These instructions are not really fused, but are tracked as though
1790 // they are. Any case in which it would be interesting to fuse them
1791 // will be taken care of by InstCombine.
1797 Instruction *I = cast<Instruction>(P->first),
1798 *J = cast<Instruction>(P->second);
1800 DEBUG(dbgs() << "BBV: fusing: " << *I <<
1801 " <-> " << *J << "\n");
1803 // Remove the pair and flipped pair from the list.
1804 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1805 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1806 ChosenPairs.erase(FP);
1807 ChosenPairs.erase(P);
1809 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1810 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1812 " aborted because of non-trivial dependency cycle\n");
1819 unsigned NumOperands = I->getNumOperands();
1820 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1821 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1824 // Make a copy of the original operation, change its type to the vector
1825 // type and replace its operands with the vector operands.
1826 Instruction *K = I->clone();
1827 if (I->hasName()) K->takeName(I);
1829 if (!isa<StoreInst>(K))
1830 K->mutateType(getVecTypeForPair(I->getType()));
1832 for (unsigned o = 0; o < NumOperands; ++o)
1833 K->setOperand(o, ReplacedOperands[o]);
1835 // If we've flipped the memory inputs, make sure that we take the correct
1837 if (FlipMemInputs) {
1838 if (isa<StoreInst>(K))
1839 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1841 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1846 // Instruction insertion point:
1847 Instruction *InsertionPt = K;
1848 Instruction *K1 = 0, *K2 = 0;
1849 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1852 // The use tree of the first original instruction must be moved to after
1853 // the location of the second instruction. The entire use tree of the
1854 // first instruction is disjoint from the input tree of the second
1855 // (by definition), and so commutes with it.
1857 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1859 if (!isa<StoreInst>(I)) {
1860 I->replaceAllUsesWith(K1);
1861 J->replaceAllUsesWith(K2);
1862 AA->replaceWithNewValue(I, K1);
1863 AA->replaceWithNewValue(J, K2);
1866 // Instructions that may read from memory may be in the load move set.
1867 // Once an instruction is fused, we no longer need its move set, and so
1868 // the values of the map never need to be updated. However, when a load
1869 // is fused, we need to merge the entries from both instructions in the
1870 // pair in case those instructions were in the move set of some other
1871 // yet-to-be-fused pair. The loads in question are the keys of the map.
1872 if (I->mayReadFromMemory()) {
1873 std::vector<ValuePair> NewSetMembers;
1874 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1875 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1876 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1877 N != IPairRange.second; ++N)
1878 NewSetMembers.push_back(ValuePair(K, N->second));
1879 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1880 N != JPairRange.second; ++N)
1881 NewSetMembers.push_back(ValuePair(K, N->second));
1882 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1883 AE = NewSetMembers.end(); A != AE; ++A)
1884 LoadMoveSet.insert(*A);
1887 // Before removing I, set the iterator to the next instruction.
1888 PI = llvm::next(BasicBlock::iterator(I));
1889 if (cast<Instruction>(PI) == J)
1894 I->eraseFromParent();
1895 J->eraseFromParent();
1898 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1902 char BBVectorize::ID = 0;
1903 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1904 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1905 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1906 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1907 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1909 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
1910 return new BBVectorize(C);
1914 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
1915 BBVectorize BBVectorizer(P, C);
1916 return BBVectorizer.vectorizeBB(BB);
1919 //===----------------------------------------------------------------------===//
1920 VectorizeConfig::VectorizeConfig() {
1921 VectorBits = ::VectorBits;
1922 VectorizeInts = !::NoInts;
1923 VectorizeFloats = !::NoFloats;
1924 VectorizePointers = !::NoPointers;
1925 VectorizeCasts = !::NoCasts;
1926 VectorizeMath = !::NoMath;
1927 VectorizeFMA = !::NoFMA;
1928 VectorizeSelect = !::NoSelect;
1929 VectorizeGEP = !::NoGEP;
1930 VectorizeMemOps = !::NoMemOps;
1931 AlignedOnly = ::AlignedOnly;
1932 ReqChainDepth= ::ReqChainDepth;
1933 SearchLimit = ::SearchLimit;
1934 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
1935 SplatBreaksChain = ::SplatBreaksChain;
1936 MaxInsts = ::MaxInsts;
1937 MaxIter = ::MaxIter;
1938 NoMemOpBoost = ::NoMemOpBoost;
1939 FastDep = ::FastDep;