Make DataLayout Non-Optional in the Module
[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<TargetTransformInfoWrapperPass>();
316     AU.setPreservesCFG();
317   }
318
319   bool doInitialization(Module &M) override {
320     DL = &M.getDataLayout();
321     return false;
322   }
323
324   bool runOnFunction(Function &F) override;
325
326  private:
327   /// Tries to split the given GEP into a variadic base and a constant offset,
328   /// and returns true if the splitting succeeds.
329   bool splitGEP(GetElementPtrInst *GEP);
330   /// Lower a GEP with multiple indices into multiple GEPs with a single index.
331   /// Function splitGEP already split the original GEP into a variadic part and
332   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
333   /// variadic part into a set of GEPs with a single index and applies
334   /// AccumulativeByteOffset to it.
335   /// \p Variadic                  The variadic part of the original GEP.
336   /// \p AccumulativeByteOffset    The constant offset.
337   void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
338                               int64_t AccumulativeByteOffset);
339   /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
340   /// Function splitGEP already split the original GEP into a variadic part and
341   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
342   /// variadic part into a set of arithmetic operations and applies
343   /// AccumulativeByteOffset to it.
344   /// \p Variadic                  The variadic part of the original GEP.
345   /// \p AccumulativeByteOffset    The constant offset.
346   void lowerToArithmetics(GetElementPtrInst *Variadic,
347                           int64_t AccumulativeByteOffset);
348   /// Finds the constant offset within each index and accumulates them. If
349   /// LowerGEP is true, it finds in indices of both sequential and structure
350   /// types, otherwise it only finds in sequential indices. The output
351   /// NeedsExtraction indicates whether we successfully find a non-zero constant
352   /// offset.
353   int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
354   /// Canonicalize array indices to pointer-size integers. This helps to
355   /// simplify the logic of splitting a GEP. For example, if a + b is a
356   /// pointer-size integer, we have
357   ///   gep base, a + b = gep (gep base, a), b
358   /// However, this equality may not hold if the size of a + b is smaller than
359   /// the pointer size, because LLVM conceptually sign-extends GEP indices to
360   /// pointer size before computing the address
361   /// (http://llvm.org/docs/LangRef.html#id181).
362   ///
363   /// This canonicalization is very likely already done in clang and
364   /// instcombine. Therefore, the program will probably remain the same.
365   ///
366   /// Returns true if the module changes.
367   ///
368   /// Verified in @i32_add in split-gep.ll
369   bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
370
371   const DataLayout *DL;
372   const TargetMachine *TM;
373   /// Whether to lower a GEP with multiple indices into arithmetic operations or
374   /// multiple GEPs with a single index.
375   bool LowerGEP;
376 };
377 }  // anonymous namespace
378
379 char SeparateConstOffsetFromGEP::ID = 0;
380 INITIALIZE_PASS_BEGIN(
381     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
382     "Split GEPs to a variadic base and a constant offset for better CSE", false,
383     false)
384 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
385 INITIALIZE_PASS_END(
386     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
387     "Split GEPs to a variadic base and a constant offset for better CSE", false,
388     false)
389
390 FunctionPass *
391 llvm::createSeparateConstOffsetFromGEPPass(const TargetMachine *TM,
392                                            bool LowerGEP) {
393   return new SeparateConstOffsetFromGEP(TM, LowerGEP);
394 }
395
396 bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
397                                             bool ZeroExtended,
398                                             BinaryOperator *BO,
399                                             bool NonNegative) {
400   // We only consider ADD, SUB and OR, because a non-zero constant found in
401   // expressions composed of these operations can be easily hoisted as a
402   // constant offset by reassociation.
403   if (BO->getOpcode() != Instruction::Add &&
404       BO->getOpcode() != Instruction::Sub &&
405       BO->getOpcode() != Instruction::Or) {
406     return false;
407   }
408
409   Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
410   // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
411   // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
412   if (BO->getOpcode() == Instruction::Or && !NoCommonBits(LHS, RHS))
413     return false;
414
415   // In addition, tracing into BO requires that its surrounding s/zext (if
416   // any) is distributable to both operands.
417   //
418   // Suppose BO = A op B.
419   //  SignExtended | ZeroExtended | Distributable?
420   // --------------+--------------+----------------------------------
421   //       0       |      0       | true because no s/zext exists
422   //       0       |      1       | zext(BO) == zext(A) op zext(B)
423   //       1       |      0       | sext(BO) == sext(A) op sext(B)
424   //       1       |      1       | zext(sext(BO)) ==
425   //               |              |     zext(sext(A)) op zext(sext(B))
426   if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
427     // If a + b >= 0 and (a >= 0 or b >= 0), then
428     //   sext(a + b) = sext(a) + sext(b)
429     // even if the addition is not marked nsw.
430     //
431     // Leveraging this invarient, we can trace into an sext'ed inbound GEP
432     // index if the constant offset is non-negative.
433     //
434     // Verified in @sext_add in split-gep.ll.
435     if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
436       if (!ConstLHS->isNegative())
437         return true;
438     }
439     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
440       if (!ConstRHS->isNegative())
441         return true;
442     }
443   }
444
445   // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
446   // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
447   if (BO->getOpcode() == Instruction::Add ||
448       BO->getOpcode() == Instruction::Sub) {
449     if (SignExtended && !BO->hasNoSignedWrap())
450       return false;
451     if (ZeroExtended && !BO->hasNoUnsignedWrap())
452       return false;
453   }
454
455   return true;
456 }
457
458 APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
459                                                    bool SignExtended,
460                                                    bool ZeroExtended) {
461   // BO being non-negative does not shed light on whether its operands are
462   // non-negative. Clear the NonNegative flag here.
463   APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
464                               /* NonNegative */ false);
465   // If we found a constant offset in the left operand, stop and return that.
466   // This shortcut might cause us to miss opportunities of combining the
467   // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
468   // However, such cases are probably already handled by -instcombine,
469   // given this pass runs after the standard optimizations.
470   if (ConstantOffset != 0) return ConstantOffset;
471   ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
472                         /* NonNegative */ false);
473   // If U is a sub operator, negate the constant offset found in the right
474   // operand.
475   if (BO->getOpcode() == Instruction::Sub)
476     ConstantOffset = -ConstantOffset;
477   return ConstantOffset;
478 }
479
480 APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
481                                     bool ZeroExtended, bool NonNegative) {
482   // TODO(jingyue): We could trace into integer/pointer casts, such as
483   // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
484   // integers because it gives good enough results for our benchmarks.
485   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
486
487   // We cannot do much with Values that are not a User, such as an Argument.
488   User *U = dyn_cast<User>(V);
489   if (U == nullptr) return APInt(BitWidth, 0);
490
491   APInt ConstantOffset(BitWidth, 0);
492   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
493     // Hooray, we found it!
494     ConstantOffset = CI->getValue();
495   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
496     // Trace into subexpressions for more hoisting opportunities.
497     if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative)) {
498       ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
499     }
500   } else if (isa<SExtInst>(V)) {
501     ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
502                           ZeroExtended, NonNegative).sext(BitWidth);
503   } else if (isa<ZExtInst>(V)) {
504     // As an optimization, we can clear the SignExtended flag because
505     // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
506     //
507     // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
508     ConstantOffset =
509         find(U->getOperand(0), /* SignExtended */ false,
510              /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
511   }
512
513   // If we found a non-zero constant offset, add it to the path for
514   // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
515   // help this optimization.
516   if (ConstantOffset != 0)
517     UserChain.push_back(U);
518   return ConstantOffset;
519 }
520
521 Value *ConstantOffsetExtractor::applyExts(Value *V) {
522   Value *Current = V;
523   // ExtInsts is built in the use-def order. Therefore, we apply them to V
524   // in the reversed order.
525   for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
526     if (Constant *C = dyn_cast<Constant>(Current)) {
527       // If Current is a constant, apply s/zext using ConstantExpr::getCast.
528       // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
529       Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
530     } else {
531       Instruction *Ext = (*I)->clone();
532       Ext->setOperand(0, Current);
533       Ext->insertBefore(IP);
534       Current = Ext;
535     }
536   }
537   return Current;
538 }
539
540 Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
541   distributeExtsAndCloneChain(UserChain.size() - 1);
542   // Remove all nullptrs (used to be s/zext) from UserChain.
543   unsigned NewSize = 0;
544   for (auto I = UserChain.begin(), E = UserChain.end(); I != E; ++I) {
545     if (*I != nullptr) {
546       UserChain[NewSize] = *I;
547       NewSize++;
548     }
549   }
550   UserChain.resize(NewSize);
551   return removeConstOffset(UserChain.size() - 1);
552 }
553
554 Value *
555 ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
556   User *U = UserChain[ChainIndex];
557   if (ChainIndex == 0) {
558     assert(isa<ConstantInt>(U));
559     // If U is a ConstantInt, applyExts will return a ConstantInt as well.
560     return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
561   }
562
563   if (CastInst *Cast = dyn_cast<CastInst>(U)) {
564     assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
565            "We only traced into two types of CastInst: sext and zext");
566     ExtInsts.push_back(Cast);
567     UserChain[ChainIndex] = nullptr;
568     return distributeExtsAndCloneChain(ChainIndex - 1);
569   }
570
571   // Function find only trace into BinaryOperator and CastInst.
572   BinaryOperator *BO = cast<BinaryOperator>(U);
573   // OpNo = which operand of BO is UserChain[ChainIndex - 1]
574   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
575   Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
576   Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
577
578   BinaryOperator *NewBO = nullptr;
579   if (OpNo == 0) {
580     NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
581                                    BO->getName(), IP);
582   } else {
583     NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
584                                    BO->getName(), IP);
585   }
586   return UserChain[ChainIndex] = NewBO;
587 }
588
589 Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
590   if (ChainIndex == 0) {
591     assert(isa<ConstantInt>(UserChain[ChainIndex]));
592     return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
593   }
594
595   BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
596   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
597   assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
598   Value *NextInChain = removeConstOffset(ChainIndex - 1);
599   Value *TheOther = BO->getOperand(1 - OpNo);
600
601   // If NextInChain is 0 and not the LHS of a sub, we can simplify the
602   // sub-expression to be just TheOther.
603   if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
604     if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
605       return TheOther;
606   }
607
608   if (BO->getOpcode() == Instruction::Or) {
609     // Rebuild "or" as "add", because "or" may be invalid for the new
610     // epxression.
611     //
612     // For instance, given
613     //   a | (b + 5) where a and b + 5 have no common bits,
614     // we can extract 5 as the constant offset.
615     //
616     // However, reusing the "or" in the new index would give us
617     //   (a | b) + 5
618     // which does not equal a | (b + 5).
619     //
620     // Replacing the "or" with "add" is fine, because
621     //   a | (b + 5) = a + (b + 5) = (a + b) + 5
622     if (OpNo == 0) {
623       return BinaryOperator::CreateAdd(NextInChain, TheOther, BO->getName(),
624                                        IP);
625     } else {
626       return BinaryOperator::CreateAdd(TheOther, NextInChain, BO->getName(),
627                                        IP);
628     }
629   }
630
631   // We can reuse BO in this case, because the new expression shares the same
632   // instruction type and BO is used at most once.
633   assert(BO->getNumUses() <= 1 &&
634          "distributeExtsAndCloneChain clones each BinaryOperator in "
635          "UserChain, so no one should be used more than "
636          "once");
637   BO->setOperand(OpNo, NextInChain);
638   BO->setHasNoSignedWrap(false);
639   BO->setHasNoUnsignedWrap(false);
640   // Make sure it appears after all instructions we've inserted so far.
641   BO->moveBefore(IP);
642   return BO;
643 }
644
645 Value *ConstantOffsetExtractor::Extract(Value *Idx, const DataLayout *DL,
646                                         GetElementPtrInst *GEP) {
647   ConstantOffsetExtractor Extractor(DL, GEP);
648   // Find a non-zero constant offset first.
649   APInt ConstantOffset =
650       Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
651                      GEP->isInBounds());
652   if (ConstantOffset == 0)
653     return nullptr;
654   // Separates the constant offset from the GEP index.
655   return Extractor.rebuildWithoutConstOffset();
656 }
657
658 int64_t ConstantOffsetExtractor::Find(Value *Idx, const DataLayout *DL,
659       GetElementPtrInst *GEP) {
660   // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
661   return ConstantOffsetExtractor(DL, GEP)
662       .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
663             GEP->isInBounds())
664       .getSExtValue();
665 }
666
667 void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne,
668                                                APInt &KnownZero) const {
669   IntegerType *IT = cast<IntegerType>(V->getType());
670   KnownOne = APInt(IT->getBitWidth(), 0);
671   KnownZero = APInt(IT->getBitWidth(), 0);
672   llvm::computeKnownBits(V, KnownZero, KnownOne, DL, 0);
673 }
674
675 bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const {
676   assert(LHS->getType() == RHS->getType() &&
677          "LHS and RHS should have the same type");
678   APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero;
679   ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero);
680   ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero);
681   return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
682 }
683
684 bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
685     GetElementPtrInst *GEP) {
686   bool Changed = false;
687   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
688   gep_type_iterator GTI = gep_type_begin(*GEP);
689   for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
690        I != E; ++I, ++GTI) {
691     // Skip struct member indices which must be i32.
692     if (isa<SequentialType>(*GTI)) {
693       if ((*I)->getType() != IntPtrTy) {
694         *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
695         Changed = true;
696       }
697     }
698   }
699   return Changed;
700 }
701
702 int64_t
703 SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
704                                                  bool &NeedsExtraction) {
705   NeedsExtraction = false;
706   int64_t AccumulativeByteOffset = 0;
707   gep_type_iterator GTI = gep_type_begin(*GEP);
708   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
709     if (isa<SequentialType>(*GTI)) {
710       // Tries to extract a constant offset from this GEP index.
711       int64_t ConstantOffset =
712           ConstantOffsetExtractor::Find(GEP->getOperand(I), DL, GEP);
713       if (ConstantOffset != 0) {
714         NeedsExtraction = true;
715         // A GEP may have multiple indices.  We accumulate the extracted
716         // constant offset to a byte offset, and later offset the remainder of
717         // the original GEP with this byte offset.
718         AccumulativeByteOffset +=
719             ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
720       }
721     } else if (LowerGEP) {
722       StructType *StTy = cast<StructType>(*GTI);
723       uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
724       // Skip field 0 as the offset is always 0.
725       if (Field != 0) {
726         NeedsExtraction = true;
727         AccumulativeByteOffset +=
728             DL->getStructLayout(StTy)->getElementOffset(Field);
729       }
730     }
731   }
732   return AccumulativeByteOffset;
733 }
734
735 void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
736     GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
737   IRBuilder<> Builder(Variadic);
738   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
739
740   Type *I8PtrTy =
741       Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
742   Value *ResultPtr = Variadic->getOperand(0);
743   if (ResultPtr->getType() != I8PtrTy)
744     ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
745
746   gep_type_iterator GTI = gep_type_begin(*Variadic);
747   // Create an ugly GEP for each sequential index. We don't create GEPs for
748   // structure indices, as they are accumulated in the constant offset index.
749   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
750     if (isa<SequentialType>(*GTI)) {
751       Value *Idx = Variadic->getOperand(I);
752       // Skip zero indices.
753       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
754         if (CI->isZero())
755           continue;
756
757       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
758                                 DL->getTypeAllocSize(GTI.getIndexedType()));
759       // Scale the index by element size.
760       if (ElementSize != 1) {
761         if (ElementSize.isPowerOf2()) {
762           Idx = Builder.CreateShl(
763               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
764         } else {
765           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
766         }
767       }
768       // Create an ugly GEP with a single index for each index.
769       ResultPtr = Builder.CreateGEP(ResultPtr, Idx, "uglygep");
770     }
771   }
772
773   // Create a GEP with the constant offset index.
774   if (AccumulativeByteOffset != 0) {
775     Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
776     ResultPtr = Builder.CreateGEP(ResultPtr, Offset, "uglygep");
777   }
778   if (ResultPtr->getType() != Variadic->getType())
779     ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
780
781   Variadic->replaceAllUsesWith(ResultPtr);
782   Variadic->eraseFromParent();
783 }
784
785 void
786 SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
787                                                int64_t AccumulativeByteOffset) {
788   IRBuilder<> Builder(Variadic);
789   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
790
791   Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
792   gep_type_iterator GTI = gep_type_begin(*Variadic);
793   // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
794   // don't create arithmetics for structure indices, as they are accumulated
795   // in the constant offset index.
796   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
797     if (isa<SequentialType>(*GTI)) {
798       Value *Idx = Variadic->getOperand(I);
799       // Skip zero indices.
800       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
801         if (CI->isZero())
802           continue;
803
804       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
805                                 DL->getTypeAllocSize(GTI.getIndexedType()));
806       // Scale the index by element size.
807       if (ElementSize != 1) {
808         if (ElementSize.isPowerOf2()) {
809           Idx = Builder.CreateShl(
810               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
811         } else {
812           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
813         }
814       }
815       // Create an ADD for each index.
816       ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
817     }
818   }
819
820   // Create an ADD for the constant offset index.
821   if (AccumulativeByteOffset != 0) {
822     ResultPtr = Builder.CreateAdd(
823         ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
824   }
825
826   ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
827   Variadic->replaceAllUsesWith(ResultPtr);
828   Variadic->eraseFromParent();
829 }
830
831 bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
832   // Skip vector GEPs.
833   if (GEP->getType()->isVectorTy())
834     return false;
835
836   // The backend can already nicely handle the case where all indices are
837   // constant.
838   if (GEP->hasAllConstantIndices())
839     return false;
840
841   bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
842
843   bool NeedsExtraction;
844   int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
845
846   if (!NeedsExtraction)
847     return Changed;
848   // If LowerGEP is disabled, before really splitting the GEP, check whether the
849   // backend supports the addressing mode we are about to produce. If no, this
850   // splitting probably won't be beneficial.
851   // If LowerGEP is enabled, even the extracted constant offset can not match
852   // the addressing mode, we can still do optimizations to other lowered parts
853   // of variable indices. Therefore, we don't check for addressing modes in that
854   // case.
855   if (!LowerGEP) {
856     TargetTransformInfo &TTI =
857         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
858             *GEP->getParent()->getParent());
859     if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),
860                                    /*BaseGV=*/nullptr, AccumulativeByteOffset,
861                                    /*HasBaseReg=*/true, /*Scale=*/0)) {
862       return Changed;
863     }
864   }
865
866   // Remove the constant offset in each sequential index. The resultant GEP
867   // computes the variadic base.
868   // Notice that we don't remove struct field indices here. If LowerGEP is
869   // disabled, a structure index is not accumulated and we still use the old
870   // one. If LowerGEP is enabled, a structure index is accumulated in the
871   // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
872   // handle the constant offset and won't need a new structure index.
873   gep_type_iterator GTI = gep_type_begin(*GEP);
874   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
875     if (isa<SequentialType>(*GTI)) {
876       // Splits this GEP index into a variadic part and a constant offset, and
877       // uses the variadic part as the new index.
878       Value *NewIdx =
879           ConstantOffsetExtractor::Extract(GEP->getOperand(I), DL, GEP);
880       if (NewIdx != nullptr) {
881         GEP->setOperand(I, NewIdx);
882       }
883     }
884   }
885
886   // Clear the inbounds attribute because the new index may be off-bound.
887   // e.g.,
888   //
889   // b = add i64 a, 5
890   // addr = gep inbounds float* p, i64 b
891   //
892   // is transformed to:
893   //
894   // addr2 = gep float* p, i64 a
895   // addr = gep float* addr2, i64 5
896   //
897   // If a is -4, although the old index b is in bounds, the new index a is
898   // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
899   // inbounds keyword is not present, the offsets are added to the base
900   // address with silently-wrapping two's complement arithmetic".
901   // Therefore, the final code will be a semantically equivalent.
902   //
903   // TODO(jingyue): do some range analysis to keep as many inbounds as
904   // possible. GEPs with inbounds are more friendly to alias analysis.
905   GEP->setIsInBounds(false);
906
907   // Lowers a GEP to either GEPs with a single index or arithmetic operations.
908   if (LowerGEP) {
909     // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
910     // arithmetic operations if the target uses alias analysis in codegen.
911     if (TM && TM->getSubtargetImpl(*GEP->getParent()->getParent())->useAA())
912       lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
913     else
914       lowerToArithmetics(GEP, AccumulativeByteOffset);
915     return true;
916   }
917
918   // No need to create another GEP if the accumulative byte offset is 0.
919   if (AccumulativeByteOffset == 0)
920     return true;
921
922   // Offsets the base with the accumulative byte offset.
923   //
924   //   %gep                        ; the base
925   //   ... %gep ...
926   //
927   // => add the offset
928   //
929   //   %gep2                       ; clone of %gep
930   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
931   //   %gep                        ; will be removed
932   //   ... %gep ...
933   //
934   // => replace all uses of %gep with %new.gep and remove %gep
935   //
936   //   %gep2                       ; clone of %gep
937   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
938   //   ... %new.gep ...
939   //
940   // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
941   // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
942   // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
943   // type of %gep.
944   //
945   //   %gep2                       ; clone of %gep
946   //   %0       = bitcast %gep2 to i8*
947   //   %uglygep = gep %0, <offset>
948   //   %new.gep = bitcast %uglygep to <type of %gep>
949   //   ... %new.gep ...
950   Instruction *NewGEP = GEP->clone();
951   NewGEP->insertBefore(GEP);
952
953   // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
954   // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
955   // used with unsigned integers later.
956   int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
957       DL->getTypeAllocSize(GEP->getType()->getElementType()));
958   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
959   if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
960     // Very likely. As long as %gep is natually aligned, the byte offset we
961     // extracted should be a multiple of sizeof(*%gep).
962     int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
963     NewGEP = GetElementPtrInst::Create(
964         NewGEP, ConstantInt::get(IntPtrTy, Index, true), GEP->getName(), GEP);
965   } else {
966     // Unlikely but possible. For example,
967     // #pragma pack(1)
968     // struct S {
969     //   int a[3];
970     //   int64 b[8];
971     // };
972     // #pragma pack()
973     //
974     // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
975     // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
976     // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
977     // sizeof(int64).
978     //
979     // Emit an uglygep in this case.
980     Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
981                                        GEP->getPointerAddressSpace());
982     NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
983     NewGEP = GetElementPtrInst::Create(
984         NewGEP, ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true),
985         "uglygep", GEP);
986     if (GEP->getType() != I8PtrTy)
987       NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
988   }
989
990   GEP->replaceAllUsesWith(NewGEP);
991   GEP->eraseFromParent();
992
993   return true;
994 }
995
996 bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
997   if (skipOptnoneFunction(F))
998     return false;
999
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 }