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