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