LLVM 24.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"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Dominators.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Instruction.h"
32#include "llvm/IR/MDBuilder.h"
40
41using namespace llvm;
42using namespace PatternMatch;
43
44#define DEBUG_TYPE "aggressive-instcombine"
45
46namespace llvm {
48}
49
50STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded");
51STATISTIC(NumGuardedRotates,
52 "Number of guarded rotates transformed into funnel shifts");
53STATISTIC(NumGuardedFunnelShifts,
54 "Number of guarded funnel shifts transformed into funnel shifts");
55STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized");
56STATISTIC(NumSelectCTTZFolded,
57 "Number of select-based split cttz patterns folded");
58STATISTIC(NumSelectCTLZFolded,
59 "Number of select-based split ctlz patterns folded");
60
62 "aggressive-instcombine-max-scan-instrs", cl::init(64), cl::Hidden,
63 cl::desc("Max number of instructions to scan for aggressive instcombine."));
64
66 "strncmp-inline-threshold", cl::init(3), cl::Hidden,
67 cl::desc("The maximum length of a constant string for a builtin string cmp "
68 "call eligible for inlining. The default value is 3."));
69
71 MemChrInlineThreshold("memchr-inline-threshold", cl::init(3), cl::Hidden,
72 cl::desc("The maximum length of a constant string to "
73 "inline a memchr call."));
74
75/// Try to fold a select-based split cttz pattern into a single full-width cttz.
76///
77/// %lo = trunc iN %val to i(N/2)
78/// %cmp = icmp eq i(N/2) %lo, 0
79/// %shr = lshr iN %val, N/2
80/// %hi = trunc iN %shr to i(N/2)
81/// %cttz_hi = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %hi, ...)
82/// %hi_plus = add/or_disjoint i(N/2) %cttz_hi, N/2
83/// %cttz_lo = call i(N/2) @llvm.cttz.i(N/2)(i(N/2) %lo, ...)
84/// %result = select i1 %cmp, i(N/2) %hi_plus, i(N/2) %cttz_lo
85/// -->
86/// %cttz_wide = call iN @llvm.cttz.iN(iN %val, i1 false)
87/// %result = trunc iN %cttz_wide to i(N/2)
88/// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/-s14-s
89// TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases.
90static bool foldSelectSplitCTTZ(Instruction &I, Value *LoTrunc, Value *HiResult,
91 Value *LoResult, Type *HalfTy) {
92 unsigned HalfWidth = HalfTy->getIntegerBitWidth();
93 unsigned FullWidth = HalfWidth * 2;
94
95 // LoTrunc: trunc iN SrcVal to i(N/2)
96 Value *SrcVal;
97 if (!match(LoTrunc, m_Trunc(m_Value(SrcVal))))
98 return false;
99 if (!SrcVal->getType()->isIntegerTy(FullWidth))
100 return false;
101
102 // LoResult: cttz(trunc(SrcVal), _), must use same truncated value
103 if (!match(LoResult, m_OneUse(m_Cttz(m_Specific(LoTrunc), m_Value()))))
104 return false;
105
106 // HiResult: add/or_disjoint(cttz(trunc(lshr(SrcVal, N/2)), _), N/2)
107 Value *CttzHiCall;
108 if (!match(HiResult, m_OneUse(m_AddLike(m_Value(CttzHiCall),
109 m_SpecificInt(HalfWidth)))))
110 return false;
111
112 Value *HiCttzArg;
113 if (!match(CttzHiCall, m_OneUse(m_Cttz(m_Value(HiCttzArg), m_Value()))))
114 return false;
115
116 if (!match(HiCttzArg,
117 m_Trunc(m_LShr(m_Specific(SrcVal), m_SpecificInt(HalfWidth)))))
118 return false;
119
120 // Match successful.
121 IRBuilder<> Builder(&I);
122 Value *CttzWide = Builder.CreateIntrinsic(
123 Intrinsic::cttz, {SrcVal->getType()}, {SrcVal, Builder.getFalse()});
124 Value *Trunc = Builder.CreateTrunc(CttzWide, HalfTy);
125
126 I.replaceAllUsesWith(Trunc);
127 ++NumSelectCTTZFolded;
128 return true;
129}
130
131/// Same as foldSelectSplitCTTZ but for leading zeros (ctlz).
132///
133/// %shr = lshr iN %val, N/2
134/// %hi = trunc iN %shr to i(N/2)
135/// %cmp = icmp eq i(N/2) %hi, 0 (or icmp eq iN %shr, 0)
136/// %lo = trunc iN %val to i(N/2)
137/// %ctlz_lo = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %lo, ...)
138/// %lo_plus = add/or_disjoint i(N/2) %ctlz_lo, N/2
139/// %ctlz_hi = call i(N/2) @llvm.ctlz.i(N/2)(i(N/2) %hi, ...)
140/// %result = select i1 %cmp, i(N/2) %lo_plus, i(N/2) %ctlz_hi
141/// -->
142/// %ctlz_wide = call iN @llvm.ctlz.iN(iN %val, i1 false)
143/// %result = trunc iN %ctlz_wide to i(N/2)
144///
145/// Alive proof (for i64/i32): https://alive2.llvm.org/ce/z/WfQepH
146// TrueVal/FalseVal are pre-normalized by the caller to the EQ/NE cases.
147static bool foldSelectSplitCTLZ(Instruction &I, Value *HiPart, Value *LoResult,
148 Value *HiResult, Type *HalfTy) {
149 unsigned HalfWidth = HalfTy->getIntegerBitWidth();
150 unsigned FullWidth = HalfWidth * 2;
151
152 // Extract SrcVal from HiPart: either trunc(lshr(SrcVal, N/2)) or
153 // lshr(SrcVal, N/2)
154 Value *SrcVal;
155 if (match(HiPart, m_Trunc(m_Value(SrcVal))))
156 HiPart = SrcVal;
157
158 if (!match(HiPart, m_LShr(m_Value(SrcVal), m_SpecificInt(HalfWidth))))
159 return false;
160 if (!SrcVal->getType()->isIntegerTy(FullWidth))
161 return false;
162
163 // HiResult: ctlz(trunc(lshr(SrcVal, N/2)), _)
164 Value *HiCtlzArg;
165 if (!match(HiResult, m_OneUse(m_Ctlz(m_Value(HiCtlzArg), m_Value()))))
166 return false;
167
168 if (!match(HiCtlzArg,
169 m_Trunc(m_LShr(m_Specific(SrcVal), m_SpecificInt(HalfWidth)))))
170 return false;
171
172 // LoResult: add/or_disjoint(ctlz(trunc(SrcVal), _), N/2)
173 Value *CtlzLoCall;
174 if (!match(LoResult, m_OneUse(m_AddLike(m_Value(CtlzLoCall),
175 m_SpecificInt(HalfWidth)))))
176 return false;
177
178 Value *LoCtlzArg;
179 if (!match(CtlzLoCall, m_OneUse(m_Ctlz(m_Value(LoCtlzArg), m_Value()))))
180 return false;
181
182 if (!match(LoCtlzArg, m_Trunc(m_Specific(SrcVal))))
183 return false;
184
185 // Match successful.
186 IRBuilder<> Builder(&I);
187 Value *CtlzWide = Builder.CreateIntrinsic(
188 Intrinsic::ctlz, {SrcVal->getType()}, {SrcVal, Builder.getFalse()});
189 Value *Trunc = Builder.CreateTrunc(CtlzWide, HalfTy);
190
191 I.replaceAllUsesWith(Trunc);
192 ++NumSelectCTLZFolded;
193 return true;
194}
195
196/// Common entry point for folding select-based split cttz/ctlz patterns.
197/// Performs the initial select and type matching shared by both transforms,
198/// then delegates to foldSelectSplitCTTZ and foldSelectSplitCTLZ.
200 Value *Cond, *TrueVal, *FalseVal;
201 if (!match(&I, m_Select(m_Value(Cond), m_Value(TrueVal), m_Value(FalseVal))))
202 return false;
203
204 Type *Ty = I.getType();
205 if (!Ty->isIntegerTy())
206 return false;
207
208 // Bail out on very small types (i1, i2): the full-width cttz/ctlz can return
209 // values not representable in the half type (e.g., cttz.i4 can return 4,
210 // which doesn't fit in i2).
211 if (Ty->getIntegerBitWidth() <= 2)
212 return false;
213
214 CmpPredicate Pred;
215 Value *CmpOp;
216 if (!match(Cond, m_ICmp(Pred, m_Value(CmpOp), m_ZeroInt())) ||
218 return false;
219
220 // Canonicalize select operands.
221 if (Pred == CmpInst::ICMP_NE)
222 std::swap(TrueVal, FalseVal);
223
224 return foldSelectSplitCTTZ(I, CmpOp, TrueVal, FalseVal, Ty) ||
225 foldSelectSplitCTLZ(I, CmpOp, TrueVal, FalseVal, Ty);
226}
227
228/// Match a pattern for a bitwise funnel/rotate operation that partially guards
229/// against undefined behavior by branching around the funnel-shift/rotation
230/// when the shift amount is 0.
232 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2)
233 return false;
234
235 // As with the one-use checks below, this is not strictly necessary, but we
236 // are being cautious to avoid potential perf regressions on targets that
237 // do not actually have a funnel/rotate instruction (where the funnel shift
238 // would be expanded back into math/shift/logic ops).
239 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits()))
240 return false;
241
242 // Match V to funnel shift left/right and capture the source operands and
243 // shift amount.
244 auto matchFunnelShift = [](Value *V, Value *&ShVal0, Value *&ShVal1,
245 Value *&ShAmt) {
246 unsigned Width = V->getType()->getScalarSizeInBits();
247
248 // fshl(ShVal0, ShVal1, ShAmt)
249 // == (ShVal0 << ShAmt) | (ShVal1 >> (Width -ShAmt))
250 if (match(V, m_OneUse(m_c_Or(
251 m_Shl(m_Value(ShVal0), m_Value(ShAmt)),
252 m_LShr(m_Value(ShVal1), m_Sub(m_SpecificInt(Width),
253 m_Deferred(ShAmt))))))) {
254 return Intrinsic::fshl;
255 }
256
257 // fshr(ShVal0, ShVal1, ShAmt)
258 // == (ShVal0 >> ShAmt) | (ShVal1 << (Width - ShAmt))
259 if (match(V,
261 m_Value(ShAmt))),
262 m_LShr(m_Value(ShVal1), m_Deferred(ShAmt)))))) {
263 return Intrinsic::fshr;
264 }
265
267 };
268
269 // One phi operand must be a funnel/rotate operation, and the other phi
270 // operand must be the source value of that funnel/rotate operation:
271 // phi [ rotate(RotSrc, ShAmt), FunnelBB ], [ RotSrc, GuardBB ]
272 // phi [ fshl(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal0, GuardBB ]
273 // phi [ fshr(ShVal0, ShVal1, ShAmt), FunnelBB ], [ ShVal1, GuardBB ]
274 PHINode &Phi = cast<PHINode>(I);
275 unsigned FunnelOp = 0, GuardOp = 1;
276 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1);
277 Value *ShVal0, *ShVal1, *ShAmt;
278 Intrinsic::ID IID = matchFunnelShift(P0, ShVal0, ShVal1, ShAmt);
279 if (IID == Intrinsic::not_intrinsic ||
280 (IID == Intrinsic::fshl && ShVal0 != P1) ||
281 (IID == Intrinsic::fshr && ShVal1 != P1)) {
282 IID = matchFunnelShift(P1, ShVal0, ShVal1, ShAmt);
283 if (IID == Intrinsic::not_intrinsic ||
284 (IID == Intrinsic::fshl && ShVal0 != P0) ||
285 (IID == Intrinsic::fshr && ShVal1 != P0))
286 return false;
287 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
288 "Pattern must match funnel shift left or right");
289 std::swap(FunnelOp, GuardOp);
290 }
291
292 // The incoming block with our source operand must be the "guard" block.
293 // That must contain a cmp+branch to avoid the funnel/rotate when the shift
294 // amount is equal to 0. The other incoming block is the block with the
295 // funnel/rotate.
296 BasicBlock *GuardBB = Phi.getIncomingBlock(GuardOp);
297 BasicBlock *FunnelBB = Phi.getIncomingBlock(FunnelOp);
298 Instruction *TermI = GuardBB->getTerminator();
299
300 // Ensure that the shift values dominate each block.
301 if (!DT.dominates(ShVal0, TermI) || !DT.dominates(ShVal1, TermI))
302 return false;
303
304 BasicBlock *PhiBB = Phi.getParent();
306 m_ZeroInt()),
307 m_SpecificBB(PhiBB), m_SpecificBB(FunnelBB))))
308 return false;
309
310 IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt());
311
312 if (ShVal0 == ShVal1)
313 ++NumGuardedRotates;
314 else
315 ++NumGuardedFunnelShifts;
316
317 // If this is not a rotate then the select was blocking poison from the
318 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
319 bool IsFshl = IID == Intrinsic::fshl;
320 if (ShVal0 != ShVal1) {
321 if (IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal1))
322 ShVal1 = Builder.CreateFreeze(ShVal1);
323 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(ShVal0))
324 ShVal0 = Builder.CreateFreeze(ShVal0);
325 }
326
327 // We matched a variation of this IR pattern:
328 // GuardBB:
329 // %cmp = icmp eq i32 %ShAmt, 0
330 // br i1 %cmp, label %PhiBB, label %FunnelBB
331 // FunnelBB:
332 // %sub = sub i32 32, %ShAmt
333 // %shr = lshr i32 %ShVal1, %sub
334 // %shl = shl i32 %ShVal0, %ShAmt
335 // %fsh = or i32 %shr, %shl
336 // br label %PhiBB
337 // PhiBB:
338 // %cond = phi i32 [ %fsh, %FunnelBB ], [ %ShVal0, %GuardBB ]
339 // -->
340 // llvm.fshl.i32(i32 %ShVal0, i32 %ShVal1, i32 %ShAmt)
341 Phi.replaceAllUsesWith(
342 Builder.CreateIntrinsic(IID, Phi.getType(), {ShVal0, ShVal1, ShAmt}));
343 return true;
344}
345
346/// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and
347/// the bit indexes (Mask) needed by a masked compare. If we're matching a chain
348/// of 'and' ops, then we also need to capture the fact that we saw an
349/// "and X, 1", so that's an extra return value for that case.
350namespace {
351struct MaskOps {
352 Value *Root = nullptr;
353 APInt Mask;
354 bool MatchAndChain;
355 bool FoundAnd1 = false;
356
357 MaskOps(unsigned BitWidth, bool MatchAnds)
358 : Mask(APInt::getZero(BitWidth)), MatchAndChain(MatchAnds) {}
359};
360} // namespace
361
362/// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a
363/// chain of 'and' or 'or' instructions looking for shift ops of a common source
364/// value. Examples:
365/// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8)
366/// returns { X, 0x129 }
367/// and (and (X >> 1), 1), (X >> 4)
368/// returns { X, 0x12 }
369static bool matchAndOrChain(Value *V, MaskOps &MOps) {
370 Value *Op0, *Op1;
371 if (MOps.MatchAndChain) {
372 // Recurse through a chain of 'and' operands. This requires an extra check
373 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere
374 // in the chain to know that all of the high bits are cleared.
375 if (match(V, m_And(m_Value(Op0), m_One()))) {
376 MOps.FoundAnd1 = true;
377 return matchAndOrChain(Op0, MOps);
378 }
379 if (match(V, m_And(m_Value(Op0), m_Value(Op1))))
380 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
381 } else {
382 // Recurse through a chain of 'or' operands.
383 if (match(V, m_Or(m_Value(Op0), m_Value(Op1))))
384 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps);
385 }
386
387 // We need a shift-right or a bare value representing a compare of bit 0 of
388 // the original source operand.
389 Value *Candidate;
390 const APInt *BitIndex = nullptr;
391 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex))))
392 Candidate = V;
393
394 // Initialize result source operand.
395 if (!MOps.Root)
396 MOps.Root = Candidate;
397
398 // The shift constant is out-of-range? This code hasn't been simplified.
399 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth()))
400 return false;
401
402 // Fill in the mask bit derived from the shift constant.
403 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0);
404 return MOps.Root == Candidate;
405}
406
407/// Match patterns that correspond to "any-bits-set" and "all-bits-set".
408/// These will include a chain of 'or' or 'and'-shifted bits from a
409/// common source value:
410/// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0
411/// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask
412/// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns
413/// that differ only with a final 'not' of the result. We expect that final
414/// 'not' to be folded with the compare that we create here (invert predicate).
416 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the
417 // final "and X, 1" instruction must be the final op in the sequence.
418 bool MatchAllBitsSet;
419 bool MatchTrunc;
420 Value *X;
421 if (I.getType()->isIntOrIntVectorTy(1)) {
422 if (match(&I, m_Trunc(m_OneUse(m_And(m_Value(), m_Value())))))
423 MatchAllBitsSet = true;
424 else if (match(&I, m_Trunc(m_OneUse(m_Or(m_Value(), m_Value())))))
425 MatchAllBitsSet = false;
426 else
427 return false;
428 MatchTrunc = true;
429 X = I.getOperand(0);
430 } else {
431 if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value()))) {
432 X = &I;
433 MatchAllBitsSet = true;
434 } else if (match(&I,
435 m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One()))) {
436 X = I.getOperand(0);
437 MatchAllBitsSet = false;
438 } else
439 return false;
440 MatchTrunc = false;
441 }
442 Type *Ty = X->getType();
443
444 MaskOps MOps(Ty->getScalarSizeInBits(), MatchAllBitsSet);
445 if (!matchAndOrChain(X, MOps) ||
446 (MatchAllBitsSet && !MatchTrunc && !MOps.FoundAnd1))
447 return false;
448
449 // The pattern was found. Create a masked compare that replaces all of the
450 // shift and logic ops.
451 IRBuilder<> Builder(&I);
452 Constant *Mask = ConstantInt::get(Ty, MOps.Mask);
453 Value *And = Builder.CreateAnd(MOps.Root, Mask);
454 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask)
455 : Builder.CreateIsNotNull(And);
456 Value *Zext = MatchTrunc ? Cmp : Builder.CreateZExt(Cmp, Ty);
457 I.replaceAllUsesWith(Zext);
458 ++NumAnyOrAllBitsSet;
459 return true;
460}
461
462/// Helper function to replace an instruction with a popcount intrinsic.
463/// This creates the ctpop intrinsic with an optional truncation appended at the
464/// end, and replaces all uses of the instruction.
466 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n");
467 Type *RootTy = Root->getType();
468 Type *OrigTy = I.getType();
469
470 IRBuilder<> Builder(&I);
471 Value *NewVal = Builder.CreateIntrinsic(Intrinsic::ctpop, RootTy, {Root});
472 if (OrigTy != RootTy) {
473 assert(RootTy->getScalarSizeInBits() > OrigTy->getScalarSizeInBits() &&
474 "Only truncation is supported for now");
475 NewVal = Builder.CreateTrunc(NewVal, OrigTy);
476 }
477 I.replaceAllUsesWith(NewVal);
478 ++NumPopCountRecognized;
479}
480
481// Matches the common innermost steps of the Hacker's Delight popcount idiom:
482// V = ((x + (x >> 4)) & 0x0F...)
483// x = (y & 0x33...) + ((y >> 2) & 0x33...) [or y - 3*((y>>2)&0x33...)]
484// y = Root - ((Root >> 1) & 0x55...)
485// This computes the popcount for each byte.
486// Returns Root on success, nullptr on failure.
487static Value *matchPopCountBytes(Value *V, unsigned Len, const DataLayout &DL) {
488 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
489 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
490 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F));
491
492 Value *Add2;
493 // Matching "((x + (x >> 4)) & 0x0F...)".
494 if (!match(V, m_And(m_c_Add(m_LShr(m_Value(Add2), m_SpecificInt(4)),
495 m_Deferred(Add2)),
496 m_SpecificInt(Mask0F))))
497 return nullptr;
498
499 Value *Sub1;
500 APInt NegThree(Len, -3, /*isSigned=*/true);
501 // Match
502 // x = (x & 0x33333333) + ((x >> 2) & 0x33333333)"
503 // Or
504 // x = x - 3*((x >> 2) & 0x33333333)
505 if (!match(Add2, m_c_Add(m_And(m_LShr(m_Value(Sub1), m_SpecificInt(2)),
506 m_SpecificInt(Mask33)),
507 m_And(m_Deferred(Sub1), m_SpecificInt(Mask33)))) &&
509 m_SpecificInt(Mask33)),
510 m_SpecificInt(NegThree)),
511 m_Deferred(Sub1))))
512 return nullptr;
513
514 Value *Root, *LShr;
515 const APInt *AndMask;
516 // Matching "x - ((x >> 1) & 0x55...)".
517 if (!match(Sub1,
518 m_Sub(m_Value(Root), m_And(m_Value(LShr, m_LShr(m_Deferred(Root),
519 m_SpecificInt(1))),
520 m_APInt(AndMask)))))
521 return nullptr;
522
523 if (*AndMask != Mask55) {
524 // Accept a narrowed mask if missing bits are known zero in Root>>1.
525 if (!AndMask->isSubsetOf(Mask55))
526 return nullptr;
527 APInt NeededMask = Mask55 & ~*AndMask;
528 if (!MaskedValueIsZero(LShr, NeededMask, SimplifyQuery(DL)))
529 return nullptr;
530 }
531
532 return Root;
533}
534
535// Try to recognize below function as popcount intrinsic.
536// This is the "best" algorithm from
537// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
538// Also used in TargetLowering::expandCTPOP().
539//
540// int popcount(unsigned int i) {
541// i = i - ((i >> 1) & 0x55555555);
542// i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
543// i = ((i + (i >> 4)) & 0x0F0F0F0F);
544// return (i * 0x01010101) >> 24;
545// }
547 if (I.getOpcode() != Instruction::LShr)
548 return false;
549
550 Type *Ty = I.getType();
551 if (!Ty->isIntOrIntVectorTy())
552 return false;
553
554 unsigned Len = Ty->getScalarSizeInBits();
555 // Len==8 is handled by tryToRecognizePopCount2n3.
556 // FIXME: other irregular type lengths.
557 if (Len > 128 || Len <= 8 || Len % 8 != 0)
558 return false;
559
560 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01));
561
562 Value *Op0 = I.getOperand(0);
563 Value *Op1 = I.getOperand(1);
564 Value *MulOp0;
565 // Matching "(i * 0x01010101...) >> 24".
566 if (!match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01))) ||
567 !match(Op1, m_SpecificInt(Len - 8)))
568 return false;
569
570 Value *Root = matchPopCountBytes(MulOp0, Len, I.getDataLayout());
571 if (!Root)
572 return false;
573
574 replaceWithPopCount(I, Root);
575 return true;
576}
577
578// Try to recognize below function as popcount intrinsic.
579// Ref. Hacker Delights
580// int popcount32(unsigned int i) {
581// uWord = (uWord & 0x55555555) + ((uWord>>1) & 0x55555555);
582// uWord = (uWord & 0x33333333) + ((uWord>>2) & 0x33333333);
583// uWord = (uWord & 0x0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F);
584// uWord = (uWord & 0x00FF00FF) + ((uWord>>8) & 0x00FF00FF);
585// return (uWord & 0x0000FFFF) + (uWord>>16);
586// }
587// int popcount64(unsigned long i) {
588// uWord = (uWord & 0x5555555555555555) + ((uWord>>1) & 0x5555555555555555);
589// uWord = (uWord & 0x3333333333333333) + ((uWord>>2) & 0x3333333333333333);
590// uWord = (uWord & 0x0F0F0F0F0F0F0F0F) + ((uWord>>4) & 0x0F0F0F0F0F0F0F0F);
591// uWord = (uWord & 0x00FF00FF00FF00FF) + ((uWord>>8) & 0x00FF00FF00FF00FF);
592// uWord = (uWord & 0x0000FFFF0000FFFF) + ((uWord>>16) & 0x0000FFFF0000FFFF);
593// return (uWord & 0x00000000FFFFFFFF) + (uWord>>32) & 0x00000000FFFFFFFF;
594// }
595//
596// InstCombine may narrow AND masks when it can prove the removed bits are
597// known zero (e.g. 0x0F0F0F0F -> 0x07070707). We accept such narrowed masks
598// by checking they are subsets of the expected masks and verifying the missing
599// bits are known zero via MaskedValueIsZero.
601 if (I.getOpcode() != Instruction::Add)
602 return false;
603
604 Type *Ty = I.getType();
605 if (!Ty->isIntOrIntVectorTy())
606 return false;
607
608 unsigned Len = Ty->getScalarSizeInBits();
609 if (Len > 64 || Len <= 8 || Len % 8 != 0)
610 return false;
611
612 // Len should be a power of 2 for the loop to work correctly
613 if (!isPowerOf2_32(Len))
614 return false;
615
616 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55));
617 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33));
618
619 SimplifyQuery SQ(I.getDataLayout());
620
621 // Check if CapturedMask is a valid (possibly narrowed) version of
622 // ExpectedMask for the given Operand. Returns true if the masks match
623 // exactly, or if CapturedMask is a subset and the missing bits are
624 // known zero in the Operand.
625 auto isValidNarrowedMask = [&](const APInt &CapturedMask,
626 const APInt &ExpectedMask,
627 Value *Operand) -> bool {
628 if (CapturedMask == ExpectedMask)
629 return true;
630 if (!CapturedMask.isSubsetOf(ExpectedMask))
631 return false;
632 APInt NeededMask = ExpectedMask & ~CapturedMask;
633 return MaskedValueIsZero(Operand, NeededMask, SQ);
634 };
635
636 // For "(x & M) + ((x >> S) & M)" patterns, both AND masks may be narrowed.
637 // Require subsets of BaseMask and prove any implied missing bits are zero.
638 auto narrowAddPairMasksOk = [&](const APInt &BaseMask, unsigned ShiftAmt,
639 Value *Val, const APInt &AndMask1,
640 const APInt &AndMask2) -> bool {
641 if (!AndMask1.isSubsetOf(BaseMask) || !AndMask2.isSubsetOf(BaseMask))
642 return false;
643 APInt NeededShifted = (BaseMask & ~AndMask1).shl(ShiftAmt);
644 APInt NeededUnshifted = BaseMask & ~AndMask2;
645 APInt AllNeeded = NeededShifted | NeededUnshifted;
646 return AllNeeded.isZero() || MaskedValueIsZero(Val, AllNeeded, SQ);
647 };
648
649 Value *ShiftOp;
650 Value *Start = &I;
651 for (unsigned I = Len; I >= 8; I = I / 2) {
652 APInt Mask = APInt::getSplat(Len, APInt::getLowBitsSet(I, I / 2));
653 const APInt *AndMask1 = nullptr, *AndMask2 = nullptr;
654
655 // Matching "(uWord & Mask) + ((uWord>>I/2) & Mask)".
656 // Both masks might have been narrowed by InstCombine.
657 if (match(Start,
658 m_c_Add(m_And(m_LShr(m_Value(ShiftOp), m_SpecificInt(I / 2)),
659 m_APInt(AndMask1)),
660 m_And(m_Deferred(ShiftOp), m_APInt(AndMask2))))) {
661 if (!narrowAddPairMasksOk(Mask, I / 2, ShiftOp, *AndMask1, *AndMask2))
662 return false;
663 }
664 // Matching "(uWord & Mask) + (uWord>>I/2)".
665 // The mask might have been narrowed by InstCombine.
666 else if (match(Start,
667 m_c_Add(m_LShr(m_Value(ShiftOp), m_SpecificInt(I / 2)),
668 m_And(m_Deferred(ShiftOp), m_APInt(AndMask1))))) {
669 if (!isValidNarrowedMask(*AndMask1, Mask, ShiftOp))
670 return false;
671 } else
672 return false;
673 Start = ShiftOp;
674 }
675
676 // Matching "uWord = (uWord & Mask33) + ((uWord>>2) & Mask33)".
677 const APInt *AndMask1 = nullptr, *AndMask2 = nullptr;
678 if (!match(Start, m_c_Add(m_And(m_LShr(m_Value(ShiftOp), m_SpecificInt(2)),
679 m_APInt(AndMask1)),
680 m_And(m_Deferred(ShiftOp), m_APInt(AndMask2)))))
681 return false;
682 if (!narrowAddPairMasksOk(Mask33, 2, ShiftOp, *AndMask1, *AndMask2))
683 return false;
684
685 Start = ShiftOp;
686 Value *Root;
687 // Matching "uWord = (uWord & Mask55) + ((uWord>>1) & Mask55)".
688 AndMask1 = nullptr;
689 AndMask2 = nullptr;
690 if (!match(Start, m_c_Add(m_And(m_LShr(m_Value(Root), m_SpecificInt(1)),
691 m_APInt(AndMask1)),
692 m_And(m_Deferred(Root), m_APInt(AndMask2)))))
693 return false;
694 if (!narrowAddPairMasksOk(Mask55, 1, Root, *AndMask1, *AndMask2))
695 return false;
696
697 replaceWithPopCount(I, Root);
698 return true;
699}
700
701// Try to recognize below function as popcount intrinsic.
702// Ref. Hackers Delight
703// int popcnt(unsigned x) {
704// x = x - ((x >> 1) & 0x55555555);
705// x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
706// x = (x + (x >> 4)) & 0x0F0F0F0F;
707// x = x + (x >> 8);
708// x = x + (x >> 16);
709// return x & 0x0000003F;
710// }
711
712// int popcnt(unsigned x) {
713// x = x - ((x >> 1) & 0x55555555);
714// x = x - 3*((x >> 2) & 0x33333333);
715// x = (x + (x >> 4)) & 0x0F0F0F0F;
716// x = x + (x >> 8);
717// x = x + (x >> 16);
718// return x & 0x0000003F;
719// }
721 if (I.getOpcode() != Instruction::And)
722 return false;
723
724 Type *Ty = I.getType();
725 if (!Ty->isIntOrIntVectorTy())
726 return false;
727
728 unsigned Len = Ty->getScalarSizeInBits();
729 Value *Add1;
730 if (Len == 8) {
731 // Special case for Len == 8, we only need to match the And at the end of
732 // matchPopCountBytes.
733 Add1 = &I;
734 } else {
735 const APInt *MaskRes;
736 if (!match(&I, m_And(m_Value(Add1), m_APInt(MaskRes))))
737 return false;
738
739 // Since `(trunc (and x, C))` might be canonicalized into `(and (trunc x),
740 // C)` we might loose the opportunity to recognize `(trunc (popcount y))`.
741 // The following block tries to capture such truncation, update `Len`, and
742 // append the truncation at the end of the emitting popcount, if there is
743 // any.
744 Value *TruncSrc;
745 if (match(Add1, m_OneUse(m_Trunc(m_Value(TruncSrc))))) {
746 Add1 = TruncSrc;
747 Len = Add1->getType()->getScalarSizeInBits();
748 }
749
750 if (Len > 64 || Len <= 8 || Len % 8 != 0)
751 return false;
752
753 // Len should be a power of 2 for the loop to work correctly
754 if (!isPowerOf2_32(Len))
755 return false;
756
757 // Number of bits needed to represent Len.
758 unsigned NumLenBits = Log2_32(Len) + 1;
759 // The "mask" here really only needs to fulfill two conditions:
760 // (1) All ones for the lower NumLenBits-bits
761 // (2) Zeros from bit 8 and onward.
762 // Condition (1) is straightforward. The reason behind condition
763 // (2) is that we don't care any 8-bit chunks but the first one
764 // in the original divide-and-conquer algorithm.
765 if (MaskRes->countTrailingOnes() < NumLenBits ||
766 MaskRes->getActiveBits() > 8)
767 return false;
768
769 for (unsigned I = Len; I >= 16; I = I / 2) {
770 Value *Add2;
771 // Matching "x = x + (x >> I/2)" for I-bit.
772 if (!match(Add1, m_c_Add(m_LShr(m_Value(Add2), m_SpecificInt(I / 2)),
773 m_Deferred(Add2))))
774 return false;
775 Add1 = Add2;
776 }
777 }
778
779 Value *Root = matchPopCountBytes(Add1, Len, I.getDataLayout());
780 if (!Root)
781 return false;
782
783 replaceWithPopCount(I, Root);
784 return true;
785}
786
787/// Fold smin(smax(fptosi(x), C1), C2) to llvm.fptosi.sat(x), providing C1 and
788/// C2 saturate the value of the fp conversion. The transform is not reversable
789/// as the fptosi.sat is more defined than the input - all values produce a
790/// valid value for the fptosi.sat, where as some produce poison for original
791/// that were out of range of the integer conversion. The reversed pattern may
792/// use fmax and fmin instead. As we cannot directly reverse the transform, and
793/// it is not always profitable, we make it conditional on the cost being
794/// reported as lower by TTI.
796 // Look for min(max(fptosi, converting to fptosi_sat.
797 Value *In;
798 const APInt *MinC, *MaxC;
800 m_APInt(MinC))),
801 m_APInt(MaxC))) &&
803 m_APInt(MaxC))),
804 m_APInt(MinC))))
805 return false;
806
807 // Check that the constants clamp a saturate.
808 if (!(*MinC + 1).isPowerOf2() || -*MaxC != *MinC + 1)
809 return false;
810
811 Type *IntTy = I.getType();
812 Type *FpTy = In->getType();
813 Type *SatTy =
814 IntegerType::get(IntTy->getContext(), (*MinC + 1).exactLogBase2() + 1);
815 if (auto *VecTy = dyn_cast<VectorType>(IntTy))
816 SatTy = VectorType::get(SatTy, VecTy->getElementCount());
817
818 // Get the cost of the intrinsic, and check that against the cost of
819 // fptosi+smin+smax
820 InstructionCost SatCost = TTI.getIntrinsicInstrCost(
821 IntrinsicCostAttributes(Intrinsic::fptosi_sat, SatTy, {In}, {FpTy}),
823 SatCost += TTI.getCastInstrCost(Instruction::SExt, IntTy, SatTy,
826
827 InstructionCost MinMaxCost = TTI.getCastInstrCost(
828 Instruction::FPToSI, IntTy, FpTy, TTI::CastContextHint::None,
830 MinMaxCost += TTI.getIntrinsicInstrCost(
831 IntrinsicCostAttributes(Intrinsic::smin, IntTy, {IntTy}),
833 MinMaxCost += TTI.getIntrinsicInstrCost(
834 IntrinsicCostAttributes(Intrinsic::smax, IntTy, {IntTy}),
836
837 if (SatCost >= MinMaxCost)
838 return false;
839
840 IRBuilder<> Builder(&I);
841 Value *Sat =
842 Builder.CreateIntrinsic(Intrinsic::fptosi_sat, {SatTy, FpTy}, In);
843 I.replaceAllUsesWith(Builder.CreateSExt(Sat, IntTy));
844 return true;
845}
846
847/// Try to replace a mathlib call to sqrt with the LLVM intrinsic. This avoids
848/// pessimistic codegen that has to account for setting errno and can enable
849/// vectorization.
850static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI,
852 DominatorTree &DT) {
853 // If (1) this is a sqrt libcall, (2) we can assume that NAN is not created
854 // (because NNAN or the operand arg must not be less than -0.0) and (2) we
855 // would not end up lowering to a libcall anyway (which could change the value
856 // of errno), then:
857 // (1) errno won't be set.
858 // (2) it is safe to convert this to an intrinsic call.
859 Type *Ty = Call->getType();
860 Value *Arg = Call->getArgOperand(0);
861 if (TTI.haveFastSqrt(Ty) &&
862 (Call->hasNoNaNs() ||
864 Arg, SimplifyQuery(Call->getDataLayout(), &TLI, &DT, &AC, Call)))) {
865 IRBuilder<> Builder(Call);
866 Value *NewSqrt =
867 Builder.CreateIntrinsic(Intrinsic::sqrt, Ty, Arg, Call, "sqrt");
868 Call->replaceAllUsesWith(NewSqrt);
869
870 // Explicitly erase the old call because a call with side effects is not
871 // trivially dead.
872 Call->eraseFromParent();
873 return true;
874 }
875
876 return false;
877}
878
879// Check if this array of constants represents a cttz table.
880// Iterate over the elements from \p Table by trying to find/match all
881// the numbers from 0 to \p InputBits that should represent cttz results.
882static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift,
883 const APInt &AndMask, Type *AccessTy,
884 unsigned InputBits, const APInt &GEPIdxFactor,
885 const DataLayout &DL) {
886 for (unsigned Idx = 0; Idx < InputBits; Idx++) {
887 APInt Index =
888 (APInt::getOneBitSet(InputBits, Idx) * Mul).lshr(Shift) & AndMask;
890 ConstantFoldLoadFromConst(Table, AccessTy, Index * GEPIdxFactor, DL));
891 if (!C || C->getValue() != Idx)
892 return false;
893 }
894
895 return true;
896}
897
898// Try to recognize table-based ctz implementation.
899// E.g., an example in C (for more cases please see the llvm/tests):
900// int f(unsigned x) {
901// static const char table[32] =
902// {0, 1, 28, 2, 29, 14, 24, 3, 30,
903// 22, 20, 15, 25, 17, 4, 8, 31, 27,
904// 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
905// return table[((unsigned)((x & -x) * 0x077CB531U)) >> 27];
906// }
907// this can be lowered to `cttz` instruction.
908// There is also a special case when the element is 0.
909//
910// The (x & -x) sets the lowest non-zero bit to 1. The multiply is a de-bruijn
911// sequence that contains each pattern of bits in it. The shift extracts
912// the top bits after the multiply, and that index into the table should
913// represent the number of trailing zeros in the original number.
914//
915// Here are some examples or LLVM IR for a 64-bit target:
916//
917// CASE 1:
918// %sub = sub i32 0, %x
919// %and = and i32 %sub, %x
920// %mul = mul i32 %and, 125613361
921// %shr = lshr i32 %mul, 27
922// %idxprom = zext i32 %shr to i64
923// %arrayidx = getelementptr inbounds [32 x i8], [32 x i8]* @ctz1.table, i64 0,
924// i64 %idxprom
925// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
926//
927// CASE 2:
928// %sub = sub i32 0, %x
929// %and = and i32 %sub, %x
930// %mul = mul i32 %and, 72416175
931// %shr = lshr i32 %mul, 26
932// %idxprom = zext i32 %shr to i64
933// %arrayidx = getelementptr inbounds [64 x i16], [64 x i16]* @ctz2.table,
934// i64 0, i64 %idxprom
935// %0 = load i16, i16* %arrayidx, align 2, !tbaa !8
936//
937// CASE 3:
938// %sub = sub i32 0, %x
939// %and = and i32 %sub, %x
940// %mul = mul i32 %and, 81224991
941// %shr = lshr i32 %mul, 27
942// %idxprom = zext i32 %shr to i64
943// %arrayidx = getelementptr inbounds [32 x i32], [32 x i32]* @ctz3.table,
944// i64 0, i64 %idxprom
945// %0 = load i32, i32* %arrayidx, align 4, !tbaa !8
946//
947// CASE 4:
948// %sub = sub i64 0, %x
949// %and = and i64 %sub, %x
950// %mul = mul i64 %and, 283881067100198605
951// %shr = lshr i64 %mul, 58
952// %arrayidx = getelementptr inbounds [64 x i8], [64 x i8]* @table, i64 0,
953// i64 %shr
954// %0 = load i8, i8* %arrayidx, align 1, !tbaa !8
955//
956// All these can be lowered to @llvm.cttz.i32/64 intrinsics.
957//
958// This shares its initial match (load from a GEP into a constant table with
959// a single variable index) with tryToRecognizeTableBasedLog2() below; see
960// tryToRecognizeTableBasedCttzOrLog2().
961static bool tryToRecognizeTableBasedCttz(LoadInst *LI, Type *AccessType,
962 GlobalVariable *GVTable, Value *GepIdx,
963 const APInt &GEPScale,
964 const DataLayout &DL) {
965 Value *X1;
966 const APInt *MulConst, *ShiftConst, *AndCst = nullptr;
967 // Check that the gep variable index is ((x & -x) * MulConst) >> ShiftConst.
968 // This might be extended to the pointer index type, and if the gep index type
969 // has been replaced with an i8 then a new And (and different ShiftConst) will
970 // be present.
971 auto MatchInner = m_LShr(
972 m_Mul(m_c_And(m_Neg(m_Value(X1)), m_Deferred(X1)), m_APInt(MulConst)),
973 m_APInt(ShiftConst));
974 if (!match(GepIdx, m_CastOrSelf(MatchInner)) &&
975 !match(GepIdx, m_CastOrSelf(m_And(MatchInner, m_APInt(AndCst)))))
976 return false;
977
978 unsigned InputBits = X1->getType()->getScalarSizeInBits();
979 if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128)
980 return false;
981
982 if (!GEPScale.isIntN(InputBits) ||
983 !isCTTZTable(GVTable->getInitializer(), *MulConst, *ShiftConst,
984 AndCst ? *AndCst : APInt::getAllOnes(InputBits), AccessType,
985 InputBits, GEPScale.zextOrTrunc(InputBits), DL))
986 return false;
987
988 ConstantInt *ZeroTableElem = cast<ConstantInt>(
989 ConstantFoldLoadFromConst(GVTable->getInitializer(), AccessType, DL));
990 bool DefinedForZero = ZeroTableElem->getZExtValue() == InputBits;
991
992 IRBuilder<> B(LI);
993 ConstantInt *BoolConst = B.getInt1(!DefinedForZero);
994 Type *XType = X1->getType();
995 auto Cttz = B.CreateIntrinsic(Intrinsic::cttz, {XType}, {X1, BoolConst});
996 Value *ZExtOrTrunc = nullptr;
997
998 if (DefinedForZero) {
999 ZExtOrTrunc = B.CreateZExtOrTrunc(Cttz, AccessType);
1000 } else {
1001 // If the value in elem 0 isn't the same as InputBits, we still want to
1002 // produce the value from the table.
1003 auto Cmp = B.CreateICmpEQ(X1, ConstantInt::get(XType, 0));
1004 auto Select = B.CreateSelect(Cmp, B.CreateZExt(ZeroTableElem, XType), Cttz);
1005
1006 // The true branch of select handles the cttz(0) case, which is rare.
1009 SelectI->setMetadata(
1010 LLVMContext::MD_prof,
1011 MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights());
1012 }
1013
1014 // NOTE: If the table[0] is 0, but the cttz(0) is defined by the Target
1015 // it should be handled as: `cttz(x) & (typeSize - 1)`.
1016
1017 ZExtOrTrunc = B.CreateZExtOrTrunc(Select, AccessType);
1018 }
1019
1020 LI->replaceAllUsesWith(ZExtOrTrunc);
1021
1022 return true;
1023}
1024
1025// Check if this array of constants represents a log2 table.
1026// Iterate over the elements from \p Table by trying to find/match all
1027// the numbers from 0 to \p InputBits that should represent log2 results.
1028static bool isLog2Table(Constant *Table, const APInt &Mul, const APInt &Shift,
1029 Type *AccessTy, unsigned InputBits,
1030 const APInt &GEPIdxFactor, const DataLayout &DL) {
1031 for (unsigned Idx = 0; Idx < InputBits; Idx++) {
1032 APInt Index = (APInt::getLowBitsSet(InputBits, Idx + 1) * Mul).lshr(Shift);
1034 ConstantFoldLoadFromConst(Table, AccessTy, Index * GEPIdxFactor, DL));
1035 if (!C || C->getValue() != Idx)
1036 return false;
1037 }
1038
1039 // Verify that an input of zero will select table index 0.
1040 APInt ZeroIndex = Mul.lshr(Shift);
1041 if (!ZeroIndex.isZero())
1042 return false;
1043
1044 return true;
1045}
1046
1047// Try to recognize table-based log2 implementation.
1048// E.g., an example in C (for more cases please the llvm/tests):
1049// int f(unsigned v) {
1050// static const char table[32] =
1051// {0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
1052// 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31};
1053//
1054// v |= v >> 1; // first round down to one less than a power of 2
1055// v |= v >> 2;
1056// v |= v >> 4;
1057// v |= v >> 8;
1058// v |= v >> 16;
1059//
1060// return table[(unsigned)(v * 0x07C4ACDDU) >> 27];
1061// }
1062// this can be lowered to `ctlz` instruction.
1063// There is also a special case when the element is 0.
1064//
1065// The >> and |= sequence sets all bits below the most significant set bit. The
1066// multiply is a de-bruijn sequence that contains each pattern of bits in it.
1067// The shift extracts the top bits after the multiply, and that index into the
1068// table should represent the floor log base 2 of the original number.
1069//
1070// Here are some examples of LLVM IR for a 64-bit target.
1071//
1072// CASE 1:
1073// %shr = lshr i32 %v, 1
1074// %or = or i32 %shr, %v
1075// %shr1 = lshr i32 %or, 2
1076// %or2 = or i32 %shr1, %or
1077// %shr3 = lshr i32 %or2, 4
1078// %or4 = or i32 %shr3, %or2
1079// %shr5 = lshr i32 %or4, 8
1080// %or6 = or i32 %shr5, %or4
1081// %shr7 = lshr i32 %or6, 16
1082// %or8 = or i32 %shr7, %or6
1083// %mul = mul i32 %or8, 130329821
1084// %shr9 = lshr i32 %mul, 27
1085// %idxprom = zext nneg i32 %shr9 to i64
1086// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %idxprom
1087// %0 = load i8, ptr %arrayidx, align 1
1088//
1089// CASE 2:
1090// %shr = lshr i64 %v, 1
1091// %or = or i64 %shr, %v
1092// %shr1 = lshr i64 %or, 2
1093// %or2 = or i64 %shr1, %or
1094// %shr3 = lshr i64 %or2, 4
1095// %or4 = or i64 %shr3, %or2
1096// %shr5 = lshr i64 %or4, 8
1097// %or6 = or i64 %shr5, %or4
1098// %shr7 = lshr i64 %or6, 16
1099// %or8 = or i64 %shr7, %or6
1100// %shr9 = lshr i64 %or8, 32
1101// %or10 = or i64 %shr9, %or8
1102// %mul = mul i64 %or10, 285870213051386505
1103// %shr11 = lshr i64 %mul, 58
1104// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr11
1105// %0 = load i8, ptr %arrayidx, align 1
1106//
1107// CASE 3:
1108// A variant where the most-significant set bit of the OR-cascade result is
1109// isolated via subtraction before the multiply, i.e.
1110// table[((v - (v >> 1)) * MulConst) >> ShiftConst], analogous to how the
1111// cttz pattern isolates the least-significant set bit via `x & -x`:
1112//
1113// %shr = lshr i64 %v, 1
1114// %or = or i64 %shr, %v
1115// ... (rest of the OR-cascade, as above) ...
1116// %shr11 = lshr i64 %or10, 1
1117// %sub = sub i64 %or10, %shr11
1118// %mul = mul i64 %sub, 571347909858961602
1119// %shr12 = lshr i64 %mul, 58
1120// %arrayidx = getelementptr inbounds i8, ptr @table, i64 %shr12
1121// %0 = load i8, ptr %arrayidx, align 1
1122//
1123// All these can be lowered to @llvm.ctlz.i32/64 intrinsics and a subtract.
1124//
1125// This shares its initial match (load from a GEP into a constant table with
1126// a single variable index) with tryToRecognizeTableBasedCttz() above; see
1127// tryToRecognizeTableBasedCttzOrLog2().
1128static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType,
1129 GlobalVariable *GVTable, Value *GepIdx,
1130 const APInt &GEPScale,
1131 const DataLayout &DL,
1133 Value *X;
1134 const APInt *MulConst, *ShiftConst;
1135 // Check that the gep variable index is (x * MulConst) >> ShiftConst.
1136 auto MatchInner =
1137 m_LShr(m_Mul(m_Value(X), m_APInt(MulConst)), m_APInt(ShiftConst));
1138 if (!match(GepIdx, m_CastOrSelf(MatchInner)))
1139 return false;
1140
1141 // The multiplied value may instead be the OR-cascade result with its
1142 // most-significant set bit isolated first via `v - (v >> 1)`: since every
1143 // bit below the MSB of an OR-cascade result is 1, this subtraction leaves
1144 // just the MSB, mirroring how tryToRecognizeTableBasedCttz() isolates the
1145 // least-significant set bit via `x & -x`.
1146 bool IsolatedMSB = false;
1147 Value *V;
1148 if (match(X, m_Sub(m_Value(V), m_LShr(m_Deferred(V), m_SpecificInt(1))))) {
1149 IsolatedMSB = true;
1150 X = V;
1151 }
1152
1153 unsigned InputBits = X->getType()->getScalarSizeInBits();
1154 if (InputBits != 16 && InputBits != 32 && InputBits != 64 && InputBits != 128)
1155 return false;
1156
1157 // Verify shift amount.
1158 // TODO: Allow other shift amounts when we have proper test coverage.
1159 if (*ShiftConst != InputBits - Log2_32(InputBits))
1160 return false;
1161
1162 // Match the sequence of OR operations with right shifts by powers of 2.
1163 for (unsigned ShiftAmt = InputBits / 2; ShiftAmt != 0; ShiftAmt /= 2) {
1164 Value *Y;
1165 if (!match(X, m_c_Or(m_LShr(m_Value(Y), m_SpecificInt(ShiftAmt)),
1166 m_Deferred(Y))))
1167 return false;
1168 X = Y;
1169 }
1170
1171 if (!GEPScale.isIntN(InputBits))
1172 return false;
1173
1174 if (IsolatedMSB) {
1175 // With the MSB isolated, the multiplicand for an input whose MSB is at bit
1176 // Idx is a single set bit rather than a run of low bits, which is exactly
1177 // what isCTTZTable() checks for (there is no additional masking here, so
1178 // pass an all-ones mask).
1179 if (!isCTTZTable(GVTable->getInitializer(), *MulConst, *ShiftConst,
1180 APInt::getAllOnes(InputBits), AccessType, InputBits,
1181 GEPScale.zextOrTrunc(InputBits), DL))
1182 return false;
1183 } else {
1184 if (!isLog2Table(GVTable->getInitializer(), *MulConst, *ShiftConst,
1185 AccessType, InputBits, GEPScale.zextOrTrunc(InputBits),
1186 DL))
1187 return false;
1188 }
1189
1190 ConstantInt *ZeroTableElem = cast<ConstantInt>(
1191 ConstantFoldLoadFromConst(GVTable->getInitializer(), AccessType, DL));
1192
1193 // Use InputBits - 1 - ctlz(X) to compute log2(X).
1194 IRBuilder<> B(LI);
1195 ConstantInt *BoolConst = B.getTrue();
1196 Type *XType = X->getType();
1197
1198 // Check the the backend has an efficient ctlz instruction.
1199 // FIXME: Teach the backend to emit the original code when ctlz isn't
1200 // supported like we do for cttz.
1202 Intrinsic::ctlz, XType,
1203 {PoisonValue::get(XType), /*is_zero_poison=*/BoolConst});
1204 InstructionCost Cost =
1205 TTI.getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
1207 return false;
1208
1209 Constant *InputBitsM1 = ConstantInt::get(XType, InputBits - 1);
1210
1211 Value *Result;
1212 if (ZeroTableElem->getZExtValue() == InputBits - 1) {
1213 Value *Ctlz =
1214 B.CreateIntrinsic(Intrinsic::ctlz, {XType}, {X, B.getFalse()});
1215 Result = B.CreateAnd(B.CreateNot(Ctlz), InputBitsM1);
1216 } else {
1217 Value *Ctlz = B.CreateIntrinsic(Intrinsic::ctlz, {XType}, {X, BoolConst});
1218 Value *Sub = B.CreateSub(InputBitsM1, Ctlz);
1219
1220 // The table won't produce a sensible result for 0.
1221 Value *Cmp = B.CreateICmpEQ(X, ConstantInt::get(XType, 0));
1222 Value *Select =
1223 B.CreateSelect(Cmp, B.CreateZExt(ZeroTableElem, XType), Sub);
1224
1225 // The true branch of select handles the log2(0) case, which is rare.
1228 SelectI->setMetadata(
1229 LLVMContext::MD_prof,
1230 MDBuilder(SelectI->getContext()).createUnlikelyBranchWeights());
1231 }
1232
1233 Result = Select;
1234 }
1235
1236 Value *ZExtOrTrunc = B.CreateZExtOrTrunc(Result, AccessType);
1237
1238 LI->replaceAllUsesWith(ZExtOrTrunc);
1239
1240 return true;
1241}
1242
1243// Match a table-based cttz or log2 implementation. These patterns share a
1244// load from a global table pattern that we match first. Then we try the
1245// specific matches for the cttz and log2 patterns.
1247 const DataLayout &DL,
1250 if (!LI)
1251 return false;
1252
1253 Type *AccessType = LI->getType();
1254 if (!AccessType->isIntegerTy())
1255 return false;
1256
1258 if (!GEP || !GEP->hasNoUnsignedSignedWrap())
1259 return false;
1260
1261 GlobalVariable *GVTable = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
1262 if (!GVTable || !GVTable->hasInitializer() || !GVTable->isConstant())
1263 return false;
1264
1265 unsigned BW = DL.getIndexTypeSizeInBits(GEP->getType());
1266 APInt ModOffset(BW, 0);
1268 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset) ||
1269 VarOffsets.size() != 1 || ModOffset != 0)
1270 return false;
1271 auto [GepIdx, GEPScale] = VarOffsets.front();
1272
1273 if (tryToRecognizeTableBasedCttz(LI, AccessType, GVTable, GepIdx, GEPScale,
1274 DL))
1275 return true;
1276
1277 return tryToRecognizeTableBasedLog2(LI, AccessType, GVTable, GepIdx, GEPScale,
1278 DL, TTI);
1279}
1280
1281/// This is used by foldLoadsRecursive() to capture a Root Load node which is
1282/// of type or(load, load) and recursively build the wide load. Also capture the
1283/// shift amount, zero extend type and loadSize.
1293
1294// Identify and Merge consecutive loads recursively which is of the form
1295// (ZExt(L1) << shift1) | (ZExt(L2) << shift2) -> ZExt(L3) << shift1
1296// (ZExt(L1) << shift1) | ZExt(L2) -> ZExt(L3)
1297static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL,
1298 AliasAnalysis &AA, bool IsRoot = false) {
1299 uint64_t ShAmt2;
1300 Value *X;
1301 Instruction *L1, *L2;
1302
1303 // For the root instruction, allow multiple uses since the final result
1304 // may legitimately be used in multiple places. For intermediate values,
1305 // require single use to avoid creating duplicate loads.
1306 if (!IsRoot && !V->hasOneUse())
1307 return false;
1308
1309 if (!match(V, m_c_Or(m_Value(X),
1311 ShAmt2)))))
1312 return false;
1313
1314 if (!foldLoadsRecursive(X, LOps, DL, AA, /*IsRoot=*/false) && LOps.FoundRoot)
1315 // Avoid Partial chain merge.
1316 return false;
1317
1318 // Check if the pattern has loads
1319 LoadInst *LI1 = LOps.Root;
1320 uint64_t ShAmt1 = LOps.Shift;
1321 if (LOps.FoundRoot == false &&
1322 match(X, m_OneUse(
1323 m_ShlOrSelf(m_OneUse(m_ZExt(m_Instruction(L1))), ShAmt1)))) {
1324 LI1 = dyn_cast<LoadInst>(L1);
1325 }
1326 LoadInst *LI2 = dyn_cast<LoadInst>(L2);
1327
1328 // Check if loads are same, atomic, volatile and having same address space.
1329 if (LI1 == LI2 || !LI1 || !LI2 || !LI1->isSimple() || !LI2->isSimple() ||
1331 return false;
1332
1333 // Check if Loads come from same BB.
1334 if (LI1->getParent() != LI2->getParent())
1335 return false;
1336
1337 // Find the data layout
1338 bool IsBigEndian = DL.isBigEndian();
1339
1340 // Check if loads are consecutive and same size.
1341 Value *Load1Ptr = LI1->getPointerOperand();
1342 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
1343 Load1Ptr =
1344 Load1Ptr->stripAndAccumulateConstantOffsets(DL, Offset1,
1345 /* AllowNonInbounds */ true);
1346
1347 Value *Load2Ptr = LI2->getPointerOperand();
1348 APInt Offset2(DL.getIndexTypeSizeInBits(Load2Ptr->getType()), 0);
1349 Load2Ptr =
1350 Load2Ptr->stripAndAccumulateConstantOffsets(DL, Offset2,
1351 /* AllowNonInbounds */ true);
1352
1353 // Verify if both loads have same base pointers
1354 uint64_t LoadSize1 = LI1->getType()->getPrimitiveSizeInBits();
1355 uint64_t LoadSize2 = LI2->getType()->getPrimitiveSizeInBits();
1356 if (Load1Ptr != Load2Ptr)
1357 return false;
1358
1359 // Make sure that there are no padding bits.
1360 if (!DL.typeSizeEqualsStoreSize(LI1->getType()) ||
1361 !DL.typeSizeEqualsStoreSize(LI2->getType()))
1362 return false;
1363
1364 // Alias Analysis to check for stores b/w the loads.
1365 LoadInst *Start = LOps.FoundRoot ? LOps.RootInsert : LI1, *End = LI2;
1367 if (!Start->comesBefore(End)) {
1368 std::swap(Start, End);
1369 // If LOps.RootInsert comes after LI2, since we use LI2 as the new insert
1370 // point, we should make sure whether the memory region accessed by LOps
1371 // isn't modified.
1372 if (LOps.FoundRoot)
1374 LOps.Root->getPointerOperand(),
1375 LocationSize::precise(DL.getTypeStoreSize(
1376 IntegerType::get(LI1->getContext(), LOps.LoadSize))),
1377 LOps.AATags);
1378 else
1379 Loc = MemoryLocation::get(End);
1380 } else
1381 Loc = MemoryLocation::get(End);
1382 unsigned NumScanned = 0;
1383 for (Instruction &Inst :
1384 make_range(Start->getIterator(), End->getIterator())) {
1385 if (Inst.mayWriteToMemory() && isModSet(AA.getModRefInfo(&Inst, Loc)))
1386 return false;
1387
1388 if (++NumScanned > MaxInstrsToScan)
1389 return false;
1390 }
1391
1392 // Make sure Load with lower Offset is at LI1
1393 bool Reverse = false;
1394 if (Offset2.slt(Offset1)) {
1395 std::swap(LI1, LI2);
1396 std::swap(ShAmt1, ShAmt2);
1397 std::swap(Offset1, Offset2);
1398 std::swap(Load1Ptr, Load2Ptr);
1399 std::swap(LoadSize1, LoadSize2);
1400 Reverse = true;
1401 }
1402
1403 // Big endian swap the shifts
1404 if (IsBigEndian)
1405 std::swap(ShAmt1, ShAmt2);
1406
1407 // First load is always LI1. This is where we put the new load.
1408 // Use the merged load size available from LI1 for forward loads.
1409 if (LOps.FoundRoot) {
1410 if (!Reverse)
1411 LoadSize1 = LOps.LoadSize;
1412 else
1413 LoadSize2 = LOps.LoadSize;
1414 }
1415
1416 // Verify if shift amount and load index aligns and verifies that loads
1417 // are consecutive.
1418 uint64_t ShiftDiff = IsBigEndian ? LoadSize2 : LoadSize1;
1419 uint64_t PrevSize =
1420 DL.getTypeStoreSize(IntegerType::get(LI1->getContext(), LoadSize1));
1421 if ((ShAmt2 - ShAmt1) != ShiftDiff || (Offset2 - Offset1) != PrevSize)
1422 return false;
1423
1424 // Reject if the combined size of the loads exceeds the target type size.
1425 // This avoids attempting to emit an invalid ZExt (from wider to narrower
1426 // type) when out-of-bounds shifts lead to matching too many loads.
1427 if (LoadSize1 + LoadSize2 > X->getType()->getScalarSizeInBits())
1428 return false;
1429
1430 // Update LOps
1431 AAMDNodes AATags1 = LOps.AATags;
1432 AAMDNodes AATags2 = LI2->getAAMetadata();
1433 if (LOps.FoundRoot == false) {
1434 LOps.FoundRoot = true;
1435 AATags1 = LI1->getAAMetadata();
1436 }
1437 LOps.LoadSize = LoadSize1 + LoadSize2;
1438 LOps.RootInsert = Start;
1439
1440 // Concatenate the AATags of the Merged Loads.
1441 LOps.AATags = AATags1.concat(AATags2);
1442
1443 LOps.Root = LI1;
1444 LOps.Shift = ShAmt1;
1445 LOps.ZextType = X->getType();
1446 return true;
1447}
1448
1449// For a given BB instruction, evaluate all loads in the chain that form a
1450// pattern which suggests that the loads can be combined. The one and only use
1451// of the loads is to form a wider load.
1454 const DominatorTree &DT) {
1455 // Only consider load chains of scalar values.
1456 if (isa<VectorType>(I.getType()))
1457 return false;
1458
1459 LoadOps LOps;
1460 if (!foldLoadsRecursive(&I, LOps, DL, AA, /*IsRoot=*/true) || !LOps.FoundRoot)
1461 return false;
1462
1463 IRBuilder<> Builder(&I);
1464 LoadInst *NewLoad = nullptr, *LI1 = LOps.Root;
1465
1466 IntegerType *WiderType = IntegerType::get(I.getContext(), LOps.LoadSize);
1467 // TTI based checks if we want to proceed with wider load
1468 bool Allowed = TTI.isTypeLegal(WiderType);
1469 if (!Allowed)
1470 return false;
1471
1472 unsigned AS = LI1->getPointerAddressSpace();
1473 unsigned Fast = 0;
1474 Allowed = TTI.allowsMisalignedMemoryAccesses(I.getContext(), LOps.LoadSize,
1475 AS, LI1->getAlign(), &Fast);
1476 if (!Allowed || !Fast)
1477 return false;
1478
1479 // Get the Index and Ptr for the new GEP.
1480 Value *Load1Ptr = LI1->getPointerOperand();
1481 Builder.SetInsertPoint(LOps.RootInsert);
1482 if (!DT.dominates(Load1Ptr, LOps.RootInsert)) {
1483 APInt Offset1(DL.getIndexTypeSizeInBits(Load1Ptr->getType()), 0);
1484 Load1Ptr = Load1Ptr->stripAndAccumulateConstantOffsets(
1485 DL, Offset1, /* AllowNonInbounds */ true);
1486 Load1Ptr = Builder.CreatePtrAdd(Load1Ptr, Builder.getInt(Offset1));
1487 }
1488 // Generate wider load.
1489 NewLoad = Builder.CreateAlignedLoad(WiderType, Load1Ptr, LI1->getAlign(),
1490 LI1->isVolatile(), "");
1491 NewLoad->takeName(LI1);
1492 // Set the New Load AATags Metadata.
1493 if (LOps.AATags)
1494 NewLoad->setAAMetadata(LOps.AATags);
1495
1496 Value *NewOp = NewLoad;
1497 // Zero extend if needed.
1498 NewOp = Builder.CreateZExt(NewOp, LOps.ZextType);
1499
1500 // Check if shift needed. We need to shift with the amount of load1
1501 // shift if not zero.
1502 if (LOps.Shift)
1503 NewOp = Builder.CreateShl(NewOp, LOps.Shift);
1504 I.replaceAllUsesWith(NewOp);
1505
1506 return true;
1507}
1508
1509/// ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset.
1517
1518 bool isCompatibleWith(const PartStore &Other) const {
1519 return PtrBase == Other.PtrBase && Val == Other.Val;
1520 }
1521
1522 bool operator<(const PartStore &Other) const {
1523 return PtrOffset.slt(Other.PtrOffset);
1524 }
1525};
1526
1527static std::optional<PartStore> matchPartStore(Instruction &I,
1528 const DataLayout &DL) {
1529 auto *Store = dyn_cast<StoreInst>(&I);
1530 if (!Store || !Store->isSimple())
1531 return std::nullopt;
1532
1533 Value *StoredVal = Store->getValueOperand();
1534 Type *StoredTy = StoredVal->getType();
1535 if (!StoredTy->isIntegerTy() || !DL.typeSizeEqualsStoreSize(StoredTy))
1536 return std::nullopt;
1537
1538 uint64_t ValWidth = StoredTy->getPrimitiveSizeInBits();
1539 uint64_t ValOffset;
1540 Value *Val;
1541 if (!match(StoredVal, m_Trunc(m_LShrOrSelf(m_Value(Val), ValOffset))))
1542 return std::nullopt;
1543
1544 Value *Ptr = Store->getPointerOperand();
1545 APInt PtrOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
1547 DL, PtrOffset, /*AllowNonInbounds=*/true);
1548 return {{PtrBase, PtrOffset, Val, ValOffset, ValWidth, Store}};
1549}
1550
1552 unsigned Width, const DataLayout &DL,
1554 if (Parts.size() < 2)
1555 return false;
1556
1557 // Check whether combining the stores is profitable.
1558 // FIXME: We could generate smaller stores if we can't produce a large one.
1559 const PartStore &First = Parts.front();
1560 LLVMContext &Ctx = First.Store->getContext();
1561 Type *NewTy = Type::getIntNTy(Ctx, Width);
1562 unsigned Fast = 0;
1563 if (!TTI.isTypeLegal(NewTy) ||
1564 !TTI.allowsMisalignedMemoryAccesses(Ctx, Width,
1565 First.Store->getPointerAddressSpace(),
1566 First.Store->getAlign(), &Fast) ||
1567 !Fast)
1568 return false;
1569
1570 // Generate the combined store.
1571 IRBuilder<> Builder(First.Store);
1572 Value *Val = First.Val;
1573 if (First.ValOffset != 0)
1574 Val = Builder.CreateLShr(Val, First.ValOffset);
1575 Val = Builder.CreateZExtOrTrunc(Val, NewTy);
1576 StoreInst *Store = Builder.CreateAlignedStore(
1577 Val, First.Store->getPointerOperand(), First.Store->getAlign());
1578
1579 // Merge various metadata onto the new store.
1580 AAMDNodes AATags = First.Store->getAAMetadata();
1581 SmallVector<Instruction *> Stores = {First.Store};
1582 Stores.reserve(Parts.size());
1583 SmallVector<DebugLoc> DbgLocs = {First.Store->getDebugLoc()};
1584 DbgLocs.reserve(Parts.size());
1585 for (const PartStore &Part : drop_begin(Parts)) {
1586 AATags = AATags.concat(Part.Store->getAAMetadata());
1587 Stores.push_back(Part.Store);
1588 DbgLocs.push_back(Part.Store->getDebugLoc());
1589 }
1590 Store->setAAMetadata(AATags);
1591 Store->mergeDIAssignID(Stores);
1592 Store->setDebugLoc(DebugLoc::getMergedLocations(DbgLocs));
1593
1594 // Remove the old stores.
1595 for (const PartStore &Part : Parts)
1596 Part.Store->eraseFromParent();
1597
1598 return true;
1599}
1600
1603 if (Parts.size() < 2)
1604 return false;
1605
1606 // We now have multiple parts of the same value stored to the same pointer.
1607 // Sort the parts by pointer offset, and make sure they are consistent with
1608 // the value offsets. Also check that the value is fully covered without
1609 // overlaps.
1610 bool Changed = false;
1611 llvm::sort(Parts);
1612 int64_t LastEndOffsetFromFirst = 0;
1613 const PartStore *First = &Parts[0];
1614 for (const PartStore &Part : Parts) {
1615 APInt PtrOffsetFromFirst = Part.PtrOffset - First->PtrOffset;
1616 int64_t ValOffsetFromFirst = Part.ValOffset - First->ValOffset;
1617 if (PtrOffsetFromFirst * 8 != ValOffsetFromFirst ||
1618 LastEndOffsetFromFirst != ValOffsetFromFirst) {
1620 LastEndOffsetFromFirst, DL, TTI);
1621 First = &Part;
1622 LastEndOffsetFromFirst = Part.ValWidth;
1623 continue;
1624 }
1625
1626 LastEndOffsetFromFirst = ValOffsetFromFirst + Part.ValWidth;
1627 }
1628
1630 LastEndOffsetFromFirst, DL, TTI);
1631 return Changed;
1632}
1633
1636 // FIXME: Add big endian support.
1637 if (DL.isBigEndian())
1638 return false;
1639
1640 BatchAAResults BatchAA(AA);
1642 bool MadeChange = false;
1643 for (Instruction &I : make_early_inc_range(BB)) {
1644 if (std::optional<PartStore> Part = matchPartStore(I, DL)) {
1645 if (Parts.empty() || Part->isCompatibleWith(Parts[0])) {
1646 Parts.push_back(std::move(*Part));
1647 continue;
1648 }
1649
1650 MadeChange |= mergePartStores(Parts, DL, TTI);
1651 Parts.clear();
1652 Parts.push_back(std::move(*Part));
1653 continue;
1654 }
1655
1656 if (Parts.empty())
1657 continue;
1658
1659 if (I.mayThrow() ||
1660 (I.mayReadOrWriteMemory() &&
1662 &I, MemoryLocation::getBeforeOrAfter(Parts[0].PtrBase))))) {
1663 MadeChange |= mergePartStores(Parts, DL, TTI);
1664 Parts.clear();
1665 continue;
1666 }
1667 }
1668
1669 MadeChange |= mergePartStores(Parts, DL, TTI);
1670 return MadeChange;
1671}
1672
1673/// Combine away instructions providing they are still equivalent when compared
1674/// against 0. i.e do they have any bits set.
1676 auto *I = dyn_cast<Instruction>(V);
1677 if (!I || I->getOpcode() != Instruction::Or || !I->hasOneUse())
1678 return nullptr;
1679
1680 Value *A;
1681
1682 // Look deeper into the chain of or's, combining away shl (so long as they are
1683 // nuw or nsw).
1684 Value *Op0 = I->getOperand(0);
1685 if (match(Op0, m_CombineOr(m_NSWShl(m_Value(A), m_Value()),
1686 m_NUWShl(m_Value(A), m_Value()))))
1687 Op0 = A;
1688 else if (auto *NOp = optimizeShiftInOrChain(Op0, Builder))
1689 Op0 = NOp;
1690
1691 Value *Op1 = I->getOperand(1);
1692 if (match(Op1, m_CombineOr(m_NSWShl(m_Value(A), m_Value()),
1693 m_NUWShl(m_Value(A), m_Value()))))
1694 Op1 = A;
1695 else if (auto *NOp = optimizeShiftInOrChain(Op1, Builder))
1696 Op1 = NOp;
1697
1698 if (Op0 != I->getOperand(0) || Op1 != I->getOperand(1))
1699 return Builder.CreateOr(Op0, Op1);
1700 return nullptr;
1701}
1702
1705 const DominatorTree &DT) {
1706 CmpPredicate Pred;
1707 Value *Op0;
1708 if (!match(&I, m_ICmp(Pred, m_Value(Op0), m_Zero())) ||
1709 !ICmpInst::isEquality(Pred))
1710 return false;
1711
1712 // If the chain or or's matches a load, combine to that before attempting to
1713 // remove shifts.
1714 if (auto OpI = dyn_cast<Instruction>(Op0))
1715 if (OpI->getOpcode() == Instruction::Or)
1716 if (foldConsecutiveLoads(*OpI, DL, TTI, AA, DT))
1717 return true;
1718
1719 IRBuilder<> Builder(&I);
1720 // icmp eq/ne or(shl(a), b), 0 -> icmp eq/ne or(a, b), 0
1721 if (auto *Res = optimizeShiftInOrChain(Op0, Builder)) {
1722 I.replaceAllUsesWith(Builder.CreateICmp(Pred, Res, I.getOperand(1)));
1723 return true;
1724 }
1725
1726 return false;
1727}
1728
1729// Calculate GEP Stride and accumulated const ModOffset. Return Stride and
1730// ModOffset
1731static std::pair<APInt, APInt>
1733 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
1734 std::optional<APInt> Stride;
1735 APInt ModOffset(BW, 0);
1736 // Return a minimum gep stride, greatest common divisor of consective gep
1737 // index scales(c.f. Bézout's identity).
1738 while (auto *GEP = dyn_cast<GEPOperator>(PtrOp)) {
1740 if (!GEP->collectOffset(DL, BW, VarOffsets, ModOffset))
1741 break;
1742
1743 for (auto [V, Scale] : VarOffsets) {
1744 // Only keep a power of two factor for non-inbounds
1745 if (!GEP->hasNoUnsignedSignedWrap())
1746 Scale = APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
1747
1748 if (!Stride)
1749 Stride = Scale;
1750 else
1751 Stride = APIntOps::GreatestCommonDivisor(*Stride, Scale);
1752 }
1753
1754 PtrOp = GEP->getPointerOperand();
1755 }
1756
1757 // Check whether pointer arrives back at Global Variable via at least one GEP.
1758 // Even if it doesn't, we can check by alignment.
1759 if (!isa<GlobalVariable>(PtrOp) || !Stride)
1760 return {APInt(BW, 1), APInt(BW, 0)};
1761
1762 // In consideration of signed GEP indices, non-negligible offset become
1763 // remainder of division by minimum GEP stride.
1764 ModOffset = ModOffset.srem(*Stride);
1765 if (ModOffset.isNegative())
1766 ModOffset += *Stride;
1767
1768 return {*Stride, ModOffset};
1769}
1770
1771/// If C is a constant patterned array and all valid loaded results for given
1772/// alignment are same to a constant, return that constant.
1774 auto *LI = dyn_cast<LoadInst>(&I);
1775 if (!LI || LI->isVolatile())
1776 return false;
1777
1778 // We can only fold the load if it is from a constant global with definitive
1779 // initializer. Skip expensive logic if this is not the case.
1780 auto *PtrOp = LI->getPointerOperand();
1782 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1783 return false;
1784
1785 // Bail for large initializers in excess of 4K to avoid too many scans.
1786 Constant *C = GV->getInitializer();
1787 uint64_t GVSize = DL.getTypeAllocSize(C->getType());
1788 if (!GVSize || 4096 < GVSize)
1789 return false;
1790
1791 Type *LoadTy = LI->getType();
1792 unsigned BW = DL.getIndexTypeSizeInBits(PtrOp->getType());
1793 auto [Stride, ConstOffset] = getStrideAndModOffsetOfGEP(PtrOp, DL);
1794
1795 // Any possible offset could be multiple of GEP stride. And any valid
1796 // offset is multiple of load alignment, so checking only multiples of bigger
1797 // one is sufficient to say results' equality.
1798 if (auto LA = LI->getAlign();
1799 LA <= GV->getAlign().valueOrOne() && Stride.getZExtValue() < LA.value()) {
1800 ConstOffset = APInt(BW, 0);
1801 Stride = APInt(BW, LA.value());
1802 }
1803
1804 Constant *Ca = ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL);
1805 if (!Ca)
1806 return false;
1807
1808 unsigned E = GVSize - DL.getTypeStoreSize(LoadTy);
1809 for (; ConstOffset.getZExtValue() <= E; ConstOffset += Stride)
1810 if (Ca != ConstantFoldLoadFromConst(C, LoadTy, ConstOffset, DL))
1811 return false;
1812
1813 I.replaceAllUsesWith(Ca);
1814
1815 return true;
1816}
1817
1818namespace {
1819class StrNCmpInliner {
1820public:
1821 StrNCmpInliner(CallInst *CI, LibFunc Func, DomTreeUpdater *DTU,
1822 const DataLayout &DL)
1823 : CI(CI), Func(Func), DTU(DTU), DL(DL) {}
1824
1825 bool optimizeStrNCmp();
1826
1827private:
1828 void inlineCompare(Value *LHS, StringRef RHS, uint64_t N, bool Swapped);
1829
1830 CallInst *CI;
1831 LibFunc Func;
1832 DomTreeUpdater *DTU;
1833 const DataLayout &DL;
1834};
1835
1836} // namespace
1837
1838/// First we normalize calls to strncmp/strcmp to the form of
1839/// compare(s1, s2, N), which means comparing first N bytes of s1 and s2
1840/// (without considering '\0').
1841///
1842/// Examples:
1843///
1844/// \code
1845/// strncmp(s, "a", 3) -> compare(s, "a", 2)
1846/// strncmp(s, "abc", 3) -> compare(s, "abc", 3)
1847/// strncmp(s, "a\0b", 3) -> compare(s, "a\0b", 2)
1848/// strcmp(s, "a") -> compare(s, "a", 2)
1849///
1850/// char s2[] = {'a'}
1851/// strncmp(s, s2, 3) -> compare(s, s2, 3)
1852///
1853/// char s2[] = {'a', 'b', 'c', 'd'}
1854/// strncmp(s, s2, 3) -> compare(s, s2, 3)
1855/// \endcode
1856///
1857/// We only handle cases where N and exactly one of s1 and s2 are constant.
1858/// Cases that s1 and s2 are both constant are already handled by the
1859/// instcombine pass.
1860///
1861/// We do not handle cases where N > StrNCmpInlineThreshold.
1862///
1863/// We also do not handles cases where N < 2, which are already
1864/// handled by the instcombine pass.
1865///
1866bool StrNCmpInliner::optimizeStrNCmp() {
1867 if (StrNCmpInlineThreshold < 2)
1868 return false;
1869
1871 return false;
1872
1873 Value *Str1P = CI->getArgOperand(0);
1874 Value *Str2P = CI->getArgOperand(1);
1875 // Should be handled elsewhere.
1876 if (Str1P == Str2P)
1877 return false;
1878
1879 StringRef Str1, Str2;
1880 bool HasStr1 = getConstantStringInfo(Str1P, Str1, /*TrimAtNul=*/false);
1881 bool HasStr2 = getConstantStringInfo(Str2P, Str2, /*TrimAtNul=*/false);
1882 if (HasStr1 == HasStr2)
1883 return false;
1884
1885 // Note that '\0' and characters after it are not trimmed.
1886 StringRef Str = HasStr1 ? Str1 : Str2;
1887 Value *StrP = HasStr1 ? Str2P : Str1P;
1888
1889 size_t Idx = Str.find('\0');
1890 uint64_t N = Idx == StringRef::npos ? UINT64_MAX : Idx + 1;
1891 if (Func == LibFunc_strncmp) {
1892 if (auto *ConstInt = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
1893 N = std::min(N, ConstInt->getZExtValue());
1894 else
1895 return false;
1896 }
1897 // Now N means how many bytes we need to compare at most.
1898 if (N > Str.size() || N < 2 || N > StrNCmpInlineThreshold)
1899 return false;
1900
1901 // Cases where StrP has two or more dereferenceable bytes might be better
1902 // optimized elsewhere.
1903 bool CanBeNull = false;
1904 if (StrP->getPointerDereferenceableBytes(DL, CanBeNull,
1905 /*CanBeFreed=*/nullptr) > 1)
1906 return false;
1907 inlineCompare(StrP, Str, N, HasStr1);
1908 return true;
1909}
1910
1911/// Convert
1912///
1913/// \code
1914/// ret = compare(s1, s2, N)
1915/// \endcode
1916///
1917/// into
1918///
1919/// \code
1920/// ret = (int)s1[0] - (int)s2[0]
1921/// if (ret != 0)
1922/// goto NE
1923/// ...
1924/// ret = (int)s1[N-2] - (int)s2[N-2]
1925/// if (ret != 0)
1926/// goto NE
1927/// ret = (int)s1[N-1] - (int)s2[N-1]
1928/// NE:
1929/// \endcode
1930///
1931/// CFG before and after the transformation:
1932///
1933/// (before)
1934/// BBCI
1935///
1936/// (after)
1937/// BBCI -> BBSubs[0] (sub,icmp) --NE-> BBNE -> BBTail
1938/// | ^
1939/// E |
1940/// | |
1941/// BBSubs[1] (sub,icmp) --NE-----+
1942/// ... |
1943/// BBSubs[N-1] (sub) ---------+
1944///
1945void StrNCmpInliner::inlineCompare(Value *LHS, StringRef RHS, uint64_t N,
1946 bool Swapped) {
1947 auto &Ctx = CI->getContext();
1948 IRBuilder<> B(Ctx);
1949 // We want these instructions to be recognized as inlined instructions for the
1950 // compare call, but we don't have a source location for the definition of
1951 // that function, since we're generating that code now. Because the generated
1952 // code is a viable point for a memory access error, we make the pragmatic
1953 // choice here to directly use CI's location so that we have useful
1954 // attribution for the generated code.
1955 B.SetCurrentDebugLocation(CI->getDebugLoc());
1956
1957 BasicBlock *BBCI = CI->getParent();
1958 BasicBlock *BBTail =
1959 SplitBlock(BBCI, CI, DTU, nullptr, nullptr, BBCI->getName() + ".tail");
1960
1962 for (uint64_t I = 0; I < N; ++I)
1963 BBSubs.push_back(
1964 BasicBlock::Create(Ctx, "sub_" + Twine(I), BBCI->getParent(), BBTail));
1965 BasicBlock *BBNE = BasicBlock::Create(Ctx, "ne", BBCI->getParent(), BBTail);
1966
1967 cast<UncondBrInst>(BBCI->getTerminator())->setSuccessor(BBSubs[0]);
1968
1969 B.SetInsertPoint(BBNE);
1970 PHINode *Phi = B.CreatePHI(CI->getType(), N);
1971 B.CreateBr(BBTail);
1972
1973 Value *Base = LHS;
1974 for (uint64_t i = 0; i < N; ++i) {
1975 B.SetInsertPoint(BBSubs[i]);
1976 Value *VL =
1977 B.CreateZExt(B.CreateLoad(B.getInt8Ty(),
1978 B.CreateInBoundsPtrAdd(Base, B.getInt64(i))),
1979 CI->getType());
1980 Value *VR =
1981 ConstantInt::get(CI->getType(), static_cast<unsigned char>(RHS[i]));
1982 Value *Sub = Swapped ? B.CreateSub(VR, VL) : B.CreateSub(VL, VR);
1983 if (i < N - 1) {
1984 CondBrInst *CondBrInst = B.CreateCondBr(
1985 B.CreateICmpNE(Sub, ConstantInt::get(CI->getType(), 0)), BBNE,
1986 BBSubs[i + 1]);
1987
1988 Function *F = CI->getFunction();
1989 assert(F && "Instruction does not belong to a function!");
1990 std::optional<uint64_t> EC = F->getEntryCount();
1991 if (EC && *EC > 0)
1993 } else {
1994 B.CreateBr(BBNE);
1995 }
1996
1997 Phi->addIncoming(Sub, BBSubs[i]);
1998 }
1999
2000 CI->replaceAllUsesWith(Phi);
2001 CI->eraseFromParent();
2002
2003 if (DTU) {
2005 Updates.push_back({DominatorTree::Insert, BBCI, BBSubs[0]});
2006 for (uint64_t i = 0; i < N; ++i) {
2007 if (i < N - 1)
2008 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBSubs[i + 1]});
2009 Updates.push_back({DominatorTree::Insert, BBSubs[i], BBNE});
2010 }
2011 Updates.push_back({DominatorTree::Insert, BBNE, BBTail});
2012 Updates.push_back({DominatorTree::Delete, BBCI, BBTail});
2013 DTU->applyUpdates(Updates);
2014 }
2015}
2016
2017/// Convert memchr with a small constant string into a switch
2019 const DataLayout &DL) {
2020 if (isa<Constant>(Call->getArgOperand(1)))
2021 return false;
2022
2023 StringRef Str;
2024 Value *Base = Call->getArgOperand(0);
2025 if (!getConstantStringInfo(Base, Str, /*TrimAtNul=*/false))
2026 return false;
2027
2028 uint64_t N = Str.size();
2029 if (auto *ConstInt = dyn_cast<ConstantInt>(Call->getArgOperand(2))) {
2030 uint64_t Val = ConstInt->getZExtValue();
2031 // Ignore the case that n is larger than the size of string.
2032 if (Val > N)
2033 return false;
2034 N = Val;
2035 } else
2036 return false;
2037
2039 return false;
2040
2041 BasicBlock *BB = Call->getParent();
2042 BasicBlock *BBNext = SplitBlock(BB, Call, DTU);
2043 IRBuilder<> IRB(BB);
2044 IRB.SetCurrentDebugLocation(Call->getDebugLoc());
2045 IntegerType *ByteTy = IRB.getInt8Ty();
2047 SwitchInst *SI = IRB.CreateSwitch(
2048 IRB.CreateTrunc(Call->getArgOperand(1), ByteTy), BBNext, N);
2049 // We can't know the precise weights here, as they would depend on the value
2050 // distribution of Call->getArgOperand(1). So we just mark it as "unknown".
2052 Type *IndexTy = DL.getIndexType(Call->getType());
2054
2055 BasicBlock *BBSuccess = BasicBlock::Create(
2056 Call->getContext(), "memchr.success", BB->getParent(), BBNext);
2057 IRB.SetInsertPoint(BBSuccess);
2058 PHINode *IndexPHI = IRB.CreatePHI(IndexTy, N, "memchr.idx");
2059 Value *FirstOccursLocation = IRB.CreateInBoundsPtrAdd(Base, IndexPHI);
2060 IRB.CreateBr(BBNext);
2061 if (DTU)
2062 Updates.push_back({DominatorTree::Insert, BBSuccess, BBNext});
2063
2065 for (uint64_t I = 0; I < N; ++I) {
2066 ConstantInt *CaseVal =
2067 ConstantInt::get(ByteTy, static_cast<unsigned char>(Str[I]));
2068 if (!Cases.insert(CaseVal).second)
2069 continue;
2070
2071 BasicBlock *BBCase = BasicBlock::Create(Call->getContext(), "memchr.case",
2072 BB->getParent(), BBSuccess);
2073 SI->addCase(CaseVal, BBCase);
2074 IRB.SetInsertPoint(BBCase);
2075 IndexPHI->addIncoming(ConstantInt::get(IndexTy, I), BBCase);
2076 IRB.CreateBr(BBSuccess);
2077 if (DTU) {
2078 Updates.push_back({DominatorTree::Insert, BB, BBCase});
2079 Updates.push_back({DominatorTree::Insert, BBCase, BBSuccess});
2080 }
2081 }
2082
2083 PHINode *PHI =
2084 PHINode::Create(Call->getType(), 2, Call->getName(), BBNext->begin());
2085 PHI->addIncoming(Constant::getNullValue(Call->getType()), BB);
2086 PHI->addIncoming(FirstOccursLocation, BBSuccess);
2087
2088 Call->replaceAllUsesWith(PHI);
2089 Call->eraseFromParent();
2090
2091 if (DTU)
2092 DTU->applyUpdates(Updates);
2093
2094 return true;
2095}
2096
2099 DominatorTree &DT, const DataLayout &DL,
2100 bool &MadeCFGChange) {
2101
2102 auto *CI = dyn_cast<CallInst>(&I);
2103 if (!CI || CI->isNoBuiltin())
2104 return false;
2105
2106 Function *CalledFunc = CI->getCalledFunction();
2107 if (!CalledFunc)
2108 return false;
2109
2110 LibFunc LF;
2111 if (!TLI.getLibFunc(*CalledFunc, LF) ||
2112 !isLibFuncEmittable(CI->getModule(), &TLI, LF))
2113 return false;
2114
2115 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
2116
2117 switch (LF) {
2118 case LibFunc_sqrt:
2119 case LibFunc_sqrtf:
2120 case LibFunc_sqrtl:
2121 return foldSqrt(CI, LF, TTI, TLI, AC, DT);
2122 case LibFunc_strcmp:
2123 case LibFunc_strncmp:
2124 if (StrNCmpInliner(CI, LF, &DTU, DL).optimizeStrNCmp()) {
2125 MadeCFGChange = true;
2126 return true;
2127 }
2128 break;
2129 case LibFunc_memchr:
2130 if (foldMemChr(CI, &DTU, DL)) {
2131 MadeCFGChange = true;
2132 return true;
2133 }
2134 break;
2135 default:;
2136 }
2137 return false;
2138}
2139
2140/// Match high part of long multiplication.
2141///
2142/// Considering a multiply made up of high and low parts, we can split the
2143/// multiply into:
2144/// x * y == (xh*T + xl) * (yh*T + yl)
2145/// where xh == x>>32 and xl == x & 0xffffffff. T = 2^32.
2146/// This expands to
2147/// xh*yh*T*T + xh*yl*T + xl*yh*T + xl*yl
2148/// which can be drawn as
2149/// [ xh*yh ]
2150/// [ xh*yl ]
2151/// [ xl*yh ]
2152/// [ xl*yl ]
2153/// We are looking for the "high" half, which is xh*yh + xh*yl>>32 + xl*yh>>32 +
2154/// some carrys. The carry makes this difficult and there are multiple ways of
2155/// representing it. The ones we attempt to support here are:
2156/// Carry: xh*yh + carry + lowsum
2157/// carry = lowsum < xh*yl ? 0x1000000 : 0
2158/// lowsum = xh*yl + xl*yh + (xl*yl>>32)
2159/// Ladder: xh*yh + c2>>32 + c3>>32
2160/// c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh
2161/// or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xl*yh
2162/// Carry4: xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32
2163/// crosssum = xh*yl + xl*yh
2164/// carry = crosssum < xh*yl ? 0x1000000 : 0
2165/// Ladder4: xh*yh + (xl*yh)>>32 + (xh*yl)>>32 + low>>32;
2166/// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff
2167///
2168/// They all start by matching xh*yh + 2 or 3 other operands. The bottom of the
2169/// tree is xh*yh, xh*yl, xl*yh and xl*yl.
2171 Type *Ty = I.getType();
2172 if (!Ty->isIntOrIntVectorTy())
2173 return false;
2174
2175 unsigned BitWidth = Ty->getScalarSizeInBits();
2177 if (BitWidth % 2 != 0)
2178 return false;
2179
2180 auto CreateMulHigh = [&](Value *X, Value *Y) {
2181 IRBuilder<> Builder(&I);
2182 Type *NTy = Ty->getWithNewBitWidth(BitWidth * 2);
2183 Value *XExt = Builder.CreateZExt(X, NTy);
2184 Value *YExt = Builder.CreateZExt(Y, NTy);
2185 Value *Mul = Builder.CreateMul(XExt, YExt, "", /*HasNUW=*/true);
2186 Value *High = Builder.CreateLShr(Mul, BitWidth);
2187 Value *Res = Builder.CreateTrunc(High, Ty, "", /*HasNUW=*/true);
2188 Res->takeName(&I);
2189 I.replaceAllUsesWith(Res);
2190 LLVM_DEBUG(dbgs() << "Created long multiply from parts of " << *X << " and "
2191 << *Y << "\n");
2192 return true;
2193 };
2194
2195 // Common check routines for X_lo*Y_lo and X_hi*Y_lo
2196 auto CheckLoLo = [&](Value *XlYl, Value *X, Value *Y) {
2197 return match(XlYl, m_c_Mul(m_And(m_Specific(X), m_SpecificInt(LowMask)),
2198 m_And(m_Specific(Y), m_SpecificInt(LowMask))));
2199 };
2200 auto CheckHiLo = [&](Value *XhYl, Value *X, Value *Y) {
2201 return match(XhYl,
2203 m_And(m_Specific(Y), m_SpecificInt(LowMask))));
2204 };
2205
2206 auto FoldMulHighCarry = [&](Value *X, Value *Y, Instruction *Carry,
2207 Instruction *B) {
2208 // Looking for LowSum >> 32 and carry (select)
2209 if (Carry->getOpcode() != Instruction::Select)
2210 std::swap(Carry, B);
2211
2212 // Carry = LowSum < XhYl ? 0x100000000 : 0
2213 Value *LowSum, *XhYl;
2214 if (!match(Carry,
2217 m_Value(XhYl))),
2219 m_Zero()))))
2220 return false;
2221
2222 // XhYl can be Xh*Yl or Xl*Yh
2223 if (!CheckHiLo(XhYl, X, Y)) {
2224 if (CheckHiLo(XhYl, Y, X))
2225 std::swap(X, Y);
2226 else
2227 return false;
2228 }
2229 if (XhYl->hasNUsesOrMore(3))
2230 return false;
2231
2232 // B = LowSum >> 32
2233 if (!match(B, m_OneUse(m_LShr(m_Specific(LowSum),
2234 m_SpecificInt(BitWidth / 2)))) ||
2235 LowSum->hasNUsesOrMore(3))
2236 return false;
2237
2238 // LowSum = XhYl + XlYh + XlYl>>32
2239 Value *XlYh, *XlYl;
2240 auto XlYlHi = m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2));
2241 if (!match(LowSum,
2242 m_c_Add(m_Specific(XhYl),
2243 m_OneUse(m_c_Add(m_OneUse(m_Value(XlYh)), XlYlHi)))) &&
2244 !match(LowSum, m_c_Add(m_OneUse(m_Value(XlYh)),
2245 m_OneUse(m_c_Add(m_Specific(XhYl), XlYlHi)))) &&
2246 !match(LowSum,
2247 m_c_Add(XlYlHi, m_OneUse(m_c_Add(m_Specific(XhYl),
2248 m_OneUse(m_Value(XlYh)))))))
2249 return false;
2250
2251 // Check XlYl and XlYh
2252 if (!CheckLoLo(XlYl, X, Y))
2253 return false;
2254 if (!CheckHiLo(XlYh, Y, X))
2255 return false;
2256
2257 return CreateMulHigh(X, Y);
2258 };
2259
2260 auto FoldMulHighLadder = [&](Value *X, Value *Y, Instruction *A,
2261 Instruction *B) {
2262 // xh*yh + c2>>32 + c3>>32
2263 // c2 = xh*yl + (xl*yl>>32); c3 = c2&0xffffffff + xl*yh
2264 // or c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32); c3 = xh*yl
2265 Value *XlYh, *XhYl, *XlYl, *C2, *C3;
2266 // Strip off the two expected shifts.
2267 if (!match(A, m_LShr(m_Value(C2), m_SpecificInt(BitWidth / 2))) ||
2269 return false;
2270
2271 if (match(C3, m_c_Add(m_Add(m_Value(), m_Value()), m_Value())))
2272 std::swap(C2, C3);
2273 // Try to match c2 = (xl*yh&0xffffffff) + xh*yl + (xl*yl>>32)
2274 if (match(C2,
2276 m_Value(XlYh)),
2277 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2)))) ||
2279 m_LShr(m_Value(XlYl),
2280 m_SpecificInt(BitWidth / 2))),
2281 m_Value(XlYh))) ||
2283 m_SpecificInt(BitWidth / 2)),
2284 m_Value(XlYh)),
2285 m_And(m_Specific(C3), m_SpecificInt(LowMask))))) {
2286 XhYl = C3;
2287 } else {
2288 // Match c3 = c2&0xffffffff + xl*yh
2289 if (!match(C3, m_c_Add(m_And(m_Specific(C2), m_SpecificInt(LowMask)),
2290 m_Value(XlYh))))
2291 std::swap(C2, C3);
2292 if (!match(C3, m_c_Add(m_OneUse(
2293 m_And(m_Specific(C2), m_SpecificInt(LowMask))),
2294 m_Value(XlYh))) ||
2295 !C3->hasOneUse() || C2->hasNUsesOrMore(3))
2296 return false;
2297
2298 // Match c2 = xh*yl + (xl*yl >> 32)
2299 if (!match(C2, m_c_Add(m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2)),
2300 m_Value(XhYl))))
2301 return false;
2302 }
2303
2304 // Match XhYl and XlYh - they can appear either way around.
2305 if (!CheckHiLo(XlYh, Y, X))
2306 std::swap(XlYh, XhYl);
2307 if (!CheckHiLo(XlYh, Y, X))
2308 return false;
2309 if (!CheckHiLo(XhYl, X, Y))
2310 return false;
2311 if (!CheckLoLo(XlYl, X, Y))
2312 return false;
2313
2314 return CreateMulHigh(X, Y);
2315 };
2316
2317 auto FoldMulHighLadder4 = [&](Value *X, Value *Y, Instruction *A,
2319 /// Ladder4: xh*yh + (xl*yh)>>32 + (xh+yl)>>32 + low>>32;
2320 /// low = (xl*yl)>>32 + (xl*yh)&0xffffffff + (xh*yl)&0xffffffff
2321
2322 // Find A = Low >> 32 and B/C = XhYl>>32, XlYh>>32.
2323 auto ShiftAdd =
2325 if (!match(A, ShiftAdd))
2326 std::swap(A, B);
2327 if (!match(A, ShiftAdd))
2328 std::swap(A, C);
2329 Value *Low;
2331 return false;
2332
2333 // Match B == XhYl>>32 and C == XlYh>>32
2334 Value *XhYl, *XlYh;
2335 if (!match(B, m_LShr(m_Value(XhYl), m_SpecificInt(BitWidth / 2))) ||
2336 !match(C, m_LShr(m_Value(XlYh), m_SpecificInt(BitWidth / 2))))
2337 return false;
2338 if (!CheckHiLo(XhYl, X, Y))
2339 std::swap(XhYl, XlYh);
2340 if (!CheckHiLo(XhYl, X, Y) || XhYl->hasNUsesOrMore(3))
2341 return false;
2342 if (!CheckHiLo(XlYh, Y, X) || XlYh->hasNUsesOrMore(3))
2343 return false;
2344
2345 // Match Low as XlYl>>32 + XhYl&0xffffffff + XlYh&0xffffffff
2346 Value *XlYl;
2347 if (!match(
2348 Low,
2349 m_c_Add(
2351 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))),
2352 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))))),
2353 m_OneUse(
2354 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))) &&
2355 !match(
2356 Low,
2357 m_c_Add(
2359 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))),
2360 m_OneUse(
2361 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))),
2362 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))))) &&
2363 !match(
2364 Low,
2365 m_c_Add(
2367 m_OneUse(m_And(m_Specific(XlYh), m_SpecificInt(LowMask))),
2368 m_OneUse(
2369 m_LShr(m_Value(XlYl), m_SpecificInt(BitWidth / 2))))),
2370 m_OneUse(m_And(m_Specific(XhYl), m_SpecificInt(LowMask))))))
2371 return false;
2372 if (!CheckLoLo(XlYl, X, Y))
2373 return false;
2374
2375 return CreateMulHigh(X, Y);
2376 };
2377
2378 auto FoldMulHighCarry4 = [&](Value *X, Value *Y, Instruction *Carry,
2380 // xh*yh + carry + crosssum>>32 + (xl*yl + crosssum&0xffffffff) >> 32
2381 // crosssum = xh*yl+xl*yh
2382 // carry = crosssum < xh*yl ? 0x1000000 : 0
2383 if (Carry->getOpcode() != Instruction::Select)
2384 std::swap(Carry, B);
2385 if (Carry->getOpcode() != Instruction::Select)
2386 std::swap(Carry, C);
2387
2388 // Carry = CrossSum < XhYl ? 0x100000000 : 0
2389 Value *CrossSum, *XhYl;
2390 if (!match(Carry,
2393 m_Value(CrossSum), m_Value(XhYl))),
2395 m_Zero()))))
2396 return false;
2397
2398 if (!match(B, m_LShr(m_Specific(CrossSum), m_SpecificInt(BitWidth / 2))))
2399 std::swap(B, C);
2400 if (!match(B, m_LShr(m_Specific(CrossSum), m_SpecificInt(BitWidth / 2))))
2401 return false;
2402
2403 Value *XlYl, *LowAccum;
2404 if (!match(C, m_LShr(m_Value(LowAccum), m_SpecificInt(BitWidth / 2))) ||
2405 !match(LowAccum, m_c_Add(m_OneUse(m_LShr(m_Value(XlYl),
2406 m_SpecificInt(BitWidth / 2))),
2407 m_OneUse(m_And(m_Specific(CrossSum),
2408 m_SpecificInt(LowMask))))) ||
2409 LowAccum->hasNUsesOrMore(3))
2410 return false;
2411 if (!CheckLoLo(XlYl, X, Y))
2412 return false;
2413
2414 if (!CheckHiLo(XhYl, X, Y))
2415 std::swap(X, Y);
2416 if (!CheckHiLo(XhYl, X, Y))
2417 return false;
2418 Value *XlYh;
2419 if (!match(CrossSum, m_c_Add(m_Specific(XhYl), m_OneUse(m_Value(XlYh)))) ||
2420 !CheckHiLo(XlYh, Y, X) || CrossSum->hasNUsesOrMore(4) ||
2421 XhYl->hasNUsesOrMore(3))
2422 return false;
2423
2424 return CreateMulHigh(X, Y);
2425 };
2426
2427 // X and Y are the two inputs, A, B and C are other parts of the pattern
2428 // (crosssum>>32, carry, etc).
2429 Value *X, *Y;
2430 Instruction *A, *B, *C;
2431 auto HiHi = m_OneUse(m_Mul(m_LShr(m_Value(X), m_SpecificInt(BitWidth / 2)),
2433 if ((match(&I, m_c_Add(HiHi, m_OneUse(m_Add(m_Instruction(A),
2434 m_Instruction(B))))) ||
2436 m_OneUse(m_c_Add(HiHi, m_Instruction(B)))))) &&
2437 A->hasOneUse() && B->hasOneUse())
2438 if (FoldMulHighCarry(X, Y, A, B) || FoldMulHighLadder(X, Y, A, B))
2439 return true;
2440
2441 if ((match(&I, m_c_Add(HiHi, m_OneUse(m_c_Add(
2444 m_Instruction(C))))))) ||
2448 m_Instruction(C))))))) ||
2452 m_OneUse(m_c_Add(HiHi, m_Instruction(C))))))) ||
2453 match(&I,
2456 A->hasOneUse() && B->hasOneUse() && C->hasOneUse())
2457 return FoldMulHighCarry4(X, Y, A, B, C) ||
2458 FoldMulHighLadder4(X, Y, A, B, C);
2459
2460 return false;
2461}
2462
2463/// This is the entry point for folds that could be implemented in regular
2464/// InstCombine, but they are separated because they are not expected to
2465/// occur frequently and/or have more than a constant-length pattern match.
2469 AssumptionCache &AC, bool &MadeCFGChange) {
2470 bool MadeChange = false;
2471 for (BasicBlock &BB : F) {
2472 // Ignore unreachable basic blocks.
2473 if (!DT.isReachableFromEntry(&BB))
2474 continue;
2475
2476 const DataLayout &DL = F.getDataLayout();
2477
2478 // Walk the block backwards for efficiency. We're matching a chain of
2479 // use->defs, so we're more likely to succeed by starting from the bottom.
2480 // Also, we want to avoid matching partial patterns.
2481 // TODO: It would be more efficient if we removed dead instructions
2482 // iteratively in this loop rather than waiting until the end.
2484 MadeChange |= foldAnyOrAllBitsSet(I);
2485 MadeChange |= foldGuardedFunnelShift(I, DT);
2486 MadeChange |= foldSelectSplitCTLZCTTZ(I);
2487 MadeChange |= tryToRecognizePopCount(I);
2488 MadeChange |= tryToRecognizePopCount1(I);
2489 MadeChange |= tryToRecognizePopCount2n3(I);
2490 MadeChange |= tryToFPToSat(I, TTI);
2491 MadeChange |= tryToRecognizeTableBasedCttzOrLog2(I, DL, TTI);
2492 MadeChange |= foldConsecutiveLoads(I, DL, TTI, AA, DT);
2493 MadeChange |= foldPatternedLoads(I, DL);
2494 MadeChange |= foldICmpOrChain(I, DL, TTI, AA, DT);
2495 MadeChange |= foldMulHigh(I);
2496 // NOTE: This function introduces erasing of the instruction `I`, so it
2497 // needs to be called at the end of this sequence, otherwise we may make
2498 // bugs.
2499 MadeChange |= foldLibCalls(I, TTI, TLI, AC, DT, DL, MadeCFGChange);
2500 }
2501
2502 // Do this separately to avoid redundantly scanning stores multiple times.
2503 MadeChange |= foldConsecutiveStores(BB, DL, TTI, AA);
2504 }
2505
2506 // We're done with transforms, so remove dead instructions.
2507 if (MadeChange)
2508 for (BasicBlock &BB : F)
2510
2511 return MadeChange;
2512}
2513
2514/// This is the entry point for all transforms. Pass manager differences are
2515/// handled in the callers of this function.
2518 AliasAnalysis &AA, bool &MadeCFGChange) {
2519 bool MadeChange = false;
2520 const DataLayout &DL = F.getDataLayout();
2521 TruncInstCombine TIC(AC, TLI, DL, DT);
2522 MadeChange |= TIC.run(F);
2523 MadeChange |= foldUnusualPatterns(F, DT, TTI, TLI, AA, AC, MadeCFGChange);
2524 return MadeChange;
2525}
2526
2529 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2530 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2531 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2532 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
2533 auto &AA = AM.getResult<AAManager>(F);
2534 bool MadeCFGChange = false;
2535 if (!runImpl(F, AC, TTI, TLI, DT, AA, MadeCFGChange)) {
2536 // No changes, all analyses are preserved.
2537 return PreservedAnalyses::all();
2538 }
2539 // Mark all the analyses that instcombine updates as preserved.
2541 if (MadeCFGChange)
2543 else
2545 return PA;
2546}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void replaceWithPopCount(Instruction &I, Value *Root)
Helper function to replace an instruction with a popcount intrinsic.
static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL, TargetTransformInfo &TTI)
static bool tryToRecognizePopCount(Instruction &I)
static bool foldSqrt(CallInst *Call, LibFunc Func, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT)
Try to replace a mathlib call to sqrt with the LLVM intrinsic.
static bool isLog2Table(Constant *Table, const APInt &Mul, const APInt &Shift, Type *AccessTy, unsigned InputBits, const APInt &GEPIdxFactor, const DataLayout &DL)
static bool foldAnyOrAllBitsSet(Instruction &I)
Match patterns that correspond to "any-bits-set" and "all-bits-set".
static cl::opt< unsigned > MemChrInlineThreshold("memchr-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string to " "inline a memchr call."))
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 cl::opt< unsigned > StrNCmpInlineThreshold("strncmp-inline-threshold", cl::init(3), cl::Hidden, cl::desc("The maximum length of a constant string for a builtin string cmp " "call eligible for inlining. The default value is 3."))
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 foldSelectSplitCTLZ(Instruction &I, Value *HiPart, Value *LoResult, Value *HiResult, Type *HalfTy)
Same as foldSelectSplitCTTZ but for leading zeros (ctlz).
static bool foldMemChr(CallInst *Call, DomTreeUpdater *DTU, const DataLayout &DL)
Convert memchr with a small constant string into a switch.
static Value * matchPopCountBytes(Value *V, unsigned Len, const DataLayout &DL)
static bool tryToRecognizePopCount2n3(Instruction &I)
static Value * optimizeShiftInOrChain(Value *V, IRBuilder<> &Builder)
Combine away instructions providing they are still equivalent when compared against 0.
static bool foldConsecutiveLoads(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
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 mergePartStores(SmallVectorImpl< PartStore > &Parts, const DataLayout &DL, TargetTransformInfo &TTI)
static bool foldLoadsRecursive(Value *V, LoadOps &LOps, const DataLayout &DL, AliasAnalysis &AA, bool IsRoot=false)
static bool mergeConsecutivePartStores(ArrayRef< PartStore > Parts, unsigned Width, const DataLayout &DL, TargetTransformInfo &TTI)
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 tryToRecognizeTableBasedCttz(LoadInst *LI, Type *AccessType, GlobalVariable *GVTable, Value *GepIdx, const APInt &GEPScale, const DataLayout &DL)
static bool foldSelectSplitCTLZCTTZ(Instruction &I)
Common entry point for folding select-based split cttz/ctlz patterns.
static bool tryToRecognizePopCount1(Instruction &I)
static bool foldICmpOrChain(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA, const DominatorTree &DT)
static bool isCTTZTable(Constant *Table, const APInt &Mul, const APInt &Shift, const APInt &AndMask, Type *AccessTy, unsigned InputBits, const APInt &GEPIdxFactor, const DataLayout &DL)
static std::optional< PartStore > matchPartStore(Instruction &I, const DataLayout &DL)
static bool foldConsecutiveStores(BasicBlock &BB, const DataLayout &DL, TargetTransformInfo &TTI, AliasAnalysis &AA)
static bool tryToRecognizeTableBasedCttzOrLog2(Instruction &I, const DataLayout &DL, TargetTransformInfo &TTI)
static std::pair< APInt, APInt > getStrideAndModOffsetOfGEP(Value *PtrOp, const DataLayout &DL)
static bool foldSelectSplitCTTZ(Instruction &I, Value *LoTrunc, Value *HiResult, Value *LoResult, Type *HalfTy)
Try to fold a select-based split cttz pattern into a single full-width cttz.
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...
static bool foldLibCalls(Instruction &I, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, const DataLayout &DL, bool &MadeCFGChange)
static bool foldMulHigh(Instruction &I)
Match high part of long multiplication.
static bool foldUnusualPatterns(Function &F, DominatorTree &DT, TargetTransformInfo &TTI, TargetLibraryInfo &TLI, AliasAnalysis &AA, AssumptionCache &AC, bool &MadeCFGChange)
This is the entry point for folds that could be implemented in regular InstCombine,...
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
This is the interface for LLVM's primary stateless and local alias analysis.
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
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")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
static Instruction * matchFunnelShift(Instruction &Or, InstCombinerImpl &IC)
Match UB-safe variants of the funnel shift intrinsic.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t High
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
BinaryOperator * Mul
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:652
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1771
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1139
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
unsigned countTrailingOnes() const
Definition APInt.h:1687
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:159
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
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.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
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...
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:221
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1210
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2540
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Definition IRBuilder.h:1239
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2097
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:524
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isSimple() const
static LocationSize precise(uint64_t Value)
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
size_type size() const
Definition MapVector.h:58
std::pair< KeyT, ValueT > & front()
Definition MapVector.h:81
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
Multiway switch.
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.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Basic
The cost of a typical 'add' 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:46
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:155
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:909
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
#define UINT64_MAX
Definition DataTypes.h:77
Abstract Attribute helper functions.
Definition Attributor.h:165
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:830
@ 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
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
ShiftLike_match< LHS, Instruction::LShr > m_LShrOrSelf(const LHS &L, uint64_t &R)
Matches lshr L, ConstShAmt or L itself (R will be set to zero in this case).
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, CastInst >, OpTy > m_CastOrSelf(const OpTy &Op)
Matches any cast or self. Used to ignore casts.
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::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< 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()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
ShiftLike_match< LHS, Instruction::Shl > m_ShlOrSelf(const LHS &L, uint64_t &R)
Matches shl L, ConstShAmt or L itself (R will be set to zero in this case).
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
specific_bbval m_SpecificBB(BasicBlock *BB)
Match a specific basic block value.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
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.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, FPToSIInst > m_FPToSI(const OpTy &Op)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
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::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
auto m_Cttz(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:392
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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:633
LLVM_ABI 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:736
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI 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...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:332
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
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
@ Other
Any other memory.
Definition ModRef.h:68
@ 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 >
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
ValWidth bits starting at ValOffset of Val stored at PtrBase+PtrOffset.
bool operator<(const PartStore &Other) const
bool isCompatibleWith(const PartStore &Other) const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
Matching combinators.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342