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 // Don't vectorize target-specific types.
616 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
618 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
621 if ((!Config.VectorizePointers || TD == 0) &&
622 (T1->getScalarType()->isPointerTy() ||
623 T2->getScalarType()->isPointerTy()))
626 if (T1->getPrimitiveSizeInBits() > Config.VectorBits/2 ||
627 T2->getPrimitiveSizeInBits() > Config.VectorBits/2)
633 // This function returns true if the two provided instructions are compatible
634 // (meaning that they can be fused into a vector instruction). This assumes
635 // that I has already been determined to be vectorizable and that J is not
636 // in the use tree of I.
637 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
638 bool IsSimpleLoadStore) {
639 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
640 " <-> " << *J << "\n");
642 // Loads and stores can be merged if they have different alignments,
643 // but are otherwise the same.
646 if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
647 if (I->getType() != J->getType())
650 if (LI->getPointerOperand()->getType() !=
651 LJ->getPointerOperand()->getType() ||
652 LI->isVolatile() != LJ->isVolatile() ||
653 LI->getOrdering() != LJ->getOrdering() ||
654 LI->getSynchScope() != LJ->getSynchScope())
656 } else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
657 if (SI->getValueOperand()->getType() !=
658 SJ->getValueOperand()->getType() ||
659 SI->getPointerOperand()->getType() !=
660 SJ->getPointerOperand()->getType() ||
661 SI->isVolatile() != SJ->isVolatile() ||
662 SI->getOrdering() != SJ->getOrdering() ||
663 SI->getSynchScope() != SJ->getSynchScope())
665 } else if (!J->isSameOperationAs(I)) {
668 // FIXME: handle addsub-type operations!
670 if (IsSimpleLoadStore) {
672 unsigned IAlignment, JAlignment;
673 int64_t OffsetInElmts = 0;
674 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
675 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
676 if (Config.AlignedOnly) {
677 Type *aType = isa<StoreInst>(I) ?
678 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
679 // An aligned load or store is possible only if the instruction
680 // with the lower offset has an alignment suitable for the
683 unsigned BottomAlignment = IAlignment;
684 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
686 Type *VType = getVecTypeForPair(aType);
687 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
688 if (BottomAlignment < VecAlignment)
694 } else if (isa<ShuffleVectorInst>(I)) {
695 // Only merge two shuffles if they're both constant
696 return isa<Constant>(I->getOperand(2)) &&
697 isa<Constant>(J->getOperand(2));
698 // FIXME: We may want to vectorize non-constant shuffles also.
701 // The powi intrinsic is special because only the first argument is
702 // vectorized, the second arguments must be equal.
703 CallInst *CI = dyn_cast<CallInst>(I);
705 if (CI && (FI = CI->getCalledFunction()) &&
706 FI->getIntrinsicID() == Intrinsic::powi) {
708 Value *A1I = CI->getArgOperand(1),
709 *A1J = cast<CallInst>(J)->getArgOperand(1);
710 const SCEV *A1ISCEV = SE->getSCEV(A1I),
711 *A1JSCEV = SE->getSCEV(A1J);
712 return (A1ISCEV == A1JSCEV);
718 // Figure out whether or not J uses I and update the users and write-set
719 // structures associated with I. Specifically, Users represents the set of
720 // instructions that depend on I. WriteSet represents the set
721 // of memory locations that are dependent on I. If UpdateUsers is true,
722 // and J uses I, then Users is updated to contain J and WriteSet is updated
723 // to contain any memory locations to which J writes. The function returns
724 // true if J uses I. By default, alias analysis is used to determine
725 // whether J reads from memory that overlaps with a location in WriteSet.
726 // If LoadMoveSet is not null, then it is a previously-computed multimap
727 // where the key is the memory-based user instruction and the value is
728 // the instruction to be compared with I. So, if LoadMoveSet is provided,
729 // then the alias analysis is not used. This is necessary because this
730 // function is called during the process of moving instructions during
731 // vectorization and the results of the alias analysis are not stable during
733 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
734 AliasSetTracker &WriteSet, Instruction *I,
735 Instruction *J, bool UpdateUsers,
736 std::multimap<Value *, Value *> *LoadMoveSet) {
739 // This instruction may already be marked as a user due, for example, to
740 // being a member of a selected pair.
745 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
748 if (I == V || Users.count(V)) {
753 if (!UsesI && J->mayReadFromMemory()) {
755 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
756 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
758 for (AliasSetTracker::iterator W = WriteSet.begin(),
759 WE = WriteSet.end(); W != WE; ++W) {
760 if (W->aliasesUnknownInst(J, *AA)) {
768 if (UsesI && UpdateUsers) {
769 if (J->mayWriteToMemory()) WriteSet.add(J);
776 // This function iterates over all instruction pairs in the provided
777 // basic block and collects all candidate pairs for vectorization.
778 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
779 BasicBlock::iterator &Start,
780 std::multimap<Value *, Value *> &CandidatePairs,
781 std::vector<Value *> &PairableInsts) {
782 BasicBlock::iterator E = BB.end();
783 if (Start == E) return false;
785 bool ShouldContinue = false, IAfterStart = false;
786 for (BasicBlock::iterator I = Start++; I != E; ++I) {
787 if (I == Start) IAfterStart = true;
789 bool IsSimpleLoadStore;
790 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
792 // Look for an instruction with which to pair instruction *I...
793 DenseSet<Value *> Users;
794 AliasSetTracker WriteSet(*AA);
795 bool JAfterStart = IAfterStart;
796 BasicBlock::iterator J = llvm::next(I);
797 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
798 if (J == Start) JAfterStart = true;
800 // Determine if J uses I, if so, exit the loop.
801 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
802 if (Config.FastDep) {
803 // Note: For this heuristic to be effective, independent operations
804 // must tend to be intermixed. This is likely to be true from some
805 // kinds of grouped loop unrolling (but not the generic LLVM pass),
806 // but otherwise may require some kind of reordering pass.
808 // When using fast dependency analysis,
809 // stop searching after first use:
815 // J does not use I, and comes before the first use of I, so it can be
816 // merged with I if the instructions are compatible.
817 if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
819 // J is a candidate for merging with I.
820 if (!PairableInsts.size() ||
821 PairableInsts[PairableInsts.size()-1] != I) {
822 PairableInsts.push_back(I);
825 CandidatePairs.insert(ValuePair(I, J));
827 // The next call to this function must start after the last instruction
828 // selected during this invocation.
830 Start = llvm::next(J);
831 IAfterStart = JAfterStart = false;
834 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
835 << *I << " <-> " << *J << "\n");
837 // If we have already found too many pairs, break here and this function
838 // will be called again starting after the last instruction selected
839 // during this invocation.
840 if (PairableInsts.size() >= Config.MaxInsts) {
841 ShouldContinue = true;
850 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
851 << " instructions with candidate pairs\n");
853 return ShouldContinue;
856 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
857 // it looks for pairs such that both members have an input which is an
858 // output of PI or PJ.
859 void BBVectorize::computePairsConnectedTo(
860 std::multimap<Value *, Value *> &CandidatePairs,
861 std::vector<Value *> &PairableInsts,
862 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
866 // For each possible pairing for this variable, look at the uses of
867 // the first value...
868 for (Value::use_iterator I = P.first->use_begin(),
869 E = P.first->use_end(); I != E; ++I) {
870 if (isa<LoadInst>(*I)) {
871 // A pair cannot be connected to a load because the load only takes one
872 // operand (the address) and it is a scalar even after vectorization.
874 } else if ((SI = dyn_cast<StoreInst>(*I)) &&
875 P.first == SI->getPointerOperand()) {
876 // Similarly, a pair cannot be connected to a store through its
881 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
883 // For each use of the first variable, look for uses of the second
885 for (Value::use_iterator J = P.second->use_begin(),
886 E2 = P.second->use_end(); J != E2; ++J) {
887 if ((SJ = dyn_cast<StoreInst>(*J)) &&
888 P.second == SJ->getPointerOperand())
891 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
894 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
895 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
898 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
899 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
902 if (Config.SplatBreaksChain) continue;
903 // Look for cases where just the first value in the pair is used by
904 // both members of another pair (splatting).
905 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
906 if ((SJ = dyn_cast<StoreInst>(*J)) &&
907 P.first == SJ->getPointerOperand())
910 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
911 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
915 if (Config.SplatBreaksChain) return;
916 // Look for cases where just the second value in the pair is used by
917 // both members of another pair (splatting).
918 for (Value::use_iterator I = P.second->use_begin(),
919 E = P.second->use_end(); I != E; ++I) {
920 if (isa<LoadInst>(*I))
922 else if ((SI = dyn_cast<StoreInst>(*I)) &&
923 P.second == SI->getPointerOperand())
926 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
928 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
929 if ((SJ = dyn_cast<StoreInst>(*J)) &&
930 P.second == SJ->getPointerOperand())
933 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
934 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
939 // This function figures out which pairs are connected. Two pairs are
940 // connected if some output of the first pair forms an input to both members
941 // of the second pair.
942 void BBVectorize::computeConnectedPairs(
943 std::multimap<Value *, Value *> &CandidatePairs,
944 std::vector<Value *> &PairableInsts,
945 std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
947 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
948 PE = PairableInsts.end(); PI != PE; ++PI) {
949 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
951 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
952 P != choiceRange.second; ++P)
953 computePairsConnectedTo(CandidatePairs, PairableInsts,
957 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
958 << " pair connections.\n");
961 // This function builds a set of use tuples such that <A, B> is in the set
962 // if B is in the use tree of A. If B is in the use tree of A, then B
963 // depends on the output of A.
964 void BBVectorize::buildDepMap(
966 std::multimap<Value *, Value *> &CandidatePairs,
967 std::vector<Value *> &PairableInsts,
968 DenseSet<ValuePair> &PairableInstUsers) {
969 DenseSet<Value *> IsInPair;
970 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
971 E = CandidatePairs.end(); C != E; ++C) {
972 IsInPair.insert(C->first);
973 IsInPair.insert(C->second);
976 // Iterate through the basic block, recording all Users of each
977 // pairable instruction.
979 BasicBlock::iterator E = BB.end();
980 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
981 if (IsInPair.find(I) == IsInPair.end()) continue;
983 DenseSet<Value *> Users;
984 AliasSetTracker WriteSet(*AA);
985 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
986 (void) trackUsesOfI(Users, WriteSet, I, J);
988 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
990 PairableInstUsers.insert(ValuePair(I, *U));
994 // Returns true if an input to pair P is an output of pair Q and also an
995 // input of pair Q is an output of pair P. If this is the case, then these
996 // two pairs cannot be simultaneously fused.
997 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
998 DenseSet<ValuePair> &PairableInstUsers,
999 std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1000 // Two pairs are in conflict if they are mutual Users of eachother.
1001 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1002 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1003 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1004 PairableInstUsers.count(ValuePair(P.second, Q.second));
1005 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1006 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1007 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1008 PairableInstUsers.count(ValuePair(Q.second, P.second));
1009 if (PairableInstUserMap) {
1010 // FIXME: The expensive part of the cycle check is not so much the cycle
1011 // check itself but this edge insertion procedure. This needs some
1012 // profiling and probably a different data structure (same is true of
1013 // most uses of std::multimap).
1015 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1016 if (!isSecondInIteratorPair(P, QPairRange))
1017 PairableInstUserMap->insert(VPPair(Q, P));
1020 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1021 if (!isSecondInIteratorPair(Q, PPairRange))
1022 PairableInstUserMap->insert(VPPair(P, Q));
1026 return (QUsesP && PUsesQ);
1029 // This function walks the use graph of current pairs to see if, starting
1030 // from P, the walk returns to P.
1031 bool BBVectorize::pairWillFormCycle(ValuePair P,
1032 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1033 DenseSet<ValuePair> &CurrentPairs) {
1034 DEBUG(if (DebugCycleCheck)
1035 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1036 << *P.second << "\n");
1037 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1038 // contains non-direct associations.
1039 DenseSet<ValuePair> Visited;
1040 SmallVector<ValuePair, 32> Q;
1041 // General depth-first post-order traversal:
1044 ValuePair QTop = Q.pop_back_val();
1045 Visited.insert(QTop);
1047 DEBUG(if (DebugCycleCheck)
1048 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1049 << *QTop.second << "\n");
1050 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1051 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1052 C != QPairRange.second; ++C) {
1053 if (C->second == P) {
1055 << "BBV: rejected to prevent non-trivial cycle formation: "
1056 << *C->first.first << " <-> " << *C->first.second << "\n");
1060 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1061 Q.push_back(C->second);
1063 } while (!Q.empty());
1068 // This function builds the initial tree of connected pairs with the
1069 // pair J at the root.
1070 void BBVectorize::buildInitialTreeFor(
1071 std::multimap<Value *, Value *> &CandidatePairs,
1072 std::vector<Value *> &PairableInsts,
1073 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1074 DenseSet<ValuePair> &PairableInstUsers,
1075 DenseMap<Value *, Value *> &ChosenPairs,
1076 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1077 // Each of these pairs is viewed as the root node of a Tree. The Tree
1078 // is then walked (depth-first). As this happens, we keep track of
1079 // the pairs that compose the Tree and the maximum depth of the Tree.
1080 SmallVector<ValuePairWithDepth, 32> Q;
1081 // General depth-first post-order traversal:
1082 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1084 ValuePairWithDepth QTop = Q.back();
1086 // Push each child onto the queue:
1087 bool MoreChildren = false;
1088 size_t MaxChildDepth = QTop.second;
1089 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1090 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1091 k != qtRange.second; ++k) {
1092 // Make sure that this child pair is still a candidate:
1093 bool IsStillCand = false;
1094 VPIteratorPair checkRange =
1095 CandidatePairs.equal_range(k->second.first);
1096 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1097 m != checkRange.second; ++m) {
1098 if (m->second == k->second.second) {
1105 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1106 if (C == Tree.end()) {
1107 size_t d = getDepthFactor(k->second.first);
1108 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1109 MoreChildren = true;
1111 MaxChildDepth = std::max(MaxChildDepth, C->second);
1116 if (!MoreChildren) {
1117 // Record the current pair as part of the Tree:
1118 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1121 } while (!Q.empty());
1124 // Given some initial tree, prune it by removing conflicting pairs (pairs
1125 // that cannot be simultaneously chosen for vectorization).
1126 void BBVectorize::pruneTreeFor(
1127 std::multimap<Value *, Value *> &CandidatePairs,
1128 std::vector<Value *> &PairableInsts,
1129 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1130 DenseSet<ValuePair> &PairableInstUsers,
1131 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1132 DenseMap<Value *, Value *> &ChosenPairs,
1133 DenseMap<ValuePair, size_t> &Tree,
1134 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1135 bool UseCycleCheck) {
1136 SmallVector<ValuePairWithDepth, 32> Q;
1137 // General depth-first post-order traversal:
1138 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1140 ValuePairWithDepth QTop = Q.pop_back_val();
1141 PrunedTree.insert(QTop.first);
1143 // Visit each child, pruning as necessary...
1144 DenseMap<ValuePair, size_t> BestChildren;
1145 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1146 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1147 K != QTopRange.second; ++K) {
1148 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1149 if (C == Tree.end()) continue;
1151 // This child is in the Tree, now we need to make sure it is the
1152 // best of any conflicting children. There could be multiple
1153 // conflicting children, so first, determine if we're keeping
1154 // this child, then delete conflicting children as necessary.
1156 // It is also necessary to guard against pairing-induced
1157 // dependencies. Consider instructions a .. x .. y .. b
1158 // such that (a,b) are to be fused and (x,y) are to be fused
1159 // but a is an input to x and b is an output from y. This
1160 // means that y cannot be moved after b but x must be moved
1161 // after b for (a,b) to be fused. In other words, after
1162 // fusing (a,b) we have y .. a/b .. x where y is an input
1163 // to a/b and x is an output to a/b: x and y can no longer
1164 // be legally fused. To prevent this condition, we must
1165 // make sure that a child pair added to the Tree is not
1166 // both an input and output of an already-selected pair.
1168 // Pairing-induced dependencies can also form from more complicated
1169 // cycles. The pair vs. pair conflicts are easy to check, and so
1170 // that is done explicitly for "fast rejection", and because for
1171 // child vs. child conflicts, we may prefer to keep the current
1172 // pair in preference to the already-selected child.
1173 DenseSet<ValuePair> CurrentPairs;
1176 for (DenseMap<ValuePair, size_t>::iterator C2
1177 = BestChildren.begin(), E2 = BestChildren.end();
1179 if (C2->first.first == C->first.first ||
1180 C2->first.first == C->first.second ||
1181 C2->first.second == C->first.first ||
1182 C2->first.second == C->first.second ||
1183 pairsConflict(C2->first, C->first, PairableInstUsers,
1184 UseCycleCheck ? &PairableInstUserMap : 0)) {
1185 if (C2->second >= C->second) {
1190 CurrentPairs.insert(C2->first);
1193 if (!CanAdd) continue;
1195 // Even worse, this child could conflict with another node already
1196 // selected for the Tree. If that is the case, ignore this child.
1197 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1198 E2 = PrunedTree.end(); T != E2; ++T) {
1199 if (T->first == C->first.first ||
1200 T->first == C->first.second ||
1201 T->second == C->first.first ||
1202 T->second == C->first.second ||
1203 pairsConflict(*T, C->first, PairableInstUsers,
1204 UseCycleCheck ? &PairableInstUserMap : 0)) {
1209 CurrentPairs.insert(*T);
1211 if (!CanAdd) continue;
1213 // And check the queue too...
1214 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1215 E2 = Q.end(); C2 != E2; ++C2) {
1216 if (C2->first.first == C->first.first ||
1217 C2->first.first == C->first.second ||
1218 C2->first.second == C->first.first ||
1219 C2->first.second == C->first.second ||
1220 pairsConflict(C2->first, C->first, PairableInstUsers,
1221 UseCycleCheck ? &PairableInstUserMap : 0)) {
1226 CurrentPairs.insert(C2->first);
1228 if (!CanAdd) continue;
1230 // Last but not least, check for a conflict with any of the
1231 // already-chosen pairs.
1232 for (DenseMap<Value *, Value *>::iterator C2 =
1233 ChosenPairs.begin(), E2 = ChosenPairs.end();
1235 if (pairsConflict(*C2, C->first, PairableInstUsers,
1236 UseCycleCheck ? &PairableInstUserMap : 0)) {
1241 CurrentPairs.insert(*C2);
1243 if (!CanAdd) continue;
1245 // To check for non-trivial cycles formed by the addition of the
1246 // current pair we've formed a list of all relevant pairs, now use a
1247 // graph walk to check for a cycle. We start from the current pair and
1248 // walk the use tree to see if we again reach the current pair. If we
1249 // do, then the current pair is rejected.
1251 // FIXME: It may be more efficient to use a topological-ordering
1252 // algorithm to improve the cycle check. This should be investigated.
1253 if (UseCycleCheck &&
1254 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1257 // This child can be added, but we may have chosen it in preference
1258 // to an already-selected child. Check for this here, and if a
1259 // conflict is found, then remove the previously-selected child
1260 // before adding this one in its place.
1261 for (DenseMap<ValuePair, size_t>::iterator C2
1262 = BestChildren.begin(); C2 != BestChildren.end();) {
1263 if (C2->first.first == C->first.first ||
1264 C2->first.first == C->first.second ||
1265 C2->first.second == C->first.first ||
1266 C2->first.second == C->first.second ||
1267 pairsConflict(C2->first, C->first, PairableInstUsers))
1268 BestChildren.erase(C2++);
1273 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1276 for (DenseMap<ValuePair, size_t>::iterator C
1277 = BestChildren.begin(), E2 = BestChildren.end();
1279 size_t DepthF = getDepthFactor(C->first.first);
1280 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1282 } while (!Q.empty());
1285 // This function finds the best tree of mututally-compatible connected
1286 // pairs, given the choice of root pairs as an iterator range.
1287 void BBVectorize::findBestTreeFor(
1288 std::multimap<Value *, Value *> &CandidatePairs,
1289 std::vector<Value *> &PairableInsts,
1290 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1291 DenseSet<ValuePair> &PairableInstUsers,
1292 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1293 DenseMap<Value *, Value *> &ChosenPairs,
1294 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1295 size_t &BestEffSize, VPIteratorPair ChoiceRange,
1296 bool UseCycleCheck) {
1297 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1298 J != ChoiceRange.second; ++J) {
1300 // Before going any further, make sure that this pair does not
1301 // conflict with any already-selected pairs (see comment below
1302 // near the Tree pruning for more details).
1303 DenseSet<ValuePair> ChosenPairSet;
1304 bool DoesConflict = false;
1305 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1306 E = ChosenPairs.end(); C != E; ++C) {
1307 if (pairsConflict(*C, *J, PairableInstUsers,
1308 UseCycleCheck ? &PairableInstUserMap : 0)) {
1309 DoesConflict = true;
1313 ChosenPairSet.insert(*C);
1315 if (DoesConflict) continue;
1317 if (UseCycleCheck &&
1318 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1321 DenseMap<ValuePair, size_t> Tree;
1322 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1323 PairableInstUsers, ChosenPairs, Tree, *J);
1325 // Because we'll keep the child with the largest depth, the largest
1326 // depth is still the same in the unpruned Tree.
1327 size_t MaxDepth = Tree.lookup(*J);
1329 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1330 << *J->first << " <-> " << *J->second << "} of depth " <<
1331 MaxDepth << " and size " << Tree.size() << "\n");
1333 // At this point the Tree has been constructed, but, may contain
1334 // contradictory children (meaning that different children of
1335 // some tree node may be attempting to fuse the same instruction).
1336 // So now we walk the tree again, in the case of a conflict,
1337 // keep only the child with the largest depth. To break a tie,
1338 // favor the first child.
1340 DenseSet<ValuePair> PrunedTree;
1341 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1342 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1343 PrunedTree, *J, UseCycleCheck);
1346 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1347 E = PrunedTree.end(); S != E; ++S)
1348 EffSize += getDepthFactor(S->first);
1350 DEBUG(if (DebugPairSelection)
1351 dbgs() << "BBV: found pruned Tree for pair {"
1352 << *J->first << " <-> " << *J->second << "} of depth " <<
1353 MaxDepth << " and size " << PrunedTree.size() <<
1354 " (effective size: " << EffSize << ")\n");
1355 if (MaxDepth >= Config.ReqChainDepth && EffSize > BestEffSize) {
1356 BestMaxDepth = MaxDepth;
1357 BestEffSize = EffSize;
1358 BestTree = PrunedTree;
1363 // Given the list of candidate pairs, this function selects those
1364 // that will be fused into vector instructions.
1365 void BBVectorize::choosePairs(
1366 std::multimap<Value *, Value *> &CandidatePairs,
1367 std::vector<Value *> &PairableInsts,
1368 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1369 DenseSet<ValuePair> &PairableInstUsers,
1370 DenseMap<Value *, Value *>& ChosenPairs) {
1371 bool UseCycleCheck =
1372 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1373 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1374 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1375 E = PairableInsts.end(); I != E; ++I) {
1376 // The number of possible pairings for this variable:
1377 size_t NumChoices = CandidatePairs.count(*I);
1378 if (!NumChoices) continue;
1380 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1382 // The best pair to choose and its tree:
1383 size_t BestMaxDepth = 0, BestEffSize = 0;
1384 DenseSet<ValuePair> BestTree;
1385 findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1386 PairableInstUsers, PairableInstUserMap, ChosenPairs,
1387 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1390 // A tree has been chosen (or not) at this point. If no tree was
1391 // chosen, then this instruction, I, cannot be paired (and is no longer
1394 DEBUG(if (BestTree.size() > 0)
1395 dbgs() << "BBV: selected pairs in the best tree for: "
1396 << *cast<Instruction>(*I) << "\n");
1398 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1399 SE2 = BestTree.end(); S != SE2; ++S) {
1400 // Insert the members of this tree into the list of chosen pairs.
1401 ChosenPairs.insert(ValuePair(S->first, S->second));
1402 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1403 *S->second << "\n");
1405 // Remove all candidate pairs that have values in the chosen tree.
1406 for (std::multimap<Value *, Value *>::iterator K =
1407 CandidatePairs.begin(); K != CandidatePairs.end();) {
1408 if (K->first == S->first || K->second == S->first ||
1409 K->second == S->second || K->first == S->second) {
1410 // Don't remove the actual pair chosen so that it can be used
1411 // in subsequent tree selections.
1412 if (!(K->first == S->first && K->second == S->second))
1413 CandidatePairs.erase(K++);
1423 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1426 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1431 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1432 (n > 0 ? "." + utostr(n) : "")).str();
1435 // Returns the value that is to be used as the pointer input to the vector
1436 // instruction that fuses I with J.
1437 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1438 Instruction *I, Instruction *J, unsigned o,
1439 bool &FlipMemInputs) {
1441 unsigned IAlignment, JAlignment;
1442 int64_t OffsetInElmts;
1443 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1446 // The pointer value is taken to be the one with the lowest offset.
1448 if (OffsetInElmts > 0) {
1451 FlipMemInputs = true;
1455 Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1456 Type *VArgType = getVecTypeForPair(ArgType);
1457 Type *VArgPtrType = PointerType::get(VArgType,
1458 cast<PointerType>(IPtr->getType())->getAddressSpace());
1459 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1460 /* insert before */ FlipMemInputs ? J : I);
1463 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1464 unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1465 unsigned IdxOffset, std::vector<Constant*> &Mask) {
1466 for (unsigned v = 0; v < NumElem/2; ++v) {
1467 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1469 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1471 unsigned mm = m + (int) IdxOffset;
1472 if (m >= (int) NumInElem)
1473 mm += (int) NumInElem;
1475 Mask[v+MaskOffset] =
1476 ConstantInt::get(Type::getInt32Ty(Context), mm);
1481 // Returns the value that is to be used as the vector-shuffle mask to the
1482 // vector instruction that fuses I with J.
1483 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1484 Instruction *I, Instruction *J) {
1485 // This is the shuffle mask. We need to append the second
1486 // mask to the first, and the numbers need to be adjusted.
1488 Type *ArgType = I->getType();
1489 Type *VArgType = getVecTypeForPair(ArgType);
1491 // Get the total number of elements in the fused vector type.
1492 // By definition, this must equal the number of elements in
1494 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1495 std::vector<Constant*> Mask(NumElem);
1497 Type *OpType = I->getOperand(0)->getType();
1498 unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1500 // For the mask from the first pair...
1501 fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1503 // For the mask from the second pair...
1504 fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1507 return ConstantVector::get(Mask);
1510 // Returns the value to be used as the specified operand of the vector
1511 // instruction that fuses I with J.
1512 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1513 Instruction *J, unsigned o, bool FlipMemInputs) {
1514 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1515 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1517 // Compute the fused vector type for this operand
1518 Type *ArgType = I->getOperand(o)->getType();
1519 VectorType *VArgType = getVecTypeForPair(ArgType);
1521 Instruction *L = I, *H = J;
1522 if (FlipMemInputs) {
1527 if (ArgType->isVectorTy()) {
1528 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1529 std::vector<Constant*> Mask(numElem);
1530 for (unsigned v = 0; v < numElem; ++v)
1531 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1533 Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1535 ConstantVector::get(Mask),
1536 getReplacementName(I, true, o));
1537 BV->insertBefore(J);
1541 // If these two inputs are the output of another vector instruction,
1542 // then we should use that output directly. It might be necessary to
1543 // permute it first. [When pairings are fused recursively, you can
1544 // end up with cases where a large vector is decomposed into scalars
1545 // using extractelement instructions, then built into size-2
1546 // vectors using insertelement and the into larger vectors using
1547 // shuffles. InstCombine does not simplify all of these cases well,
1548 // and so we make sure that shuffles are generated here when possible.
1549 ExtractElementInst *LEE
1550 = dyn_cast<ExtractElementInst>(L->getOperand(o));
1551 ExtractElementInst *HEE
1552 = dyn_cast<ExtractElementInst>(H->getOperand(o));
1555 LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1556 VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1557 unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1558 unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1559 if (LEE->getOperand(0) == HEE->getOperand(0)) {
1560 if (LowIndx == 0 && HighIndx == 1)
1561 return LEE->getOperand(0);
1563 std::vector<Constant*> Mask(2);
1564 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1565 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1567 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1568 UndefValue::get(EEType),
1569 ConstantVector::get(Mask),
1570 getReplacementName(I, true, o));
1571 BV->insertBefore(J);
1575 std::vector<Constant*> Mask(2);
1576 HighIndx += EEType->getNumElements();
1577 Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1578 Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1580 Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1582 ConstantVector::get(Mask),
1583 getReplacementName(I, true, o));
1584 BV->insertBefore(J);
1588 Instruction *BV1 = InsertElementInst::Create(
1589 UndefValue::get(VArgType),
1590 L->getOperand(o), CV0,
1591 getReplacementName(I, true, o, 1));
1592 BV1->insertBefore(I);
1593 Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1595 getReplacementName(I, true, o, 2));
1596 BV2->insertBefore(J);
1600 // This function creates an array of values that will be used as the inputs
1601 // to the vector instruction that fuses I with J.
1602 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1603 Instruction *I, Instruction *J,
1604 SmallVector<Value *, 3> &ReplacedOperands,
1605 bool &FlipMemInputs) {
1606 FlipMemInputs = false;
1607 unsigned NumOperands = I->getNumOperands();
1609 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1610 // Iterate backward so that we look at the store pointer
1611 // first and know whether or not we need to flip the inputs.
1613 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1614 // This is the pointer for a load/store instruction.
1615 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1618 } else if (isa<CallInst>(I)) {
1619 Function *F = cast<CallInst>(I)->getCalledFunction();
1620 unsigned IID = F->getIntrinsicID();
1621 if (o == NumOperands-1) {
1622 BasicBlock &BB = *I->getParent();
1624 Module *M = BB.getParent()->getParent();
1625 Type *ArgType = I->getType();
1626 Type *VArgType = getVecTypeForPair(ArgType);
1628 // FIXME: is it safe to do this here?
1629 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1630 (Intrinsic::ID) IID, VArgType);
1632 } else if (IID == Intrinsic::powi && o == 1) {
1633 // The second argument of powi is a single integer and we've already
1634 // checked that both arguments are equal. As a result, we just keep
1635 // I's second argument.
1636 ReplacedOperands[o] = I->getOperand(o);
1639 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1640 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1644 ReplacedOperands[o] =
1645 getReplacementInput(Context, I, J, o, FlipMemInputs);
1649 // This function creates two values that represent the outputs of the
1650 // original I and J instructions. These are generally vector shuffles
1651 // or extracts. In many cases, these will end up being unused and, thus,
1652 // eliminated by later passes.
1653 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1654 Instruction *J, Instruction *K,
1655 Instruction *&InsertionPt,
1656 Instruction *&K1, Instruction *&K2,
1657 bool &FlipMemInputs) {
1658 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1659 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1661 if (isa<StoreInst>(I)) {
1662 AA->replaceWithNewValue(I, K);
1663 AA->replaceWithNewValue(J, K);
1665 Type *IType = I->getType();
1666 Type *VType = getVecTypeForPair(IType);
1668 if (IType->isVectorTy()) {
1669 unsigned numElem = cast<VectorType>(IType)->getNumElements();
1670 std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1671 for (unsigned v = 0; v < numElem; ++v) {
1672 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1673 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1676 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1677 ConstantVector::get(
1678 FlipMemInputs ? Mask2 : Mask1),
1679 getReplacementName(K, false, 1));
1680 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1681 ConstantVector::get(
1682 FlipMemInputs ? Mask1 : Mask2),
1683 getReplacementName(K, false, 2));
1685 K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1686 getReplacementName(K, false, 1));
1687 K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1688 getReplacementName(K, false, 2));
1692 K2->insertAfter(K1);
1697 // Move all uses of the function I (including pairing-induced uses) after J.
1698 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1699 std::multimap<Value *, Value *> &LoadMoveSet,
1700 Instruction *I, Instruction *J) {
1701 // Skip to the first instruction past I.
1702 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1704 DenseSet<Value *> Users;
1705 AliasSetTracker WriteSet(*AA);
1706 for (; cast<Instruction>(L) != J; ++L)
1707 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1709 assert(cast<Instruction>(L) == J &&
1710 "Tracking has not proceeded far enough to check for dependencies");
1711 // If J is now in the use set of I, then trackUsesOfI will return true
1712 // and we have a dependency cycle (and the fusing operation must abort).
1713 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1716 // Move all uses of the function I (including pairing-induced uses) after J.
1717 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1718 std::multimap<Value *, Value *> &LoadMoveSet,
1719 Instruction *&InsertionPt,
1720 Instruction *I, Instruction *J) {
1721 // Skip to the first instruction past I.
1722 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1724 DenseSet<Value *> Users;
1725 AliasSetTracker WriteSet(*AA);
1726 for (; cast<Instruction>(L) != J;) {
1727 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1728 // Move this instruction
1729 Instruction *InstToMove = L; ++L;
1731 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1732 " to after " << *InsertionPt << "\n");
1733 InstToMove->removeFromParent();
1734 InstToMove->insertAfter(InsertionPt);
1735 InsertionPt = InstToMove;
1742 // Collect all load instruction that are in the move set of a given first
1743 // pair member. These loads depend on the first instruction, I, and so need
1744 // to be moved after J (the second instruction) when the pair is fused.
1745 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1746 DenseMap<Value *, Value *> &ChosenPairs,
1747 std::multimap<Value *, Value *> &LoadMoveSet,
1749 // Skip to the first instruction past I.
1750 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1752 DenseSet<Value *> Users;
1753 AliasSetTracker WriteSet(*AA);
1755 // Note: We cannot end the loop when we reach J because J could be moved
1756 // farther down the use chain by another instruction pairing. Also, J
1757 // could be before I if this is an inverted input.
1758 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1759 if (trackUsesOfI(Users, WriteSet, I, L)) {
1760 if (L->mayReadFromMemory())
1761 LoadMoveSet.insert(ValuePair(L, I));
1766 // In cases where both load/stores and the computation of their pointers
1767 // are chosen for vectorization, we can end up in a situation where the
1768 // aliasing analysis starts returning different query results as the
1769 // process of fusing instruction pairs continues. Because the algorithm
1770 // relies on finding the same use trees here as were found earlier, we'll
1771 // need to precompute the necessary aliasing information here and then
1772 // manually update it during the fusion process.
1773 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1774 std::vector<Value *> &PairableInsts,
1775 DenseMap<Value *, Value *> &ChosenPairs,
1776 std::multimap<Value *, Value *> &LoadMoveSet) {
1777 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1778 PIE = PairableInsts.end(); PI != PIE; ++PI) {
1779 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1780 if (P == ChosenPairs.end()) continue;
1782 Instruction *I = cast<Instruction>(P->first);
1783 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1787 // This function fuses the chosen instruction pairs into vector instructions,
1788 // taking care preserve any needed scalar outputs and, then, it reorders the
1789 // remaining instructions as needed (users of the first member of the pair
1790 // need to be moved to after the location of the second member of the pair
1791 // because the vector instruction is inserted in the location of the pair's
1793 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1794 std::vector<Value *> &PairableInsts,
1795 DenseMap<Value *, Value *> &ChosenPairs) {
1796 LLVMContext& Context = BB.getContext();
1798 // During the vectorization process, the order of the pairs to be fused
1799 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1800 // list. After a pair is fused, the flipped pair is removed from the list.
1801 std::vector<ValuePair> FlippedPairs;
1802 FlippedPairs.reserve(ChosenPairs.size());
1803 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1804 E = ChosenPairs.end(); P != E; ++P)
1805 FlippedPairs.push_back(ValuePair(P->second, P->first));
1806 for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1807 E = FlippedPairs.end(); P != E; ++P)
1808 ChosenPairs.insert(*P);
1810 std::multimap<Value *, Value *> LoadMoveSet;
1811 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1813 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1815 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1816 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1817 if (P == ChosenPairs.end()) {
1822 if (getDepthFactor(P->first) == 0) {
1823 // These instructions are not really fused, but are tracked as though
1824 // they are. Any case in which it would be interesting to fuse them
1825 // will be taken care of by InstCombine.
1831 Instruction *I = cast<Instruction>(P->first),
1832 *J = cast<Instruction>(P->second);
1834 DEBUG(dbgs() << "BBV: fusing: " << *I <<
1835 " <-> " << *J << "\n");
1837 // Remove the pair and flipped pair from the list.
1838 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1839 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1840 ChosenPairs.erase(FP);
1841 ChosenPairs.erase(P);
1843 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1844 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1846 " aborted because of non-trivial dependency cycle\n");
1853 unsigned NumOperands = I->getNumOperands();
1854 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1855 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1858 // Make a copy of the original operation, change its type to the vector
1859 // type and replace its operands with the vector operands.
1860 Instruction *K = I->clone();
1861 if (I->hasName()) K->takeName(I);
1863 if (!isa<StoreInst>(K))
1864 K->mutateType(getVecTypeForPair(I->getType()));
1866 for (unsigned o = 0; o < NumOperands; ++o)
1867 K->setOperand(o, ReplacedOperands[o]);
1869 // If we've flipped the memory inputs, make sure that we take the correct
1871 if (FlipMemInputs) {
1872 if (isa<StoreInst>(K))
1873 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1875 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1880 // Instruction insertion point:
1881 Instruction *InsertionPt = K;
1882 Instruction *K1 = 0, *K2 = 0;
1883 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1886 // The use tree of the first original instruction must be moved to after
1887 // the location of the second instruction. The entire use tree of the
1888 // first instruction is disjoint from the input tree of the second
1889 // (by definition), and so commutes with it.
1891 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1893 if (!isa<StoreInst>(I)) {
1894 I->replaceAllUsesWith(K1);
1895 J->replaceAllUsesWith(K2);
1896 AA->replaceWithNewValue(I, K1);
1897 AA->replaceWithNewValue(J, K2);
1900 // Instructions that may read from memory may be in the load move set.
1901 // Once an instruction is fused, we no longer need its move set, and so
1902 // the values of the map never need to be updated. However, when a load
1903 // is fused, we need to merge the entries from both instructions in the
1904 // pair in case those instructions were in the move set of some other
1905 // yet-to-be-fused pair. The loads in question are the keys of the map.
1906 if (I->mayReadFromMemory()) {
1907 std::vector<ValuePair> NewSetMembers;
1908 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1909 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1910 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1911 N != IPairRange.second; ++N)
1912 NewSetMembers.push_back(ValuePair(K, N->second));
1913 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1914 N != JPairRange.second; ++N)
1915 NewSetMembers.push_back(ValuePair(K, N->second));
1916 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1917 AE = NewSetMembers.end(); A != AE; ++A)
1918 LoadMoveSet.insert(*A);
1921 // Before removing I, set the iterator to the next instruction.
1922 PI = llvm::next(BasicBlock::iterator(I));
1923 if (cast<Instruction>(PI) == J)
1928 I->eraseFromParent();
1929 J->eraseFromParent();
1932 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1936 char BBVectorize::ID = 0;
1937 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1938 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1939 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1940 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1941 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1943 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
1944 return new BBVectorize(C);
1948 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
1949 BBVectorize BBVectorizer(P, C);
1950 return BBVectorizer.vectorizeBB(BB);
1953 //===----------------------------------------------------------------------===//
1954 VectorizeConfig::VectorizeConfig() {
1955 VectorBits = ::VectorBits;
1956 VectorizeInts = !::NoInts;
1957 VectorizeFloats = !::NoFloats;
1958 VectorizePointers = !::NoPointers;
1959 VectorizeCasts = !::NoCasts;
1960 VectorizeMath = !::NoMath;
1961 VectorizeFMA = !::NoFMA;
1962 VectorizeSelect = !::NoSelect;
1963 VectorizeGEP = !::NoGEP;
1964 VectorizeMemOps = !::NoMemOps;
1965 AlignedOnly = ::AlignedOnly;
1966 ReqChainDepth= ::ReqChainDepth;
1967 SearchLimit = ::SearchLimit;
1968 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
1969 SplatBreaksChain = ::SplatBreaksChain;
1970 MaxInsts = ::MaxInsts;
1971 MaxIter = ::MaxIter;
1972 NoMemOpBoost = ::NoMemOpBoost;
1973 FastDep = ::FastDep;