blob: 0eca6704b496e2ed489ccc6e3dc6f33d7c77667a [file] [log] [blame]
Eugene Zelenko5adb96c2017-10-26 00:55:39 +00001//===- SeparateConstOffsetFromGEP.cpp -------------------------------------===//
Eli Benderskya108a652014-05-01 18:38:36 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eli Benderskya108a652014-05-01 18:38:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Loop unrolling may create many similar GEPs for array accesses.
10// e.g., a 2-level loop
11//
12// float a[32][32]; // global variable
13//
14// for (int i = 0; i < 2; ++i) {
15// for (int j = 0; j < 2; ++j) {
16// ...
17// ... = a[x + i][y + j];
18// ...
19// }
20// }
21//
22// will probably be unrolled to:
23//
24// gep %a, 0, %x, %y; load
25// gep %a, 0, %x, %y + 1; load
26// gep %a, 0, %x + 1, %y; load
27// gep %a, 0, %x + 1, %y + 1; load
28//
29// LLVM's GVN does not use partial redundancy elimination yet, and is thus
30// unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
31// significant slowdown in targets with limited addressing modes. For instance,
32// because the PTX target does not support the reg+reg addressing mode, the
33// NVPTX backend emits PTX code that literally computes the pointer address of
34// each GEP, wasting tons of registers. It emits the following PTX for the
35// first load and similar PTX for other loads.
36//
37// mov.u32 %r1, %x;
38// mov.u32 %r2, %y;
39// mul.wide.u32 %rl2, %r1, 128;
40// mov.u64 %rl3, a;
41// add.s64 %rl4, %rl3, %rl2;
42// mul.wide.u32 %rl5, %r2, 4;
43// add.s64 %rl6, %rl4, %rl5;
44// ld.global.f32 %f1, [%rl6];
45//
46// To reduce the register pressure, the optimization implemented in this file
47// merges the common part of a group of GEPs, so we can compute each pointer
48// address by adding a simple offset to the common part, saving many registers.
49//
50// It works by splitting each GEP into a variadic base and a constant offset.
51// The variadic base can be computed once and reused by multiple GEPs, and the
52// constant offsets can be nicely folded into the reg+immediate addressing mode
53// (supported by most targets) without using any extra register.
54//
55// For instance, we transform the four GEPs and four loads in the above example
56// into:
57//
58// base = gep a, 0, x, y
59// load base
60// laod base + 1 * sizeof(float)
61// load base + 32 * sizeof(float)
62// load base + 33 * sizeof(float)
63//
64// Given the transformed IR, a backend that supports the reg+immediate
65// addressing mode can easily fold the pointer arithmetics into the loads. For
66// example, the NVPTX backend can easily fold the pointer arithmetics into the
67// ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
68//
69// mov.u32 %r1, %tid.x;
70// mov.u32 %r2, %tid.y;
71// mul.wide.u32 %rl2, %r1, 128;
72// mov.u64 %rl3, a;
73// add.s64 %rl4, %rl3, %rl2;
74// mul.wide.u32 %rl5, %r2, 4;
75// add.s64 %rl6, %rl4, %rl5;
76// ld.global.f32 %f1, [%rl6]; // so far the same as unoptimized PTX
77// ld.global.f32 %f2, [%rl6+4]; // much better
78// ld.global.f32 %f3, [%rl6+128]; // much better
79// ld.global.f32 %f4, [%rl6+132]; // much better
80//
Hao Liu1d2a0612014-11-19 06:24:44 +000081// Another improvement enabled by the LowerGEP flag is to lower a GEP with
82// multiple indices to either multiple GEPs with a single index or arithmetic
83// operations (depending on whether the target uses alias analysis in codegen).
84// Such transformation can have following benefits:
85// (1) It can always extract constants in the indices of structure type.
86// (2) After such Lowering, there are more optimization opportunities such as
87// CSE, LICM and CGP.
88//
89// E.g. The following GEPs have multiple indices:
90// BB1:
91// %p = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 3
92// load %p
93// ...
94// BB2:
95// %p2 = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 2
96// load %p2
97// ...
98//
Haicheng Wu5b106ef2017-12-19 18:49:21 +000099// We can not do CSE to the common part related to index "i64 %i". Lowering
Hao Liu1d2a0612014-11-19 06:24:44 +0000100// GEPs can achieve such goals.
101// If the target does not use alias analysis in codegen, this pass will
102// lower a GEP with multiple indices into arithmetic operations:
103// BB1:
104// %1 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
105// %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
106// %3 = add i64 %1, %2 ; CSE opportunity
107// %4 = mul i64 %j1, length_of_struct
108// %5 = add i64 %3, %4
109// %6 = add i64 %3, struct_field_3 ; Constant offset
110// %p = inttoptr i64 %6 to i32*
111// load %p
112// ...
113// BB2:
114// %7 = ptrtoint [10 x %struct]* %ptr to i64 ; CSE opportunity
115// %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
116// %9 = add i64 %7, %8 ; CSE opportunity
117// %10 = mul i64 %j2, length_of_struct
118// %11 = add i64 %9, %10
119// %12 = add i64 %11, struct_field_2 ; Constant offset
120// %p = inttoptr i64 %12 to i32*
121// load %p2
122// ...
123//
124// If the target uses alias analysis in codegen, this pass will lower a GEP
125// with multiple indices into multiple GEPs with a single index:
126// BB1:
127// %1 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
128// %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
129// %3 = getelementptr i8* %1, i64 %2 ; CSE opportunity
130// %4 = mul i64 %j1, length_of_struct
131// %5 = getelementptr i8* %3, i64 %4
132// %6 = getelementptr i8* %5, struct_field_3 ; Constant offset
133// %p = bitcast i8* %6 to i32*
134// load %p
135// ...
136// BB2:
137// %7 = bitcast [10 x %struct]* %ptr to i8* ; CSE opportunity
138// %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
139// %9 = getelementptr i8* %7, i64 %8 ; CSE opportunity
140// %10 = mul i64 %j2, length_of_struct
141// %11 = getelementptr i8* %9, i64 %10
142// %12 = getelementptr i8* %11, struct_field_2 ; Constant offset
143// %p2 = bitcast i8* %12 to i32*
144// load %p2
145// ...
146//
147// Lowering GEPs can also benefit other passes such as LICM and CGP.
148// LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
149// indices if one of the index is variant. If we lower such GEP into invariant
150// parts and variant parts, LICM can hoist/sink those invariant parts.
151// CGP (CodeGen Prepare) tries to sink address calculations that match the
152// target's addressing modes. A GEP with multiple indices may not match and will
153// not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
154// them. So we end up with a better addressing mode.
155//
Eli Benderskya108a652014-05-01 18:38:36 +0000156//===----------------------------------------------------------------------===//
157
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000158#include "llvm/ADT/APInt.h"
159#include "llvm/ADT/DenseMap.h"
160#include "llvm/ADT/DepthFirstIterator.h"
161#include "llvm/ADT/SmallVector.h"
Lawrence Hucac0b892015-09-23 19:25:30 +0000162#include "llvm/Analysis/LoopInfo.h"
163#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000164#include "llvm/Analysis/ScalarEvolution.h"
Lawrence Hucac0b892015-09-23 19:25:30 +0000165#include "llvm/Analysis/TargetLibraryInfo.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000166#include "llvm/Analysis/TargetTransformInfo.h"
167#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000168#include "llvm/IR/BasicBlock.h"
169#include "llvm/IR/Constant.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000170#include "llvm/IR/Constants.h"
171#include "llvm/IR/DataLayout.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000172#include "llvm/IR/DerivedTypes.h"
Jingyue Wuca321902015-05-14 23:53:19 +0000173#include "llvm/IR/Dominators.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000174#include "llvm/IR/Function.h"
175#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000176#include "llvm/IR/IRBuilder.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000177#include "llvm/IR/Instruction.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000178#include "llvm/IR/Instructions.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000179#include "llvm/IR/Module.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000180#include "llvm/IR/PatternMatch.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000181#include "llvm/IR/Type.h"
182#include "llvm/IR/User.h"
183#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -0800184#include "llvm/InitializePasses.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000185#include "llvm/Pass.h"
186#include "llvm/Support/Casting.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000187#include "llvm/Support/CommandLine.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000188#include "llvm/Support/ErrorHandling.h"
Eli Benderskya108a652014-05-01 18:38:36 +0000189#include "llvm/Support/raw_ostream.h"
Hao Liu1d2a0612014-11-19 06:24:44 +0000190#include "llvm/Target/TargetMachine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000191#include "llvm/Transforms/Scalar.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -0800192#include "llvm/Transforms/Utils/Local.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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000215/// A helper class for separating a constant offset from a GEP index.
Eli Benderskya108a652014-05-01 18:38:36 +0000216///
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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342/// 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>.
Drew Wock0bcfafc2020-01-15 12:51:42 -0500434 Instruction *findClosestMatchingDominator(
435 const SCEV *Key, Instruction *Dominatee,
436 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> &DominatingExprs);
437
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000438 /// Verify F is free of dead code.
439 void verifyNoDeadCode(Function &F);
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000440
Lawrence Hucac0b892015-09-23 19:25:30 +0000441 bool hasMoreThanOneUseInLoop(Value *v, Loop *L);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000442
Lawrence Hucac0b892015-09-23 19:25:30 +0000443 // Swap the index operand of two GEP.
444 void swapGEPOperand(GetElementPtrInst *First, GetElementPtrInst *Second);
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000445
Lawrence Hucac0b892015-09-23 19:25:30 +0000446 // Check if it is safe to swap operand of two GEP.
447 bool isLegalToSwapOperand(GetElementPtrInst *First, GetElementPtrInst *Second,
448 Loop *CurLoop);
449
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000450 const DataLayout *DL = nullptr;
451 DominatorTree *DT = nullptr;
Jingyue Wu1238f342015-08-14 02:02:05 +0000452 ScalarEvolution *SE;
Lawrence Hucac0b892015-09-23 19:25:30 +0000453
454 LoopInfo *LI;
455 TargetLibraryInfo *TLI;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000456
Hao Liu1d2a0612014-11-19 06:24:44 +0000457 /// Whether to lower a GEP with multiple indices into arithmetic operations or
458 /// multiple GEPs with a single index.
459 bool LowerGEP;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000460
Drew Wock0bcfafc2020-01-15 12:51:42 -0500461 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> DominatingAdds;
462 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> DominatingSubs;
Eli Benderskya108a652014-05-01 18:38:36 +0000463};
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000464
465} // end anonymous namespace
Eli Benderskya108a652014-05-01 18:38:36 +0000466
467char SeparateConstOffsetFromGEP::ID = 0;
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000468
Eli Benderskya108a652014-05-01 18:38:36 +0000469INITIALIZE_PASS_BEGIN(
470 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
471 "Split GEPs to a variadic base and a constant offset for better CSE", false,
472 false)
Jingyue Wuca321902015-05-14 23:53:19 +0000473INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000474INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000475INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Lawrence Hucac0b892015-09-23 19:25:30 +0000476INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
477INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Eli Benderskya108a652014-05-01 18:38:36 +0000478INITIALIZE_PASS_END(
479 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
480 "Split GEPs to a variadic base and a constant offset for better CSE", false,
481 false)
482
David Blaikie8ad9a972018-03-28 22:28:50 +0000483FunctionPass *llvm::createSeparateConstOffsetFromGEPPass(bool LowerGEP) {
484 return new SeparateConstOffsetFromGEP(LowerGEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000485}
486
Jingyue Wu84465472014-06-05 22:07:33 +0000487bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
488 bool ZeroExtended,
489 BinaryOperator *BO,
490 bool NonNegative) {
491 // We only consider ADD, SUB and OR, because a non-zero constant found in
492 // expressions composed of these operations can be easily hoisted as a
493 // constant offset by reassociation.
494 if (BO->getOpcode() != Instruction::Add &&
495 BO->getOpcode() != Instruction::Sub &&
496 BO->getOpcode() != Instruction::Or) {
497 return false;
498 }
499
500 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
501 // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
502 // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
Roman Lebedev25cbb622018-04-15 18:59:27 +0000503 // FIXME: this does not appear to be covered by any tests
504 // (with x86/aarch64 backends at least)
Jingyue Wuca321902015-05-14 23:53:19 +0000505 if (BO->getOpcode() == Instruction::Or &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000506 !haveNoCommonBitsSet(LHS, RHS, DL, nullptr, BO, DT))
Jingyue Wu84465472014-06-05 22:07:33 +0000507 return false;
508
509 // In addition, tracing into BO requires that its surrounding s/zext (if
510 // any) is distributable to both operands.
511 //
512 // Suppose BO = A op B.
513 // SignExtended | ZeroExtended | Distributable?
514 // --------------+--------------+----------------------------------
515 // 0 | 0 | true because no s/zext exists
516 // 0 | 1 | zext(BO) == zext(A) op zext(B)
517 // 1 | 0 | sext(BO) == sext(A) op sext(B)
518 // 1 | 1 | zext(sext(BO)) ==
519 // | | zext(sext(A)) op zext(sext(B))
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000520 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
Jingyue Wu84465472014-06-05 22:07:33 +0000521 // If a + b >= 0 and (a >= 0 or b >= 0), then
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000522 // sext(a + b) = sext(a) + sext(b)
Jingyue Wu84465472014-06-05 22:07:33 +0000523 // even if the addition is not marked nsw.
524 //
525 // Leveraging this invarient, we can trace into an sext'ed inbound GEP
526 // index if the constant offset is non-negative.
527 //
528 // Verified in @sext_add in split-gep.ll.
529 if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
530 if (!ConstLHS->isNegative())
531 return true;
532 }
533 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
534 if (!ConstRHS->isNegative())
535 return true;
536 }
537 }
Jingyue Wu80a738d2014-05-27 18:00:00 +0000538
539 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
540 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
541 if (BO->getOpcode() == Instruction::Add ||
542 BO->getOpcode() == Instruction::Sub) {
Jingyue Wu84465472014-06-05 22:07:33 +0000543 if (SignExtended && !BO->hasNoSignedWrap())
544 return false;
545 if (ZeroExtended && !BO->hasNoUnsignedWrap())
546 return false;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000547 }
548
Jingyue Wu84465472014-06-05 22:07:33 +0000549 return true;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000550}
551
Jingyue Wu84465472014-06-05 22:07:33 +0000552APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
553 bool SignExtended,
554 bool ZeroExtended) {
555 // BO being non-negative does not shed light on whether its operands are
556 // non-negative. Clear the NonNegative flag here.
557 APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
558 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000559 // If we found a constant offset in the left operand, stop and return that.
560 // This shortcut might cause us to miss opportunities of combining the
561 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
562 // However, such cases are probably already handled by -instcombine,
563 // given this pass runs after the standard optimizations.
564 if (ConstantOffset != 0) return ConstantOffset;
Jingyue Wu84465472014-06-05 22:07:33 +0000565 ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
566 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000567 // If U is a sub operator, negate the constant offset found in the right
568 // operand.
Jingyue Wu84465472014-06-05 22:07:33 +0000569 if (BO->getOpcode() == Instruction::Sub)
570 ConstantOffset = -ConstantOffset;
571 return ConstantOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000572}
573
Jingyue Wu84465472014-06-05 22:07:33 +0000574APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
575 bool ZeroExtended, bool NonNegative) {
576 // TODO(jingyue): We could trace into integer/pointer casts, such as
Eli Benderskya108a652014-05-01 18:38:36 +0000577 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
578 // integers because it gives good enough results for our benchmarks.
Jingyue Wu84465472014-06-05 22:07:33 +0000579 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Eli Benderskya108a652014-05-01 18:38:36 +0000580
Jingyue Wu84465472014-06-05 22:07:33 +0000581 // We cannot do much with Values that are not a User, such as an Argument.
Eli Benderskya108a652014-05-01 18:38:36 +0000582 User *U = dyn_cast<User>(V);
Jingyue Wu84465472014-06-05 22:07:33 +0000583 if (U == nullptr) return APInt(BitWidth, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000584
Jingyue Wu84465472014-06-05 22:07:33 +0000585 APInt ConstantOffset(BitWidth, 0);
586 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Eli Benderskya108a652014-05-01 18:38:36 +0000587 // Hooray, we found it!
Jingyue Wu84465472014-06-05 22:07:33 +0000588 ConstantOffset = CI->getValue();
589 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
590 // Trace into subexpressions for more hoisting opportunities.
Jingyue Wuca321902015-05-14 23:53:19 +0000591 if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative))
Jingyue Wu84465472014-06-05 22:07:33 +0000592 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
Artem Belevichc2cd5d52018-05-11 21:13:19 +0000593 } else if (isa<TruncInst>(V)) {
594 ConstantOffset =
595 find(U->getOperand(0), SignExtended, ZeroExtended, NonNegative)
596 .trunc(BitWidth);
Jingyue Wu84465472014-06-05 22:07:33 +0000597 } else if (isa<SExtInst>(V)) {
598 ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
599 ZeroExtended, NonNegative).sext(BitWidth);
600 } else if (isa<ZExtInst>(V)) {
601 // As an optimization, we can clear the SignExtended flag because
602 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
603 //
604 // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
Jingyue Wu84465472014-06-05 22:07:33 +0000605 ConstantOffset =
606 find(U->getOperand(0), /* SignExtended */ false,
607 /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
Eli Benderskya108a652014-05-01 18:38:36 +0000608 }
Jingyue Wu84465472014-06-05 22:07:33 +0000609
610 // If we found a non-zero constant offset, add it to the path for
611 // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
612 // help this optimization.
Eli Benderskya108a652014-05-01 18:38:36 +0000613 if (ConstantOffset != 0)
614 UserChain.push_back(U);
615 return ConstantOffset;
616}
617
Jingyue Wu84465472014-06-05 22:07:33 +0000618Value *ConstantOffsetExtractor::applyExts(Value *V) {
619 Value *Current = V;
620 // ExtInsts is built in the use-def order. Therefore, we apply them to V
621 // in the reversed order.
622 for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
623 if (Constant *C = dyn_cast<Constant>(Current)) {
624 // If Current is a constant, apply s/zext using ConstantExpr::getCast.
625 // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
626 Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
627 } else {
628 Instruction *Ext = (*I)->clone();
629 Ext->setOperand(0, Current);
630 Ext->insertBefore(IP);
631 Current = Ext;
632 }
Eli Benderskya108a652014-05-01 18:38:36 +0000633 }
Jingyue Wu84465472014-06-05 22:07:33 +0000634 return Current;
Eli Benderskya108a652014-05-01 18:38:36 +0000635}
636
Jingyue Wu84465472014-06-05 22:07:33 +0000637Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
638 distributeExtsAndCloneChain(UserChain.size() - 1);
639 // Remove all nullptrs (used to be s/zext) from UserChain.
640 unsigned NewSize = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000641 for (User *I : UserChain) {
642 if (I != nullptr) {
643 UserChain[NewSize] = I;
Jingyue Wu84465472014-06-05 22:07:33 +0000644 NewSize++;
645 }
Eli Benderskya108a652014-05-01 18:38:36 +0000646 }
Jingyue Wu84465472014-06-05 22:07:33 +0000647 UserChain.resize(NewSize);
648 return removeConstOffset(UserChain.size() - 1);
Eli Benderskya108a652014-05-01 18:38:36 +0000649}
650
Jingyue Wu84465472014-06-05 22:07:33 +0000651Value *
652ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
653 User *U = UserChain[ChainIndex];
654 if (ChainIndex == 0) {
655 assert(isa<ConstantInt>(U));
656 // If U is a ConstantInt, applyExts will return a ConstantInt as well.
657 return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
658 }
Eli Benderskya108a652014-05-01 18:38:36 +0000659
Jingyue Wu84465472014-06-05 22:07:33 +0000660 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
Artem Belevichc2cd5d52018-05-11 21:13:19 +0000661 assert(
662 (isa<SExtInst>(Cast) || isa<ZExtInst>(Cast) || isa<TruncInst>(Cast)) &&
663 "Only following instructions can be traced: sext, zext & trunc");
Jingyue Wu84465472014-06-05 22:07:33 +0000664 ExtInsts.push_back(Cast);
665 UserChain[ChainIndex] = nullptr;
666 return distributeExtsAndCloneChain(ChainIndex - 1);
667 }
668
669 // Function find only trace into BinaryOperator and CastInst.
670 BinaryOperator *BO = cast<BinaryOperator>(U);
671 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
672 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
673 Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
674 Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
675
676 BinaryOperator *NewBO = nullptr;
677 if (OpNo == 0) {
678 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
679 BO->getName(), IP);
680 } else {
681 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
682 BO->getName(), IP);
683 }
684 return UserChain[ChainIndex] = NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000685}
686
Jingyue Wu84465472014-06-05 22:07:33 +0000687Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
688 if (ChainIndex == 0) {
689 assert(isa<ConstantInt>(UserChain[ChainIndex]));
690 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
691 }
Eli Benderskya108a652014-05-01 18:38:36 +0000692
Jingyue Wu84465472014-06-05 22:07:33 +0000693 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000694 assert(BO->getNumUses() <= 1 &&
695 "distributeExtsAndCloneChain clones each BinaryOperator in "
696 "UserChain, so no one should be used more than "
697 "once");
698
Jingyue Wu84465472014-06-05 22:07:33 +0000699 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
700 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
701 Value *NextInChain = removeConstOffset(ChainIndex - 1);
702 Value *TheOther = BO->getOperand(1 - OpNo);
703
704 // If NextInChain is 0 and not the LHS of a sub, we can simplify the
705 // sub-expression to be just TheOther.
706 if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
707 if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
708 return TheOther;
709 }
710
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000711 BinaryOperator::BinaryOps NewOp = BO->getOpcode();
Jingyue Wu84465472014-06-05 22:07:33 +0000712 if (BO->getOpcode() == Instruction::Or) {
713 // Rebuild "or" as "add", because "or" may be invalid for the new
Hiroshi Inouef2096492018-06-14 05:41:49 +0000714 // expression.
Jingyue Wu84465472014-06-05 22:07:33 +0000715 //
716 // For instance, given
717 // a | (b + 5) where a and b + 5 have no common bits,
718 // we can extract 5 as the constant offset.
719 //
720 // However, reusing the "or" in the new index would give us
721 // (a | b) + 5
722 // which does not equal a | (b + 5).
723 //
724 // Replacing the "or" with "add" is fine, because
725 // a | (b + 5) = a + (b + 5) = (a + b) + 5
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000726 NewOp = Instruction::Add;
Jingyue Wu84465472014-06-05 22:07:33 +0000727 }
728
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000729 BinaryOperator *NewBO;
730 if (OpNo == 0) {
731 NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
732 } else {
733 NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
734 }
735 NewBO->takeName(BO);
736 return NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000737}
738
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000739Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
Jingyue Wuca321902015-05-14 23:53:19 +0000740 User *&UserChainTail,
741 const DominatorTree *DT) {
742 ConstantOffsetExtractor Extractor(GEP, DT);
Eli Benderskya108a652014-05-01 18:38:36 +0000743 // Find a non-zero constant offset first.
Jingyue Wu84465472014-06-05 22:07:33 +0000744 APInt ConstantOffset =
745 Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
746 GEP->isInBounds());
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000747 if (ConstantOffset == 0) {
748 UserChainTail = nullptr;
Hao Liu1d2a0612014-11-19 06:24:44 +0000749 return nullptr;
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000750 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000751 // Separates the constant offset from the GEP index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000752 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
753 UserChainTail = Extractor.UserChain.back();
754 return IdxWithoutConstOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000755}
756
Jingyue Wuca321902015-05-14 23:53:19 +0000757int64_t ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP,
758 const DominatorTree *DT) {
Jingyue Wu84465472014-06-05 22:07:33 +0000759 // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
Jingyue Wuca321902015-05-14 23:53:19 +0000760 return ConstantOffsetExtractor(GEP, DT)
Jingyue Wu84465472014-06-05 22:07:33 +0000761 .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
762 GEP->isInBounds())
763 .getSExtValue();
Eli Benderskya108a652014-05-01 18:38:36 +0000764}
765
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000766bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
767 GetElementPtrInst *GEP) {
768 bool Changed = false;
Jingyue Wuca321902015-05-14 23:53:19 +0000769 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000770 gep_type_iterator GTI = gep_type_begin(*GEP);
771 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
772 I != E; ++I, ++GTI) {
773 // Skip struct member indices which must be i32.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000774 if (GTI.isSequential()) {
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000775 if ((*I)->getType() != IntPtrTy) {
776 *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
777 Changed = true;
778 }
779 }
780 }
781 return Changed;
782}
783
784int64_t
785SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
786 bool &NeedsExtraction) {
Eli Benderskya108a652014-05-01 18:38:36 +0000787 NeedsExtraction = false;
788 int64_t AccumulativeByteOffset = 0;
789 gep_type_iterator GTI = gep_type_begin(*GEP);
790 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000791 if (GTI.isSequential()) {
Eli Benderskya108a652014-05-01 18:38:36 +0000792 // Tries to extract a constant offset from this GEP index.
793 int64_t ConstantOffset =
Jingyue Wuca321902015-05-14 23:53:19 +0000794 ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP, DT);
Eli Benderskya108a652014-05-01 18:38:36 +0000795 if (ConstantOffset != 0) {
796 NeedsExtraction = true;
797 // A GEP may have multiple indices. We accumulate the extracted
798 // constant offset to a byte offset, and later offset the remainder of
799 // the original GEP with this byte offset.
800 AccumulativeByteOffset +=
Jingyue Wuca321902015-05-14 23:53:19 +0000801 ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
Eli Benderskya108a652014-05-01 18:38:36 +0000802 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000803 } else if (LowerGEP) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000804 StructType *StTy = GTI.getStructType();
Hao Liu1d2a0612014-11-19 06:24:44 +0000805 uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
806 // Skip field 0 as the offset is always 0.
807 if (Field != 0) {
808 NeedsExtraction = true;
809 AccumulativeByteOffset +=
Jingyue Wuca321902015-05-14 23:53:19 +0000810 DL->getStructLayout(StTy)->getElementOffset(Field);
Hao Liu1d2a0612014-11-19 06:24:44 +0000811 }
Eli Benderskya108a652014-05-01 18:38:36 +0000812 }
813 }
814 return AccumulativeByteOffset;
815}
816
Hao Liu1d2a0612014-11-19 06:24:44 +0000817void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
818 GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
819 IRBuilder<> Builder(Variadic);
Jingyue Wuca321902015-05-14 23:53:19 +0000820 Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000821
822 Type *I8PtrTy =
823 Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
824 Value *ResultPtr = Variadic->getOperand(0);
Lawrence Hucac0b892015-09-23 19:25:30 +0000825 Loop *L = LI->getLoopFor(Variadic->getParent());
826 // Check if the base is not loop invariant or used more than once.
827 bool isSwapCandidate =
828 L && L->isLoopInvariant(ResultPtr) &&
829 !hasMoreThanOneUseInLoop(ResultPtr, L);
830 Value *FirstResult = nullptr;
831
Hao Liu1d2a0612014-11-19 06:24:44 +0000832 if (ResultPtr->getType() != I8PtrTy)
833 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
834
835 gep_type_iterator GTI = gep_type_begin(*Variadic);
836 // Create an ugly GEP for each sequential index. We don't create GEPs for
837 // structure indices, as they are accumulated in the constant offset index.
838 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000839 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000840 Value *Idx = Variadic->getOperand(I);
841 // Skip zero indices.
842 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
843 if (CI->isZero())
844 continue;
845
846 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Jingyue Wuca321902015-05-14 23:53:19 +0000847 DL->getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000848 // Scale the index by element size.
849 if (ElementSize != 1) {
850 if (ElementSize.isPowerOf2()) {
851 Idx = Builder.CreateShl(
852 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
853 } else {
854 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
855 }
856 }
857 // Create an ugly GEP with a single index for each index.
David Blaikie93c54442015-04-03 19:41:44 +0000858 ResultPtr =
859 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Idx, "uglygep");
Lawrence Hucac0b892015-09-23 19:25:30 +0000860 if (FirstResult == nullptr)
861 FirstResult = ResultPtr;
Hao Liu1d2a0612014-11-19 06:24:44 +0000862 }
863 }
864
865 // Create a GEP with the constant offset index.
866 if (AccumulativeByteOffset != 0) {
867 Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
David Blaikie93c54442015-04-03 19:41:44 +0000868 ResultPtr =
869 Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Offset, "uglygep");
Lawrence Hucac0b892015-09-23 19:25:30 +0000870 } else
871 isSwapCandidate = false;
872
873 // If we created a GEP with constant index, and the base is loop invariant,
874 // then we swap the first one with it, so LICM can move constant GEP out
875 // later.
Lawrence Hu84e6f1d2016-02-19 02:17:07 +0000876 GetElementPtrInst *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
877 GetElementPtrInst *SecondGEP = dyn_cast_or_null<GetElementPtrInst>(ResultPtr);
Lawrence Hucac0b892015-09-23 19:25:30 +0000878 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
879 swapGEPOperand(FirstGEP, SecondGEP);
880
Hao Liu1d2a0612014-11-19 06:24:44 +0000881 if (ResultPtr->getType() != Variadic->getType())
882 ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
883
884 Variadic->replaceAllUsesWith(ResultPtr);
885 Variadic->eraseFromParent();
886}
887
888void
889SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
890 int64_t AccumulativeByteOffset) {
891 IRBuilder<> Builder(Variadic);
Jingyue Wuca321902015-05-14 23:53:19 +0000892 Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
Hao Liu1d2a0612014-11-19 06:24:44 +0000893
894 Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
895 gep_type_iterator GTI = gep_type_begin(*Variadic);
896 // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
897 // don't create arithmetics for structure indices, as they are accumulated
898 // in the constant offset index.
899 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000900 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000901 Value *Idx = Variadic->getOperand(I);
902 // Skip zero indices.
903 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
904 if (CI->isZero())
905 continue;
906
907 APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
Jingyue Wuca321902015-05-14 23:53:19 +0000908 DL->getTypeAllocSize(GTI.getIndexedType()));
Hao Liu1d2a0612014-11-19 06:24:44 +0000909 // Scale the index by element size.
910 if (ElementSize != 1) {
911 if (ElementSize.isPowerOf2()) {
912 Idx = Builder.CreateShl(
913 Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
914 } else {
915 Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
916 }
917 }
918 // Create an ADD for each index.
919 ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
920 }
921 }
922
923 // Create an ADD for the constant offset index.
924 if (AccumulativeByteOffset != 0) {
925 ResultPtr = Builder.CreateAdd(
926 ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
927 }
928
929 ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
930 Variadic->replaceAllUsesWith(ResultPtr);
931 Variadic->eraseFromParent();
932}
933
Eli Benderskya108a652014-05-01 18:38:36 +0000934bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
935 // Skip vector GEPs.
936 if (GEP->getType()->isVectorTy())
937 return false;
938
939 // The backend can already nicely handle the case where all indices are
940 // constant.
941 if (GEP->hasAllConstantIndices())
942 return false;
943
Jingyue Wu0bdc0272014-07-16 23:25:00 +0000944 bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000945
Eli Benderskya108a652014-05-01 18:38:36 +0000946 bool NeedsExtraction;
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000947 int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
Eli Benderskya108a652014-05-01 18:38:36 +0000948
949 if (!NeedsExtraction)
950 return Changed;
David Blaikie8ad9a972018-03-28 22:28:50 +0000951
952 TargetTransformInfo &TTI =
953 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*GEP->getFunction());
954
Hao Liu1d2a0612014-11-19 06:24:44 +0000955 // If LowerGEP is disabled, before really splitting the GEP, check whether the
956 // backend supports the addressing mode we are about to produce. If no, this
957 // splitting probably won't be beneficial.
958 // If LowerGEP is enabled, even the extracted constant offset can not match
959 // the addressing mode, we can still do optimizations to other lowered parts
960 // of variable indices. Therefore, we don't check for addressing modes in that
961 // case.
962 if (!LowerGEP) {
Matt Arsenaulte81944f2015-06-07 20:17:44 +0000963 unsigned AddrSpace = GEP->getPointerAddressSpace();
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000964 if (!TTI.isLegalAddressingMode(GEP->getResultElementType(),
Hao Liu1d2a0612014-11-19 06:24:44 +0000965 /*BaseGV=*/nullptr, AccumulativeByteOffset,
Matt Arsenaulte81944f2015-06-07 20:17:44 +0000966 /*HasBaseReg=*/true, /*Scale=*/0,
967 AddrSpace)) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000968 return Changed;
969 }
Eli Benderskya108a652014-05-01 18:38:36 +0000970 }
971
Hao Liu1d2a0612014-11-19 06:24:44 +0000972 // Remove the constant offset in each sequential index. The resultant GEP
973 // computes the variadic base.
974 // Notice that we don't remove struct field indices here. If LowerGEP is
975 // disabled, a structure index is not accumulated and we still use the old
976 // one. If LowerGEP is enabled, a structure index is accumulated in the
977 // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
978 // handle the constant offset and won't need a new structure index.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000979 gep_type_iterator GTI = gep_type_begin(*GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000980 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000981 if (GTI.isSequential()) {
Hao Liu1d2a0612014-11-19 06:24:44 +0000982 // Splits this GEP index into a variadic part and a constant offset, and
983 // uses the variadic part as the new index.
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000984 Value *OldIdx = GEP->getOperand(I);
985 User *UserChainTail;
986 Value *NewIdx =
Jingyue Wuca321902015-05-14 23:53:19 +0000987 ConstantOffsetExtractor::Extract(OldIdx, GEP, UserChainTail, DT);
Hao Liu1d2a0612014-11-19 06:24:44 +0000988 if (NewIdx != nullptr) {
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000989 // Switches to the index with the constant offset removed.
Eli Benderskya108a652014-05-01 18:38:36 +0000990 GEP->setOperand(I, NewIdx);
Jingyue Wuf763c3f2015-04-21 19:53:18 +0000991 // After switching to the new index, we can garbage-collect UserChain
992 // and the old index if they are not used.
993 RecursivelyDeleteTriviallyDeadInstructions(UserChainTail);
994 RecursivelyDeleteTriviallyDeadInstructions(OldIdx);
Eli Benderskya108a652014-05-01 18:38:36 +0000995 }
996 }
997 }
Hao Liu1d2a0612014-11-19 06:24:44 +0000998
Jingyue Wu84465472014-06-05 22:07:33 +0000999 // Clear the inbounds attribute because the new index may be off-bound.
1000 // e.g.,
1001 //
Jingyue Wu1238f342015-08-14 02:02:05 +00001002 // b = add i64 a, 5
1003 // addr = gep inbounds float, float* p, i64 b
Jingyue Wu84465472014-06-05 22:07:33 +00001004 //
1005 // is transformed to:
1006 //
Jingyue Wu1238f342015-08-14 02:02:05 +00001007 // addr2 = gep float, float* p, i64 a ; inbounds removed
1008 // addr = gep inbounds float, float* addr2, i64 5
Jingyue Wu84465472014-06-05 22:07:33 +00001009 //
1010 // If a is -4, although the old index b is in bounds, the new index a is
1011 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
1012 // inbounds keyword is not present, the offsets are added to the base
1013 // address with silently-wrapping two's complement arithmetic".
1014 // Therefore, the final code will be a semantically equivalent.
1015 //
1016 // TODO(jingyue): do some range analysis to keep as many inbounds as
1017 // possible. GEPs with inbounds are more friendly to alias analysis.
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001018 bool GEPWasInBounds = GEP->isInBounds();
Jingyue Wu84465472014-06-05 22:07:33 +00001019 GEP->setIsInBounds(false);
Eli Benderskya108a652014-05-01 18:38:36 +00001020
Hao Liu1d2a0612014-11-19 06:24:44 +00001021 // Lowers a GEP to either GEPs with a single index or arithmetic operations.
1022 if (LowerGEP) {
1023 // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
1024 // arithmetic operations if the target uses alias analysis in codegen.
David Blaikie8ad9a972018-03-28 22:28:50 +00001025 if (TTI.useAA())
Hao Liu1d2a0612014-11-19 06:24:44 +00001026 lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
1027 else
1028 lowerToArithmetics(GEP, AccumulativeByteOffset);
1029 return true;
1030 }
1031
1032 // No need to create another GEP if the accumulative byte offset is 0.
1033 if (AccumulativeByteOffset == 0)
1034 return true;
1035
Eli Benderskya108a652014-05-01 18:38:36 +00001036 // Offsets the base with the accumulative byte offset.
1037 //
1038 // %gep ; the base
1039 // ... %gep ...
1040 //
1041 // => add the offset
1042 //
1043 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001044 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +00001045 // %gep ; will be removed
1046 // ... %gep ...
1047 //
1048 // => replace all uses of %gep with %new.gep and remove %gep
1049 //
1050 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001051 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +00001052 // ... %new.gep ...
1053 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001054 // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
1055 // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
1056 // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
1057 // type of %gep.
Eli Benderskya108a652014-05-01 18:38:36 +00001058 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001059 // %gep2 ; clone of %gep
1060 // %0 = bitcast %gep2 to i8*
1061 // %uglygep = gep %0, <offset>
1062 // %new.gep = bitcast %uglygep to <type of %gep>
1063 // ... %new.gep ...
Eli Benderskya108a652014-05-01 18:38:36 +00001064 Instruction *NewGEP = GEP->clone();
1065 NewGEP->insertBefore(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +00001066
Jingyue Wufe72fce2014-10-25 18:34:03 +00001067 // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
1068 // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
1069 // used with unsigned integers later.
1070 int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001071 DL->getTypeAllocSize(GEP->getResultElementType()));
Jingyue Wuca321902015-05-14 23:53:19 +00001072 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001073 if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
Hiroshi Inouef2096492018-06-14 05:41:49 +00001074 // Very likely. As long as %gep is naturally aligned, the byte offset we
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001075 // extracted should be a multiple of sizeof(*%gep).
Jingyue Wufe72fce2014-10-25 18:34:03 +00001076 int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
David Blaikie741c8f82015-03-14 01:53:18 +00001077 NewGEP = GetElementPtrInst::Create(GEP->getResultElementType(), NewGEP,
1078 ConstantInt::get(IntPtrTy, Index, true),
1079 GEP->getName(), GEP);
Marek Olsak8e7d1492018-01-31 20:17:52 +00001080 NewGEP->copyMetadata(*GEP);
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001081 // Inherit the inbounds attribute of the original GEP.
1082 cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001083 } else {
1084 // Unlikely but possible. For example,
1085 // #pragma pack(1)
1086 // struct S {
1087 // int a[3];
1088 // int64 b[8];
1089 // };
1090 // #pragma pack()
1091 //
1092 // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
1093 // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
1094 // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
1095 // sizeof(int64).
1096 //
1097 // Emit an uglygep in this case.
1098 Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
1099 GEP->getPointerAddressSpace());
1100 NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
1101 NewGEP = GetElementPtrInst::Create(
David Blaikie741c8f82015-03-14 01:53:18 +00001102 Type::getInt8Ty(GEP->getContext()), NewGEP,
1103 ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "uglygep",
1104 GEP);
Marek Olsak8e7d1492018-01-31 20:17:52 +00001105 NewGEP->copyMetadata(*GEP);
Jingyue Wu13a80ea2015-08-13 18:48:49 +00001106 // Inherit the inbounds attribute of the original GEP.
1107 cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
Jingyue Wubbb6e4a2014-05-23 18:39:40 +00001108 if (GEP->getType() != I8PtrTy)
1109 NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
1110 }
1111
1112 GEP->replaceAllUsesWith(NewGEP);
Eli Benderskya108a652014-05-01 18:38:36 +00001113 GEP->eraseFromParent();
1114
1115 return true;
1116}
1117
1118bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001119 if (skipFunction(F))
Jingyue Wu6c26bb62015-02-01 02:34:41 +00001120 return false;
1121
Eli Benderskya108a652014-05-01 18:38:36 +00001122 if (DisableSeparateConstOffsetFromGEP)
1123 return false;
1124
Jingyue Wuca321902015-05-14 23:53:19 +00001125 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001126 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Lawrence Hucac0b892015-09-23 19:25:30 +00001127 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001128 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Eli Benderskya108a652014-05-01 18:38:36 +00001129 bool Changed = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001130 for (BasicBlock &B : F) {
1131 for (BasicBlock::iterator I = B.begin(), IE = B.end(); I != IE;)
Lawrence Hucac0b892015-09-23 19:25:30 +00001132 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++))
Eli Benderskya108a652014-05-01 18:38:36 +00001133 Changed |= splitGEP(GEP);
Lawrence Hucac0b892015-09-23 19:25:30 +00001134 // No need to split GEP ConstantExprs because all its indices are constant
1135 // already.
Eli Benderskya108a652014-05-01 18:38:36 +00001136 }
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001137
Jingyue Wu1238f342015-08-14 02:02:05 +00001138 Changed |= reuniteExts(F);
1139
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001140 if (VerifyNoDeadCode)
1141 verifyNoDeadCode(F);
1142
Eli Benderskya108a652014-05-01 18:38:36 +00001143 return Changed;
1144}
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001145
Jingyue Wu1238f342015-08-14 02:02:05 +00001146Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
Drew Wock0bcfafc2020-01-15 12:51:42 -05001147 const SCEV *Key, Instruction *Dominatee,
1148 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> &DominatingExprs) {
Jingyue Wu1238f342015-08-14 02:02:05 +00001149 auto Pos = DominatingExprs.find(Key);
1150 if (Pos == DominatingExprs.end())
1151 return nullptr;
1152
1153 auto &Candidates = Pos->second;
1154 // Because we process the basic blocks in pre-order of the dominator tree, a
1155 // candidate that doesn't dominate the current instruction won't dominate any
1156 // future instruction either. Therefore, we pop it out of the stack. This
1157 // optimization makes the algorithm O(n).
1158 while (!Candidates.empty()) {
1159 Instruction *Candidate = Candidates.back();
1160 if (DT->dominates(Candidate, Dominatee))
1161 return Candidate;
1162 Candidates.pop_back();
1163 }
1164 return nullptr;
1165}
1166
1167bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1168 if (!SE->isSCEVable(I->getType()))
1169 return false;
1170
1171 // Dom: LHS+RHS
1172 // I: sext(LHS)+sext(RHS)
1173 // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1174 // TODO: handle zext
1175 Value *LHS = nullptr, *RHS = nullptr;
Drew Wock0bcfafc2020-01-15 12:51:42 -05001176 if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
Jingyue Wu1238f342015-08-14 02:02:05 +00001177 if (LHS->getType() == RHS->getType()) {
1178 const SCEV *Key =
1179 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
Drew Wock0bcfafc2020-01-15 12:51:42 -05001180 if (auto *Dom = findClosestMatchingDominator(Key, I, DominatingAdds)) {
1181 Instruction *NewSExt = new SExtInst(Dom, I->getType(), "", I);
1182 NewSExt->takeName(I);
1183 I->replaceAllUsesWith(NewSExt);
1184 RecursivelyDeleteTriviallyDeadInstructions(I);
1185 return true;
1186 }
1187 }
1188 } else if (match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1189 if (LHS->getType() == RHS->getType()) {
1190 const SCEV *Key =
1191 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1192 if (auto *Dom = findClosestMatchingDominator(Key, I, DominatingSubs)) {
Jingyue Wu1238f342015-08-14 02:02:05 +00001193 Instruction *NewSExt = new SExtInst(Dom, I->getType(), "", I);
1194 NewSExt->takeName(I);
1195 I->replaceAllUsesWith(NewSExt);
1196 RecursivelyDeleteTriviallyDeadInstructions(I);
1197 return true;
1198 }
1199 }
1200 }
1201
1202 // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
Drew Wock0bcfafc2020-01-15 12:51:42 -05001203 if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS)))) {
Sanjoy Das08989c72017-04-30 19:41:19 +00001204 if (programUndefinedIfFullPoison(I)) {
Jingyue Wu1238f342015-08-14 02:02:05 +00001205 const SCEV *Key =
1206 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
Drew Wock0bcfafc2020-01-15 12:51:42 -05001207 DominatingAdds[Key].push_back(I);
1208 }
1209 } else if (match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
1210 if (programUndefinedIfFullPoison(I)) {
1211 const SCEV *Key =
1212 SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1213 DominatingSubs[Key].push_back(I);
Jingyue Wu1238f342015-08-14 02:02:05 +00001214 }
1215 }
1216 return false;
1217}
1218
1219bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1220 bool Changed = false;
Drew Wock0bcfafc2020-01-15 12:51:42 -05001221 DominatingAdds.clear();
1222 DominatingSubs.clear();
Daniel Berlin11da66f2016-08-19 22:18:38 +00001223 for (const auto Node : depth_first(DT)) {
1224 BasicBlock *BB = Node->getBlock();
1225 for (auto I = BB->begin(); I != BB->end(); ) {
1226 Instruction *Cur = &*I++;
1227 Changed |= reuniteExts(Cur);
1228 }
1229 }
Jingyue Wu1238f342015-08-14 02:02:05 +00001230 return Changed;
1231}
1232
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001233void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001234 for (BasicBlock &B : F) {
1235 for (Instruction &I : B) {
Jingyue Wuf763c3f2015-04-21 19:53:18 +00001236 if (isInstructionTriviallyDead(&I)) {
1237 std::string ErrMessage;
1238 raw_string_ostream RSO(ErrMessage);
1239 RSO << "Dead instruction detected!\n" << I << "\n";
1240 llvm_unreachable(RSO.str().c_str());
1241 }
1242 }
1243 }
1244}
Lawrence Hucac0b892015-09-23 19:25:30 +00001245
1246bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1247 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP, Loop *CurLoop) {
1248 if (!FirstGEP || !FirstGEP->hasOneUse())
1249 return false;
1250
1251 if (!SecondGEP || FirstGEP->getParent() != SecondGEP->getParent())
1252 return false;
1253
1254 if (FirstGEP == SecondGEP)
1255 return false;
1256
1257 unsigned FirstNum = FirstGEP->getNumOperands();
1258 unsigned SecondNum = SecondGEP->getNumOperands();
1259 // Give up if the number of operands are not 2.
1260 if (FirstNum != SecondNum || FirstNum != 2)
1261 return false;
1262
1263 Value *FirstBase = FirstGEP->getOperand(0);
1264 Value *SecondBase = SecondGEP->getOperand(0);
1265 Value *FirstOffset = FirstGEP->getOperand(1);
1266 // Give up if the index of the first GEP is loop invariant.
1267 if (CurLoop->isLoopInvariant(FirstOffset))
1268 return false;
1269
1270 // Give up if base doesn't have same type.
1271 if (FirstBase->getType() != SecondBase->getType())
1272 return false;
1273
1274 Instruction *FirstOffsetDef = dyn_cast<Instruction>(FirstOffset);
1275
1276 // Check if the second operand of first GEP has constant coefficient.
1277 // For an example, for the following code, we won't gain anything by
1278 // hoisting the second GEP out because the second GEP can be folded away.
1279 // %scevgep.sum.ur159 = add i64 %idxprom48.ur, 256
1280 // %67 = shl i64 %scevgep.sum.ur159, 2
1281 // %uglygep160 = getelementptr i8* %65, i64 %67
1282 // %uglygep161 = getelementptr i8* %uglygep160, i64 -1024
1283
1284 // Skip constant shift instruction which may be generated by Splitting GEPs.
1285 if (FirstOffsetDef && FirstOffsetDef->isShift() &&
Craig Topper66059c92015-11-18 07:07:59 +00001286 isa<ConstantInt>(FirstOffsetDef->getOperand(1)))
Lawrence Hucac0b892015-09-23 19:25:30 +00001287 FirstOffsetDef = dyn_cast<Instruction>(FirstOffsetDef->getOperand(0));
1288
1289 // Give up if FirstOffsetDef is an Add or Sub with constant.
1290 // Because it may not profitable at all due to constant folding.
1291 if (FirstOffsetDef)
1292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FirstOffsetDef)) {
1293 unsigned opc = BO->getOpcode();
1294 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
Craig Topper66059c92015-11-18 07:07:59 +00001295 (isa<ConstantInt>(BO->getOperand(0)) ||
1296 isa<ConstantInt>(BO->getOperand(1))))
Lawrence Hucac0b892015-09-23 19:25:30 +00001297 return false;
1298 }
1299 return true;
1300}
1301
1302bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(Value *V, Loop *L) {
1303 int UsesInLoop = 0;
1304 for (User *U : V->users()) {
1305 if (Instruction *User = dyn_cast<Instruction>(U))
1306 if (L->contains(User))
1307 if (++UsesInLoop > 1)
1308 return true;
1309 }
1310 return false;
1311}
1312
1313void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *First,
1314 GetElementPtrInst *Second) {
1315 Value *Offset1 = First->getOperand(1);
1316 Value *Offset2 = Second->getOperand(1);
1317 First->setOperand(1, Offset2);
1318 Second->setOperand(1, Offset1);
1319
1320 // We changed p+o+c to p+c+o, p+c may not be inbound anymore.
1321 const DataLayout &DAL = First->getModule()->getDataLayout();
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001322 APInt Offset(DAL.getIndexSizeInBits(
Lawrence Hucac0b892015-09-23 19:25:30 +00001323 cast<PointerType>(First->getType())->getAddressSpace()),
1324 0);
1325 Value *NewBase =
1326 First->stripAndAccumulateInBoundsConstantOffsets(DAL, Offset);
1327 uint64_t ObjectSize;
1328 if (!getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1329 Offset.ugt(ObjectSize)) {
1330 First->setIsInBounds(false);
1331 Second->setIsInBounds(false);
1332 } else
1333 First->setIsInBounds(true);
1334}