1 //===- Scalarizer.cpp - Scalarize vector operations -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass converts vector operations into scalar operations, in order
10 // to expose optimization opportunities on the individual scalar operations.
11 // It is mainly intended for targets that do not have vector units, but it
12 // may also be useful for revectorizing code to different vector widths.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Scalar/Scalarizer.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Analysis/VectorUtils.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstVisitor.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 #include <map>
47 #include <utility>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "scalarizer"
52 
53 static cl::opt<bool> ClScalarizeVariableInsertExtract(
54     "scalarize-variable-insert-extract", cl::init(true), cl::Hidden,
55     cl::desc("Allow the scalarizer pass to scalarize "
56              "insertelement/extractelement with variable index"));
57 
58 // This is disabled by default because having separate loads and stores
59 // makes it more likely that the -combiner-alias-analysis limits will be
60 // reached.
61 static cl::opt<bool> ClScalarizeLoadStore(
62     "scalarize-load-store", cl::init(false), cl::Hidden,
63     cl::desc("Allow the scalarizer pass to scalarize loads and store"));
64 
65 namespace {
66 
67 BasicBlock::iterator skipPastPhiNodesAndDbg(BasicBlock::iterator Itr) {
68   BasicBlock *BB = Itr->getParent();
69   if (isa<PHINode>(Itr))
70     Itr = BB->getFirstInsertionPt();
71   if (Itr != BB->end())
72     Itr = skipDebugIntrinsics(Itr);
73   return Itr;
74 }
75 
76 // Used to store the scattered form of a vector.
77 using ValueVector = SmallVector<Value *, 8>;
78 
79 // Used to map a vector Value to its scattered form.  We use std::map
80 // because we want iterators to persist across insertion and because the
81 // values are relatively large.
82 using ScatterMap = std::map<Value *, ValueVector>;
83 
84 // Lists Instructions that have been replaced with scalar implementations,
85 // along with a pointer to their scattered forms.
86 using GatherList = SmallVector<std::pair<Instruction *, ValueVector *>, 16>;
87 
88 // Provides a very limited vector-like interface for lazily accessing one
89 // component of a scattered vector or vector pointer.
90 class Scatterer {
91 public:
92   Scatterer() = default;
93 
94   // Scatter V into Size components.  If new instructions are needed,
95   // insert them before BBI in BB.  If Cache is nonnull, use it to cache
96   // the results.
97   Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v, Type *PtrElemTy,
98             ValueVector *cachePtr = nullptr);
99 
100   // Return component I, creating a new Value for it if necessary.
101   Value *operator[](unsigned I);
102 
103   // Return the number of components.
104   unsigned size() const { return Size; }
105 
106 private:
107   BasicBlock *BB;
108   BasicBlock::iterator BBI;
109   Value *V;
110   Type *PtrElemTy;
111   ValueVector *CachePtr;
112   ValueVector Tmp;
113   unsigned Size;
114 };
115 
116 // FCmpSpliiter(FCI)(Builder, X, Y, Name) uses Builder to create an FCmp
117 // called Name that compares X and Y in the same way as FCI.
118 struct FCmpSplitter {
119   FCmpSplitter(FCmpInst &fci) : FCI(fci) {}
120 
121   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
122                     const Twine &Name) const {
123     return Builder.CreateFCmp(FCI.getPredicate(), Op0, Op1, Name);
124   }
125 
126   FCmpInst &FCI;
127 };
128 
129 // ICmpSpliiter(ICI)(Builder, X, Y, Name) uses Builder to create an ICmp
130 // called Name that compares X and Y in the same way as ICI.
131 struct ICmpSplitter {
132   ICmpSplitter(ICmpInst &ici) : ICI(ici) {}
133 
134   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
135                     const Twine &Name) const {
136     return Builder.CreateICmp(ICI.getPredicate(), Op0, Op1, Name);
137   }
138 
139   ICmpInst &ICI;
140 };
141 
142 // UnarySpliiter(UO)(Builder, X, Name) uses Builder to create
143 // a unary operator like UO called Name with operand X.
144 struct UnarySplitter {
145   UnarySplitter(UnaryOperator &uo) : UO(uo) {}
146 
147   Value *operator()(IRBuilder<> &Builder, Value *Op, const Twine &Name) const {
148     return Builder.CreateUnOp(UO.getOpcode(), Op, Name);
149   }
150 
151   UnaryOperator &UO;
152 };
153 
154 // BinarySpliiter(BO)(Builder, X, Y, Name) uses Builder to create
155 // a binary operator like BO called Name with operands X and Y.
156 struct BinarySplitter {
157   BinarySplitter(BinaryOperator &bo) : BO(bo) {}
158 
159   Value *operator()(IRBuilder<> &Builder, Value *Op0, Value *Op1,
160                     const Twine &Name) const {
161     return Builder.CreateBinOp(BO.getOpcode(), Op0, Op1, Name);
162   }
163 
164   BinaryOperator &BO;
165 };
166 
167 // Information about a load or store that we're scalarizing.
168 struct VectorLayout {
169   VectorLayout() = default;
170 
171   // Return the alignment of element I.
172   Align getElemAlign(unsigned I) {
173     return commonAlignment(VecAlign, I * ElemSize);
174   }
175 
176   // The type of the vector.
177   VectorType *VecTy = nullptr;
178 
179   // The type of each element.
180   Type *ElemTy = nullptr;
181 
182   // The alignment of the vector.
183   Align VecAlign;
184 
185   // The size of each element.
186   uint64_t ElemSize = 0;
187 };
188 
189 template <typename T>
190 T getWithDefaultOverride(const cl::opt<T> &ClOption,
191                          const llvm::Optional<T> &DefaultOverride) {
192   return ClOption.getNumOccurrences() ? ClOption
193                                       : DefaultOverride.getValueOr(ClOption);
194 }
195 
196 class ScalarizerVisitor : public InstVisitor<ScalarizerVisitor, bool> {
197 public:
198   ScalarizerVisitor(unsigned ParallelLoopAccessMDKind, DominatorTree *DT,
199                     ScalarizerPassOptions Options)
200       : ParallelLoopAccessMDKind(ParallelLoopAccessMDKind), DT(DT),
201         ScalarizeVariableInsertExtract(
202             getWithDefaultOverride(ClScalarizeVariableInsertExtract,
203                                    Options.ScalarizeVariableInsertExtract)),
204         ScalarizeLoadStore(getWithDefaultOverride(ClScalarizeLoadStore,
205                                                   Options.ScalarizeLoadStore)) {
206   }
207 
208   bool visit(Function &F);
209 
210   // InstVisitor methods.  They return true if the instruction was scalarized,
211   // false if nothing changed.
212   bool visitInstruction(Instruction &I) { return false; }
213   bool visitSelectInst(SelectInst &SI);
214   bool visitICmpInst(ICmpInst &ICI);
215   bool visitFCmpInst(FCmpInst &FCI);
216   bool visitUnaryOperator(UnaryOperator &UO);
217   bool visitBinaryOperator(BinaryOperator &BO);
218   bool visitGetElementPtrInst(GetElementPtrInst &GEPI);
219   bool visitCastInst(CastInst &CI);
220   bool visitBitCastInst(BitCastInst &BCI);
221   bool visitInsertElementInst(InsertElementInst &IEI);
222   bool visitExtractElementInst(ExtractElementInst &EEI);
223   bool visitShuffleVectorInst(ShuffleVectorInst &SVI);
224   bool visitPHINode(PHINode &PHI);
225   bool visitLoadInst(LoadInst &LI);
226   bool visitStoreInst(StoreInst &SI);
227   bool visitCallInst(CallInst &ICI);
228 
229 private:
230   Scatterer scatter(Instruction *Point, Value *V, Type *PtrElemTy = nullptr);
231   void gather(Instruction *Op, const ValueVector &CV);
232   bool canTransferMetadata(unsigned Kind);
233   void transferMetadataAndIRFlags(Instruction *Op, const ValueVector &CV);
234   Optional<VectorLayout> getVectorLayout(Type *Ty, Align Alignment,
235                                          const DataLayout &DL);
236   bool finish();
237 
238   template<typename T> bool splitUnary(Instruction &, const T &);
239   template<typename T> bool splitBinary(Instruction &, const T &);
240 
241   bool splitCall(CallInst &CI);
242 
243   ScatterMap Scattered;
244   GatherList Gathered;
245 
246   SmallVector<WeakTrackingVH, 32> PotentiallyDeadInstrs;
247 
248   unsigned ParallelLoopAccessMDKind;
249 
250   DominatorTree *DT;
251 
252   const bool ScalarizeVariableInsertExtract;
253   const bool ScalarizeLoadStore;
254 };
255 
256 class ScalarizerLegacyPass : public FunctionPass {
257 public:
258   static char ID;
259 
260   ScalarizerLegacyPass() : FunctionPass(ID) {
261     initializeScalarizerLegacyPassPass(*PassRegistry::getPassRegistry());
262   }
263 
264   bool runOnFunction(Function &F) override;
265 
266   void getAnalysisUsage(AnalysisUsage& AU) const override {
267     AU.addRequired<DominatorTreeWrapperPass>();
268     AU.addPreserved<DominatorTreeWrapperPass>();
269   }
270 };
271 
272 } // end anonymous namespace
273 
274 char ScalarizerLegacyPass::ID = 0;
275 INITIALIZE_PASS_BEGIN(ScalarizerLegacyPass, "scalarizer",
276                       "Scalarize vector operations", false, false)
277 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
278 INITIALIZE_PASS_END(ScalarizerLegacyPass, "scalarizer",
279                     "Scalarize vector operations", false, false)
280 
281 Scatterer::Scatterer(BasicBlock *bb, BasicBlock::iterator bbi, Value *v,
282                      Type *PtrElemTy, ValueVector *cachePtr)
283     : BB(bb), BBI(bbi), V(v), PtrElemTy(PtrElemTy), CachePtr(cachePtr) {
284   Type *Ty = V->getType();
285   if (Ty->isPointerTy()) {
286     assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(PtrElemTy) &&
287            "Pointer element type mismatch");
288     Ty = PtrElemTy;
289   }
290   Size = cast<FixedVectorType>(Ty)->getNumElements();
291   if (!CachePtr)
292     Tmp.resize(Size, nullptr);
293   else if (CachePtr->empty())
294     CachePtr->resize(Size, nullptr);
295   else
296     assert(Size == CachePtr->size() && "Inconsistent vector sizes");
297 }
298 
299 // Return component I, creating a new Value for it if necessary.
300 Value *Scatterer::operator[](unsigned I) {
301   ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
302   // Try to reuse a previous value.
303   if (CV[I])
304     return CV[I];
305   IRBuilder<> Builder(BB, BBI);
306   if (PtrElemTy) {
307     Type *VectorElemTy = cast<VectorType>(PtrElemTy)->getElementType();
308     if (!CV[0]) {
309       Type *NewPtrTy = PointerType::get(
310           VectorElemTy, V->getType()->getPointerAddressSpace());
311       CV[0] = Builder.CreateBitCast(V, NewPtrTy, V->getName() + ".i0");
312     }
313     if (I != 0)
314       CV[I] = Builder.CreateConstGEP1_32(VectorElemTy, CV[0], I,
315                                          V->getName() + ".i" + Twine(I));
316   } else {
317     // Search through a chain of InsertElementInsts looking for element I.
318     // Record other elements in the cache.  The new V is still suitable
319     // for all uncached indices.
320     while (true) {
321       InsertElementInst *Insert = dyn_cast<InsertElementInst>(V);
322       if (!Insert)
323         break;
324       ConstantInt *Idx = dyn_cast<ConstantInt>(Insert->getOperand(2));
325       if (!Idx)
326         break;
327       unsigned J = Idx->getZExtValue();
328       V = Insert->getOperand(0);
329       if (I == J) {
330         CV[J] = Insert->getOperand(1);
331         return CV[J];
332       } else if (!CV[J]) {
333         // Only cache the first entry we find for each index we're not actively
334         // searching for. This prevents us from going too far up the chain and
335         // caching incorrect entries.
336         CV[J] = Insert->getOperand(1);
337       }
338     }
339     CV[I] = Builder.CreateExtractElement(V, Builder.getInt32(I),
340                                          V->getName() + ".i" + Twine(I));
341   }
342   return CV[I];
343 }
344 
345 bool ScalarizerLegacyPass::runOnFunction(Function &F) {
346   if (skipFunction(F))
347     return false;
348 
349   Module &M = *F.getParent();
350   unsigned ParallelLoopAccessMDKind =
351       M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
352   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
353   ScalarizerVisitor Impl(ParallelLoopAccessMDKind, DT, ScalarizerPassOptions());
354   return Impl.visit(F);
355 }
356 
357 FunctionPass *llvm::createScalarizerPass() {
358   return new ScalarizerLegacyPass();
359 }
360 
361 bool ScalarizerVisitor::visit(Function &F) {
362   assert(Gathered.empty() && Scattered.empty());
363 
364   // To ensure we replace gathered components correctly we need to do an ordered
365   // traversal of the basic blocks in the function.
366   ReversePostOrderTraversal<BasicBlock *> RPOT(&F.getEntryBlock());
367   for (BasicBlock *BB : RPOT) {
368     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
369       Instruction *I = &*II;
370       bool Done = InstVisitor::visit(I);
371       ++II;
372       if (Done && I->getType()->isVoidTy())
373         I->eraseFromParent();
374     }
375   }
376   return finish();
377 }
378 
379 // Return a scattered form of V that can be accessed by Point.  V must be a
380 // vector or a pointer to a vector.
381 Scatterer ScalarizerVisitor::scatter(Instruction *Point, Value *V,
382                                      Type *PtrElemTy) {
383   if (Argument *VArg = dyn_cast<Argument>(V)) {
384     // Put the scattered form of arguments in the entry block,
385     // so that it can be used everywhere.
386     Function *F = VArg->getParent();
387     BasicBlock *BB = &F->getEntryBlock();
388     return Scatterer(BB, BB->begin(), V, PtrElemTy, &Scattered[V]);
389   }
390   if (Instruction *VOp = dyn_cast<Instruction>(V)) {
391     // When scalarizing PHI nodes we might try to examine/rewrite InsertElement
392     // nodes in predecessors. If those predecessors are unreachable from entry,
393     // then the IR in those blocks could have unexpected properties resulting in
394     // infinite loops in Scatterer::operator[]. By simply treating values
395     // originating from instructions in unreachable blocks as undef we do not
396     // need to analyse them further.
397     if (!DT->isReachableFromEntry(VOp->getParent()))
398       return Scatterer(Point->getParent(), Point->getIterator(),
399                        UndefValue::get(V->getType()), PtrElemTy);
400     // Put the scattered form of an instruction directly after the
401     // instruction, skipping over PHI nodes and debug intrinsics.
402     BasicBlock *BB = VOp->getParent();
403     return Scatterer(
404         BB, skipPastPhiNodesAndDbg(std::next(BasicBlock::iterator(VOp))), V,
405         PtrElemTy, &Scattered[V]);
406   }
407   // In the fallback case, just put the scattered before Point and
408   // keep the result local to Point.
409   return Scatterer(Point->getParent(), Point->getIterator(), V, PtrElemTy);
410 }
411 
412 // Replace Op with the gathered form of the components in CV.  Defer the
413 // deletion of Op and creation of the gathered form to the end of the pass,
414 // so that we can avoid creating the gathered form if all uses of Op are
415 // replaced with uses of CV.
416 void ScalarizerVisitor::gather(Instruction *Op, const ValueVector &CV) {
417   transferMetadataAndIRFlags(Op, CV);
418 
419   // If we already have a scattered form of Op (created from ExtractElements
420   // of Op itself), replace them with the new form.
421   ValueVector &SV = Scattered[Op];
422   if (!SV.empty()) {
423     for (unsigned I = 0, E = SV.size(); I != E; ++I) {
424       Value *V = SV[I];
425       if (V == nullptr || SV[I] == CV[I])
426         continue;
427 
428       Instruction *Old = cast<Instruction>(V);
429       if (isa<Instruction>(CV[I]))
430         CV[I]->takeName(Old);
431       Old->replaceAllUsesWith(CV[I]);
432       PotentiallyDeadInstrs.emplace_back(Old);
433     }
434   }
435   SV = CV;
436   Gathered.push_back(GatherList::value_type(Op, &SV));
437 }
438 
439 // Return true if it is safe to transfer the given metadata tag from
440 // vector to scalar instructions.
441 bool ScalarizerVisitor::canTransferMetadata(unsigned Tag) {
442   return (Tag == LLVMContext::MD_tbaa
443           || Tag == LLVMContext::MD_fpmath
444           || Tag == LLVMContext::MD_tbaa_struct
445           || Tag == LLVMContext::MD_invariant_load
446           || Tag == LLVMContext::MD_alias_scope
447           || Tag == LLVMContext::MD_noalias
448           || Tag == ParallelLoopAccessMDKind
449           || Tag == LLVMContext::MD_access_group);
450 }
451 
452 // Transfer metadata from Op to the instructions in CV if it is known
453 // to be safe to do so.
454 void ScalarizerVisitor::transferMetadataAndIRFlags(Instruction *Op,
455                                                    const ValueVector &CV) {
456   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
457   Op->getAllMetadataOtherThanDebugLoc(MDs);
458   for (unsigned I = 0, E = CV.size(); I != E; ++I) {
459     if (Instruction *New = dyn_cast<Instruction>(CV[I])) {
460       for (const auto &MD : MDs)
461         if (canTransferMetadata(MD.first))
462           New->setMetadata(MD.first, MD.second);
463       New->copyIRFlags(Op);
464       if (Op->getDebugLoc() && !New->getDebugLoc())
465         New->setDebugLoc(Op->getDebugLoc());
466     }
467   }
468 }
469 
470 // Try to fill in Layout from Ty, returning true on success.  Alignment is
471 // the alignment of the vector, or None if the ABI default should be used.
472 Optional<VectorLayout>
473 ScalarizerVisitor::getVectorLayout(Type *Ty, Align Alignment,
474                                    const DataLayout &DL) {
475   VectorLayout Layout;
476   // Make sure we're dealing with a vector.
477   Layout.VecTy = dyn_cast<VectorType>(Ty);
478   if (!Layout.VecTy)
479     return None;
480   // Check that we're dealing with full-byte elements.
481   Layout.ElemTy = Layout.VecTy->getElementType();
482   if (!DL.typeSizeEqualsStoreSize(Layout.ElemTy))
483     return None;
484   Layout.VecAlign = Alignment;
485   Layout.ElemSize = DL.getTypeStoreSize(Layout.ElemTy);
486   return Layout;
487 }
488 
489 // Scalarize one-operand instruction I, using Split(Builder, X, Name)
490 // to create an instruction like I with operand X and name Name.
491 template<typename Splitter>
492 bool ScalarizerVisitor::splitUnary(Instruction &I, const Splitter &Split) {
493   VectorType *VT = dyn_cast<VectorType>(I.getType());
494   if (!VT)
495     return false;
496 
497   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
498   IRBuilder<> Builder(&I);
499   Scatterer Op = scatter(&I, I.getOperand(0));
500   assert(Op.size() == NumElems && "Mismatched unary operation");
501   ValueVector Res;
502   Res.resize(NumElems);
503   for (unsigned Elem = 0; Elem < NumElems; ++Elem)
504     Res[Elem] = Split(Builder, Op[Elem], I.getName() + ".i" + Twine(Elem));
505   gather(&I, Res);
506   return true;
507 }
508 
509 // Scalarize two-operand instruction I, using Split(Builder, X, Y, Name)
510 // to create an instruction like I with operands X and Y and name Name.
511 template<typename Splitter>
512 bool ScalarizerVisitor::splitBinary(Instruction &I, const Splitter &Split) {
513   VectorType *VT = dyn_cast<VectorType>(I.getType());
514   if (!VT)
515     return false;
516 
517   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
518   IRBuilder<> Builder(&I);
519   Scatterer VOp0 = scatter(&I, I.getOperand(0));
520   Scatterer VOp1 = scatter(&I, I.getOperand(1));
521   assert(VOp0.size() == NumElems && "Mismatched binary operation");
522   assert(VOp1.size() == NumElems && "Mismatched binary operation");
523   ValueVector Res;
524   Res.resize(NumElems);
525   for (unsigned Elem = 0; Elem < NumElems; ++Elem) {
526     Value *Op0 = VOp0[Elem];
527     Value *Op1 = VOp1[Elem];
528     Res[Elem] = Split(Builder, Op0, Op1, I.getName() + ".i" + Twine(Elem));
529   }
530   gather(&I, Res);
531   return true;
532 }
533 
534 static bool isTriviallyScalariable(Intrinsic::ID ID) {
535   return isTriviallyVectorizable(ID);
536 }
537 
538 // All of the current scalarizable intrinsics only have one mangled type.
539 static Function *getScalarIntrinsicDeclaration(Module *M,
540                                                Intrinsic::ID ID,
541                                                ArrayRef<Type*> Tys) {
542   return Intrinsic::getDeclaration(M, ID, Tys);
543 }
544 
545 /// If a call to a vector typed intrinsic function, split into a scalar call per
546 /// element if possible for the intrinsic.
547 bool ScalarizerVisitor::splitCall(CallInst &CI) {
548   VectorType *VT = dyn_cast<VectorType>(CI.getType());
549   if (!VT)
550     return false;
551 
552   Function *F = CI.getCalledFunction();
553   if (!F)
554     return false;
555 
556   Intrinsic::ID ID = F->getIntrinsicID();
557   if (ID == Intrinsic::not_intrinsic || !isTriviallyScalariable(ID))
558     return false;
559 
560   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
561   unsigned NumArgs = CI.arg_size();
562 
563   ValueVector ScalarOperands(NumArgs);
564   SmallVector<Scatterer, 8> Scattered(NumArgs);
565 
566   Scattered.resize(NumArgs);
567 
568   SmallVector<llvm::Type *, 3> Tys;
569   Tys.push_back(VT->getScalarType());
570 
571   // Assumes that any vector type has the same number of elements as the return
572   // vector type, which is true for all current intrinsics.
573   for (unsigned I = 0; I != NumArgs; ++I) {
574     Value *OpI = CI.getOperand(I);
575     if (OpI->getType()->isVectorTy()) {
576       Scattered[I] = scatter(&CI, OpI);
577       assert(Scattered[I].size() == NumElems && "mismatched call operands");
578     } else {
579       ScalarOperands[I] = OpI;
580       if (hasVectorInstrinsicOverloadedScalarOpd(ID, I))
581         Tys.push_back(OpI->getType());
582     }
583   }
584 
585   ValueVector Res(NumElems);
586   ValueVector ScalarCallOps(NumArgs);
587 
588   Function *NewIntrin = getScalarIntrinsicDeclaration(F->getParent(), ID, Tys);
589   IRBuilder<> Builder(&CI);
590 
591   // Perform actual scalarization, taking care to preserve any scalar operands.
592   for (unsigned Elem = 0; Elem < NumElems; ++Elem) {
593     ScalarCallOps.clear();
594 
595     for (unsigned J = 0; J != NumArgs; ++J) {
596       if (hasVectorInstrinsicScalarOpd(ID, J))
597         ScalarCallOps.push_back(ScalarOperands[J]);
598       else
599         ScalarCallOps.push_back(Scattered[J][Elem]);
600     }
601 
602     Res[Elem] = Builder.CreateCall(NewIntrin, ScalarCallOps,
603                                    CI.getName() + ".i" + Twine(Elem));
604   }
605 
606   gather(&CI, Res);
607   return true;
608 }
609 
610 bool ScalarizerVisitor::visitSelectInst(SelectInst &SI) {
611   VectorType *VT = dyn_cast<VectorType>(SI.getType());
612   if (!VT)
613     return false;
614 
615   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
616   IRBuilder<> Builder(&SI);
617   Scatterer VOp1 = scatter(&SI, SI.getOperand(1));
618   Scatterer VOp2 = scatter(&SI, SI.getOperand(2));
619   assert(VOp1.size() == NumElems && "Mismatched select");
620   assert(VOp2.size() == NumElems && "Mismatched select");
621   ValueVector Res;
622   Res.resize(NumElems);
623 
624   if (SI.getOperand(0)->getType()->isVectorTy()) {
625     Scatterer VOp0 = scatter(&SI, SI.getOperand(0));
626     assert(VOp0.size() == NumElems && "Mismatched select");
627     for (unsigned I = 0; I < NumElems; ++I) {
628       Value *Op0 = VOp0[I];
629       Value *Op1 = VOp1[I];
630       Value *Op2 = VOp2[I];
631       Res[I] = Builder.CreateSelect(Op0, Op1, Op2,
632                                     SI.getName() + ".i" + Twine(I));
633     }
634   } else {
635     Value *Op0 = SI.getOperand(0);
636     for (unsigned I = 0; I < NumElems; ++I) {
637       Value *Op1 = VOp1[I];
638       Value *Op2 = VOp2[I];
639       Res[I] = Builder.CreateSelect(Op0, Op1, Op2,
640                                     SI.getName() + ".i" + Twine(I));
641     }
642   }
643   gather(&SI, Res);
644   return true;
645 }
646 
647 bool ScalarizerVisitor::visitICmpInst(ICmpInst &ICI) {
648   return splitBinary(ICI, ICmpSplitter(ICI));
649 }
650 
651 bool ScalarizerVisitor::visitFCmpInst(FCmpInst &FCI) {
652   return splitBinary(FCI, FCmpSplitter(FCI));
653 }
654 
655 bool ScalarizerVisitor::visitUnaryOperator(UnaryOperator &UO) {
656   return splitUnary(UO, UnarySplitter(UO));
657 }
658 
659 bool ScalarizerVisitor::visitBinaryOperator(BinaryOperator &BO) {
660   return splitBinary(BO, BinarySplitter(BO));
661 }
662 
663 bool ScalarizerVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
664   VectorType *VT = dyn_cast<VectorType>(GEPI.getType());
665   if (!VT)
666     return false;
667 
668   IRBuilder<> Builder(&GEPI);
669   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
670   unsigned NumIndices = GEPI.getNumIndices();
671 
672   // The base pointer might be scalar even if it's a vector GEP. In those cases,
673   // splat the pointer into a vector value, and scatter that vector.
674   Value *Op0 = GEPI.getOperand(0);
675   if (!Op0->getType()->isVectorTy())
676     Op0 = Builder.CreateVectorSplat(NumElems, Op0);
677   Scatterer Base = scatter(&GEPI, Op0);
678 
679   SmallVector<Scatterer, 8> Ops;
680   Ops.resize(NumIndices);
681   for (unsigned I = 0; I < NumIndices; ++I) {
682     Value *Op = GEPI.getOperand(I + 1);
683 
684     // The indices might be scalars even if it's a vector GEP. In those cases,
685     // splat the scalar into a vector value, and scatter that vector.
686     if (!Op->getType()->isVectorTy())
687       Op = Builder.CreateVectorSplat(NumElems, Op);
688 
689     Ops[I] = scatter(&GEPI, Op);
690   }
691 
692   ValueVector Res;
693   Res.resize(NumElems);
694   for (unsigned I = 0; I < NumElems; ++I) {
695     SmallVector<Value *, 8> Indices;
696     Indices.resize(NumIndices);
697     for (unsigned J = 0; J < NumIndices; ++J)
698       Indices[J] = Ops[J][I];
699     Res[I] = Builder.CreateGEP(GEPI.getSourceElementType(), Base[I], Indices,
700                                GEPI.getName() + ".i" + Twine(I));
701     if (GEPI.isInBounds())
702       if (GetElementPtrInst *NewGEPI = dyn_cast<GetElementPtrInst>(Res[I]))
703         NewGEPI->setIsInBounds();
704   }
705   gather(&GEPI, Res);
706   return true;
707 }
708 
709 bool ScalarizerVisitor::visitCastInst(CastInst &CI) {
710   VectorType *VT = dyn_cast<VectorType>(CI.getDestTy());
711   if (!VT)
712     return false;
713 
714   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
715   IRBuilder<> Builder(&CI);
716   Scatterer Op0 = scatter(&CI, CI.getOperand(0));
717   assert(Op0.size() == NumElems && "Mismatched cast");
718   ValueVector Res;
719   Res.resize(NumElems);
720   for (unsigned I = 0; I < NumElems; ++I)
721     Res[I] = Builder.CreateCast(CI.getOpcode(), Op0[I], VT->getElementType(),
722                                 CI.getName() + ".i" + Twine(I));
723   gather(&CI, Res);
724   return true;
725 }
726 
727 bool ScalarizerVisitor::visitBitCastInst(BitCastInst &BCI) {
728   VectorType *DstVT = dyn_cast<VectorType>(BCI.getDestTy());
729   VectorType *SrcVT = dyn_cast<VectorType>(BCI.getSrcTy());
730   if (!DstVT || !SrcVT)
731     return false;
732 
733   unsigned DstNumElems = cast<FixedVectorType>(DstVT)->getNumElements();
734   unsigned SrcNumElems = cast<FixedVectorType>(SrcVT)->getNumElements();
735   IRBuilder<> Builder(&BCI);
736   Scatterer Op0 = scatter(&BCI, BCI.getOperand(0));
737   ValueVector Res;
738   Res.resize(DstNumElems);
739 
740   if (DstNumElems == SrcNumElems) {
741     for (unsigned I = 0; I < DstNumElems; ++I)
742       Res[I] = Builder.CreateBitCast(Op0[I], DstVT->getElementType(),
743                                      BCI.getName() + ".i" + Twine(I));
744   } else if (DstNumElems > SrcNumElems) {
745     // <M x t1> -> <N*M x t2>.  Convert each t1 to <N x t2> and copy the
746     // individual elements to the destination.
747     unsigned FanOut = DstNumElems / SrcNumElems;
748     auto *MidTy = FixedVectorType::get(DstVT->getElementType(), FanOut);
749     unsigned ResI = 0;
750     for (unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
751       Value *V = Op0[Op0I];
752       Instruction *VI;
753       // Look through any existing bitcasts before converting to <N x t2>.
754       // In the best case, the resulting conversion might be a no-op.
755       while ((VI = dyn_cast<Instruction>(V)) &&
756              VI->getOpcode() == Instruction::BitCast)
757         V = VI->getOperand(0);
758       V = Builder.CreateBitCast(V, MidTy, V->getName() + ".cast");
759       Scatterer Mid = scatter(&BCI, V);
760       for (unsigned MidI = 0; MidI < FanOut; ++MidI)
761         Res[ResI++] = Mid[MidI];
762     }
763   } else {
764     // <N*M x t1> -> <M x t2>.  Convert each group of <N x t1> into a t2.
765     unsigned FanIn = SrcNumElems / DstNumElems;
766     auto *MidTy = FixedVectorType::get(SrcVT->getElementType(), FanIn);
767     unsigned Op0I = 0;
768     for (unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
769       Value *V = PoisonValue::get(MidTy);
770       for (unsigned MidI = 0; MidI < FanIn; ++MidI)
771         V = Builder.CreateInsertElement(V, Op0[Op0I++], Builder.getInt32(MidI),
772                                         BCI.getName() + ".i" + Twine(ResI)
773                                         + ".upto" + Twine(MidI));
774       Res[ResI] = Builder.CreateBitCast(V, DstVT->getElementType(),
775                                         BCI.getName() + ".i" + Twine(ResI));
776     }
777   }
778   gather(&BCI, Res);
779   return true;
780 }
781 
782 bool ScalarizerVisitor::visitInsertElementInst(InsertElementInst &IEI) {
783   VectorType *VT = dyn_cast<VectorType>(IEI.getType());
784   if (!VT)
785     return false;
786 
787   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
788   IRBuilder<> Builder(&IEI);
789   Scatterer Op0 = scatter(&IEI, IEI.getOperand(0));
790   Value *NewElt = IEI.getOperand(1);
791   Value *InsIdx = IEI.getOperand(2);
792 
793   ValueVector Res;
794   Res.resize(NumElems);
795 
796   if (auto *CI = dyn_cast<ConstantInt>(InsIdx)) {
797     for (unsigned I = 0; I < NumElems; ++I)
798       Res[I] = CI->getValue().getZExtValue() == I ? NewElt : Op0[I];
799   } else {
800     if (!ScalarizeVariableInsertExtract)
801       return false;
802 
803     for (unsigned I = 0; I < NumElems; ++I) {
804       Value *ShouldReplace =
805           Builder.CreateICmpEQ(InsIdx, ConstantInt::get(InsIdx->getType(), I),
806                                InsIdx->getName() + ".is." + Twine(I));
807       Value *OldElt = Op0[I];
808       Res[I] = Builder.CreateSelect(ShouldReplace, NewElt, OldElt,
809                                     IEI.getName() + ".i" + Twine(I));
810     }
811   }
812 
813   gather(&IEI, Res);
814   return true;
815 }
816 
817 bool ScalarizerVisitor::visitExtractElementInst(ExtractElementInst &EEI) {
818   VectorType *VT = dyn_cast<VectorType>(EEI.getOperand(0)->getType());
819   if (!VT)
820     return false;
821 
822   unsigned NumSrcElems = cast<FixedVectorType>(VT)->getNumElements();
823   IRBuilder<> Builder(&EEI);
824   Scatterer Op0 = scatter(&EEI, EEI.getOperand(0));
825   Value *ExtIdx = EEI.getOperand(1);
826 
827   if (auto *CI = dyn_cast<ConstantInt>(ExtIdx)) {
828     Value *Res = Op0[CI->getValue().getZExtValue()];
829     gather(&EEI, {Res});
830     return true;
831   }
832 
833   if (!ScalarizeVariableInsertExtract)
834     return false;
835 
836   Value *Res = UndefValue::get(VT->getElementType());
837   for (unsigned I = 0; I < NumSrcElems; ++I) {
838     Value *ShouldExtract =
839         Builder.CreateICmpEQ(ExtIdx, ConstantInt::get(ExtIdx->getType(), I),
840                              ExtIdx->getName() + ".is." + Twine(I));
841     Value *Elt = Op0[I];
842     Res = Builder.CreateSelect(ShouldExtract, Elt, Res,
843                                EEI.getName() + ".upto" + Twine(I));
844   }
845   gather(&EEI, {Res});
846   return true;
847 }
848 
849 bool ScalarizerVisitor::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
850   VectorType *VT = dyn_cast<VectorType>(SVI.getType());
851   if (!VT)
852     return false;
853 
854   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
855   Scatterer Op0 = scatter(&SVI, SVI.getOperand(0));
856   Scatterer Op1 = scatter(&SVI, SVI.getOperand(1));
857   ValueVector Res;
858   Res.resize(NumElems);
859 
860   for (unsigned I = 0; I < NumElems; ++I) {
861     int Selector = SVI.getMaskValue(I);
862     if (Selector < 0)
863       Res[I] = UndefValue::get(VT->getElementType());
864     else if (unsigned(Selector) < Op0.size())
865       Res[I] = Op0[Selector];
866     else
867       Res[I] = Op1[Selector - Op0.size()];
868   }
869   gather(&SVI, Res);
870   return true;
871 }
872 
873 bool ScalarizerVisitor::visitPHINode(PHINode &PHI) {
874   VectorType *VT = dyn_cast<VectorType>(PHI.getType());
875   if (!VT)
876     return false;
877 
878   unsigned NumElems = cast<FixedVectorType>(VT)->getNumElements();
879   IRBuilder<> Builder(&PHI);
880   ValueVector Res;
881   Res.resize(NumElems);
882 
883   unsigned NumOps = PHI.getNumOperands();
884   for (unsigned I = 0; I < NumElems; ++I)
885     Res[I] = Builder.CreatePHI(VT->getElementType(), NumOps,
886                                PHI.getName() + ".i" + Twine(I));
887 
888   for (unsigned I = 0; I < NumOps; ++I) {
889     Scatterer Op = scatter(&PHI, PHI.getIncomingValue(I));
890     BasicBlock *IncomingBlock = PHI.getIncomingBlock(I);
891     for (unsigned J = 0; J < NumElems; ++J)
892       cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
893   }
894   gather(&PHI, Res);
895   return true;
896 }
897 
898 bool ScalarizerVisitor::visitLoadInst(LoadInst &LI) {
899   if (!ScalarizeLoadStore)
900     return false;
901   if (!LI.isSimple())
902     return false;
903 
904   Optional<VectorLayout> Layout = getVectorLayout(
905       LI.getType(), LI.getAlign(), LI.getModule()->getDataLayout());
906   if (!Layout)
907     return false;
908 
909   unsigned NumElems = cast<FixedVectorType>(Layout->VecTy)->getNumElements();
910   IRBuilder<> Builder(&LI);
911   Scatterer Ptr = scatter(&LI, LI.getPointerOperand(), LI.getType());
912   ValueVector Res;
913   Res.resize(NumElems);
914 
915   for (unsigned I = 0; I < NumElems; ++I)
916     Res[I] = Builder.CreateAlignedLoad(Layout->VecTy->getElementType(), Ptr[I],
917                                        Align(Layout->getElemAlign(I)),
918                                        LI.getName() + ".i" + Twine(I));
919   gather(&LI, Res);
920   return true;
921 }
922 
923 bool ScalarizerVisitor::visitStoreInst(StoreInst &SI) {
924   if (!ScalarizeLoadStore)
925     return false;
926   if (!SI.isSimple())
927     return false;
928 
929   Value *FullValue = SI.getValueOperand();
930   Optional<VectorLayout> Layout = getVectorLayout(
931       FullValue->getType(), SI.getAlign(), SI.getModule()->getDataLayout());
932   if (!Layout)
933     return false;
934 
935   unsigned NumElems = cast<FixedVectorType>(Layout->VecTy)->getNumElements();
936   IRBuilder<> Builder(&SI);
937   Scatterer VPtr = scatter(&SI, SI.getPointerOperand(), FullValue->getType());
938   Scatterer VVal = scatter(&SI, FullValue);
939 
940   ValueVector Stores;
941   Stores.resize(NumElems);
942   for (unsigned I = 0; I < NumElems; ++I) {
943     Value *Val = VVal[I];
944     Value *Ptr = VPtr[I];
945     Stores[I] = Builder.CreateAlignedStore(Val, Ptr, Layout->getElemAlign(I));
946   }
947   transferMetadataAndIRFlags(&SI, Stores);
948   return true;
949 }
950 
951 bool ScalarizerVisitor::visitCallInst(CallInst &CI) {
952   return splitCall(CI);
953 }
954 
955 // Delete the instructions that we scalarized.  If a full vector result
956 // is still needed, recreate it using InsertElements.
957 bool ScalarizerVisitor::finish() {
958   // The presence of data in Gathered or Scattered indicates changes
959   // made to the Function.
960   if (Gathered.empty() && Scattered.empty())
961     return false;
962   for (const auto &GMI : Gathered) {
963     Instruction *Op = GMI.first;
964     ValueVector &CV = *GMI.second;
965     if (!Op->use_empty()) {
966       // The value is still needed, so recreate it using a series of
967       // InsertElements.
968       Value *Res = PoisonValue::get(Op->getType());
969       if (auto *Ty = dyn_cast<VectorType>(Op->getType())) {
970         BasicBlock *BB = Op->getParent();
971         unsigned Count = cast<FixedVectorType>(Ty)->getNumElements();
972         IRBuilder<> Builder(Op);
973         if (isa<PHINode>(Op))
974           Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
975         for (unsigned I = 0; I < Count; ++I)
976           Res = Builder.CreateInsertElement(Res, CV[I], Builder.getInt32(I),
977                                             Op->getName() + ".upto" + Twine(I));
978         Res->takeName(Op);
979       } else {
980         assert(CV.size() == 1 && Op->getType() == CV[0]->getType());
981         Res = CV[0];
982         if (Op == Res)
983           continue;
984       }
985       Op->replaceAllUsesWith(Res);
986     }
987     PotentiallyDeadInstrs.emplace_back(Op);
988   }
989   Gathered.clear();
990   Scattered.clear();
991 
992   RecursivelyDeleteTriviallyDeadInstructionsPermissive(PotentiallyDeadInstrs);
993 
994   return true;
995 }
996 
997 PreservedAnalyses ScalarizerPass::run(Function &F, FunctionAnalysisManager &AM) {
998   Module &M = *F.getParent();
999   unsigned ParallelLoopAccessMDKind =
1000       M.getContext().getMDKindID("llvm.mem.parallel_loop_access");
1001   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1002   ScalarizerVisitor Impl(ParallelLoopAccessMDKind, DT, Options);
1003   bool Changed = Impl.visit(F);
1004   PreservedAnalyses PA;
1005   PA.preserve<DominatorTreeAnalysis>();
1006   return Changed ? PA : PreservedAnalyses::all();
1007 }
1008