1 //===------- VectorCombine.cpp - Optimize partial 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 optimizes scalar/vector interactions using target cost models. The
10 // transforms implemented here may not fit in traditional loop-based or SLP
11 // vectorization passes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Vectorize/VectorCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/VectorUtils.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Transforms/Vectorize.h"
31 
32 using namespace llvm;
33 using namespace llvm::PatternMatch;
34 
35 #define DEBUG_TYPE "vector-combine"
36 STATISTIC(NumVecCmp, "Number of vector compares formed");
37 STATISTIC(NumVecBO, "Number of vector binops formed");
38 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
39 STATISTIC(NumScalarBO, "Number of scalar binops formed");
40 STATISTIC(NumScalarCmp, "Number of scalar compares formed");
41 
42 static cl::opt<bool> DisableVectorCombine(
43     "disable-vector-combine", cl::init(false), cl::Hidden,
44     cl::desc("Disable all vector combine transforms"));
45 
46 static cl::opt<bool> DisableBinopExtractShuffle(
47     "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
48     cl::desc("Disable binop extract to shuffle transforms"));
49 
50 
51 /// Compare the relative costs of 2 extracts followed by scalar operation vs.
52 /// vector operation(s) followed by extract. Return true if the existing
53 /// instructions are cheaper than a vector alternative. Otherwise, return false
54 /// and if one of the extracts should be transformed to a shufflevector, set
55 /// \p ConvertToShuffle to that extract instruction.
56 static bool isExtractExtractCheap(ExtractElementInst *Ext0,
57                                   ExtractElementInst *Ext1, unsigned Opcode,
58                                   const TargetTransformInfo &TTI,
59                                   ExtractElementInst *&ConvertToShuffle,
60                                   unsigned PreferredExtractIndex) {
61   assert(isa<ConstantInt>(Ext0->getOperand(1)) &&
62          isa<ConstantInt>(Ext1->getOperand(1)) &&
63          "Expected constant extract indexes");
64   Type *ScalarTy = Ext0->getType();
65   auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
66   int ScalarOpCost, VectorOpCost;
67 
68   // Get cost estimates for scalar and vector versions of the operation.
69   bool IsBinOp = Instruction::isBinaryOp(Opcode);
70   if (IsBinOp) {
71     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
72     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
73   } else {
74     assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
75            "Expected a compare");
76     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy,
77                                           CmpInst::makeCmpResultType(ScalarTy));
78     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy,
79                                           CmpInst::makeCmpResultType(VecTy));
80   }
81 
82   // Get cost estimates for the extract elements. These costs will factor into
83   // both sequences.
84   unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue();
85   unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue();
86 
87   int Extract0Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
88                                             VecTy, Ext0Index);
89   int Extract1Cost = TTI.getVectorInstrCost(Instruction::ExtractElement,
90                                             VecTy, Ext1Index);
91 
92   // A more expensive extract will always be replaced by a splat shuffle.
93   // For example, if Ext0 is more expensive:
94   // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
95   // extelt (opcode (splat V0, Ext0), V1), Ext1
96   // TODO: Evaluate whether that always results in lowest cost. Alternatively,
97   //       check the cost of creating a broadcast shuffle and shuffling both
98   //       operands to element 0.
99   int CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
100 
101   // Extra uses of the extracts mean that we include those costs in the
102   // vector total because those instructions will not be eliminated.
103   int OldCost, NewCost;
104   if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
105     // Handle a special case. If the 2 extracts are identical, adjust the
106     // formulas to account for that. The extra use charge allows for either the
107     // CSE'd pattern or an unoptimized form with identical values:
108     // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
109     bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
110                                   : !Ext0->hasOneUse() || !Ext1->hasOneUse();
111     OldCost = CheapExtractCost + ScalarOpCost;
112     NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
113   } else {
114     // Handle the general case. Each extract is actually a different value:
115     // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
116     OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
117     NewCost = VectorOpCost + CheapExtractCost +
118               !Ext0->hasOneUse() * Extract0Cost +
119               !Ext1->hasOneUse() * Extract1Cost;
120   }
121 
122   if (Ext0Index == Ext1Index) {
123     // If the extract indexes are identical, no shuffle is needed.
124     ConvertToShuffle = nullptr;
125   } else {
126     if (IsBinOp && DisableBinopExtractShuffle)
127       return true;
128 
129     // If we are extracting from 2 different indexes, then one operand must be
130     // shuffled before performing the vector operation. The shuffle mask is
131     // undefined except for 1 lane that is being translated to the remaining
132     // extraction lane. Therefore, it is a splat shuffle. Ex:
133     // ShufMask = { undef, undef, 0, undef }
134     // TODO: The cost model has an option for a "broadcast" shuffle
135     //       (splat-from-element-0), but no option for a more general splat.
136     NewCost +=
137         TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
138 
139     // The more expensive extract will be replaced by a shuffle. If the costs
140     // are equal and there is a preferred extract index, shuffle the opposite
141     // operand. Otherwise, replace the extract with the higher index.
142     if (Extract0Cost > Extract1Cost)
143       ConvertToShuffle = Ext0;
144     else if (Extract1Cost > Extract0Cost)
145       ConvertToShuffle = Ext1;
146     else if (PreferredExtractIndex == Ext0Index)
147       ConvertToShuffle = Ext1;
148     else if (PreferredExtractIndex == Ext1Index)
149       ConvertToShuffle = Ext0;
150     else
151       ConvertToShuffle = Ext0Index > Ext1Index ? Ext0 : Ext1;
152   }
153 
154   // Aggressively form a vector op if the cost is equal because the transform
155   // may enable further optimization.
156   // Codegen can reverse this transform (scalarize) if it was not profitable.
157   return OldCost < NewCost;
158 }
159 
160 /// Given an extract element instruction with constant index operand, shuffle
161 /// the source vector (shift the scalar element) to a NewIndex for extraction.
162 /// Return null if the input can be constant folded, so that we are not creating
163 /// unnecessary instructions.
164 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
165                                             unsigned NewIndex) {
166   // If the extract can be constant-folded, this code is unsimplified. Defer
167   // to other passes to handle that.
168   Value *X = ExtElt->getVectorOperand();
169   Value *C = ExtElt->getIndexOperand();
170   if (isa<Constant>(X))
171     return nullptr;
172 
173   // The shuffle mask is undefined except for 1 lane that is being translated
174   // to the cheap extraction lane. Example:
175   // ShufMask = { 2, undef, undef, undef }
176   auto *VecTy = cast<FixedVectorType>(X->getType());
177   SmallVector<int, 32> Mask(VecTy->getNumElements(), -1);
178   assert(isa<ConstantInt>(C) && "Expected a constant index operand");
179   Mask[NewIndex] = cast<ConstantInt>(C)->getZExtValue();
180 
181   // extelt X, C --> extelt (shuffle X), NewIndex
182   IRBuilder<> Builder(ExtElt);
183   Value *Shuf = Builder.CreateShuffleVector(X, UndefValue::get(VecTy), Mask);
184   return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
185 }
186 
187 /// Try to reduce extract element costs by converting scalar compares to vector
188 /// compares followed by extract.
189 /// cmp (ext0 V0, C), (ext1 V1, C)
190 static void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
191                           Instruction &I) {
192   assert(isa<CmpInst>(&I) && "Expected a compare");
193   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
194              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
195          "Expected matching constant extract indexes");
196 
197   // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
198   ++NumVecCmp;
199   IRBuilder<> Builder(&I);
200   CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
201   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
202   Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
203   Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
204   I.replaceAllUsesWith(NewExt);
205 }
206 
207 /// Try to reduce extract element costs by converting scalar binops to vector
208 /// binops followed by extract.
209 /// bo (ext0 V0, C), (ext1 V1, C)
210 static void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
211                             Instruction &I) {
212   assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
213   assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
214              cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
215          "Expected matching constant extract indexes");
216 
217   // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
218   ++NumVecBO;
219   IRBuilder<> Builder(&I);
220   Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
221   Value *VecBO =
222       Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
223 
224   // All IR flags are safe to back-propagate because any potential poison
225   // created in unused vector elements is discarded by the extract.
226   if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
227     VecBOInst->copyIRFlags(&I);
228 
229   Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
230   I.replaceAllUsesWith(NewExt);
231 }
232 
233 /// Match an instruction with extracted vector operands.
234 static bool foldExtractExtract(Instruction &I, const TargetTransformInfo &TTI) {
235   // It is not safe to transform things like div, urem, etc. because we may
236   // create undefined behavior when executing those on unknown vector elements.
237   if (!isSafeToSpeculativelyExecute(&I))
238     return false;
239 
240   Instruction *I0, *I1;
241   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
242   if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
243       !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
244     return false;
245 
246   Value *V0, *V1;
247   uint64_t C0, C1;
248   if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
249       !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
250       V0->getType() != V1->getType())
251     return false;
252 
253   // If the scalar value 'I' is going to be re-inserted into a vector, then try
254   // to create an extract to that same element. The extract/insert can be
255   // reduced to a "select shuffle".
256   // TODO: If we add a larger pattern match that starts from an insert, this
257   //       probably becomes unnecessary.
258   auto *Ext0 = cast<ExtractElementInst>(I0);
259   auto *Ext1 = cast<ExtractElementInst>(I1);
260   uint64_t InsertIndex = std::numeric_limits<uint64_t>::max();
261   if (I.hasOneUse())
262     match(I.user_back(),
263           m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
264 
265   ExtractElementInst *ExtractToChange;
266   if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), TTI, ExtractToChange,
267                             InsertIndex))
268     return false;
269 
270   if (ExtractToChange) {
271     unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
272     ExtractElementInst *NewExtract =
273         translateExtract(ExtractToChange, CheapExtractIdx);
274     if (!NewExtract)
275       return false;
276     if (ExtractToChange == Ext0)
277       Ext0 = NewExtract;
278     else
279       Ext1 = NewExtract;
280   }
281 
282   if (Pred != CmpInst::BAD_ICMP_PREDICATE)
283     foldExtExtCmp(Ext0, Ext1, I);
284   else
285     foldExtExtBinop(Ext0, Ext1, I);
286 
287   return true;
288 }
289 
290 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the
291 /// destination type followed by shuffle. This can enable further transforms by
292 /// moving bitcasts or shuffles together.
293 static bool foldBitcastShuf(Instruction &I, const TargetTransformInfo &TTI) {
294   Value *V;
295   ArrayRef<int> Mask;
296   if (!match(&I, m_BitCast(
297                      m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
298     return false;
299 
300   // Disallow non-vector casts and length-changing shuffles.
301   // TODO: We could allow any shuffle.
302   auto *DestTy = dyn_cast<VectorType>(I.getType());
303   auto *SrcTy = cast<VectorType>(V->getType());
304   if (!DestTy || I.getOperand(0)->getType() != SrcTy)
305     return false;
306 
307   // The new shuffle must not cost more than the old shuffle. The bitcast is
308   // moved ahead of the shuffle, so assume that it has the same cost as before.
309   if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) >
310       TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy))
311     return false;
312 
313   unsigned DestNumElts = DestTy->getNumElements();
314   unsigned SrcNumElts = SrcTy->getNumElements();
315   SmallVector<int, 16> NewMask;
316   if (SrcNumElts <= DestNumElts) {
317     // The bitcast is from wide to narrow/equal elements. The shuffle mask can
318     // always be expanded to the equivalent form choosing narrower elements.
319     assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
320     unsigned ScaleFactor = DestNumElts / SrcNumElts;
321     narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
322   } else {
323     // The bitcast is from narrow elements to wide elements. The shuffle mask
324     // must choose consecutive elements to allow casting first.
325     assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
326     unsigned ScaleFactor = SrcNumElts / DestNumElts;
327     if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
328       return false;
329   }
330   // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
331   ++NumShufOfBitcast;
332   IRBuilder<> Builder(&I);
333   Value *CastV = Builder.CreateBitCast(V, DestTy);
334   Value *Shuf =
335       Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask);
336   I.replaceAllUsesWith(Shuf);
337   return true;
338 }
339 
340 /// Match a vector binop or compare instruction with at least one inserted
341 /// scalar operand and convert to scalar binop/cmp followed by insertelement.
342 static bool scalarizeBinopOrCmp(Instruction &I,
343                                 const TargetTransformInfo &TTI) {
344   CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
345   Value *Ins0, *Ins1;
346   if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
347       !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
348     return false;
349 
350   // Do not convert the vector condition of a vector select into a scalar
351   // condition. That may cause problems for codegen because of differences in
352   // boolean formats and register-file transfers.
353   // TODO: Can we account for that in the cost model?
354   bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
355   if (IsCmp)
356     for (User *U : I.users())
357       if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
358         return false;
359 
360   // Match against one or both scalar values being inserted into constant
361   // vectors:
362   // vec_op VecC0, (inselt VecC1, V1, Index)
363   // vec_op (inselt VecC0, V0, Index), VecC1
364   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
365   // TODO: Deal with mismatched index constants and variable indexes?
366   Constant *VecC0 = nullptr, *VecC1 = nullptr;
367   Value *V0 = nullptr, *V1 = nullptr;
368   uint64_t Index0 = 0, Index1 = 0;
369   if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
370                                m_ConstantInt(Index0))) &&
371       !match(Ins0, m_Constant(VecC0)))
372     return false;
373   if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
374                                m_ConstantInt(Index1))) &&
375       !match(Ins1, m_Constant(VecC1)))
376     return false;
377 
378   bool IsConst0 = !V0;
379   bool IsConst1 = !V1;
380   if (IsConst0 && IsConst1)
381     return false;
382   if (!IsConst0 && !IsConst1 && Index0 != Index1)
383     return false;
384 
385   // Bail for single insertion if it is a load.
386   // TODO: Handle this once getVectorInstrCost can cost for load/stores.
387   auto *I0 = dyn_cast_or_null<Instruction>(V0);
388   auto *I1 = dyn_cast_or_null<Instruction>(V1);
389   if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
390       (IsConst1 && I0 && I0->mayReadFromMemory()))
391     return false;
392 
393   uint64_t Index = IsConst0 ? Index1 : Index0;
394   Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
395   Type *VecTy = I.getType();
396   assert(VecTy->isVectorTy() &&
397          (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
398          (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy()) &&
399          "Unexpected types for insert into binop");
400 
401   unsigned Opcode = I.getOpcode();
402   int ScalarOpCost, VectorOpCost;
403   if (IsCmp) {
404     ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy);
405     VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy);
406   } else {
407     ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
408     VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
409   }
410 
411   // Get cost estimate for the insert element. This cost will factor into
412   // both sequences.
413   int InsertCost =
414       TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
415   int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) +
416                 VectorOpCost;
417   int NewCost = ScalarOpCost + InsertCost +
418                 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
419                 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
420 
421   // We want to scalarize unless the vector variant actually has lower cost.
422   if (OldCost < NewCost)
423     return false;
424 
425   // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
426   // inselt NewVecC, (scalar_op V0, V1), Index
427   if (IsCmp)
428     ++NumScalarCmp;
429   else
430     ++NumScalarBO;
431 
432   // For constant cases, extract the scalar element, this should constant fold.
433   IRBuilder<> Builder(&I);
434   if (IsConst0)
435     V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
436   if (IsConst1)
437     V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
438 
439   Value *Scalar =
440       IsCmp ? Builder.CreateCmp(Pred, V0, V1)
441             : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
442 
443   Scalar->setName(I.getName() + ".scalar");
444 
445   // All IR flags are safe to back-propagate. There is no potential for extra
446   // poison to be created by the scalar instruction.
447   if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
448     ScalarInst->copyIRFlags(&I);
449 
450   // Fold the vector constants in the original vectors into a new base vector.
451   Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1)
452                             : ConstantExpr::get(Opcode, VecC0, VecC1);
453   Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
454   I.replaceAllUsesWith(Insert);
455   Insert->takeName(&I);
456   return true;
457 }
458 
459 /// This is the entry point for all transforms. Pass manager differences are
460 /// handled in the callers of this function.
461 static bool runImpl(Function &F, const TargetTransformInfo &TTI,
462                     const DominatorTree &DT) {
463   if (DisableVectorCombine)
464     return false;
465 
466   bool MadeChange = false;
467   for (BasicBlock &BB : F) {
468     // Ignore unreachable basic blocks.
469     if (!DT.isReachableFromEntry(&BB))
470       continue;
471     // Do not delete instructions under here and invalidate the iterator.
472     // Walk the block forwards to enable simple iterative chains of transforms.
473     // TODO: It could be more efficient to remove dead instructions
474     //       iteratively in this loop rather than waiting until the end.
475     for (Instruction &I : BB) {
476       if (isa<DbgInfoIntrinsic>(I))
477         continue;
478       MadeChange |= foldExtractExtract(I, TTI);
479       MadeChange |= foldBitcastShuf(I, TTI);
480       MadeChange |= scalarizeBinopOrCmp(I, TTI);
481     }
482   }
483 
484   // We're done with transforms, so remove dead instructions.
485   if (MadeChange)
486     for (BasicBlock &BB : F)
487       SimplifyInstructionsInBlock(&BB);
488 
489   return MadeChange;
490 }
491 
492 // Pass manager boilerplate below here.
493 
494 namespace {
495 class VectorCombineLegacyPass : public FunctionPass {
496 public:
497   static char ID;
498   VectorCombineLegacyPass() : FunctionPass(ID) {
499     initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
500   }
501 
502   void getAnalysisUsage(AnalysisUsage &AU) const override {
503     AU.addRequired<DominatorTreeWrapperPass>();
504     AU.addRequired<TargetTransformInfoWrapperPass>();
505     AU.setPreservesCFG();
506     AU.addPreserved<DominatorTreeWrapperPass>();
507     AU.addPreserved<GlobalsAAWrapperPass>();
508     AU.addPreserved<AAResultsWrapperPass>();
509     AU.addPreserved<BasicAAWrapperPass>();
510     FunctionPass::getAnalysisUsage(AU);
511   }
512 
513   bool runOnFunction(Function &F) override {
514     if (skipFunction(F))
515       return false;
516     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
517     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
518     return runImpl(F, TTI, DT);
519   }
520 };
521 } // namespace
522 
523 char VectorCombineLegacyPass::ID = 0;
524 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
525                       "Optimize scalar/vector ops", false,
526                       false)
527 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
528 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
529                     "Optimize scalar/vector ops", false, false)
530 Pass *llvm::createVectorCombinePass() {
531   return new VectorCombineLegacyPass();
532 }
533 
534 PreservedAnalyses VectorCombinePass::run(Function &F,
535                                          FunctionAnalysisManager &FAM) {
536   TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
537   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
538   if (!runImpl(F, TTI, DT))
539     return PreservedAnalyses::all();
540   PreservedAnalyses PA;
541   PA.preserveSet<CFGAnalyses>();
542   PA.preserve<GlobalsAA>();
543   PA.preserve<AAManager>();
544   PA.preserve<BasicAA>();
545   return PA;
546 }
547