blob: e614ecee53a0f9f78d6c461a65e4b476c1d7c904 [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
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"
25
26using namespace llvm;
27
28namespace {
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,
51 ValueVector *cachePtr = 0);
52
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 {
104 VectorLayout() : VecTy(0), ElemTy(0), VecAlign(0), ElemSize(0) {}
105
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
134 virtual bool doInitialization(Module &M);
135 virtual bool runOnFunction(Function &F);
136
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
152private:
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 &);
158 bool finish();
159
160 template<typename T> bool splitBinary(Instruction &, const T &);
161
162 ScatterMap Scattered;
163 GatherList Gathered;
164 unsigned ParallelLoopAccessMDKind;
165 const DataLayout *TDL;
166};
167
168char Scalarizer::ID = 0;
169} // end anonymous namespace
170
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.
173static 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"));
176
177INITIALIZE_PASS(Scalarizer, "scalarizer", "Scalarize vector operations",
178 false, false)
179
180Scatterer::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);
185 if (PtrTy)
186 Ty = PtrTy->getElementType();
187 Size = Ty->getVectorNumElements();
188 if (!CachePtr)
189 Tmp.resize(Size, 0);
190 else if (CachePtr->empty())
191 CachePtr->resize(Size, 0);
192 else
193 assert(Size == CachePtr->size() && "Inconsistent vector sizes");
194}
195
196// Return component I, creating a new Value for it if necessary.
197Value *Scatterer::operator[](unsigned I) {
198 ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
199 // Try to reuse a previous value.
200 if (CV[I])
201 return CV[I];
202 IRBuilder<> Builder(BB, BBI);
203 if (PtrTy) {
204 if (!CV[0]) {
205 Type *Ty =
206 PointerType::get(PtrTy->getElementType()->getVectorElementType(),
207 PtrTy->getAddressSpace());
208 CV[0] = Builder.CreateBitCast(V, Ty, V->getName() + ".i0");
209 }
210 if (I != 0)
211 CV[I] = Builder.CreateConstGEP1_32(CV[0], I,
212 V->getName() + ".i" + Twine(I));
213 } else {
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.
217 for (;;) {
218 InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
219 if (!Insert)
220 break;
221 ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
222 if (!Idx)
223 break;
224 unsigned J = Idx->getZExtValue();
225 CV[J] = Insert->getOperand(1);
226 V = Insert->getOperand(0);
227 if (I == J)
228 return CV[J];
229 }
230 CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
231 V->getName() + ".i" + Twine(I));
232 }
233 return CV[I];
234}
235
236bool Scalarizer::doInitialization(Module &M) {
237 ParallelLoopAccessMDKind =
238 M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
239 return false;
240}
241
242bool Scalarizer::runOnFunction(Function &F) {
243 TDL = getAnalysisIfAvailable<DataLayout>();
244 for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
245 BasicBlock *BB = BBI;
246 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
247 Instruction *I = II;
248 bool Done = visit(I);
249 ++II;
250 if (Done && I->getType()->isVoidTy())
251 I->eraseFromParent();
252 }
253 }
254 return finish();
255}
256
257// Return a scattered form of V that can be accessed by Point. V must be a
258// vector or a pointer to a vector.
259Scatterer Scalarizer::scatter(Instruction *Point, Value *V) {
260 if (Argument *VArg = dyn_cast<Argument>(V)) {
261 // Put the scattered form of arguments in the entry block,
262 // so that it can be used everywhere.
263 Function *F = VArg->getParent();
264 BasicBlock *BB = &F->getEntryBlock();
265 return Scatterer(BB, BB->begin(), V, &Scattered[V]);
266 }
267 if (Instruction *VOp = dyn_cast<Instruction>(V)) {
268 // Put the scattered form of an instruction directly after the
269 // instruction.
270 BasicBlock *BB = VOp->getParent();
271 return Scatterer(BB, llvm::next(BasicBlock::iterator(VOp)),
272 V, &Scattered[V]);
273 }
274 // In the fallback case, just put the scattered before Point and
275 // keep the result local to Point.
276 return Scatterer(Point->getParent(), Point, V);
277}
278
279// Replace Op with the gathered form of the components in CV. Defer the
280// deletion of Op and creation of the gathered form to the end of the pass,
281// so that we can avoid creating the gathered form if all uses of Op are
282// replaced with uses of CV.
283void Scalarizer::gather(Instruction *Op, const ValueVector &CV) {
284 // Since we're not deleting Op yet, stub out its operands, so that it
285 // doesn't make anything live unnecessarily.
286 for (unsigned I = 0, E = Op->getNumOperands(); I != E; ++I)
287 Op->setOperand(I, UndefValue::get(Op->getOperand(I)->getType()));
288
289 transferMetadata(Op, CV);
290
291 // If we already have a scattered form of Op (created from ExtractElements
292 // of Op itself), replace them with the new form.
293 ValueVector &SV = Scattered[Op];
294 if (!SV.empty()) {
295 for (unsigned I = 0, E = SV.size(); I != E; ++I) {
296 Instruction *Old = cast<Instruction>(SV[I]);
297 CV[I]->takeName(Old);
298 Old->replaceAllUsesWith(CV[I]);
299 Old->eraseFromParent();
300 }
301 }
302 SV = CV;
303 Gathered.push_back(GatherList::value_type(Op, &SV));
304}
305
306// Return true if it is safe to transfer the given metadata tag from
307// vector to scalar instructions.
308bool Scalarizer::canTransferMetadata(unsigned Tag) {
309 return (Tag == LLVMContext::MD_tbaa
310 || Tag == LLVMContext::MD_fpmath
311 || Tag == LLVMContext::MD_tbaa_struct
312 || Tag == LLVMContext::MD_invariant_load
313 || Tag == ParallelLoopAccessMDKind);
314}
315
316// Transfer metadata from Op to the instructions in CV if it is known
317// to be safe to do so.
318void Scalarizer::transferMetadata(Instruction *Op, const ValueVector &CV) {
319 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
320 Op->getAllMetadataOtherThanDebugLoc(MDs);
321 for (unsigned I = 0, E = CV.size(); I != E; ++I) {
322 if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
323 for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator
324 MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI)
325 if (canTransferMetadata(MI->first))
326 New->setMetadata(MI->first, MI->second);
327 New->setDebugLoc(Op->getDebugLoc());
328 }
329 }
330}
331
332// Try to fill in Layout from Ty, returning true on success. Alignment is
333// the alignment of the vector, or 0 if the ABI default should be used.
334bool Scalarizer::getVectorLayout(Type *Ty, unsigned Alignment,
335 VectorLayout &Layout) {
336 if (!TDL)
337 return false;
338
339 // Make sure we're dealing with a vector.
340 Layout.VecTy = dyn_cast<VectorType>(Ty);
341 if (!Layout.VecTy)
342 return false;
343
344 // Check that we're dealing with full-byte elements.
345 Layout.ElemTy = Layout.VecTy->getElementType();
346 if (TDL->getTypeSizeInBits(Layout.ElemTy) !=
347 TDL->getTypeStoreSizeInBits(Layout.ElemTy))
348 return false;
349
350 if (Alignment)
351 Layout.VecAlign = Alignment;
352 else
353 Layout.VecAlign = TDL->getABITypeAlignment(Layout.VecTy);
354 Layout.ElemSize = TDL->getTypeStoreSize(Layout.ElemTy);
355 return true;
356}
357
358// Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
359// to create an instruction like I with operands X and Y and name Name.
360template<typename Splitter>
361bool Scalarizer::splitBinary(Instruction &I, const Splitter &Split) {
362 VectorType *VT = dyn_cast<VectorType>(I.getType());
363 if (!VT)
364 return false;
365
366 unsigned NumElems = VT->getNumElements();
367 IRBuilder<> Builder(I.getParent(), &I);
368 Scatterer Op0 = scatter(&I, I.getOperand(0));
369 Scatterer Op1 = scatter(&I, I.getOperand(1));
370 assert(Op0.size() == NumElems && "Mismatched binary operation");
371 assert(Op1.size() == NumElems && "Mismatched binary operation");
372 ValueVector Res;
373 Res.resize(NumElems);
374 for (unsigned Elem = 0; Elem < NumElems; ++Elem)
375 Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
376 I.getName() + ".i" + Twine(Elem));
377 gather(&I, Res);
378 return true;
379}
380
381bool Scalarizer::visitSelectInst(SelectInst &SI) {
382 VectorType *VT = dyn_cast<VectorType>(SI.getType());
383 if (!VT)
384 return false;
385
386 unsigned NumElems = VT->getNumElements();
387 IRBuilder<> Builder(SI.getParent(), &SI);
388 Scatterer Op1 = scatter(&SI, SI.getOperand(1));
389 Scatterer Op2 = scatter(&SI, SI.getOperand(2));
390 assert(Op1.size() == NumElems && "Mismatched select");
391 assert(Op2.size() == NumElems && "Mismatched select");
392 ValueVector Res;
393 Res.resize(NumElems);
394
395 if (SI.getOperand(0)->getType()->isVectorTy()) {
396 Scatterer Op0 = scatter(&SI, SI.getOperand(0));
397 assert(Op0.size() == NumElems && "Mismatched select");
398 for (unsigned I = 0; I < NumElems; ++I)
399 Res[I] = Builder.CreateSelect(Op0[I], Op1[I], Op2[I],
400 SI.getName() + ".i" + Twine(I));
401 } else {
402 Value *Op0 = SI.getOperand(0);
403 for (unsigned I = 0; I < NumElems; ++I)
404 Res[I] = Builder.CreateSelect(Op0, Op1[I], Op2[I],
405 SI.getName() + ".i" + Twine(I));
406 }
407 gather(&SI, Res);
408 return true;
409}
410
411bool Scalarizer::visitICmpInst(ICmpInst &ICI) {
412 return splitBinary(ICI, ICmpSplitter(ICI));
413}
414
415bool Scalarizer::visitFCmpInst(FCmpInst &FCI) {
416 return splitBinary(FCI, FCmpSplitter(FCI));
417}
418
419bool Scalarizer::visitBinaryOperator(BinaryOperator &BO) {
420 return splitBinary(BO, BinarySplitter(BO));
421}
422
423bool Scalarizer::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Richard Sandiford3548cbb2013-12-23 14:45:00 +0000424 VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
425 if (!VT)
426 return false;
427
428 IRBuilder<> Builder(GEPI.getParent(), &GEPI);
429 unsigned NumElems = VT->getNumElements();
430 unsigned NumIndices = GEPI.getNumIndices();
431
432 Scatterer Base = scatter(&GEPI, GEPI.getOperand(0));
433
434 SmallVector<Scatterer, 8> Ops;
435 Ops.resize(NumIndices);
436 for (unsigned I = 0; I < NumIndices; ++I)
437 Ops[I] = scatter(&GEPI, GEPI.getOperand(I + 1));
438
439 ValueVector Res;
440 Res.resize(NumElems);
441 for (unsigned I = 0; I < NumElems; ++I) {
442 SmallVector<Value *, 8> Indices;
443 Indices.resize(NumIndices);
444 for (unsigned J = 0; J < NumIndices; ++J)
445 Indices[J] = Ops[J][I];
446 Res[I] = Builder.CreateGEP(Base[I], Indices,
447 GEPI.getName() + ".i" + Twine(I));
448 if (GEPI.isInBounds())
449 if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
450 NewGEPI->setIsInBounds();
451 }
452 gather(&GEPI, Res);
453 return true;
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000454}
455
456bool Scalarizer::visitCastInst(CastInst &CI) {
457 VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
458 if (!VT)
459 return false;
460
461 unsigned NumElems = VT->getNumElements();
462 IRBuilder<> Builder(CI.getParent(), &CI);
463 Scatterer Op0 = scatter(&CI, CI.getOperand(0));
464 assert(Op0.size() == NumElems && "Mismatched cast");
465 ValueVector Res;
466 Res.resize(NumElems);
467 for (unsigned I = 0; I < NumElems; ++I)
468 Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
469 CI.getName() + ".i" + Twine(I));
470 gather(&CI, Res);
471 return true;
472}
473
474bool Scalarizer::visitBitCastInst(BitCastInst &BCI) {
475 VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
476 VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
477 if (!DstVT || !SrcVT)
478 return false;
479
480 unsigned DstNumElems = DstVT->getNumElements();
481 unsigned SrcNumElems = SrcVT->getNumElements();
482 IRBuilder<> Builder(BCI.getParent(), &BCI);
483 Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
484 ValueVector Res;
485 Res.resize(DstNumElems);
486
487 if (DstNumElems == SrcNumElems) {
488 for (unsigned I = 0; I < DstNumElems; ++I)
489 Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
490 BCI.getName() + ".i" + Twine(I));
491 } else if (DstNumElems > SrcNumElems) {
492 // <M x t1> -> <N*M x t2>. Convert each t1 to <N x t2> and copy the
493 // individual elements to the destination.
494 unsigned FanOut = DstNumElems / SrcNumElems;
495 Type *MidTy = VectorType::get(DstVT->getElementType(), FanOut);
496 unsigned ResI = 0;
497 for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
498 Value *V = Op0[Op0I];
499 Instruction *VI;
500 // Look through any existing bitcasts before converting to <N x t2>.
501 // In the best case, the resulting conversion might be a no-op.
502 while ((VI = dyn_cast<Instruction>(V)) &&
503 VI->getOpcode() == Instruction::BitCast)
504 V = VI->getOperand(0);
505 V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
506 Scatterer Mid = scatter(&BCI, V);
507 for (unsigned MidI = 0; MidI < FanOut; ++MidI)
508 Res[ResI++] = Mid[MidI];
509 }
510 } else {
511 // <N*M x t1> -> <M x t2>. Convert each group of <N x t1> into a t2.
512 unsigned FanIn = SrcNumElems / DstNumElems;
513 Type *MidTy = VectorType::get(SrcVT->getElementType(), FanIn);
514 unsigned Op0I = 0;
515 for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
516 Value *V = UndefValue::get(MidTy);
517 for (unsigned MidI = 0; MidI < FanIn; ++MidI)
518 V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
519 BCI.getName() + ".i" + Twine(ResI)
520 + ".upto" + Twine(MidI));
521 Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
522 BCI.getName() + ".i" + Twine(ResI));
523 }
524 }
525 gather(&BCI, Res);
526 return true;
527}
528
529bool Scalarizer::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
530 VectorType *VT = dyn_cast<VectorType>(SVI.getType());
531 if (!VT)
532 return false;
533
534 unsigned NumElems = VT->getNumElements();
535 Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
536 Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
537 ValueVector Res;
538 Res.resize(NumElems);
539
540 for (unsigned I = 0; I < NumElems; ++I) {
541 int Selector = SVI.getMaskValue(I);
542 if (Selector < 0)
543 Res[I] = UndefValue::get(VT->getElementType());
544 else if (unsigned(Selector) < Op0.size())
545 Res[I] = Op0[Selector];
546 else
547 Res[I] = Op1[Selector - Op0.size()];
548 }
549 gather(&SVI, Res);
550 return true;
551}
552
553bool Scalarizer::visitPHINode(PHINode &PHI) {
554 VectorType *VT = dyn_cast<VectorType>(PHI.getType());
555 if (!VT)
556 return false;
557
558 unsigned NumElems = VT->getNumElements();
559 IRBuilder<> Builder(PHI.getParent(), &PHI);
560 ValueVector Res;
561 Res.resize(NumElems);
562
563 unsigned NumOps = PHI.getNumOperands();
564 for (unsigned I = 0; I < NumElems; ++I)
565 Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
566 PHI.getName() + ".i" + Twine(I));
567
568 for (unsigned I = 0; I < NumOps; ++I) {
569 Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
570 BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
571 for (unsigned J = 0; J < NumElems; ++J)
572 cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
573 }
574 gather(&PHI, Res);
575 return true;
576}
577
578bool Scalarizer::visitLoadInst(LoadInst &LI) {
579 if (!ScalarizeLoadStore)
580 return false;
581 if (!LI.isSimple())
582 return false;
583
584 VectorLayout Layout;
585 if (!getVectorLayout(LI.getType(), LI.getAlignment(), Layout))
586 return false;
587
588 unsigned NumElems = Layout.VecTy->getNumElements();
589 IRBuilder<> Builder(LI.getParent(), &LI);
590 Scatterer Ptr = scatter(&LI, LI.getPointerOperand());
591 ValueVector Res;
592 Res.resize(NumElems);
593
594 for (unsigned I = 0; I < NumElems; ++I)
595 Res[I] = Builder.CreateAlignedLoad(Ptr[I], Layout.getElemAlign(I),
596 LI.getName() + ".i" + Twine(I));
597 gather(&LI, Res);
598 return true;
599}
600
601bool Scalarizer::visitStoreInst(StoreInst &SI) {
602 if (!ScalarizeLoadStore)
603 return false;
604 if (!SI.isSimple())
605 return false;
606
607 VectorLayout Layout;
608 Value *FullValue = SI.getValueOperand();
609 if (!getVectorLayout(FullValue->getType(), SI.getAlignment(), Layout))
610 return false;
611
612 unsigned NumElems = Layout.VecTy->getNumElements();
613 IRBuilder<> Builder(SI.getParent(), &SI);
614 Scatterer Ptr = scatter(&SI, SI.getPointerOperand());
615 Scatterer Val = scatter(&SI, FullValue);
616
617 ValueVector Stores;
618 Stores.resize(NumElems);
619 for (unsigned I = 0; I < NumElems; ++I) {
620 unsigned Align = Layout.getElemAlign(I);
621 Stores[I] = Builder.CreateAlignedStore(Val[I], Ptr[I], Align);
622 }
623 transferMetadata(&SI, Stores);
624 return true;
625}
626
627// Delete the instructions that we scalarized. If a full vector result
628// is still needed, recreate it using InsertElements.
629bool Scalarizer::finish() {
630 if (Gathered.empty())
631 return false;
632 for (GatherList::iterator GMI = Gathered.begin(), GME = Gathered.end();
633 GMI != GME; ++GMI) {
634 Instruction *Op = GMI->first;
635 ValueVector &CV = *GMI->second;
636 if (!Op->use_empty()) {
637 // The value is still needed, so recreate it using a series of
638 // InsertElements.
639 Type *Ty = Op->getType();
640 Value *Res = UndefValue::get(Ty);
Richard Sandiford1fb5c132013-12-23 14:51:56 +0000641 BasicBlock *BB = Op->getParent();
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000642 unsigned Count = Ty->getVectorNumElements();
Richard Sandiford1fb5c132013-12-23 14:51:56 +0000643 IRBuilder<> Builder(BB, Op);
644 if (isa<PHINode>(Op))
645 Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
Richard Sandiford8ee1b772013-11-22 16:58:05 +0000646 for (unsigned I = 0; I < Count; ++I)
647 Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
648 Op->getName() + ".upto" + Twine(I));
649 Res->takeName(Op);
650 Op->replaceAllUsesWith(Res);
651 }
652 Op->eraseFromParent();
653 }
654 Gathered.clear();
655 Scattered.clear();
656 return true;
657}
658
659FunctionPass *llvm::createScalarizerPass() {
660 return new Scalarizer();
661}