LLVM 17.0.0git
AggressiveInstCombine.cpp
Go to the documentation of this file.
1//===- AggressiveInstCombine.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// This file implements the aggressive expression pattern combiner classes.
10// Currently, it handles expression patterns for:
11// * Truncate instruction
12//
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/Statistic.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
33
34using namespace llvm;
35using namespace PatternMatch;
36
37#define DEBUG_TYPE "aggressive-instcombine"
38
39STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
40STATISTIC(NumGuardedRotates,
41 "Number of guarded rotates transformed into funnel shifts");
42STATISTIC(NumGuardedFunnelShifts,
43 "Number of guarded funnel shifts transformed into funnel shifts");
44STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
45
47 "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
48 cl::desc("Max number of instructions to scan for aggressive instcombine."));
49
50/// Match a pattern for a bitwise funnel/rotate operation that partially guards
51/// against undefined behavior by branching around the funnel-shift/rotation
52/// when the shift amount is 0.
54 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
55 return false;
56
57 // As with the one-use checks below, this is not strictly necessary, but we
58 // are being cautious to avoid potential perf regressions on targets that
59 // do not actually have a funnel/rotate instruction (where the funnel shift
60 // would be expanded back into math/shift/logic ops).
61 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
62 return false;
63
64 // Match V to funnel shift left/right and capture the source operands and
65 // shift amount.
66 auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
67 Value *&ShAmt) {
68 unsigned Width = V->getType()->getScalarSizeInBits();
69
70 // fshl(ShVal0, ShVal1, ShAmt)
71 // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
72 if (match(V, m_OneUse(m_c_Or(
73 m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
74 m_LShr(m_Value(ShVal1),
75 m_Sub(m_SpecificInt(Width), m_Deferred(ShAmt))))))) {
76 return Intrinsic::fshl;
77 }
78
79 // fshr(ShVal0, ShVal1, ShAmt)
80 // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
81 if (match(V,
83 m_Value(ShAmt))),
84 m_LShr(m_Value(ShVal1), m_Deferred(ShAmt)))))) {
85 return Intrinsic::fshr;
86 }
87
89 };
90
91 // One phi operand must be a funnel/rotate operation, and the other phi
92 // operand must be the source value of that funnel/rotate operation:
93 // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
94 // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
95 // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
96 PHINode &Phi = cast<PHINode>(I);
97 unsigned FunnelOp = 0, GuardOp = 1;
98 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
99 Value *ShVal0, *ShVal1, *ShAmt;
100 Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
101 if (IID == Intrinsic::not_intrinsic ||
102 (IID == Intrinsic::fshl && ShVal0 != P1) ||
103 (IID == Intrinsic::fshr && ShVal1 != P1)) {
104 IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
105 if (IID == Intrinsic::not_intrinsic ||
106 (IID == Intrinsic::fshl && ShVal0 != P0) ||
107 (IID == Intrinsic::fshr && ShVal1 != P0))
108 return false;
109 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
110 "Pattern must match funnel shift left or right");
111 std::swap(FunnelOp, GuardOp);
112 }
113
114 // The incoming block with our source operand must be the "guard" block.
115 // That must contain a cmp+branch to avoid the funnel/rotate when the shift
116 // amount is equal to 0. The other incoming block is the block with the
117 // funnel/rotate.
118 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
119 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
120 Instruction *TermI = GuardBB->getTerminator();
121
122 // Ensure that the shift values dominate each block.
123 if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
124 return false;
125
127 BasicBlock *PhiBB = Phi.getParent();
128 if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()),
129 m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
130 return false;
131
132 if (Pred != CmpInst::ICMP_EQ)
133 return false;
134
135 IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
136
137 if (ShVal0 == ShVal1)
138 ++NumGuardedRotates;
139 else
140 ++NumGuardedFunnelShifts;
141
142 // If this is not a rotate then the select was blocking poison from the
143 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
144 bool IsFshl = IID == Intrinsic::fshl;
145 if (ShVal0 != ShVal1) {
146 if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
147 ShVal1 = Builder.CreateFreeze(ShVal1);
148 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
149 ShVal0 = Builder.CreateFreeze(ShVal0);
150 }
151
152 // We matched a variation of this IR pattern:
153 // GuardBB:
154 // %cmp = icmp eq i32 %ShAmt, 0
155 // br i1 %cmp, label %PhiBB, label %FunnelBB
156 // FunnelBB:
157 // %sub = sub i32 32, %ShAmt
158 // %shr = lshr i32 %ShVal1, %sub
159 // %shl = shl i32 %ShVal0, %ShAmt
160 // %fsh = or i32 %shr, %shl
161 // br label %PhiBB
162 // PhiBB:
163 // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
164 // -->
165 // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
167 Phi.replaceAllUsesWith(Builder.CreateCall(F, {ShVal0, ShVal1, ShAmt}));
168 return true;
169}
170
171/// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
172/// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
173/// of 'and' ops, then we also need to capture the fact that we saw an
174/// "and X, 1", so that's an extra return value for that case.
175struct MaskOps {
176 Value *Root = nullptr;
179 bool FoundAnd1 = false;
180
181 MaskOps(unsigned BitWidth, bool MatchAnds)
182 : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
183};
184
185/// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
186/// chain of 'and' or 'or' instructions looking for shift ops of a common source
187/// value. Examples:
188/// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
189/// returns { X, 0x129 }
190/// and (and (X >> 1), 1), (X >> 4)
191/// returns { X, 0x12 }
192static bool matchAndOrChain(Value *V, MaskOps &MOps) {
193 Value *Op0, *Op1;
194 if (MOps.MatchAndChain) {
195 // Recurse through a chain of 'and' operands. This requires an extra check
196 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
197 // in the chain to know that all of the high bits are cleared.
198 if (match(V, m_And(m_Value(Op0), m_One()))) {
199 MOps.FoundAnd1 = true;
200 return matchAndOrChain(Op0, MOps);
201 }
202 if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
203 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
204 } else {
205 // Recurse through a chain of 'or' operands.
206 if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
207 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
208 }
209
210 // We need a shift-right or a bare value representing a compare of bit 0 of
211 // the original source operand.
212 Value *Candidate;
213 const APInt *BitIndex = nullptr;
214 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
215 Candidate = V;
216
217 // Initialize result source operand.
218 if (!MOps.Root)
219 MOps.Root = Candidate;
220
221 // The shift constant is out-of-range? This code hasn't been simplified.
222 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
223 return false;
224
225 // Fill in the mask bit derived from the shift constant.
226 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
227 return MOps.Root == Candidate;
228}
229
230/// Match patterns that correspond to "any-bits-set" and "all-bits-set".
231/// These will include a chain of 'or' or 'and'-shifted bits from a
232/// common source value:
233/// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
234/// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
235/// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
236/// that differ only with a final 'not' of the result. We expect that final
237/// 'not' to be folded with the compare that we create here (invert predicate).
239 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
240 // final "and X, 1" instruction must be the final op in the sequence.
241 bool MatchAllBitsSet;
243 MatchAllBitsSet = true;
244 else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One())))
245 MatchAllBitsSet = false;
246 else
247 return false;
248
249 MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet);
250 if (MatchAllBitsSet) {
251 if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1)
252 return false;
253 } else {
254 if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps))
255 return false;
256 }
257
258 // The pattern was found. Create a masked compare that replaces all of the
259 // shift and logic ops.
261 Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask);
262 Value *And = Builder.CreateAnd(MOps.Root, Mask);
263 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
264 : Builder.CreateIsNotNull(And);
265 Value *Zext = Builder.CreateZExt(Cmp, I.getType());
266 I.replaceAllUsesWith(Zext);
267 ++NumAnyOrAllBitsSet;
268 return true;
269}
270
271// Try to recognize below function as popcount intrinsic.
272// This is the "best" algorithm from
273// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
274// Also used in TargetLowering::expandCTPOP().
275//
276// int popcount(unsigned int i) {
277// i = i - ((i >> 1) & 0x55555555);
278// i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
279// i = ((i + (i >> 4)) & 0x0F0F0F0F);
280// return (i * 0x01010101) >> 24;
281// }
283 if (I.getOpcode() != Instruction::LShr)
284 return false;
285
286 Type *Ty = I.getType();
287 if (!Ty->isIntOrIntVectorTy())
288 return false;
289
290 unsigned Len = Ty->getScalarSizeInBits();
291 // FIXME: fix Len == 8 and other irregular type lengths.
292 if (!(Len <= 128 && Len > 8 && Len % 8 == 0))
293 return false;
294
295 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
296 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
297 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
298 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
299 APInt MaskShift = APInt(Len, Len - 8);
300
301 Value *Op0 = I.getOperand(0);
302 Value *Op1 = I.getOperand(1);
303 Value *MulOp0;
304 // Matching "(i * 0x01010101...) >> 24".
305 if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) &&
306 match(Op1, m_SpecificInt(MaskShift))) {
307 Value *ShiftOp0;
308 // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)".
309 if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)),
310 m_Deferred(ShiftOp0)),
311 m_SpecificInt(Mask0F)))) {
312 Value *AndOp0;
313 // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)".
314 if (match(ShiftOp0,
315 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)),
317 m_SpecificInt(Mask33))))) {
318 Value *Root, *SubOp1;
319 // Matching "i - ((i >> 1) & 0x55555555...)".
320 if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) &&
321 match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)),
322 m_SpecificInt(Mask55)))) {
323 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
326 I.getModule(), Intrinsic::ctpop, I.getType());
327 I.replaceAllUsesWith(Builder.CreateCall(Func, {Root}));
328 ++NumPopCountRecognized;
329 return true;
330 }
331 }
332 }
333 }
334
335 return false;
336}
337
338/// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
339/// C2 saturate the value of the fp conversion. The transform is not reversable
340/// as the fptosi.sat is more defined than the input - all values produce a
341/// valid value for the fptosi.sat, where as some produce poison for original
342/// that were out of range of the integer conversion. The reversed pattern may
343/// use fmax and fmin instead. As we cannot directly reverse the transform, and
344/// it is not always profitable, we make it conditional on the cost being
345/// reported as lower by TTI.
347 // Look for min(max(fptosi, converting to fptosi_sat.
348 Value *In;
349 const APInt *MinC, *MaxC;
351 m_APInt(MinC))),
352 m_APInt(MaxC))) &&
354 m_APInt(MaxC))),
355 m_APInt(MinC))))
356 return false;
357
358 // Check that the constants clamp a saturate.
359 if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
360 return false;
361
362 Type *IntTy = I.getType();
363 Type *FpTy = In->getType();
364 Type *SatTy =
365 IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
366 if (auto *VecTy = dyn_cast<VectorType>(IntTy))
367 SatTy = VectorType::get(SatTy, VecTy->getElementCount());
368
369 // Get the cost of the intrinsic, and check that against the cost of
370 // fptosi+smin+smax
372 IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
374 SatCost += TTI.getCastInstrCost(Instruction::SExt, SatTy, IntTy,
377
379 Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
381 MinMaxCost += TTI.getIntrinsicInstrCost(
382 IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
384 MinMaxCost += TTI.getIntrinsicInstrCost(
385 IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
387
388 if (SatCost >= MinMaxCost)
389 return false;
390
392 Function *Fn = Intrinsic::getDeclaration(I.getModule(), Intrinsic::fptosi_sat,
393 {SatTy, FpTy});
394 Value *Sat = Builder.CreateCall(Fn, In);
395 I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
396 return true;
397}
398
399/// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
400/// pessimistic codegen that has to account for setting errno and can enable
401/// vectorization.
403 TargetLibraryInfo &TLI) {
404 // Match a call to sqrt mathlib function.
405 auto *Call = dyn_cast<CallInst>(&I);
406 if (!Call)
407 return false;
408
409 Module *M = Call->getModule();
410 LibFunc Func;
411 if (!TLI.getLibFunc(*Call, Func) || !isLibFuncEmittable(M, &TLI, Func))
412 return false;
413
414 if (Func != LibFunc_sqrt && Func != LibFunc_sqrtf && Func != LibFunc_sqrtl)
415 return false;
416
417 // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
418 // (because NNAN or the operand arg must not be less than -0.0) and (2) we
419 // would not end up lowering to a libcall anyway (which could change the value
420 // of errno), then:
421 // (1) errno won't be set.
422 // (2) it is safe to convert this to an intrinsic call.
423 Type *Ty = Call->getType();
424 Value *Arg = Call->getArgOperand(0);
425 if (TTI.haveFastSqrt(Ty) &&
426 (Call->hasNoNaNs() ||
427 CannotBeOrderedLessThanZero(Arg, M->getDataLayout(), &TLI))) {
430 Builder.setFastMathFlags(Call->getFastMathFlags());
431
432 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, Ty);
433 Value *NewSqrt = Builder.CreateCall(Sqrt, Arg, "sqrt");
434 I.replaceAllUsesWith(NewSqrt);
435
436 // Explicitly erase the old call because a call with side effects is not
437 // trivially dead.
438 I.eraseFromParent();
439 return true;
440 }
441
442 return false;
443}
444
445// Check if this array of constants represents a cttz table.
446// Iterate over the elements from \p Table by trying to find/match all
447// the numbers from 0 to \p InputBits that should represent cttz results.
448static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul,
449 uint64_t Shift, uint64_t InputBits) {
450 unsigned Length = Table.getNumElements();
451 if (Length < InputBits || Length > InputBits * 2)
452 return false;
453
454 APInt Mask = APInt::getBitsSetFrom(InputBits, Shift);
455 unsigned Matched = 0;
456
457 for (unsigned i = 0; i < Length; i++) {
458 uint64_t Element = Table.getElementAsInteger(i);
459 if (Element >= InputBits)
460 continue;
461
462 // Check if \p Element matches a concrete answer. It could fail for some
463 // elements that are never accessed, so we keep iterating over each element
464 // from the table. The number of matched elements should be equal to the
465 // number of potential right answers which is \p InputBits actually.
466 if ((((Mul << Element) & Mask.getZExtValue()) >> Shift) == i)
467 Matched++;
468 }
469
470 return Matched == InputBits;
471}
472
473// Try to recognize table-based ctz implementation.
474// E.g., an example in C (for more cases please see the llvm/tests):
475// int f(unsigned x) {
476// static const char table[32] =
477// {0, 1, 28, 2, 29, 14, 24, 3, 30,
478// 22, 20, 15, 25, 17, 4, 8, 31, 27,
479// 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
480// return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
481// }
482// this can be lowered to `cttz` instruction.
483// There is also a special case when the element is 0.
484//
485// Here are some examples or LLVM IR for a 64-bit target:
486//
487// CASE 1:
488// %sub = sub i32 0, %x
489// %and = and i32 %sub, %x
490// %mul = mul i32 %and, 125613361
491// %shr = lshr i32 %mul, 27
492// %idxprom = zext i32 %shr to i64
493// %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
494// i64 %idxprom %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
495//
496// CASE 2:
497// %sub = sub i32 0, %x
498// %and = and i32 %sub, %x
499// %mul = mul i32 %and, 72416175
500// %shr = lshr i32 %mul, 26
501// %idxprom = zext i32 %shr to i64
502// %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table, i64
503// 0, i64 %idxprom %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
504//
505// CASE 3:
506// %sub = sub i32 0, %x
507// %and = and i32 %sub, %x
508// %mul = mul i32 %and, 81224991
509// %shr = lshr i32 %mul, 27
510// %idxprom = zext i32 %shr to i64
511// %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table, i64
512// 0, i64 %idxprom %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
513//
514// CASE 4:
515// %sub = sub i64 0, %x
516// %and = and i64 %sub, %x
517// %mul = mul i64 %and, 283881067100198605
518// %shr = lshr i64 %mul, 58
519// %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0, i64
520// %shr %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
521//
522// All this can be lowered to @llvm.cttz.i32/64 intrinsic.
524 LoadInst *LI = dyn_cast<LoadInst>(&I);
525 if (!LI)
526 return false;
527
528 Type *AccessType = LI->getType();
529 if (!AccessType->isIntegerTy())
530 return false;
531
532 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getPointerOperand());
533 if (!GEP || !GEP->isInBounds() || GEP->getNumIndices() != 2)
534 return false;
535
536 if (!GEP->getSourceElementType()->isArrayTy())
537 return false;
538
539 uint64_t ArraySize = GEP->getSourceElementType()->getArrayNumElements();
540 if (ArraySize != 32 && ArraySize != 64)
541 return false;
542
543 GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
544 if (!GVTable || !GVTable->hasInitializer() || !GVTable->isConstant())
545 return false;
546
547 ConstantDataArray *ConstData =
548 dyn_cast<ConstantDataArray>(GVTable->getInitializer());
549 if (!ConstData)
550 return false;
551
552 if (!match(GEP->idx_begin()->get(), m_ZeroInt()))
553 return false;
554
555 Value *Idx2 = std::next(GEP->idx_begin())->get();
556 Value *X1;
557 uint64_t MulConst, ShiftConst;
558 // FIXME: 64-bit targets have `i64` type for the GEP index, so this match will
559 // probably fail for other (e.g. 32-bit) targets.
560 if (!match(Idx2, m_ZExtOrSelf(
562 m_ConstantInt(MulConst)),
563 m_ConstantInt(ShiftConst)))))
564 return false;
565
566 unsigned InputBits = X1->getType()->getScalarSizeInBits();
567 if (InputBits != 32 && InputBits != 64)
568 return false;
569
570 // Shift should extract top 5..7 bits.
571 if (InputBits - Log2_32(InputBits) != ShiftConst &&
572 InputBits - Log2_32(InputBits) - 1 != ShiftConst)
573 return false;
574
575 if (!isCTTZTable(*ConstData, MulConst, ShiftConst, InputBits))
576 return false;
577
578 auto ZeroTableElem = ConstData->getElementAsInteger(0);
579 bool DefinedForZero = ZeroTableElem == InputBits;
580
581 IRBuilder<> B(LI);
582 ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
583 Type *XType = X1->getType();
584 auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
585 Value *ZExtOrTrunc = nullptr;
586
587 if (DefinedForZero) {
588 ZExtOrTrunc = B.CreateZExtOrTrunc(Cttz, AccessType);
589 } else {
590 // If the value in elem 0 isn't the same as InputBits, we still want to
591 // produce the value from the table.
592 auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
593 auto Select =
594 B.CreateSelect(Cmp, ConstantInt::get(XType, ZeroTableElem), Cttz);
595
596 // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
597 // it should be handled as: `cttz(x) & (typeSize - 1)`.
598
599 ZExtOrTrunc = B.CreateZExtOrTrunc(Select, AccessType);
600 }
601
602 LI->replaceAllUsesWith(ZExtOrTrunc);
603
604 return true;
605}
606
607/// This is used by foldLoadsRecursive() to capture a Root Load node which is
608/// of type or(load, load) and recursively build the wide load. Also capture the
609/// shift amount, zero extend type and loadSize.
610struct LoadOps {
611 LoadInst *Root = nullptr;
613 bool FoundRoot = false;
615 const APInt *Shift = nullptr;
618};
619
620// Identify and Merge consecutive loads recursively which is of the form
621// (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
622// (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
623static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
624 AliasAnalysis &AA) {
625 const APInt *ShAmt2 = nullptr;
626 Value *X;
627 Instruction *L1, *L2;
628
629 // Go to the last node with loads.
630 if (match(V, m_OneUse(m_c_Or(
631 m_Value(X),
633 m_APInt(ShAmt2)))))) ||
636 if (!foldLoadsRecursive(X, LOps, DL, AA) && LOps.FoundRoot)
637 // Avoid Partial chain merge.
638 return false;
639 } else
640 return false;
641
642 // Check if the pattern has loads
643 LoadInst *LI1 = LOps.Root;
644 const APInt *ShAmt1 = LOps.Shift;
645 if (LOps.FoundRoot == false &&
648 m_APInt(ShAmt1)))))) {
649 LI1 = dyn_cast<LoadInst>(L1);
650 }
651 LoadInst *LI2 = dyn_cast<LoadInst>(L2);
652
653 // Check if loads are same, atomic, volatile and having same address space.
654 if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
656 return false;
657
658 // Check if Loads come from same BB.
659 if (LI1->getParent() != LI2->getParent())
660 return false;
661
662 // Find the data layout
663 bool IsBigEndian = DL.isBigEndian();
664
665 // Check if loads are consecutive and same size.
666 Value *Load1Ptr = LI1->getPointerOperand();
667 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
668 Load1Ptr =
669 Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
670 /* AllowNonInbounds */ true);
671
672 Value *Load2Ptr = LI2->getPointerOperand();
673 APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
674 Load2Ptr =
675 Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
676 /* AllowNonInbounds */ true);
677
678 // Verify if both loads have same base pointers and load sizes are same.
679 uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
680 uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
681 if (Load1Ptr != Load2Ptr || LoadSize1 != LoadSize2)
682 return false;
683
684 // Support Loadsizes greater or equal to 8bits and only power of 2.
685 if (LoadSize1 < 8 || !isPowerOf2_64(LoadSize1))
686 return false;
687
688 // Alias Analysis to check for stores b/w the loads.
689 LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
690 MemoryLocation Loc;
691 if (!Start->comesBefore(End)) {
692 std::swap(Start, End);
694 if (LOps.FoundRoot)
695 Loc = Loc.getWithNewSize(LOps.LoadSize);
696 } else
698 unsigned NumScanned = 0;
699 for (Instruction &Inst :
700 make_range(Start->getIterator(), End->getIterator())) {
701 if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
702 return false;
703 if (++NumScanned > MaxInstrsToScan)
704 return false;
705 }
706
707 // Make sure Load with lower Offset is at LI1
708 bool Reverse = false;
709 if (Offset2.slt(Offset1)) {
710 std::swap(LI1, LI2);
711 std::swap(ShAmt1, ShAmt2);
712 std::swap(Offset1, Offset2);
713 std::swap(Load1Ptr, Load2Ptr);
714 std::swap(LoadSize1, LoadSize2);
715 Reverse = true;
716 }
717
718 // Big endian swap the shifts
719 if (IsBigEndian)
720 std::swap(ShAmt1, ShAmt2);
721
722 // Find Shifts values.
723 uint64_t Shift1 = 0, Shift2 = 0;
724 if (ShAmt1)
725 Shift1 = ShAmt1->getZExtValue();
726 if (ShAmt2)
727 Shift2 = ShAmt2->getZExtValue();
728
729 // First load is always LI1. This is where we put the new load.
730 // Use the merged load size available from LI1 for forward loads.
731 if (LOps.FoundRoot) {
732 if (!Reverse)
733 LoadSize1 = LOps.LoadSize;
734 else
735 LoadSize2 = LOps.LoadSize;
736 }
737
738 // Verify if shift amount and load index aligns and verifies that loads
739 // are consecutive.
740 uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
741 uint64_t PrevSize =
742 DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
743 if ((Shift2 - Shift1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
744 return false;
745
746 // Update LOps
747 AAMDNodes AATags1 = LOps.AATags;
748 AAMDNodes AATags2 = LI2->getAAMetadata();
749 if (LOps.FoundRoot == false) {
750 LOps.FoundRoot = true;
751 AATags1 = LI1->getAAMetadata();
752 }
753 LOps.LoadSize = LoadSize1 + LoadSize2;
754 LOps.RootInsert = Start;
755
756 // Concatenate the AATags of the Merged Loads.
757 LOps.AATags = AATags1.concat(AATags2);
758
759 LOps.Root = LI1;
760 LOps.Shift = ShAmt1;
761 LOps.ZextType = X->getType();
762 return true;
763}
764
765// For a given BB instruction, evaluate all loads in the chain that form a
766// pattern which suggests that the loads can be combined. The one and only use
767// of the loads is to form a wider load.
770 const DominatorTree &DT) {
771 // Only consider load chains of scalar values.
772 if (isa<VectorType>(I.getType()))
773 return false;
774
775 LoadOps LOps;
776 if (!foldLoadsRecursive(&I, LOps, DL, AA) || !LOps.FoundRoot)
777 return false;
778
780 LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
781
782 IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
783 // TTI based checks if we want to proceed with wider load
784 bool Allowed = TTI.isTypeLegal(WiderType);
785 if (!Allowed)
786 return false;
787
788 unsigned AS = LI1->getPointerAddressSpace();
789 unsigned Fast = 0;
790 Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
791 AS, LI1->getAlign(), &Fast);
792 if (!Allowed || !Fast)
793 return false;
794
795 // Get the Index and Ptr for the new GEP.
796 Value *Load1Ptr = LI1->getPointerOperand();
797 Builder.SetInsertPoint(LOps.RootInsert);
798 if (!DT.dominates(Load1Ptr, LOps.RootInsert)) {
799 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
800 Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets(
801 DL, Offset1, /* AllowNonInbounds */ true);
802 Load1Ptr = Builder.CreateGEP(Builder.getInt8Ty(), Load1Ptr,
803 Builder.getInt32(Offset1.getZExtValue()));
804 }
805 // Generate wider load.
806 Value *NewPtr = Builder.CreateBitCast(Load1Ptr, WiderType->getPointerTo(AS));
807 NewLoad = Builder.CreateAlignedLoad(WiderType, NewPtr, LI1->getAlign(),
808 LI1->isVolatile(), "");
809 NewLoad->takeName(LI1);
810 // Set the New Load AATags Metadata.
811 if (LOps.AATags)
812 NewLoad->setAAMetadata(LOps.AATags);
813
814 Value *NewOp = NewLoad;
815 // Check if zero extend needed.
816 if (LOps.ZextType)
817 NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
818
819 // Check if shift needed. We need to shift with the amount of load1
820 // shift if not zero.
821 if (LOps.Shift)
822 NewOp = Builder.CreateShl(NewOp, ConstantInt::get(I.getContext(), *LOps.Shift));
823 I.replaceAllUsesWith(NewOp);
824
825 return true;
826}
827
828// Calculate GEP Stride and accumulated const ModOffset. Return Stride and
829// ModOffset
830static std::pair<APInt, APInt>
832 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
833 std::optional<APInt> Stride;
834 APInt ModOffset(BW, 0);
835 // Return a minimum gep stride, greatest common divisor of consective gep
836 // index scales(c.f. Bézout's identity).
837 while (auto *GEP = dyn_cast<GEPOperator>(PtrOp)) {
838 MapVector<Value *, APInt> VarOffsets;
839 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset))
840 break;
841
842 for (auto [V, Scale] : VarOffsets) {
843 // Only keep a power of two factor for non-inbounds
844 if (!GEP->isInBounds())
845 Scale = APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
846
847 if (!Stride)
848 Stride = Scale;
849 else
850 Stride = APIntOps::GreatestCommonDivisor(*Stride, Scale);
851 }
852
853 PtrOp = GEP->getPointerOperand();
854 }
855
856 // Check whether pointer arrives back at Global Variable via at least one GEP.
857 // Even if it doesn't, we can check by alignment.
858 if (!isa<GlobalVariable>(PtrOp) || !Stride)
859 return {APInt(BW, 1), APInt(BW, 0)};
860
861 // In consideration of signed GEP indices, non-negligible offset become
862 // remainder of division by minimum GEP stride.
863 ModOffset = ModOffset.srem(*Stride);
864 if (ModOffset.isNegative())
865 ModOffset += *Stride;
866
867 return {*Stride, ModOffset};
868}
869
870/// If C is a constant patterned array and all valid loaded results for given
871/// alignment are same to a constant, return that constant.
873 auto *LI = dyn_cast<LoadInst>(&I);
874 if (!LI || LI->isVolatile())
875 return false;
876
877 // We can only fold the load if it is from a constant global with definitive
878 // initializer. Skip expensive logic if this is not the case.
879 auto *PtrOp = LI->getPointerOperand();
880 auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(PtrOp));
881 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
882 return false;
883
884 // Bail for large initializers in excess of 4K to avoid too many scans.
885 Constant *C = GV->getInitializer();
886 uint64_t GVSize = DL.getTypeAllocSize(C->getType());
887 if (!GVSize || 4096 < GVSize)
888 return false;
889
890 Type *LoadTy = LI->getType();
891 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
892 auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL);
893
894 // Any possible offset could be multiple of GEP stride. And any valid
895 // offset is multiple of load alignment, so checking only multiples of bigger
896 // one is sufficient to say results' equality.
897 if (auto LA = LI->getAlign();
898 LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
899 ConstOffset = APInt(BW, 0);
900 Stride = APInt(BW, LA.value());
901 }
902
903 Constant *Ca = ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL);
904 if (!Ca)
905 return false;
906
907 unsigned E = GVSize - DL.getTypeStoreSize(LoadTy);
908 for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
909 if (Ca != ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL))
910 return false;
911
912 I.replaceAllUsesWith(Ca);
913
914 return true;
915}
916
917/// This is the entry point for folds that could be implemented in regular
918/// InstCombine, but they are separated because they are not expected to
919/// occur frequently and/or have more than a constant-length pattern match.
923 bool MadeChange = false;
924 for (BasicBlock &BB : F) {
925 // Ignore unreachable basic blocks.
926 if (!DT.isReachableFromEntry(&BB))
927 continue;
928
929 const DataLayout &DL = F.getParent()->getDataLayout();
930
931 // Walk the block backwards for efficiency. We're matching a chain of
932 // use->defs, so we're more likely to succeed by starting from the bottom.
933 // Also, we want to avoid matching partial patterns.
934 // TODO: It would be more efficient if we removed dead instructions
935 // iteratively in this loop rather than waiting until the end.
937 MadeChange |= foldAnyOrAllBitsSet(I);
938 MadeChange |= foldGuardedFunnelShift(I, DT);
939 MadeChange |= tryToRecognizePopCount(I);
940 MadeChange |= tryToFPToSat(I, TTI);
941 MadeChange |= tryToRecognizeTableBasedCttz(I);
942 MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT);
943 MadeChange |= foldPatternedLoads(I, DL);
944 // NOTE: This function introduces erasing of the instruction `I`, so it
945 // needs to be called at the end of this sequence, otherwise we may make
946 // bugs.
947 MadeChange |= foldSqrt(I, TTI, TLI);
948 }
949 }
950
951 // We're done with transforms, so remove dead instructions.
952 if (MadeChange)
953 for (BasicBlock &BB : F)
955
956 return MadeChange;
957}
958
959/// This is the entry point for all transforms. Pass manager differences are
960/// handled in the callers of this function.
963 AliasAnalysis &AA) {
964 bool MadeChange = false;
965 const DataLayout &DL = F.getParent()->getDataLayout();
966 TruncInstCombine TIC(AC, TLI, DL, DT);
967 MadeChange |= TIC.run(F);
968 MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA);
969 return MadeChange;
970}
971
974 auto &AC = AM.getResult<AssumptionAnalysis>(F);
975 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
976 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
977 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
978 auto &AA = AM.getResult<AAManager>(F);
979 if (!runImpl(F, AC, TTI, TLI, DT, AA)) {
980 // No changes, all analyses are preserved.
981 return PreservedAnalyses::all();
982 }
983 // Mark all the analyses that instcombine updates as preserved.
986 return PA;
987}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
amdgpu AMDGPU Register Bank Select
static bool tryToRecognizePopCount(Instruction &I)
static bool foldSqrt(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI)
Try to replace a mathlib call to sqrt with the LLVM intrinsic.
static bool foldAnyOrAllBitsSet(Instruction &I)
Match patterns that correspond to "any-bits-set" and "all-bits-set".
static bool tryToFPToSat(Instruction &I, TargetTransformInfo &TTI)
Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and C2 saturate the value of t...
static bool runImpl(Function &F, AssumptionCache &AC, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, DominatorTree &DT, AliasAnalysis &AA)
This is the entry point for all transforms.
static bool matchAndOrChain(Value *V, MaskOps &MOps)
This is a recursive helper for foldAnyOrAllBitsSet() that walks through a chain of 'and' or 'or' inst...
static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool tryToRecognizeTableBasedCttz(Instruction &I)
static bool foldGuardedFunnelShift(Instruction &I, const DominatorTree &DT)
Match a pattern for a bitwise funnel/rotate operation that partially guards against undefined behavio...
static bool foldUnusualPatterns(Function &F, DominatorTree &DT, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AliasAnalysis &AA)
This is the entry point for folds that could be implemented in regular InstCombine,...
static cl::opt< unsigned > MaxInstrsToScan("aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden, cl::desc("Max number of instructions to scan for aggressive instcombine."))
static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, AliasAnalysis &AA)
static std::pair< APInt, APInt > getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL)
static bool isCTTZTable(const ConstantDataArray &Table, uint64_t Mul, uint64_t Shift, uint64_t InputBits)
static bool foldPatternedLoads(Instruction &I, const DataLayout &DL)
If C is a constant patterned array and all valid loaded results for given alignment are same to a con...
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
assume Assume Builder
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:464
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, const TargetLowering &TLI)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
Definition: IRBuilder.cpp:537
static Instruction * matchFunnelShift(Instruction &Or, InstCombinerImpl &IC)
Match UB-safe variants of the funnel shift intrinsic.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This pass exposes codegen information to IR-level passes.
BinaryOperator * Mul
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:75
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1498
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1312
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1443
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:312
static APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition: APInt.cpp:611
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition: APInt.cpp:1733
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1112
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:269
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:222
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1203
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:253
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:711
@ ICMP_EQ
equal
Definition: InstrTypes.h:732
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:677
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:3049
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2792
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
This is an important base class in LLVM.
Definition: Constant.h:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:940
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2564
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:70
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1608
const BasicBlock * getParent() const
Definition: Instruction.h:90
AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1594
Class to represent integer types.
Definition: DerivedTypes.h:40
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:339
An instruction for reading from memory.
Definition: Instructions.h:177
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:270
Value * getPointerOperand()
Definition: Instructions.h:264
bool isSimple() const
Definition: Instructions.h:256
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:37
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
@ TCK_RecipThroughput
Reciprocal throughput.
bool isTypeLegal(Type *Ty) const
Return true if this type is legal.
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace=0, Align Alignment=Align(1), unsigned *Fast=nullptr) const
Determine if the target supports unaligned memory accesses.
bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
@ None
The cast is not used with a load/store of any kind.
bool run(Function &F)
Perform TruncInst pattern optimization on given function.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:235
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:229
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr) const
Accumulate the constant offset this value has compared to a base pointer.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:535
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1069
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:384
APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition: APInt.cpp:758
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1465
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:854
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, OpTy > m_ZExtOrSelf(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:716
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:772
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:147
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:517
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:790
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:524
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
specific_bbval m_SpecificBB(BasicBlock *BB)
Match a specific basic block value.
Definition: PatternMatch.h:887
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastClass_match< OpTy, Instruction::FPToSI > m_FPToSI(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:991
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:440
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
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:748
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition: Local.cpp:717
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:297
bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:382
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:511
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:292
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
@ And
Bitwise or logical AND of integers.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
bool CannotBeOrderedLessThanZero(const Value *V, const DataLayout &DL, const TargetLibraryInfo *TLI)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
const APInt * Shift
LoadInst * RootInsert
This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and the bit indexes (Mask) nee...
MaskOps(unsigned BitWidth, bool MatchAnds)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:651
AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.