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