blob: 78af1bda7b2e1c9f4297f5847e9c2189e4ce07d2 [file] [log] [blame]
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001//===- SeparateConstOffsetFromGEP.cpp -------------------------------------===//
Eli Benderskya108a652014-05-01 18:38:36 +00002//
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//
Hao Liu1d2a0612014-11-19 06:24:44 +000082// 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//
Haicheng Wu5b106ef2017-12-19 18:49:21 +0000100// We can not do CSE to the common part related to index "i64 %i". Lowering
Hao Liu1d2a0612014-11-19 06:24:44 +0000101// 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//
Eli Benderskya108a652014-05-01 18:38:36 +0000157//===----------------------------------------------------------------------===//
158
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000159#include "llvm/ADT/APInt.h"
160#include "llvm/ADT/DenseMap.h"
161#include "llvm/ADT/DepthFirstIterator.h"
162#include "llvm/ADT/SmallVector.h"
Lawrence Hucac0b892015-09-23 19:25:30 +0000163#include "llvm/Analysis/LoopInfo.h"
164#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000165#include "llvm/Analysis/ScalarEvolution.h"
Lawrence Hucac0b892015-09-23 19:25:30 +0000166#include "llvm/Analysis/TargetLibraryInfo.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000167#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +0000168#include "llvm/Analysis/Utils/Local.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000169#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000170#include "llvm/IR/BasicBlock.h"
171#include "llvm/IR/Constant.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000172#include "llvm/IR/Constants.h"
173#include "llvm/IR/DataLayout.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000174#include "llvm/IR/DerivedTypes.h"
Jingyue Wuca321902015-05-14 23:53:19 +0000175#include "llvm/IR/Dominators.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000176#include "llvm/IR/Function.h"
177#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000178#include "llvm/IR/IRBuilder.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000179#include "llvm/IR/Instruction.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000180#include "llvm/IR/Instructions.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000181#include "llvm/IR/Module.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000182#include "llvm/IR/PatternMatch.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000183#include "llvm/IR/Type.h"
184#include "llvm/IR/User.h"
185#include "llvm/IR/Value.h"
186#include "llvm/Pass.h"
187#include "llvm/Support/Casting.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000188#include "llvm/Support/CommandLine.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000189#include "llvm/Support/ErrorHandling.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000190#include "llvm/Support/raw_ostream.h"
Hao Liu1d2a0612014-11-19 06:24:44 +0000191#include "llvm/Target/TargetMachine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000192#include "llvm/Transforms/Scalar.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000193#include <cassert>
194#include <cstdint>
195#include <string>
Eli Benderskya108a652014-05-01 18:38:36 +0000196
197using namespace llvm;
Jingyue Wu1238f342015-08-14 02:02:05 +0000198using namespace llvm::PatternMatch;
Eli Benderskya108a652014-05-01 18:38:36 +0000199
200static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
201 "disable-separate-const-offset-from-gep", cl::init(false),
202 cl::desc("Do not separate the constant offset from a GEP instruction"),
203 cl::Hidden);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000204
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000205// Setting this flag may emit false positives when the input module already
206// contains dead instructions. Therefore, we set it only in unit tests that are
207// free of dead code.
208static cl::opt<bool>
209 VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
210 cl::desc("Verify this pass produces no dead code"),
211 cl::Hidden);
Eli Benderskya108a652014-05-01 18:38:36 +0000212
213namespace {
214
215/// \brief A helper class for separating a constant offset from a GEP index.
216///
217/// In real programs, a GEP index may be more complicated than a simple addition
218/// of something and a constant integer which can be trivially splitted. For
219/// example, to split ((a << 3) | 5) + b, we need to search deeper for the
Alp Tokerbeaca192014-05-15 01:52:21 +0000220/// constant offset, so that we can separate the index to (a << 3) + b and 5.
Eli Benderskya108a652014-05-01 18:38:36 +0000221///
222/// Therefore, this class looks into the expression that computes a given GEP
223/// index, and tries to find a constant integer that can be hoisted to the
224/// outermost level of the expression as an addition. Not every constant in an
225/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
226/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
227/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
228class ConstantOffsetExtractor {
Jingyue Wuca321902015-05-14 23:53:19 +0000229public:
Hao Liu1d2a0612014-11-19 06:24:44 +0000230 /// Extracts a constant offset from the given GEP index. It returns the
Eli Benderskya108a652014-05-01 18:38:36 +0000231 /// new index representing the remainder (equal to the original index minus
Hao Liu1d2a0612014-11-19 06:24:44 +0000232 /// the constant offset), or nullptr if we cannot extract a constant offset.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000233 /// \p Idx The given GEP index
234 /// \p GEP The given GEP
235 /// \p UserChainTail Outputs the tail of UserChain so that we can
236 /// garbage-collect unused instructions in UserChain.
Jingyue Wuca321902015-05-14 23:53:19 +0000237 static Value *Extract(Value *Idx, GetElementPtrInst *GEP,
238 User *&UserChainTail, const DominatorTree *DT);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000239
Hao Liu1d2a0612014-11-19 06:24:44 +0000240 /// Looks for a constant offset from the given GEP index without extracting
241 /// it. It returns the numeric value of the extracted constant offset (0 if
242 /// failed). The meaning of the arguments are the same as Extract.
Jingyue Wuca321902015-05-14 23:53:19 +0000243 static int64_t Find(Value *Idx, GetElementPtrInst *GEP,
244 const DominatorTree *DT);
Eli Benderskya108a652014-05-01 18:38:36 +0000245
Jingyue Wuca321902015-05-14 23:53:19 +0000246private:
247 ConstantOffsetExtractor(Instruction *InsertionPt, const DominatorTree *DT)
248 : IP(InsertionPt), DL(InsertionPt->getModule()->getDataLayout()), DT(DT) {
249 }
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000250
Jingyue Wu84465472014-06-05 22:07:33 +0000251 /// Searches the expression that computes V for a non-zero constant C s.t.
252 /// V can be reassociated into the form V' + C. If the searching is
253 /// successful, returns C and update UserChain as a def-use chain from C to V;
254 /// otherwise, UserChain is empty.
Eli Benderskya108a652014-05-01 18:38:36 +0000255 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000256 /// \p V The given expression
257 /// \p SignExtended Whether V will be sign-extended in the computation of the
258 /// GEP index
259 /// \p ZeroExtended Whether V will be zero-extended in the computation of the
260 /// GEP index
261 /// \p NonNegative Whether V is guaranteed to be non-negative. For example,
262 /// an index of an inbounds GEP is guaranteed to be
263 /// non-negative. Levaraging this, we can better split
264 /// inbounds GEPs.
265 APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000266
Jingyue Wu84465472014-06-05 22:07:33 +0000267 /// A helper function to look into both operands of a binary operator.
268 APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
269 bool ZeroExtended);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000270
Jingyue Wu84465472014-06-05 22:07:33 +0000271 /// After finding the constant offset C from the GEP index I, we build a new
272 /// index I' s.t. I' + C = I. This function builds and returns the new
273 /// index I' according to UserChain produced by function "find".
274 ///
275 /// The building conceptually takes two steps:
276 /// 1) iteratively distribute s/zext towards the leaves of the expression tree
277 /// that computes I
278 /// 2) reassociate the expression tree to the form I' + C.
279 ///
280 /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
281 /// sext to a, b and 5 so that we have
282 /// sext(a) + (sext(b) + 5).
283 /// Then, we reassociate it to
284 /// (sext(a) + sext(b)) + 5.
285 /// Given this form, we know I' is sext(a) + sext(b).
286 Value *rebuildWithoutConstOffset();
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000287
Jingyue Wu84465472014-06-05 22:07:33 +0000288 /// After the first step of rebuilding the GEP index without the constant
289 /// offset, distribute s/zext to the operands of all operators in UserChain.
290 /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
291 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
292 ///
293 /// The function also updates UserChain to point to new subexpressions after
294 /// distributing s/zext. e.g., the old UserChain of the above example is
295 /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
296 /// and the new UserChain is
297 /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
298 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
299 ///
300 /// \p ChainIndex The index to UserChain. ChainIndex is initially
301 /// UserChain.size() - 1, and is decremented during
302 /// the recursion.
303 Value *distributeExtsAndCloneChain(unsigned ChainIndex);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000304
Jingyue Wu84465472014-06-05 22:07:33 +0000305 /// Reassociates the GEP index to the form I' + C and returns I'.
306 Value *removeConstOffset(unsigned ChainIndex);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000307
Jingyue Wu84465472014-06-05 22:07:33 +0000308 /// A helper function to apply ExtInsts, a list of s/zext, to value V.
309 /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
310 /// returns "sext i32 (zext i16 V to i32) to i64".
311 Value *applyExts(Value *V);
Eli Benderskya108a652014-05-01 18:38:36 +0000312
Jingyue Wu84465472014-06-05 22:07:33 +0000313 /// A helper function that returns whether we can trace into the operands
314 /// of binary operator BO for a constant offset.
315 ///
316 /// \p SignExtended Whether BO is surrounded by sext
317 /// \p ZeroExtended Whether BO is surrounded by zext
318 /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
319 /// array index.
320 bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
321 bool NonNegative);
Eli Benderskya108a652014-05-01 18:38:36 +0000322
323 /// The path from the constant offset to the old GEP index. e.g., if the GEP
324 /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
325 /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
326 /// UserChain[2] will be the entire expression "a * b + (c + 5)".
327 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000328 /// This path helps to rebuild the new GEP index.
Eli Benderskya108a652014-05-01 18:38:36 +0000329 SmallVector<User *, 8> UserChain;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000330
Jingyue Wu84465472014-06-05 22:07:33 +0000331 /// A data structure used in rebuildWithoutConstOffset. Contains all
332 /// sext/zext instructions along UserChain.
333 SmallVector<CastInst *, 16> ExtInsts;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000334
335 /// Insertion position of cloned instructions.
336 Instruction *IP;
337
Jingyue Wuca321902015-05-14 23:53:19 +0000338 const DataLayout &DL;
339 const DominatorTree *DT;
Eli Benderskya108a652014-05-01 18:38:36 +0000340};
341
342/// \brief A pass that tries to split every GEP in the function into a variadic
Alp Tokerbeaca192014-05-15 01:52:21 +0000343/// base and a constant offset. It is a FunctionPass because searching for the
Eli Benderskya108a652014-05-01 18:38:36 +0000344/// constant offset may inspect other basic blocks.
345class SeparateConstOffsetFromGEP : public FunctionPass {
Jingyue Wuca321902015-05-14 23:53:19 +0000346public:
Eli Benderskya108a652014-05-01 18:38:36 +0000347 static char ID;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000348
David Blaikie8ad9a972018-03-28 22:28:50 +0000349 SeparateConstOffsetFromGEP(bool LowerGEP = false)
350 : FunctionPass(ID), LowerGEP(LowerGEP) {
Eli Benderskya108a652014-05-01 18:38:36 +0000351 initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
352 }
353
354 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jingyue Wuca321902015-05-14 23:53:19 +0000355 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000356 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000357 AU.addRequired<TargetTransformInfoWrapperPass>();
Lawrence Hucac0b892015-09-23 19:25:30 +0000358 AU.addRequired<LoopInfoWrapperPass>();
Jingyue Wu6e091c82015-02-01 02:33:02 +0000359 AU.setPreservesCFG();
Lawrence Hucac0b892015-09-23 19:25:30 +0000360 AU.addRequired<TargetLibraryInfoWrapperPass>();
Eli Benderskya108a652014-05-01 18:38:36 +0000361 }
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000362
Jingyue Wuca321902015-05-14 23:53:19 +0000363 bool doInitialization(Module &M) override {
364 DL = &M.getDataLayout();
365 return false;
366 }
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000367
Eli Benderskya108a652014-05-01 18:38:36 +0000368 bool runOnFunction(Function &F) override;
369
Jingyue Wuca321902015-05-14 23:53:19 +0000370private:
Eli Benderskya108a652014-05-01 18:38:36 +0000371 /// Tries to split the given GEP into a variadic base and a constant offset,
372 /// and returns true if the splitting succeeds.
373 bool splitGEP(GetElementPtrInst *GEP);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000374
Hao Liu1d2a0612014-11-19 06:24:44 +0000375 /// Lower a GEP with multiple indices into multiple GEPs with a single index.
376 /// Function splitGEP already split the original GEP into a variadic part and
377 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
378 /// variadic part into a set of GEPs with a single index and applies
379 /// AccumulativeByteOffset to it.
380 /// \p Variadic The variadic part of the original GEP.
381 /// \p AccumulativeByteOffset The constant offset.
382 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
383 int64_t AccumulativeByteOffset);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000384
Hao Liu1d2a0612014-11-19 06:24:44 +0000385 /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
386 /// Function splitGEP already split the original GEP into a variadic part and
387 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
388 /// variadic part into a set of arithmetic operations and applies
389 /// AccumulativeByteOffset to it.
390 /// \p Variadic The variadic part of the original GEP.
391 /// \p AccumulativeByteOffset The constant offset.
392 void lowerToArithmetics(GetElementPtrInst *Variadic,
393 int64_t AccumulativeByteOffset);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000394
Hao Liu1d2a0612014-11-19 06:24:44 +0000395 /// Finds the constant offset within each index and accumulates them. If
396 /// LowerGEP is true, it finds in indices of both sequential and structure
397 /// types, otherwise it only finds in sequential indices. The output
398 /// NeedsExtraction indicates whether we successfully find a non-zero constant
399 /// offset.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000400 int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000401
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000402 /// Canonicalize array indices to pointer-size integers. This helps to
403 /// simplify the logic of splitting a GEP. For example, if a + b is a
404 /// pointer-size integer, we have
405 /// gep base, a + b = gep (gep base, a), b
406 /// However, this equality may not hold if the size of a + b is smaller than
407 /// the pointer size, because LLVM conceptually sign-extends GEP indices to
408 /// pointer size before computing the address
409 /// (http://llvm.org/docs/LangRef.html#id181).
410 ///
411 /// This canonicalization is very likely already done in clang and
412 /// instcombine. Therefore, the program will probably remain the same.
413 ///
Jingyue Wu5c7b1ae2014-06-08 23:49:34 +0000414 /// Returns true if the module changes.
415 ///
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000416 /// Verified in @i32_add in split-gep.ll
417 bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000418
Jingyue Wu1238f342015-08-14 02:02:05 +0000419 /// Optimize sext(a)+sext(b) to sext(a+b) when a+b can't sign overflow.
420 /// SeparateConstOffsetFromGEP distributes a sext to leaves before extracting
421 /// the constant offset. After extraction, it becomes desirable to reunion the
422 /// distributed sexts. For example,
423 ///
424 /// &a[sext(i +nsw (j +nsw 5)]
425 /// => distribute &a[sext(i) +nsw (sext(j) +nsw 5)]
426 /// => constant extraction &a[sext(i) + sext(j)] + 5
427 /// => reunion &a[sext(i +nsw j)] + 5
428 bool reuniteExts(Function &F);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000429
Jingyue Wu1238f342015-08-14 02:02:05 +0000430 /// A helper that reunites sexts in an instruction.
431 bool reuniteExts(Instruction *I);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000432
Jingyue Wu1238f342015-08-14 02:02:05 +0000433 /// Find the closest dominator of <Dominatee> that is equivalent to <Key>.
434 Instruction *findClosestMatchingDominator(const SCEV *Key,
435 Instruction *Dominatee);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000436 /// Verify F is free of dead code.
437 void verifyNoDeadCode(Function &F);
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000438
Lawrence Hucac0b892015-09-23 19:25:30 +0000439 bool hasMoreThanOneUseInLoop(Value *v, Loop *L);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000440
Lawrence Hucac0b892015-09-23 19:25:30 +0000441 // Swap the index operand of two GEP.
442 void swapGEPOperand(GetElementPtrInst *First, GetElementPtrInst *Second);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000443
Lawrence Hucac0b892015-09-23 19:25:30 +0000444 // Check if it is safe to swap operand of two GEP.
445 bool isLegalToSwapOperand(GetElementPtrInst *First, GetElementPtrInst *Second,
446 Loop *CurLoop);
447
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000448 const DataLayout *DL = nullptr;
449 DominatorTree *DT = nullptr;
Jingyue Wu1238f342015-08-14 02:02:05 +0000450 ScalarEvolution *SE;
Lawrence Hucac0b892015-09-23 19:25:30 +0000451
452 LoopInfo *LI;
453 TargetLibraryInfo *TLI;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000454
Hao Liu1d2a0612014-11-19 06:24:44 +0000455 /// Whether to lower a GEP with multiple indices into arithmetic operations or
456 /// multiple GEPs with a single index.
457 bool LowerGEP;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000458
Jingyue Wu1238f342015-08-14 02:02:05 +0000459 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> DominatingExprs;
Eli Benderskya108a652014-05-01 18:38:36 +0000460};
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000461
462} // end anonymous namespace
Eli Benderskya108a652014-05-01 18:38:36 +0000463
464char SeparateConstOffsetFromGEP::ID = 0;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000465
Eli Benderskya108a652014-05-01 18:38:36 +0000466INITIALIZE_PASS_BEGIN(
467 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
468 "Split GEPs to a variadic base and a constant offset for better CSE", false,
469 false)
Jingyue Wuca321902015-05-14 23:53:19 +0000470INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000471INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000472INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Lawrence Hucac0b892015-09-23 19:25:30 +0000473INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
474INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Eli Benderskya108a652014-05-01 18:38:36 +0000475INITIALIZE_PASS_END(
476 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
477 "Split GEPs to a variadic base and a constant offset for better CSE", false,
478 false)
479
David Blaikie8ad9a972018-03-28 22:28:50 +0000480FunctionPass *llvm::createSeparateConstOffsetFromGEPPass(bool LowerGEP) {
481 return new SeparateConstOffsetFromGEP(LowerGEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000482}
483
Jingyue Wu84465472014-06-05 22:07:33 +0000484bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
485 bool ZeroExtended,
486 BinaryOperator *BO,
487 bool NonNegative) {
488 // We only consider ADD, SUB and OR, because a non-zero constant found in
489 // expressions composed of these operations can be easily hoisted as a
490 // constant offset by reassociation.
491 if (BO->getOpcode() != Instruction::Add &&
492 BO->getOpcode() != Instruction::Sub &&
493 BO->getOpcode() != Instruction::Or) {
494 return false;
495 }
496
497 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
498 // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
499 // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
Jingyue Wuca321902015-05-14 23:53:19 +0000500 if (BO->getOpcode() == Instruction::Or &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000501 !haveNoCommonBitsSet(LHS, RHS, DL, nullptr, BO, DT))
Jingyue Wu84465472014-06-05 22:07:33 +0000502 return false;
503
504 // In addition, tracing into BO requires that its surrounding s/zext (if
505 // any) is distributable to both operands.
506 //
507 // Suppose BO = A op B.
508 // SignExtended | ZeroExtended | Distributable?
509 // --------------+--------------+----------------------------------
510 // 0 | 0 | true because no s/zext exists
511 // 0 | 1 | zext(BO) == zext(A) op zext(B)
512 // 1 | 0 | sext(BO) == sext(A) op sext(B)
513 // 1 | 1 | zext(sext(BO)) ==
514 // | | zext(sext(A)) op zext(sext(B))
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000515 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
Jingyue Wu84465472014-06-05 22:07:33 +0000516 // If a + b >= 0 and (a >= 0 or b >= 0), then
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000517 // sext(a + b) = sext(a) + sext(b)
Jingyue Wu84465472014-06-05 22:07:33 +0000518 // even if the addition is not marked nsw.
519 //
520 // Leveraging this invarient, we can trace into an sext'ed inbound GEP
521 // index if the constant offset is non-negative.
522 //
523 // Verified in @sext_add in split-gep.ll.
524 if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
525 if (!ConstLHS->isNegative())
526 return true;
527 }
528 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
529 if (!ConstRHS->isNegative())
530 return true;
531 }
532 }
Jingyue Wu80a738d2014-05-27 18:00:00 +0000533
534 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
535 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
536 if (BO->getOpcode() == Instruction::Add ||
537 BO->getOpcode() == Instruction::Sub) {
Jingyue Wu84465472014-06-05 22:07:33 +0000538 if (SignExtended && !BO->hasNoSignedWrap())
539 return false;
540 if (ZeroExtended && !BO->hasNoUnsignedWrap())
541 return false;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000542 }
543
Jingyue Wu84465472014-06-05 22:07:33 +0000544 return true;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000545}
546
Jingyue Wu84465472014-06-05 22:07:33 +0000547APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
548 bool SignExtended,
549 bool ZeroExtended) {
550 // BO being non-negative does not shed light on whether its operands are
551 // non-negative. Clear the NonNegative flag here.
552 APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
553 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000554 // If we found a constant offset in the left operand, stop and return that.
555 // This shortcut might cause us to miss opportunities of combining the
556 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
557 // However, such cases are probably already handled by -instcombine,
558 // given this pass runs after the standard optimizations.
559 if (ConstantOffset != 0) return ConstantOffset;
Jingyue Wu84465472014-06-05 22:07:33 +0000560 ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
561 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000562 // If U is a sub operator, negate the constant offset found in the right
563 // operand.
Jingyue Wu84465472014-06-05 22:07:33 +0000564 if (BO->getOpcode() == Instruction::Sub)
565 ConstantOffset = -ConstantOffset;
566 return ConstantOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000567}
568
Jingyue Wu84465472014-06-05 22:07:33 +0000569APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
570 bool ZeroExtended, bool NonNegative) {
571 // TODO(jingyue): We could trace into integer/pointer casts, such as
Eli Benderskya108a652014-05-01 18:38:36 +0000572 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
573 // integers because it gives good enough results for our benchmarks.
Jingyue Wu84465472014-06-05 22:07:33 +0000574 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Eli Benderskya108a652014-05-01 18:38:36 +0000575
Jingyue Wu84465472014-06-05 22:07:33 +0000576 // We cannot do much with Values that are not a User, such as an Argument.
Eli Benderskya108a652014-05-01 18:38:36 +0000577 User *U = dyn_cast<User>(V);
Jingyue Wu84465472014-06-05 22:07:33 +0000578 if (U == nullptr) return APInt(BitWidth, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000579
Jingyue Wu84465472014-06-05 22:07:33 +0000580 APInt ConstantOffset(BitWidth, 0);
581 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Eli Benderskya108a652014-05-01 18:38:36 +0000582 // Hooray, we found it!
Jingyue Wu84465472014-06-05 22:07:33 +0000583 ConstantOffset = CI->getValue();
584 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
585 // Trace into subexpressions for more hoisting opportunities.
Jingyue Wuca321902015-05-14 23:53:19 +0000586 if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative))
Jingyue Wu84465472014-06-05 22:07:33 +0000587 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
Jingyue Wu84465472014-06-05 22:07:33 +0000588 } else if (isa<SExtInst>(V)) {
589 ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
590 ZeroExtended, NonNegative).sext(BitWidth);
591 } else if (isa<ZExtInst>(V)) {
592 // As an optimization, we can clear the SignExtended flag because
593 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
594 //
595 // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
Jingyue Wu84465472014-06-05 22:07:33 +0000596 ConstantOffset =
597 find(U->getOperand(0), /* SignExtended */ false,
598 /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
Eli Benderskya108a652014-05-01 18:38:36 +0000599 }
Jingyue Wu84465472014-06-05 22:07:33 +0000600
601 // If we found a non-zero constant offset, add it to the path for
602 // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
603 // help this optimization.
Eli Benderskya108a652014-05-01 18:38:36 +0000604 if (ConstantOffset != 0)
605 UserChain.push_back(U);
606 return ConstantOffset;
607}
608
Jingyue Wu84465472014-06-05 22:07:33 +0000609Value *ConstantOffsetExtractor::applyExts(Value *V) {
610 Value *Current = V;
611 // ExtInsts is built in the use-def order. Therefore, we apply them to V
612 // in the reversed order.
613 for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
614 if (Constant *C = dyn_cast<Constant>(Current)) {
615 // If Current is a constant, apply s/zext using ConstantExpr::getCast.
616 // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
617 Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
618 } else {
619 Instruction *Ext = (*I)->clone();
620 Ext->setOperand(0, Current);
621 Ext->insertBefore(IP);
622 Current = Ext;
623 }
Eli Benderskya108a652014-05-01 18:38:36 +0000624 }
Jingyue Wu84465472014-06-05 22:07:33 +0000625 return Current;
Eli Benderskya108a652014-05-01 18:38:36 +0000626}
627
Jingyue Wu84465472014-06-05 22:07:33 +0000628Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
629 distributeExtsAndCloneChain(UserChain.size() - 1);
630 // Remove all nullptrs (used to be s/zext) from UserChain.
631 unsigned NewSize = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000632 for (User *I : UserChain) {
633 if (I != nullptr) {
634 UserChain[NewSize] = I;
Jingyue Wu84465472014-06-05 22:07:33 +0000635 NewSize++;
636 }
Eli Benderskya108a652014-05-01 18:38:36 +0000637 }
Jingyue Wu84465472014-06-05 22:07:33 +0000638 UserChain.resize(NewSize);
639 return removeConstOffset(UserChain.size() - 1);
Eli Benderskya108a652014-05-01 18:38:36 +0000640}
641
Jingyue Wu84465472014-06-05 22:07:33 +0000642Value *
643ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
644 User *U = UserChain[ChainIndex];
645 if (ChainIndex == 0) {
646 assert(isa<ConstantInt>(U));
647 // If U is a ConstantInt, applyExts will return a ConstantInt as well.
648 return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
649 }
Eli Benderskya108a652014-05-01 18:38:36 +0000650
Jingyue Wu84465472014-06-05 22:07:33 +0000651 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
652 assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
653 "We only traced into two types of CastInst: sext and zext");
654 ExtInsts.push_back(Cast);
655 UserChain[ChainIndex] = nullptr;
656 return distributeExtsAndCloneChain(ChainIndex - 1);
657 }
658
659 // Function find only trace into BinaryOperator and CastInst.
660 BinaryOperator *BO = cast<BinaryOperator>(U);
661 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
662 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
663 Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
664 Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
665
666 BinaryOperator *NewBO = nullptr;
667 if (OpNo == 0) {
668 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
669 BO->getName(), IP);
670 } else {
671 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
672 BO->getName(), IP);
673 }
674 return UserChain[ChainIndex] = NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000675}
676
Jingyue Wu84465472014-06-05 22:07:33 +0000677Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
678 if (ChainIndex == 0) {
679 assert(isa<ConstantInt>(UserChain[ChainIndex]));
680 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
681 }
Eli Benderskya108a652014-05-01 18:38:36 +0000682
Jingyue Wu84465472014-06-05 22:07:33 +0000683 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000684 assert(BO->getNumUses() <= 1 &&
685 "distributeExtsAndCloneChain clones each BinaryOperator in "
686 "UserChain, so no one should be used more than "
687 "once");
688
Jingyue Wu84465472014-06-05 22:07:33 +0000689 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
690 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
691 Value *NextInChain = removeConstOffset(ChainIndex - 1);
692 Value *TheOther = BO->getOperand(1 - OpNo);
693
694 // If NextInChain is 0 and not the LHS of a sub, we can simplify the
695 // sub-expression to be just TheOther.
696 if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
697 if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
698 return TheOther;
699 }
700
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000701 BinaryOperator::BinaryOps NewOp = BO->getOpcode();
Jingyue Wu84465472014-06-05 22:07:33 +0000702 if (BO->getOpcode() == Instruction::Or) {
703 // Rebuild "or" as "add", because "or" may be invalid for the new
704 // epxression.
705 //
706 // For instance, given
707 // a | (b + 5) where a and b + 5 have no common bits,
708 // we can extract 5 as the constant offset.
709 //
710 // However, reusing the "or" in the new index would give us
711 // (a | b) + 5
712 // which does not equal a | (b + 5).
713 //
714 // Replacing the "or" with "add" is fine, because
715 // a | (b + 5) = a + (b + 5) = (a + b) + 5
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000716 NewOp = Instruction::Add;
Jingyue Wu84465472014-06-05 22:07:33 +0000717 }
718
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000719 BinaryOperator *NewBO;
720 if (OpNo == 0) {
721 NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
722 } else {
723 NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
724 }
725 NewBO->takeName(BO);
726 return NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000727}
728
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000729Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
Jingyue Wuca321902015-05-14 23:53:19 +0000730 User *&UserChainTail,
731 const DominatorTree *DT) {
732 ConstantOffsetExtractor Extractor(GEP, DT);
Eli Benderskya108a652014-05-01 18:38:36 +0000733 // Find a non-zero constant offset first.
Jingyue Wu84465472014-06-05 22:07:33 +0000734 APInt ConstantOffset =
735 Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
736 GEP->isInBounds());
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000737 if (ConstantOffset == 0) {
738 UserChainTail = nullptr;
Hao Liu1d2a0612014-11-19 06:24:44 +0000739 return nullptr;
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000740 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000741 // Separates the constant offset from the GEP index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000742 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
743 UserChainTail = Extractor.UserChain.back();
744 return IdxWithoutConstOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000745}
746
Jingyue Wuca321902015-05-14 23:53:19 +0000747int64_t ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP,
748 const DominatorTree *DT) {
Jingyue Wu84465472014-06-05 22:07:33 +0000749 // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
Jingyue Wuca321902015-05-14 23:53:19 +0000750 return ConstantOffsetExtractor(GEP, DT)
Jingyue Wu84465472014-06-05 22:07:33 +0000751 .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
752 GEP->isInBounds())
753 .getSExtValue();
Eli Benderskya108a652014-05-01 18:38:36 +0000754}
755
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000756bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
757 GetElementPtrInst *GEP) {
758 bool Changed = false;
Jingyue Wuca321902015-05-14 23:53:19 +0000759 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000760 gep_type_iterator GTI = gep_type_begin(*GEP);
761 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
762 I != E; ++I, ++GTI) {
763 // Skip struct member indices which must be i32.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000764 if (GTI.isSequential()) {
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000765 if ((*I)->getType() != IntPtrTy) {
766 *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
767 Changed = true;
768 }
769 }
770 }
771 return Changed;
772}
773
774int64_t
775SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
776 bool &NeedsExtraction) {
Eli Benderskya108a652014-05-01 18:38:36 +0000777 NeedsExtraction = false;
778 int64_t AccumulativeByteOffset = 0;
779 gep_type_iterator GTI = gep_type_begin(*GEP);
780 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000781 if (GTI.isSequential()) {
Eli Benderskya108a652014-05-01 18:38:36 +0000782 // Tries to extract a constant offset from this GEP index.
783 int64_t ConstantOffset =
Jingyue Wuca321902015-05-14 23:53:19 +0000784 ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP, DT);
Eli Benderskya108a652014-05-01 18:38:36 +0000785 if (ConstantOffset != 0) {
786 NeedsExtraction = true;
787 // A GEP may have multiple indices. We accumulate the extracted
788 // constant offset to a byte offset, and later offset the remainder of
789 // the original GEP with this byte offset.
790 AccumulativeByteOffset +=
Jingyue Wuca321902015-05-14 23:53:19 +0000791 ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
Eli Benderskya108a652014-05-01 18:38:36 +0000792 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000793 } else if (LowerGEP) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000794 StructType *StTy = GTI.getStructType();
Hao Liu1d2a0612014-11-19 06:24:44 +0000795 uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
796 // Skip field 0 as the offset is always 0.
797 if (Field != 0) {
798 NeedsExtraction = true;
799 AccumulativeByteOffset +=
Jingyue Wuca321902015-05-14 23:53:19 +0000800 DL->getStructLayout(StTy)->getElementOffset(Field);
Hao Liu1d2a0612014-11-19 06:24:44 +0000801 }
Eli Benderskya108a652014-05-01 18:38:36 +0000802 }
803 }
804 return AccumulativeByteOffset;
805}
806
Hao Liu1d2a0612014-11-19 06:24:44 +0000807void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
808 GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
809 IRBuilder<> Builder(Variadic);
Jingyue Wuca321902015-05-14 23:53:19 +0000810 Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000811
812 Type *I8PtrTy =
813 Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
814 Value *ResultPtr = Variadic->getOperand(0);
Lawrence Hucac0b892015-09-23 19:25:30 +0000815 Loop *L = LI->getLoopFor(Variadic->getParent());
816 // Check if the base is not loop invariant or used more than once.
817 bool isSwapCandidate =
818 L && L->isLoopInvariant(ResultPtr) &&
819 !hasMoreThanOneUseInLoop(ResultPtr, L);
820 Value *FirstResult = nullptr;
821
Hao Liu1d2a0612014-11-19 06:24:44 +0000822 if (ResultPtr->getType() != I8PtrTy)
823 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
824
825 gep_type_iterator GTI = gep_type_begin(*Variadic);
826 // Create an ugly GEP for each sequential index. We don't create GEPs for
827 // structure indices, as they are accumulated in the constant offset index.
828 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000829 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000830 Value *Idx = Variadic->getOperand(I);
831 // Skip zero indices.
832 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
833 if (CI->isZero())
834 continue;
835
836 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Jingyue Wuca321902015-05-14 23:53:19 +0000837 DL->getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000838 // Scale the index by element size.
839 if (ElementSize != 1) {
840 if (ElementSize.isPowerOf2()) {
841 Idx = Builder.CreateShl(
842 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
843 } else {
844 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
845 }
846 }
847 // Create an ugly GEP with a single index for each index.
David Blaikie93c54442015-04-03 19:41:44 +0000848 ResultPtr =
849 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Idx, "uglygep");
Lawrence Hucac0b892015-09-23 19:25:30 +0000850 if (FirstResult == nullptr)
851 FirstResult = ResultPtr;
Hao Liu1d2a0612014-11-19 06:24:44 +0000852 }
853 }
854
855 // Create a GEP with the constant offset index.
856 if (AccumulativeByteOffset != 0) {
857 Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
David Blaikie93c54442015-04-03 19:41:44 +0000858 ResultPtr =
859 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Offset, "uglygep");
Lawrence Hucac0b892015-09-23 19:25:30 +0000860 } else
861 isSwapCandidate = false;
862
863 // If we created a GEP with constant index, and the base is loop invariant,
864 // then we swap the first one with it, so LICM can move constant GEP out
865 // later.
Lawrence Hu84e6f1d2016-02-19 02:17:07 +0000866 GetElementPtrInst *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
867 GetElementPtrInst *SecondGEP = dyn_cast_or_null<GetElementPtrInst>(ResultPtr);
Lawrence Hucac0b892015-09-23 19:25:30 +0000868 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
869 swapGEPOperand(FirstGEP, SecondGEP);
870
Hao Liu1d2a0612014-11-19 06:24:44 +0000871 if (ResultPtr->getType() != Variadic->getType())
872 ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
873
874 Variadic->replaceAllUsesWith(ResultPtr);
875 Variadic->eraseFromParent();
876}
877
878void
879SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
880 int64_t AccumulativeByteOffset) {
881 IRBuilder<> Builder(Variadic);
Jingyue Wuca321902015-05-14 23:53:19 +0000882 Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000883
884 Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
885 gep_type_iterator GTI = gep_type_begin(*Variadic);
886 // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
887 // don't create arithmetics for structure indices, as they are accumulated
888 // in the constant offset index.
889 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000890 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000891 Value *Idx = Variadic->getOperand(I);
892 // Skip zero indices.
893 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
894 if (CI->isZero())
895 continue;
896
897 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Jingyue Wuca321902015-05-14 23:53:19 +0000898 DL->getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000899 // Scale the index by element size.
900 if (ElementSize != 1) {
901 if (ElementSize.isPowerOf2()) {
902 Idx = Builder.CreateShl(
903 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
904 } else {
905 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
906 }
907 }
908 // Create an ADD for each index.
909 ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
910 }
911 }
912
913 // Create an ADD for the constant offset index.
914 if (AccumulativeByteOffset != 0) {
915 ResultPtr = Builder.CreateAdd(
916 ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
917 }
918
919 ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
920 Variadic->replaceAllUsesWith(ResultPtr);
921 Variadic->eraseFromParent();
922}
923
Eli Benderskya108a652014-05-01 18:38:36 +0000924bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
925 // Skip vector GEPs.
926 if (GEP->getType()->isVectorTy())
927 return false;
928
929 // The backend can already nicely handle the case where all indices are
930 // constant.
931 if (GEP->hasAllConstantIndices())
932 return false;
933
Jingyue Wu0bdc0272014-07-16 23:25:00 +0000934 bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000935
Eli Benderskya108a652014-05-01 18:38:36 +0000936 bool NeedsExtraction;
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000937 int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
Eli Benderskya108a652014-05-01 18:38:36 +0000938
939 if (!NeedsExtraction)
940 return Changed;
David Blaikie8ad9a972018-03-28 22:28:50 +0000941
942 TargetTransformInfo &TTI =
943 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*GEP->getFunction());
944
Hao Liu1d2a0612014-11-19 06:24:44 +0000945 // If LowerGEP is disabled, before really splitting the GEP, check whether the
946 // backend supports the addressing mode we are about to produce. If no, this
947 // splitting probably won't be beneficial.
948 // If LowerGEP is enabled, even the extracted constant offset can not match
949 // the addressing mode, we can still do optimizations to other lowered parts
950 // of variable indices. Therefore, we don't check for addressing modes in that
951 // case.
952 if (!LowerGEP) {
Matt Arsenaulte81944f2015-06-07 20:17:44 +0000953 unsigned AddrSpace = GEP->getPointerAddressSpace();
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000954 if (!TTI.isLegalAddressingMode(GEP->getResultElementType(),
Hao Liu1d2a0612014-11-19 06:24:44 +0000955 /*BaseGV=*/nullptr, AccumulativeByteOffset,
Matt Arsenaulte81944f2015-06-07 20:17:44 +0000956 /*HasBaseReg=*/true, /*Scale=*/0,
957 AddrSpace)) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000958 return Changed;
959 }
Eli Benderskya108a652014-05-01 18:38:36 +0000960 }
961
Hao Liu1d2a0612014-11-19 06:24:44 +0000962 // Remove the constant offset in each sequential index. The resultant GEP
963 // computes the variadic base.
964 // Notice that we don't remove struct field indices here. If LowerGEP is
965 // disabled, a structure index is not accumulated and we still use the old
966 // one. If LowerGEP is enabled, a structure index is accumulated in the
967 // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
968 // handle the constant offset and won't need a new structure index.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000969 gep_type_iterator GTI = gep_type_begin(*GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000970 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000971 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000972 // Splits this GEP index into a variadic part and a constant offset, and
973 // uses the variadic part as the new index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000974 Value *OldIdx = GEP->getOperand(I);
975 User *UserChainTail;
976 Value *NewIdx =
Jingyue Wuca321902015-05-14 23:53:19 +0000977 ConstantOffsetExtractor::Extract(OldIdx, GEP, UserChainTail, DT);
Hao Liu1d2a0612014-11-19 06:24:44 +0000978 if (NewIdx != nullptr) {
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000979 // Switches to the index with the constant offset removed.
Eli Benderskya108a652014-05-01 18:38:36 +0000980 GEP->setOperand(I, NewIdx);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000981 // After switching to the new index, we can garbage-collect UserChain
982 // and the old index if they are not used.
983 RecursivelyDeleteTriviallyDeadInstructions(UserChainTail);
984 RecursivelyDeleteTriviallyDeadInstructions(OldIdx);
Eli Benderskya108a652014-05-01 18:38:36 +0000985 }
986 }
987 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000988
Jingyue Wu84465472014-06-05 22:07:33 +0000989 // Clear the inbounds attribute because the new index may be off-bound.
990 // e.g.,
991 //
Jingyue Wu1238f342015-08-14 02:02:05 +0000992 // b = add i64 a, 5
993 // addr = gep inbounds float, float* p, i64 b
Jingyue Wu84465472014-06-05 22:07:33 +0000994 //
995 // is transformed to:
996 //
Jingyue Wu1238f342015-08-14 02:02:05 +0000997 // addr2 = gep float, float* p, i64 a ; inbounds removed
998 // addr = gep inbounds float, float* addr2, i64 5
Jingyue Wu84465472014-06-05 22:07:33 +0000999 //
1000 // If a is -4, although the old index b is in bounds, the new index a is
1001 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
1002 // inbounds keyword is not present, the offsets are added to the base
1003 // address with silently-wrapping two's complement arithmetic".
1004 // Therefore, the final code will be a semantically equivalent.
1005 //
1006 // TODO(jingyue): do some range analysis to keep as many inbounds as
1007 // possible. GEPs with inbounds are more friendly to alias analysis.
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001008 bool GEPWasInBounds = GEP->isInBounds();
Jingyue Wu84465472014-06-05 22:07:33 +00001009 GEP->setIsInBounds(false);
Eli Benderskya108a652014-05-01 18:38:36 +00001010
Hao Liu1d2a0612014-11-19 06:24:44 +00001011 // Lowers a GEP to either GEPs with a single index or arithmetic operations.
1012 if (LowerGEP) {
1013 // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
1014 // arithmetic operations if the target uses alias analysis in codegen.
David Blaikie8ad9a972018-03-28 22:28:50 +00001015 if (TTI.useAA())
Hao Liu1d2a0612014-11-19 06:24:44 +00001016 lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
1017 else
1018 lowerToArithmetics(GEP, AccumulativeByteOffset);
1019 return true;
1020 }
1021
1022 // No need to create another GEP if the accumulative byte offset is 0.
1023 if (AccumulativeByteOffset == 0)
1024 return true;
1025
Eli Benderskya108a652014-05-01 18:38:36 +00001026 // Offsets the base with the accumulative byte offset.
1027 //
1028 // %gep ; the base
1029 // ... %gep ...
1030 //
1031 // => add the offset
1032 //
1033 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001034 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +00001035 // %gep ; will be removed
1036 // ... %gep ...
1037 //
1038 // => replace all uses of %gep with %new.gep and remove %gep
1039 //
1040 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001041 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +00001042 // ... %new.gep ...
1043 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001044 // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
1045 // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
1046 // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
1047 // type of %gep.
Eli Benderskya108a652014-05-01 18:38:36 +00001048 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001049 // %gep2 ; clone of %gep
1050 // %0 = bitcast %gep2 to i8*
1051 // %uglygep = gep %0, <offset>
1052 // %new.gep = bitcast %uglygep to <type of %gep>
1053 // ... %new.gep ...
Eli Benderskya108a652014-05-01 18:38:36 +00001054 Instruction *NewGEP = GEP->clone();
1055 NewGEP->insertBefore(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +00001056
Jingyue Wufe72fce2014-10-25 18:34:03 +00001057 // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
1058 // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
1059 // used with unsigned integers later.
1060 int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001061 DL->getTypeAllocSize(GEP->getResultElementType()));
Jingyue Wuca321902015-05-14 23:53:19 +00001062 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001063 if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
1064 // Very likely. As long as %gep is natually aligned, the byte offset we
1065 // extracted should be a multiple of sizeof(*%gep).
Jingyue Wufe72fce2014-10-25 18:34:03 +00001066 int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
David Blaikie741c8f82015-03-14 01:53:18 +00001067 NewGEP = GetElementPtrInst::Create(GEP->getResultElementType(), NewGEP,
1068 ConstantInt::get(IntPtrTy, Index, true),
1069 GEP->getName(), GEP);
Marek Olsak8e7d1492018-01-31 20:17:52 +00001070 NewGEP->copyMetadata(*GEP);
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001071 // Inherit the inbounds attribute of the original GEP.
1072 cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001073 } else {
1074 // Unlikely but possible. For example,
1075 // #pragma pack(1)
1076 // struct S {
1077 // int a[3];
1078 // int64 b[8];
1079 // };
1080 // #pragma pack()
1081 //
1082 // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
1083 // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
1084 // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
1085 // sizeof(int64).
1086 //
1087 // Emit an uglygep in this case.
1088 Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
1089 GEP->getPointerAddressSpace());
1090 NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
1091 NewGEP = GetElementPtrInst::Create(
David Blaikie741c8f82015-03-14 01:53:18 +00001092 Type::getInt8Ty(GEP->getContext()), NewGEP,
1093 ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "uglygep",
1094 GEP);
Marek Olsak8e7d1492018-01-31 20:17:52 +00001095 NewGEP->copyMetadata(*GEP);
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001096 // Inherit the inbounds attribute of the original GEP.
1097 cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001098 if (GEP->getType() != I8PtrTy)
1099 NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
1100 }
1101
1102 GEP->replaceAllUsesWith(NewGEP);
Eli Benderskya108a652014-05-01 18:38:36 +00001103 GEP->eraseFromParent();
1104
1105 return true;
1106}
1107
1108bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001109 if (skipFunction(F))
Jingyue Wu6c26bb62015-02-01 02:34:41 +00001110 return false;
1111
Eli Benderskya108a652014-05-01 18:38:36 +00001112 if (DisableSeparateConstOffsetFromGEP)
1113 return false;
1114
Jingyue Wuca321902015-05-14 23:53:19 +00001115 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001116 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Lawrence Hucac0b892015-09-23 19:25:30 +00001117 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1118 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Eli Benderskya108a652014-05-01 18:38:36 +00001119 bool Changed = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001120 for (BasicBlock &B : F) {
1121 for (BasicBlock::iterator I = B.begin(), IE = B.end(); I != IE;)
Lawrence Hucac0b892015-09-23 19:25:30 +00001122 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++))
Eli Benderskya108a652014-05-01 18:38:36 +00001123 Changed |= splitGEP(GEP);
Lawrence Hucac0b892015-09-23 19:25:30 +00001124 // No need to split GEP ConstantExprs because all its indices are constant
1125 // already.
Eli Benderskya108a652014-05-01 18:38:36 +00001126 }
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001127
Jingyue Wu1238f342015-08-14 02:02:05 +00001128 Changed |= reuniteExts(F);
1129
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001130 if (VerifyNoDeadCode)
1131 verifyNoDeadCode(F);
1132
Eli Benderskya108a652014-05-01 18:38:36 +00001133 return Changed;
1134}
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001135
Jingyue Wu1238f342015-08-14 02:02:05 +00001136Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1137 const SCEV *Key, Instruction *Dominatee) {
1138 auto Pos = DominatingExprs.find(Key);
1139 if (Pos == DominatingExprs.end())
1140 return nullptr;
1141
1142 auto &Candidates = Pos->second;
1143 // Because we process the basic blocks in pre-order of the dominator tree, a
1144 // candidate that doesn't dominate the current instruction won't dominate any
1145 // future instruction either. Therefore, we pop it out of the stack. This
1146 // optimization makes the algorithm O(n).
1147 while (!Candidates.empty()) {
1148 Instruction *Candidate = Candidates.back();
1149 if (DT->dominates(Candidate, Dominatee))
1150 return Candidate;
1151 Candidates.pop_back();
1152 }
1153 return nullptr;
1154}
1155
1156bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1157 if (!SE->isSCEVable(I->getType()))
1158 return false;
1159
1160 // Dom: LHS+RHS
1161 // I: sext(LHS)+sext(RHS)
1162 // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1163 // TODO: handle zext
1164 Value *LHS = nullptr, *RHS = nullptr;
1165 if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS)))) ||
1166 match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1167 if (LHS->getType() == RHS->getType()) {
1168 const SCEV *Key =
1169 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1170 if (auto *Dom = findClosestMatchingDominator(Key, I)) {
1171 Instruction *NewSExt = new SExtInst(Dom, I->getType(), "", I);
1172 NewSExt->takeName(I);
1173 I->replaceAllUsesWith(NewSExt);
1174 RecursivelyDeleteTriviallyDeadInstructions(I);
1175 return true;
1176 }
1177 }
1178 }
1179
1180 // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
1181 if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS))) ||
1182 match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
Sanjoy Das08989c72017-04-30 19:41:19 +00001183 if (programUndefinedIfFullPoison(I)) {
Jingyue Wu1238f342015-08-14 02:02:05 +00001184 const SCEV *Key =
1185 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1186 DominatingExprs[Key].push_back(I);
1187 }
1188 }
1189 return false;
1190}
1191
1192bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1193 bool Changed = false;
1194 DominatingExprs.clear();
Daniel Berlin11da66f2016-08-19 22:18:38 +00001195 for (const auto Node : depth_first(DT)) {
1196 BasicBlock *BB = Node->getBlock();
1197 for (auto I = BB->begin(); I != BB->end(); ) {
1198 Instruction *Cur = &*I++;
1199 Changed |= reuniteExts(Cur);
1200 }
1201 }
Jingyue Wu1238f342015-08-14 02:02:05 +00001202 return Changed;
1203}
1204
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001205void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001206 for (BasicBlock &B : F) {
1207 for (Instruction &I : B) {
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001208 if (isInstructionTriviallyDead(&I)) {
1209 std::string ErrMessage;
1210 raw_string_ostream RSO(ErrMessage);
1211 RSO << "Dead instruction detected!\n" << I << "\n";
1212 llvm_unreachable(RSO.str().c_str());
1213 }
1214 }
1215 }
1216}
Lawrence Hucac0b892015-09-23 19:25:30 +00001217
1218bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1219 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP, Loop *CurLoop) {
1220 if (!FirstGEP || !FirstGEP->hasOneUse())
1221 return false;
1222
1223 if (!SecondGEP || FirstGEP->getParent() != SecondGEP->getParent())
1224 return false;
1225
1226 if (FirstGEP == SecondGEP)
1227 return false;
1228
1229 unsigned FirstNum = FirstGEP->getNumOperands();
1230 unsigned SecondNum = SecondGEP->getNumOperands();
1231 // Give up if the number of operands are not 2.
1232 if (FirstNum != SecondNum || FirstNum != 2)
1233 return false;
1234
1235 Value *FirstBase = FirstGEP->getOperand(0);
1236 Value *SecondBase = SecondGEP->getOperand(0);
1237 Value *FirstOffset = FirstGEP->getOperand(1);
1238 // Give up if the index of the first GEP is loop invariant.
1239 if (CurLoop->isLoopInvariant(FirstOffset))
1240 return false;
1241
1242 // Give up if base doesn't have same type.
1243 if (FirstBase->getType() != SecondBase->getType())
1244 return false;
1245
1246 Instruction *FirstOffsetDef = dyn_cast<Instruction>(FirstOffset);
1247
1248 // Check if the second operand of first GEP has constant coefficient.
1249 // For an example, for the following code, we won't gain anything by
1250 // hoisting the second GEP out because the second GEP can be folded away.
1251 // %scevgep.sum.ur159 = add i64 %idxprom48.ur, 256
1252 // %67 = shl i64 %scevgep.sum.ur159, 2
1253 // %uglygep160 = getelementptr i8* %65, i64 %67
1254 // %uglygep161 = getelementptr i8* %uglygep160, i64 -1024
1255
1256 // Skip constant shift instruction which may be generated by Splitting GEPs.
1257 if (FirstOffsetDef && FirstOffsetDef->isShift() &&
Craig Topper66059c92015-11-18 07:07:59 +00001258 isa<ConstantInt>(FirstOffsetDef->getOperand(1)))
Lawrence Hucac0b892015-09-23 19:25:30 +00001259 FirstOffsetDef = dyn_cast<Instruction>(FirstOffsetDef->getOperand(0));
1260
1261 // Give up if FirstOffsetDef is an Add or Sub with constant.
1262 // Because it may not profitable at all due to constant folding.
1263 if (FirstOffsetDef)
1264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FirstOffsetDef)) {
1265 unsigned opc = BO->getOpcode();
1266 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
Craig Topper66059c92015-11-18 07:07:59 +00001267 (isa<ConstantInt>(BO->getOperand(0)) ||
1268 isa<ConstantInt>(BO->getOperand(1))))
Lawrence Hucac0b892015-09-23 19:25:30 +00001269 return false;
1270 }
1271 return true;
1272}
1273
1274bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(Value *V, Loop *L) {
1275 int UsesInLoop = 0;
1276 for (User *U : V->users()) {
1277 if (Instruction *User = dyn_cast<Instruction>(U))
1278 if (L->contains(User))
1279 if (++UsesInLoop > 1)
1280 return true;
1281 }
1282 return false;
1283}
1284
1285void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *First,
1286 GetElementPtrInst *Second) {
1287 Value *Offset1 = First->getOperand(1);
1288 Value *Offset2 = Second->getOperand(1);
1289 First->setOperand(1, Offset2);
1290 Second->setOperand(1, Offset1);
1291
1292 // We changed p+o+c to p+c+o, p+c may not be inbound anymore.
1293 const DataLayout &DAL = First->getModule()->getDataLayout();
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001294 APInt Offset(DAL.getIndexSizeInBits(
Lawrence Hucac0b892015-09-23 19:25:30 +00001295 cast<PointerType>(First->getType())->getAddressSpace()),
1296 0);
1297 Value *NewBase =
1298 First->stripAndAccumulateInBoundsConstantOffsets(DAL, Offset);
1299 uint64_t ObjectSize;
1300 if (!getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1301 Offset.ugt(ObjectSize)) {
1302 First->setIsInBounds(false);
1303 Second->setIsInBounds(false);
1304 } else
1305 First->setIsInBounds(true);
1306}