SLSR: Pass address space to isLegalAddressingMode
[oota-llvm.git] / lib / Transforms / Scalar / StraightLineStrengthReduce.cpp
1 //===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
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 file implements straight-line strength reduction (SLSR). Unlike loop
11 // strength reduction, this algorithm is designed to reduce arithmetic
12 // redundancy in straight-line code instead of loops. It has proven to be
13 // effective in simplifying arithmetic statements derived from an unrolled loop.
14 // It can also simplify the logic of SeparateConstOffsetFromGEP.
15 //
16 // There are many optimizations we can perform in the domain of SLSR. This file
17 // for now contains only an initial step. Specifically, we look for strength
18 // reduction candidates in the following forms:
19 //
20 // Form 1: B + i * S
21 // Form 2: (B + i) * S
22 // Form 3: &B[i * S]
23 //
24 // where S is an integer variable, and i is a constant integer. If we found two
25 // candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
26 // in a simpler way with respect to S1. For example,
27 //
28 // S1: X = B + i * S
29 // S2: Y = B + i' * S   => X + (i' - i) * S
30 //
31 // S1: X = (B + i) * S
32 // S2: Y = (B + i') * S => X + (i' - i) * S
33 //
34 // S1: X = &B[i * S]
35 // S2: Y = &B[i' * S]   => &X[(i' - i) * S]
36 //
37 // Note: (i' - i) * S is folded to the extent possible.
38 //
39 // This rewriting is in general a good idea. The code patterns we focus on
40 // usually come from loop unrolling, so (i' - i) * S is likely the same
41 // across iterations and can be reused. When that happens, the optimized form
42 // takes only one add starting from the second iteration.
43 //
44 // When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
45 // multiple bases, we choose to rewrite S2 with respect to its "immediate"
46 // basis, the basis that is the closest ancestor in the dominator tree.
47 //
48 // TODO:
49 //
50 // - Floating point arithmetics when fast math is enabled.
51 //
52 // - SLSR may decrease ILP at the architecture level. Targets that are very
53 //   sensitive to ILP may want to disable it. Having SLSR to consider ILP is
54 //   left as future work.
55 //
56 // - When (i' - i) is constant but i and i' are not, we could still perform
57 //   SLSR.
58 #include <vector>
59
60 #include "llvm/ADT/DenseSet.h"
61 #include "llvm/ADT/FoldingSet.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/TargetTransformInfo.h"
64 #include "llvm/Analysis/ValueTracking.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/Dominators.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Transforms/Scalar.h"
72 #include "llvm/Transforms/Utils/Local.h"
73
74 using namespace llvm;
75 using namespace PatternMatch;
76
77 namespace {
78
79 class StraightLineStrengthReduce : public FunctionPass {
80 public:
81   // SLSR candidate. Such a candidate must be in one of the forms described in
82   // the header comments.
83   struct Candidate : public ilist_node<Candidate> {
84     enum Kind {
85       Invalid, // reserved for the default constructor
86       Add,     // B + i * S
87       Mul,     // (B + i) * S
88       GEP,     // &B[..][i * S][..]
89     };
90
91     Candidate()
92         : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
93           Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
94     Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
95               Instruction *I)
96         : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
97           Basis(nullptr) {}
98     Kind CandidateKind;
99     const SCEV *Base;
100     // Note that Index and Stride of a GEP candidate do not necessarily have the
101     // same integer type. In that case, during rewriting, Stride will be
102     // sign-extended or truncated to Index's type.
103     ConstantInt *Index;
104     Value *Stride;
105     // The instruction this candidate corresponds to. It helps us to rewrite a
106     // candidate with respect to its immediate basis. Note that one instruction
107     // can correspond to multiple candidates depending on how you associate the
108     // expression. For instance,
109     //
110     // (a + 1) * (b + 2)
111     //
112     // can be treated as
113     //
114     // <Base: a, Index: 1, Stride: b + 2>
115     //
116     // or
117     //
118     // <Base: b, Index: 2, Stride: a + 1>
119     Instruction *Ins;
120     // Points to the immediate basis of this candidate, or nullptr if we cannot
121     // find any basis for this candidate.
122     Candidate *Basis;
123   };
124
125   static char ID;
126
127   StraightLineStrengthReduce()
128       : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
129     initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
130   }
131
132   void getAnalysisUsage(AnalysisUsage &AU) const override {
133     AU.addRequired<DominatorTreeWrapperPass>();
134     AU.addRequired<ScalarEvolution>();
135     AU.addRequired<TargetTransformInfoWrapperPass>();
136     // We do not modify the shape of the CFG.
137     AU.setPreservesCFG();
138   }
139
140   bool doInitialization(Module &M) override {
141     DL = &M.getDataLayout();
142     return false;
143   }
144
145   bool runOnFunction(Function &F) override;
146
147 private:
148   // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
149   // share the same base and stride.
150   bool isBasisFor(const Candidate &Basis, const Candidate &C);
151   // Returns whether the candidate can be folded into an addressing mode.
152   bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
153                   const DataLayout *DL);
154   // Returns true if C is already in a simplest form and not worth being
155   // rewritten.
156   bool isSimplestForm(const Candidate &C);
157   // Checks whether I is in a candidate form. If so, adds all the matching forms
158   // to Candidates, and tries to find the immediate basis for each of them.
159   void allocateCandidatesAndFindBasis(Instruction *I);
160   // Allocate candidates and find bases for Add instructions.
161   void allocateCandidatesAndFindBasisForAdd(Instruction *I);
162   // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
163   // candidate.
164   void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
165                                             Instruction *I);
166   // Allocate candidates and find bases for Mul instructions.
167   void allocateCandidatesAndFindBasisForMul(Instruction *I);
168   // Splits LHS into Base + Index and, if succeeds, calls
169   // allocateCandidatesAndFindBasis.
170   void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
171                                             Instruction *I);
172   // Allocate candidates and find bases for GetElementPtr instructions.
173   void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
174   // A helper function that scales Idx with ElementSize before invoking
175   // allocateCandidatesAndFindBasis.
176   void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
177                                             Value *S, uint64_t ElementSize,
178                                             Instruction *I);
179   // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
180   // basis.
181   void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
182                                       ConstantInt *Idx, Value *S,
183                                       Instruction *I);
184   // Rewrites candidate C with respect to Basis.
185   void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
186   // A helper function that factors ArrayIdx to a product of a stride and a
187   // constant index, and invokes allocateCandidatesAndFindBasis with the
188   // factorings.
189   void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
190                         GetElementPtrInst *GEP);
191   // Emit code that computes the "bump" from Basis to C. If the candidate is a
192   // GEP and the bump is not divisible by the element size of the GEP, this
193   // function sets the BumpWithUglyGEP flag to notify its caller to bump the
194   // basis using an ugly GEP.
195   static Value *emitBump(const Candidate &Basis, const Candidate &C,
196                          IRBuilder<> &Builder, const DataLayout *DL,
197                          bool &BumpWithUglyGEP);
198
199   const DataLayout *DL;
200   DominatorTree *DT;
201   ScalarEvolution *SE;
202   TargetTransformInfo *TTI;
203   ilist<Candidate> Candidates;
204   // Temporarily holds all instructions that are unlinked (but not deleted) by
205   // rewriteCandidateWithBasis. These instructions will be actually removed
206   // after all rewriting finishes.
207   std::vector<Instruction *> UnlinkedInstructions;
208 };
209 }  // anonymous namespace
210
211 char StraightLineStrengthReduce::ID = 0;
212 INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
213                       "Straight line strength reduction", false, false)
214 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
215 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
216 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
217 INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
218                     "Straight line strength reduction", false, false)
219
220 FunctionPass *llvm::createStraightLineStrengthReducePass() {
221   return new StraightLineStrengthReduce();
222 }
223
224 bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
225                                             const Candidate &C) {
226   return (Basis.Ins != C.Ins && // skip the same instruction
227           // Basis must dominate C in order to rewrite C with respect to Basis.
228           DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
229           // They share the same base, stride, and candidate kind.
230           Basis.Base == C.Base &&
231           Basis.Stride == C.Stride &&
232           Basis.CandidateKind == C.CandidateKind);
233 }
234
235 static bool isGEPFoldable(GetElementPtrInst *GEP,
236                           const TargetTransformInfo *TTI,
237                           const DataLayout *DL) {
238   GlobalVariable *BaseGV = nullptr;
239   int64_t BaseOffset = 0;
240   bool HasBaseReg = false;
241   int64_t Scale = 0;
242
243   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
244     BaseGV = GV;
245   else
246     HasBaseReg = true;
247
248   gep_type_iterator GTI = gep_type_begin(GEP);
249   for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
250     if (isa<SequentialType>(*GTI)) {
251       int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
252       if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
253         BaseOffset += ConstIdx->getSExtValue() * ElementSize;
254       } else {
255         // Needs scale register.
256         if (Scale != 0) {
257           // No addressing mode takes two scale registers.
258           return false;
259         }
260         Scale = ElementSize;
261       }
262     } else {
263       StructType *STy = cast<StructType>(*GTI);
264       uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
265       BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
266     }
267   }
268
269   unsigned AddrSpace = GEP->getPointerAddressSpace();
270   return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
271                                     BaseOffset, HasBaseReg, Scale, AddrSpace);
272 }
273
274 // Returns whether (Base + Index * Stride) can be folded to an addressing mode.
275 static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
276                           TargetTransformInfo *TTI) {
277   return TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
278                                     Index->getSExtValue());
279 }
280
281 bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
282                                             TargetTransformInfo *TTI,
283                                             const DataLayout *DL) {
284   if (C.CandidateKind == Candidate::Add)
285     return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
286   if (C.CandidateKind == Candidate::GEP)
287     return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI, DL);
288   return false;
289 }
290
291 // Returns true if GEP has zero or one non-zero index.
292 static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
293   unsigned NumNonZeroIndices = 0;
294   for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
295     ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
296     if (ConstIdx == nullptr || !ConstIdx->isZero())
297       ++NumNonZeroIndices;
298   }
299   return NumNonZeroIndices <= 1;
300 }
301
302 bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
303   if (C.CandidateKind == Candidate::Add) {
304     // B + 1 * S or B + (-1) * S
305     return C.Index->isOne() || C.Index->isMinusOne();
306   }
307   if (C.CandidateKind == Candidate::Mul) {
308     // (B + 0) * S
309     return C.Index->isZero();
310   }
311   if (C.CandidateKind == Candidate::GEP) {
312     // (char*)B + S or (char*)B - S
313     return ((C.Index->isOne() || C.Index->isMinusOne()) &&
314             hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
315   }
316   return false;
317 }
318
319 // TODO: We currently implement an algorithm whose time complexity is linear in
320 // the number of existing candidates. However, we could do better by using
321 // ScopedHashTable. Specifically, while traversing the dominator tree, we could
322 // maintain all the candidates that dominate the basic block being traversed in
323 // a ScopedHashTable. This hash table is indexed by the base and the stride of
324 // a candidate. Therefore, finding the immediate basis of a candidate boils down
325 // to one hash-table look up.
326 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
327     Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
328     Instruction *I) {
329   Candidate C(CT, B, Idx, S, I);
330   // SLSR can complicate an instruction in two cases:
331   //
332   // 1. If we can fold I into an addressing mode, computing I is likely free or
333   // takes only one instruction.
334   //
335   // 2. I is already in a simplest form. For example, when
336   //      X = B + 8 * S
337   //      Y = B + S,
338   //    rewriting Y to X - 7 * S is probably a bad idea.
339   //
340   // In the above cases, we still add I to the candidate list so that I can be
341   // the basis of other candidates, but we leave I's basis blank so that I
342   // won't be rewritten.
343   if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
344     // Try to compute the immediate basis of C.
345     unsigned NumIterations = 0;
346     // Limit the scan radius to avoid running in quadratice time.
347     static const unsigned MaxNumIterations = 50;
348     for (auto Basis = Candidates.rbegin();
349          Basis != Candidates.rend() && NumIterations < MaxNumIterations;
350          ++Basis, ++NumIterations) {
351       if (isBasisFor(*Basis, C)) {
352         C.Basis = &(*Basis);
353         break;
354       }
355     }
356   }
357   // Regardless of whether we find a basis for C, we need to push C to the
358   // candidate list so that it can be the basis of other candidates.
359   Candidates.push_back(C);
360 }
361
362 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
363     Instruction *I) {
364   switch (I->getOpcode()) {
365   case Instruction::Add:
366     allocateCandidatesAndFindBasisForAdd(I);
367     break;
368   case Instruction::Mul:
369     allocateCandidatesAndFindBasisForMul(I);
370     break;
371   case Instruction::GetElementPtr:
372     allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
373     break;
374   }
375 }
376
377 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
378     Instruction *I) {
379   // Try matching B + i * S.
380   if (!isa<IntegerType>(I->getType()))
381     return;
382
383   assert(I->getNumOperands() == 2 && "isn't I an add?");
384   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
385   allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
386   if (LHS != RHS)
387     allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
388 }
389
390 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
391     Value *LHS, Value *RHS, Instruction *I) {
392   Value *S = nullptr;
393   ConstantInt *Idx = nullptr;
394   if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
395     // I = LHS + RHS = LHS + Idx * S
396     allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
397   } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
398     // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
399     APInt One(Idx->getBitWidth(), 1);
400     Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
401     allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
402   } else {
403     // At least, I = LHS + 1 * RHS
404     ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
405     allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
406                                    I);
407   }
408 }
409
410 // Returns true if A matches B + C where C is constant.
411 static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
412   return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
413           match(A, m_Add(m_ConstantInt(C), m_Value(B))));
414 }
415
416 // Returns true if A matches B | C where C is constant.
417 static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
418   return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
419           match(A, m_Or(m_ConstantInt(C), m_Value(B))));
420 }
421
422 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
423     Value *LHS, Value *RHS, Instruction *I) {
424   Value *B = nullptr;
425   ConstantInt *Idx = nullptr;
426   if (matchesAdd(LHS, B, Idx)) {
427     // If LHS is in the form of "Base + Index", then I is in the form of
428     // "(Base + Index) * RHS".
429     allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
430   } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
431     // If LHS is in the form of "Base | Index" and Base and Index have no common
432     // bits set, then
433     //   Base | Index = Base + Index
434     // and I is thus in the form of "(Base + Index) * RHS".
435     allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
436   } else {
437     // Otherwise, at least try the form (LHS + 0) * RHS.
438     ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
439     allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
440                                    I);
441   }
442 }
443
444 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
445     Instruction *I) {
446   // Try matching (B + i) * S.
447   // TODO: we could extend SLSR to float and vector types.
448   if (!isa<IntegerType>(I->getType()))
449     return;
450
451   assert(I->getNumOperands() == 2 && "isn't I a mul?");
452   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
453   allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
454   if (LHS != RHS) {
455     // Symmetrically, try to split RHS to Base + Index.
456     allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
457   }
458 }
459
460 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
461     const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
462     Instruction *I) {
463   // I = B + sext(Idx *nsw S) * ElementSize
464   //   = B + (sext(Idx) * sext(S)) * ElementSize
465   //   = B + (sext(Idx) * ElementSize) * sext(S)
466   // Casting to IntegerType is safe because we skipped vector GEPs.
467   IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
468   ConstantInt *ScaledIdx = ConstantInt::get(
469       IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
470   allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
471 }
472
473 void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
474                                                   const SCEV *Base,
475                                                   uint64_t ElementSize,
476                                                   GetElementPtrInst *GEP) {
477   // At least, ArrayIdx = ArrayIdx *nsw 1.
478   allocateCandidatesAndFindBasisForGEP(
479       Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
480       ArrayIdx, ElementSize, GEP);
481   Value *LHS = nullptr;
482   ConstantInt *RHS = nullptr;
483   // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
484   // itself. This would allow us to handle the shl case for free. However,
485   // matching SCEVs has two issues:
486   //
487   // 1. this would complicate rewriting because the rewriting procedure
488   // would have to translate SCEVs back to IR instructions. This translation
489   // is difficult when LHS is further evaluated to a composite SCEV.
490   //
491   // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
492   // to strip nsw/nuw flags which are critical for SLSR to trace into
493   // sext'ed multiplication.
494   if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
495     // SLSR is currently unsafe if i * S may overflow.
496     // GEP = Base + sext(LHS *nsw RHS) * ElementSize
497     allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
498   } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
499     // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
500     //     = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
501     APInt One(RHS->getBitWidth(), 1);
502     ConstantInt *PowerOf2 =
503         ConstantInt::get(RHS->getContext(), One << RHS->getValue());
504     allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
505   }
506 }
507
508 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
509     GetElementPtrInst *GEP) {
510   // TODO: handle vector GEPs
511   if (GEP->getType()->isVectorTy())
512     return;
513
514   SmallVector<const SCEV *, 4> IndexExprs;
515   for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
516     IndexExprs.push_back(SE->getSCEV(*I));
517
518   gep_type_iterator GTI = gep_type_begin(GEP);
519   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
520     if (!isa<SequentialType>(*GTI++))
521       continue;
522
523     const SCEV *OrigIndexExpr = IndexExprs[I - 1];
524     IndexExprs[I - 1] = SE->getConstant(OrigIndexExpr->getType(), 0);
525
526     // The base of this candidate is GEP's base plus the offsets of all
527     // indices except this current one.
528     const SCEV *BaseExpr = SE->getGEPExpr(GEP->getSourceElementType(),
529                                           SE->getSCEV(GEP->getPointerOperand()),
530                                           IndexExprs, GEP->isInBounds());
531     Value *ArrayIdx = GEP->getOperand(I);
532     uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
533     factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
534     // When ArrayIdx is the sext of a value, we try to factor that value as
535     // well.  Handling this case is important because array indices are
536     // typically sign-extended to the pointer size.
537     Value *TruncatedArrayIdx = nullptr;
538     if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))))
539       factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
540
541     IndexExprs[I - 1] = OrigIndexExpr;
542   }
543 }
544
545 // A helper function that unifies the bitwidth of A and B.
546 static void unifyBitWidth(APInt &A, APInt &B) {
547   if (A.getBitWidth() < B.getBitWidth())
548     A = A.sext(B.getBitWidth());
549   else if (A.getBitWidth() > B.getBitWidth())
550     B = B.sext(A.getBitWidth());
551 }
552
553 Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
554                                             const Candidate &C,
555                                             IRBuilder<> &Builder,
556                                             const DataLayout *DL,
557                                             bool &BumpWithUglyGEP) {
558   APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
559   unifyBitWidth(Idx, BasisIdx);
560   APInt IndexOffset = Idx - BasisIdx;
561
562   BumpWithUglyGEP = false;
563   if (Basis.CandidateKind == Candidate::GEP) {
564     APInt ElementSize(
565         IndexOffset.getBitWidth(),
566         DL->getTypeAllocSize(
567             cast<GetElementPtrInst>(Basis.Ins)->getType()->getElementType()));
568     APInt Q, R;
569     APInt::sdivrem(IndexOffset, ElementSize, Q, R);
570     if (R.getSExtValue() == 0)
571       IndexOffset = Q;
572     else
573       BumpWithUglyGEP = true;
574   }
575
576   // Compute Bump = C - Basis = (i' - i) * S.
577   // Common case 1: if (i' - i) is 1, Bump = S.
578   if (IndexOffset.getSExtValue() == 1)
579     return C.Stride;
580   // Common case 2: if (i' - i) is -1, Bump = -S.
581   if (IndexOffset.getSExtValue() == -1)
582     return Builder.CreateNeg(C.Stride);
583
584   // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
585   // have different bit widths.
586   IntegerType *DeltaType =
587       IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
588   Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
589   if (IndexOffset.isPowerOf2()) {
590     // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
591     ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
592     return Builder.CreateShl(ExtendedStride, Exponent);
593   }
594   if ((-IndexOffset).isPowerOf2()) {
595     // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
596     ConstantInt *Exponent =
597         ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
598     return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
599   }
600   Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
601   return Builder.CreateMul(ExtendedStride, Delta);
602 }
603
604 void StraightLineStrengthReduce::rewriteCandidateWithBasis(
605     const Candidate &C, const Candidate &Basis) {
606   assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
607          C.Stride == Basis.Stride);
608   // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
609   // basis of a candidate cannot be unlinked before the candidate.
610   assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
611
612   // An instruction can correspond to multiple candidates. Therefore, instead of
613   // simply deleting an instruction when we rewrite it, we mark its parent as
614   // nullptr (i.e. unlink it) so that we can skip the candidates whose
615   // instruction is already rewritten.
616   if (!C.Ins->getParent())
617     return;
618
619   IRBuilder<> Builder(C.Ins);
620   bool BumpWithUglyGEP;
621   Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
622   Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
623   switch (C.CandidateKind) {
624   case Candidate::Add:
625   case Candidate::Mul:
626     // C = Basis + Bump
627     if (BinaryOperator::isNeg(Bump)) {
628       // If Bump is a neg instruction, emit C = Basis - (-Bump).
629       Reduced =
630           Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
631       // We only use the negative argument of Bump, and Bump itself may be
632       // trivially dead.
633       RecursivelyDeleteTriviallyDeadInstructions(Bump);
634     } else {
635       Reduced = Builder.CreateAdd(Basis.Ins, Bump);
636     }
637     break;
638   case Candidate::GEP:
639     {
640       Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
641       bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
642       if (BumpWithUglyGEP) {
643         // C = (char *)Basis + Bump
644         unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
645         Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
646         Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
647         if (InBounds)
648           Reduced =
649               Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
650         else
651           Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
652         Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
653       } else {
654         // C = gep Basis, Bump
655         // Canonicalize bump to pointer size.
656         Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
657         if (InBounds)
658           Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
659         else
660           Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
661       }
662     }
663     break;
664   default:
665     llvm_unreachable("C.CandidateKind is invalid");
666   };
667   Reduced->takeName(C.Ins);
668   C.Ins->replaceAllUsesWith(Reduced);
669   // Unlink C.Ins so that we can skip other candidates also corresponding to
670   // C.Ins. The actual deletion is postponed to the end of runOnFunction.
671   C.Ins->removeFromParent();
672   UnlinkedInstructions.push_back(C.Ins);
673 }
674
675 bool StraightLineStrengthReduce::runOnFunction(Function &F) {
676   if (skipOptnoneFunction(F))
677     return false;
678
679   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
680   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
681   SE = &getAnalysis<ScalarEvolution>();
682   // Traverse the dominator tree in the depth-first order. This order makes sure
683   // all bases of a candidate are in Candidates when we process it.
684   for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
685        node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
686     for (auto &I : *node->getBlock())
687       allocateCandidatesAndFindBasis(&I);
688   }
689
690   // Rewrite candidates in the reverse depth-first order. This order makes sure
691   // a candidate being rewritten is not a basis for any other candidate.
692   while (!Candidates.empty()) {
693     const Candidate &C = Candidates.back();
694     if (C.Basis != nullptr) {
695       rewriteCandidateWithBasis(C, *C.Basis);
696     }
697     Candidates.pop_back();
698   }
699
700   // Delete all unlink instructions.
701   for (auto *UnlinkedInst : UnlinkedInstructions) {
702     for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
703       Value *Op = UnlinkedInst->getOperand(I);
704       UnlinkedInst->setOperand(I, nullptr);
705       RecursivelyDeleteTriviallyDeadInstructions(Op);
706     }
707     delete UnlinkedInst;
708   }
709   bool Ret = !UnlinkedInstructions.empty();
710   UnlinkedInstructions.clear();
711   return Ret;
712 }