LLVM 23.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"
167#include <cassert>
168#include <cstdint>
169#include <string>
170
171using namespace llvm;
172using namespace llvm::PatternMatch;
173
175 "disable-separate-const-offset-from-gep", cl::init(false),
176 cl::desc("Do not separate the constant offset from a GEP instruction"),
177 cl::Hidden);
178
179// Setting this flag may emit false positives when the input module already
180// contains dead instructions. Therefore, we set it only in unit tests that are
181// free of dead code.
182static cl::opt<bool>
183 VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
184 cl::desc("Verify this pass produces no dead code"),
185 cl::Hidden);
186
187namespace {
188
189/// A helper class for separating a constant offset from a GEP index.
190///
191/// In real programs, a GEP index may be more complicated than a simple addition
192/// of something and a constant integer which can be trivially splitted. For
193/// example, to split ((a << 3) | 5) + b, we need to search deeper for the
194/// constant offset, so that we can separate the index to (a << 3) + b and 5.
195///
196/// Therefore, this class looks into the expression that computes a given GEP
197/// index, and tries to find a constant integer that can be hoisted to the
198/// outermost level of the expression as an addition. Not every constant in an
199/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
200/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
201/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
202class ConstantOffsetExtractor {
203public:
204 /// Extracts a constant offset from the given GEP index. It returns the
205 /// new index representing the remainder (equal to the original index minus
206 /// the constant offset), or nullptr if we cannot extract a constant offset.
207 /// \p Idx The given GEP index
208 /// \p GEP The given GEP
209 /// \p UserChainTail Outputs the tail of UserChain so that we can
210 /// garbage-collect unused instructions in UserChain.
211 /// \p PreservesNUW Outputs whether the extraction allows preserving the
212 /// GEP's nuw flag, if it has one.
213 static Value *Extract(Value *Idx, GetElementPtrInst *GEP,
214 User *&UserChainTail, bool &PreservesNUW);
215
216 /// Looks for a constant offset from the given GEP index without extracting
217 /// it. It returns the numeric value of the extracted constant offset (0 if
218 /// failed). The meaning of the arguments are the same as Extract.
219 static APInt Find(Value *Idx, GetElementPtrInst *GEP);
220
221private:
222 ConstantOffsetExtractor(BasicBlock::iterator InsertionPt)
223 : IP(InsertionPt), DL(InsertionPt->getDataLayout()) {}
224
225 /// Searches the expression that computes V for a non-zero constant C s.t.
226 /// V can be reassociated into the form V' + C. If the searching is
227 /// successful, returns C and update UserChain as a def-use chain from C to V;
228 /// otherwise, UserChain is empty.
229 ///
230 /// \p V The given expression
231 /// \p SignExtended Whether V will be sign-extended in the computation of the
232 /// GEP index
233 /// \p ZeroExtended Whether V will be zero-extended in the computation of the
234 /// GEP index
235 /// \p NonNegative Whether V is guaranteed to be non-negative. For example,
236 /// an index of an inbounds GEP is guaranteed to be
237 /// non-negative. Levaraging this, we can better split
238 /// inbounds GEPs.
239 APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
240
241 /// A helper function to look into both operands of a binary operator.
242 APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
243 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 NonNegative Whether BO is known to be non-negative, e.g., an in-bound
294 /// array index.
295 bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
296 bool NonNegative);
297
298 /// Analyze XOR instruction to extract disjoint constant bits that behave
299 /// like addition operations for improved address mode folding.
300 APInt extractDisjointBitsFromXor(BinaryOperator *XorInst);
301
302 /// The path from the constant offset to the old GEP index. e.g., if the GEP
303 /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
304 /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
305 /// UserChain[2] will be the entire expression "a * b + (c + 5)".
306 ///
307 /// This path helps to rebuild the new GEP index.
308 SmallVector<User *, 8> UserChain;
309
310 /// A data structure used in rebuildWithoutConstOffset. Contains all
311 /// sext/zext/trunc instructions along UserChain.
313
314 /// Insertion position of cloned instructions.
316
317 const DataLayout &DL;
318};
319
320/// A pass that tries to split every GEP in the function into a variadic
321/// base and a constant offset. It is a FunctionPass because searching for the
322/// constant offset may inspect other basic blocks.
323class SeparateConstOffsetFromGEPLegacyPass : public FunctionPass {
324public:
325 static char ID;
326
327 SeparateConstOffsetFromGEPLegacyPass(bool LowerGEP = false)
328 : FunctionPass(ID), LowerGEP(LowerGEP) {
331 }
332
333 void getAnalysisUsage(AnalysisUsage &AU) const override {
334 AU.addRequired<DominatorTreeWrapperPass>();
335 AU.addRequired<TargetTransformInfoWrapperPass>();
336 AU.addRequired<LoopInfoWrapperPass>();
337 AU.setPreservesCFG();
338 AU.addRequired<TargetLibraryInfoWrapperPass>();
339 }
340
341 bool runOnFunction(Function &F) override;
342
343private:
344 bool LowerGEP;
345};
346
347/// A pass that tries to split every GEP in the function into a variadic
348/// base and a constant offset. It is a FunctionPass because searching for the
349/// constant offset may inspect other basic blocks.
350class SeparateConstOffsetFromGEP {
351public:
352 SeparateConstOffsetFromGEP(
353 DominatorTree *DT, LoopInfo *LI, TargetLibraryInfo *TLI,
354 function_ref<TargetTransformInfo &(Function &)> GetTTI, bool LowerGEP)
355 : DT(DT), LI(LI), TLI(TLI), GetTTI(GetTTI), LowerGEP(LowerGEP) {}
356
357 bool run(Function &F);
358
359private:
360 /// Track the operands of an add or sub.
361 using ExprKey = std::pair<Value *, Value *>;
362
363 /// Create a pair for use as a map key for a commutable operation.
364 static ExprKey createNormalizedCommutablePair(Value *A, Value *B) {
365 if (A < B)
366 return {A, B};
367 return {B, A};
368 }
369
370 /// Tries to split the given GEP into a variadic base and a constant offset,
371 /// and returns true if the splitting succeeds.
372 bool splitGEP(GetElementPtrInst *GEP);
373
374 /// Tries to reorder the given GEP with the GEP that produces the base if
375 /// doing so results in producing a constant offset as the outermost
376 /// index.
377 bool reorderGEP(GetElementPtrInst *GEP, TargetTransformInfo &TTI);
378
379 /// Lower a GEP with multiple indices into multiple GEPs with a single index.
380 /// Function splitGEP already split the original GEP into a variadic part and
381 /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
382 /// variadic part into a set of GEPs with a single index and applies
383 /// AccumulativeByteOffset to it.
384 /// \p Variadic The variadic part of the original GEP.
385 /// \p AccumulativeByteOffset The constant offset.
386 void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
387 const APInt &AccumulativeByteOffset);
388
389 /// Finds the constant offset within each index and accumulates them. If
390 /// LowerGEP is true, it finds in indices of both sequential and structure
391 /// types, otherwise it only finds in sequential indices. The output
392 /// NeedsExtraction indicates whether we successfully find a non-zero constant
393 /// offset.
394 APInt accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
395
396 /// Canonicalize array indices to pointer-size integers. This helps to
397 /// simplify the logic of splitting a GEP. For example, if a + b is a
398 /// pointer-size integer, we have
399 /// gep base, a + b = gep (gep base, a), b
400 /// However, this equality may not hold if the size of a + b is smaller than
401 /// the pointer size, because LLVM conceptually sign-extends GEP indices to
402 /// pointer size before computing the address
403 /// (http://llvm.org/docs/LangRef.html#id181).
404 ///
405 /// This canonicalization is very likely already done in clang and
406 /// instcombine. Therefore, the program will probably remain the same.
407 ///
408 /// Returns true if the module changes.
409 ///
410 /// Verified in @i32_add in split-gep.ll
411 bool canonicalizeArrayIndicesToIndexSize(GetElementPtrInst *GEP);
412
413 /// Optimize sext(a)+sext(b) to sext(a+b) when a+b can't sign overflow.
414 /// SeparateConstOffsetFromGEP distributes a sext to leaves before extracting
415 /// the constant offset. After extraction, it becomes desirable to reunion the
416 /// distributed sexts. For example,
417 ///
418 /// &a[sext(i +nsw (j +nsw 5)]
419 /// => distribute &a[sext(i) +nsw (sext(j) +nsw 5)]
420 /// => constant extraction &a[sext(i) + sext(j)] + 5
421 /// => reunion &a[sext(i +nsw j)] + 5
422 bool reuniteExts(Function &F);
423
424 /// A helper that reunites sexts in an instruction.
425 bool reuniteExts(Instruction *I);
426
427 /// Find the closest dominator of <Dominatee> that is equivalent to <Key>.
428 Instruction *findClosestMatchingDominator(
429 ExprKey Key, Instruction *Dominatee,
430 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs);
431
432 /// Verify F is free of dead code.
433 void verifyNoDeadCode(Function &F);
434
435 bool hasMoreThanOneUseInLoop(Value *v, Loop *L);
436
437 // Swap the index operand of two GEP.
438 void swapGEPOperand(GetElementPtrInst *First, GetElementPtrInst *Second);
439
440 // Check if it is safe to swap operand of two GEP.
441 bool isLegalToSwapOperand(GetElementPtrInst *First, GetElementPtrInst *Second,
442 Loop *CurLoop);
443
444 const DataLayout *DL = nullptr;
445 DominatorTree *DT = nullptr;
446 LoopInfo *LI;
447 TargetLibraryInfo *TLI;
448 // Retrieved lazily since not always used.
449 function_ref<TargetTransformInfo &(Function &)> GetTTI;
450
451 /// Whether to lower a GEP with multiple indices into arithmetic operations or
452 /// multiple GEPs with a single index.
453 bool LowerGEP;
454
455 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingAdds;
456 DenseMap<ExprKey, SmallVector<Instruction *, 2>> DominatingSubs;
457};
458
459} // end anonymous namespace
460
461char SeparateConstOffsetFromGEPLegacyPass::ID = 0;
462
464 SeparateConstOffsetFromGEPLegacyPass, "separate-const-offset-from-gep",
465 "Split GEPs to a variadic base and a constant offset for better CSE", false,
466 false)
473 SeparateConstOffsetFromGEPLegacyPass, "separate-const-offset-from-gep",
474 "Split GEPs to a variadic base and a constant offset for better CSE", false,
475 false)
476
478 return new SeparateConstOffsetFromGEPLegacyPass(LowerGEP);
479}
480
481bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
482 bool ZeroExtended,
483 BinaryOperator *BO,
484 bool NonNegative) {
485 // We only consider ADD, SUB and OR, because a non-zero constant found in
486 // expressions composed of these operations can be easily hoisted as a
487 // constant offset by reassociation.
488 if (BO->getOpcode() != Instruction::Add &&
489 BO->getOpcode() != Instruction::Sub &&
490 BO->getOpcode() != Instruction::Or) {
491 return false;
492 }
493
494 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
495 // Do not trace into "or" unless it is equivalent to "add nuw nsw".
496 // This is the case if the or's disjoint flag is set.
497 if (BO->getOpcode() == Instruction::Or &&
498 !cast<PossiblyDisjointInst>(BO)->isDisjoint())
499 return false;
500
501 // FIXME: We don't currently support constants from the RHS of subs,
502 // when we are zero-extended, because we need a way to zero-extended
503 // them before they are negated.
504 if (ZeroExtended && !SignExtended && BO->getOpcode() == Instruction::Sub)
505 return false;
506
507 // In addition, tracing into BO requires that its surrounding sext/zext/trunc
508 // (if any) is distributable to both operands.
509 //
510 // Suppose BO = A op B.
511 // SignExtended | ZeroExtended | Distributable?
512 // --------------+--------------+----------------------------------
513 // 0 | 0 | true because no s/zext exists
514 // 0 | 1 | zext(BO) == zext(A) op zext(B)
515 // 1 | 0 | sext(BO) == sext(A) op sext(B)
516 // 1 | 1 | zext(sext(BO)) ==
517 // | | zext(sext(A)) op zext(sext(B))
518 if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
519 // If a + b >= 0 and (a >= 0 or b >= 0), then
520 // sext(a + b) = sext(a) + sext(b)
521 // even if the addition is not marked nsw.
522 //
523 // Leveraging this invariant, we can trace into an sext'ed inbound GEP
524 // index if the constant offset is non-negative.
525 //
526 // Verified in @sext_add in split-gep.ll.
527 if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
528 if (!ConstLHS->isNegative())
529 return true;
530 }
531 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
532 if (!ConstRHS->isNegative())
533 return true;
534 }
535 }
536
537 // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
538 // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
539 if (BO->getOpcode() == Instruction::Add ||
540 BO->getOpcode() == Instruction::Sub) {
541 if (SignExtended && !BO->hasNoSignedWrap())
542 return false;
543 if (ZeroExtended && !BO->hasNoUnsignedWrap())
544 return false;
545 }
546
547 return true;
548}
549
550APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
551 bool SignExtended,
552 bool ZeroExtended) {
553 // Save off the current height of the chain, in case we need to restore it.
554 size_t ChainLength = UserChain.size();
555
556 // BO being non-negative does not shed light on whether its operands are
557 // non-negative. Clear the NonNegative flag here.
558 APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
559 /* NonNegative */ false);
560 // If we found a constant offset in the left operand, stop and return that.
561 // This shortcut might cause us to miss opportunities of combining the
562 // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
563 // However, such cases are probably already handled by -instcombine,
564 // given this pass runs after the standard optimizations.
565 if (ConstantOffset != 0) return ConstantOffset;
566
567 // Reset the chain back to where it was when we started exploring this node,
568 // since visiting the LHS didn't pan out.
569 UserChain.resize(ChainLength);
570
571 ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
572 /* NonNegative */ false);
573 // If U is a sub operator, negate the constant offset found in the right
574 // operand.
575 if (BO->getOpcode() == Instruction::Sub)
576 ConstantOffset = -ConstantOffset;
577
578 // If RHS wasn't a suitable candidate either, reset the chain again.
579 if (ConstantOffset == 0)
580 UserChain.resize(ChainLength);
581
582 return ConstantOffset;
583}
584
585APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
586 bool ZeroExtended, bool NonNegative) {
587 // TODO(jingyue): We could trace into integer/pointer casts, such as
588 // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
589 // integers because it gives good enough results for our benchmarks.
590 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
591
592 // We cannot do much with Values that are not a User, such as an Argument.
593 User *U = dyn_cast<User>(V);
594 if (U == nullptr) return APInt(BitWidth, 0);
595
596 APInt ConstantOffset(BitWidth, 0);
597 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
598 // Hooray, we found it!
599 ConstantOffset = CI->getValue();
600 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
601 // Trace into subexpressions for more hoisting opportunities.
602 if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative))
603 ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
604 // Handle XOR with disjoint bits that can be treated as addition.
605 else if (BO->getOpcode() == Instruction::Xor)
606 ConstantOffset = extractDisjointBitsFromXor(BO);
607 } else if (isa<TruncInst>(V)) {
608 ConstantOffset =
609 find(U->getOperand(0), SignExtended, ZeroExtended, NonNegative)
610 .trunc(BitWidth);
611 } else if (isa<SExtInst>(V)) {
612 ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
613 ZeroExtended, NonNegative).sext(BitWidth);
614 } else if (isa<ZExtInst>(V)) {
615 // As an optimization, we can clear the SignExtended flag because
616 // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
617 //
618 // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
619 ConstantOffset =
620 find(U->getOperand(0), /* SignExtended */ false,
621 /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
622 }
623
624 // If we found a non-zero constant offset, add it to the path for
625 // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
626 // help this optimization.
627 if (ConstantOffset != 0)
628 UserChain.push_back(U);
629 return ConstantOffset;
630}
631
632Value *ConstantOffsetExtractor::applyCasts(Value *V) {
633 Value *Current = V;
634 // CastInsts is built in the use-def order. Therefore, we apply them to V
635 // in the reversed order.
636 for (CastInst *I : llvm::reverse(CastInsts)) {
637 if (Constant *C = dyn_cast<Constant>(Current)) {
638 // Try to constant fold the cast.
639 Current = ConstantFoldCastOperand(I->getOpcode(), C, I->getType(), DL);
640 if (Current)
641 continue;
642 }
643
644 Instruction *Cast = I->clone();
645 Cast->setOperand(0, Current);
646 // In ConstantOffsetExtractor::find we do not analyze nuw/nsw for trunc, so
647 // we assume that it is ok to redistribute trunc over add/sub/or. But for
648 // example (add (trunc nuw A), (trunc nuw B)) is more poisonous than (trunc
649 // nuw (add A, B))). To make such redistributions legal we drop all the
650 // poison generating flags from cloned trunc instructions here.
651 if (isa<TruncInst>(Cast))
653 Cast->insertBefore(*IP->getParent(), IP);
654 Current = Cast;
655 }
656 return Current;
657}
658
659Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
660 distributeCastsAndCloneChain(UserChain.size() - 1);
661 // Remove all nullptrs (used to be sext/zext/trunc) from UserChain.
662 unsigned NewSize = 0;
663 for (User *I : UserChain) {
664 if (I != nullptr) {
665 UserChain[NewSize] = I;
666 NewSize++;
667 }
668 }
669 UserChain.resize(NewSize);
670 return removeConstOffset(UserChain.size() - 1);
671}
672
673Value *
674ConstantOffsetExtractor::distributeCastsAndCloneChain(unsigned ChainIndex) {
675 User *U = UserChain[ChainIndex];
676 if (ChainIndex == 0) {
678 // If U is a ConstantInt, applyCasts will return a ConstantInt as well.
679 return UserChain[ChainIndex] = cast<ConstantInt>(applyCasts(U));
680 }
681
682 if (CastInst *Cast = dyn_cast<CastInst>(U)) {
683 assert(
684 (isa<SExtInst>(Cast) || isa<ZExtInst>(Cast) || isa<TruncInst>(Cast)) &&
685 "Only following instructions can be traced: sext, zext & trunc");
686 CastInsts.push_back(Cast);
687 UserChain[ChainIndex] = nullptr;
688 return distributeCastsAndCloneChain(ChainIndex - 1);
689 }
690
691 // Function find only trace into BinaryOperator and CastInst.
692 BinaryOperator *BO = cast<BinaryOperator>(U);
693 // OpNo = which operand of BO is UserChain[ChainIndex - 1]
694 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
695 Value *TheOther = applyCasts(BO->getOperand(1 - OpNo));
696 Value *NextInChain = distributeCastsAndCloneChain(ChainIndex - 1);
697
698 BinaryOperator *NewBO = nullptr;
699 if (OpNo == 0) {
700 NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
701 BO->getName(), IP);
702 } else {
703 NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
704 BO->getName(), IP);
705 }
706 return UserChain[ChainIndex] = NewBO;
707}
708
709Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
710 if (ChainIndex == 0) {
711 assert(isa<ConstantInt>(UserChain[ChainIndex]));
712 return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
713 }
714
715 BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
716 assert((BO->use_empty() || BO->hasOneUse()) &&
717 "distributeCastsAndCloneChain clones each BinaryOperator in "
718 "UserChain, so no one should be used more than "
719 "once");
720
721 unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
722 assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
723 Value *NextInChain = removeConstOffset(ChainIndex - 1);
724 Value *TheOther = BO->getOperand(1 - OpNo);
725
726 if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
727 if (CI->isZero()) {
728 // Custom XOR handling for disjoint bits - preserves original XOR
729 // with non-disjoint constant bits.
730 // TODO: The design should be updated to support partial constant
731 // extraction.
732 if (BO->getOpcode() == Instruction::Xor)
733 return BO;
734
735 // If NextInChain is 0 and not the LHS of a sub, we can simplify the
736 // sub-expression to be just TheOther.
737 if (!(BO->getOpcode() == Instruction::Sub && OpNo == 0))
738 return TheOther;
739 }
740 }
741
742 BinaryOperator::BinaryOps NewOp = BO->getOpcode();
743 if (BO->getOpcode() == Instruction::Or) {
744 // Rebuild "or" as "add", because "or" may be invalid for the new
745 // expression.
746 //
747 // For instance, given
748 // a | (b + 5) where a and b + 5 have no common bits,
749 // we can extract 5 as the constant offset.
750 //
751 // However, reusing the "or" in the new index would give us
752 // (a | b) + 5
753 // which does not equal a | (b + 5).
754 //
755 // Replacing the "or" with "add" is fine, because
756 // a | (b + 5) = a + (b + 5) = (a + b) + 5
757 NewOp = Instruction::Add;
758 }
759
760 BinaryOperator *NewBO;
761 if (OpNo == 0) {
762 NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
763 } else {
764 NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
765 }
766 NewBO->takeName(BO);
767 return NewBO;
768}
769
770/// Analyze XOR instruction to extract disjoint constant bits for address
771/// folding
772///
773/// This function identifies bits in an XOR constant operand that are disjoint
774/// from the base operand's known set bits. For these disjoint bits, XOR behaves
775/// identically to addition, allowing us to extract them as constant offsets
776/// that can be folded into addressing modes.
777///
778/// Transformation: `Base ^ Const` becomes `(Base ^ NonDisjointBits) +
779/// DisjointBits` where DisjointBits = Const & KnownZeros(Base)
780///
781/// Example with ptr having known-zero low bit:
782/// Original: `xor %ptr, 3` ; 3 = 0b11
783/// Analysis: DisjointBits = 3 & KnownZeros(%ptr) = 0b11 & 0b01 = 0b01
784/// Result: `(xor %ptr, 2) + 1` where 1 can be folded into address mode
785///
786/// \param XorInst The XOR binary operator to analyze
787/// \return APInt containing the disjoint bits that can be extracted as offset,
788/// or zero if no disjoint bits exist
789APInt ConstantOffsetExtractor::extractDisjointBitsFromXor(
790 BinaryOperator *XorInst) {
791 assert(XorInst && XorInst->getOpcode() == Instruction::Xor &&
792 "Expected XOR instruction");
793
794 const unsigned BitWidth = XorInst->getType()->getScalarSizeInBits();
795 Value *BaseOperand;
796 ConstantInt *XorConstant;
797
798 // Match pattern: xor BaseOperand, Constant.
799 if (!match(XorInst, m_Xor(m_Value(BaseOperand), m_ConstantInt(XorConstant))))
800 return APInt::getZero(BitWidth);
801
802 // Compute known bits for the base operand.
803 const SimplifyQuery SQ(DL);
804 const KnownBits BaseKnownBits = computeKnownBits(BaseOperand, SQ);
805 const APInt &ConstantValue = XorConstant->getValue();
806
807 // Identify disjoint bits: constant bits that are known zero in base.
808 const APInt DisjointBits = ConstantValue & BaseKnownBits.Zero;
809
810 // Early exit if no disjoint bits found.
811 if (DisjointBits.isZero())
812 return APInt::getZero(BitWidth);
813
814 // Compute the remaining non-disjoint bits that stay in the XOR.
815 const APInt NonDisjointBits = ConstantValue & ~DisjointBits;
816
817 // FIXME: Enhance XOR constant extraction to handle nested binary operations.
818 // Currently we only extract disjoint bits from the immediate XOR constant,
819 // but we could recursively process cases like:
820 // xor (add %base, C1), C2 -> add %base, (C1 ^ disjoint_bits(C2))
821 // This requires careful analysis to ensure the transformation preserves
822 // semantics, particularly around sign extension and overflow behavior.
823
824 // Add the non-disjoint constant to the user chain for later transformation
825 // This will replace the original constant in the XOR with the new
826 // constant.
827 UserChain.push_back(ConstantInt::get(XorInst->getType(), NonDisjointBits));
828 return DisjointBits;
829}
830
831/// A helper function to check if reassociating through an entry in the user
832/// chain would invalidate the GEP's nuw flag.
833static bool allowsPreservingNUW(const User *U) {
834 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
835 // Binary operations need to be effectively add nuw.
836 auto Opcode = BO->getOpcode();
837 if (Opcode == BinaryOperator::Or) {
838 // Ors are only considered here if they are disjoint. The addition that
839 // they represent in this case is NUW.
840 assert(cast<PossiblyDisjointInst>(BO)->isDisjoint());
841 return true;
842 }
843 return Opcode == BinaryOperator::Add && BO->hasNoUnsignedWrap();
844 }
845 // UserChain can only contain ConstantInt, CastInst, or BinaryOperator.
846 // Among the possible CastInsts, only trunc without nuw is a problem: If it
847 // is distributed through an add nuw, wrapping may occur:
848 // "add nuw trunc(a), trunc(b)" is more poisonous than "trunc(add nuw a, b)"
849 if (const TruncInst *TI = dyn_cast<TruncInst>(U))
850 return TI->hasNoUnsignedWrap();
851 assert((isa<CastInst>(U) || isa<ConstantInt>(U)) && "Unexpected User.");
852 return true;
853}
854
855Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
856 User *&UserChainTail,
857 bool &PreservesNUW) {
858 ConstantOffsetExtractor Extractor(GEP->getIterator());
859 // Find a non-zero constant offset first.
860 APInt ConstantOffset =
861 Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
862 GEP->isInBounds());
863 if (ConstantOffset == 0) {
864 UserChainTail = nullptr;
865 PreservesNUW = true;
866 return nullptr;
867 }
868
869 PreservesNUW = all_of(Extractor.UserChain, allowsPreservingNUW);
870
871 // Separates the constant offset from the GEP index.
872 Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
873 UserChainTail = Extractor.UserChain.back();
874 return IdxWithoutConstOffset;
875}
876
877APInt ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP) {
878 // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
879 return ConstantOffsetExtractor(GEP->getIterator())
880 .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
881 GEP->isInBounds());
882}
883
884bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToIndexSize(
885 GetElementPtrInst *GEP) {
886 bool Changed = false;
887 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
889 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
890 I != E; ++I, ++GTI) {
891 // Skip struct member indices which must be i32.
892 if (GTI.isSequential()) {
893 if ((*I)->getType() != PtrIdxTy) {
894 *I = CastInst::CreateIntegerCast(*I, PtrIdxTy, true, "idxprom",
895 GEP->getIterator());
896 Changed = true;
897 }
898 }
899 }
900 return Changed;
901}
902
903APInt SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
904 bool &NeedsExtraction) {
905 NeedsExtraction = false;
906 unsigned IdxWidth = DL->getIndexTypeSizeInBits(GEP->getType());
907 APInt AccumulativeByteOffset(IdxWidth, 0);
909 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
910 if (GTI.isSequential()) {
911 // Constant offsets of scalable types are not really constant.
912 if (GTI.getIndexedType()->isScalableTy())
913 continue;
914
915 // Tries to extract a constant offset from this GEP index.
916 APInt ConstantOffset =
917 ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP)
918 .sextOrTrunc(IdxWidth);
919 if (ConstantOffset != 0) {
920 NeedsExtraction = true;
921 // A GEP may have multiple indices. We accumulate the extracted
922 // constant offset to a byte offset, and later offset the remainder of
923 // the original GEP with this byte offset.
924 AccumulativeByteOffset +=
925 ConstantOffset * APInt(IdxWidth,
927 /*IsSigned=*/true, /*ImplicitTrunc=*/true);
928 }
929 } else if (LowerGEP) {
930 StructType *StTy = GTI.getStructType();
931 uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
932 // Skip field 0 as the offset is always 0.
933 if (Field != 0) {
934 NeedsExtraction = true;
935 AccumulativeByteOffset +=
936 APInt(IdxWidth, DL->getStructLayout(StTy)->getElementOffset(Field),
937 /*IsSigned=*/true, /*ImplicitTrunc=*/true);
938 }
939 }
940 }
941 return AccumulativeByteOffset;
942}
943
944void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
945 GetElementPtrInst *Variadic, const APInt &AccumulativeByteOffset) {
946 IRBuilder<> Builder(Variadic);
947 Type *PtrIndexTy = DL->getIndexType(Variadic->getType());
948
949 Value *ResultPtr = Variadic->getOperand(0);
950 Loop *L = LI->getLoopFor(Variadic->getParent());
951 // Check if the base is not loop invariant or used more than once.
952 bool isSwapCandidate =
953 L && L->isLoopInvariant(ResultPtr) &&
954 !hasMoreThanOneUseInLoop(ResultPtr, L);
955 Value *FirstResult = nullptr;
956
957 gep_type_iterator GTI = gep_type_begin(*Variadic);
958 // Create an ugly GEP for each sequential index. We don't create GEPs for
959 // structure indices, as they are accumulated in the constant offset index.
960 for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
961 if (GTI.isSequential()) {
962 Value *Idx = Variadic->getOperand(I);
963 // Skip zero indices.
964 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
965 if (CI->isZero())
966 continue;
967
968 APInt ElementSize = APInt(PtrIndexTy->getIntegerBitWidth(),
970 // Scale the index by element size.
971 if (ElementSize != 1) {
972 if (ElementSize.isPowerOf2()) {
973 Idx = Builder.CreateShl(
974 Idx, ConstantInt::get(PtrIndexTy, ElementSize.logBase2()));
975 } else {
976 Idx =
977 Builder.CreateMul(Idx, ConstantInt::get(PtrIndexTy, ElementSize));
978 }
979 }
980 // Create an ugly GEP with a single index for each index.
981 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Idx, "uglygep");
982 if (FirstResult == nullptr)
983 FirstResult = ResultPtr;
984 }
985 }
986
987 // Create a GEP with the constant offset index.
988 if (AccumulativeByteOffset != 0) {
989 Value *Offset = ConstantInt::get(PtrIndexTy, AccumulativeByteOffset);
990 ResultPtr = Builder.CreatePtrAdd(ResultPtr, Offset, "uglygep");
991 } else
992 isSwapCandidate = false;
993
994 // If we created a GEP with constant index, and the base is loop invariant,
995 // then we swap the first one with it, so LICM can move constant GEP out
996 // later.
997 auto *FirstGEP = dyn_cast_or_null<GetElementPtrInst>(FirstResult);
998 auto *SecondGEP = dyn_cast<GetElementPtrInst>(ResultPtr);
999 if (isSwapCandidate && isLegalToSwapOperand(FirstGEP, SecondGEP, L))
1000 swapGEPOperand(FirstGEP, SecondGEP);
1001
1002 Variadic->replaceAllUsesWith(ResultPtr);
1003 Variadic->eraseFromParent();
1004}
1005
1006bool SeparateConstOffsetFromGEP::reorderGEP(GetElementPtrInst *GEP,
1007 TargetTransformInfo &TTI) {
1008 auto PtrGEP = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());
1009 if (!PtrGEP)
1010 return false;
1011
1012 bool NestedNeedsExtraction;
1013 APInt NestedByteOffset = accumulateByteOffset(PtrGEP, NestedNeedsExtraction);
1014 if (!NestedNeedsExtraction)
1015 return false;
1016
1017 unsigned AddrSpace = PtrGEP->getPointerAddressSpace();
1018 if (!TTI.isLegalAddressingMode(GEP->getResultElementType(),
1019 /*BaseGV=*/nullptr,
1020 NestedByteOffset.getSExtValue(),
1021 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace))
1022 return false;
1023
1024 bool GEPInBounds = GEP->isInBounds();
1025 bool PtrGEPInBounds = PtrGEP->isInBounds();
1026 bool IsChainInBounds = GEPInBounds && PtrGEPInBounds;
1027 if (IsChainInBounds) {
1028 auto IsKnownNonNegative = [this](Value *V) {
1029 return isKnownNonNegative(V, *DL);
1030 };
1031 IsChainInBounds &= all_of(GEP->indices(), IsKnownNonNegative);
1032 if (IsChainInBounds)
1033 IsChainInBounds &= all_of(PtrGEP->indices(), IsKnownNonNegative);
1034 }
1035
1036 IRBuilder<> Builder(GEP);
1037 // For trivial GEP chains, we can swap the indices.
1038 Value *NewSrc = Builder.CreateGEP(
1039 GEP->getSourceElementType(), PtrGEP->getPointerOperand(),
1040 SmallVector<Value *, 4>(GEP->indices()), "", IsChainInBounds);
1041 Value *NewGEP = Builder.CreateGEP(PtrGEP->getSourceElementType(), NewSrc,
1042 SmallVector<Value *, 4>(PtrGEP->indices()),
1043 "", IsChainInBounds);
1044 GEP->replaceAllUsesWith(NewGEP);
1046 return true;
1047}
1048
1049bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
1050 // Skip vector GEPs.
1051 if (GEP->getType()->isVectorTy())
1052 return false;
1053
1054 // If the base of this GEP is a ptradd of a constant, lets pass the constant
1055 // along. This ensures that when we have a chain of GEPs the constant
1056 // offset from each is accumulated.
1057 Value *NewBase;
1058 const APInt *BaseOffset;
1059 const bool ExtractBase =
1060 match(GEP->getPointerOperand(),
1061 m_PtrAdd(m_Value(NewBase), m_APInt(BaseOffset)));
1062
1063 unsigned IdxWidth = DL->getIndexTypeSizeInBits(GEP->getType());
1064 const APInt BaseByteOffset =
1065 ExtractBase ? BaseOffset->sextOrTrunc(IdxWidth) : APInt(IdxWidth, 0);
1066
1067 // The backend can already nicely handle the case where all indices are
1068 // constant.
1069 if (GEP->hasAllConstantIndices() && !ExtractBase)
1070 return false;
1071
1072 bool Changed = canonicalizeArrayIndicesToIndexSize(GEP);
1073
1074 bool NeedsExtraction;
1075 APInt AccumulativeByteOffset =
1076 BaseByteOffset + accumulateByteOffset(GEP, NeedsExtraction);
1077
1078 TargetTransformInfo &TTI = GetTTI(*GEP->getFunction());
1079
1080 if (!NeedsExtraction && !ExtractBase) {
1081 Changed |= reorderGEP(GEP, TTI);
1082 return Changed;
1083 }
1084
1085 // If LowerGEP is disabled, before really splitting the GEP, check whether the
1086 // backend supports the addressing mode we are about to produce. If no, this
1087 // splitting probably won't be beneficial.
1088 // If LowerGEP is enabled, even the extracted constant offset can not match
1089 // the addressing mode, we can still do optimizations to other lowered parts
1090 // of variable indices. Therefore, we don't check for addressing modes in that
1091 // case.
1092 if (!LowerGEP) {
1093 unsigned AddrSpace = GEP->getPointerAddressSpace();
1095 GEP->getResultElementType(),
1096 /*BaseGV=*/nullptr, AccumulativeByteOffset.getSExtValue(),
1097 /*HasBaseReg=*/true, /*Scale=*/0, AddrSpace)) {
1098 return Changed;
1099 }
1100 }
1101
1102 // Track information for preserving GEP flags.
1103 bool AllOffsetsNonNegative = AccumulativeByteOffset.isNonNegative();
1104 bool AllNUWPreserved = GEP->hasNoUnsignedWrap();
1105 bool NewGEPInBounds = GEP->isInBounds();
1106 bool NewGEPNUSW = GEP->hasNoUnsignedSignedWrap();
1107
1108 // Remove the constant offset in each sequential index. The resultant GEP
1109 // computes the variadic base.
1110 // Notice that we don't remove struct field indices here. If LowerGEP is
1111 // disabled, a structure index is not accumulated and we still use the old
1112 // one. If LowerGEP is enabled, a structure index is accumulated in the
1113 // constant offset. LowerToSingleIndexGEPs will later handle the constant
1114 // offset and won't need a new structure index.
1116 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
1117 if (GTI.isSequential()) {
1118 // Constant offsets of scalable types are not really constant.
1119 if (GTI.getIndexedType()->isScalableTy())
1120 continue;
1121
1122 // Splits this GEP index into a variadic part and a constant offset, and
1123 // uses the variadic part as the new index.
1124 Value *Idx = GEP->getOperand(I);
1125 User *UserChainTail;
1126 bool PreservesNUW;
1127 Value *NewIdx = ConstantOffsetExtractor::Extract(Idx, GEP, UserChainTail,
1128 PreservesNUW);
1129 if (NewIdx != nullptr) {
1130 // Switches to the index with the constant offset removed.
1131 GEP->setOperand(I, NewIdx);
1132 // After switching to the new index, we can garbage-collect UserChain
1133 // and the old index if they are not used.
1136 Idx = NewIdx;
1137 AllNUWPreserved &= PreservesNUW;
1138 }
1139 AllOffsetsNonNegative =
1140 AllOffsetsNonNegative && isKnownNonNegative(Idx, *DL);
1141 }
1142 }
1143 if (ExtractBase) {
1144 GEPOperator *Base = cast<GEPOperator>(GEP->getPointerOperand());
1145 AllNUWPreserved &= Base->hasNoUnsignedWrap();
1146 NewGEPInBounds &= Base->isInBounds();
1147 NewGEPNUSW &= Base->hasNoUnsignedSignedWrap();
1148 AllOffsetsNonNegative &= BaseByteOffset.isNonNegative();
1149
1150 GEP->setOperand(0, NewBase);
1152 }
1153
1154 // Clear the inbounds attribute because the new index may be off-bound.
1155 // e.g.,
1156 //
1157 // b = add i64 a, 5
1158 // addr = gep inbounds float, float* p, i64 b
1159 //
1160 // is transformed to:
1161 //
1162 // addr2 = gep float, float* p, i64 a ; inbounds removed
1163 // addr = gep float, float* addr2, i64 5 ; inbounds removed
1164 //
1165 // If a is -4, although the old index b is in bounds, the new index a is
1166 // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
1167 // inbounds keyword is not present, the offsets are added to the base
1168 // address with silently-wrapping two's complement arithmetic".
1169 // Therefore, the final code will be a semantically equivalent.
1170 GEPNoWrapFlags NewGEPFlags = GEPNoWrapFlags::none();
1171
1172 // If the initial GEP was inbounds/nusw and all variable indices and the
1173 // accumulated offsets are non-negative, they can be added in any order and
1174 // the intermediate results are in bounds and don't overflow in a nusw sense.
1175 // So, we can preserve the inbounds/nusw flag for both GEPs.
1176 bool CanPreserveInBoundsNUSW = AllOffsetsNonNegative;
1177
1178 // If the initial GEP was NUW and all operations that we reassociate were NUW
1179 // additions, the resulting GEPs are also NUW.
1180 if (AllNUWPreserved) {
1181 NewGEPFlags |= GEPNoWrapFlags::noUnsignedWrap();
1182 // If the initial GEP additionally had NUSW (or inbounds, which implies
1183 // NUSW), we know that the indices in the initial GEP must all have their
1184 // signbit not set. For indices that are the result of NUW adds, the
1185 // add-operands therefore also don't have their signbit set. Therefore, all
1186 // indices of the resulting GEPs are non-negative -> we can preserve
1187 // the inbounds/nusw flag.
1188 CanPreserveInBoundsNUSW |= NewGEPNUSW;
1189 }
1190
1191 if (CanPreserveInBoundsNUSW) {
1192 if (NewGEPInBounds)
1193 NewGEPFlags |= GEPNoWrapFlags::inBounds();
1194 else if (NewGEPNUSW)
1195 NewGEPFlags |= GEPNoWrapFlags::noUnsignedSignedWrap();
1196 }
1197
1198 GEP->setNoWrapFlags(NewGEPFlags);
1199
1200 // Lowers a GEP to GEPs with a single index.
1201 if (LowerGEP) {
1202 lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
1203 return true;
1204 }
1205
1206 // No need to create another GEP if the accumulative byte offset is 0.
1207 if (AccumulativeByteOffset == 0)
1208 return true;
1209
1210 // Offsets the base with the accumulative byte offset.
1211 //
1212 // %gep ; the base
1213 // ... %gep ...
1214 //
1215 // => add the offset
1216 //
1217 // %gep2 ; clone of %gep
1218 // %new.gep = gep i8, %gep2, %offset
1219 // %gep ; will be removed
1220 // ... %gep ...
1221 //
1222 // => replace all uses of %gep with %new.gep and remove %gep
1223 //
1224 // %gep2 ; clone of %gep
1225 // %new.gep = gep i8, %gep2, %offset
1226 // ... %new.gep ...
1227 Instruction *NewGEP = GEP->clone();
1228 NewGEP->insertBefore(GEP->getIterator());
1229
1230 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
1231 IRBuilder<> Builder(GEP);
1232 NewGEP = cast<Instruction>(Builder.CreatePtrAdd(
1233 NewGEP, ConstantInt::get(PtrIdxTy, AccumulativeByteOffset),
1234 GEP->getName(), NewGEPFlags));
1235 NewGEP->copyMetadata(*GEP);
1236
1237 GEP->replaceAllUsesWith(NewGEP);
1238 GEP->eraseFromParent();
1239
1240 return true;
1241}
1242
1243bool SeparateConstOffsetFromGEPLegacyPass::runOnFunction(Function &F) {
1244 if (skipFunction(F))
1245 return false;
1246 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1247 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1248 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1249 auto GetTTI = [this](Function &F) -> TargetTransformInfo & {
1250 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1251 };
1252 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
1253 return Impl.run(F);
1254}
1255
1256bool SeparateConstOffsetFromGEP::run(Function &F) {
1258 return false;
1259
1260 DL = &F.getDataLayout();
1261 bool Changed = false;
1262
1263 ReversePostOrderTraversal<Function *> RPOT(&F);
1264 for (BasicBlock *B : RPOT) {
1265 if (!DT->isReachableFromEntry(B))
1266 continue;
1267
1268 for (Instruction &I : llvm::make_early_inc_range(*B))
1269 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I))
1270 Changed |= splitGEP(GEP);
1271 // No need to split GEP ConstantExprs because all its indices are constant
1272 // already.
1273 }
1274
1275 Changed |= reuniteExts(F);
1276
1277 if (VerifyNoDeadCode)
1278 verifyNoDeadCode(F);
1279
1280 return Changed;
1281}
1282
1283Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1284 ExprKey Key, Instruction *Dominatee,
1285 DenseMap<ExprKey, SmallVector<Instruction *, 2>> &DominatingExprs) {
1286 auto Pos = DominatingExprs.find(Key);
1287 if (Pos == DominatingExprs.end())
1288 return nullptr;
1289
1290 auto &Candidates = Pos->second;
1291 // Because we process the basic blocks in pre-order of the dominator tree, a
1292 // candidate that doesn't dominate the current instruction won't dominate any
1293 // future instruction either. Therefore, we pop it out of the stack. This
1294 // optimization makes the algorithm O(n).
1295 while (!Candidates.empty()) {
1296 Instruction *Candidate = Candidates.back();
1297 if (DT->dominates(Candidate, Dominatee))
1298 return Candidate;
1299 Candidates.pop_back();
1300 }
1301 return nullptr;
1302}
1303
1304bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1305 if (!I->getType()->isIntOrIntVectorTy())
1306 return false;
1307
1308 // Dom: LHS+RHS
1309 // I: sext(LHS)+sext(RHS)
1310 // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1311 // TODO: handle zext
1312 Value *LHS = nullptr, *RHS = nullptr;
1313 if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1314 if (LHS->getType() == RHS->getType()) {
1315 ExprKey Key = createNormalizedCommutablePair(LHS, RHS);
1316 if (auto *Dom = findClosestMatchingDominator(Key, I, DominatingAdds)) {
1317 Instruction *NewSExt =
1318 new SExtInst(Dom, I->getType(), "", I->getIterator());
1319 NewSExt->takeName(I);
1320 I->replaceAllUsesWith(NewSExt);
1321 NewSExt->setDebugLoc(I->getDebugLoc());
1323 return true;
1324 }
1325 }
1326 } else if (match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1327 if (LHS->getType() == RHS->getType()) {
1328 if (auto *Dom =
1329 findClosestMatchingDominator({LHS, RHS}, I, DominatingSubs)) {
1330 Instruction *NewSExt =
1331 new SExtInst(Dom, I->getType(), "", I->getIterator());
1332 NewSExt->takeName(I);
1333 I->replaceAllUsesWith(NewSExt);
1334 NewSExt->setDebugLoc(I->getDebugLoc());
1336 return true;
1337 }
1338 }
1339 }
1340
1341 // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
1342 if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS)))) {
1344 ExprKey Key = createNormalizedCommutablePair(LHS, RHS);
1345 DominatingAdds[Key].push_back(I);
1346 }
1347 } else if (match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
1349 DominatingSubs[{LHS, RHS}].push_back(I);
1350 }
1351 return false;
1352}
1353
1354bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1355 bool Changed = false;
1356 DominatingAdds.clear();
1357 DominatingSubs.clear();
1358 for (const auto Node : depth_first(DT)) {
1359 BasicBlock *BB = Node->getBlock();
1360 for (Instruction &I : llvm::make_early_inc_range(*BB))
1361 Changed |= reuniteExts(&I);
1362 }
1363 return Changed;
1364}
1365
1366void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
1367 for (BasicBlock &B : F) {
1368 for (Instruction &I : B) {
1370 std::string ErrMessage;
1371 raw_string_ostream RSO(ErrMessage);
1372 RSO << "Dead instruction detected!\n" << I << "\n";
1373 llvm_unreachable(RSO.str().c_str());
1374 }
1375 }
1376 }
1377}
1378
1379bool SeparateConstOffsetFromGEP::isLegalToSwapOperand(
1380 GetElementPtrInst *FirstGEP, GetElementPtrInst *SecondGEP, Loop *CurLoop) {
1381 if (!FirstGEP || !FirstGEP->hasOneUse())
1382 return false;
1383
1384 if (!SecondGEP || FirstGEP->getParent() != SecondGEP->getParent())
1385 return false;
1386
1387 if (FirstGEP == SecondGEP)
1388 return false;
1389
1390 unsigned FirstNum = FirstGEP->getNumOperands();
1391 unsigned SecondNum = SecondGEP->getNumOperands();
1392 // Give up if the number of operands are not 2.
1393 if (FirstNum != SecondNum || FirstNum != 2)
1394 return false;
1395
1396 Value *FirstBase = FirstGEP->getOperand(0);
1397 Value *SecondBase = SecondGEP->getOperand(0);
1398 Value *FirstOffset = FirstGEP->getOperand(1);
1399 // Give up if the index of the first GEP is loop invariant.
1400 if (CurLoop->isLoopInvariant(FirstOffset))
1401 return false;
1402
1403 // Give up if base doesn't have same type.
1404 if (FirstBase->getType() != SecondBase->getType())
1405 return false;
1406
1407 Instruction *FirstOffsetDef = dyn_cast<Instruction>(FirstOffset);
1408
1409 // Check if the second operand of first GEP has constant coefficient.
1410 // For an example, for the following code, we won't gain anything by
1411 // hoisting the second GEP out because the second GEP can be folded away.
1412 // %scevgep.sum.ur159 = add i64 %idxprom48.ur, 256
1413 // %67 = shl i64 %scevgep.sum.ur159, 2
1414 // %uglygep160 = getelementptr i8* %65, i64 %67
1415 // %uglygep161 = getelementptr i8* %uglygep160, i64 -1024
1416
1417 // Skip constant shift instruction which may be generated by Splitting GEPs.
1418 if (FirstOffsetDef && FirstOffsetDef->isShift() &&
1419 isa<ConstantInt>(FirstOffsetDef->getOperand(1)))
1420 FirstOffsetDef = dyn_cast<Instruction>(FirstOffsetDef->getOperand(0));
1421
1422 // Give up if FirstOffsetDef is an Add or Sub with constant.
1423 // Because it may not profitable at all due to constant folding.
1424 if (FirstOffsetDef)
1425 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FirstOffsetDef)) {
1426 unsigned opc = BO->getOpcode();
1427 if ((opc == Instruction::Add || opc == Instruction::Sub) &&
1428 (isa<ConstantInt>(BO->getOperand(0)) ||
1430 return false;
1431 }
1432 return true;
1433}
1434
1435bool SeparateConstOffsetFromGEP::hasMoreThanOneUseInLoop(Value *V, Loop *L) {
1436 // TODO: Could look at uses of globals, but we need to make sure we are
1437 // looking at the correct function.
1438 if (isa<Constant>(V))
1439 return false;
1440
1441 int UsesInLoop = 0;
1442 for (User *U : V->users()) {
1443 if (Instruction *User = dyn_cast<Instruction>(U))
1444 if (L->contains(User))
1445 if (++UsesInLoop > 1)
1446 return true;
1447 }
1448 return false;
1449}
1450
1451void SeparateConstOffsetFromGEP::swapGEPOperand(GetElementPtrInst *First,
1452 GetElementPtrInst *Second) {
1453 Value *Offset1 = First->getOperand(1);
1454 Value *Offset2 = Second->getOperand(1);
1455 First->setOperand(1, Offset2);
1456 Second->setOperand(1, Offset1);
1457
1458 // We changed p+o+c to p+c+o, p+c may not be inbound anymore.
1459 const DataLayout &DAL = First->getDataLayout();
1460 APInt Offset(DAL.getIndexSizeInBits(
1461 cast<PointerType>(First->getType())->getAddressSpace()),
1462 0);
1463 Value *NewBase =
1465 uint64_t ObjectSize;
1466 if (!getObjectSize(NewBase, ObjectSize, DAL, TLI) ||
1467 Offset.ugt(ObjectSize)) {
1468 // TODO(gep_nowrap): Make flag preservation more precise.
1469 First->setNoWrapFlags(GEPNoWrapFlags::none());
1471 } else
1472 First->setIsInBounds(true);
1473}
1474
1476 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1478 ->printPipeline(OS, MapClassName2PassName);
1479 OS << '<';
1480 if (LowerGEP)
1481 OS << "lower-gep";
1482 OS << '>';
1483}
1484
1487 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1488 auto *LI = &AM.getResult<LoopAnalysis>(F);
1489 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1490 auto GetTTI = [&AM](Function &F) -> TargetTransformInfo & {
1491 return AM.getResult<TargetIRAnalysis>(F);
1492 };
1493 SeparateConstOffsetFromGEP Impl(DT, LI, TLI, GetTTI, LowerGEP);
1494 if (!Impl.run(F))
1495 return PreservedAnalyses::all();
1498 return PA;
1499}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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)
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:1023
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:936
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1052
unsigned logBase2() const
Definition APInt.h:1770
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:996
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1571
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:270
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BinaryOps getOpcode() const
Definition InstrTypes.h:374
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.
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
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:498
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:321
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()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
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:569
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:596
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:61
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
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
Use * op_iterator
Definition User.h:280
void setOperand(unsigned i, Value *Val)
Definition User.h:238
Value * getOperand(unsigned i) const
Definition User.h:233
unsigned getNumOperands() const
Definition User.h:255
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
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:759
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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)
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
class_match< Value > 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.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
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.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1763
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:1737
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:533
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:632
LLVM_ABI void initializeSeparateConstOffsetFromGEPLegacyPassPass(PassRegistry &)
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:402
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:406
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
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...
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70