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