1 //===--- Scalarizer.cpp - Scalarize vector operations ---------------------===//
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 pass converts vector operations into scalar operations, in order
11 // to expose optimization opportunities on the individual scalar operations.
12 // It is mainly intended for targets that do not have vector units, but it
13 // may also be useful for revectorizing code to different vector widths.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "scalarizer"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/InstVisitor.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 // Used to store the scattered form of a vector.
30 typedef SmallVector<Value *, 8> ValueVector;
32 // Used to map a vector Value to its scattered form. We use std::map
33 // because we want iterators to persist across insertion and because the
34 // values are relatively large.
35 typedef std::map<Value *, ValueVector> ScatterMap;
37 // Lists Instructions that have been replaced with scalar implementations,
38 // along with a pointer to their scattered forms.
39 typedef SmallVector<std::pair<Instruction *, ValueVector *>, 16> GatherList;
41 // Provides a very limited vector-like interface for lazily accessing one
42 // component of a scattered vector or vector pointer.
47 // Scatter V into Size components. If new instructions are needed,
48 // insert them before BBI in BB. If Cache is nonnull, use it to cache
50 Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
51 ValueVector *cachePtr = 0);
53 // Return component I, creating a new Value for it if necessary.
54 Value *operator[](unsigned I);
56 // Return the number of components.
57 unsigned size() const { return Size; }
61 BasicBlock::iterator BBI;
63 ValueVector *CachePtr;
69 // FCmpSpliiter(FCI)(Builder, X, Y, Name) uses Builder to create an FCmp
70 // called Name that compares X and Y in the same way as FCI.
72 FCmpSplitter(FCmpInst &fci) : FCI(fci) {}
73 Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
74 const Twine &Name) const {
75 return Builder.CreateFCmp(FCI.getPredicate(), Op0, Op1, Name);
80 // ICmpSpliiter(ICI)(Builder, X, Y, Name) uses Builder to create an ICmp
81 // called Name that compares X and Y in the same way as ICI.
83 ICmpSplitter(ICmpInst &ici) : ICI(ici) {}
84 Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
85 const Twine &Name) const {
86 return Builder.CreateICmp(ICI.getPredicate(), Op0, Op1, Name);
91 // BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
92 // a binary operator like BO called Name with operands X and Y.
93 struct BinarySplitter {
94 BinarySplitter(BinaryOperator &bo) : BO(bo) {}
95 Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
96 const Twine &Name) const {
97 return Builder.CreateBinOp(BO.getOpcode(), Op0, Op1, Name);
102 // Information about a load or store that we're scalarizing.
103 struct VectorLayout {
104 VectorLayout() : VecTy(0), ElemTy(0), VecAlign(0), ElemSize(0) {}
106 // Return the alignment of element I.
107 uint64_t getElemAlign(unsigned I) {
108 return MinAlign(VecAlign, I * ElemSize);
111 // The type of the vector.
114 // The type of each element.
117 // The alignment of the vector.
120 // The size of each element.
124 class Scalarizer : public FunctionPass,
125 public InstVisitor<Scalarizer, bool> {
131 initializeScalarizerPass(*PassRegistry::getPassRegistry());
134 virtual bool doInitialization(Module &M);
135 virtual bool runOnFunction(Function &F);
137 // InstVisitor methods. They return true if the instruction was scalarized,
138 // false if nothing changed.
139 bool visitInstruction(Instruction &) { return false; }
140 bool visitSelectInst(SelectInst &SI);
141 bool visitICmpInst(ICmpInst &);
142 bool visitFCmpInst(FCmpInst &);
143 bool visitBinaryOperator(BinaryOperator &);
144 bool visitGetElementPtrInst(GetElementPtrInst &);
145 bool visitCastInst(CastInst &);
146 bool visitBitCastInst(BitCastInst &);
147 bool visitShuffleVectorInst(ShuffleVectorInst &);
148 bool visitPHINode(PHINode &);
149 bool visitLoadInst(LoadInst &);
150 bool visitStoreInst(StoreInst &);
153 Scatterer scatter(Instruction *, Value *);
154 void gather(Instruction *, const ValueVector &);
155 bool canTransferMetadata(unsigned Kind);
156 void transferMetadata(Instruction *, const ValueVector &);
157 bool getVectorLayout(Type *, unsigned, VectorLayout &);
160 template<typename T> bool splitBinary(Instruction &, const T &);
162 ScatterMap Scattered;
164 unsigned ParallelLoopAccessMDKind;
165 const DataLayout *DL;
168 char Scalarizer::ID = 0;
169 } // end anonymous namespace
171 // This is disabled by default because having separate loads and stores makes
172 // it more likely that the -combiner-alias-analysis limits will be reached.
173 static cl::opt<bool> ScalarizeLoadStore
174 ("scalarize-load-store", cl::Hidden, cl::init(false),
175 cl::desc("Allow the scalarizer pass to scalarize loads and store"));
177 INITIALIZE_PASS(Scalarizer, "scalarizer", "Scalarize vector operations",
180 Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
181 ValueVector *cachePtr)
182 : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
183 Type *Ty = V->getType();
184 PtrTy = dyn_cast<PointerType>(Ty);
186 Ty = PtrTy->getElementType();
187 Size = Ty->getVectorNumElements();
190 else if (CachePtr->empty())
191 CachePtr->resize(Size, 0);
193 assert(Size == CachePtr->size() && "Inconsistent vector sizes");
196 // Return component I, creating a new Value for it if necessary.
197 Value *Scatterer::operator[](unsigned I) {
198 ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
199 // Try to reuse a previous value.
202 IRBuilder<> Builder(BB, BBI);
206 PointerType::get(PtrTy->getElementType()->getVectorElementType(),
207 PtrTy->getAddressSpace());
208 CV[0] = Builder.CreateBitCast(V, Ty, V->getName() + ".i0");
211 CV[I] = Builder.CreateConstGEP1_32(CV[0], I,
212 V->getName() + ".i" + Twine(I));
214 // Search through a chain of InsertElementInsts looking for element I.
215 // Record other elements in the cache. The new V is still suitable
216 // for all uncached indices.
218 InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
221 ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
224 unsigned J = Idx->getZExtValue();
225 CV[J] = Insert->getOperand(1);
226 V = Insert->getOperand(0);
230 CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
231 V->getName() + ".i" + Twine(I));
236 bool Scalarizer::doInitialization(Module &M) {
237 ParallelLoopAccessMDKind =
238 M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
242 bool Scalarizer::runOnFunction(Function &F) {
243 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
244 DL = DLP ? &DLP->getDataLayout() : 0;
245 for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
246 BasicBlock *BB = BBI;
247 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
249 bool Done = visit(I);
251 if (Done && I->getType()->isVoidTy())
252 I->eraseFromParent();
258 // Return a scattered form of V that can be accessed by Point. V must be a
259 // vector or a pointer to a vector.
260 Scatterer Scalarizer::scatter(Instruction *Point, Value *V) {
261 if (Argument *VArg = dyn_cast<Argument>(V)) {
262 // Put the scattered form of arguments in the entry block,
263 // so that it can be used everywhere.
264 Function *F = VArg->getParent();
265 BasicBlock *BB = &F->getEntryBlock();
266 return Scatterer(BB, BB->begin(), V, &Scattered[V]);
268 if (Instruction *VOp = dyn_cast<Instruction>(V)) {
269 // Put the scattered form of an instruction directly after the
271 BasicBlock *BB = VOp->getParent();
272 return Scatterer(BB, std::next(BasicBlock::iterator(VOp)),
275 // In the fallback case, just put the scattered before Point and
276 // keep the result local to Point.
277 return Scatterer(Point->getParent(), Point, V);
280 // Replace Op with the gathered form of the components in CV. Defer the
281 // deletion of Op and creation of the gathered form to the end of the pass,
282 // so that we can avoid creating the gathered form if all uses of Op are
283 // replaced with uses of CV.
284 void Scalarizer::gather(Instruction *Op, const ValueVector &CV) {
285 // Since we're not deleting Op yet, stub out its operands, so that it
286 // doesn't make anything live unnecessarily.
287 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
288 Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
290 transferMetadata(Op, CV);
292 // If we already have a scattered form of Op (created from ExtractElements
293 // of Op itself), replace them with the new form.
294 ValueVector &SV = Scattered[Op];
296 for (unsigned I = 0, E = SV.size(); I != E; ++I) {
297 Instruction *Old = cast<Instruction>(SV[I]);
298 CV[I]->takeName(Old);
299 Old->replaceAllUsesWith(CV[I]);
300 Old->eraseFromParent();
304 Gathered.push_back(GatherList::value_type(Op, &SV));
307 // Return true if it is safe to transfer the given metadata tag from
308 // vector to scalar instructions.
309 bool Scalarizer::canTransferMetadata(unsigned Tag) {
310 return (Tag == LLVMContext::MD_tbaa
311 || Tag == LLVMContext::MD_fpmath
312 || Tag == LLVMContext::MD_tbaa_struct
313 || Tag == LLVMContext::MD_invariant_load
314 || Tag == ParallelLoopAccessMDKind);
317 // Transfer metadata from Op to the instructions in CV if it is known
318 // to be safe to do so.
319 void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
320 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
321 Op->getAllMetadataOtherThanDebugLoc(MDs);
322 for (unsigned I = 0, E = CV.size(); I != E; ++I) {
323 if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
324 for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator
325 MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI)
326 if (canTransferMetadata(MI->first))
327 New->setMetadata(MI->first, MI->second);
328 New->setDebugLoc(Op->getDebugLoc());
333 // Try to fill in Layout from Ty, returning true on success. Alignment is
334 // the alignment of the vector, or 0 if the ABI default should be used.
335 bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
336 VectorLayout &Layout) {
340 // Make sure we're dealing with a vector.
341 Layout.VecTy = dyn_cast<VectorType>(Ty);
345 // Check that we're dealing with full-byte elements.
346 Layout.ElemTy = Layout.VecTy->getElementType();
347 if (DL->getTypeSizeInBits(Layout.ElemTy) !=
348 DL->getTypeStoreSizeInBits(Layout.ElemTy))
352 Layout.VecAlign = Alignment;
354 Layout.VecAlign = DL->getABITypeAlignment(Layout.VecTy);
355 Layout.ElemSize = DL->getTypeStoreSize(Layout.ElemTy);
359 // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
360 // to create an instruction like I with operands X and Y and name Name.
361 template<typename Splitter>
362 bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
363 VectorType *VT = dyn_cast<VectorType>(I.getType());
367 unsigned NumElems = VT->getNumElements();
368 IRBuilder<> Builder(I.getParent(), &I);
369 Scatterer Op0 = scatter(&I, I.getOperand(0));
370 Scatterer Op1 = scatter(&I, I.getOperand(1));
371 assert(Op0.size() == NumElems && "Mismatched binary operation");
372 assert(Op1.size() == NumElems && "Mismatched binary operation");
374 Res.resize(NumElems);
375 for (unsigned Elem = 0; Elem < NumElems; ++Elem)
376 Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
377 I.getName() + ".i" + Twine(Elem));
382 bool Scalarizer::visitSelectInst(SelectInst &SI) {
383 VectorType *VT = dyn_cast<VectorType>(SI.getType());
387 unsigned NumElems = VT->getNumElements();
388 IRBuilder<> Builder(SI.getParent(), &SI);
389 Scatterer Op1 = scatter(&SI, SI.getOperand(1));
390 Scatterer Op2 = scatter(&SI, SI.getOperand(2));
391 assert(Op1.size() == NumElems && "Mismatched select");
392 assert(Op2.size() == NumElems && "Mismatched select");
394 Res.resize(NumElems);
396 if (SI.getOperand(0)->getType()->isVectorTy()) {
397 Scatterer Op0 = scatter(&SI, SI.getOperand(0));
398 assert(Op0.size() == NumElems && "Mismatched select");
399 for (unsigned I = 0; I < NumElems; ++I)
400 Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
401 SI.getName() + ".i" + Twine(I));
403 Value *Op0 = SI.getOperand(0);
404 for (unsigned I = 0; I < NumElems; ++I)
405 Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
406 SI.getName() + ".i" + Twine(I));
412 bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
413 return splitBinary(ICI, ICmpSplitter(ICI));
416 bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
417 return splitBinary(FCI, FCmpSplitter(FCI));
420 bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
421 return splitBinary(BO, BinarySplitter(BO));
424 bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
425 VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
429 IRBuilder<> Builder(GEPI.getParent(), &GEPI);
430 unsigned NumElems = VT->getNumElements();
431 unsigned NumIndices = GEPI.getNumIndices();
433 Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
435 SmallVector<Scatterer, 8> Ops;
436 Ops.resize(NumIndices);
437 for (unsigned I = 0; I < NumIndices; ++I)
438 Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
441 Res.resize(NumElems);
442 for (unsigned I = 0; I < NumElems; ++I) {
443 SmallVector<Value *, 8> Indices;
444 Indices.resize(NumIndices);
445 for (unsigned J = 0; J < NumIndices; ++J)
446 Indices[J] = Ops[J][I];
447 Res[I] = Builder.CreateGEP(Base[I], Indices,
448 GEPI.getName() + ".i" + Twine(I));
449 if (GEPI.isInBounds())
450 if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
451 NewGEPI->setIsInBounds();
457 bool Scalarizer::visitCastInst(CastInst &CI) {
458 VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
462 unsigned NumElems = VT->getNumElements();
463 IRBuilder<> Builder(CI.getParent(), &CI);
464 Scatterer Op0 = scatter(&CI, CI.getOperand(0));
465 assert(Op0.size() == NumElems && "Mismatched cast");
467 Res.resize(NumElems);
468 for (unsigned I = 0; I < NumElems; ++I)
469 Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
470 CI.getName() + ".i" + Twine(I));
475 bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
476 VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
477 VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
478 if (!DstVT || !SrcVT)
481 unsigned DstNumElems = DstVT->getNumElements();
482 unsigned SrcNumElems = SrcVT->getNumElements();
483 IRBuilder<> Builder(BCI.getParent(), &BCI);
484 Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
486 Res.resize(DstNumElems);
488 if (DstNumElems == SrcNumElems) {
489 for (unsigned I = 0; I < DstNumElems; ++I)
490 Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
491 BCI.getName() + ".i" + Twine(I));
492 } else if (DstNumElems > SrcNumElems) {
493 // <M x t1> -> <N*M x t2>. Convert each t1 to <N x t2> and copy the
494 // individual elements to the destination.
495 unsigned FanOut = DstNumElems / SrcNumElems;
496 Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
498 for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
499 Value *V = Op0[Op0I];
501 // Look through any existing bitcasts before converting to <N x t2>.
502 // In the best case, the resulting conversion might be a no-op.
503 while ((VI = dyn_cast<Instruction>(V)) &&
504 VI->getOpcode() == Instruction::BitCast)
505 V = VI->getOperand(0);
506 V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
507 Scatterer Mid = scatter(&BCI, V);
508 for (unsigned MidI = 0; MidI < FanOut; ++MidI)
509 Res[ResI++] = Mid[MidI];
512 // <N*M x t1> -> <M x t2>. Convert each group of <N x t1> into a t2.
513 unsigned FanIn = SrcNumElems / DstNumElems;
514 Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
516 for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
517 Value *V = UndefValue::get(MidTy);
518 for (unsigned MidI = 0; MidI < FanIn; ++MidI)
519 V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
520 BCI.getName() + ".i" + Twine(ResI)
521 + ".upto" + Twine(MidI));
522 Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
523 BCI.getName() + ".i" + Twine(ResI));
530 bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
531 VectorType *VT = dyn_cast<VectorType>(SVI.getType());
535 unsigned NumElems = VT->getNumElements();
536 Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
537 Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
539 Res.resize(NumElems);
541 for (unsigned I = 0; I < NumElems; ++I) {
542 int Selector = SVI.getMaskValue(I);
544 Res[I] = UndefValue::get(VT->getElementType());
545 else if (unsigned(Selector) < Op0.size())
546 Res[I] = Op0[Selector];
548 Res[I] = Op1[Selector - Op0.size()];
554 bool Scalarizer::visitPHINode(PHINode &PHI) {
555 VectorType *VT = dyn_cast<VectorType>(PHI.getType());
559 unsigned NumElems = VT->getNumElements();
560 IRBuilder<> Builder(PHI.getParent(), &PHI);
562 Res.resize(NumElems);
564 unsigned NumOps = PHI.getNumOperands();
565 for (unsigned I = 0; I < NumElems; ++I)
566 Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
567 PHI.getName() + ".i" + Twine(I));
569 for (unsigned I = 0; I < NumOps; ++I) {
570 Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
571 BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
572 for (unsigned J = 0; J < NumElems; ++J)
573 cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
579 bool Scalarizer::visitLoadInst(LoadInst &LI) {
580 if (!ScalarizeLoadStore)
586 if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout))
589 unsigned NumElems = Layout.VecTy->getNumElements();
590 IRBuilder<> Builder(LI.getParent(), &LI);
591 Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
593 Res.resize(NumElems);
595 for (unsigned I = 0; I < NumElems; ++I)
596 Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
597 LI.getName() + ".i" + Twine(I));
602 bool Scalarizer::visitStoreInst(StoreInst &SI) {
603 if (!ScalarizeLoadStore)
609 Value *FullValue = SI.getValueOperand();
610 if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout))
613 unsigned NumElems = Layout.VecTy->getNumElements();
614 IRBuilder<> Builder(SI.getParent(), &SI);
615 Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
616 Scatterer Val = scatter(&SI, FullValue);
619 Stores.resize(NumElems);
620 for (unsigned I = 0; I < NumElems; ++I) {
621 unsigned Align = Layout.getElemAlign(I);
622 Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
624 transferMetadata(&SI, Stores);
628 // Delete the instructions that we scalarized. If a full vector result
629 // is still needed, recreate it using InsertElements.
630 bool Scalarizer::finish() {
631 if (Gathered.empty())
633 for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
635 Instruction *Op = GMI->first;
636 ValueVector &CV = *GMI->second;
637 if (!Op->use_empty()) {
638 // The value is still needed, so recreate it using a series of
640 Type *Ty = Op->getType();
641 Value *Res = UndefValue::get(Ty);
642 BasicBlock *BB = Op->getParent();
643 unsigned Count = Ty->getVectorNumElements();
644 IRBuilder<> Builder(BB, Op);
645 if (isa<PHINode>(Op))
646 Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
647 for (unsigned I = 0; I < Count; ++I)
648 Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
649 Op->getName() + ".upto" + Twine(I));
651 Op->replaceAllUsesWith(Res);
653 Op->eraseFromParent();
660 FunctionPass *llvm::createScalarizerPass() {
661 return new Scalarizer();