LLVM 24.0.0git
SeparateConstOffsetFromGEP.cpp
Go to the documentation of this file.
1//===- SeparateConstOffsetFromGEP.cpp -------------------------------------===//
2//
3// 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
6//
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// load 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//
81// Another improvement enabled by the LowerGEP flag is to lower a GEP with
82// multiple indices to multiple GEPs with a single index.
83// Such transformation can have following benefits:
84// (1) It can always extract constants in the indices of structure type.
85// (2) After such Lowering, there are more optimization opportunities such as
86// CSE, LICM and CGP.
87//
88// E.g. The following GEPs have multiple indices:
89// BB1:
90// %p = getelementptr [10 x %struct], ptr %ptr, i64 %i, i64 %j1, i32 3
91// load %p
92// ...
93// BB2:
94// %p2 = getelementptr [10 x %struct], ptr %ptr, i64 %i, i64 %j1, i32 2
95// load %p2
96// ...
97//
98// We can not do CSE to the common part related to index "i64 %i". Lowering
99// GEPs can achieve such goals.
100//
101// This pass will lower a GEP with multiple indices into multiple GEPs with a
102// single index:
103// BB1:
104// %2 = mul i64 %i, length_of_10xstruct ; CSE opportunity
105// %3 = getelementptr i8, ptr %ptr, i64 %2 ; CSE opportunity
106// %4 = mul i64 %j1, length_of_struct
107// %5 = getelementptr i8, ptr %3, i64 %4
108// %p = getelementptr i8, ptr %5, struct_field_3 ; Constant offset
109// load %p
110// ...
111// BB2:
112// %8 = mul i64 %i, length_of_10xstruct ; CSE opportunity
113// %9 = getelementptr i8, ptr %ptr, i64 %8 ; CSE opportunity
114// %10 = mul i64 %j2, length_of_struct
115// %11 = getelementptr i8, ptr %9, i64 %10
116// %p2 = getelementptr i8, ptr %11, struct_field_2 ; Constant offset
117// load %p2
118// ...
119//
120// Lowering GEPs can also benefit other passes such as LICM and CGP.
121// LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
122// indices if one of the index is variant. If we lower such GEP into invariant
123// parts and variant parts, LICM can hoist/sink those invariant parts.
124// CGP (CodeGen Prepare) tries to sink address calculations that match the
125// target's addressing modes. A GEP with multiple indices may not match and will
126// not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
127// them. So we end up with a better addressing mode.
128//
129//===----------------------------------------------------------------------===//
130
132#include "llvm/ADT/APInt.h"
133#include "llvm/ADT/DenseMap.h"
135#include "llvm/ADT/SmallVector.h"
141#include "llvm/IR/BasicBlock.h"
142#include "llvm/IR/Constant.h"
143#include "llvm/IR/Constants.h"
144#include "llvm/IR/DataLayout.h"
145#include "llvm/IR/DerivedTypes.h"
146#include "llvm/IR/Dominators.h"
147#include "llvm/IR/Function.h"
149#include "llvm/IR/IRBuilder.h"
150#include "llvm/IR/InstrTypes.h"
151#include "llvm/IR/Instruction.h"
152#include "llvm/IR/Instructions.h"
153#include "llvm/IR/Module.h"
154#include "llvm/IR/PassManager.h"
155#include "llvm/IR/PatternMatch.h"
156#include "llvm/IR/Type.h"
157#include "llvm/IR/User.h"
158#include "llvm/IR/Value.h"
160#include "llvm/Pass.h"
161#include "llvm/Support/Casting.h"
168#include <cassert>
169#include <cstdint>
170#include <iterator>
171#include <optional>
172#include <string>
173
174using namespace llvm;
175using namespace llvm::PatternMatch;
176
178 "disable-separate-const-offset-from-gep", cl::init(false),
179 cl::desc("Do not separate the constant offset from a GEP instruction"),
180 cl::Hidden);
181
182// Setting this flag may emit false positives when the input module already
183// contains dead instructions. Therefore, we set it only in unit tests that are
184// free of dead code.
185static cl::opt<bool>
186 VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
187 cl::desc("Verify this pass produces no dead code"),
188 cl::Hidden);
189
190namespace {
191
192/// A helper class for separating a constant offset from a GEP index.
193///
194/// In real programs, a GEP index may be more complicated than a simple addition
195/// of something and a constant integer which can be trivially splitted. For
196/// example, to split ((a << 3) | 5) + b, we need to search deeper for the
197/// constant offset, so that we can separate the index to (a << 3) + b and 5.
198///
199/// Therefore, this class looks into the expression that computes a given GEP
200/// index, and tries to find a constant integer that can be hoisted to the
201/// outermost level of the expression as an addition. Not every constant in an
202/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
203/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
204/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
205class ConstantOffsetExtractor {
206public:
207 /// Extracts a constant offset from the given GEP index. It returns the
208 /// new index representing the remainder (equal to the original index minus
209 /// the constant offset), or nullptr if we cannot extract a constant offset.
210 /// \p Idx The given GEP index use
211 /// \p UserChainTail Outputs the tail of UserChain so that we can
212 /// garbage-collect unused instructions in UserChain.
213 /// \p PreservesNUW Outputs whether the extraction allows preserving the
214 /// GEP's nuw flag, if it has one.
215 static Value *Extract(const Use &Idx, User *&UserChainTail,
216 bool &PreservesNUW);
217
218 /// Looks for a constant offset from the given GEP index without extracting
219 /// it. It returns the numeric value of the extracted constant offset, or
220 /// std::nullopt on failure. The arguments have the same meaning as Extract.
221 static std::optional<APInt> Find(const Use &Idx);
222
223private:
224 ConstantOffsetExtractor(BasicBlock::iterator InsertionPt)
225 : IP(InsertionPt), DL(InsertionPt->getDataLayout()), SQ(DL) {}
226
227 /// Searches the expression that computes V for a constant offset C s.t.
228 /// V can be reassociated into the form V' + C. If the searching is
229 /// successful, returns C and update UserChain as a def-use chain from C to V;
230 /// otherwise, returns std::nullopt and UserChain is empty.
231 /// \p V The given expression
232 /// \p Idx The original index use of the GEP, or nullptr if its
233 /// sign and bounds information no longer applies
234 /// \p SignExtended Whether V will be sign-extended in the computation of
235 /// the GEP index
236 /// \p ZeroExtended Whether V will be zero-extended in the computation of
237 /// the GEP index
238 std::optional<APInt> find(Value *V, const Use *Idx, bool SignExtended,
239 bool ZeroExtended);
240
241 /// A helper function to look into both operands of a binary operator.
242 std::optional<APInt>
243 findInEitherOperand(BinaryOperator *BO, bool SignExtended, bool ZeroExtended);
244
245 /// After finding the constant offset C from the GEP index I, we build a new
246 /// index I' s.t. I' + C = I. This function builds and returns the new
247 /// index I' according to UserChain produced by function "find".
248 ///
249 /// The building conceptually takes two steps:
250 /// 1) iteratively distribute sext/zext/trunc towards the leaves of the
251 /// expression tree that computes I
252 /// 2) reassociate the expression tree to the form I' + C.
253 ///
254 /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
255 /// sext to a, b and 5 so that we have
256 /// sext(a) + (sext(b) + 5).
257 /// Then, we reassociate it to
258 /// (sext(a) + sext(b)) + 5.
259 /// Given this form, we know I' is sext(a) + sext(b).
260 Value *rebuildWithoutConstOffset();
261
262 /// After the first step of rebuilding the GEP index without the constant
263 /// offset, distribute sext/zext/trunc to the operands of all operators in
264 /// UserChain. e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
265 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
266 ///
267 /// The function also updates UserChain to point to new subexpressions after
268 /// distributing sext/zext/trunc. e.g., the old UserChain of the above example
269 /// is
270 /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
271 /// and the new UserChain is
272 /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
273 /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
274 ///
275 /// \p ChainIndex The index to UserChain. ChainIndex is initially
276 /// UserChain.size() - 1, and is decremented during
277 /// the recursion.
278 Value *distributeCastsAndCloneChain(unsigned ChainIndex);
279
280 /// Reassociates the GEP index to the form I' + C and returns I'.
281 Value *removeConstOffset(unsigned ChainIndex);
282
283 /// A helper function to apply CastInsts, a list of sext/zext/trunc, to value
284 /// V. e.g., if CastInsts = [sext i32 to i64, zext i16 to i32], this function
285 /// returns "sext i32 (zext i16 V to i32) to i64".
286 Value *applyCasts(Value *V);
287
288 /// A helper function that returns whether we can trace into the operands
289 /// of binary operator BO for a constant offset.
290 ///
291 /// \p SignExtended Whether BO is surrounded by sext
292 /// \p ZeroExtended Whether BO is surrounded by zext
293 /// \p Idx The original index use of the GEP, or nullptr if its
294 /// sign and bounds information no longer applies
295 bool canTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
296 const Use *Idx);
297
298 /// Analyze a xor expression, and identify the bits in the constant operand
299 /// that are disjoint from the base operand's known set bits. For these
300 /// disjoint bits, a xor is equivalent to an addition, which allows us to
301 /// extract them as constant offsets that can be folded into the immediate
302 /// field of addressing operations. The transformation is the following one:
303 ///
304 /// Base ^ Const becomes (Base ^ NonDisjointBits) + DisjointBits
305 ///
306 /// where DisjointBits = Const & KnownZeros(Base) and
307 /// NonDisjointBits = Const & ~DisjointBits.
308 ///
309 /// Example with ptr having known-zero low bit:
310 /// Original: `xor %ptr, 3` ; 3 = 0b11
311 /// Analysis: DisjointBits = 3 & KnownZeros(%ptr) = 0b11 & 0b01 = 0b01
312 /// Result: `(xor %ptr, 2) + 1` where 1 can be folded into address mode
313 ///
314 /// \param XorInst The XOR binary operator to analyze
315 /// \return Returns the disjoint bits (the extractable offset), or
316 /// std::nullopt if none exist. On success, stores NonDisjointBits in
317 /// NonDisjointXorConstantBits.
318 std::optional<APInt> extractDisjointBitsFromXor(BinaryOperator *XorInst);
319
320 /// The non-disjoint bits remaining after xor decomposition in
321 /// `extractDisjointBitsFromXor`, which are later used while replacing the
322 /// original xor constant operand.
323 ConstantInt *NonDisjointXorConstantBits = nullptr;
324
325 /// The path from the constant offset to the old GEP index. e.g., if the GEP
326 /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
327 /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
328 /// UserChain[2] will be the entire expression "a * b + (c + 5)".
329 ///
330 /// This path helps to rebuild the new GEP index.
331 SmallVector<User *, 8> UserChain;
332
333 /// A data structure used in rebuildWithoutConstOffset. Contains all
334 /// sext/zext/trunc instructions along UserChain.
336
337 /// Insertion position of cloned instructions.
339
340 const DataLayout &DL;
341 const SimplifyQuery SQ;
342};
343
344/// A pass that tries to split every GEP in the function into a variadic
345/// base and a constant offset. It is a FunctionPass because searching for the
346/// constant offset may inspect other basic blocks.
347class SeparateConstOffsetFromGEPLegacyPass : public FunctionPass {
348public:
349 static char ID;
350
351 SeparateConstOffsetFromGEPLegacyPass(bool LowerGEP = false)
352 : FunctionPass(ID), LowerGEP(LowerGEP) {
355 }
356
357 void getAnalysisUsage(AnalysisUsage &AU) const override {
358 AU.addRequired<DominatorTreeWrapperPass>();
359 AU.addRequired<TargetTransformInfoWrapperPass>();
360 AU.addRequired<LoopInfoWrapperPass>();
361 AU.setPreservesCFG();
362 AU.addRequired<TargetLibraryInfoWrapperPass>();
363 }
364
365 bool runOnFunction(Function &F) override;
366
367private:
368 bool LowerGEP;
369};
370
371/// A pass that tries to split every GEP in the function into a variadic
372/// base and a constant offset. It is a FunctionPass because searching for the
373/// constant offset may inspect other basic blocks.
374class SeparateConstOffsetFromGEP {
375public:
376 SeparateConstOffsetFromGEP(
377 DominatorTree *DT, LoopInfo *LI, TargetLibraryInfo *TLI,
378 function_ref<TargetTransformInfo &(Function &)> GetTTI, bool LowerGEP)
379 : DT(DT), LI(LI), TLI(TLI), GetTTI(GetTTI), LowerGEP(LowerGEP) {}
380
381 bool run(Function &F);
382
383private:
384 /// Track the operands of an add or sub.
385 using ExprKey = std::pair<Value *, Value *>;
386
387 /// Create a pair for use as a map key for a commutable operation.
388 static ExprKey createNormalizedCommutablePair(Value *A, Value *B) {
389 if (A < B)
390 return {A, B};
391 return {B, A};
392 }
393
394 /// Tries to split the given GEP into a variadic base and a constant offset,
395 /// and returns true if the splitting succeeds.
396 bool splitGEP(GetElementPtrInst *GEP);
397
398 /// Tries to reorder the given GEP with the GEP that produces the base if
399 /// doing so results in producing a constant offset as the outermost
400 /// index.
401 bool reorderGEP(GetElementPtrInst *GEP, TargetTransformInfo &TTI);
402
403 /// Lower a GEP with multiple indices into multiple GEPs with a single index.
404 /// Function splitGEP already split the original GEP into a variadic part and
405 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
406 /// variadic part into a set of GEPs with a single index and applies
407 /// AccumulativeByteOffset to it.
408 /// \p Variadic The variadic part of the original GEP.
409 /// \p AccumulativeByteOffset The constant offset.
410 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
411 const APInt &AccumulativeByteOffset);
412
413 /// Finds the constant offset within each index and accumulates them. If
414 /// LowerGEP is true, it finds in indices of both sequential and structure
415 /// types, otherwise it only finds in sequential indices. The output
416 /// NeedsExtraction indicates whether we successfully find a constant
417 /// offset, and SignedOverflow indicates if there was signed overflow in
418 /// offset calculation.
419 APInt accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction,
420 bool &SignedOverflow);
421
422 /// Canonicalize array indices to pointer-size integers. This helps to
423 /// simplify the logic of splitting a GEP. For example, if a + b is a
424 /// pointer-size integer, we have
425 /// gep base, a + b = gep (gep base, a), b
426 /// However, this equality may not hold if the size of a + b is smaller than
427 /// the pointer size, because LLVM conceptually sign-extends GEP indices to
428 /// pointer size before computing the address
429 /// (http://llvm.org/docs/LangRef.html#id181).
430 ///
431 /// This canonicalization is very likely already done in clang and
432 /// instcombine. Therefore, the program will probably remain the same.
433 ///
434 /// Returns true if the module changes.
435 ///
436 /// Verified in @i32_add in split-gep.ll
437 bool canonicalizeArrayIndicesToIndexSize(GetElementPtrInst *GEP);
438
439 /// Optimize sext(a)+sext(b) to sext(a+b) when a+b can't sign overflow.
440 /// SeparateConstOffsetFromGEP distributes a sext to leaves before extracting
441 /// the constant offset. After extraction, it becomes desirable to reunion the
442 /// distributed sexts. For example,
443 ///
444 /// &a[sext(i +nsw (j +nsw 5)]
445 /// => distribute &a[sext(i) +nsw (sext(j) +nsw 5)]
446 /// => constant extraction &a[sext(i) + sext(j)] + 5
447 /// => reunion &a[sext(i +nsw j)] + 5
448 bool reuniteExts(Function &F);
449
450 /// A helper that reunites sexts in an instruction.
451 bool reuniteExts(Instruction *I);
452
453 /// Find the closest dominator of <Dominatee> that is equivalent to <Key>.
454 Instruction *findClosestMatchingDominator(
455 ExprKey Key, Instruction *Dominatee,
456 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs);
457
458 /// Verify F is free of dead code.
459 void verifyNoDeadCode(Function &F);
460
461 bool hasMoreThanOneUseInLoop(Value *v, Loop *L);
462
463 // Swap the index operand of two GEP.
464 void swapGEPOperand(GetElementPtrInst *First, GetElementPtrInst *Second);
465
466 // Check if it is safe to swap operand of two GEP.
467 bool isLegalToSwapOperand(GetElementPtrInst *First, GetElementPtrInst *Second,
468 Loop *CurLoop);
469
470 const DataLayout *DL = nullptr;
471 DominatorTree *DT = nullptr;
472 LoopInfo *LI;
473 TargetLibraryInfo *TLI;
474 // Retrieved lazily since not always used.
475 function_ref<TargetTransformInfo &(Function &)> GetTTI;
476
477 /// Whether to lower a GEP with multiple indices into arithmetic operations or
478 /// multiple GEPs with a single index.
479 bool LowerGEP;
480
481 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingAdds;
482 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingSubs;
483};
484
485} // end anonymous namespace
486
487char SeparateConstOffsetFromGEPLegacyPass::ID = 0;
488
490 SeparateConstOffsetFromGEPLegacyPass, "separate-const-offset-from-gep",
491 "Split GEPs to a variadic base and a constant offset for better CSE", false,
492 false)
499 SeparateConstOffsetFromGEPLegacyPass, "separate-const-offset-from-gep",
500 "Split GEPs to a variadic base and a constant offset for better CSE", false,
501 false)
502
504 return new SeparateConstOffsetFromGEPLegacyPass(LowerGEP);
505}
506
507// Checks if it is safe to reorder an add/sext result used in a GEP.
508//
509// An inbounds GEP does not guarantee that the index is non-negative.
510// This helper first checks whether value tracking proves that the add cannot
511// have signed overflow. If so, the transform is safe.
512// Second, it checks whether the GEP is inbounds and directly based on a global
513// or an alloca, which are required to prove futher transform validity.
514// If the GEP:
515// - Has a zero offset from the base and Idx is its first index, the index is
516// non-negative (any negative value would produce poison/UB)
517// - Has ObjectSize < (2^(N-1) - C + 1) * stride, where C is a constant from the
518// add, stride is the element size of Idx, and N is bitwidth of the add.
519// This is because with this pattern:
520// %add = add iN %val, C
521// %sext = sext iN %add to i64
522// %gep = getelementptr inbounds TYPE, %sext
523// The worst-case is when %val sign-flips to produce the smallest magnitude
524// negative value, at 2^(N-1)-1. In this case, the add/sext is -(2^(N-1)-C+1),
525// and the sext/add is 2^(N-1)+C-1 (2^N difference). The original add/sext
526// only produces a defined GEP when -(2^(N-1)-C+1) is inbounds. So, if
527// ObjectSize < (2^(N-1) - C + 1) * stride, it is impossible for the
528// worst-case sign-flip to be defined.
529// Note that in this case the GEP is not neccesarily non-negative, but any
530// negative results will still produce the same behavior in the reordered
531// version with a defined GEP.
532// This can also work for negative C, but the threshold is instead
533// (2^(N-1)+C)*stride, since the sign-flip is done in reverse and is instead
534// producing a large positive value that still needs to be inbounds to the
535// object size. If C is negative, we cannot make any useful assumptions based
536// on the offset, since it would need to be extremely large.
537static bool canReorderAddSextToGEP(const Use *Idx, const BinaryOperator *Add,
538 const DataLayout &DL) {
541 return true;
542
543 const auto *GEP = cast<GetElementPtrInst>(Idx->getUser());
544 if (!GEP->isInBounds())
545 return false;
546
547 const Value *Ptr = GEP->getPointerOperand();
548 int64_t Offset = 0;
549 const Value *Base =
550 GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL);
551
552 // We need one of the operands to be a constant to be able to trace into the
553 // operator.
554 const ConstantInt *CI = dyn_cast<ConstantInt>(Add->getOperand(0));
555 if (!CI)
556 CI = dyn_cast<ConstantInt>(Add->getOperand(1));
557 if (!CI)
558 return false;
559 // Calculate the threshold
560 APInt Threshold;
561 unsigned N = Add->getType()->getIntegerBitWidth();
562 // Track the use: the same value may index different types in this GEP.
563 auto GTI = std::next(gep_type_begin(GEP), Idx->getOperandNo() - 1);
564 TypeSize ElemSize = GTI.getSequentialElementStride(DL);
565 if (ElemSize.isScalable())
566 return false;
567 uint64_t Stride = ElemSize.getFixedValue();
568 if (!CI->isNegative()) {
569 // (2^(N-1) - C + 1) * stride
570 Threshold = (APInt::getSignedMinValue(N).zext(128) -
571 CI->getValue().zextOrTrunc(128) + 1) *
572 APInt(128, Stride);
573 } else {
574 // (2^(N-1) + C) * stride
575 Threshold = (APInt::getSignedMinValue(N).zext(128) +
576 CI->getValue().sextOrTrunc(128)) *
577 APInt(128, Stride);
578 }
579
580 // Only the first index is relative to Ptr. Earlier indices may move the
581 // pointer within the object, so later indices must use the object-size proof.
582 if (Idx->getOperandNo() == 1 && Base &&
584 // If the offset is zero from an alloca or global, inbounds is sufficient to
585 // prove non-negativity if one add operand is non-negative
586 if (Offset == 0)
587 return true;
588
589 // Check if the Offset < Threshold (positive CI only) otherwise
590 if (Offset < 0)
591 return true;
592 if (APInt(128, (uint64_t)Offset).ult(Threshold))
593 return true;
594 } else {
595 // If we can't determine the offset from the base object, we can still use
596 // the underlying object and type size constraints
598 // Can only prove non-negativity if the base object is known
600 return false;
601 }
602
603 // Check if the ObjectSize < Threshold (for both positive or negative C)
604 uint64_t ObjSize = 0;
605 if (const auto *AI = dyn_cast<AllocaInst>(Base)) {
606 if (auto AllocSize = AI->getAllocationSize(DL))
607 if (!AllocSize->isScalable())
608 ObjSize = AllocSize->getFixedValue();
609 } else if (const auto *GV = dyn_cast<GlobalVariable>(Base)) {
610 TypeSize GVSize = DL.getTypeAllocSize(GV->getValueType());
611 if (!GVSize.isScalable())
612 ObjSize = GVSize.getFixedValue();
613 }
614 if (ObjSize > 0 && APInt(128, ObjSize).ult(Threshold))
615 return true;
616
617 return false;
618}
619
620bool ConstantOffsetExtractor::canTraceInto(bool SignExtended, bool ZeroExtended,
621 BinaryOperator *BO, const Use *Idx) {
622 // Do not trace into "or" unless it is equivalent to "add nuw nsw".
623 // This is the case if the or's disjoint flag is set.
624 if (BO->getOpcode() == Instruction::Or)
625 return cast<PossiblyDisjointInst>(BO)->isDisjoint();
626
627 // We only consider ADD and SUB here, because a non-zero constant found in
628 // expressions composed of these operations can be easily hoisted as a
629 // constant offset by reassociation.
630 if (BO->getOpcode() != Instruction::Add &&
631 BO->getOpcode() != Instruction::Sub)
632 return false;
633
634 // FIXME: We don't currently support constants from the RHS of subs,
635 // when we are zero-extended, because we need a way to zero-extended
636 // them before they are negated.
637 if (ZeroExtended && !SignExtended && BO->getOpcode() == Instruction::Sub)
638 return false;
639
640 // In addition, tracing into BO requires that its surrounding sext/zext/trunc
641 // (if any) is distributable to both operands.
642 //
643 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
644 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
645 if ((!SignExtended || BO->hasNoSignedWrap()) &&
646 (!ZeroExtended || BO->hasNoUnsignedWrap()))
647 return true;
648
649 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && Idx) {
650 const auto *GEP = cast<GetElementPtrInst>(Idx->getUser());
651 // For a sext(add nuw), allow tracing through when the enclosing GEP is both
652 // inbounds and nuw.
653 if (SignExtended && BO->hasNoUnsignedWrap() && GEP->isInBounds() &&
654 GEP->hasNoUnsignedWrap())
655 return true;
656
657 // Trace through sext when value tracking or the GEP's bounds prove that
658 // the addition cannot have signed overflow.
659 //
660 // Verified in @sext_add in split-gep.ll.
661 if (canReorderAddSextToGEP(Idx, BO, DL))
662 return true;
663 }
664
665 return false;
666}
667
668std::optional<APInt> ConstantOffsetExtractor::findInEitherOperand(
669 BinaryOperator *BO, bool SignExtended, bool ZeroExtended) {
670 // Save off the current height of the chain, in case we need to restore it.
671 size_t ChainLength = UserChain.size();
672
673 // An intervening binary operator invalidates the GEP's index sign and bounds
674 // information, so do not pass it to either operand.
675 std::optional<APInt> ConstantOffset =
676 find(BO->getOperand(0), nullptr, SignExtended, ZeroExtended);
677 // If we found a constant offset in the left operand, stop and return that.
678 // This shortcut might cause us to miss opportunities of combining the
679 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
680 // However, such cases are probably already handled by -instcombine,
681 // given this pass runs after the standard optimizations.
682 if (ConstantOffset)
683 return ConstantOffset;
684
685 // Reset the chain back to where it was when we started exploring this node,
686 // since visiting the LHS didn't pan out.
687 UserChain.resize(ChainLength);
688
689 ConstantOffset = find(BO->getOperand(1), nullptr, SignExtended, ZeroExtended);
690 // If U is a sub operator, negate the constant offset found in the right
691 // operand.
692 if (ConstantOffset && BO->getOpcode() == Instruction::Sub)
693 *ConstantOffset = -*ConstantOffset;
694
695 // If RHS wasn't a suitable candidate either, reset the chain again.
696 if (!ConstantOffset)
697 UserChain.resize(ChainLength);
698
699 return ConstantOffset;
700}
701
702std::optional<APInt> ConstantOffsetExtractor::find(Value *V, const Use *Idx,
703 bool SignExtended,
704 bool ZeroExtended) {
705 // TODO(jingyue): We could trace into integer/pointer casts, such as
706 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
707 // integers because it gives good enough results for our benchmarks.
708 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
709
710 // We cannot do much with Values that are not a User, such as an Argument.
711 User *U = dyn_cast<User>(V);
712 if (U == nullptr)
713 return std::nullopt;
714
715 std::optional<APInt> ConstantOffset;
716 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
717 // Leave literal zero offsets alone.
718 if (CI->isZero())
719 return std::nullopt;
720 // Hooray, we found it!
721 ConstantOffset = CI->getValue();
722 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
723 // Trace into subexpressions for more hoisting opportunities.
724 if (canTraceInto(SignExtended, ZeroExtended, BO, Idx))
725 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
726 else if (BO->getOpcode() == Instruction::Xor)
727 ConstantOffset = extractDisjointBitsFromXor(BO);
728 } else if (isa<TruncInst>(V)) {
729 if (SignExtended || ZeroExtended)
730 return ConstantOffset;
731 ConstantOffset = find(U->getOperand(0), Idx, SignExtended, ZeroExtended);
732 if (ConstantOffset)
733 *ConstantOffset = ConstantOffset->trunc(BitWidth);
734 } else if (isa<SExtInst>(V)) {
735 ConstantOffset =
736 find(U->getOperand(0), Idx, /* SignExtended */ true, ZeroExtended);
737 if (ConstantOffset)
738 *ConstantOffset = ConstantOffset->sext(BitWidth);
739 } else if (isa<ZExtInst>(V)) {
740 // As an optimization, we can clear the SignExtended flag because
741 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
742 ConstantOffset = find(U->getOperand(0), Idx, /* SignExtended */ false,
743 /* ZeroExtended */ true);
744 if (ConstantOffset)
745 *ConstantOffset = ConstantOffset->zext(BitWidth);
746 }
747
748 // If we found a constant offset, add it to the path for
749 // rebuildWithoutConstOffset.
750 if (ConstantOffset)
751 UserChain.push_back(U);
752 return ConstantOffset;
753}
754
755Value *ConstantOffsetExtractor::applyCasts(Value *V) {
756 Value *Current = V;
757 // CastInsts is built in the use-def order. Therefore, we apply them to V
758 // in the reversed order.
759 for (CastInst *I : llvm::reverse(CastInsts)) {
760 if (Constant *C = dyn_cast<Constant>(Current)) {
761 // Try to constant fold the cast.
762 Current = ConstantFoldCastOperand(I->getOpcode(), C, I->getType(), DL);
763 if (Current)
764 continue;
765 }
766
767 Instruction *Cast = I->clone();
768 Cast->setOperand(0, Current);
769 // In ConstantOffsetExtractor::find we do not analyze nuw/nsw for trunc, so
770 // we assume that it is ok to redistribute trunc over add/sub/or. But for
771 // example (add (trunc nuw A), (trunc nuw B)) is more poisonous than (trunc
772 // nuw (add A, B))). To make such redistributions legal we drop all the
773 // poison generating flags from cloned trunc instructions here.
774 if (isa<TruncInst>(Cast))
776 Cast->insertBefore(*IP->getParent(), IP);
777 Current = Cast;
778 }
779 return Current;
780}
781
782Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
783 distributeCastsAndCloneChain(UserChain.size() - 1);
784 // Remove all nullptrs (used to be sext/zext/trunc) from UserChain.
785 unsigned NewSize = 0;
786 for (User *I : UserChain) {
787 if (I != nullptr) {
788 UserChain[NewSize] = I;
789 NewSize++;
790 }
791 }
792 UserChain.resize(NewSize);
793 return removeConstOffset(UserChain.size() - 1);
794}
795
796Value *
797ConstantOffsetExtractor::distributeCastsAndCloneChain(unsigned ChainIndex) {
798 User *U = UserChain[ChainIndex];
799 if (ChainIndex == 0) {
801 // If U is a ConstantInt, applyCasts will return a ConstantInt as well.
802 return UserChain[ChainIndex] = cast<ConstantInt>(applyCasts(U));
803 }
804
805 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
806 assert(
807 (isa<SExtInst>(Cast) || isa<ZExtInst>(Cast) || isa<TruncInst>(Cast)) &&
808 "Only following instructions can be traced: sext, zext & trunc");
809 CastInsts.push_back(Cast);
810 UserChain[ChainIndex] = nullptr;
811 return distributeCastsAndCloneChain(ChainIndex - 1);
812 }
813
814 // Function find only trace into BinaryOperator and CastInst.
815 BinaryOperator *BO = cast<BinaryOperator>(U);
816 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
817 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
818 Value *TheOther = applyCasts(BO->getOperand(1 - OpNo));
819 Value *NextInChain = distributeCastsAndCloneChain(ChainIndex - 1);
820
821 BinaryOperator *NewBO = nullptr;
822 if (OpNo == 0) {
823 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
824 BO->getName(), IP);
825 } else {
826 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
827 BO->getName(), IP);
828 }
829 return UserChain[ChainIndex] = NewBO;
830}
831
832Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
833 if (ChainIndex == 0) {
834 assert(isa<ConstantInt>(UserChain[ChainIndex]));
835 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
836 }
837
838 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
839 assert((BO->use_empty() || BO->hasOneUse()) &&
840 "distributeCastsAndCloneChain clones each BinaryOperator in "
841 "UserChain, so no one should be used more than "
842 "once");
843
844 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
845 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
846 Value *NextInChain = removeConstOffset(ChainIndex - 1);
847 Value *TheOther = BO->getOperand(1 - OpNo);
848
849 // When rewriting xor(TheOther, NextInChain) expressions, the original
850 // constant operand is replaced with the non-disjoints bits, which are the
851 // non-extractable bits, i.e., those that must remain in the xor (the other
852 // bits have already compounded the GEP offset).
853 if (BO->getOpcode() == Instruction::Xor) {
854 // The non-disjoint bits are cached in NonDisjointXorConstantBits, which is
855 // always up-to-date.
856 assert(NonDisjointXorConstantBits &&
857 "XOR in UserChain without recorded non-disjoint bits");
858 // Only casts can happen to be distributed among the xor operands.
859 NextInChain = applyCasts(NonDisjointXorConstantBits);
860 }
861
862 Value *LHS = OpNo == 0 ? NextInChain : TheOther;
863 Value *RHS = OpNo == 0 ? TheOther : NextInChain;
864
865 // Zero is a right identity for all supported operators, and a left identity
866 // for all except subtraction.
867 if (match(RHS, m_Zero()))
868 return LHS;
869 if (match(LHS, m_Zero()) && BO->getOpcode() != Instruction::Sub)
870 return RHS;
871
872 BinaryOperator::BinaryOps NewOp = BO->getOpcode();
873 if (BO->getOpcode() == Instruction::Or) {
874 // Rebuild "or" as "add", because "or" may be invalid for the new
875 // expression.
876 //
877 // For instance, given
878 // a | (b + 5) where a and b + 5 have no common bits,
879 // we can extract 5 as the constant offset.
880 //
881 // However, reusing the "or" in the new index would give us
882 // (a | b) + 5
883 // which does not equal a | (b + 5).
884 //
885 // Replacing the "or" with "add" is fine, because
886 // a | (b + 5) = a + (b + 5) = (a + b) + 5
887 NewOp = Instruction::Add;
888 }
889
890 BinaryOperator *NewBO = BinaryOperator::Create(NewOp, LHS, RHS, "", IP);
891 NewBO->takeName(BO);
892 return NewBO;
893}
894
895std::optional<APInt>
896ConstantOffsetExtractor::extractDisjointBitsFromXor(BinaryOperator *XorInst) {
897 assert(XorInst && XorInst->getOpcode() == Instruction::Xor &&
898 "Expected XOR instruction");
899
900 Value *BaseOp;
901 ConstantInt *XorConstantOp;
902
903 if (!match(XorInst, m_Xor(m_Value(BaseOp), m_ConstantInt(XorConstantOp))))
904 return std::nullopt;
905
906 const KnownBits BaseKnownBits = computeKnownBits(BaseOp, SQ);
907 const APInt &ConstantValue = XorConstantOp->getValue();
908
909 // Compute the disjoint bits, i.e., those bits of the constant operand that
910 // are known-zero in the base. These disjoint bits will contribute to the
911 // final GEP offset. If there are no disjoint bits, there isn't any offset to
912 // extract from the xor.
913 const APInt DisjointBits = ConstantValue & BaseKnownBits.Zero;
914 if (DisjointBits.isZero())
915 return std::nullopt;
916
917 // Avoid a pessimizing rewrite if the disjoint bits include the sign bit.
918 if (DisjointBits.isSignBitSet())
919 return std::nullopt;
920
921 // Compute the remaining bits, i.e., the non-disjoint ones, which are those
922 // that must be preserved in the xor.
923 const APInt NonDisjointBits = ConstantValue & ~DisjointBits;
924 NonDisjointXorConstantBits =
925 ConstantInt::get(XorInst->getContext(), NonDisjointBits);
926
927 // UserChain maintains a path from the constant up to the GEP index. Push the
928 // xor constant operand, which is the constant leaf of the chain (which is
929 // also what `distributeCastsAndCloneChain` expects). Such a chained operand
930 // is the one to be replaced with the non-disjoint bits, while rebuilding the
931 // xor afterwards. The xor instruction itself is pushed upon returning.
932 UserChain.push_back(XorConstantOp);
933
934 return DisjointBits;
935}
936
937/// A helper function to check if reassociating through an entry in the user
938/// chain would invalidate the GEP's nuw flag.
939static bool allowsPreservingNUW(const User *U) {
940 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
941 // Binary operations need to be effectively add nuw.
942 auto Opcode = BO->getOpcode();
943 if (Opcode == BinaryOperator::Or) {
944 // Ors are only considered here if they are disjoint. The addition that
945 // they represent in this case is NUW.
946 assert(cast<PossiblyDisjointInst>(BO)->isDisjoint());
947 return true;
948 }
949 return Opcode == BinaryOperator::Add && BO->hasNoUnsignedWrap();
950 }
951 // UserChain can only contain ConstantInt, CastInst, or BinaryOperator.
952 // Among the possible CastInsts, only trunc without nuw is a problem: If it
953 // is distributed through an add nuw, wrapping may occur:
954 // "add nuw trunc(a), trunc(b)" is more poisonous than "trunc(add nuw a, b)"
955 if (const TruncInst *TI = dyn_cast<TruncInst>(U))
956 return TI->hasNoUnsignedWrap();
957 assert((isa<CastInst>(U) || isa<ConstantInt>(U)) && "Unexpected User.");
958 return true;
959}
960
962 if (auto *I = dyn_cast<Instruction>(Idx.get()))
963 if (auto IP = I->getInsertionPointAfterDef())
964 return *IP;
965 return cast<GetElementPtrInst>(Idx.getUser())->getIterator();
966}
967
968Value *ConstantOffsetExtractor::Extract(const Use &Idx, User *&UserChainTail,
969 bool &PreservesNUW) {
970 ConstantOffsetExtractor Extractor(getIndexInsertionPoint(Idx));
971 // Find a constant offset first.
972 if (!Extractor.find(Idx, &Idx, /* SignExtended */ false,
973 /* ZeroExtended */ false)) {
974 UserChainTail = nullptr;
975 PreservesNUW = true;
976 return nullptr;
977 }
978
979 PreservesNUW = all_of(Extractor.UserChain, allowsPreservingNUW);
980
981 // Separates the constant offset from the GEP index.
982 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
983 UserChainTail = Extractor.UserChain.back();
984 return IdxWithoutConstOffset;
985}
986
987std::optional<APInt> ConstantOffsetExtractor::Find(const Use &Idx) {
988 auto *GEP = cast<GetElementPtrInst>(Idx.getUser());
989 return ConstantOffsetExtractor(GEP->getIterator())
990 .find(Idx, &Idx, /* SignExtended */ false, /* ZeroExtended */ false);
991}
992
993bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToIndexSize(
994 GetElementPtrInst *GEP) {
995 bool Changed = false;
996 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
998 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
999 I != E; ++I, ++GTI) {
1000 // Skip struct member indices which must be i32.
1001 if (GTI.isSequential()) {
1002 if ((*I)->getType() != PtrIdxTy) {
1003 *I = CastInst::CreateIntegerCast(*I, PtrIdxTy, true, "idxprom",
1005 Changed = true;
1006 }
1007 }
1008 }
1009 return Changed;
1010}
1011
1012APInt SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
1013 bool &NeedsExtraction,
1014 bool &SignedOverflow) {
1015 NeedsExtraction = false;
1016 SignedOverflow = false;
1017 unsigned IdxWidth = DL->getIndexTypeSizeInBits(GEP->getType());
1018 APInt AccumulativeByteOffset(IdxWidth, 0);
1020 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1021 if (GTI.isSequential()) {
1022 // Constant offsets of scalable types are not really constant.
1023 if (GTI.getIndexedType()->isScalableTy())
1024 continue;
1025
1026 // Tries to extract a constant offset from this GEP index.
1027 if (std::optional<APInt> ConstantOffset =
1028 ConstantOffsetExtractor::Find(GEP->getOperandUse(I))) {
1029 NeedsExtraction = true;
1030 // A GEP may have multiple indices. We accumulate the extracted
1031 // constant offset to a byte offset, and later offset the remainder of
1032 // the original GEP with this byte offset.
1033 bool Overflow;
1034 auto ByteOffset = ConstantOffset->sextOrTrunc(IdxWidth).smul_ov(
1035 APInt(IdxWidth, GTI.getSequentialElementStride(*DL),
1036 /*IsSigned=*/true, /*ImplicitTrunc=*/true),
1037 Overflow);
1038 SignedOverflow |= Overflow;
1039 AccumulativeByteOffset =
1040 AccumulativeByteOffset.sadd_ov(ByteOffset, Overflow);
1041 SignedOverflow |= Overflow;
1042 }
1043 } else if (LowerGEP) {
1044 StructType *StTy = GTI.getStructType();
1045 uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
1046 // Skip field 0 as the offset is always 0.
1047 if (Field != 0) {
1048 NeedsExtraction = true;
1049 AccumulativeByteOffset +=
1050 APInt(IdxWidth, DL->getStructLayout(StTy)->getElementOffset(Field),
1051 /*IsSigned=*/true, /*ImplicitTrunc=*/true);
1052 }
1053 }
1054 }
1055 return AccumulativeByteOffset;
1056}
1057
1058void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
1059 GetElementPtrInst *Variadic, const APInt &AccumulativeByteOffset) {
1060 IRBuilder<> Builder(Variadic);
1061 Type *PtrIndexTy = DL->getIndexType(Variadic->getType());
1062
1063 Value *ResultPtr = Variadic->getOperand(0);
1064 Loop *L = LI->getLoopFor(Variadic->getParent());
1065 // Check if the base is not loop invariant or used more than once.
1066 bool isSwapCandidate =
1067 L && L->isLoopInvariant(ResultPtr) &&
1068 !hasMoreThanOneUseInLoop(ResultPtr, L);
1069 Value *FirstResult = nullptr;
1070
1071 gep_type_iterator GTI = gep_type_begin(*Variadic);
1072 // Create an ugly GEP for each sequential index. We don't create GEPs for
1073 // structure indices, as they are accumulated in the constant offset index.
1074 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
1075 if (GTI.isSequential()) {
1076 Value *Idx = Variadic->getOperand(I);
1077 // Skip zero indices.
1078 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
1079 if (CI->isZero())
1080 continue;
1081
1082 APInt ElementSize = APInt(PtrIndexTy->getIntegerBitWidth(),
1084 // Scale the index by element size.
1085 if (ElementSize != 1) {
1086 if (ElementSize.isPowerOf2()) {
1087 Idx = Builder.CreateShl(
1088 Idx, ConstantInt::get(PtrIndexTy, ElementSize.logBase2()));
1089 } else {
1090 Idx =
1091 Builder.CreateMul(Idx, ConstantInt::get(PtrIndexTy, ElementSize));
1092 }
1093 }
1094 // Create an ugly GEP with a single index for each index.
1095 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Idx, "uglygep");
1096 if (FirstResult == nullptr)
1097 FirstResult = ResultPtr;
1098 }
1099 }
1100
1101 // Create a GEP with the constant offset index.
1102 if (AccumulativeByteOffset != 0) {
1103 Value *Offset = ConstantInt::get(PtrIndexTy, AccumulativeByteOffset);
1104 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Offset, "uglygep");
1105 } else
1106 isSwapCandidate = false;
1107
1108 // If we created a GEP with constant index, and the base is loop invariant,
1109 // then we swap the first one with it, so LICM can move constant GEP out
1110 // later.
1111 auto *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
1112 auto *SecondGEP = dyn_cast<GetElementPtrInst>(ResultPtr);
1113 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
1114 swapGEPOperand(FirstGEP, SecondGEP);
1115
1116 Variadic->replaceAllUsesWith(ResultPtr);
1117 Variadic->eraseFromParent();
1118}
1119
1120bool SeparateConstOffsetFromGEP::reorderGEP(GetElementPtrInst *GEP,
1121 TargetTransformInfo &TTI) {
1122 auto PtrGEP = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());
1123 if (!PtrGEP)
1124 return false;
1125
1126 bool NestedNeedsExtraction, OffsetOverflow;
1127 APInt NestedByteOffset =
1128 accumulateByteOffset(PtrGEP, NestedNeedsExtraction, OffsetOverflow);
1129 if (!NestedNeedsExtraction)
1130 return false;
1131
1132 unsigned AddrSpace = PtrGEP->getPointerAddressSpace();
1133 if (!TTI.isLegalAddressingMode(GEP->getResultElementType(),
1134 /*BaseGV=*/nullptr,
1135 NestedByteOffset.getSExtValue(),
1136 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace))
1137 return false;
1138
1139 bool GEPInBounds = GEP->isInBounds();
1140 bool PtrGEPInBounds = PtrGEP->isInBounds();
1141 bool IsChainInBounds = GEPInBounds && PtrGEPInBounds;
1142 if (IsChainInBounds) {
1143 auto IsKnownNonNegative = [this](Value *V) {
1144 return isKnownNonNegative(V, *DL);
1145 };
1146 IsChainInBounds &= all_of(GEP->indices(), IsKnownNonNegative);
1147 if (IsChainInBounds)
1148 IsChainInBounds &= all_of(PtrGEP->indices(), IsKnownNonNegative);
1149 }
1150
1151 IRBuilder<> Builder(GEP);
1152 // For trivial GEP chains, we can swap the indices.
1153 Value *NewSrc = Builder.CreateGEP(
1154 GEP->getSourceElementType(), PtrGEP->getPointerOperand(),
1155 SmallVector<Value *, 4>(GEP->indices()), "", IsChainInBounds);
1156 Value *NewGEP = Builder.CreateGEP(PtrGEP->getSourceElementType(), NewSrc,
1157 SmallVector<Value *, 4>(PtrGEP->indices()),
1158 "", IsChainInBounds);
1159 GEP->replaceAllUsesWith(NewGEP);
1161 return true;
1162}
1163
1164bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
1165 // Skip vector GEPs.
1166 if (GEP->getType()->isVectorTy())
1167 return false;
1168
1169 // If the base of this GEP is a ptradd of a constant, lets pass the constant
1170 // along. This ensures that when we have a chain of GEPs the constant
1171 // offset from each is accumulated.
1172 Value *NewBase;
1173 const APInt *BaseOffset;
1174 bool ExtractBase = match(GEP->getPointerOperand(),
1175 m_PtrAdd(m_Value(NewBase), m_APInt(BaseOffset)));
1176
1177 unsigned IdxWidth = DL->getIndexTypeSizeInBits(GEP->getType());
1178 APInt BaseByteOffset =
1179 ExtractBase ? BaseOffset->sextOrTrunc(IdxWidth) : APInt(IdxWidth, 0);
1180
1181 // The backend can already nicely handle the case where all indices are
1182 // constant.
1183 if (GEP->hasAllConstantIndices() && !ExtractBase)
1184 return false;
1185
1186 bool Changed = canonicalizeArrayIndicesToIndexSize(GEP);
1187
1188 bool NeedsExtraction, OffsetOverflow;
1189 APInt NonBaseByteOffset =
1190 accumulateByteOffset(GEP, NeedsExtraction, OffsetOverflow);
1191 bool AddOverflow;
1192 APInt AccumulativeByteOffset =
1193 BaseByteOffset.sadd_ov(NonBaseByteOffset, AddOverflow);
1194 OffsetOverflow |= AddOverflow;
1195
1196 TargetTransformInfo &TTI = GetTTI(*GEP->getFunction());
1197
1198 if (!NeedsExtraction && !ExtractBase) {
1199 Changed |= reorderGEP(GEP, TTI);
1200 return Changed;
1201 }
1202
1203 // If LowerGEP is disabled, before really splitting the GEP, check whether the
1204 // backend supports the addressing mode we are about to produce. If no, this
1205 // splitting probably won't be beneficial.
1206 // If LowerGEP is enabled, even the extracted constant offset can not match
1207 // the addressing mode, we can still do optimizations to other lowered parts
1208 // of variable indices. Therefore, we don't check for addressing modes in that
1209 // case.
1210 if (!LowerGEP) {
1211 unsigned AddrSpace = GEP->getPointerAddressSpace();
1213 GEP->getResultElementType(),
1214 /*BaseGV=*/nullptr, AccumulativeByteOffset.getSExtValue(),
1215 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace)) {
1216 // If the addressing mode was not legal and the base byte offset was not
1217 // 0, it could be a case where the total offset became too large for
1218 // the addressing mode. Try again without extracting the base offset.
1219 if (!ExtractBase)
1220 return Changed;
1221 ExtractBase = false;
1222 BaseByteOffset = APInt(IdxWidth, 0);
1223 AccumulativeByteOffset = NonBaseByteOffset;
1225 GEP->getResultElementType(),
1226 /*BaseGV=*/nullptr, AccumulativeByteOffset.getSExtValue(),
1227 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace))
1228 return Changed;
1229 // We can proceed with just extracting the other (non-base) offsets.
1230 NeedsExtraction = true;
1231 }
1232 }
1233
1234 // Track information for preserving GEP flags.
1235 bool AllOffsetsNonNegative =
1236 AccumulativeByteOffset.isNonNegative() && !OffsetOverflow;
1237 bool AllNUWPreserved = GEP->hasNoUnsignedWrap();
1238 bool NewGEPInBounds = GEP->isInBounds();
1239 bool NewGEPNUSW = GEP->hasNoUnsignedSignedWrap();
1240
1241 // Remove the constant offset in each sequential index. The resultant GEP
1242 // computes the variadic base.
1243 // Notice that we don't remove struct field indices here. If LowerGEP is
1244 // disabled, a structure index is not accumulated and we still use the old
1245 // one. If LowerGEP is enabled, a structure index is accumulated in the
1246 // constant offset. LowerToSingleIndexGEPs will later handle the constant
1247 // offset and won't need a new structure index.
1249 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1250 if (GTI.isSequential()) {
1251 // Constant offsets of scalable types are not really constant.
1252 if (GTI.getIndexedType()->isScalableTy())
1253 continue;
1254
1255 // Splits this GEP index into a variadic part and a constant offset, and
1256 // uses the variadic part as the new index.
1257 Value *Idx = GEP->getOperand(I);
1258 User *UserChainTail;
1259 bool PreservesNUW;
1260 Value *NewIdx = ConstantOffsetExtractor::Extract(
1261 GEP->getOperandUse(I), UserChainTail, PreservesNUW);
1262 if (NewIdx != nullptr) {
1263 // Switches to the index with the constant offset removed.
1264 GEP->setOperand(I, NewIdx);
1265 // After switching to the new index, we can garbage-collect UserChain
1266 // and the old index if they are not used.
1269 Idx = NewIdx;
1270 AllNUWPreserved &= PreservesNUW;
1271 }
1272 AllOffsetsNonNegative =
1273 AllOffsetsNonNegative && isKnownNonNegative(Idx, *DL);
1274 }
1275 }
1276 if (ExtractBase) {
1277 GEPOperator *Base = cast<GEPOperator>(GEP->getPointerOperand());
1278 AllNUWPreserved &= Base->hasNoUnsignedWrap();
1279 NewGEPInBounds &= Base->isInBounds();
1280 NewGEPNUSW &= Base->hasNoUnsignedSignedWrap();
1281 AllOffsetsNonNegative &= BaseByteOffset.isNonNegative();
1282
1283 GEP->setOperand(0, NewBase);
1285 }
1286
1287 // Clear the inbounds attribute because the new index may be off-bound.
1288 // e.g.,
1289 //
1290 // b = add i64 a, 5
1291 // addr = gep inbounds float, float* p, i64 b
1292 //
1293 // is transformed to:
1294 //
1295 // addr2 = gep float, float* p, i64 a ; inbounds removed
1296 // addr = gep float, float* addr2, i64 5 ; inbounds removed
1297 //
1298 // If a is -4, although the old index b is in bounds, the new index a is
1299 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
1300 // inbounds keyword is not present, the offsets are added to the base
1301 // address with silently-wrapping two's complement arithmetic".
1302 // Therefore, the final code will be a semantically equivalent.
1303 GEPNoWrapFlags NewGEPFlags = GEPNoWrapFlags::none();
1304
1305 // If the initial GEP was inbounds/nusw and all variable indices and the
1306 // accumulated offsets are non-negative, they can be added in any order and
1307 // the intermediate results are in bounds and don't overflow in a nusw sense.
1308 // So, we can preserve the inbounds/nusw flag for both GEPs.
1309 bool CanPreserveInBoundsNUSW = AllOffsetsNonNegative;
1310
1311 // If the initial GEP was NUW and all operations that we reassociate were NUW
1312 // additions, the resulting GEPs are also NUW.
1313 if (AllNUWPreserved) {
1314 NewGEPFlags |= GEPNoWrapFlags::noUnsignedWrap();
1315 // If the initial GEP additionally had NUSW (or inbounds, which implies
1316 // NUSW), we know that the indices in the initial GEP must all have their
1317 // signbit not set. For indices that are the result of NUW adds, the
1318 // add-operands therefore also don't have their signbit set. Therefore, all
1319 // indices of the resulting GEPs are non-negative -> we can preserve
1320 // the inbounds/nusw flag.
1321 CanPreserveInBoundsNUSW |= NewGEPNUSW;
1322 }
1323
1324 if (CanPreserveInBoundsNUSW) {
1325 if (NewGEPInBounds)
1326 NewGEPFlags |= GEPNoWrapFlags::inBounds();
1327 else if (NewGEPNUSW)
1328 NewGEPFlags |= GEPNoWrapFlags::noUnsignedSignedWrap();
1329 }
1330
1331 GEP->setNoWrapFlags(NewGEPFlags);
1332
1333 // Lowers a GEP to GEPs with a single index.
1334 if (LowerGEP) {
1335 lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
1336 return true;
1337 }
1338
1339 // No need to create another GEP if the accumulative byte offset is 0.
1340 if (AccumulativeByteOffset == 0)
1341 return true;
1342
1343 // Offsets the base with the accumulative byte offset.
1344 //
1345 // %gep ; the base
1346 // ... %gep ...
1347 //
1348 // => add the offset
1349 //
1350 // %gep2 ; clone of %gep
1351 // %new.gep = gep i8, %gep2, %offset
1352 // %gep ; will be removed
1353 // ... %gep ...
1354 //
1355 // => replace all uses of %gep with %new.gep and remove %gep
1356 //
1357 // %gep2 ; clone of %gep
1358 // %new.gep = gep i8, %gep2, %offset
1359 // ... %new.gep ...
1360 Instruction *NewGEP = GEP->clone();
1361 NewGEP->insertBefore(GEP->getIterator());
1362
1363 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
1364 IRBuilder<> Builder(GEP);
1365 NewGEP = cast<Instruction>(Builder.CreatePtrAdd(
1366 NewGEP, ConstantInt::get(PtrIdxTy, AccumulativeByteOffset),
1367 GEP->getName(), NewGEPFlags));
1368 NewGEP->copyMetadata(*GEP);
1369
1370 GEP->replaceAllUsesWith(NewGEP);
1371 GEP->eraseFromParent();
1372
1373 return true;
1374}
1375
1376bool SeparateConstOffsetFromGEPLegacyPass::runOnFunction(Function &F) {
1377 if (skipFunction(F))
1378 return false;
1379 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1380 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1381 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1382 auto GetTTI = [this](Function &F) -> TargetTransformInfo & {
1383 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1384 };
1385 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
1386 return Impl.run(F);
1387}
1388
1389bool SeparateConstOffsetFromGEP::run(Function &F) {
1391 return false;
1392
1393 DL = &F.getDataLayout();
1394 bool Changed = false;
1395
1396 ReversePostOrderTraversal<Function *> RPOT(&F);
1397 for (BasicBlock *B : RPOT) {
1398 if (!DT->isReachableFromEntry(B))
1399 continue;
1400
1401 for (Instruction &I : llvm::make_early_inc_range(*B))
1402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I))
1403 Changed |= splitGEP(GEP);
1404 // No need to split GEP ConstantExprs because all its indices are constant
1405 // already.
1406 }
1407
1408 Changed |= reuniteExts(F);
1409
1410 if (VerifyNoDeadCode)
1411 verifyNoDeadCode(F);
1412
1413 return Changed;
1414}
1415
1416Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1417 ExprKey Key, Instruction *Dominatee,
1418 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs) {
1419 auto Pos = DominatingExprs.find(Key);
1420 if (Pos == DominatingExprs.end())
1421 return nullptr;
1422
1423 auto &Candidates = Pos->second;
1424 // Because we process the basic blocks in pre-order of the dominator tree, a
1425 // candidate that doesn't dominate the current instruction won't dominate any
1426 // future instruction either. Therefore, we pop it out of the stack. This
1427 // optimization makes the algorithm O(n).
1428 while (!Candidates.empty()) {
1429 Instruction *Candidate = Candidates.back();
1430 if (DT->dominates(Candidate, Dominatee))
1431 return Candidate;
1432 Candidates.pop_back();
1433 }
1434 return nullptr;
1435}
1436
1437bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1438 if (!I->getType()->isIntOrIntVectorTy())
1439 return false;
1440
1441 // Dom: LHS+RHS
1442 // I: sext(LHS)+sext(RHS)
1443 // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1444 // TODO: handle zext
1445 Value *LHS = nullptr, *RHS = nullptr;
1446 if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1447 if (LHS->getType() == RHS->getType()) {
1448 ExprKey Key = createNormalizedCommutablePair(LHS, RHS);
1449 if (auto *Dom = findClosestMatchingDominator(Key, I, DominatingAdds)) {
1450 Instruction *NewSExt =
1451 new SExtInst(Dom, I->getType(), "", I->getIterator());
1452 NewSExt->takeName(I);
1453 I->replaceAllUsesWith(NewSExt);
1454 NewSExt->setDebugLoc(I->getDebugLoc());
1456 return true;
1457 }
1458 }
1459 } else if (match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1460 if (LHS->getType() == RHS->getType()) {
1461 if (auto *Dom =
1462 findClosestMatchingDominator({LHS, RHS}, I, DominatingSubs)) {
1463 Instruction *NewSExt =
1464 new SExtInst(Dom, I->getType(), "", I->getIterator());
1465 NewSExt->takeName(I);
1466 I->replaceAllUsesWith(NewSExt);
1467 NewSExt->setDebugLoc(I->getDebugLoc());
1469 return true;
1470 }
1471 }
1472 }
1473
1474 // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
1475 if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS)))) {
1477 ExprKey Key = createNormalizedCommutablePair(LHS, RHS);
1478 DominatingAdds[Key].push_back(I);
1479 }
1480 } else if (match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
1482 DominatingSubs[{LHS, RHS}].push_back(I);
1483 }
1484 return false;
1485}
1486
1487bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1488 bool Changed = false;
1489 DominatingAdds.clear();
1490 DominatingSubs.clear();
1491 for (const auto Node : depth_first(DT)) {
1492 BasicBlock *BB = Node->getBlock();
1493 for (Instruction &I : llvm::make_early_inc_range(*BB))
1494 Changed |= reuniteExts(&I);
1495 }
1496 return Changed;
1497}
1498
1499void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
1500 for (BasicBlock &B : F) {
1501 for (Instruction &I : B) {
1503 std::string ErrMessage;
1504 raw_string_ostream RSO(ErrMessage);
1505 RSO << "Dead instruction detected!\n" << I << "\n";
1506 llvm_unreachable(RSO.str().c_str());
1507 }
1508 }
1509 }
1510}
1511
1512bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1513 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP, Loop *CurLoop) {
1514 if (!FirstGEP || !FirstGEP->hasOneUse())
1515 return false;
1516
1517 if (!SecondGEP || FirstGEP->getParent() != SecondGEP->getParent())
1518 return false;
1519
1520 if (FirstGEP == SecondGEP)
1521 return false;
1522
1523 unsigned FirstNum = FirstGEP->getNumOperands();
1524 unsigned SecondNum = SecondGEP->getNumOperands();
1525 // Give up if the number of operands are not 2.
1526 if (FirstNum != SecondNum || FirstNum != 2)
1527 return false;
1528
1529 Value *FirstBase = FirstGEP->getOperand(0);
1530 Value *SecondBase = SecondGEP->getOperand(0);
1531 Value *FirstOffset = FirstGEP->getOperand(1);
1532 // Give up if the index of the first GEP is loop invariant.
1533 if (CurLoop->isLoopInvariant(FirstOffset))
1534 return false;
1535
1536 // Give up if base doesn't have same type.
1537 if (FirstBase->getType() != SecondBase->getType())
1538 return false;
1539
1540 Instruction *FirstOffsetDef = dyn_cast<Instruction>(FirstOffset);
1541
1542 // Check if the second operand of first GEP has constant coefficient.
1543 // For an example, for the following code, we won't gain anything by
1544 // hoisting the second GEP out because the second GEP can be folded away.
1545 // %scevgep.sum.ur159 = add i64 %idxprom48.ur, 256
1546 // %67 = shl i64 %scevgep.sum.ur159, 2
1547 // %uglygep160 = getelementptr i8* %65, i64 %67
1548 // %uglygep161 = getelementptr i8* %uglygep160, i64 -1024
1549
1550 // Skip constant shift instruction which may be generated by Splitting GEPs.
1551 if (FirstOffsetDef && FirstOffsetDef->isShift() &&
1552 isa<ConstantInt>(FirstOffsetDef->getOperand(1)))
1553 FirstOffsetDef = dyn_cast<Instruction>(FirstOffsetDef->getOperand(0));
1554
1555 // Give up if FirstOffsetDef is an Add or Sub with constant.
1556 // Because it may not profitable at all due to constant folding.
1557 if (FirstOffsetDef)
1558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FirstOffsetDef)) {
1559 unsigned opc = BO->getOpcode();
1560 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
1561 (isa<ConstantInt>(BO->getOperand(0)) ||
1563 return false;
1564 }
1565 return true;
1566}
1567
1568bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(Value *V, Loop *L) {
1569 // TODO: Could look at uses of globals, but we need to make sure we are
1570 // looking at the correct function.
1571 if (isa<Constant>(V))
1572 return false;
1573
1574 int UsesInLoop = 0;
1575 for (User *U : V->users()) {
1576 if (Instruction *User = dyn_cast<Instruction>(U))
1577 if (L->contains(User))
1578 if (++UsesInLoop > 1)
1579 return true;
1580 }
1581 return false;
1582}
1583
1584void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *First,
1585 GetElementPtrInst *Second) {
1586 Value *Offset1 = First->getOperand(1);
1587 Value *Offset2 = Second->getOperand(1);
1588 First->setOperand(1, Offset2);
1589 Second->setOperand(1, Offset1);
1590
1591 // After changing (p+o)+c to (p+c)+o, the inner GEP may not be inbounds
1592 // anymore.
1593 const DataLayout &DAL = First->getDataLayout();
1594 unsigned IdxBits = DAL.getIndexSizeInBits(
1595 cast<PointerType>(First->getType())->getAddressSpace());
1596
1597 auto ClearNoWrapFlags = [&] {
1598 // TODO(gep_nowrap): Make flag preservation more precise.
1599 First->setNoWrapFlags(GEPNoWrapFlags::none());
1601 };
1602
1603 APInt FirstOffset(IdxBits, 0);
1604 if (!First->accumulateConstantOffset(DAL, FirstOffset)) {
1605 ClearNoWrapFlags();
1606 return;
1607 }
1608
1609 APInt BaseOffset(IdxBits, 0);
1610 Value *NewBase =
1612 DAL, BaseOffset);
1613
1614 bool Overflow = false;
1615 APInt TotalOffset = BaseOffset.uadd_ov(FirstOffset, Overflow);
1616 uint64_t ObjectSize;
1617 if (Overflow || !getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1618 TotalOffset.ugt(ObjectSize)) {
1619 ClearNoWrapFlags();
1620 return;
1621 }
1622
1623 First->setIsInBounds(true);
1624}
1625
1627 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1628 static_cast<PassInfoMixin<SeparateConstOffsetFromGEPPass> *>(this)
1629 ->printPipeline(OS, MapClassName2PassName);
1630 OS << '<';
1631 if (LowerGEP)
1632 OS << "lower-gep";
1633 OS << '>';
1634}
1635
1638 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1639 auto *LI = &AM.getResult<LoopAnalysis>(F);
1640 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1641 auto GetTTI = [&AM](Function &F) -> TargetTransformInfo & {
1642 return AM.getResult<TargetIRAnalysis>(F);
1643 };
1644 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
1645 if (!Impl.run(F))
1646 return PreservedAnalyses::all();
1649 return PA;
1650}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static const T * Find(StringRef S, ArrayRef< T > A)
Find KV in array using binary search.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
OptimizedStructLayoutField Field
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static cl::opt< bool > DisableSeparateConstOffsetFromGEP("disable-separate-const-offset-from-gep", cl::init(false), cl::desc("Do not separate the constant offset from a GEP instruction"), cl::Hidden)
static bool allowsPreservingNUW(const User *U)
A helper function to check if reassociating through an entry in the user chain would invalidate the G...
static cl::opt< bool > VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false), cl::desc("Verify this pass produces no dead code"), cl::Hidden)
static bool canReorderAddSextToGEP(const Use *Idx, const BinaryOperator *Add, const DataLayout &DL)
static BasicBlock::iterator getIndexInsertionPoint(const Use &Idx)
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
unsigned logBase2() const
Definition APInt.h:1781
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isNegative() const
Definition Constants.h:214
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Definition DataLayout.h:509
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GEPNoWrapFlags none()
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0, Instruction *I=nullptr, int64_t ScalableOffset=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
This class represents a truncation of integer types.
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Use * op_iterator
Definition User.h:254
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:526
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
LLVM_ABI void initializeSeparateConstOffsetFromGEPLegacyPassPass(PassRegistry &)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:406
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
@ Add
Sum of integers.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
#define N