blob: 6557ce4575dda2995ea8b7d885bc543160e16e47 [file] [log] [blame]
Eli Benderskya108a652014-05-01 18:38:36 +00001//===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Loop unrolling may create many similar GEPs for array accesses.
11// e.g., a 2-level loop
12//
13// float a[32][32]; // global variable
14//
15// for (int i = 0; i < 2; ++i) {
16// for (int j = 0; j < 2; ++j) {
17// ...
18// ... = a[x + i][y + j];
19// ...
20// }
21// }
22//
23// will probably be unrolled to:
24//
25// gep %a, 0, %x, %y; load
26// gep %a, 0, %x, %y + 1; load
27// gep %a, 0, %x + 1, %y; load
28// gep %a, 0, %x + 1, %y + 1; load
29//
30// LLVM's GVN does not use partial redundancy elimination yet, and is thus
31// unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
32// significant slowdown in targets with limited addressing modes. For instance,
33// because the PTX target does not support the reg+reg addressing mode, the
34// NVPTX backend emits PTX code that literally computes the pointer address of
35// each GEP, wasting tons of registers. It emits the following PTX for the
36// first load and similar PTX for other loads.
37//
38// mov.u32 %r1, %x;
39// mov.u32 %r2, %y;
40// mul.wide.u32 %rl2, %r1, 128;
41// mov.u64 %rl3, a;
42// add.s64 %rl4, %rl3, %rl2;
43// mul.wide.u32 %rl5, %r2, 4;
44// add.s64 %rl6, %rl4, %rl5;
45// ld.global.f32 %f1, [%rl6];
46//
47// To reduce the register pressure, the optimization implemented in this file
48// merges the common part of a group of GEPs, so we can compute each pointer
49// address by adding a simple offset to the common part, saving many registers.
50//
51// It works by splitting each GEP into a variadic base and a constant offset.
52// The variadic base can be computed once and reused by multiple GEPs, and the
53// constant offsets can be nicely folded into the reg+immediate addressing mode
54// (supported by most targets) without using any extra register.
55//
56// For instance, we transform the four GEPs and four loads in the above example
57// into:
58//
59// base = gep a, 0, x, y
60// load base
61// laod base + 1 * sizeof(float)
62// load base + 32 * sizeof(float)
63// load base + 33 * sizeof(float)
64//
65// Given the transformed IR, a backend that supports the reg+immediate
66// addressing mode can easily fold the pointer arithmetics into the loads. For
67// example, the NVPTX backend can easily fold the pointer arithmetics into the
68// ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
69//
70// mov.u32 %r1, %tid.x;
71// mov.u32 %r2, %tid.y;
72// mul.wide.u32 %rl2, %r1, 128;
73// mov.u64 %rl3, a;
74// add.s64 %rl4, %rl3, %rl2;
75// mul.wide.u32 %rl5, %r2, 4;
76// add.s64 %rl6, %rl4, %rl5;
77// ld.global.f32 %f1, [%rl6]; // so far the same as unoptimized PTX
78// ld.global.f32 %f2, [%rl6+4]; // much better
79// ld.global.f32 %f3, [%rl6+128]; // much better
80// ld.global.f32 %f4, [%rl6+132]; // much better
81//
82//===----------------------------------------------------------------------===//
83
84#include "llvm/Analysis/TargetTransformInfo.h"
85#include "llvm/Analysis/ValueTracking.h"
86#include "llvm/IR/Constants.h"
87#include "llvm/IR/DataLayout.h"
88#include "llvm/IR/Instructions.h"
89#include "llvm/IR/LLVMContext.h"
90#include "llvm/IR/Module.h"
91#include "llvm/IR/Operator.h"
92#include "llvm/Support/CommandLine.h"
93#include "llvm/Support/raw_ostream.h"
94#include "llvm/Transforms/Scalar.h"
95
96using namespace llvm;
97
98static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
99 "disable-separate-const-offset-from-gep", cl::init(false),
100 cl::desc("Do not separate the constant offset from a GEP instruction"),
101 cl::Hidden);
102
103namespace {
104
105/// \brief A helper class for separating a constant offset from a GEP index.
106///
107/// In real programs, a GEP index may be more complicated than a simple addition
108/// of something and a constant integer which can be trivially splitted. For
109/// example, to split ((a << 3) | 5) + b, we need to search deeper for the
Alp Tokerbeaca192014-05-15 01:52:21 +0000110/// constant offset, so that we can separate the index to (a << 3) + b and 5.
Eli Benderskya108a652014-05-01 18:38:36 +0000111///
112/// Therefore, this class looks into the expression that computes a given GEP
113/// index, and tries to find a constant integer that can be hoisted to the
114/// outermost level of the expression as an addition. Not every constant in an
115/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
116/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
117/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
118class ConstantOffsetExtractor {
119 public:
120 /// Extracts a constant offset from the given GEP index. It outputs the
121 /// numeric value of the extracted constant offset (0 if failed), and a
122 /// new index representing the remainder (equal to the original index minus
123 /// the constant offset).
Jingyue Wu84465472014-06-05 22:07:33 +0000124 /// \p Idx The given GEP index
125 /// \p NewIdx The new index to replace (output)
126 /// \p DL The datalayout of the module
127 /// \p GEP The given GEP
Eli Benderskya108a652014-05-01 18:38:36 +0000128 static int64_t Extract(Value *Idx, Value *&NewIdx, const DataLayout *DL,
Jingyue Wu84465472014-06-05 22:07:33 +0000129 GetElementPtrInst *GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000130 /// Looks for a constant offset without extracting it. The meaning of the
131 /// arguments and the return value are the same as Extract.
Jingyue Wu84465472014-06-05 22:07:33 +0000132 static int64_t Find(Value *Idx, const DataLayout *DL, GetElementPtrInst *GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000133
134 private:
135 ConstantOffsetExtractor(const DataLayout *Layout, Instruction *InsertionPt)
136 : DL(Layout), IP(InsertionPt) {}
Jingyue Wu84465472014-06-05 22:07:33 +0000137 /// Searches the expression that computes V for a non-zero constant C s.t.
138 /// V can be reassociated into the form V' + C. If the searching is
139 /// successful, returns C and update UserChain as a def-use chain from C to V;
140 /// otherwise, UserChain is empty.
Eli Benderskya108a652014-05-01 18:38:36 +0000141 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000142 /// \p V The given expression
143 /// \p SignExtended Whether V will be sign-extended in the computation of the
144 /// GEP index
145 /// \p ZeroExtended Whether V will be zero-extended in the computation of the
146 /// GEP index
147 /// \p NonNegative Whether V is guaranteed to be non-negative. For example,
148 /// an index of an inbounds GEP is guaranteed to be
149 /// non-negative. Levaraging this, we can better split
150 /// inbounds GEPs.
151 APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
152 /// A helper function to look into both operands of a binary operator.
153 APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
154 bool ZeroExtended);
155 /// After finding the constant offset C from the GEP index I, we build a new
156 /// index I' s.t. I' + C = I. This function builds and returns the new
157 /// index I' according to UserChain produced by function "find".
158 ///
159 /// The building conceptually takes two steps:
160 /// 1) iteratively distribute s/zext towards the leaves of the expression tree
161 /// that computes I
162 /// 2) reassociate the expression tree to the form I' + C.
163 ///
164 /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
165 /// sext to a, b and 5 so that we have
166 /// sext(a) + (sext(b) + 5).
167 /// Then, we reassociate it to
168 /// (sext(a) + sext(b)) + 5.
169 /// Given this form, we know I' is sext(a) + sext(b).
170 Value *rebuildWithoutConstOffset();
171 /// After the first step of rebuilding the GEP index without the constant
172 /// offset, distribute s/zext to the operands of all operators in UserChain.
173 /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
174 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
175 ///
176 /// The function also updates UserChain to point to new subexpressions after
177 /// distributing s/zext. e.g., the old UserChain of the above example is
178 /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
179 /// and the new UserChain is
180 /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
181 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
182 ///
183 /// \p ChainIndex The index to UserChain. ChainIndex is initially
184 /// UserChain.size() - 1, and is decremented during
185 /// the recursion.
186 Value *distributeExtsAndCloneChain(unsigned ChainIndex);
187 /// Reassociates the GEP index to the form I' + C and returns I'.
188 Value *removeConstOffset(unsigned ChainIndex);
189 /// A helper function to apply ExtInsts, a list of s/zext, to value V.
190 /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
191 /// returns "sext i32 (zext i16 V to i32) to i64".
192 Value *applyExts(Value *V);
Eli Benderskya108a652014-05-01 18:38:36 +0000193
194 /// Returns true if LHS and RHS have no bits in common, i.e., LHS | RHS == 0.
195 bool NoCommonBits(Value *LHS, Value *RHS) const;
196 /// Computes which bits are known to be one or zero.
197 /// \p KnownOne Mask of all bits that are known to be one.
198 /// \p KnownZero Mask of all bits that are known to be zero.
199 void ComputeKnownBits(Value *V, APInt &KnownOne, APInt &KnownZero) const;
Jingyue Wu84465472014-06-05 22:07:33 +0000200 /// A helper function that returns whether we can trace into the operands
201 /// of binary operator BO for a constant offset.
202 ///
203 /// \p SignExtended Whether BO is surrounded by sext
204 /// \p ZeroExtended Whether BO is surrounded by zext
205 /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
206 /// array index.
207 bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
208 bool NonNegative);
Eli Benderskya108a652014-05-01 18:38:36 +0000209
210 /// The path from the constant offset to the old GEP index. e.g., if the GEP
211 /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
212 /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
213 /// UserChain[2] will be the entire expression "a * b + (c + 5)".
214 ///
Jingyue Wu84465472014-06-05 22:07:33 +0000215 /// This path helps to rebuild the new GEP index.
Eli Benderskya108a652014-05-01 18:38:36 +0000216 SmallVector<User *, 8> UserChain;
Jingyue Wu84465472014-06-05 22:07:33 +0000217 /// A data structure used in rebuildWithoutConstOffset. Contains all
218 /// sext/zext instructions along UserChain.
219 SmallVector<CastInst *, 16> ExtInsts;
Eli Benderskya108a652014-05-01 18:38:36 +0000220 /// The data layout of the module. Used in ComputeKnownBits.
221 const DataLayout *DL;
222 Instruction *IP; /// Insertion position of cloned instructions.
223};
224
225/// \brief A pass that tries to split every GEP in the function into a variadic
Alp Tokerbeaca192014-05-15 01:52:21 +0000226/// base and a constant offset. It is a FunctionPass because searching for the
Eli Benderskya108a652014-05-01 18:38:36 +0000227/// constant offset may inspect other basic blocks.
228class SeparateConstOffsetFromGEP : public FunctionPass {
229 public:
230 static char ID;
231 SeparateConstOffsetFromGEP() : FunctionPass(ID) {
232 initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
233 }
234
235 void getAnalysisUsage(AnalysisUsage &AU) const override {
236 AU.addRequired<DataLayoutPass>();
237 AU.addRequired<TargetTransformInfo>();
238 }
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000239
240 bool doInitialization(Module &M) override {
241 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
242 if (DLP == nullptr)
243 report_fatal_error("data layout missing");
244 DL = &DLP->getDataLayout();
245 return false;
246 }
247
Eli Benderskya108a652014-05-01 18:38:36 +0000248 bool runOnFunction(Function &F) override;
249
250 private:
251 /// Tries to split the given GEP into a variadic base and a constant offset,
252 /// and returns true if the splitting succeeds.
253 bool splitGEP(GetElementPtrInst *GEP);
254 /// Finds the constant offset within each index, and accumulates them. This
255 /// function only inspects the GEP without changing it. The output
256 /// NeedsExtraction indicates whether we can extract a non-zero constant
257 /// offset from any index.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000258 int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
259 /// Canonicalize array indices to pointer-size integers. This helps to
260 /// simplify the logic of splitting a GEP. For example, if a + b is a
261 /// pointer-size integer, we have
262 /// gep base, a + b = gep (gep base, a), b
263 /// However, this equality may not hold if the size of a + b is smaller than
264 /// the pointer size, because LLVM conceptually sign-extends GEP indices to
265 /// pointer size before computing the address
266 /// (http://llvm.org/docs/LangRef.html#id181).
267 ///
268 /// This canonicalization is very likely already done in clang and
269 /// instcombine. Therefore, the program will probably remain the same.
270 ///
Jingyue Wu5c7b1ae2014-06-08 23:49:34 +0000271 /// Returns true if the module changes.
272 ///
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000273 /// Verified in @i32_add in split-gep.ll
274 bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
275
276 const DataLayout *DL;
Eli Benderskya108a652014-05-01 18:38:36 +0000277};
278} // anonymous namespace
279
280char SeparateConstOffsetFromGEP::ID = 0;
281INITIALIZE_PASS_BEGIN(
282 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
283 "Split GEPs to a variadic base and a constant offset for better CSE", false,
284 false)
285INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
286INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)
287INITIALIZE_PASS_END(
288 SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
289 "Split GEPs to a variadic base and a constant offset for better CSE", false,
290 false)
291
292FunctionPass *llvm::createSeparateConstOffsetFromGEPPass() {
293 return new SeparateConstOffsetFromGEP();
294}
295
Jingyue Wu84465472014-06-05 22:07:33 +0000296bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
297 bool ZeroExtended,
298 BinaryOperator *BO,
299 bool NonNegative) {
300 // We only consider ADD, SUB and OR, because a non-zero constant found in
301 // expressions composed of these operations can be easily hoisted as a
302 // constant offset by reassociation.
303 if (BO->getOpcode() != Instruction::Add &&
304 BO->getOpcode() != Instruction::Sub &&
305 BO->getOpcode() != Instruction::Or) {
306 return false;
307 }
308
309 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
310 // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
311 // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
312 if (BO->getOpcode() == Instruction::Or && !NoCommonBits(LHS, RHS))
313 return false;
314
315 // In addition, tracing into BO requires that its surrounding s/zext (if
316 // any) is distributable to both operands.
317 //
318 // Suppose BO = A op B.
319 // SignExtended | ZeroExtended | Distributable?
320 // --------------+--------------+----------------------------------
321 // 0 | 0 | true because no s/zext exists
322 // 0 | 1 | zext(BO) == zext(A) op zext(B)
323 // 1 | 0 | sext(BO) == sext(A) op sext(B)
324 // 1 | 1 | zext(sext(BO)) ==
325 // | | zext(sext(A)) op zext(sext(B))
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000326 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
Jingyue Wu84465472014-06-05 22:07:33 +0000327 // If a + b >= 0 and (a >= 0 or b >= 0), then
Jingyue Wu01ceeb12014-06-08 20:19:38 +0000328 // sext(a + b) = sext(a) + sext(b)
Jingyue Wu84465472014-06-05 22:07:33 +0000329 // even if the addition is not marked nsw.
330 //
331 // Leveraging this invarient, we can trace into an sext'ed inbound GEP
332 // index if the constant offset is non-negative.
333 //
334 // Verified in @sext_add in split-gep.ll.
335 if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
336 if (!ConstLHS->isNegative())
337 return true;
338 }
339 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
340 if (!ConstRHS->isNegative())
341 return true;
342 }
343 }
Jingyue Wu80a738d2014-05-27 18:00:00 +0000344
345 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
346 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
347 if (BO->getOpcode() == Instruction::Add ||
348 BO->getOpcode() == Instruction::Sub) {
Jingyue Wu84465472014-06-05 22:07:33 +0000349 if (SignExtended && !BO->hasNoSignedWrap())
350 return false;
351 if (ZeroExtended && !BO->hasNoUnsignedWrap())
352 return false;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000353 }
354
Jingyue Wu84465472014-06-05 22:07:33 +0000355 return true;
Jingyue Wu80a738d2014-05-27 18:00:00 +0000356}
357
Jingyue Wu84465472014-06-05 22:07:33 +0000358APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
359 bool SignExtended,
360 bool ZeroExtended) {
361 // BO being non-negative does not shed light on whether its operands are
362 // non-negative. Clear the NonNegative flag here.
363 APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
364 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000365 // If we found a constant offset in the left operand, stop and return that.
366 // This shortcut might cause us to miss opportunities of combining the
367 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
368 // However, such cases are probably already handled by -instcombine,
369 // given this pass runs after the standard optimizations.
370 if (ConstantOffset != 0) return ConstantOffset;
Jingyue Wu84465472014-06-05 22:07:33 +0000371 ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
372 /* NonNegative */ false);
Eli Benderskya108a652014-05-01 18:38:36 +0000373 // If U is a sub operator, negate the constant offset found in the right
374 // operand.
Jingyue Wu84465472014-06-05 22:07:33 +0000375 if (BO->getOpcode() == Instruction::Sub)
376 ConstantOffset = -ConstantOffset;
377 return ConstantOffset;
Eli Benderskya108a652014-05-01 18:38:36 +0000378}
379
Jingyue Wu84465472014-06-05 22:07:33 +0000380APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
381 bool ZeroExtended, bool NonNegative) {
382 // TODO(jingyue): We could trace into integer/pointer casts, such as
Eli Benderskya108a652014-05-01 18:38:36 +0000383 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
384 // integers because it gives good enough results for our benchmarks.
Jingyue Wu84465472014-06-05 22:07:33 +0000385 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Eli Benderskya108a652014-05-01 18:38:36 +0000386
Jingyue Wu84465472014-06-05 22:07:33 +0000387 // We cannot do much with Values that are not a User, such as an Argument.
Eli Benderskya108a652014-05-01 18:38:36 +0000388 User *U = dyn_cast<User>(V);
Jingyue Wu84465472014-06-05 22:07:33 +0000389 if (U == nullptr) return APInt(BitWidth, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000390
Jingyue Wu84465472014-06-05 22:07:33 +0000391 APInt ConstantOffset(BitWidth, 0);
392 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Eli Benderskya108a652014-05-01 18:38:36 +0000393 // Hooray, we found it!
Jingyue Wu84465472014-06-05 22:07:33 +0000394 ConstantOffset = CI->getValue();
395 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
396 // Trace into subexpressions for more hoisting opportunities.
397 if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative)) {
398 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
Eli Benderskya108a652014-05-01 18:38:36 +0000399 }
Jingyue Wu84465472014-06-05 22:07:33 +0000400 } else if (isa<SExtInst>(V)) {
401 ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
402 ZeroExtended, NonNegative).sext(BitWidth);
403 } else if (isa<ZExtInst>(V)) {
404 // As an optimization, we can clear the SignExtended flag because
405 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
406 //
407 // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
Jingyue Wu84465472014-06-05 22:07:33 +0000408 ConstantOffset =
409 find(U->getOperand(0), /* SignExtended */ false,
410 /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
Eli Benderskya108a652014-05-01 18:38:36 +0000411 }
Jingyue Wu84465472014-06-05 22:07:33 +0000412
413 // If we found a non-zero constant offset, add it to the path for
414 // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
415 // help this optimization.
Eli Benderskya108a652014-05-01 18:38:36 +0000416 if (ConstantOffset != 0)
417 UserChain.push_back(U);
418 return ConstantOffset;
419}
420
Jingyue Wu84465472014-06-05 22:07:33 +0000421Value *ConstantOffsetExtractor::applyExts(Value *V) {
422 Value *Current = V;
423 // ExtInsts is built in the use-def order. Therefore, we apply them to V
424 // in the reversed order.
425 for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
426 if (Constant *C = dyn_cast<Constant>(Current)) {
427 // If Current is a constant, apply s/zext using ConstantExpr::getCast.
428 // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
429 Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
430 } else {
431 Instruction *Ext = (*I)->clone();
432 Ext->setOperand(0, Current);
433 Ext->insertBefore(IP);
434 Current = Ext;
435 }
Eli Benderskya108a652014-05-01 18:38:36 +0000436 }
Jingyue Wu84465472014-06-05 22:07:33 +0000437 return Current;
Eli Benderskya108a652014-05-01 18:38:36 +0000438}
439
Jingyue Wu84465472014-06-05 22:07:33 +0000440Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
441 distributeExtsAndCloneChain(UserChain.size() - 1);
442 // Remove all nullptrs (used to be s/zext) from UserChain.
443 unsigned NewSize = 0;
444 for (auto I = UserChain.begin(), E = UserChain.end(); I != E; ++I) {
445 if (*I != nullptr) {
446 UserChain[NewSize] = *I;
447 NewSize++;
448 }
Eli Benderskya108a652014-05-01 18:38:36 +0000449 }
Jingyue Wu84465472014-06-05 22:07:33 +0000450 UserChain.resize(NewSize);
451 return removeConstOffset(UserChain.size() - 1);
Eli Benderskya108a652014-05-01 18:38:36 +0000452}
453
Jingyue Wu84465472014-06-05 22:07:33 +0000454Value *
455ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
456 User *U = UserChain[ChainIndex];
457 if (ChainIndex == 0) {
458 assert(isa<ConstantInt>(U));
459 // If U is a ConstantInt, applyExts will return a ConstantInt as well.
460 return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
461 }
Eli Benderskya108a652014-05-01 18:38:36 +0000462
Jingyue Wu84465472014-06-05 22:07:33 +0000463 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
464 assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
465 "We only traced into two types of CastInst: sext and zext");
466 ExtInsts.push_back(Cast);
467 UserChain[ChainIndex] = nullptr;
468 return distributeExtsAndCloneChain(ChainIndex - 1);
469 }
470
471 // Function find only trace into BinaryOperator and CastInst.
472 BinaryOperator *BO = cast<BinaryOperator>(U);
473 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
474 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
475 Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
476 Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
477
478 BinaryOperator *NewBO = nullptr;
479 if (OpNo == 0) {
480 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
481 BO->getName(), IP);
482 } else {
483 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
484 BO->getName(), IP);
485 }
486 return UserChain[ChainIndex] = NewBO;
Eli Benderskya108a652014-05-01 18:38:36 +0000487}
488
Jingyue Wu84465472014-06-05 22:07:33 +0000489Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
490 if (ChainIndex == 0) {
491 assert(isa<ConstantInt>(UserChain[ChainIndex]));
492 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
493 }
Eli Benderskya108a652014-05-01 18:38:36 +0000494
Jingyue Wu84465472014-06-05 22:07:33 +0000495 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
496 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
497 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
498 Value *NextInChain = removeConstOffset(ChainIndex - 1);
499 Value *TheOther = BO->getOperand(1 - OpNo);
500
501 // If NextInChain is 0 and not the LHS of a sub, we can simplify the
502 // sub-expression to be just TheOther.
503 if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
504 if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
505 return TheOther;
506 }
507
508 if (BO->getOpcode() == Instruction::Or) {
509 // Rebuild "or" as "add", because "or" may be invalid for the new
510 // epxression.
511 //
512 // For instance, given
513 // a | (b + 5) where a and b + 5 have no common bits,
514 // we can extract 5 as the constant offset.
515 //
516 // However, reusing the "or" in the new index would give us
517 // (a | b) + 5
518 // which does not equal a | (b + 5).
519 //
520 // Replacing the "or" with "add" is fine, because
521 // a | (b + 5) = a + (b + 5) = (a + b) + 5
522 return BinaryOperator::CreateAdd(BO->getOperand(0), BO->getOperand(1),
523 BO->getName(), IP);
524 }
525
526 // We can reuse BO in this case, because the new expression shares the same
527 // instruction type and BO is used at most once.
528 assert(BO->getNumUses() <= 1 &&
529 "distributeExtsAndCloneChain clones each BinaryOperator in "
530 "UserChain, so no one should be used more than "
531 "once");
532 BO->setOperand(OpNo, NextInChain);
533 BO->setHasNoSignedWrap(false);
534 BO->setHasNoUnsignedWrap(false);
535 // Make sure it appears after all instructions we've inserted so far.
536 BO->moveBefore(IP);
537 return BO;
Eli Benderskya108a652014-05-01 18:38:36 +0000538}
539
540int64_t ConstantOffsetExtractor::Extract(Value *Idx, Value *&NewIdx,
541 const DataLayout *DL,
Jingyue Wu84465472014-06-05 22:07:33 +0000542 GetElementPtrInst *GEP) {
543 ConstantOffsetExtractor Extractor(DL, GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000544 // Find a non-zero constant offset first.
Jingyue Wu84465472014-06-05 22:07:33 +0000545 APInt ConstantOffset =
546 Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
547 GEP->isInBounds());
548 if (ConstantOffset != 0) {
549 // Separates the constant offset from the GEP index.
550 NewIdx = Extractor.rebuildWithoutConstOffset();
551 }
552 return ConstantOffset.getSExtValue();
Eli Benderskya108a652014-05-01 18:38:36 +0000553}
554
Jingyue Wu84465472014-06-05 22:07:33 +0000555int64_t ConstantOffsetExtractor::Find(Value *Idx, const DataLayout *DL,
556 GetElementPtrInst *GEP) {
557 // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
558 return ConstantOffsetExtractor(DL, GEP)
559 .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
560 GEP->isInBounds())
561 .getSExtValue();
Eli Benderskya108a652014-05-01 18:38:36 +0000562}
563
564void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne,
565 APInt &KnownZero) const {
566 IntegerType *IT = cast<IntegerType>(V->getType());
567 KnownOne = APInt(IT->getBitWidth(), 0);
568 KnownZero = APInt(IT->getBitWidth(), 0);
Jay Foada0653a32014-05-14 21:14:37 +0000569 llvm::computeKnownBits(V, KnownZero, KnownOne, DL, 0);
Eli Benderskya108a652014-05-01 18:38:36 +0000570}
571
572bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const {
573 assert(LHS->getType() == RHS->getType() &&
574 "LHS and RHS should have the same type");
575 APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero;
576 ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero);
577 ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero);
578 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
579}
580
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000581bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
582 GetElementPtrInst *GEP) {
583 bool Changed = false;
584 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
585 gep_type_iterator GTI = gep_type_begin(*GEP);
586 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
587 I != E; ++I, ++GTI) {
588 // Skip struct member indices which must be i32.
589 if (isa<SequentialType>(*GTI)) {
590 if ((*I)->getType() != IntPtrTy) {
591 *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
592 Changed = true;
593 }
594 }
595 }
596 return Changed;
597}
598
599int64_t
600SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
601 bool &NeedsExtraction) {
Eli Benderskya108a652014-05-01 18:38:36 +0000602 NeedsExtraction = false;
603 int64_t AccumulativeByteOffset = 0;
604 gep_type_iterator GTI = gep_type_begin(*GEP);
605 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
606 if (isa<SequentialType>(*GTI)) {
607 // Tries to extract a constant offset from this GEP index.
608 int64_t ConstantOffset =
Jingyue Wu84465472014-06-05 22:07:33 +0000609 ConstantOffsetExtractor::Find(GEP->getOperand(I), DL, GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000610 if (ConstantOffset != 0) {
611 NeedsExtraction = true;
612 // A GEP may have multiple indices. We accumulate the extracted
613 // constant offset to a byte offset, and later offset the remainder of
614 // the original GEP with this byte offset.
615 AccumulativeByteOffset +=
616 ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
617 }
618 }
619 }
620 return AccumulativeByteOffset;
621}
622
623bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
624 // Skip vector GEPs.
625 if (GEP->getType()->isVectorTy())
626 return false;
627
628 // The backend can already nicely handle the case where all indices are
629 // constant.
630 if (GEP->hasAllConstantIndices())
631 return false;
632
Jingyue Wu0bdc0272014-07-16 23:25:00 +0000633 bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000634
Eli Benderskya108a652014-05-01 18:38:36 +0000635 bool NeedsExtraction;
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000636 int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
Eli Benderskya108a652014-05-01 18:38:36 +0000637
638 if (!NeedsExtraction)
639 return Changed;
640 // Before really splitting the GEP, check whether the backend supports the
641 // addressing mode we are about to produce. If no, this splitting probably
642 // won't be beneficial.
643 TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
644 if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),
645 /*BaseGV=*/nullptr, AccumulativeByteOffset,
646 /*HasBaseReg=*/true, /*Scale=*/0)) {
647 return Changed;
648 }
649
650 // Remove the constant offset in each GEP index. The resultant GEP computes
651 // the variadic base.
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000652 gep_type_iterator GTI = gep_type_begin(*GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000653 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
654 if (isa<SequentialType>(*GTI)) {
655 Value *NewIdx = nullptr;
656 // Tries to extract a constant offset from this GEP index.
657 int64_t ConstantOffset =
658 ConstantOffsetExtractor::Extract(GEP->getOperand(I), NewIdx, DL, GEP);
659 if (ConstantOffset != 0) {
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000660 assert(NewIdx != nullptr &&
661 "ConstantOffset != 0 implies NewIdx is set");
Eli Benderskya108a652014-05-01 18:38:36 +0000662 GEP->setOperand(I, NewIdx);
Eli Benderskya108a652014-05-01 18:38:36 +0000663 }
664 }
665 }
Jingyue Wu84465472014-06-05 22:07:33 +0000666 // Clear the inbounds attribute because the new index may be off-bound.
667 // e.g.,
668 //
669 // b = add i64 a, 5
670 // addr = gep inbounds float* p, i64 b
671 //
672 // is transformed to:
673 //
674 // addr2 = gep float* p, i64 a
675 // addr = gep float* addr2, i64 5
676 //
677 // If a is -4, although the old index b is in bounds, the new index a is
678 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
679 // inbounds keyword is not present, the offsets are added to the base
680 // address with silently-wrapping two's complement arithmetic".
681 // Therefore, the final code will be a semantically equivalent.
682 //
683 // TODO(jingyue): do some range analysis to keep as many inbounds as
684 // possible. GEPs with inbounds are more friendly to alias analysis.
685 GEP->setIsInBounds(false);
Eli Benderskya108a652014-05-01 18:38:36 +0000686
687 // Offsets the base with the accumulative byte offset.
688 //
689 // %gep ; the base
690 // ... %gep ...
691 //
692 // => add the offset
693 //
694 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000695 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +0000696 // %gep ; will be removed
697 // ... %gep ...
698 //
699 // => replace all uses of %gep with %new.gep and remove %gep
700 //
701 // %gep2 ; clone of %gep
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000702 // %new.gep = gep %gep2, <offset / sizeof(*%gep)>
Eli Benderskya108a652014-05-01 18:38:36 +0000703 // ... %new.gep ...
704 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000705 // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
706 // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
707 // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
708 // type of %gep.
Eli Benderskya108a652014-05-01 18:38:36 +0000709 //
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000710 // %gep2 ; clone of %gep
711 // %0 = bitcast %gep2 to i8*
712 // %uglygep = gep %0, <offset>
713 // %new.gep = bitcast %uglygep to <type of %gep>
714 // ... %new.gep ...
Eli Benderskya108a652014-05-01 18:38:36 +0000715 Instruction *NewGEP = GEP->clone();
716 NewGEP->insertBefore(GEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000717
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000718 uint64_t ElementTypeSizeOfGEP =
719 DL->getTypeAllocSize(GEP->getType()->getElementType());
Jingyue Wu48a5abe2014-06-08 20:15:45 +0000720 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wubbb6e4a2014-05-23 18:39:40 +0000721 if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
722 // Very likely. As long as %gep is natually aligned, the byte offset we
723 // extracted should be a multiple of sizeof(*%gep).
724 // Per ANSI C standard, signed / unsigned = unsigned. Therefore, we
725 // cast ElementTypeSizeOfGEP to signed.
726 int64_t Index =
727 AccumulativeByteOffset / static_cast<int64_t>(ElementTypeSizeOfGEP);
728 NewGEP = GetElementPtrInst::Create(
729 NewGEP, ConstantInt::get(IntPtrTy, Index, true), GEP->getName(), GEP);
730 } else {
731 // Unlikely but possible. For example,
732 // #pragma pack(1)
733 // struct S {
734 // int a[3];
735 // int64 b[8];
736 // };
737 // #pragma pack()
738 //
739 // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
740 // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
741 // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
742 // sizeof(int64).
743 //
744 // Emit an uglygep in this case.
745 Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
746 GEP->getPointerAddressSpace());
747 NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
748 NewGEP = GetElementPtrInst::Create(
749 NewGEP, ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true),
750 "uglygep", GEP);
751 if (GEP->getType() != I8PtrTy)
752 NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
753 }
754
755 GEP->replaceAllUsesWith(NewGEP);
Eli Benderskya108a652014-05-01 18:38:36 +0000756 GEP->eraseFromParent();
757
758 return true;
759}
760
761bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
762 if (DisableSeparateConstOffsetFromGEP)
763 return false;
764
765 bool Changed = false;
766 for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {
767 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {
768 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {
769 Changed |= splitGEP(GEP);
770 }
771 // No need to split GEP ConstantExprs because all its indices are constant
772 // already.
773 }
774 }
775 return Changed;
776}