[PM] Change the core design of the TTI analysis to use a polymorphic
[oota-llvm.git] / lib / Transforms / Scalar / SeparateConstOffsetFromGEP.cpp
1 //===-- SeparateConstOffsetFromGEP.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 // Loop unrolling may create many similar GEPs for array accesses.
11 // e.g., a 2-level loop
12 //
13 // float a[32][32]; // global variable
14 //
15 // for (int i = 0; i < 2; ++i) {
16 //   for (int j = 0; j < 2; ++j) {
17 //     ...
18 //     ... = a[x + i][y + j];
19 //     ...
20 //   }
21 // }
22 //
23 // will probably be unrolled to:
24 //
25 // gep %a, 0, %x, %y; load
26 // gep %a, 0, %x, %y + 1; load
27 // gep %a, 0, %x + 1, %y; load
28 // gep %a, 0, %x + 1, %y + 1; load
29 //
30 // LLVM's GVN does not use partial redundancy elimination yet, and is thus
31 // unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
32 // significant slowdown in targets with limited addressing modes. For instance,
33 // because the PTX target does not support the reg+reg addressing mode, the
34 // NVPTX backend emits PTX code that literally computes the pointer address of
35 // each GEP, wasting tons of registers. It emits the following PTX for the
36 // first load and similar PTX for other loads.
37 //
38 // mov.u32         %r1, %x;
39 // mov.u32         %r2, %y;
40 // mul.wide.u32    %rl2, %r1, 128;
41 // mov.u64         %rl3, a;
42 // add.s64         %rl4, %rl3, %rl2;
43 // mul.wide.u32    %rl5, %r2, 4;
44 // add.s64         %rl6, %rl4, %rl5;
45 // ld.global.f32   %f1, [%rl6];
46 //
47 // To reduce the register pressure, the optimization implemented in this file
48 // merges the common part of a group of GEPs, so we can compute each pointer
49 // address by adding a simple offset to the common part, saving many registers.
50 //
51 // It works by splitting each GEP into a variadic base and a constant offset.
52 // The variadic base can be computed once and reused by multiple GEPs, and the
53 // constant offsets can be nicely folded into the reg+immediate addressing mode
54 // (supported by most targets) without using any extra register.
55 //
56 // For instance, we transform the four GEPs and four loads in the above example
57 // into:
58 //
59 // base = gep a, 0, x, y
60 // load base
61 // laod base + 1  * sizeof(float)
62 // load base + 32 * sizeof(float)
63 // load base + 33 * sizeof(float)
64 //
65 // Given the transformed IR, a backend that supports the reg+immediate
66 // addressing mode can easily fold the pointer arithmetics into the loads. For
67 // example, the NVPTX backend can easily fold the pointer arithmetics into the
68 // ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
69 //
70 // mov.u32         %r1, %tid.x;
71 // mov.u32         %r2, %tid.y;
72 // mul.wide.u32    %rl2, %r1, 128;
73 // mov.u64         %rl3, a;
74 // add.s64         %rl4, %rl3, %rl2;
75 // mul.wide.u32    %rl5, %r2, 4;
76 // add.s64         %rl6, %rl4, %rl5;
77 // ld.global.f32   %f1, [%rl6]; // so far the same as unoptimized PTX
78 // ld.global.f32   %f2, [%rl6+4]; // much better
79 // ld.global.f32   %f3, [%rl6+128]; // much better
80 // ld.global.f32   %f4, [%rl6+132]; // much better
81 //
82 // Another improvement enabled by the LowerGEP flag is to lower a GEP with
83 // multiple indices to either multiple GEPs with a single index or arithmetic
84 // operations (depending on whether the target uses alias analysis in codegen).
85 // Such transformation can have following benefits:
86 // (1) It can always extract constants in the indices of structure type.
87 // (2) After such Lowering, there are more optimization opportunities such as
88 //     CSE, LICM and CGP.
89 //
90 // E.g. The following GEPs have multiple indices:
91 //  BB1:
92 //    %p = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 3
93 //    load %p
94 //    ...
95 //  BB2:
96 //    %p2 = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 2
97 //    load %p2
98 //    ...
99 //
100 // We can not do CSE for to the common part related to index "i64 %i". Lowering
101 // GEPs can achieve such goals.
102 // If the target does not use alias analysis in codegen, this pass will
103 // lower a GEP with multiple indices into arithmetic operations:
104 //  BB1:
105 //    %1 = ptrtoint [10 x %struct]* %ptr to i64    ; CSE opportunity
106 //    %2 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
107 //    %3 = add i64 %1, %2                          ; CSE opportunity
108 //    %4 = mul i64 %j1, length_of_struct
109 //    %5 = add i64 %3, %4
110 //    %6 = add i64 %3, struct_field_3              ; Constant offset
111 //    %p = inttoptr i64 %6 to i32*
112 //    load %p
113 //    ...
114 //  BB2:
115 //    %7 = ptrtoint [10 x %struct]* %ptr to i64    ; CSE opportunity
116 //    %8 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
117 //    %9 = add i64 %7, %8                          ; CSE opportunity
118 //    %10 = mul i64 %j2, length_of_struct
119 //    %11 = add i64 %9, %10
120 //    %12 = add i64 %11, struct_field_2            ; Constant offset
121 //    %p = inttoptr i64 %12 to i32*
122 //    load %p2
123 //    ...
124 //
125 // If the target uses alias analysis in codegen, this pass will lower a GEP
126 // with multiple indices into multiple GEPs with a single index:
127 //  BB1:
128 //    %1 = bitcast [10 x %struct]* %ptr to i8*     ; CSE opportunity
129 //    %2 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
130 //    %3 = getelementptr i8* %1, i64 %2            ; CSE opportunity
131 //    %4 = mul i64 %j1, length_of_struct
132 //    %5 = getelementptr i8* %3, i64 %4
133 //    %6 = getelementptr i8* %5, struct_field_3    ; Constant offset
134 //    %p = bitcast i8* %6 to i32*
135 //    load %p
136 //    ...
137 //  BB2:
138 //    %7 = bitcast [10 x %struct]* %ptr to i8*     ; CSE opportunity
139 //    %8 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
140 //    %9 = getelementptr i8* %7, i64 %8            ; CSE opportunity
141 //    %10 = mul i64 %j2, length_of_struct
142 //    %11 = getelementptr i8* %9, i64 %10
143 //    %12 = getelementptr i8* %11, struct_field_2  ; Constant offset
144 //    %p2 = bitcast i8* %12 to i32*
145 //    load %p2
146 //    ...
147 //
148 // Lowering GEPs can also benefit other passes such as LICM and CGP.
149 // LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
150 // indices if one of the index is variant. If we lower such GEP into invariant
151 // parts and variant parts, LICM can hoist/sink those invariant parts.
152 // CGP (CodeGen Prepare) tries to sink address calculations that match the
153 // target's addressing modes. A GEP with multiple indices may not match and will
154 // not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
155 // them. So we end up with a better addressing mode.
156 //
157 //===----------------------------------------------------------------------===//
158
159 #include "llvm/Analysis/TargetTransformInfo.h"
160 #include "llvm/Analysis/ValueTracking.h"
161 #include "llvm/IR/Constants.h"
162 #include "llvm/IR/DataLayout.h"
163 #include "llvm/IR/Instructions.h"
164 #include "llvm/IR/LLVMContext.h"
165 #include "llvm/IR/Module.h"
166 #include "llvm/IR/Operator.h"
167 #include "llvm/Support/CommandLine.h"
168 #include "llvm/Support/raw_ostream.h"
169 #include "llvm/Transforms/Scalar.h"
170 #include "llvm/Target/TargetMachine.h"
171 #include "llvm/Target/TargetSubtargetInfo.h"
172 #include "llvm/IR/IRBuilder.h"
173
174 using namespace llvm;
175
176 static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
177     "disable-separate-const-offset-from-gep", cl::init(false),
178     cl::desc("Do not separate the constant offset from a GEP instruction"),
179     cl::Hidden);
180
181 namespace {
182
183 /// \brief A helper class for separating a constant offset from a GEP index.
184 ///
185 /// In real programs, a GEP index may be more complicated than a simple addition
186 /// of something and a constant integer which can be trivially splitted. For
187 /// example, to split ((a << 3) | 5) + b, we need to search deeper for the
188 /// constant offset, so that we can separate the index to (a << 3) + b and 5.
189 ///
190 /// Therefore, this class looks into the expression that computes a given GEP
191 /// index, and tries to find a constant integer that can be hoisted to the
192 /// outermost level of the expression as an addition. Not every constant in an
193 /// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
194 /// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
195 /// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
196 class ConstantOffsetExtractor {
197  public:
198   /// Extracts a constant offset from the given GEP index. It returns the
199   /// new index representing the remainder (equal to the original index minus
200   /// the constant offset), or nullptr if we cannot extract a constant offset.
201   /// \p Idx    The given GEP index
202   /// \p DL     The datalayout of the module
203   /// \p GEP    The given GEP
204   static Value *Extract(Value *Idx, const DataLayout *DL,
205                         GetElementPtrInst *GEP);
206   /// Looks for a constant offset from the given GEP index without extracting
207   /// it. It returns the numeric value of the extracted constant offset (0 if
208   /// failed). The meaning of the arguments are the same as Extract.
209   static int64_t Find(Value *Idx, const DataLayout *DL, GetElementPtrInst *GEP);
210
211  private:
212   ConstantOffsetExtractor(const DataLayout *Layout, Instruction *InsertionPt)
213       : DL(Layout), IP(InsertionPt) {}
214   /// Searches the expression that computes V for a non-zero constant C s.t.
215   /// V can be reassociated into the form V' + C. If the searching is
216   /// successful, returns C and update UserChain as a def-use chain from C to V;
217   /// otherwise, UserChain is empty.
218   ///
219   /// \p V            The given expression
220   /// \p SignExtended Whether V will be sign-extended in the computation of the
221   ///                 GEP index
222   /// \p ZeroExtended Whether V will be zero-extended in the computation of the
223   ///                 GEP index
224   /// \p NonNegative  Whether V is guaranteed to be non-negative. For example,
225   ///                 an index of an inbounds GEP is guaranteed to be
226   ///                 non-negative. Levaraging this, we can better split
227   ///                 inbounds GEPs.
228   APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
229   /// A helper function to look into both operands of a binary operator.
230   APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
231                             bool ZeroExtended);
232   /// After finding the constant offset C from the GEP index I, we build a new
233   /// index I' s.t. I' + C = I. This function builds and returns the new
234   /// index I' according to UserChain produced by function "find".
235   ///
236   /// The building conceptually takes two steps:
237   /// 1) iteratively distribute s/zext towards the leaves of the expression tree
238   /// that computes I
239   /// 2) reassociate the expression tree to the form I' + C.
240   ///
241   /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
242   /// sext to a, b and 5 so that we have
243   ///   sext(a) + (sext(b) + 5).
244   /// Then, we reassociate it to
245   ///   (sext(a) + sext(b)) + 5.
246   /// Given this form, we know I' is sext(a) + sext(b).
247   Value *rebuildWithoutConstOffset();
248   /// After the first step of rebuilding the GEP index without the constant
249   /// offset, distribute s/zext to the operands of all operators in UserChain.
250   /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
251   /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
252   ///
253   /// The function also updates UserChain to point to new subexpressions after
254   /// distributing s/zext. e.g., the old UserChain of the above example is
255   /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
256   /// and the new UserChain is
257   /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
258   ///   zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
259   ///
260   /// \p ChainIndex The index to UserChain. ChainIndex is initially
261   ///               UserChain.size() - 1, and is decremented during
262   ///               the recursion.
263   Value *distributeExtsAndCloneChain(unsigned ChainIndex);
264   /// Reassociates the GEP index to the form I' + C and returns I'.
265   Value *removeConstOffset(unsigned ChainIndex);
266   /// A helper function to apply ExtInsts, a list of s/zext, to value V.
267   /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
268   /// returns "sext i32 (zext i16 V to i32) to i64".
269   Value *applyExts(Value *V);
270
271   /// Returns true if LHS and RHS have no bits in common, i.e., LHS | RHS == 0.
272   bool NoCommonBits(Value *LHS, Value *RHS) const;
273   /// Computes which bits are known to be one or zero.
274   /// \p KnownOne Mask of all bits that are known to be one.
275   /// \p KnownZero Mask of all bits that are known to be zero.
276   void ComputeKnownBits(Value *V, APInt &KnownOne, APInt &KnownZero) const;
277   /// A helper function that returns whether we can trace into the operands
278   /// of binary operator BO for a constant offset.
279   ///
280   /// \p SignExtended Whether BO is surrounded by sext
281   /// \p ZeroExtended Whether BO is surrounded by zext
282   /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
283   ///                array index.
284   bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
285                     bool NonNegative);
286
287   /// The path from the constant offset to the old GEP index. e.g., if the GEP
288   /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
289   /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
290   /// UserChain[2] will be the entire expression "a * b + (c + 5)".
291   ///
292   /// This path helps to rebuild the new GEP index.
293   SmallVector<User *, 8> UserChain;
294   /// A data structure used in rebuildWithoutConstOffset. Contains all
295   /// sext/zext instructions along UserChain.
296   SmallVector<CastInst *, 16> ExtInsts;
297   /// The data layout of the module. Used in ComputeKnownBits.
298   const DataLayout *DL;
299   Instruction *IP;  /// Insertion position of cloned instructions.
300 };
301
302 /// \brief A pass that tries to split every GEP in the function into a variadic
303 /// base and a constant offset. It is a FunctionPass because searching for the
304 /// constant offset may inspect other basic blocks.
305 class SeparateConstOffsetFromGEP : public FunctionPass {
306  public:
307   static char ID;
308   SeparateConstOffsetFromGEP(const TargetMachine *TM = nullptr,
309                              bool LowerGEP = false)
310       : FunctionPass(ID), TM(TM), LowerGEP(LowerGEP) {
311     initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
312   }
313
314   void getAnalysisUsage(AnalysisUsage &AU) const override {
315     AU.addRequired<DataLayoutPass>();
316     AU.addRequired<TargetTransformInfoWrapperPass>();
317   }
318
319   bool doInitialization(Module &M) override {
320     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
321     if (DLP == nullptr)
322       report_fatal_error("data layout missing");
323     DL = &DLP->getDataLayout();
324     return false;
325   }
326
327   bool runOnFunction(Function &F) override;
328
329  private:
330   /// Tries to split the given GEP into a variadic base and a constant offset,
331   /// and returns true if the splitting succeeds.
332   bool splitGEP(GetElementPtrInst *GEP);
333   /// Lower a GEP with multiple indices into multiple GEPs with a single index.
334   /// Function splitGEP already split the original GEP into a variadic part and
335   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
336   /// variadic part into a set of GEPs with a single index and applies
337   /// AccumulativeByteOffset to it.
338   /// \p Variadic                  The variadic part of the original GEP.
339   /// \p AccumulativeByteOffset    The constant offset.
340   void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
341                               int64_t AccumulativeByteOffset);
342   /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
343   /// Function splitGEP already split the original GEP into a variadic part and
344   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
345   /// variadic part into a set of arithmetic operations and applies
346   /// AccumulativeByteOffset to it.
347   /// \p Variadic                  The variadic part of the original GEP.
348   /// \p AccumulativeByteOffset    The constant offset.
349   void lowerToArithmetics(GetElementPtrInst *Variadic,
350                           int64_t AccumulativeByteOffset);
351   /// Finds the constant offset within each index and accumulates them. If
352   /// LowerGEP is true, it finds in indices of both sequential and structure
353   /// types, otherwise it only finds in sequential indices. The output
354   /// NeedsExtraction indicates whether we successfully find a non-zero constant
355   /// offset.
356   int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
357   /// Canonicalize array indices to pointer-size integers. This helps to
358   /// simplify the logic of splitting a GEP. For example, if a + b is a
359   /// pointer-size integer, we have
360   ///   gep base, a + b = gep (gep base, a), b
361   /// However, this equality may not hold if the size of a + b is smaller than
362   /// the pointer size, because LLVM conceptually sign-extends GEP indices to
363   /// pointer size before computing the address
364   /// (http://llvm.org/docs/LangRef.html#id181).
365   ///
366   /// This canonicalization is very likely already done in clang and
367   /// instcombine. Therefore, the program will probably remain the same.
368   ///
369   /// Returns true if the module changes.
370   ///
371   /// Verified in @i32_add in split-gep.ll
372   bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
373
374   const DataLayout *DL;
375   const TargetMachine *TM;
376   /// Whether to lower a GEP with multiple indices into arithmetic operations or
377   /// multiple GEPs with a single index.
378   bool LowerGEP;
379 };
380 }  // anonymous namespace
381
382 char SeparateConstOffsetFromGEP::ID = 0;
383 INITIALIZE_PASS_BEGIN(
384     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
385     "Split GEPs to a variadic base and a constant offset for better CSE", false,
386     false)
387 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
388 INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)
389 INITIALIZE_PASS_END(
390     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
391     "Split GEPs to a variadic base and a constant offset for better CSE", false,
392     false)
393
394 FunctionPass *
395 llvm::createSeparateConstOffsetFromGEPPass(const TargetMachine *TM,
396                                            bool LowerGEP) {
397   return new SeparateConstOffsetFromGEP(TM, LowerGEP);
398 }
399
400 bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
401                                             bool ZeroExtended,
402                                             BinaryOperator *BO,
403                                             bool NonNegative) {
404   // We only consider ADD, SUB and OR, because a non-zero constant found in
405   // expressions composed of these operations can be easily hoisted as a
406   // constant offset by reassociation.
407   if (BO->getOpcode() != Instruction::Add &&
408       BO->getOpcode() != Instruction::Sub &&
409       BO->getOpcode() != Instruction::Or) {
410     return false;
411   }
412
413   Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
414   // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
415   // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
416   if (BO->getOpcode() == Instruction::Or && !NoCommonBits(LHS, RHS))
417     return false;
418
419   // In addition, tracing into BO requires that its surrounding s/zext (if
420   // any) is distributable to both operands.
421   //
422   // Suppose BO = A op B.
423   //  SignExtended | ZeroExtended | Distributable?
424   // --------------+--------------+----------------------------------
425   //       0       |      0       | true because no s/zext exists
426   //       0       |      1       | zext(BO) == zext(A) op zext(B)
427   //       1       |      0       | sext(BO) == sext(A) op sext(B)
428   //       1       |      1       | zext(sext(BO)) ==
429   //               |              |     zext(sext(A)) op zext(sext(B))
430   if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
431     // If a + b >= 0 and (a >= 0 or b >= 0), then
432     //   sext(a + b) = sext(a) + sext(b)
433     // even if the addition is not marked nsw.
434     //
435     // Leveraging this invarient, we can trace into an sext'ed inbound GEP
436     // index if the constant offset is non-negative.
437     //
438     // Verified in @sext_add in split-gep.ll.
439     if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
440       if (!ConstLHS->isNegative())
441         return true;
442     }
443     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
444       if (!ConstRHS->isNegative())
445         return true;
446     }
447   }
448
449   // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
450   // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
451   if (BO->getOpcode() == Instruction::Add ||
452       BO->getOpcode() == Instruction::Sub) {
453     if (SignExtended && !BO->hasNoSignedWrap())
454       return false;
455     if (ZeroExtended && !BO->hasNoUnsignedWrap())
456       return false;
457   }
458
459   return true;
460 }
461
462 APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
463                                                    bool SignExtended,
464                                                    bool ZeroExtended) {
465   // BO being non-negative does not shed light on whether its operands are
466   // non-negative. Clear the NonNegative flag here.
467   APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
468                               /* NonNegative */ false);
469   // If we found a constant offset in the left operand, stop and return that.
470   // This shortcut might cause us to miss opportunities of combining the
471   // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
472   // However, such cases are probably already handled by -instcombine,
473   // given this pass runs after the standard optimizations.
474   if (ConstantOffset != 0) return ConstantOffset;
475   ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
476                         /* NonNegative */ false);
477   // If U is a sub operator, negate the constant offset found in the right
478   // operand.
479   if (BO->getOpcode() == Instruction::Sub)
480     ConstantOffset = -ConstantOffset;
481   return ConstantOffset;
482 }
483
484 APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
485                                     bool ZeroExtended, bool NonNegative) {
486   // TODO(jingyue): We could trace into integer/pointer casts, such as
487   // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
488   // integers because it gives good enough results for our benchmarks.
489   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
490
491   // We cannot do much with Values that are not a User, such as an Argument.
492   User *U = dyn_cast<User>(V);
493   if (U == nullptr) return APInt(BitWidth, 0);
494
495   APInt ConstantOffset(BitWidth, 0);
496   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
497     // Hooray, we found it!
498     ConstantOffset = CI->getValue();
499   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
500     // Trace into subexpressions for more hoisting opportunities.
501     if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative)) {
502       ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
503     }
504   } else if (isa<SExtInst>(V)) {
505     ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
506                           ZeroExtended, NonNegative).sext(BitWidth);
507   } else if (isa<ZExtInst>(V)) {
508     // As an optimization, we can clear the SignExtended flag because
509     // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
510     //
511     // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
512     ConstantOffset =
513         find(U->getOperand(0), /* SignExtended */ false,
514              /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
515   }
516
517   // If we found a non-zero constant offset, add it to the path for
518   // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
519   // help this optimization.
520   if (ConstantOffset != 0)
521     UserChain.push_back(U);
522   return ConstantOffset;
523 }
524
525 Value *ConstantOffsetExtractor::applyExts(Value *V) {
526   Value *Current = V;
527   // ExtInsts is built in the use-def order. Therefore, we apply them to V
528   // in the reversed order.
529   for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
530     if (Constant *C = dyn_cast<Constant>(Current)) {
531       // If Current is a constant, apply s/zext using ConstantExpr::getCast.
532       // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
533       Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
534     } else {
535       Instruction *Ext = (*I)->clone();
536       Ext->setOperand(0, Current);
537       Ext->insertBefore(IP);
538       Current = Ext;
539     }
540   }
541   return Current;
542 }
543
544 Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
545   distributeExtsAndCloneChain(UserChain.size() - 1);
546   // Remove all nullptrs (used to be s/zext) from UserChain.
547   unsigned NewSize = 0;
548   for (auto I = UserChain.begin(), E = UserChain.end(); I != E; ++I) {
549     if (*I != nullptr) {
550       UserChain[NewSize] = *I;
551       NewSize++;
552     }
553   }
554   UserChain.resize(NewSize);
555   return removeConstOffset(UserChain.size() - 1);
556 }
557
558 Value *
559 ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
560   User *U = UserChain[ChainIndex];
561   if (ChainIndex == 0) {
562     assert(isa<ConstantInt>(U));
563     // If U is a ConstantInt, applyExts will return a ConstantInt as well.
564     return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
565   }
566
567   if (CastInst *Cast = dyn_cast<CastInst>(U)) {
568     assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
569            "We only traced into two types of CastInst: sext and zext");
570     ExtInsts.push_back(Cast);
571     UserChain[ChainIndex] = nullptr;
572     return distributeExtsAndCloneChain(ChainIndex - 1);
573   }
574
575   // Function find only trace into BinaryOperator and CastInst.
576   BinaryOperator *BO = cast<BinaryOperator>(U);
577   // OpNo = which operand of BO is UserChain[ChainIndex - 1]
578   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
579   Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
580   Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
581
582   BinaryOperator *NewBO = nullptr;
583   if (OpNo == 0) {
584     NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
585                                    BO->getName(), IP);
586   } else {
587     NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
588                                    BO->getName(), IP);
589   }
590   return UserChain[ChainIndex] = NewBO;
591 }
592
593 Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
594   if (ChainIndex == 0) {
595     assert(isa<ConstantInt>(UserChain[ChainIndex]));
596     return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
597   }
598
599   BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
600   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
601   assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
602   Value *NextInChain = removeConstOffset(ChainIndex - 1);
603   Value *TheOther = BO->getOperand(1 - OpNo);
604
605   // If NextInChain is 0 and not the LHS of a sub, we can simplify the
606   // sub-expression to be just TheOther.
607   if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
608     if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
609       return TheOther;
610   }
611
612   if (BO->getOpcode() == Instruction::Or) {
613     // Rebuild "or" as "add", because "or" may be invalid for the new
614     // epxression.
615     //
616     // For instance, given
617     //   a | (b + 5) where a and b + 5 have no common bits,
618     // we can extract 5 as the constant offset.
619     //
620     // However, reusing the "or" in the new index would give us
621     //   (a | b) + 5
622     // which does not equal a | (b + 5).
623     //
624     // Replacing the "or" with "add" is fine, because
625     //   a | (b + 5) = a + (b + 5) = (a + b) + 5
626     if (OpNo == 0) {
627       return BinaryOperator::CreateAdd(NextInChain, TheOther, BO->getName(),
628                                        IP);
629     } else {
630       return BinaryOperator::CreateAdd(TheOther, NextInChain, BO->getName(),
631                                        IP);
632     }
633   }
634
635   // We can reuse BO in this case, because the new expression shares the same
636   // instruction type and BO is used at most once.
637   assert(BO->getNumUses() <= 1 &&
638          "distributeExtsAndCloneChain clones each BinaryOperator in "
639          "UserChain, so no one should be used more than "
640          "once");
641   BO->setOperand(OpNo, NextInChain);
642   BO->setHasNoSignedWrap(false);
643   BO->setHasNoUnsignedWrap(false);
644   // Make sure it appears after all instructions we've inserted so far.
645   BO->moveBefore(IP);
646   return BO;
647 }
648
649 Value *ConstantOffsetExtractor::Extract(Value *Idx, const DataLayout *DL,
650                                         GetElementPtrInst *GEP) {
651   ConstantOffsetExtractor Extractor(DL, GEP);
652   // Find a non-zero constant offset first.
653   APInt ConstantOffset =
654       Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
655                      GEP->isInBounds());
656   if (ConstantOffset == 0)
657     return nullptr;
658   // Separates the constant offset from the GEP index.
659   return Extractor.rebuildWithoutConstOffset();
660 }
661
662 int64_t ConstantOffsetExtractor::Find(Value *Idx, const DataLayout *DL,
663       GetElementPtrInst *GEP) {
664   // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
665   return ConstantOffsetExtractor(DL, GEP)
666       .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
667             GEP->isInBounds())
668       .getSExtValue();
669 }
670
671 void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne,
672                                                APInt &KnownZero) const {
673   IntegerType *IT = cast<IntegerType>(V->getType());
674   KnownOne = APInt(IT->getBitWidth(), 0);
675   KnownZero = APInt(IT->getBitWidth(), 0);
676   llvm::computeKnownBits(V, KnownZero, KnownOne, DL, 0);
677 }
678
679 bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const {
680   assert(LHS->getType() == RHS->getType() &&
681          "LHS and RHS should have the same type");
682   APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero;
683   ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero);
684   ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero);
685   return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
686 }
687
688 bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
689     GetElementPtrInst *GEP) {
690   bool Changed = false;
691   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
692   gep_type_iterator GTI = gep_type_begin(*GEP);
693   for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
694        I != E; ++I, ++GTI) {
695     // Skip struct member indices which must be i32.
696     if (isa<SequentialType>(*GTI)) {
697       if ((*I)->getType() != IntPtrTy) {
698         *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
699         Changed = true;
700       }
701     }
702   }
703   return Changed;
704 }
705
706 int64_t
707 SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
708                                                  bool &NeedsExtraction) {
709   NeedsExtraction = false;
710   int64_t AccumulativeByteOffset = 0;
711   gep_type_iterator GTI = gep_type_begin(*GEP);
712   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
713     if (isa<SequentialType>(*GTI)) {
714       // Tries to extract a constant offset from this GEP index.
715       int64_t ConstantOffset =
716           ConstantOffsetExtractor::Find(GEP->getOperand(I), DL, GEP);
717       if (ConstantOffset != 0) {
718         NeedsExtraction = true;
719         // A GEP may have multiple indices.  We accumulate the extracted
720         // constant offset to a byte offset, and later offset the remainder of
721         // the original GEP with this byte offset.
722         AccumulativeByteOffset +=
723             ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
724       }
725     } else if (LowerGEP) {
726       StructType *StTy = cast<StructType>(*GTI);
727       uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
728       // Skip field 0 as the offset is always 0.
729       if (Field != 0) {
730         NeedsExtraction = true;
731         AccumulativeByteOffset +=
732             DL->getStructLayout(StTy)->getElementOffset(Field);
733       }
734     }
735   }
736   return AccumulativeByteOffset;
737 }
738
739 void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
740     GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
741   IRBuilder<> Builder(Variadic);
742   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
743
744   Type *I8PtrTy =
745       Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
746   Value *ResultPtr = Variadic->getOperand(0);
747   if (ResultPtr->getType() != I8PtrTy)
748     ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
749
750   gep_type_iterator GTI = gep_type_begin(*Variadic);
751   // Create an ugly GEP for each sequential index. We don't create GEPs for
752   // structure indices, as they are accumulated in the constant offset index.
753   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
754     if (isa<SequentialType>(*GTI)) {
755       Value *Idx = Variadic->getOperand(I);
756       // Skip zero indices.
757       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
758         if (CI->isZero())
759           continue;
760
761       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
762                                 DL->getTypeAllocSize(GTI.getIndexedType()));
763       // Scale the index by element size.
764       if (ElementSize != 1) {
765         if (ElementSize.isPowerOf2()) {
766           Idx = Builder.CreateShl(
767               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
768         } else {
769           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
770         }
771       }
772       // Create an ugly GEP with a single index for each index.
773       ResultPtr = Builder.CreateGEP(ResultPtr, Idx, "uglygep");
774     }
775   }
776
777   // Create a GEP with the constant offset index.
778   if (AccumulativeByteOffset != 0) {
779     Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
780     ResultPtr = Builder.CreateGEP(ResultPtr, Offset, "uglygep");
781   }
782   if (ResultPtr->getType() != Variadic->getType())
783     ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
784
785   Variadic->replaceAllUsesWith(ResultPtr);
786   Variadic->eraseFromParent();
787 }
788
789 void
790 SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
791                                                int64_t AccumulativeByteOffset) {
792   IRBuilder<> Builder(Variadic);
793   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
794
795   Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
796   gep_type_iterator GTI = gep_type_begin(*Variadic);
797   // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
798   // don't create arithmetics for structure indices, as they are accumulated
799   // in the constant offset index.
800   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
801     if (isa<SequentialType>(*GTI)) {
802       Value *Idx = Variadic->getOperand(I);
803       // Skip zero indices.
804       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
805         if (CI->isZero())
806           continue;
807
808       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
809                                 DL->getTypeAllocSize(GTI.getIndexedType()));
810       // Scale the index by element size.
811       if (ElementSize != 1) {
812         if (ElementSize.isPowerOf2()) {
813           Idx = Builder.CreateShl(
814               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
815         } else {
816           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
817         }
818       }
819       // Create an ADD for each index.
820       ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
821     }
822   }
823
824   // Create an ADD for the constant offset index.
825   if (AccumulativeByteOffset != 0) {
826     ResultPtr = Builder.CreateAdd(
827         ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
828   }
829
830   ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
831   Variadic->replaceAllUsesWith(ResultPtr);
832   Variadic->eraseFromParent();
833 }
834
835 bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
836   // Skip vector GEPs.
837   if (GEP->getType()->isVectorTy())
838     return false;
839
840   // The backend can already nicely handle the case where all indices are
841   // constant.
842   if (GEP->hasAllConstantIndices())
843     return false;
844
845   bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
846
847   bool NeedsExtraction;
848   int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
849
850   if (!NeedsExtraction)
851     return Changed;
852   // If LowerGEP is disabled, before really splitting the GEP, check whether the
853   // backend supports the addressing mode we are about to produce. If no, this
854   // splitting probably won't be beneficial.
855   // If LowerGEP is enabled, even the extracted constant offset can not match
856   // the addressing mode, we can still do optimizations to other lowered parts
857   // of variable indices. Therefore, we don't check for addressing modes in that
858   // case.
859   if (!LowerGEP) {
860     TargetTransformInfo &TTI =
861         getAnalysis<TargetTransformInfoWrapperPass>().getTTI();
862     if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),
863                                    /*BaseGV=*/nullptr, AccumulativeByteOffset,
864                                    /*HasBaseReg=*/true, /*Scale=*/0)) {
865       return Changed;
866     }
867   }
868
869   // Remove the constant offset in each sequential index. The resultant GEP
870   // computes the variadic base.
871   // Notice that we don't remove struct field indices here. If LowerGEP is
872   // disabled, a structure index is not accumulated and we still use the old
873   // one. If LowerGEP is enabled, a structure index is accumulated in the
874   // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
875   // handle the constant offset and won't need a new structure index.
876   gep_type_iterator GTI = gep_type_begin(*GEP);
877   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
878     if (isa<SequentialType>(*GTI)) {
879       // Splits this GEP index into a variadic part and a constant offset, and
880       // uses the variadic part as the new index.
881       Value *NewIdx =
882           ConstantOffsetExtractor::Extract(GEP->getOperand(I), DL, GEP);
883       if (NewIdx != nullptr) {
884         GEP->setOperand(I, NewIdx);
885       }
886     }
887   }
888
889   // Clear the inbounds attribute because the new index may be off-bound.
890   // e.g.,
891   //
892   // b = add i64 a, 5
893   // addr = gep inbounds float* p, i64 b
894   //
895   // is transformed to:
896   //
897   // addr2 = gep float* p, i64 a
898   // addr = gep float* addr2, i64 5
899   //
900   // If a is -4, although the old index b is in bounds, the new index a is
901   // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
902   // inbounds keyword is not present, the offsets are added to the base
903   // address with silently-wrapping two's complement arithmetic".
904   // Therefore, the final code will be a semantically equivalent.
905   //
906   // TODO(jingyue): do some range analysis to keep as many inbounds as
907   // possible. GEPs with inbounds are more friendly to alias analysis.
908   GEP->setIsInBounds(false);
909
910   // Lowers a GEP to either GEPs with a single index or arithmetic operations.
911   if (LowerGEP) {
912     // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
913     // arithmetic operations if the target uses alias analysis in codegen.
914     if (TM && TM->getSubtargetImpl(*GEP->getParent()->getParent())->useAA())
915       lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
916     else
917       lowerToArithmetics(GEP, AccumulativeByteOffset);
918     return true;
919   }
920
921   // No need to create another GEP if the accumulative byte offset is 0.
922   if (AccumulativeByteOffset == 0)
923     return true;
924
925   // Offsets the base with the accumulative byte offset.
926   //
927   //   %gep                        ; the base
928   //   ... %gep ...
929   //
930   // => add the offset
931   //
932   //   %gep2                       ; clone of %gep
933   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
934   //   %gep                        ; will be removed
935   //   ... %gep ...
936   //
937   // => replace all uses of %gep with %new.gep and remove %gep
938   //
939   //   %gep2                       ; clone of %gep
940   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
941   //   ... %new.gep ...
942   //
943   // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
944   // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
945   // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
946   // type of %gep.
947   //
948   //   %gep2                       ; clone of %gep
949   //   %0       = bitcast %gep2 to i8*
950   //   %uglygep = gep %0, <offset>
951   //   %new.gep = bitcast %uglygep to <type of %gep>
952   //   ... %new.gep ...
953   Instruction *NewGEP = GEP->clone();
954   NewGEP->insertBefore(GEP);
955
956   // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
957   // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
958   // used with unsigned integers later.
959   int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
960       DL->getTypeAllocSize(GEP->getType()->getElementType()));
961   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
962   if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
963     // Very likely. As long as %gep is natually aligned, the byte offset we
964     // extracted should be a multiple of sizeof(*%gep).
965     int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
966     NewGEP = GetElementPtrInst::Create(
967         NewGEP, ConstantInt::get(IntPtrTy, Index, true), GEP->getName(), GEP);
968   } else {
969     // Unlikely but possible. For example,
970     // #pragma pack(1)
971     // struct S {
972     //   int a[3];
973     //   int64 b[8];
974     // };
975     // #pragma pack()
976     //
977     // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
978     // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
979     // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
980     // sizeof(int64).
981     //
982     // Emit an uglygep in this case.
983     Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
984                                        GEP->getPointerAddressSpace());
985     NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
986     NewGEP = GetElementPtrInst::Create(
987         NewGEP, ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true),
988         "uglygep", GEP);
989     if (GEP->getType() != I8PtrTy)
990       NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
991   }
992
993   GEP->replaceAllUsesWith(NewGEP);
994   GEP->eraseFromParent();
995
996   return true;
997 }
998
999 bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
1000   if (DisableSeparateConstOffsetFromGEP)
1001     return false;
1002
1003   bool Changed = false;
1004   for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {
1005     for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {
1006       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {
1007         Changed |= splitGEP(GEP);
1008       }
1009       // No need to split GEP ConstantExprs because all its indices are constant
1010       // already.
1011     }
1012   }
1013   return Changed;
1014 }