blob: 5e6df0ddf6d77f6651259d3e398ae943306f5643 [file] [log] [blame]
Richard Sandiford8ee1b772013-11-22 16:58:05 +00001//===--- Scalarizer.cpp - Scalarize vector operations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
14//
15//===----------------------------------------------------------------------===//
16
Mehdi Aminib550cb12016-04-18 09:17:29 +000017#include "llvm/Transforms/Scalar.h"
Richard Sandiford8ee1b772013-11-22 16:58:05 +000018#include "llvm/ADT/STLExtras.h"
19#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000020#include "llvm/IR/InstVisitor.h"
Richard Sandiford8ee1b772013-11-22 16:58:05 +000021#include "llvm/Pass.h"
Richard Sandiford8ee1b772013-11-22 16:58:05 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23
24using namespace llvm;
25
Chandler Carruth964daaa2014-04-22 02:55:47 +000026#define DEBUG_TYPE "scalarizer"
27
Richard Sandiford8ee1b772013-11-22 16:58:05 +000028namespace {
29// Used to store the scattered form of a vector.
30typedef SmallVector<Value *, 8> ValueVector;
31
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.
35typedef std::map<Value *, ValueVector> ScatterMap;
36
37// Lists Instructions that have been replaced with scalar implementations,
38// along with a pointer to their scattered forms.
39typedef SmallVector<std::pair<Instruction *, ValueVector *>, 16> GatherList;
40
41// Provides a very limited vector-like interface for lazily accessing one
42// component of a scattered vector or vector pointer.
43class Scatterer {
44public:
Richard Sandiford3548cbb2013-12-23 14:45:00 +000045 Scatterer() {}
46
Richard Sandiford8ee1b772013-11-22 16:58:05 +000047 // 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
49 // the results.
50 Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
Craig Topperf40110f2014-04-25 05:29:35 +000051 ValueVector *cachePtr = nullptr);
Richard Sandiford8ee1b772013-11-22 16:58:05 +000052
53 // Return component I, creating a new Value for it if necessary.
54 Value *operator[](unsigned I);
55
56 // Return the number of components.
57 unsigned size() const { return Size; }
58
59private:
60 BasicBlock *BB;
61 BasicBlock::iterator BBI;
62 Value *V;
63 ValueVector *CachePtr;
64 PointerType *PtrTy;
65 ValueVector Tmp;
66 unsigned Size;
67};
68
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.
71struct FCmpSplitter {
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);
76 }
77 FCmpInst &FCI;
78};
79
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.
82struct ICmpSplitter {
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);
87 }
88 ICmpInst &ICI;
89};
90
91// BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
92// a binary operator like BO called Name with operands X and Y.
93struct 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);
98 }
99 BinaryOperator &BO;
100};
101
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000102// Information about a load or store that we're scalarizing.
103struct VectorLayout {
Craig Topperf40110f2014-04-25 05:29:35 +0000104 VectorLayout() : VecTy(nullptr), ElemTy(nullptr), VecAlign(0), ElemSize(0) {}
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000105
106 // Return the alignment of element I.
107 uint64_t getElemAlign(unsigned I) {
108 return MinAlign(VecAlign, I * ElemSize);
109 }
110
111 // The type of the vector.
112 VectorType *VecTy;
113
114 // The type of each element.
115 Type *ElemTy;
116
117 // The alignment of the vector.
118 uint64_t VecAlign;
119
120 // The size of each element.
121 uint64_t ElemSize;
122};
123
124class Scalarizer : public FunctionPass,
125 public InstVisitor<Scalarizer, bool> {
126public:
127 static char ID;
128
129 Scalarizer() :
130 FunctionPass(ID) {
131 initializeScalarizerPass(*PassRegistry::getPassRegistry());
132 }
133
Craig Topper3e4c6972014-03-05 09:10:37 +0000134 bool doInitialization(Module &M) override;
135 bool runOnFunction(Function &F) override;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000136
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 &);
151
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000152 static void registerOptions() {
153 // This is disabled by default because having separate loads and stores
154 // makes it more likely that the -combiner-alias-analysis limits will be
155 // reached.
156 OptionRegistry::registerOption<bool, Scalarizer,
157 &Scalarizer::ScalarizeLoadStore>(
158 "scalarize-load-store",
159 "Allow the scalarizer pass to scalarize loads and store", false);
160 }
161
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000162private:
163 Scatterer scatter(Instruction *, Value *);
164 void gather(Instruction *, const ValueVector &);
165 bool canTransferMetadata(unsigned Kind);
166 void transferMetadata(Instruction *, const ValueVector &);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000167 bool getVectorLayout(Type *, unsigned, VectorLayout &, const DataLayout &);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000168 bool finish();
169
170 template<typename T> bool splitBinary(Instruction &, const T &);
171
172 ScatterMap Scattered;
173 GatherList Gathered;
174 unsigned ParallelLoopAccessMDKind;
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000175 bool ScalarizeLoadStore;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000176};
177
178char Scalarizer::ID = 0;
179} // end anonymous namespace
180
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000181INITIALIZE_PASS_WITH_OPTIONS(Scalarizer, "scalarizer",
Chris Bieneman5c4e9552014-10-15 23:11:35 +0000182 "Scalarize vector operations", false, false)
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000183
184Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
185 ValueVector *cachePtr)
186 : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
187 Type *Ty = V->getType();
188 PtrTy = dyn_cast<PointerType>(Ty);
189 if (PtrTy)
190 Ty = PtrTy->getElementType();
191 Size = Ty->getVectorNumElements();
192 if (!CachePtr)
Craig Topperf40110f2014-04-25 05:29:35 +0000193 Tmp.resize(Size, nullptr);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000194 else if (CachePtr->empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000195 CachePtr->resize(Size, nullptr);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000196 else
197 assert(Size == CachePtr->size() && "Inconsistent vector sizes");
198}
199
200// Return component I, creating a new Value for it if necessary.
201Value *Scatterer::operator[](unsigned I) {
202 ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
203 // Try to reuse a previous value.
204 if (CV[I])
205 return CV[I];
206 IRBuilder<> Builder(BB, BBI);
207 if (PtrTy) {
208 if (!CV[0]) {
209 Type *Ty =
210 PointerType::get(PtrTy->getElementType()->getVectorElementType(),
211 PtrTy->getAddressSpace());
212 CV[0] = Builder.CreateBitCast(V, Ty, V->getName() + ".i0");
213 }
214 if (I != 0)
David Blaikie95d3e532015-04-03 23:03:54 +0000215 CV[I] = Builder.CreateConstGEP1_32(nullptr, CV[0], I,
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000216 V->getName() + ".i" + Twine(I));
217 } else {
218 // Search through a chain of InsertElementInsts looking for element I.
219 // Record other elements in the cache. The new V is still suitable
220 // for all uncached indices.
221 for (;;) {
222 InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
223 if (!Insert)
224 break;
225 ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
226 if (!Idx)
227 break;
228 unsigned J = Idx->getZExtValue();
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000229 V = Insert->getOperand(0);
Fraser Cormacke29ab2b2015-08-10 14:48:47 +0000230 if (I == J) {
231 CV[J] = Insert->getOperand(1);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000232 return CV[J];
Fraser Cormacke29ab2b2015-08-10 14:48:47 +0000233 } else if (!CV[J]) {
234 // Only cache the first entry we find for each index we're not actively
235 // searching for. This prevents us from going too far up the chain and
236 // caching incorrect entries.
237 CV[J] = Insert->getOperand(1);
238 }
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000239 }
240 CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
241 V->getName() + ".i" + Twine(I));
242 }
243 return CV[I];
244}
245
246bool Scalarizer::doInitialization(Module &M) {
247 ParallelLoopAccessMDKind =
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000248 M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
249 ScalarizeLoadStore =
Chris Bieneman5c4e9552014-10-15 23:11:35 +0000250 M.getContext().getOption<bool, Scalarizer, &Scalarizer::ScalarizeLoadStore>();
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000251 return false;
252}
253
254bool Scalarizer::runOnFunction(Function &F) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000255 if (skipFunction(F))
256 return false;
Matt Wala878c1442015-07-23 20:53:46 +0000257 assert(Gathered.empty() && Scattered.empty());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000258 for (BasicBlock &BB : F) {
259 for (BasicBlock::iterator II = BB.begin(), IE = BB.end(); II != IE;) {
260 Instruction *I = &*II;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000261 bool Done = visit(I);
262 ++II;
263 if (Done && I->getType()->isVoidTy())
264 I->eraseFromParent();
265 }
266 }
267 return finish();
268}
269
270// Return a scattered form of V that can be accessed by Point. V must be a
271// vector or a pointer to a vector.
272Scatterer Scalarizer::scatter(Instruction *Point, Value *V) {
273 if (Argument *VArg = dyn_cast<Argument>(V)) {
274 // Put the scattered form of arguments in the entry block,
275 // so that it can be used everywhere.
276 Function *F = VArg->getParent();
277 BasicBlock *BB = &F->getEntryBlock();
278 return Scatterer(BB, BB->begin(), V, &Scattered[V]);
279 }
280 if (Instruction *VOp = dyn_cast<Instruction>(V)) {
281 // Put the scattered form of an instruction directly after the
282 // instruction.
283 BasicBlock *BB = VOp->getParent();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000284 return Scatterer(BB, std::next(BasicBlock::iterator(VOp)),
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000285 V, &Scattered[V]);
286 }
287 // In the fallback case, just put the scattered before Point and
288 // keep the result local to Point.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000289 return Scatterer(Point->getParent(), Point->getIterator(), V);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000290}
291
292// Replace Op with the gathered form of the components in CV. Defer the
293// deletion of Op and creation of the gathered form to the end of the pass,
294// so that we can avoid creating the gathered form if all uses of Op are
295// replaced with uses of CV.
296void Scalarizer::gather(Instruction *Op, const ValueVector &CV) {
297 // Since we're not deleting Op yet, stub out its operands, so that it
298 // doesn't make anything live unnecessarily.
299 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
300 Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
301
302 transferMetadata(Op, CV);
303
304 // If we already have a scattered form of Op (created from ExtractElements
305 // of Op itself), replace them with the new form.
306 ValueVector &SV = Scattered[Op];
307 if (!SV.empty()) {
308 for (unsigned I = 0, E = SV.size(); I != E; ++I) {
309 Instruction *Old = cast<Instruction>(SV[I]);
310 CV[I]->takeName(Old);
311 Old->replaceAllUsesWith(CV[I]);
312 Old->eraseFromParent();
313 }
314 }
315 SV = CV;
316 Gathered.push_back(GatherList::value_type(Op, &SV));
317}
318
319// Return true if it is safe to transfer the given metadata tag from
320// vector to scalar instructions.
321bool Scalarizer::canTransferMetadata(unsigned Tag) {
322 return (Tag == LLVMContext::MD_tbaa
323 || Tag == LLVMContext::MD_fpmath
324 || Tag == LLVMContext::MD_tbaa_struct
325 || Tag == LLVMContext::MD_invariant_load
Hal Finkel94146652014-07-24 14:25:39 +0000326 || Tag == LLVMContext::MD_alias_scope
327 || Tag == LLVMContext::MD_noalias
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000328 || Tag == ParallelLoopAccessMDKind);
329}
330
331// Transfer metadata from Op to the instructions in CV if it is known
332// to be safe to do so.
333void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000334 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000335 Op->getAllMetadataOtherThanDebugLoc(MDs);
336 for (unsigned I = 0, E = CV.size(); I != E; ++I) {
337 if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000338 for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
339 MI = MDs.begin(),
340 ME = MDs.end();
341 MI != ME; ++MI)
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000342 if (canTransferMetadata(MI->first))
343 New->setMetadata(MI->first, MI->second);
Patrik Hagglund0acaefa2016-06-16 10:48:54 +0000344 if (Op->getDebugLoc() && !New->getDebugLoc())
345 New->setDebugLoc(Op->getDebugLoc());
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000346 }
347 }
348}
349
350// Try to fill in Layout from Ty, returning true on success. Alignment is
351// the alignment of the vector, or 0 if the ABI default should be used.
352bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 VectorLayout &Layout, const DataLayout &DL) {
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000354 // Make sure we're dealing with a vector.
355 Layout.VecTy = dyn_cast<VectorType>(Ty);
356 if (!Layout.VecTy)
357 return false;
358
359 // Check that we're dealing with full-byte elements.
360 Layout.ElemTy = Layout.VecTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000361 if (DL.getTypeSizeInBits(Layout.ElemTy) !=
362 DL.getTypeStoreSizeInBits(Layout.ElemTy))
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000363 return false;
364
365 if (Alignment)
366 Layout.VecAlign = Alignment;
367 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 Layout.VecAlign = DL.getABITypeAlignment(Layout.VecTy);
369 Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000370 return true;
371}
372
373// Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
374// to create an instruction like I with operands X and Y and name Name.
375template<typename Splitter>
376bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
377 VectorType *VT = dyn_cast<VectorType>(I.getType());
378 if (!VT)
379 return false;
380
381 unsigned NumElems = VT->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000382 IRBuilder<> Builder(&I);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000383 Scatterer Op0 = scatter(&I, I.getOperand(0));
384 Scatterer Op1 = scatter(&I, I.getOperand(1));
385 assert(Op0.size() == NumElems && "Mismatched binary operation");
386 assert(Op1.size() == NumElems && "Mismatched binary operation");
387 ValueVector Res;
388 Res.resize(NumElems);
389 for (unsigned Elem = 0; Elem < NumElems; ++Elem)
390 Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
391 I.getName() + ".i" + Twine(Elem));
392 gather(&I, Res);
393 return true;
394}
395
396bool Scalarizer::visitSelectInst(SelectInst &SI) {
397 VectorType *VT = dyn_cast<VectorType>(SI.getType());
398 if (!VT)
399 return false;
400
401 unsigned NumElems = VT->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000402 IRBuilder<> Builder(&SI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000403 Scatterer Op1 = scatter(&SI, SI.getOperand(1));
404 Scatterer Op2 = scatter(&SI, SI.getOperand(2));
405 assert(Op1.size() == NumElems && "Mismatched select");
406 assert(Op2.size() == NumElems && "Mismatched select");
407 ValueVector Res;
408 Res.resize(NumElems);
409
410 if (SI.getOperand(0)->getType()->isVectorTy()) {
411 Scatterer Op0 = scatter(&SI, SI.getOperand(0));
412 assert(Op0.size() == NumElems && "Mismatched select");
413 for (unsigned I = 0; I < NumElems; ++I)
414 Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
415 SI.getName() + ".i" + Twine(I));
416 } else {
417 Value *Op0 = SI.getOperand(0);
418 for (unsigned I = 0; I < NumElems; ++I)
419 Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
420 SI.getName() + ".i" + Twine(I));
421 }
422 gather(&SI, Res);
423 return true;
424}
425
426bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
427 return splitBinary(ICI, ICmpSplitter(ICI));
428}
429
430bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
431 return splitBinary(FCI, FCmpSplitter(FCI));
432}
433
434bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
435 return splitBinary(BO, BinarySplitter(BO));
436}
437
438bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Richard Sandiford3548cbb2013-12-23 14:45:00 +0000439 VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
440 if (!VT)
441 return false;
442
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000443 IRBuilder<> Builder(&GEPI);
Richard Sandiford3548cbb2013-12-23 14:45:00 +0000444 unsigned NumElems = VT->getNumElements();
445 unsigned NumIndices = GEPI.getNumIndices();
446
447 Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
448
449 SmallVector<Scatterer, 8> Ops;
450 Ops.resize(NumIndices);
451 for (unsigned I = 0; I < NumIndices; ++I)
452 Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
453
454 ValueVector Res;
455 Res.resize(NumElems);
456 for (unsigned I = 0; I < NumElems; ++I) {
457 SmallVector<Value *, 8> Indices;
458 Indices.resize(NumIndices);
459 for (unsigned J = 0; J < NumIndices; ++J)
460 Indices[J] = Ops[J][I];
David Blaikie68d535c2015-03-24 22:38:16 +0000461 Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
Richard Sandiford3548cbb2013-12-23 14:45:00 +0000462 GEPI.getName() + ".i" + Twine(I));
463 if (GEPI.isInBounds())
464 if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
465 NewGEPI->setIsInBounds();
466 }
467 gather(&GEPI, Res);
468 return true;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000469}
470
471bool Scalarizer::visitCastInst(CastInst &CI) {
472 VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
473 if (!VT)
474 return false;
475
476 unsigned NumElems = VT->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000477 IRBuilder<> Builder(&CI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000478 Scatterer Op0 = scatter(&CI, CI.getOperand(0));
479 assert(Op0.size() == NumElems && "Mismatched cast");
480 ValueVector Res;
481 Res.resize(NumElems);
482 for (unsigned I = 0; I < NumElems; ++I)
483 Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
484 CI.getName() + ".i" + Twine(I));
485 gather(&CI, Res);
486 return true;
487}
488
489bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
490 VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
491 VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
492 if (!DstVT || !SrcVT)
493 return false;
494
495 unsigned DstNumElems = DstVT->getNumElements();
496 unsigned SrcNumElems = SrcVT->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000497 IRBuilder<> Builder(&BCI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000498 Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
499 ValueVector Res;
500 Res.resize(DstNumElems);
501
502 if (DstNumElems == SrcNumElems) {
503 for (unsigned I = 0; I < DstNumElems; ++I)
504 Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
505 BCI.getName() + ".i" + Twine(I));
506 } else if (DstNumElems > SrcNumElems) {
507 // <M x t1> -> <N*M x t2>. Convert each t1 to <N x t2> and copy the
508 // individual elements to the destination.
509 unsigned FanOut = DstNumElems / SrcNumElems;
510 Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
511 unsigned ResI = 0;
512 for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
513 Value *V = Op0[Op0I];
514 Instruction *VI;
515 // Look through any existing bitcasts before converting to <N x t2>.
516 // In the best case, the resulting conversion might be a no-op.
517 while ((VI = dyn_cast<Instruction>(V)) &&
518 VI->getOpcode() == Instruction::BitCast)
519 V = VI->getOperand(0);
520 V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
521 Scatterer Mid = scatter(&BCI, V);
522 for (unsigned MidI = 0; MidI < FanOut; ++MidI)
523 Res[ResI++] = Mid[MidI];
524 }
525 } else {
526 // <N*M x t1> -> <M x t2>. Convert each group of <N x t1> into a t2.
527 unsigned FanIn = SrcNumElems / DstNumElems;
528 Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
529 unsigned Op0I = 0;
530 for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
531 Value *V = UndefValue::get(MidTy);
532 for (unsigned MidI = 0; MidI < FanIn; ++MidI)
533 V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
534 BCI.getName() + ".i" + Twine(ResI)
535 + ".upto" + Twine(MidI));
536 Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
537 BCI.getName() + ".i" + Twine(ResI));
538 }
539 }
540 gather(&BCI, Res);
541 return true;
542}
543
544bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
545 VectorType *VT = dyn_cast<VectorType>(SVI.getType());
546 if (!VT)
547 return false;
548
549 unsigned NumElems = VT->getNumElements();
550 Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
551 Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
552 ValueVector Res;
553 Res.resize(NumElems);
554
555 for (unsigned I = 0; I < NumElems; ++I) {
556 int Selector = SVI.getMaskValue(I);
557 if (Selector < 0)
558 Res[I] = UndefValue::get(VT->getElementType());
559 else if (unsigned(Selector) < Op0.size())
560 Res[I] = Op0[Selector];
561 else
562 Res[I] = Op1[Selector - Op0.size()];
563 }
564 gather(&SVI, Res);
565 return true;
566}
567
568bool Scalarizer::visitPHINode(PHINode &PHI) {
569 VectorType *VT = dyn_cast<VectorType>(PHI.getType());
570 if (!VT)
571 return false;
572
573 unsigned NumElems = VT->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000574 IRBuilder<> Builder(&PHI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000575 ValueVector Res;
576 Res.resize(NumElems);
577
578 unsigned NumOps = PHI.getNumOperands();
579 for (unsigned I = 0; I < NumElems; ++I)
580 Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
581 PHI.getName() + ".i" + Twine(I));
582
583 for (unsigned I = 0; I < NumOps; ++I) {
584 Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
585 BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
586 for (unsigned J = 0; J < NumElems; ++J)
587 cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
588 }
589 gather(&PHI, Res);
590 return true;
591}
592
593bool Scalarizer::visitLoadInst(LoadInst &LI) {
594 if (!ScalarizeLoadStore)
595 return false;
596 if (!LI.isSimple())
597 return false;
598
599 VectorLayout Layout;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600 if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout,
601 LI.getModule()->getDataLayout()))
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000602 return false;
603
604 unsigned NumElems = Layout.VecTy->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000605 IRBuilder<> Builder(&LI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000606 Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
607 ValueVector Res;
608 Res.resize(NumElems);
609
610 for (unsigned I = 0; I < NumElems; ++I)
611 Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
612 LI.getName() + ".i" + Twine(I));
613 gather(&LI, Res);
614 return true;
615}
616
617bool Scalarizer::visitStoreInst(StoreInst &SI) {
618 if (!ScalarizeLoadStore)
619 return false;
620 if (!SI.isSimple())
621 return false;
622
623 VectorLayout Layout;
624 Value *FullValue = SI.getValueOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout,
626 SI.getModule()->getDataLayout()))
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000627 return false;
628
629 unsigned NumElems = Layout.VecTy->getNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000630 IRBuilder<> Builder(&SI);
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000631 Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
632 Scatterer Val = scatter(&SI, FullValue);
633
634 ValueVector Stores;
635 Stores.resize(NumElems);
636 for (unsigned I = 0; I < NumElems; ++I) {
637 unsigned Align = Layout.getElemAlign(I);
638 Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
639 }
640 transferMetadata(&SI, Stores);
641 return true;
642}
643
644// Delete the instructions that we scalarized. If a full vector result
645// is still needed, recreate it using InsertElements.
646bool Scalarizer::finish() {
Matt Wala878c1442015-07-23 20:53:46 +0000647 // The presence of data in Gathered or Scattered indicates changes
648 // made to the Function.
649 if (Gathered.empty() && Scattered.empty())
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000650 return false;
651 for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
652 GMI != GME; ++GMI) {
653 Instruction *Op = GMI->first;
654 ValueVector &CV = *GMI->second;
655 if (!Op->use_empty()) {
656 // The value is still needed, so recreate it using a series of
657 // InsertElements.
658 Type *Ty = Op->getType();
659 Value *Res = UndefValue::get(Ty);
Richard Sandiford1fb5c132013-12-23 14:51:56 +0000660 BasicBlock *BB = Op->getParent();
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000661 unsigned Count = Ty->getVectorNumElements();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000662 IRBuilder<> Builder(Op);
Richard Sandiford1fb5c132013-12-23 14:51:56 +0000663 if (isa<PHINode>(Op))
664 Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000665 for (unsigned I = 0; I < Count; ++I)
666 Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
667 Op->getName() + ".upto" + Twine(I));
668 Res->takeName(Op);
669 Op->replaceAllUsesWith(Res);
670 }
671 Op->eraseFromParent();
672 }
673 Gathered.clear();
674 Scattered.clear();
675 return true;
676}
677
678FunctionPass *llvm::createScalarizerPass() {
679 return new Scalarizer();
680}