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