1//===- InstCombineCalls.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 visitCall, visitInvoke, and visitCallBr functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/Bitset.h"
19#include "llvm/ADT/STLFunctionalExtras.h"
20#include "llvm/ADT/SmallBitVector.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/AssumeBundleQueries.h"
26#include "llvm/Analysis/AssumptionCache.h"
27#include "llvm/Analysis/InstructionSimplify.h"
28#include "llvm/Analysis/Loads.h"
29#include "llvm/Analysis/MemoryBuiltins.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Analysis/VectorUtils.h"
32#include "llvm/IR/AttributeMask.h"
33#include "llvm/IR/Attributes.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/BundleAttributes.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/DebugInfo.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InlineAsm.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/IntrinsicsAArch64.h"
50#include "llvm/IR/IntrinsicsAMDGPU.h"
51#include "llvm/IR/IntrinsicsARM.h"
52#include "llvm/IR/IntrinsicsHexagon.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/PatternMatch.h"
56#include "llvm/IR/ProfDataUtils.h"
57#include "llvm/IR/Statepoint.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/IR/ValueHandle.h"
62#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/KnownBits.h"
69#include "llvm/Support/KnownFPClass.h"
70#include "llvm/Support/MathExtras.h"
71#include "llvm/Support/TypeSize.h"
72#include "llvm/Support/raw_ostream.h"
73#include "llvm/Transforms/InstCombine/InstCombiner.h"
74#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
75#include "llvm/Transforms/Utils/Local.h"
76#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
77#include <algorithm>
78#include <cassert>
79#include <cstdint>
80#include <optional>
81#include <utility>
82#include <vector>
83
84#define DEBUG_TYPE "instcombine"
85#include "llvm/Transforms/Utils/InstructionWorklist.h"
86
87using namespace llvm;
88using namespace PatternMatch;
89
90STATISTIC(NumSimplified, "Number of library calls simplified");
91
92static cl::opt<unsigned> GuardWideningWindow(
93 "instcombine-guard-widening-window",
94 cl::init(Val: 3),
95 cl::desc("How wide an instruction window to bypass looking for "
96 "another guard"));
97
98/// Return the specified type promoted as it would be to pass though a va_arg
99/// area.
100static Type *getPromotedType(Type *Ty) {
101 if (IntegerType* ITy = dyn_cast<IntegerType>(Val: Ty)) {
102 if (ITy->getBitWidth() < 32)
103 return Type::getInt32Ty(C&: Ty->getContext());
104 }
105 return Ty;
106}
107
108/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.
109/// TODO: This should probably be integrated with visitAllocSites, but that
110/// requires a deeper change to allow either unread or unwritten objects.
111static bool hasUndefSource(AnyMemTransferInst *MI) {
112 auto *Src = MI->getRawSource();
113 while (isa<GetElementPtrInst>(Val: Src)) {
114 if (!Src->hasOneUse())
115 return false;
116 Src = cast<Instruction>(Val: Src)->getOperand(i: 0);
117 }
118 return isa<AllocaInst>(Val: Src) && Src->hasOneUse();
119}
120
121Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
122 Align DstAlign = getKnownAlignment(V: MI->getRawDest(), DL, CxtI: MI, AC: &AC, DT: &DT);
123 MaybeAlign CopyDstAlign = MI->getDestAlign();
124 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
125 MI->setDestAlignment(DstAlign);
126 return MI;
127 }
128
129 Align SrcAlign = getKnownAlignment(V: MI->getRawSource(), DL, CxtI: MI, AC: &AC, DT: &DT);
130 MaybeAlign CopySrcAlign = MI->getSourceAlign();
131 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
132 MI->setSourceAlignment(SrcAlign);
133 return MI;
134 }
135
136 // If we have a store to a location which is known constant, we can conclude
137 // that the store must be storing the constant value (else the memory
138 // wouldn't be constant), and this must be a noop.
139 if (!isModSet(MRI: AA->getModRefInfoMask(P: MI->getDest()))) {
140 // Set the size of the copy to 0, it will be deleted on the next iteration.
141 MI->setLength((uint64_t)0);
142 return MI;
143 }
144
145 // If the source is provably undef, the memcpy/memmove doesn't do anything
146 // (unless the transfer is volatile).
147 if (hasUndefSource(MI) && !MI->isVolatile()) {
148 // Set the size of the copy to 0, it will be deleted on the next iteration.
149 MI->setLength((uint64_t)0);
150 return MI;
151 }
152
153 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
154 // load/store.
155 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(Val: MI->getLength());
156 if (!MemOpLength) return nullptr;
157
158 // Source and destination pointer types are always "i8*" for intrinsic. See
159 // if the size is something we can handle with a single primitive load/store.
160 // A single load+store correctly handles overlapping memory in the memmove
161 // case.
162 uint64_t Size = MemOpLength->getLimitedValue();
163 assert(Size && "0-sized memory transferring should be removed already.");
164
165 if (Size > 8 || (Size&(Size-1)))
166 return nullptr; // If not 1/2/4/8 bytes, exit.
167
168 // If it is an atomic and alignment is less than the size then we will
169 // introduce the unaligned memory access which will be later transformed
170 // into libcall in CodeGen. This is not evident performance gain so disable
171 // it now.
172 if (MI->isAtomic())
173 if (*CopyDstAlign < Size || *CopySrcAlign < Size)
174 return nullptr;
175
176 // Use an integer load+store unless we can find something better.
177 IntegerType* IntType = IntegerType::get(C&: MI->getContext(), NumBits: Size<<3);
178
179 // If the memcpy has metadata describing the members, see if we can get the
180 // TBAA, scope and noalias tags describing our copy.
181 AAMDNodes AACopyMD = MI->getAAMetadata().adjustForAccess(AccessSize: Size);
182
183 Value *Src = MI->getArgOperand(i: 1);
184 Value *Dest = MI->getArgOperand(i: 0);
185 LoadInst *L = Builder.CreateLoad(Ty: IntType, Ptr: Src);
186 // Alignment from the mem intrinsic will be better, so use it.
187 L->setAlignment(*CopySrcAlign);
188 L->setAAMetadata(AACopyMD);
189 MDNode *LoopMemParallelMD =
190 MI->getMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access);
191 if (LoopMemParallelMD)
192 L->setMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access, Node: LoopMemParallelMD);
193 MDNode *AccessGroupMD = MI->getMetadata(KindID: LLVMContext::MD_access_group);
194 if (AccessGroupMD)
195 L->setMetadata(KindID: LLVMContext::MD_access_group, Node: AccessGroupMD);
196
197 StoreInst *S = Builder.CreateStore(Val: L, Ptr: Dest);
198 // Alignment from the mem intrinsic will be better, so use it.
199 S->setAlignment(*CopyDstAlign);
200 S->setAAMetadata(AACopyMD);
201 if (LoopMemParallelMD)
202 S->setMetadata(KindID: LLVMContext::MD_mem_parallel_loop_access, Node: LoopMemParallelMD);
203 if (AccessGroupMD)
204 S->setMetadata(KindID: LLVMContext::MD_access_group, Node: AccessGroupMD);
205 S->copyMetadata(SrcInst: *MI, WL: LLVMContext::MD_DIAssignID);
206
207 if (auto *MT = dyn_cast<MemTransferInst>(Val: MI)) {
208 // non-atomics can be volatile
209 L->setVolatile(MT->isVolatile());
210 S->setVolatile(MT->isVolatile());
211 }
212 if (MI->isAtomic()) {
213 // atomics have to be unordered
214 L->setOrdering(AtomicOrdering::Unordered);
215 S->setOrdering(AtomicOrdering::Unordered);
216 }
217
218 // Set the size of the copy to 0, it will be deleted on the next iteration.
219 MI->setLength((uint64_t)0);
220 return MI;
221}
222
223Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {
224 const Align KnownAlignment =
225 getKnownAlignment(V: MI->getDest(), DL, CxtI: MI, AC: &AC, DT: &DT);
226 MaybeAlign MemSetAlign = MI->getDestAlign();
227 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
228 MI->setDestAlignment(KnownAlignment);
229 return MI;
230 }
231
232 // If we have a store to a location which is known constant, we can conclude
233 // that the store must be storing the constant value (else the memory
234 // wouldn't be constant), and this must be a noop.
235 if (!isModSet(MRI: AA->getModRefInfoMask(P: MI->getDest()))) {
236 // Set the size of the copy to 0, it will be deleted on the next iteration.
237 MI->setLength((uint64_t)0);
238 return MI;
239 }
240
241 // Remove memset with an undef value.
242 // FIXME: This is technically incorrect because it might overwrite a poison
243 // value. Change to PoisonValue once #52930 is resolved.
244 if (isa<UndefValue>(Val: MI->getValue())) {
245 // Set the size of the copy to 0, it will be deleted on the next iteration.
246 MI->setLength((uint64_t)0);
247 return MI;
248 }
249
250 // Extract the length and alignment and fill if they are constant.
251 ConstantInt *LenC = dyn_cast<ConstantInt>(Val: MI->getLength());
252 ConstantInt *FillC = dyn_cast<ConstantInt>(Val: MI->getValue());
253 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(BitWidth: 8))
254 return nullptr;
255 const uint64_t Len = LenC->getLimitedValue();
256 assert(Len && "0-sized memory setting should be removed already.");
257 const Align Alignment = MI->getDestAlign().valueOrOne();
258
259 // If it is an atomic and alignment is less than the size then we will
260 // introduce the unaligned memory access which will be later transformed
261 // into libcall in CodeGen. This is not evident performance gain so disable
262 // it now.
263 if (MI->isAtomic() && Alignment < Len)
264 return nullptr;
265
266 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
267 if (Len <= 8 && isPowerOf2_32(Value: (uint32_t)Len)) {
268 Value *Dest = MI->getDest();
269
270 // Extract the fill value and store.
271 Constant *FillVal = ConstantInt::get(
272 Context&: MI->getContext(), V: APInt::getSplat(NewLen: Len * 8, V: FillC->getValue()));
273 StoreInst *S = Builder.CreateStore(Val: FillVal, Ptr: Dest, isVolatile: MI->isVolatile());
274 S->copyMetadata(SrcInst: *MI, WL: LLVMContext::MD_DIAssignID);
275 for (DbgVariableRecord *DbgAssign : at::getDVRAssignmentMarkers(Inst: S)) {
276 if (llvm::is_contained(Range: DbgAssign->location_ops(), Element: FillC))
277 DbgAssign->replaceVariableLocationOp(OldValue: FillC, NewValue: FillVal);
278 }
279
280 S->setAlignment(Alignment);
281 if (MI->isAtomic())
282 S->setOrdering(AtomicOrdering::Unordered);
283
284 // Set the size of the copy to 0, it will be deleted on the next iteration.
285 MI->setLength((uint64_t)0);
286 return MI;
287 }
288
289 return nullptr;
290}
291
292// TODO, Obvious Missing Transforms:
293// * Narrow width by halfs excluding zero/undef lanes
294Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
295 Value *LoadPtr = II.getArgOperand(i: 0);
296 const Align Alignment = II.getParamAlign(ArgNo: 0).valueOrOne();
297 Value *Mask = II.getArgOperand(i: 1);
298
299 // If the mask is all ones or poison, this is a plain vector load of the 1st
300 // argument.
301 if (match(V: Mask, P: m_AllOnesOrPoison())) {
302 LoadInst *L = Builder.CreateAlignedLoad(Ty: II.getType(), Ptr: LoadPtr, Align: Alignment,
303 Name: "unmaskedload");
304 L->copyMetadata(SrcInst: II);
305 return L;
306 }
307
308 // If we can unconditionally load from this address, replace with a
309 // load/select idiom.
310 if (isDereferenceablePointer(V: LoadPtr, Ty: II.getType(),
311 Q: SQ.getWithInstruction(I: &II))) {
312 LoadInst *LI = Builder.CreateAlignedLoad(Ty: II.getType(), Ptr: LoadPtr, Align: Alignment,
313 Name: "unmaskedload");
314 LI->copyMetadata(SrcInst: II);
315 return Builder.CreateSelect(C: II.getArgOperand(i: 1), True: LI, False: II.getArgOperand(i: 2));
316 }
317
318 return nullptr;
319}
320
321// TODO, Obvious Missing Transforms:
322// * Single constant active lane -> store
323// * Narrow width by halfs excluding zero/undef lanes
324Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
325 Value *StorePtr = II.getArgOperand(i: 1);
326 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
327 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 2));
328 if (!ConstMask)
329 return nullptr;
330
331 // If the mask is all zeros or poison, this instruction does nothing.
332 if (match(V: ConstMask, P: m_ZeroOrPoison()))
333 return eraseInstFromFunction(I&: II);
334
335 // If the mask is all ones or poison, this is a plain vector store of the 1st
336 // argument.
337 if (match(V: ConstMask, P: m_AllOnesOrPoison())) {
338 StoreInst *S =
339 new StoreInst(II.getArgOperand(i: 0), StorePtr, false, Alignment);
340 S->copyMetadata(SrcInst: II);
341 return S;
342 }
343
344 if (isa<ScalableVectorType>(Val: ConstMask->getType()))
345 return nullptr;
346
347 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
348 APInt DemandedElts = possiblyDemandedEltsInMask(Mask: ConstMask);
349 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
350 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 0), DemandedElts,
351 PoisonElts))
352 return replaceOperand(I&: II, OpNum: 0, V);
353
354 return nullptr;
355}
356
357// TODO, Obvious Missing Transforms:
358// * Single constant active lane load -> load
359// * Dereferenceable address & few lanes -> scalarize speculative load/selects
360// * Adjacent vector addresses -> masked.load
361// * Narrow width by halfs excluding zero/undef lanes
362// * Vector incrementing address -> vector masked load
363Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
364 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 1));
365 if (!ConstMask)
366 return nullptr;
367
368 // Vector splat address w/known mask -> scalar load
369 // Fold the gather to load the source vector first lane
370 // because it is reloading the same value each time
371 if (ConstMask->isAllOnesValue())
372 if (auto *SplatPtr = getSplatValue(V: II.getArgOperand(i: 0))) {
373 auto *VecTy = cast<VectorType>(Val: II.getType());
374 const Align Alignment = II.getParamAlign(ArgNo: 0).valueOrOne();
375 LoadInst *L = Builder.CreateAlignedLoad(Ty: VecTy->getElementType(), Ptr: SplatPtr,
376 Align: Alignment, Name: "load.scalar");
377 Value *Shuf =
378 Builder.CreateVectorSplat(EC: VecTy->getElementCount(), V: L, Name: "broadcast");
379 return replaceInstUsesWith(I&: II, V: cast<Instruction>(Val: Shuf));
380 }
381
382 return nullptr;
383}
384
385// TODO, Obvious Missing Transforms:
386// * Single constant active lane -> store
387// * Adjacent vector addresses -> masked.store
388// * Narrow store width by halfs excluding zero/undef lanes
389// * Vector incrementing address -> vector masked store
390Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
391 auto *ConstMask = dyn_cast<Constant>(Val: II.getArgOperand(i: 2));
392 if (!ConstMask)
393 return nullptr;
394
395 // If the mask is all zeros or poison, a scatter does nothing.
396 if (match(V: ConstMask, P: m_ZeroOrPoison()))
397 return eraseInstFromFunction(I&: II);
398
399 // Vector splat address -> scalar store
400 if (auto *SplatPtr = getSplatValue(V: II.getArgOperand(i: 1))) {
401 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
402 if (auto *SplatValue = getSplatValue(V: II.getArgOperand(i: 0))) {
403 if (maskContainsAllOneOrUndef(Mask: ConstMask)) {
404 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
405 StoreInst *S = new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false,
406 Alignment);
407 S->copyMetadata(SrcInst: II);
408 return S;
409 }
410 }
411 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
412 // lastlane), ptr
413 if (ConstMask->isAllOnesValue()) {
414 Align Alignment = II.getParamAlign(ArgNo: 1).valueOrOne();
415 VectorType *WideLoadTy = cast<VectorType>(Val: II.getArgOperand(i: 1)->getType());
416 ElementCount VF = WideLoadTy->getElementCount();
417 Value *RunTimeVF = Builder.CreateElementCount(Ty: Builder.getInt32Ty(), EC: VF);
418 Value *LastLane = Builder.CreateSub(LHS: RunTimeVF, RHS: Builder.getInt32(C: 1));
419 Value *Extract =
420 Builder.CreateExtractElement(Vec: II.getArgOperand(i: 0), Idx: LastLane);
421 StoreInst *S =
422 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
423 S->copyMetadata(SrcInst: II);
424 return S;
425 }
426 }
427 if (isa<ScalableVectorType>(Val: ConstMask->getType()))
428 return nullptr;
429
430 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
431 APInt DemandedElts = possiblyDemandedEltsInMask(Mask: ConstMask);
432 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
433 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 0), DemandedElts,
434 PoisonElts))
435 return replaceOperand(I&: II, OpNum: 0, V);
436 if (Value *V = SimplifyDemandedVectorElts(V: II.getOperand(i_nocapture: 1), DemandedElts,
437 PoisonElts))
438 return replaceOperand(I&: II, OpNum: 1, V);
439
440 return nullptr;
441}
442
443/// This function transforms launder.invariant.group and strip.invariant.group
444/// like:
445/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
446/// launder(strip(%x)) -> launder(%x)
447/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
448/// strip(launder(%x)) -> strip(%x)
449/// This is legal because it preserves the most recent information about
450/// the presence or absence of invariant.group.
451static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
452 InstCombinerImpl &IC) {
453 auto *Arg = II.getArgOperand(i: 0);
454 auto *StrippedArg = Arg->stripPointerCasts();
455 auto *StrippedInvariantGroupsArg = StrippedArg;
456 while (auto *Intr = dyn_cast<IntrinsicInst>(Val: StrippedInvariantGroupsArg)) {
457 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
458 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
459 break;
460 StrippedInvariantGroupsArg = Intr->getArgOperand(i: 0)->stripPointerCasts();
461 }
462 if (StrippedArg == StrippedInvariantGroupsArg)
463 return nullptr; // No launders/strips to remove.
464
465 Value *Result = nullptr;
466
467 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
468 Result = IC.Builder.CreateLaunderInvariantGroup(Ptr: StrippedInvariantGroupsArg);
469 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
470 Result = IC.Builder.CreateStripInvariantGroup(Ptr: StrippedInvariantGroupsArg);
471 else
472 llvm_unreachable(
473 "simplifyInvariantGroupIntrinsic only handles launder and strip");
474 if (Result->getType()->getPointerAddressSpace() !=
475 II.getType()->getPointerAddressSpace())
476 Result = IC.Builder.CreateAddrSpaceCast(V: Result, DestTy: II.getType());
477
478 return cast<Instruction>(Val: Result);
479}
480
481static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {
482 assert((II.getIntrinsicID() == Intrinsic::cttz ||
483 II.getIntrinsicID() == Intrinsic::ctlz) &&
484 "Expected cttz or ctlz intrinsic");
485 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
486 Value *Op0 = II.getArgOperand(i: 0);
487 Value *Op1 = II.getArgOperand(i: 1);
488 Value *X;
489 // ctlz(bitreverse(x)) -> cttz(x)
490 // cttz(bitreverse(x)) -> ctlz(x)
491 if (match(V: Op0, P: m_BitReverse(Op0: m_Value(V&: X)))) {
492 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
493 Function *F =
494 Intrinsic::getOrInsertDeclaration(M: II.getModule(), id: ID, OverloadTys: II.getType());
495 return CallInst::Create(Func: F, Args: {X, II.getArgOperand(i: 1)});
496 }
497
498 if (II.getType()->isIntOrIntVectorTy(BitWidth: 1)) {
499 // ctlz/cttz i1 Op0 --> not Op0
500 if (match(V: Op1, P: m_Zero()))
501 return BinaryOperator::CreateNot(Op: Op0);
502 // If zero is poison, then the input can be assumed to be "true", so the
503 // instruction simplifies to "false".
504 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
505 return IC.replaceInstUsesWith(I&: II, V: ConstantInt::getNullValue(Ty: II.getType()));
506 }
507
508 // If ctlz/cttz is only used as a shift amount, set is_zero_poison to true.
509 if (II.hasOneUse() && match(V: Op1, P: m_Zero()) &&
510 match(V: II.user_back(), P: m_Shift(L: m_Value(), R: m_Specific(V: &II))))
511 return CallInst::Create(Func: II.getCalledFunction(),
512 Args: {Op0, IC.Builder.getTrue()});
513
514 Constant *C;
515
516 if (IsTZ) {
517 // cttz(-x) -> cttz(x)
518 if (match(V: Op0, P: m_Neg(V: m_Value(V&: X))))
519 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
520
521 // cttz(-x & x) -> cttz(x)
522 if (match(V: Op0, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X))))
523 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
524
525 // cttz(sext(x)) -> cttz(zext(x))
526 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X))))) {
527 auto *Zext = IC.Builder.CreateZExt(V: X, DestTy: II.getType());
528 auto *CttzZext =
529 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: Zext, RHS: Op1);
530 return IC.replaceInstUsesWith(I&: II, V: CttzZext);
531 }
532
533 // Zext doesn't change the number of trailing zeros, so narrow:
534 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
535 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) && match(V: Op1, P: m_One())) {
536 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: X,
537 RHS: IC.Builder.getTrue());
538 auto *ZextCttz = IC.Builder.CreateZExt(V: Cttz, DestTy: II.getType());
539 return IC.replaceInstUsesWith(I&: II, V: ZextCttz);
540 }
541
542 // cttz(abs(x)) -> cttz(x)
543 // cttz(nabs(x)) -> cttz(x)
544 Value *Y;
545 SelectPatternFlavor SPF = matchSelectPattern(V: Op0, LHS&: X, RHS&: Y).Flavor;
546 if (SPF == SPF_ABS || SPF == SPF_NABS)
547 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
548
549 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: X))))
550 return CallInst::Create(Func: II.getCalledFunction(), Args: {X, Op1});
551
552 // cttz(shl(%const, %val), 1) --> add(cttz(%const, 1), %val)
553 if (match(V: Op0, P: m_Shl(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
554 match(V: Op1, P: m_One())) {
555 Value *ConstCttz =
556 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: C, RHS: Op1);
557 return BinaryOperator::CreateAdd(V1: ConstCttz, V2: X);
558 }
559
560 // cttz(lshr exact (%const, %val), 1) --> sub(cttz(%const, 1), %val)
561 if (match(V: Op0, P: m_Exact(SubPattern: m_LShr(L: m_ImmConstant(C), R: m_Value(V&: X)))) &&
562 match(V: Op1, P: m_One())) {
563 Value *ConstCttz =
564 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::cttz, LHS: C, RHS: Op1);
565 return BinaryOperator::CreateSub(V1: ConstCttz, V2: X);
566 }
567
568 // cttz(add(lshr(UINT_MAX, %val), 1)) --> sub(width, %val)
569 if (match(V: Op0, P: m_Add(L: m_LShr(L: m_AllOnes(), R: m_Value(V&: X)), R: m_One()))) {
570 Value *Width =
571 ConstantInt::get(Ty: II.getType(), V: II.getType()->getScalarSizeInBits());
572 return BinaryOperator::CreateSub(V1: Width, V2: X);
573 }
574 } else {
575 // ctlz(lshr(%const, %val), 1) --> add(ctlz(%const, 1), %val)
576 if (match(V: Op0, P: m_LShr(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
577 match(V: Op1, P: m_One())) {
578 Value *ConstCtlz =
579 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::ctlz, LHS: C, RHS: Op1);
580 return BinaryOperator::CreateAdd(V1: ConstCtlz, V2: X);
581 }
582
583 // ctlz(shl nuw (%const, %val), 1) --> sub(ctlz(%const, 1), %val)
584 if (match(V: Op0, P: m_NUWShl(L: m_ImmConstant(C), R: m_Value(V&: X))) &&
585 match(V: Op1, P: m_One())) {
586 Value *ConstCtlz =
587 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::ctlz, LHS: C, RHS: Op1);
588 return BinaryOperator::CreateSub(V1: ConstCtlz, V2: X);
589 }
590
591 // ctlz(~x & (x - 1)) -> bitwidth - cttz(x, false)
592 if (Op0->hasOneUse() &&
593 match(V: Op0,
594 P: m_c_And(L: m_Not(V: m_Value(V&: X)), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())))) {
595 Type *Ty = II.getType();
596 unsigned BitWidth = Ty->getScalarSizeInBits();
597 auto *Cttz = IC.Builder.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: Ty,
598 Args: {X, IC.Builder.getFalse()});
599 auto *Bw = ConstantInt::get(Ty, V: APInt(BitWidth, BitWidth));
600 return IC.replaceInstUsesWith(I&: II, V: IC.Builder.CreateSub(LHS: Bw, RHS: Cttz));
601 }
602 }
603
604 // cttz(Pow2) -> Log2(Pow2)
605 // ctlz(Pow2) -> BitWidth - 1 - Log2(Pow2)
606 if (auto *R = IC.tryGetLog2(Op: Op0, AssumeNonZero: match(V: Op1, P: m_One()))) {
607 if (IsTZ)
608 return IC.replaceInstUsesWith(I&: II, V: R);
609 BinaryOperator *BO = BinaryOperator::CreateSub(
610 V1: ConstantInt::get(Ty: R->getType(), V: R->getType()->getScalarSizeInBits() - 1),
611 V2: R);
612 BO->setHasNoSignedWrap();
613 BO->setHasNoUnsignedWrap();
614 return BO;
615 }
616
617 KnownBits Known = IC.computeKnownBits(V: Op0, CxtI: &II);
618
619 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
620 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
621 : Known.countMaxLeadingZeros();
622 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
623 : Known.countMinLeadingZeros();
624
625 // If all bits above (ctlz) or below (cttz) the first known one are known
626 // zero, this value is constant.
627 // FIXME: This should be in InstSimplify because we're replacing an
628 // instruction with a constant.
629 if (PossibleZeros == DefiniteZeros) {
630 auto *C = ConstantInt::get(Ty: Op0->getType(), V: DefiniteZeros);
631 return IC.replaceInstUsesWith(I&: II, V: C);
632 }
633
634 // If the input to cttz/ctlz is known to be non-zero,
635 // then change the 'ZeroIsPoison' parameter to 'true'
636 // because we know the zero behavior can't affect the result.
637 if (!Known.One.isZero() ||
638 isKnownNonZero(V: Op0, Q: IC.getSimplifyQuery().getWithInstruction(I: &II))) {
639 if (!match(V: II.getArgOperand(i: 1), P: m_One()))
640 return CallInst::Create(Func: II.getCalledFunction(),
641 Args: {Op0, IC.Builder.getTrue()});
642 }
643
644 // Add range attribute since known bits can't completely reflect what we know.
645 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
646 if (BitWidth != 1 && !II.hasRetAttr(Kind: Attribute::Range) &&
647 !II.getMetadata(KindID: LLVMContext::MD_range)) {
648 ConstantRange Range(APInt(BitWidth, DefiniteZeros),
649 APInt(BitWidth, PossibleZeros + 1));
650 II.addRangeRetAttr(CR: Range);
651 return &II;
652 }
653
654 return nullptr;
655}
656
657static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {
658 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
659 "Expected ctpop intrinsic");
660 Type *Ty = II.getType();
661 unsigned BitWidth = Ty->getScalarSizeInBits();
662 Value *Op0 = II.getArgOperand(i: 0);
663 Value *X, *Y;
664
665 // ctpop(bitreverse(x)) -> ctpop(x)
666 // ctpop(bswap(x)) -> ctpop(x)
667 if (match(V: Op0, P: m_BitReverse(Op0: m_Value(V&: X))) || match(V: Op0, P: m_BSwap(Op0: m_Value(V&: X))))
668 return CallInst::Create(Func: II.getCalledFunction(), Args: X);
669
670 // ctpop(rot(x)) -> ctpop(x)
671 if ((match(V: Op0, P: m_FShl(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_Value())) ||
672 match(V: Op0, P: m_FShr(Op0: m_Value(V&: X), Op1: m_Value(V&: Y), Op2: m_Value()))) &&
673 X == Y)
674 return CallInst::Create(Func: II.getCalledFunction(), Args: X);
675
676 // ctpop(x | -x) -> bitwidth - cttz(x, false)
677 if (Op0->hasOneUse() &&
678 match(V: Op0, P: m_c_Or(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))))) {
679 auto *Cttz = IC.Builder.CreateIntrinsic(ID: Intrinsic::cttz, OverloadTypes: Ty,
680 Args: {X, IC.Builder.getFalse()});
681 auto *Bw = ConstantInt::get(Ty, V: APInt(BitWidth, BitWidth));
682 return IC.replaceInstUsesWith(I&: II, V: IC.Builder.CreateSub(LHS: Bw, RHS: Cttz));
683 }
684
685 // ctpop(~x & (x - 1)) -> cttz(x, false)
686 if (match(V: Op0,
687 P: m_c_And(L: m_Not(V: m_Value(V&: X)), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())))) {
688 Function *F =
689 Intrinsic::getOrInsertDeclaration(M: II.getModule(), id: Intrinsic::cttz, OverloadTys: Ty);
690 return CallInst::Create(Func: F, Args: {X, IC.Builder.getFalse()});
691 }
692
693 // Zext doesn't change the number of set bits, so narrow:
694 // ctpop (zext X) --> zext (ctpop X)
695 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))))) {
696 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: X);
697 return CastInst::Create(Instruction::ZExt, S: NarrowPop, Ty);
698 }
699
700 KnownBits Known(BitWidth);
701 IC.computeKnownBits(V: Op0, Known, CxtI: &II);
702
703 // If all bits are zero except for exactly one fixed bit, then the result
704 // must be 0 or 1, and we can get that answer by shifting to LSB:
705 // ctpop (X & 32) --> (X & 32) >> 5
706 // TODO: Investigate removing this as its likely unnecessary given the below
707 // `isKnownToBeAPowerOfTwo` check.
708 if ((~Known.Zero).isPowerOf2())
709 return BinaryOperator::CreateLShr(
710 V1: Op0, V2: ConstantInt::get(Ty, V: (~Known.Zero).exactLogBase2()));
711
712 // More generally we can also handle non-constant power of 2 patterns such as
713 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
714 // ctpop(Pow2OrZero) --> icmp ne X, 0
715 if (IC.isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ true))
716 return CastInst::Create(Instruction::ZExt,
717 S: IC.Builder.CreateICmp(P: ICmpInst::ICMP_NE, LHS: Op0,
718 RHS: Constant::getNullValue(Ty)),
719 Ty);
720
721 // Add range attribute since known bits can't completely reflect what we know.
722 if (BitWidth != 1) {
723 ConstantRange OldRange =
724 II.getRange().value_or(u: ConstantRange::getFull(BitWidth));
725
726 unsigned Lower = Known.countMinPopulation();
727 unsigned Upper = Known.countMaxPopulation() + 1;
728
729 if (Lower == 0 && OldRange.contains(Val: APInt::getZero(numBits: BitWidth)) &&
730 isKnownNonZero(V: Op0, Q: IC.getSimplifyQuery().getWithInstruction(I: &II)))
731 Lower = 1;
732
733 ConstantRange Range(APInt(BitWidth, Lower), APInt(BitWidth, Upper));
734 Range = Range.intersectWith(CR: OldRange, Type: ConstantRange::Unsigned);
735
736 if (Range != OldRange) {
737 II.addRangeRetAttr(CR: Range);
738 return &II;
739 }
740 }
741
742 return nullptr;
743}
744
745/// Convert `tbl`/`tbx` intrinsics to shufflevector if the mask is constant, and
746/// at most two source operands are actually referenced.
747static Instruction *simplifyNeonTbl(IntrinsicInst &II, InstCombiner &IC,
748 bool IsExtension) {
749 // Bail out if the mask is not a constant.
750 auto *C = dyn_cast<Constant>(Val: II.getArgOperand(i: II.arg_size() - 1));
751 if (!C)
752 return nullptr;
753
754 auto *RetTy = cast<FixedVectorType>(Val: II.getType());
755 unsigned NumIndexes = RetTy->getNumElements();
756
757 // Only perform this transformation for <8 x i8> and <16 x i8> vector types.
758 if (!RetTy->getElementType()->isIntegerTy(BitWidth: 8) ||
759 (NumIndexes != 8 && NumIndexes != 16))
760 return nullptr;
761
762 // For tbx instructions, the first argument is the "fallback" vector, which
763 // has the same length as the mask and return type.
764 unsigned int StartIndex = (unsigned)IsExtension;
765 auto *SourceTy =
766 cast<FixedVectorType>(Val: II.getArgOperand(i: StartIndex)->getType());
767 // Note that the element count of each source vector does *not* need to be the
768 // same as the element count of the return type and mask! All source vectors
769 // must have the same element count as each other, though.
770 unsigned NumElementsPerSource = SourceTy->getNumElements();
771
772 // There are no tbl/tbx intrinsics for which the destination size exceeds the
773 // source size. However, our definitions of the intrinsics, at least in
774 // IntrinsicsAArch64.td, allow for arbitrary destination vector sizes, so it
775 // *could* technically happen.
776 if (NumIndexes > NumElementsPerSource)
777 return nullptr;
778
779 // The tbl/tbx intrinsics take several source operands followed by a mask
780 // operand.
781 unsigned int NumSourceOperands = II.arg_size() - 1 - (unsigned)IsExtension;
782
783 // Map input operands to shuffle indices. This also helpfully deduplicates the
784 // input arguments, in case the same value is passed as an argument multiple
785 // times.
786 SmallDenseMap<Value *, unsigned, 2> ValueToShuffleSlot;
787 Value *ShuffleOperands[2] = {PoisonValue::get(T: SourceTy),
788 PoisonValue::get(T: SourceTy)};
789
790 int Indexes[16];
791 for (unsigned I = 0; I < NumIndexes; ++I) {
792 Constant *COp = C->getAggregateElement(Elt: I);
793
794 if (!COp || (!isa<UndefValue>(Val: COp) && !isa<ConstantInt>(Val: COp)))
795 return nullptr;
796
797 if (isa<UndefValue>(Val: COp)) {
798 Indexes[I] = -1;
799 continue;
800 }
801
802 uint64_t Index = cast<ConstantInt>(Val: COp)->getZExtValue();
803 // The index of the input argument that this index references (0 = first
804 // source argument, etc).
805 unsigned SourceOperandIndex = Index / NumElementsPerSource;
806 // The index of the element at that source operand.
807 unsigned SourceOperandElementIndex = Index % NumElementsPerSource;
808
809 Value *SourceOperand;
810 if (SourceOperandIndex >= NumSourceOperands) {
811 // This index is out of bounds. Map it to index into either the fallback
812 // vector (tbx) or vector of zeroes (tbl).
813 SourceOperandIndex = NumSourceOperands;
814 if (IsExtension) {
815 // For out-of-bounds indices in tbx, choose the `I`th element of the
816 // fallback.
817 SourceOperand = II.getArgOperand(i: 0);
818 SourceOperandElementIndex = I;
819 } else {
820 // Otherwise, choose some element from the dummy vector of zeroes (we'll
821 // always choose the first).
822 SourceOperand = Constant::getNullValue(Ty: SourceTy);
823 SourceOperandElementIndex = 0;
824 }
825 } else {
826 SourceOperand = II.getArgOperand(i: SourceOperandIndex + StartIndex);
827 }
828
829 // The source operand may be the fallback vector, which may not have the
830 // same number of elements as the source vector. In that case, we *could*
831 // choose to extend its length with another shufflevector, but it's simpler
832 // to just bail instead.
833 if (cast<FixedVectorType>(Val: SourceOperand->getType())->getNumElements() !=
834 NumElementsPerSource)
835 return nullptr;
836
837 // We now know the source operand referenced by this index. Make it a
838 // shufflevector operand, if it isn't already.
839 unsigned NumSlots = ValueToShuffleSlot.size();
840 // This shuffle references more than two sources, and hence cannot be
841 // represented as a shufflevector.
842 if (NumSlots == 2 && !ValueToShuffleSlot.contains(Val: SourceOperand))
843 return nullptr;
844
845 auto [It, Inserted] =
846 ValueToShuffleSlot.try_emplace(Key: SourceOperand, Args&: NumSlots);
847 if (Inserted)
848 ShuffleOperands[It->getSecond()] = SourceOperand;
849
850 unsigned RemappedIndex =
851 (It->getSecond() * NumElementsPerSource) + SourceOperandElementIndex;
852 Indexes[I] = RemappedIndex;
853 }
854
855 Value *Shuf = IC.Builder.CreateShuffleVector(
856 V1: ShuffleOperands[0], V2: ShuffleOperands[1], Mask: ArrayRef(Indexes, NumIndexes));
857 return IC.replaceInstUsesWith(I&: II, V: Shuf);
858}
859
860// Returns true iff the 2 intrinsics have the same operands, limiting the
861// comparison to the first NumOperands.
862static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
863 unsigned NumOperands) {
864 assert(I.arg_size() >= NumOperands && "Not enough operands");
865 assert(E.arg_size() >= NumOperands && "Not enough operands");
866 for (unsigned i = 0; i < NumOperands; i++)
867 if (I.getArgOperand(i) != E.getArgOperand(i))
868 return false;
869 return true;
870}
871
872// Remove trivially empty start/end intrinsic ranges, i.e. a start
873// immediately followed by an end (ignoring debuginfo or other
874// start/end intrinsics in between). As this handles only the most trivial
875// cases, tracking the nesting level is not needed:
876//
877// call @llvm.foo.start(i1 0)
878// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
879// call @llvm.foo.end(i1 0)
880// call @llvm.foo.end(i1 0) ; &I
881static bool
882removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,
883 std::function<bool(const IntrinsicInst &)> IsStart) {
884 // We start from the end intrinsic and scan backwards, so that InstCombine
885 // has already processed (and potentially removed) all the instructions
886 // before the end intrinsic.
887 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
888 for (; BI != BE; ++BI) {
889 if (auto *I = dyn_cast<IntrinsicInst>(Val: &*BI)) {
890 if (I->isDebugOrPseudoInst() ||
891 I->getIntrinsicID() == EndI.getIntrinsicID())
892 continue;
893 if (IsStart(*I)) {
894 if (haveSameOperands(I: EndI, E: *I, NumOperands: EndI.arg_size())) {
895 IC.eraseInstFromFunction(I&: *I);
896 IC.eraseInstFromFunction(I&: EndI);
897 return true;
898 }
899 // Skip start intrinsics that don't pair with this end intrinsic.
900 continue;
901 }
902 }
903 break;
904 }
905
906 return false;
907}
908
909Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {
910 removeTriviallyEmptyRange(EndI&: I, IC&: *this, IsStart: [&I](const IntrinsicInst &II) {
911 // Bail out on the case where the source va_list of a va_copy is destroyed
912 // immediately by a follow-up va_end.
913 return II.getIntrinsicID() == Intrinsic::vastart ||
914 (II.getIntrinsicID() == Intrinsic::vacopy &&
915 I.getArgOperand(i: 0) != II.getArgOperand(i: 1));
916 });
917 return nullptr;
918}
919
920static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {
921 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
922 Value *Arg0 = Call.getArgOperand(i: 0), *Arg1 = Call.getArgOperand(i: 1);
923 if (isa<Constant>(Val: Arg0) && !isa<Constant>(Val: Arg1)) {
924 Call.setArgOperand(i: 0, v: Arg1);
925 Call.setArgOperand(i: 1, v: Arg0);
926 AttributeList CallAttr = Call.getAttributes();
927 AttributeSet LHSAttr = CallAttr.getParamAttrs(ArgNo: 0);
928 AttributeSet RHSAttr = CallAttr.getParamAttrs(ArgNo: 1);
929 LLVMContext &Ctx = Call.getContext();
930 Call.setAttributes(CallAttr
931 .setAttributesAtIndex(
932 C&: Ctx, Index: AttributeList::FirstArgIndex + 0, Attrs: RHSAttr)
933 .setAttributesAtIndex(
934 C&: Ctx, Index: AttributeList::FirstArgIndex + 1, Attrs: LHSAttr));
935 return &Call;
936 }
937 return nullptr;
938}
939
940/// Creates a result tuple for an overflow intrinsic \p II with a given
941/// \p Result and a constant \p Overflow value.
942static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,
943 Constant *Overflow) {
944 Constant *V[] = {PoisonValue::get(T: Result->getType()), Overflow};
945 StructType *ST = cast<StructType>(Val: II->getType());
946 Constant *Struct = ConstantStruct::get(T: ST, V);
947 return InsertValueInst::Create(Agg: Struct, Val: Result, Idxs: 0);
948}
949
950Instruction *
951InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
952 WithOverflowInst *WO = cast<WithOverflowInst>(Val: II);
953 Value *OperationResult = nullptr;
954 Constant *OverflowResult = nullptr;
955 if (OptimizeOverflowCheck(BinaryOp: WO->getBinaryOp(), IsSigned: WO->isSigned(), LHS: WO->getLHS(),
956 RHS: WO->getRHS(), CtxI&: *WO, OperationResult, OverflowResult))
957 return createOverflowTuple(II: WO, Result: OperationResult, Overflow: OverflowResult);
958
959 // See whether we can optimize the overflow check with assumption information.
960 for (User *U : WO->users()) {
961 if (!match(V: U, P: m_ExtractValue<1>(V: m_Value())))
962 continue;
963
964 for (auto &AssumeVH : AC.assumptionsFor(V: U)) {
965 if (!AssumeVH)
966 continue;
967 CallInst *I = cast<CallInst>(Val&: AssumeVH);
968 if (!match(V: I->getArgOperand(i: 0), P: m_Not(V: m_Specific(V: U))))
969 continue;
970 if (!isValidAssumeForContext(I, CxtI: II, /*DT=*/nullptr,
971 /*AllowEphemerals=*/true))
972 continue;
973 Value *Result =
974 Builder.CreateBinOp(Opc: WO->getBinaryOp(), LHS: WO->getLHS(), RHS: WO->getRHS());
975 Result->takeName(V: WO);
976 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
977 if (WO->isSigned())
978 Inst->setHasNoSignedWrap();
979 else
980 Inst->setHasNoUnsignedWrap();
981 }
982 return createOverflowTuple(II: WO, Result,
983 Overflow: ConstantInt::getFalse(Ty: U->getType()));
984 }
985 }
986
987 return nullptr;
988}
989
990static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
991 Ty = Ty->getScalarType();
992 return F.getDenormalMode(FPType: Ty->getFltSemantics()).Input == DenormalMode::IEEE;
993}
994
995static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
996 Ty = Ty->getScalarType();
997 return F.getDenormalMode(FPType: Ty->getFltSemantics()).inputsAreZero();
998}
999
1000/// \returns the compare predicate type if the test performed by
1001/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
1002/// floating-point environment assumed for \p F for type \p Ty
1003static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask,
1004 const Function &F, Type *Ty) {
1005 switch (static_cast<unsigned>(Mask)) {
1006 case fcZero:
1007 if (inputDenormalIsIEEE(F, Ty))
1008 return FCmpInst::FCMP_OEQ;
1009 break;
1010 case fcZero | fcSubnormal:
1011 if (inputDenormalIsDAZ(F, Ty))
1012 return FCmpInst::FCMP_OEQ;
1013 break;
1014 case fcPositive | fcNegZero:
1015 if (inputDenormalIsIEEE(F, Ty))
1016 return FCmpInst::FCMP_OGE;
1017 break;
1018 case fcPositive | fcNegZero | fcNegSubnormal:
1019 if (inputDenormalIsDAZ(F, Ty))
1020 return FCmpInst::FCMP_OGE;
1021 break;
1022 case fcPosSubnormal | fcPosNormal | fcPosInf:
1023 if (inputDenormalIsIEEE(F, Ty))
1024 return FCmpInst::FCMP_OGT;
1025 break;
1026 case fcNegative | fcPosZero:
1027 if (inputDenormalIsIEEE(F, Ty))
1028 return FCmpInst::FCMP_OLE;
1029 break;
1030 case fcNegative | fcPosZero | fcPosSubnormal:
1031 if (inputDenormalIsDAZ(F, Ty))
1032 return FCmpInst::FCMP_OLE;
1033 break;
1034 case fcNegSubnormal | fcNegNormal | fcNegInf:
1035 if (inputDenormalIsIEEE(F, Ty))
1036 return FCmpInst::FCMP_OLT;
1037 break;
1038 case fcPosNormal | fcPosInf:
1039 if (inputDenormalIsDAZ(F, Ty))
1040 return FCmpInst::FCMP_OGT;
1041 break;
1042 case fcNegNormal | fcNegInf:
1043 if (inputDenormalIsDAZ(F, Ty))
1044 return FCmpInst::FCMP_OLT;
1045 break;
1046 case ~fcZero & ~fcNan:
1047 if (inputDenormalIsIEEE(F, Ty))
1048 return FCmpInst::FCMP_ONE;
1049 break;
1050 case ~(fcZero | fcSubnormal) & ~fcNan:
1051 if (inputDenormalIsDAZ(F, Ty))
1052 return FCmpInst::FCMP_ONE;
1053 break;
1054 default:
1055 break;
1056 }
1057
1058 return FCmpInst::BAD_FCMP_PREDICATE;
1059}
1060
1061Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
1062 Value *Src0 = II.getArgOperand(i: 0);
1063 Value *Src1 = II.getArgOperand(i: 1);
1064 const ConstantInt *CMask = cast<ConstantInt>(Val: Src1);
1065 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
1066 const bool IsUnordered = (Mask & fcNan) == fcNan;
1067 const bool IsOrdered = (Mask & fcNan) == fcNone;
1068 const FPClassTest OrderedMask = Mask & ~fcNan;
1069 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
1070
1071 const bool IsStrict =
1072 II.getFunction()->getAttributes().hasFnAttr(Kind: Attribute::StrictFP);
1073
1074 Value *FNegSrc;
1075 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
1076 if (match(V: Src0, P: m_FNeg(X: m_Value(V&: FNegSrc))))
1077 return CallInst::Create(
1078 Func: II.getCalledFunction(),
1079 Args: {FNegSrc, ConstantInt::get(Ty: Src1->getType(), V: fneg(Mask))});
1080
1081 Value *FAbsSrc;
1082 if (match(V: Src0, P: m_FAbs(Op0: m_Value(V&: FAbsSrc))))
1083 return CallInst::Create(
1084 Func: II.getCalledFunction(),
1085 Args: {FAbsSrc, ConstantInt::get(Ty: Src1->getType(), V: inverse_fabs(Mask))});
1086
1087 if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&
1088 (IsOrdered || IsUnordered) && !IsStrict) {
1089 // is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf
1090 // is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf
1091 // is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf
1092 // is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf
1093 Constant *Inf = ConstantFP::getInfinity(Ty: Src0->getType());
1094 FCmpInst::Predicate Pred =
1095 IsUnordered ? FCmpInst::FCMP_UEQ : FCmpInst::FCMP_OEQ;
1096 if (OrderedInvertedMask == fcInf)
1097 Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;
1098
1099 Value *Fabs = Builder.CreateFAbs(V: Src0);
1100 Value *CmpInf = Builder.CreateFCmp(P: Pred, LHS: Fabs, RHS: Inf);
1101 CmpInf->takeName(V: &II);
1102 return replaceInstUsesWith(I&: II, V: CmpInf);
1103 }
1104
1105 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
1106 (IsOrdered || IsUnordered) && !IsStrict) {
1107 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
1108 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
1109 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
1110 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
1111 Constant *Inf =
1112 ConstantFP::getInfinity(Ty: Src0->getType(), Negative: OrderedMask == fcNegInf);
1113 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(LHS: Src0, RHS: Inf)
1114 : Builder.CreateFCmpOEQ(LHS: Src0, RHS: Inf);
1115
1116 EqInf->takeName(V: &II);
1117 return replaceInstUsesWith(I&: II, V: EqInf);
1118 }
1119
1120 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
1121 (IsOrdered || IsUnordered) && !IsStrict) {
1122 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
1123 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
1124 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
1125 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
1126 Constant *Inf = ConstantFP::getInfinity(Ty: Src0->getType(),
1127 Negative: OrderedInvertedMask == fcNegInf);
1128 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(LHS: Src0, RHS: Inf)
1129 : Builder.CreateFCmpONE(LHS: Src0, RHS: Inf);
1130 NeInf->takeName(V: &II);
1131 return replaceInstUsesWith(I&: II, V: NeInf);
1132 }
1133
1134 if (Mask == fcNan && !IsStrict) {
1135 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
1136 // exceptions.
1137 Value *IsNan =
1138 Builder.CreateFCmpUNO(LHS: Src0, RHS: ConstantFP::getZero(Ty: Src0->getType()));
1139 IsNan->takeName(V: &II);
1140 return replaceInstUsesWith(I&: II, V: IsNan);
1141 }
1142
1143 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
1144 // Equivalent of !isnan. Replace with standard fcmp.
1145 Value *FCmp =
1146 Builder.CreateFCmpORD(LHS: Src0, RHS: ConstantFP::getZero(Ty: Src0->getType()));
1147 FCmp->takeName(V: &II);
1148 return replaceInstUsesWith(I&: II, V: FCmp);
1149 }
1150
1151 FCmpInst::Predicate PredType = FCmpInst::BAD_FCMP_PREDICATE;
1152
1153 // Try to replace with an fcmp with 0
1154 //
1155 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
1156 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
1157 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
1158 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
1159 //
1160 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
1161 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
1162 //
1163 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
1164 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
1165 //
1166 if (!IsStrict && (IsOrdered || IsUnordered) &&
1167 (PredType = fpclassTestIsFCmp0(Mask: OrderedMask, F: *II.getFunction(),
1168 Ty: Src0->getType())) !=
1169 FCmpInst::BAD_FCMP_PREDICATE) {
1170 Constant *Zero = ConstantFP::getZero(Ty: Src0->getType());
1171 // Equivalent of == 0.
1172 Value *FCmp = Builder.CreateFCmp(
1173 P: IsUnordered ? FCmpInst::getUnorderedPredicate(Pred: PredType) : PredType,
1174 LHS: Src0, RHS: Zero);
1175
1176 FCmp->takeName(V: &II);
1177 return replaceInstUsesWith(I&: II, V: FCmp);
1178 }
1179
1180 KnownFPClass Known =
1181 computeKnownFPClass(V: Src0, InterestedClasses: Mask, SQ: SQ.getWithInstruction(I: &II));
1182
1183 // Clear test bits we know must be false from the source value.
1184 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
1185 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
1186 if ((Mask & Known.KnownFPClasses) != Mask) {
1187 II.setArgOperand(
1188 i: 1, v: ConstantInt::get(Ty: Src1->getType(), V: Mask & Known.KnownFPClasses));
1189 return &II;
1190 }
1191
1192 // If none of the tests which can return false are possible, fold to true.
1193 // fp_class (nnan x), ~(qnan|snan) -> true
1194 // fp_class (ninf x), ~(ninf|pinf) -> true
1195 if (Mask == Known.KnownFPClasses)
1196 return replaceInstUsesWith(I&: II, V: ConstantInt::get(Ty: II.getType(), V: true));
1197
1198 return nullptr;
1199}
1200
1201static std::optional<bool> getKnownSign(Value *Op, const SimplifyQuery &SQ) {
1202 KnownBits Known = computeKnownBits(V: Op, Q: SQ);
1203 if (Known.isNonNegative())
1204 return false;
1205 if (Known.isNegative())
1206 return true;
1207
1208 Value *X, *Y;
1209 if (match(V: Op, P: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y))))
1210 return isImpliedByDomCondition(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y, ContextI: SQ.CxtI, DL: SQ.DL);
1211
1212 return std::nullopt;
1213}
1214
1215static std::optional<bool> getKnownSignOrZero(Value *Op,
1216 const SimplifyQuery &SQ) {
1217 if (std::optional<bool> Sign = getKnownSign(Op, SQ))
1218 return Sign;
1219
1220 Value *X, *Y;
1221 if (match(V: Op, P: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y))))
1222 return isImpliedByDomCondition(Pred: ICmpInst::ICMP_SLE, LHS: X, RHS: Y, ContextI: SQ.CxtI, DL: SQ.DL);
1223
1224 return std::nullopt;
1225}
1226
1227/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.
1228static bool signBitMustBeTheSame(Value *Op0, Value *Op1,
1229 const SimplifyQuery &SQ) {
1230 std::optional<bool> Known1 = getKnownSign(Op: Op1, SQ);
1231 if (!Known1)
1232 return false;
1233 std::optional<bool> Known0 = getKnownSign(Op: Op0, SQ);
1234 if (!Known0)
1235 return false;
1236 return *Known0 == *Known1;
1237}
1238
1239// Determines if ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b)) is safe.
1240//
1241// This is true if, when the add saturates, the resulting ldexp is guaranteed to
1242// produce 0 or inf.
1243static bool ldexpSaturatingAddIsSafe(Type *FpTy, Type *ExpTy) {
1244 const fltSemantics &FltSem = FpTy->getScalarType()->getFltSemantics();
1245 if (!APFloat::semanticsHasInf(FltSem))
1246 return false;
1247
1248 // Cap ExpBits at 32 because scalbn takes an int. This is sufficient for any
1249 // reasonable fp type (for example, `double` only has 11 exponent bits).
1250 unsigned ExpBits = std::min(a: ExpTy->getScalarSizeInBits(), b: 32u);
1251 int SignedMax = static_cast<int>(maxIntN(N: ExpBits));
1252 int SignedMin = static_cast<int>(minIntN(N: ExpBits));
1253 APFloat ScaledUp = scalbn(X: APFloat::getSmallest(Sem: FltSem), Exp: SignedMax,
1254 RM: APFloat::rmNearestTiesToEven);
1255 APFloat ScaledDown = scalbn(X: APFloat::getLargest(Sem: FltSem), Exp: SignedMin,
1256 RM: APFloat::rmNearestTiesToEven);
1257 return ScaledUp.isInfinity() && ScaledDown.isZero();
1258}
1259
1260/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1261/// can trigger other combines.
1262static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
1263 InstCombiner::BuilderTy &Builder) {
1264 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1265 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1266 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1267 "Expected a min or max intrinsic");
1268
1269 // TODO: Match vectors with undef elements, but undef may not propagate.
1270 Value *Op0 = II->getArgOperand(i: 0), *Op1 = II->getArgOperand(i: 1);
1271 Value *X;
1272 const APInt *C0, *C1;
1273 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C0)))) ||
1274 !match(V: Op1, P: m_APInt(Res&: C1)))
1275 return nullptr;
1276
1277 // Check for necessary no-wrap and overflow constraints.
1278 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1279 auto *Add = cast<BinaryOperator>(Val: Op0);
1280 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1281 (!IsSigned && !Add->hasNoUnsignedWrap()))
1282 return nullptr;
1283
1284 // If the constant difference overflows, then instsimplify should reduce the
1285 // min/max to the add or C1.
1286 bool Overflow;
1287 APInt CDiff =
1288 IsSigned ? C1->ssub_ov(RHS: *C0, Overflow) : C1->usub_ov(RHS: *C0, Overflow);
1289 assert(!Overflow && "Expected simplify of min/max");
1290
1291 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1292 // Note: the "mismatched" no-overflow setting does not propagate.
1293 Constant *NewMinMaxC = ConstantInt::get(Ty: II->getType(), V: CDiff);
1294 Value *NewMinMax = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS: NewMinMaxC);
1295 return IsSigned ? BinaryOperator::CreateNSWAdd(V1: NewMinMax, V2: Add->getOperand(i_nocapture: 1))
1296 : BinaryOperator::CreateNUWAdd(V1: NewMinMax, V2: Add->getOperand(i_nocapture: 1));
1297}
1298/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1299Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1300 Type *Ty = MinMax1.getType();
1301
1302 // We are looking for a tree of:
1303 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1304 // Where the min and max could be reversed
1305 Instruction *MinMax2;
1306 BinaryOperator *AddSub;
1307 const APInt *MinValue, *MaxValue;
1308 if (match(V: &MinMax1, P: m_SMin(Op0: m_Instruction(I&: MinMax2), Op1: m_APInt(Res&: MaxValue)))) {
1309 if (!match(V: MinMax2, P: m_SMax(Op0: m_BinOp(I&: AddSub), Op1: m_APInt(Res&: MinValue))))
1310 return nullptr;
1311 } else if (match(V: &MinMax1,
1312 P: m_SMax(Op0: m_Instruction(I&: MinMax2), Op1: m_APInt(Res&: MinValue)))) {
1313 if (!match(V: MinMax2, P: m_SMin(Op0: m_BinOp(I&: AddSub), Op1: m_APInt(Res&: MaxValue))))
1314 return nullptr;
1315 } else
1316 return nullptr;
1317
1318 // Check that the constants clamp a saturate, and that the new type would be
1319 // sensible to convert to.
1320 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1321 return nullptr;
1322 // In what bitwidth can this be treated as saturating arithmetics?
1323 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1324 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1325 // good first approximation for what should be done there.
1326 if (!shouldChangeType(FromBitWidth: Ty->getScalarType()->getIntegerBitWidth(), ToBitWidth: NewBitWidth))
1327 return nullptr;
1328
1329 // Also make sure that the inner min/max and the add/sub have one use.
1330 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1331 return nullptr;
1332
1333 // Create the new type (which can be a vector type)
1334 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1335
1336 Intrinsic::ID IntrinsicID;
1337 if (AddSub->getOpcode() == Instruction::Add)
1338 IntrinsicID = Intrinsic::sadd_sat;
1339 else if (AddSub->getOpcode() == Instruction::Sub)
1340 IntrinsicID = Intrinsic::ssub_sat;
1341 else
1342 return nullptr;
1343
1344 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1345 // is usually achieved via a sext from a smaller type.
1346 if (ComputeMaxSignificantBits(Op: AddSub->getOperand(i_nocapture: 0), CxtI: AddSub) > NewBitWidth ||
1347 ComputeMaxSignificantBits(Op: AddSub->getOperand(i_nocapture: 1), CxtI: AddSub) > NewBitWidth)
1348 return nullptr;
1349
1350 // Finally create and return the sat intrinsic, truncated to the new type
1351 Value *AT = Builder.CreateTrunc(V: AddSub->getOperand(i_nocapture: 0), DestTy: NewTy);
1352 Value *BT = Builder.CreateTrunc(V: AddSub->getOperand(i_nocapture: 1), DestTy: NewTy);
1353 Value *Sat = Builder.CreateIntrinsic(ID: IntrinsicID, OverloadTypes: NewTy, Args: {AT, BT});
1354 return CastInst::Create(Instruction::SExt, S: Sat, Ty);
1355}
1356
1357
1358/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1359/// can only be one of two possible constant values -- turn that into a select
1360/// of constants.
1361static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,
1362 InstCombiner::BuilderTy &Builder) {
1363 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
1364 Value *X;
1365 const APInt *C0, *C1;
1366 if (!match(V: I1, P: m_APInt(Res&: C1)) || !I0->hasOneUse())
1367 return nullptr;
1368
1369 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
1370 switch (II->getIntrinsicID()) {
1371 case Intrinsic::smax:
1372 if (match(V: I0, P: m_SMin(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C0 == *C1 + 1)
1373 Pred = ICmpInst::ICMP_SGT;
1374 break;
1375 case Intrinsic::smin:
1376 if (match(V: I0, P: m_SMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C1 == *C0 + 1)
1377 Pred = ICmpInst::ICMP_SLT;
1378 break;
1379 case Intrinsic::umax:
1380 if (match(V: I0, P: m_UMin(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C0 == *C1 + 1)
1381 Pred = ICmpInst::ICMP_UGT;
1382 break;
1383 case Intrinsic::umin:
1384 if (match(V: I0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C0))) && *C1 == *C0 + 1)
1385 Pred = ICmpInst::ICMP_ULT;
1386 break;
1387 default:
1388 llvm_unreachable("Expected min/max intrinsic");
1389 }
1390 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1391 return nullptr;
1392
1393 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1394 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1395 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: X, RHS: I1);
1396 return SelectInst::Create(C: Cmp, S1: ConstantInt::get(Ty: II->getType(), V: *C0), S2: I1);
1397}
1398
1399/// If this min/max has a constant operand and an operand that is a matching
1400/// min/max with a constant operand, constant-fold the 2 constant operands.
1401static Value *reassociateMinMaxWithConstants(IntrinsicInst *II,
1402 IRBuilderBase &Builder,
1403 const SimplifyQuery &SQ) {
1404 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1405 auto *LHS = dyn_cast<MinMaxIntrinsic>(Val: II->getArgOperand(i: 0));
1406 if (!LHS)
1407 return nullptr;
1408
1409 Constant *C0, *C1;
1410 if (!match(V: LHS->getArgOperand(i: 1), P: m_ImmConstant(C&: C0)) ||
1411 !match(V: II->getArgOperand(i: 1), P: m_ImmConstant(C&: C1)))
1412 return nullptr;
1413
1414 // max (max X, C0), C1 --> max X, (max C0, C1)
1415 // min (min X, C0), C1 --> min X, (min C0, C1)
1416 // umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)
1417 // smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)
1418 Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();
1419 if (InnerMinMaxID != MinMaxID &&
1420 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1421 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1422 isKnownNonNegative(V: C0, SQ) && isKnownNonNegative(V: C1, SQ)))
1423 return nullptr;
1424
1425 ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(ID: MinMaxID);
1426 Value *CondC = Builder.CreateICmp(P: Pred, LHS: C0, RHS: C1);
1427 Value *NewC = Builder.CreateSelect(C: CondC, True: C0, False: C1);
1428 return Builder.CreateIntrinsic(ID: InnerMinMaxID, OverloadTypes: II->getType(),
1429 Args: {LHS->getArgOperand(i: 0), NewC});
1430}
1431
1432/// If this min/max has a matching min/max operand with a constant, try to push
1433/// the constant operand into this instruction. This can enable more folds.
1434static Instruction *
1435reassociateMinMaxWithConstantInOperand(IntrinsicInst *II,
1436 InstCombiner::BuilderTy &Builder) {
1437 // Match and capture a min/max operand candidate.
1438 Value *X, *Y;
1439 Constant *C;
1440 Instruction *Inner;
1441 if (!match(V: II, P: m_c_MaxOrMin(L: m_OneUse(SubPattern: m_CombineAnd(
1442 Ps: m_Instruction(I&: Inner),
1443 Ps: m_MaxOrMin(Op0: m_Value(V&: X), Op1: m_ImmConstant(C)))),
1444 R: m_Value(V&: Y))))
1445 return nullptr;
1446
1447 // The inner op must match. Check for constants to avoid infinite loops.
1448 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1449 auto *InnerMM = dyn_cast<IntrinsicInst>(Val: Inner);
1450 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1451 match(V: X, P: m_ImmConstant()) || match(V: Y, P: m_ImmConstant()))
1452 return nullptr;
1453
1454 // max (max X, C), Y --> max (max X, Y), C
1455 Function *MinMax = Intrinsic::getOrInsertDeclaration(M: II->getModule(),
1456 id: MinMaxID, OverloadTys: II->getType());
1457 Value *NewInner = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS: Y);
1458 NewInner->takeName(V: Inner);
1459 return CallInst::Create(Func: MinMax, Args: {NewInner, C});
1460}
1461
1462/// Reduce a sequence of min/max intrinsics with a common operand.
1463static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {
1464 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1465 auto *LHS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0));
1466 auto *RHS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 1));
1467 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1468 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1469 RHS->getIntrinsicID() != MinMaxID ||
1470 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1471 return nullptr;
1472
1473 Value *A = LHS->getArgOperand(i: 0);
1474 Value *B = LHS->getArgOperand(i: 1);
1475 Value *C = RHS->getArgOperand(i: 0);
1476 Value *D = RHS->getArgOperand(i: 1);
1477
1478 // Look for a common operand.
1479 Value *MinMaxOp = nullptr;
1480 Value *ThirdOp = nullptr;
1481 if (LHS->hasOneUse()) {
1482 // If the LHS is only used in this chain and the RHS is used outside of it,
1483 // reuse the RHS min/max because that will eliminate the LHS.
1484 if (D == A || C == A) {
1485 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1486 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1487 MinMaxOp = RHS;
1488 ThirdOp = B;
1489 } else if (D == B || C == B) {
1490 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1491 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1492 MinMaxOp = RHS;
1493 ThirdOp = A;
1494 }
1495 } else {
1496 assert(RHS->hasOneUse() && "Expected one-use operand");
1497 // Reuse the LHS. This will eliminate the RHS.
1498 if (D == A || D == B) {
1499 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1500 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1501 MinMaxOp = LHS;
1502 ThirdOp = C;
1503 } else if (C == A || C == B) {
1504 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1505 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1506 MinMaxOp = LHS;
1507 ThirdOp = D;
1508 }
1509 }
1510
1511 if (!MinMaxOp || !ThirdOp)
1512 return nullptr;
1513
1514 Module *Mod = II->getModule();
1515 Function *MinMax =
1516 Intrinsic::getOrInsertDeclaration(M: Mod, id: MinMaxID, OverloadTys: II->getType());
1517 return CallInst::Create(Func: MinMax, Args: { MinMaxOp, ThirdOp });
1518}
1519
1520/// If all arguments of the intrinsic are unary shuffles with the same mask,
1521/// try to shuffle after the intrinsic.
1522Instruction *
1523InstCombinerImpl::foldShuffledIntrinsicOperands(IntrinsicInst *II) {
1524 if (!II->getType()->isVectorTy() ||
1525 !isTriviallyVectorizable(ID: II->getIntrinsicID()) ||
1526 !II->getCalledFunction()->isSpeculatable())
1527 return nullptr;
1528
1529 Value *X;
1530 Constant *C;
1531 ArrayRef<int> Mask;
1532 auto *NonConstArg = find_if_not(Range: II->args(), P: [&II](Use &Arg) {
1533 return isa<Constant>(Val: Arg.get()) ||
1534 isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1535 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr);
1536 });
1537 if (!NonConstArg ||
1538 !match(V: NonConstArg, P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_Mask(Mask))))
1539 return nullptr;
1540
1541 // At least 1 operand must be a shuffle with 1 use because we are creating 2
1542 // instructions.
1543 if (none_of(Range: II->args(), P: match_fn(P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(), v2: m_Value())))))
1544 return nullptr;
1545
1546 // See if all arguments are shuffled with the same mask.
1547 SmallVector<Value *, 4> NewArgs;
1548 Type *SrcTy = X->getType();
1549 for (Use &Arg : II->args()) {
1550 if (isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1551 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr))
1552 NewArgs.push_back(Elt: Arg);
1553 else if (match(V: &Arg,
1554 P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_SpecificMask(Mask))) &&
1555 X->getType() == SrcTy)
1556 NewArgs.push_back(Elt: X);
1557 else if (match(V: &Arg, P: m_ImmConstant(C))) {
1558 // If it's a constant, try find the constant that would be shuffled to C.
1559 if (Constant *ShuffledC =
1560 unshuffleConstant(ShMask: Mask, C, NewCTy: cast<VectorType>(Val: SrcTy)))
1561 NewArgs.push_back(Elt: ShuffledC);
1562 else
1563 return nullptr;
1564 } else
1565 return nullptr;
1566 }
1567
1568 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1569 Instruction *FPI = isa<FPMathOperator>(Val: II) ? II : nullptr;
1570 // Result type might be a different vector width.
1571 // TODO: Check that the result type isn't widened?
1572 VectorType *ResTy =
1573 VectorType::get(ElementType: II->getType()->getScalarType(), Other: cast<VectorType>(Val: SrcTy));
1574 Value *NewIntrinsic =
1575 Builder.CreateIntrinsic(RetTy: ResTy, ID: II->getIntrinsicID(), Args: NewArgs, FMFSource: FPI);
1576 return new ShuffleVectorInst(NewIntrinsic, Mask);
1577}
1578
1579/// If all arguments of the intrinsic are reverses, try to pull the reverse
1580/// after the intrinsic.
1581Value *InstCombinerImpl::foldReversedIntrinsicOperands(IntrinsicInst *II) {
1582 if (!II->getType()->isVectorTy() ||
1583 !isTriviallyVectorizable(ID: II->getIntrinsicID()))
1584 return nullptr;
1585
1586 // At least 1 operand must be a reverse with 1 use because we are creating 2
1587 // instructions.
1588 if (none_of(Range: II->args(), P: [](Value *V) {
1589 return match(V, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value())));
1590 }))
1591 return nullptr;
1592
1593 Value *X;
1594 Constant *C;
1595 SmallVector<Value *> NewArgs;
1596 for (Use &Arg : II->args()) {
1597 if (isVectorIntrinsicWithScalarOpAtArg(ID: II->getIntrinsicID(),
1598 ScalarOpdIdx: Arg.getOperandNo(), TTI: nullptr))
1599 NewArgs.push_back(Elt: Arg);
1600 else if (match(V: &Arg, P: m_VecReverse(Op0: m_Value(V&: X))))
1601 NewArgs.push_back(Elt: X);
1602 else if (isSplatValue(V: Arg))
1603 NewArgs.push_back(Elt: Arg);
1604 else if (match(V: &Arg, P: m_ImmConstant(C)))
1605 NewArgs.push_back(Elt: Builder.CreateVectorReverse(V: C));
1606 else
1607 return nullptr;
1608 }
1609
1610 // intrinsic (reverse X), (reverse Y), ... --> reverse (intrinsic X, Y, ...)
1611 Instruction *FPI = isa<FPMathOperator>(Val: II) ? II : nullptr;
1612 Value *NewIntrinsic = Builder.CreateIntrinsic(
1613 RetTy: II->getType(), ID: II->getIntrinsicID(), Args: NewArgs, FMFSource: FPI);
1614 return Builder.CreateVectorReverse(V: NewIntrinsic);
1615}
1616
1617/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1618/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1619/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1620template <Intrinsic::ID IntrID>
1621static Instruction *foldBitOrderCrossLogicOp(Value *V,
1622 InstCombiner::BuilderTy &Builder) {
1623 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1624 "This helper only supports BSWAP and BITREVERSE intrinsics");
1625
1626 Value *X, *Y;
1627 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1628 // don't match ConstantExpr that aren't meaningful for this transform.
1629 if (match(V, P: m_OneUse(SubPattern: m_BitwiseLogic(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
1630 isa<BinaryOperator>(Val: V)) {
1631 Value *OldReorderX, *OldReorderY;
1632 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(Val: V)->getOpcode();
1633
1634 // If both X and Y are bswap/bitreverse, the transform reduces the number
1635 // of instructions even if there's multiuse.
1636 // If only one operand is bswap/bitreverse, we need to ensure the operand
1637 // have only one use.
1638 if (match(X, m_Intrinsic<IntrID>(m_Value(V&: OldReorderX))) &&
1639 match(Y, m_Intrinsic<IntrID>(m_Value(V&: OldReorderY)))) {
1640 return BinaryOperator::Create(Op, S1: OldReorderX, S2: OldReorderY);
1641 }
1642
1643 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: OldReorderX))))) {
1644 Value *NewReorder = Builder.CreateUnaryIntrinsic(ID: IntrID, Op: Y);
1645 return BinaryOperator::Create(Op, S1: OldReorderX, S2: NewReorder);
1646 }
1647
1648 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: OldReorderY))))) {
1649 Value *NewReorder = Builder.CreateUnaryIntrinsic(ID: IntrID, Op: X);
1650 return BinaryOperator::Create(Op, S1: NewReorder, S2: OldReorderY);
1651 }
1652 }
1653 return nullptr;
1654}
1655
1656/// Helper to match idempotent binary intrinsics, namely, intrinsics where
1657/// `f(f(x, y), y) == f(x, y)` holds.
1658static bool isIdempotentBinaryIntrinsic(Intrinsic::ID IID) {
1659 switch (IID) {
1660 case Intrinsic::smax:
1661 case Intrinsic::smin:
1662 case Intrinsic::umax:
1663 case Intrinsic::umin:
1664 case Intrinsic::maximum:
1665 case Intrinsic::minimum:
1666 case Intrinsic::maximumnum:
1667 case Intrinsic::minimumnum:
1668 case Intrinsic::maxnum:
1669 case Intrinsic::minnum:
1670 return true;
1671 default:
1672 return false;
1673 }
1674}
1675
1676/// Attempt to simplify value-accumulating recurrences of kind:
1677/// %umax.acc = phi i8 [ %umax, %backedge ], [ %a, %entry ]
1678/// %umax = call i8 @llvm.umax.i8(i8 %umax.acc, i8 %b)
1679/// And let the idempotent binary intrinsic be hoisted, when the operands are
1680/// known to be loop-invariant.
1681static Value *foldIdempotentBinaryIntrinsicRecurrence(InstCombinerImpl &IC,
1682 IntrinsicInst *II) {
1683 PHINode *PN;
1684 Value *Init, *OtherOp;
1685
1686 // A binary intrinsic recurrence with loop-invariant operands is equivalent to
1687 // `call @llvm.binary.intrinsic(Init, OtherOp)`.
1688 auto IID = II->getIntrinsicID();
1689 if (!isIdempotentBinaryIntrinsic(IID) ||
1690 !matchSimpleBinaryIntrinsicRecurrence(I: II, P&: PN, Init, OtherOp) ||
1691 !IC.getDominatorTree().dominates(Def: OtherOp, User: PN))
1692 return nullptr;
1693
1694 auto *InvariantBinaryInst =
1695 IC.Builder.CreateBinaryIntrinsic(ID: IID, LHS: Init, RHS: OtherOp);
1696 if (isa<FPMathOperator>(Val: InvariantBinaryInst))
1697 cast<Instruction>(Val: InvariantBinaryInst)->copyFastMathFlags(I: II);
1698 return InvariantBinaryInst;
1699}
1700
1701static Value *simplifyReductionOperand(Value *Arg, bool CanReorderLanes) {
1702 if (!CanReorderLanes)
1703 return nullptr;
1704
1705 Value *V;
1706 if (match(V: Arg, P: m_VecReverse(Op0: m_Value(V))))
1707 return V;
1708
1709 ArrayRef<int> Mask;
1710 if (!isa<FixedVectorType>(Val: Arg->getType()) ||
1711 !match(V: Arg, P: m_Shuffle(v1: m_Value(V), v2: m_Undef(), mask: m_Mask(Mask))) ||
1712 !cast<ShuffleVectorInst>(Val: Arg)->isSingleSource())
1713 return nullptr;
1714
1715 int Sz = Mask.size();
1716 SmallBitVector UsedIndices(Sz);
1717 for (int Idx : Mask) {
1718 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
1719 return nullptr;
1720 UsedIndices.set(Idx);
1721 }
1722
1723 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
1724 // other changes.
1725 return UsedIndices.all() ? V : nullptr;
1726}
1727
1728/// Fold an unsigned minimum of trailing or leading zero bits counts:
1729/// umin(cttz(CtOp1, ZeroUndef), ConstOp) --> cttz(CtOp1 | (1 << ConstOp))
1730/// umin(ctlz(CtOp1, ZeroUndef), ConstOp) --> ctlz(CtOp1 | (SignedMin
1731/// >> ConstOp))
1732/// umin(cttz(CtOp1), cttz(CtOp2)) --> cttz(CtOp1 | CtOp2)
1733/// umin(ctlz(CtOp1), ctlz(CtOp2)) --> ctlz(CtOp1 | CtOp2)
1734template <Intrinsic::ID IntrID>
1735static Value *
1736foldMinimumOverTrailingOrLeadingZeroCount(Value *I0, Value *I1,
1737 const DataLayout &DL,
1738 InstCombiner::BuilderTy &Builder) {
1739 static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,
1740 "This helper only supports cttz and ctlz intrinsics");
1741
1742 Value *CtOp1, *CtOp2;
1743 Value *ZeroUndef1, *ZeroUndef2;
1744 if (!match(I0, m_OneUse(
1745 m_Intrinsic<IntrID>(m_Value(V&: CtOp1), m_Value(V&: ZeroUndef1)))))
1746 return nullptr;
1747
1748 if (match(I1,
1749 m_OneUse(m_Intrinsic<IntrID>(m_Value(V&: CtOp2), m_Value(V&: ZeroUndef2)))))
1750 return Builder.CreateBinaryIntrinsic(
1751 ID: IntrID, LHS: Builder.CreateOr(LHS: CtOp1, RHS: CtOp2),
1752 RHS: Builder.CreateOr(LHS: ZeroUndef1, RHS: ZeroUndef2));
1753
1754 unsigned BitWidth = I1->getType()->getScalarSizeInBits();
1755 auto LessBitWidth = [BitWidth](auto &C) { return C.ult(BitWidth); };
1756 if (!match(I1, m_CheckedInt(LessBitWidth)))
1757 // We have a constant >= BitWidth (which can be handled by CVP)
1758 // or a non-splat vector with elements < and >= BitWidth
1759 return nullptr;
1760
1761 Type *Ty = I1->getType();
1762 Constant *NewConst = ConstantFoldBinaryOpOperands(
1763 Opcode: IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,
1764 LHS: IntrID == Intrinsic::cttz
1765 ? ConstantInt::get(Ty, V: 1)
1766 : ConstantInt::get(Ty, V: APInt::getSignedMinValue(numBits: BitWidth)),
1767 RHS: cast<Constant>(Val: I1), DL);
1768 return Builder.CreateBinaryIntrinsic(
1769 ID: IntrID, LHS: Builder.CreateOr(LHS: CtOp1, RHS: NewConst),
1770 RHS: ConstantInt::getTrue(Ty: ZeroUndef1->getType()));
1771}
1772
1773/// Return whether "X LOp (Y ROp Z)" is always equal to
1774/// "(X LOp Y) ROp (X LOp Z)".
1775static bool leftDistributesOverRight(Instruction::BinaryOps LOp, bool HasNUW,
1776 bool HasNSW, Intrinsic::ID ROp) {
1777 switch (ROp) {
1778 case Intrinsic::umax:
1779 case Intrinsic::umin:
1780 if (HasNUW && LOp == Instruction::Add)
1781 return true;
1782 if (HasNUW && LOp == Instruction::Shl)
1783 return true;
1784 return false;
1785 case Intrinsic::smax:
1786 case Intrinsic::smin:
1787 return HasNSW && LOp == Instruction::Add;
1788 default:
1789 return false;
1790 }
1791}
1792
1793/// Return whether "(X ROp Y) LOp Z" is always equal to
1794/// "(X LOp Z) ROp (Y LOp Z)".
1795static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, bool HasNUW,
1796 bool HasNSW, Intrinsic::ID ROp) {
1797 if (Instruction::isCommutative(Opcode: LOp) || LOp == Instruction::Shl)
1798 return leftDistributesOverRight(LOp, HasNUW, HasNSW, ROp);
1799 switch (ROp) {
1800 case Intrinsic::umax:
1801 case Intrinsic::umin:
1802 return HasNUW && LOp == Instruction::Sub;
1803 case Intrinsic::smax:
1804 case Intrinsic::smin:
1805 return HasNSW && LOp == Instruction::Sub;
1806 default:
1807 return false;
1808 }
1809}
1810
1811// Attempts to factorise a common term
1812// in an instruction that has the form "(A op' B) op (C op' D)
1813// where op is an intrinsic and op' is a binop
1814static Value *
1815foldIntrinsicUsingDistributiveLaws(IntrinsicInst *II,
1816 InstCombiner::BuilderTy &Builder) {
1817 Value *LHS = II->getOperand(i_nocapture: 0), *RHS = II->getOperand(i_nocapture: 1);
1818 Intrinsic::ID TopLevelOpcode = II->getIntrinsicID();
1819
1820 OverflowingBinaryOperator *Op0 = dyn_cast<OverflowingBinaryOperator>(Val: LHS);
1821 OverflowingBinaryOperator *Op1 = dyn_cast<OverflowingBinaryOperator>(Val: RHS);
1822
1823 if (!Op0 || !Op1)
1824 return nullptr;
1825
1826 if (Op0->getOpcode() != Op1->getOpcode())
1827 return nullptr;
1828
1829 if (!Op0->hasOneUse() || !Op1->hasOneUse())
1830 return nullptr;
1831
1832 Instruction::BinaryOps InnerOpcode =
1833 static_cast<Instruction::BinaryOps>(Op0->getOpcode());
1834 bool HasNUW = Op0->hasNoUnsignedWrap() && Op1->hasNoUnsignedWrap();
1835 bool HasNSW = Op0->hasNoSignedWrap() && Op1->hasNoSignedWrap();
1836
1837 Value *A = Op0->getOperand(i_nocapture: 0);
1838 Value *B = Op0->getOperand(i_nocapture: 1);
1839 Value *C = Op1->getOperand(i_nocapture: 0);
1840 Value *D = Op1->getOperand(i_nocapture: 1);
1841
1842 // Attempts to swap variables such that A equals C or B equals D,
1843 // if the inner operation is commutative.
1844 if (Op0->isCommutative() && A != C && B != D) {
1845 if (A == D || B == C)
1846 std::swap(a&: C, b&: D);
1847 else
1848 return nullptr;
1849 }
1850
1851 BinaryOperator *NewBinop;
1852 if (A == C &&
1853 leftDistributesOverRight(LOp: InnerOpcode, HasNUW, HasNSW, ROp: TopLevelOpcode)) {
1854 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(ID: TopLevelOpcode, LHS: B, RHS: D);
1855 NewBinop =
1856 cast<BinaryOperator>(Val: Builder.CreateBinOp(Opc: InnerOpcode, LHS: A, RHS: NewIntrinsic));
1857 } else if (B == D && rightDistributesOverLeft(LOp: InnerOpcode, HasNUW, HasNSW,
1858 ROp: TopLevelOpcode)) {
1859 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(ID: TopLevelOpcode, LHS: A, RHS: C);
1860 NewBinop =
1861 cast<BinaryOperator>(Val: Builder.CreateBinOp(Opc: InnerOpcode, LHS: NewIntrinsic, RHS: B));
1862 } else {
1863 return nullptr;
1864 }
1865
1866 NewBinop->setHasNoUnsignedWrap(HasNUW);
1867 NewBinop->setHasNoSignedWrap(HasNSW);
1868
1869 return NewBinop;
1870}
1871
1872static Instruction *foldNeonShift(IntrinsicInst *II, InstCombinerImpl &IC) {
1873 Value *Arg0 = II->getArgOperand(i: 0);
1874 auto *ShiftConst = dyn_cast<Constant>(Val: II->getArgOperand(i: 1));
1875 if (!ShiftConst)
1876 return nullptr;
1877
1878 int ElemBits = Arg0->getType()->getScalarSizeInBits();
1879 bool AllPositive = true;
1880 bool AllNegative = true;
1881
1882 auto Check = [&](Constant *C) -> bool {
1883 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val: C)) {
1884 const APInt &V = CI->getValue();
1885 if (V.isNonNegative()) {
1886 AllNegative = false;
1887 return AllPositive && V.ult(RHS: ElemBits);
1888 }
1889 AllPositive = false;
1890 return AllNegative && V.sgt(RHS: -ElemBits);
1891 }
1892 return false;
1893 };
1894
1895 if (auto *VTy = dyn_cast<FixedVectorType>(Val: Arg0->getType())) {
1896 for (unsigned I = 0, E = VTy->getNumElements(); I < E; ++I) {
1897 if (!Check(ShiftConst->getAggregateElement(Elt: I)))
1898 return nullptr;
1899 }
1900
1901 } else if (!Check(ShiftConst))
1902 return nullptr;
1903
1904 IRBuilderBase &B = IC.Builder;
1905 if (AllPositive)
1906 return IC.replaceInstUsesWith(I&: *II, V: B.CreateShl(LHS: Arg0, RHS: ShiftConst));
1907
1908 Value *NegAmt = B.CreateNeg(V: ShiftConst);
1909 Intrinsic::ID IID = II->getIntrinsicID();
1910 const bool IsSigned =
1911 IID == Intrinsic::arm_neon_vshifts || IID == Intrinsic::aarch64_neon_sshl;
1912 Value *Result =
1913 IsSigned ? B.CreateAShr(LHS: Arg0, RHS: NegAmt) : B.CreateLShr(LHS: Arg0, RHS: NegAmt);
1914 return IC.replaceInstUsesWith(I&: *II, V: Result);
1915}
1916
1917/// CallInst simplification. This mostly only handles folding of intrinsic
1918/// instructions. For normal calls, it allows visitCallBase to do the heavy
1919/// lifting.
1920Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
1921 // Don't try to simplify calls without uses. It will not do anything useful,
1922 // but will result in the following folds being skipped.
1923 if (!CI.use_empty()) {
1924 SmallVector<Value *, 8> Args(CI.args());
1925 if (Value *V = simplifyCall(Call: &CI, Callee: CI.getCalledOperand(), Args,
1926 Q: SQ.getWithInstruction(I: &CI)))
1927 return replaceInstUsesWith(I&: CI, V);
1928 }
1929
1930 if (Value *FreedOp = getFreedOperand(CB: &CI, TLI: &TLI))
1931 return visitFree(FI&: CI, FreedOp);
1932
1933 // If the caller function (i.e. us, the function that contains this CallInst)
1934 // is nounwind, mark the call as nounwind, even if the callee isn't.
1935 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1936 CI.setDoesNotThrow();
1937 return &CI;
1938 }
1939
1940 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: &CI);
1941 if (!II)
1942 return visitCallBase(Call&: CI);
1943
1944 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1945 // instead of in visitCallBase.
1946 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Val: II)) {
1947 if (auto NumBytes = MI->getLengthInBytes()) {
1948 // memmove/cpy/set of zero bytes is a noop.
1949 if (NumBytes->isZero())
1950 return eraseInstFromFunction(I&: CI);
1951
1952 // For atomic unordered mem intrinsics if len is not a positive or
1953 // not a multiple of element size then behavior is undefined.
1954 if (MI->isAtomic() &&
1955 (NumBytes->isNegative() ||
1956 (NumBytes->getZExtValue() % MI->getElementSizeInBytes() != 0))) {
1957 CreateNonTerminatorUnreachable(InsertAt: MI);
1958 assert(MI->getType()->isVoidTy() &&
1959 "non void atomic unordered mem intrinsic");
1960 return eraseInstFromFunction(I&: *MI);
1961 }
1962 }
1963
1964 // No other transformations apply to volatile transfers.
1965 if (MI->isVolatile())
1966 return nullptr;
1967
1968 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(Val: MI)) {
1969 // memmove(x,x,size) -> noop.
1970 if (MTI->getSource() == MTI->getDest())
1971 return eraseInstFromFunction(I&: CI);
1972 }
1973
1974 auto IsPointerUndefined = [MI](Value *Ptr) {
1975 return isa<ConstantPointerNull>(Val: Ptr) &&
1976 !NullPointerIsDefined(
1977 F: MI->getFunction(),
1978 AS: cast<PointerType>(Val: Ptr->getType())->getAddressSpace());
1979 };
1980 bool SrcIsUndefined = false;
1981 // If we can determine a pointer alignment that is bigger than currently
1982 // set, update the alignment.
1983 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Val: MI)) {
1984 if (Instruction *I = SimplifyAnyMemTransfer(MI: MTI))
1985 return I;
1986 SrcIsUndefined = IsPointerUndefined(MTI->getRawSource());
1987 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(Val: MI)) {
1988 if (Instruction *I = SimplifyAnyMemSet(MI: MSI))
1989 return I;
1990 }
1991
1992 // If src/dest is null, this memory intrinsic must be a noop.
1993 if (SrcIsUndefined || IsPointerUndefined(MI->getRawDest())) {
1994 Builder.CreateAssumption(Cond: Builder.CreateIsNull(Arg: MI->getLength()));
1995 return eraseInstFromFunction(I&: CI);
1996 }
1997
1998 // If we have a memmove and the source operation is a constant global,
1999 // then the source and dest pointers can't alias, so we can change this
2000 // into a call to memcpy.
2001 if (auto *MMI = dyn_cast<AnyMemMoveInst>(Val: MI)) {
2002 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(Val: MMI->getSource()))
2003 if (GVSrc->isConstant()) {
2004 Module *M = CI.getModule();
2005 Intrinsic::ID MemCpyID =
2006 MMI->isAtomic()
2007 ? Intrinsic::memcpy_element_unordered_atomic
2008 : Intrinsic::memcpy;
2009 Type *Tys[3] = { CI.getArgOperand(i: 0)->getType(),
2010 CI.getArgOperand(i: 1)->getType(),
2011 CI.getArgOperand(i: 2)->getType() };
2012 CI.setCalledFunction(
2013 Intrinsic::getOrInsertDeclaration(M, id: MemCpyID, OverloadTys: Tys));
2014 return II;
2015 }
2016 }
2017 }
2018
2019 // For fixed width vector result intrinsics, use the generic demanded vector
2020 // support.
2021 if (auto *IIFVTy = dyn_cast<FixedVectorType>(Val: II->getType())) {
2022 auto VWidth = IIFVTy->getNumElements();
2023 APInt PoisonElts(VWidth, 0);
2024 APInt AllOnesEltMask(APInt::getAllOnes(numBits: VWidth));
2025 if (Value *V = SimplifyDemandedVectorElts(V: II, DemandedElts: AllOnesEltMask, PoisonElts)) {
2026 if (V != II)
2027 return replaceInstUsesWith(I&: *II, V);
2028 return II;
2029 }
2030 }
2031
2032 if (II->isCommutative()) {
2033 if (auto Pair = matchSymmetricPair(LHS: II->getOperand(i_nocapture: 0), RHS: II->getOperand(i_nocapture: 1))) {
2034 replaceOperand(I&: *II, OpNum: 0, V: Pair->first);
2035 replaceOperand(I&: *II, OpNum: 1, V: Pair->second);
2036 II->dropPoisonGeneratingAnnotations();
2037 II->dropUBImplyingAttrsAndMetadata();
2038 return II;
2039 }
2040
2041 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(Call&: CI))
2042 return NewCall;
2043 }
2044
2045 // Unused constrained FP intrinsic calls may have declared side effect, which
2046 // prevents it from being removed. In some cases however the side effect is
2047 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
2048 // returns a replacement, the call may be removed.
2049 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(Val: CI)) {
2050 if (simplifyConstrainedFPCall(Call: &CI, Q: SQ.getWithInstruction(I: &CI)))
2051 return eraseInstFromFunction(I&: CI);
2052 }
2053
2054 Intrinsic::ID IID = II->getIntrinsicID();
2055 switch (IID) {
2056 case Intrinsic::objectsize: {
2057 SmallVector<Instruction *> InsertedInstructions;
2058 if (Value *V = lowerObjectSizeCall(ObjectSize: II, DL, TLI: &TLI, AA, /*MustSucceed=*/false,
2059 InsertedInstructions: &InsertedInstructions)) {
2060 for (Instruction *Inserted : InsertedInstructions)
2061 Worklist.add(I: Inserted);
2062 return replaceInstUsesWith(I&: CI, V);
2063 }
2064 return nullptr;
2065 }
2066 case Intrinsic::abs: {
2067 Value *IIOperand = II->getArgOperand(i: 0);
2068 bool IntMinIsPoison = cast<Constant>(Val: II->getArgOperand(i: 1))->isOneValue();
2069
2070 // abs(-x) -> abs(x)
2071 Value *X;
2072 if (match(V: IIOperand, P: m_Neg(V: m_Value(V&: X))))
2073 return CallInst::Create(
2074 Func: II->getCalledFunction(),
2075 Args: {X,
2076 Builder.getInt1(V: IntMinIsPoison ||
2077 cast<Instruction>(Val: IIOperand)->hasNoSignedWrap())});
2078
2079 if (match(V: IIOperand, P: m_c_Select(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X))))
2080 return CallInst::Create(Func: II->getCalledFunction(),
2081 Args: {X, II->getArgOperand(i: 1)});
2082
2083 Value *Y;
2084 // abs(a * abs(b)) -> abs(a * b)
2085 if (match(V: IIOperand,
2086 P: m_OneUse(SubPattern: m_c_Mul(L: m_Value(V&: X),
2087 R: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(V&: Y)))))) {
2088 bool NSW =
2089 cast<Instruction>(Val: IIOperand)->hasNoSignedWrap() && IntMinIsPoison;
2090 auto *XY = NSW ? Builder.CreateNSWMul(LHS: X, RHS: Y) : Builder.CreateMul(LHS: X, RHS: Y);
2091 return CallInst::Create(Func: II->getCalledFunction(),
2092 Args: {XY, II->getArgOperand(i: 1)});
2093 }
2094
2095 if (std::optional<bool> Known =
2096 getKnownSignOrZero(Op: IIOperand, SQ: SQ.getWithInstruction(I: II))) {
2097 // abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)
2098 // abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)
2099 if (!*Known)
2100 return replaceInstUsesWith(I&: *II, V: IIOperand);
2101
2102 // abs(x) -> -x if x < 0
2103 // abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)
2104 if (IntMinIsPoison)
2105 return BinaryOperator::CreateNSWNeg(Op: IIOperand);
2106 return BinaryOperator::CreateNeg(Op: IIOperand);
2107 }
2108
2109 // abs (sext X) --> zext (abs X*)
2110 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
2111 if (match(V: IIOperand, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X))))) {
2112 Value *NarrowAbs =
2113 Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: X, RHS: Builder.getFalse());
2114 return CastInst::Create(Instruction::ZExt, S: NarrowAbs, Ty: II->getType());
2115 }
2116
2117 // Match a complicated way to check if a number is odd/even:
2118 // abs (srem X, 2) --> and X, 1
2119 const APInt *C;
2120 if (match(V: IIOperand, P: m_SRem(L: m_Value(V&: X), R: m_APInt(Res&: C))) && *C == 2)
2121 return BinaryOperator::CreateAnd(V1: X, V2: ConstantInt::get(Ty: II->getType(), V: 1));
2122
2123 break;
2124 }
2125 case Intrinsic::umin: {
2126 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2127 // umin(x, 1) == zext(x != 0)
2128 if (match(V: I1, P: m_One())) {
2129 assert(II->getType()->getScalarSizeInBits() != 1 &&
2130 "Expected simplify of umin with max constant");
2131 Value *Zero = Constant::getNullValue(Ty: I0->getType());
2132 Value *Cmp = Builder.CreateICmpNE(LHS: I0, RHS: Zero);
2133 return CastInst::Create(Instruction::ZExt, S: Cmp, Ty: II->getType());
2134 }
2135 // umin(cttz(x), const) --> cttz(x | (1 << const))
2136 if (Value *FoldedCttz =
2137 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::cttz>(
2138 I0, I1, DL, Builder))
2139 return replaceInstUsesWith(I&: *II, V: FoldedCttz);
2140 // umin(ctlz(x), const) --> ctlz(x | (SignedMin >> const))
2141 if (Value *FoldedCtlz =
2142 foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::ctlz>(
2143 I0, I1, DL, Builder))
2144 return replaceInstUsesWith(I&: *II, V: FoldedCtlz);
2145 [[fallthrough]];
2146 }
2147 case Intrinsic::umax: {
2148 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2149 Value *X, *Y;
2150 if (match(V: I0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: I1, P: m_ZExt(Op: m_Value(V&: Y))) &&
2151 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
2152 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y);
2153 return CastInst::Create(Instruction::ZExt, S: NarrowMaxMin, Ty: II->getType());
2154 }
2155 Constant *C;
2156 if (match(V: I0, P: m_ZExt(Op: m_Value(V&: X))) && match(V: I1, P: m_Constant(C)) &&
2157 I0->hasOneUse()) {
2158 if (Constant *NarrowC = getLosslessUnsignedTrunc(C, DestTy: X->getType(), DL)) {
2159 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: NarrowC);
2160 return CastInst::Create(Instruction::ZExt, S: NarrowMaxMin, Ty: II->getType());
2161 }
2162 }
2163 // If C is not 0:
2164 // umax(nuw_shl(x, C), x + 1) -> x == 0 ? 1 : nuw_shl(x, C)
2165 // If C is not 0 or 1:
2166 // umax(nuw_mul(x, C), x + 1) -> x == 0 ? 1 : nuw_mul(x, C)
2167 auto foldMaxMulShift = [&](Value *A, Value *B) -> Instruction * {
2168 const APInt *C;
2169 Value *X;
2170 if (!match(V: A, P: m_NUWShl(L: m_Value(V&: X), R: m_APInt(Res&: C))) &&
2171 !(match(V: A, P: m_NUWMul(L: m_Value(V&: X), R: m_APInt(Res&: C))) && !C->isOne()))
2172 return nullptr;
2173 if (C->isZero())
2174 return nullptr;
2175 if (!match(V: B, P: m_OneUse(SubPattern: m_Add(L: m_Specific(V: X), R: m_One()))))
2176 return nullptr;
2177
2178 Value *Cmp = Builder.CreateICmpEQ(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: 0));
2179 Value *NewSelect = nullptr;
2180 NewSelect = Builder.CreateSelectWithUnknownProfile(
2181 C: Cmp, True: ConstantInt::get(Ty: X->getType(), V: 1), False: A, DEBUG_TYPE);
2182 return replaceInstUsesWith(I&: *II, V: NewSelect);
2183 };
2184
2185 if (IID == Intrinsic::umax) {
2186 if (Instruction *I = foldMaxMulShift(I0, I1))
2187 return I;
2188 if (Instruction *I = foldMaxMulShift(I1, I0))
2189 return I;
2190 }
2191
2192 // If both operands of unsigned min/max are sign-extended, it is still ok
2193 // to narrow the operation.
2194 [[fallthrough]];
2195 }
2196 case Intrinsic::smax:
2197 case Intrinsic::smin: {
2198 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2199 Value *X, *Y;
2200 if (match(V: I0, P: m_SExt(Op: m_Value(V&: X))) && match(V: I1, P: m_SExt(Op: m_Value(V&: Y))) &&
2201 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
2202 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y);
2203 return CastInst::Create(Instruction::SExt, S: NarrowMaxMin, Ty: II->getType());
2204 }
2205
2206 Constant *C;
2207 if (match(V: I0, P: m_SExt(Op: m_Value(V&: X))) && match(V: I1, P: m_Constant(C)) &&
2208 I0->hasOneUse()) {
2209 if (Constant *NarrowC = getLosslessSignedTrunc(C, DestTy: X->getType(), DL)) {
2210 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: NarrowC);
2211 return CastInst::Create(Instruction::SExt, S: NarrowMaxMin, Ty: II->getType());
2212 }
2213 }
2214
2215 // smax(smin(X, MinC), MaxC) -> smin(smax(X, MaxC), MinC) if MinC s>= MaxC
2216 // umax(umin(X, MinC), MaxC) -> umin(umax(X, MaxC), MinC) if MinC u>= MaxC
2217 const APInt *MinC, *MaxC;
2218 auto CreateCanonicalClampForm = [&](bool IsSigned) {
2219 auto MaxIID = IsSigned ? Intrinsic::smax : Intrinsic::umax;
2220 auto MinIID = IsSigned ? Intrinsic::smin : Intrinsic::umin;
2221 Value *NewMax = Builder.CreateBinaryIntrinsic(
2222 ID: MaxIID, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: *MaxC));
2223 return replaceInstUsesWith(
2224 I&: *II, V: Builder.CreateBinaryIntrinsic(
2225 ID: MinIID, LHS: NewMax, RHS: ConstantInt::get(Ty: X->getType(), V: *MinC)));
2226 };
2227 if (IID == Intrinsic::smax &&
2228 match(V: I0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::smin>(Op0: m_Value(V&: X),
2229 Op1: m_APInt(Res&: MinC)))) &&
2230 match(V: I1, P: m_APInt(Res&: MaxC)) && MinC->sgt(RHS: *MaxC))
2231 return CreateCanonicalClampForm(true);
2232 if (IID == Intrinsic::umax &&
2233 match(V: I0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::umin>(Op0: m_Value(V&: X),
2234 Op1: m_APInt(Res&: MinC)))) &&
2235 match(V: I1, P: m_APInt(Res&: MaxC)) && MinC->ugt(RHS: *MaxC))
2236 return CreateCanonicalClampForm(false);
2237
2238 // umin(i1 X, i1 Y) -> and i1 X, Y
2239 // smax(i1 X, i1 Y) -> and i1 X, Y
2240 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
2241 II->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2242 return BinaryOperator::CreateAnd(V1: I0, V2: I1);
2243 }
2244
2245 // umax(i1 X, i1 Y) -> or i1 X, Y
2246 // smin(i1 X, i1 Y) -> or i1 X, Y
2247 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
2248 II->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2249 return BinaryOperator::CreateOr(V1: I0, V2: I1);
2250 }
2251
2252 // smin(smax(X, -1), 1) -> scmp(X, 0)
2253 // smax(smin(X, 1), -1) -> scmp(X, 0)
2254 // At this point, smax(smin(X, 1), -1) is changed to smin(smax(X, -1)
2255 // And i1's have been changed to and/ors
2256 // So we only need to check for smin
2257 if (IID == Intrinsic::smin) {
2258 if (match(V: I0, P: m_OneUse(SubPattern: m_SMax(Op0: m_Value(V&: X), Op1: m_AllOnes()))) &&
2259 match(V: I1, P: m_One())) {
2260 Value *Zero = ConstantInt::get(Ty: X->getType(), V: 0);
2261 return replaceInstUsesWith(
2262 I&: CI,
2263 V: Builder.CreateIntrinsic(RetTy: II->getType(), ID: Intrinsic::scmp, Args: {X, Zero}));
2264 }
2265 }
2266
2267 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2268 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
2269 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
2270 // TODO: Canonicalize neg after min/max if I1 is constant.
2271 if (match(V: I0, P: m_NSWNeg(V: m_Value(V&: X))) && match(V: I1, P: m_NSWNeg(V: m_Value(V&: Y))) &&
2272 (I0->hasOneUse() || I1->hasOneUse())) {
2273 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: IID);
2274 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(ID: InvID, LHS: X, RHS: Y);
2275 return BinaryOperator::CreateNSWNeg(Op: InvMaxMin);
2276 }
2277 }
2278
2279 // (umax X, (xor X, Pow2))
2280 // -> (or X, Pow2)
2281 // (umin X, (xor X, Pow2))
2282 // -> (and X, ~Pow2)
2283 // (smax X, (xor X, Pos_Pow2))
2284 // -> (or X, Pos_Pow2)
2285 // (smin X, (xor X, Pos_Pow2))
2286 // -> (and X, ~Pos_Pow2)
2287 // (smax X, (xor X, Neg_Pow2))
2288 // -> (and X, ~Neg_Pow2)
2289 // (smin X, (xor X, Neg_Pow2))
2290 // -> (or X, Neg_Pow2)
2291 if ((match(V: I0, P: m_c_Xor(L: m_Specific(V: I1), R: m_Value(V&: X))) ||
2292 match(V: I1, P: m_c_Xor(L: m_Specific(V: I0), R: m_Value(V&: X)))) &&
2293 isKnownToBeAPowerOfTwo(V: X, /* OrZero */ true)) {
2294 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
2295 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
2296
2297 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2298 auto KnownSign = getKnownSign(Op: X, SQ: SQ.getWithInstruction(I: II));
2299 if (KnownSign == std::nullopt) {
2300 UseOr = false;
2301 UseAndN = false;
2302 } else if (*KnownSign /* true is Signed. */) {
2303 UseOr ^= true;
2304 UseAndN ^= true;
2305 Type *Ty = I0->getType();
2306 // Negative power of 2 must be IntMin. It's possible to be able to
2307 // prove negative / power of 2 without actually having known bits, so
2308 // just get the value by hand.
2309 X = Constant::getIntegerValue(
2310 Ty, V: APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits()));
2311 }
2312 }
2313 if (UseOr)
2314 return BinaryOperator::CreateOr(V1: I0, V2: X);
2315 else if (UseAndN)
2316 return BinaryOperator::CreateAnd(V1: I0, V2: Builder.CreateNot(V: X));
2317 }
2318
2319 // If we can eliminate ~A and Y is free to invert:
2320 // max ~A, Y --> ~(min A, ~Y)
2321 //
2322 // Examples:
2323 // max ~A, ~Y --> ~(min A, Y)
2324 // max ~A, C --> ~(min A, ~C)
2325 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
2326 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2327 Value *A;
2328 if (match(V: X, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: A)))) &&
2329 !isFreeToInvert(V: A, WillInvertAllUses: A->hasOneUse())) {
2330 if (Value *NotY = getFreelyInverted(V: Y, WillInvertAllUses: Y->hasOneUse(), Builder: &Builder)) {
2331 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: IID);
2332 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(ID: InvID, LHS: A, RHS: NotY);
2333 return BinaryOperator::CreateNot(Op: InvMaxMin);
2334 }
2335 }
2336 return nullptr;
2337 };
2338
2339 if (Instruction *I = moveNotAfterMinMax(I0, I1))
2340 return I;
2341 if (Instruction *I = moveNotAfterMinMax(I1, I0))
2342 return I;
2343
2344 if (Instruction *I = moveAddAfterMinMax(II, Builder))
2345 return I;
2346
2347 // minmax (X & NegPow2C, Y & NegPow2C) --> minmax(X, Y) & NegPow2C
2348 const APInt *RHSC;
2349 if (match(V: I0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_NegatedPower2(V&: RHSC)))) &&
2350 match(V: I1, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: Y), R: m_SpecificInt(V: *RHSC)))))
2351 return BinaryOperator::CreateAnd(V1: Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y),
2352 V2: ConstantInt::get(Ty: II->getType(), V: *RHSC));
2353
2354 // smax(X, -X) --> abs(X)
2355 // smin(X, -X) --> -abs(X)
2356 // umax(X, -X) --> -abs(X)
2357 // umin(X, -X) --> abs(X)
2358 if (isKnownNegation(X: I0, Y: I1)) {
2359 // We can choose either operand as the input to abs(), but if we can
2360 // eliminate the only use of a value, that's better for subsequent
2361 // transforms/analysis.
2362 if (I0->hasOneUse() && !I1->hasOneUse())
2363 std::swap(a&: I0, b&: I1);
2364
2365 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
2366 // operation and potentially its negation.
2367 bool IntMinIsPoison = isKnownNegation(X: I0, Y: I1, /* NeedNSW */ true);
2368 Value *Abs = Builder.CreateBinaryIntrinsic(
2369 ID: Intrinsic::abs, LHS: I0,
2370 RHS: ConstantInt::getBool(Context&: II->getContext(), V: IntMinIsPoison));
2371
2372 // We don't have a "nabs" intrinsic, so negate if needed based on the
2373 // max/min operation.
2374 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
2375 Abs = Builder.CreateNeg(V: Abs, Name: "nabs", HasNSW: IntMinIsPoison);
2376 return replaceInstUsesWith(I&: CI, V: Abs);
2377 }
2378
2379 if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
2380 return Sel;
2381
2382 if (Instruction *SAdd = matchSAddSubSat(MinMax1&: *II))
2383 return SAdd;
2384
2385 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))
2386 return replaceInstUsesWith(I&: *II, V: NewMinMax);
2387
2388 if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder))
2389 return R;
2390
2391 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
2392 return NewMinMax;
2393
2394 // Try to fold minmax with constant RHS based on range information
2395 if (match(V: I1, P: m_APIntAllowPoison(Res&: RHSC))) {
2396 ICmpInst::Predicate Pred =
2397 ICmpInst::getNonStrictPredicate(pred: MinMaxIntrinsic::getPredicate(ID: IID));
2398 bool IsSigned = MinMaxIntrinsic::isSigned(ID: IID);
2399 ConstantRange LHS_CR = computeConstantRangeIncludingKnownBits(
2400 V: I0, ForSigned: IsSigned, SQ: SQ.getWithInstruction(I: II));
2401 if (!LHS_CR.isFullSet()) {
2402 if (LHS_CR.icmp(Pred, Other: *RHSC))
2403 return replaceInstUsesWith(I&: *II, V: I0);
2404 if (LHS_CR.icmp(Pred: ICmpInst::getSwappedPredicate(pred: Pred), Other: *RHSC))
2405 return replaceInstUsesWith(I&: *II,
2406 V: ConstantInt::get(Ty: II->getType(), V: *RHSC));
2407 }
2408 }
2409
2410 if (Value *V = foldIntrinsicUsingDistributiveLaws(II, Builder))
2411 return replaceInstUsesWith(I&: *II, V);
2412
2413 break;
2414 }
2415 case Intrinsic::scmp: {
2416 Value *I0 = II->getArgOperand(i: 0), *I1 = II->getArgOperand(i: 1);
2417 Value *LHS, *RHS;
2418 if (match(V: I0, P: m_NSWSub(L: m_Value(V&: LHS), R: m_Value(V&: RHS))) && match(V: I1, P: m_Zero()))
2419 return replaceInstUsesWith(
2420 I&: CI,
2421 V: Builder.CreateIntrinsic(RetTy: II->getType(), ID: Intrinsic::scmp, Args: {LHS, RHS}));
2422 break;
2423 }
2424 case Intrinsic::bitreverse: {
2425 Value *IIOperand = II->getArgOperand(i: 0);
2426 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
2427 Value *X;
2428 if (match(V: IIOperand, P: m_ZExt(Op: m_Value(V&: X))) &&
2429 X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2430 Type *Ty = II->getType();
2431 APInt SignBit = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2432 return SelectInst::Create(C: X, S1: ConstantInt::get(Ty, V: SignBit),
2433 S2: ConstantInt::getNullValue(Ty));
2434 }
2435
2436 if (Instruction *crossLogicOpFold =
2437 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(V: IIOperand, Builder))
2438 return crossLogicOpFold;
2439
2440 break;
2441 }
2442 case Intrinsic::bswap: {
2443 Value *IIOperand = II->getArgOperand(i: 0);
2444
2445 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
2446 // inverse-shift-of-bswap:
2447 // bswap (shl X, Y) --> lshr (bswap X), Y
2448 // bswap (lshr X, Y) --> shl (bswap X), Y
2449 Value *X, *Y;
2450 if (match(V: IIOperand, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2451 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
2452 if (MaskedValueIsZero(V: Y, Mask: APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 3))) {
2453 Value *NewSwap = Builder.CreateUnaryIntrinsic(ID: Intrinsic::bswap, Op: X);
2454 BinaryOperator::BinaryOps InverseShift =
2455 cast<BinaryOperator>(Val: IIOperand)->getOpcode() == Instruction::Shl
2456 ? Instruction::LShr
2457 : Instruction::Shl;
2458 return BinaryOperator::Create(Op: InverseShift, S1: NewSwap, S2: Y);
2459 }
2460 }
2461
2462 KnownBits Known = computeKnownBits(V: IIOperand, CxtI: II);
2463 uint64_t LZ = alignDown(Value: Known.countMinLeadingZeros(), Align: 8);
2464 uint64_t TZ = alignDown(Value: Known.countMinTrailingZeros(), Align: 8);
2465 unsigned BW = Known.getBitWidth();
2466
2467 // bswap(x) -> shift(x) if x has exactly one "active byte"
2468 if (BW - LZ - TZ == 8) {
2469 assert(LZ != TZ && "active byte cannot be in the middle");
2470 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
2471 return BinaryOperator::CreateNUWShl(
2472 V1: IIOperand, V2: ConstantInt::get(Ty: IIOperand->getType(), V: LZ - TZ));
2473 // -> lshr(x) if the "active byte" is in the high part of x
2474 return BinaryOperator::CreateExactLShr(
2475 V1: IIOperand, V2: ConstantInt::get(Ty: IIOperand->getType(), V: TZ - LZ));
2476 }
2477
2478 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
2479 if (match(V: IIOperand, P: m_Trunc(Op: m_BSwap(Op0: m_Value(V&: X))))) {
2480 unsigned C = X->getType()->getScalarSizeInBits() - BW;
2481 Value *CV = ConstantInt::get(Ty: X->getType(), V: C);
2482 Value *V = Builder.CreateLShr(LHS: X, RHS: CV);
2483 return new TruncInst(V, IIOperand->getType());
2484 }
2485
2486 if (Instruction *crossLogicOpFold =
2487 foldBitOrderCrossLogicOp<Intrinsic::bswap>(V: IIOperand, Builder)) {
2488 return crossLogicOpFold;
2489 }
2490
2491 // Try to fold into bitreverse if bswap is the root of the expression tree.
2492 if (Instruction *BitOp = matchBSwapOrBitReverse(I&: *II, /*MatchBSwaps*/ false,
2493 /*MatchBitReversals*/ true))
2494 return BitOp;
2495 break;
2496 }
2497 case Intrinsic::masked_load:
2498 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(II&: *II))
2499 return replaceInstUsesWith(I&: CI, V: SimplifiedMaskedOp);
2500 break;
2501 case Intrinsic::masked_store:
2502 return simplifyMaskedStore(II&: *II);
2503 case Intrinsic::masked_gather:
2504 return simplifyMaskedGather(II&: *II);
2505 case Intrinsic::masked_scatter:
2506 return simplifyMaskedScatter(II&: *II);
2507 case Intrinsic::launder_invariant_group:
2508 case Intrinsic::strip_invariant_group:
2509 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(II&: *II, IC&: *this))
2510 return replaceInstUsesWith(I&: *II, V: SkippedBarrier);
2511 break;
2512 case Intrinsic::powi: {
2513 if (ConstantInt *Power = dyn_cast<ConstantInt>(Val: II->getArgOperand(i: 1))) {
2514 // 0 and 1 are handled in instsimplify
2515 // powi(x, -1) -> 1/x
2516 if (Power->isMinusOne())
2517 return BinaryOperator::CreateFDivFMF(V1: ConstantFP::get(Ty: CI.getType(), V: 1.0),
2518 V2: II->getArgOperand(i: 0), FMFSource: II);
2519 // powi(x, 2) -> x*x
2520 if (Power->equalsInt(V: 2))
2521 return BinaryOperator::CreateFMulFMF(V1: II->getArgOperand(i: 0),
2522 V2: II->getArgOperand(i: 0), FMFSource: II);
2523
2524 if (!Power->getValue()[0]) {
2525 Value *X;
2526 // If power is even:
2527 // powi(-x, p) -> powi(x, p)
2528 // powi(fabs(x), p) -> powi(x, p)
2529 // powi(copysign(x, y), p) -> powi(x, p)
2530 if (match(V: II->getArgOperand(i: 0), P: m_FNeg(X: m_Value(V&: X))) ||
2531 match(V: II->getArgOperand(i: 0), P: m_FAbs(Op0: m_Value(V&: X))) ||
2532 match(V: II->getArgOperand(i: 0),
2533 P: m_Intrinsic<Intrinsic::copysign>(Op0: m_Value(V&: X), Op1: m_Value())))
2534 return CallInst::Create(Func: II->getCalledFunction(), Args: {X, Power});
2535 }
2536 }
2537 if (ConstantFP *Base = dyn_cast<ConstantFP>(Val: II->getArgOperand(i: 0))) {
2538 Value *Exp = II->getArgOperand(i: 1);
2539 Type *Ty = Base->getType();
2540 // powi(2.0, p) -> ldexp(1.0, p)
2541 if (II->hasApproxFunc() && Base->isExactlyValue(V: 2.0)) {
2542 ConstantFP *One = ConstantFP::get(Ty, V: 1.0);
2543 if (auto *VTy = dyn_cast<VectorType>(Val: Ty))
2544 Exp = Builder.CreateVectorSplat(EC: VTy->getElementCount(), V: Exp);
2545 Value *Ldexp = Builder.CreateLdexp(Src: One, Exp, FMFSource: II);
2546 return replaceInstUsesWith(I&: *II, V: Ldexp);
2547 }
2548 }
2549 break;
2550 }
2551
2552 case Intrinsic::cttz:
2553 case Intrinsic::ctlz:
2554 if (auto *I = foldCttzCtlz(II&: *II, IC&: *this))
2555 return I;
2556 break;
2557
2558 case Intrinsic::ctpop:
2559 if (auto *I = foldCtpop(II&: *II, IC&: *this))
2560 return I;
2561 break;
2562
2563 case Intrinsic::fshl:
2564 case Intrinsic::fshr: {
2565 Value *Op0 = II->getArgOperand(i: 0), *Op1 = II->getArgOperand(i: 1);
2566 Type *Ty = II->getType();
2567 unsigned BitWidth = Ty->getScalarSizeInBits();
2568 Constant *ShAmtC;
2569 if (match(V: II->getArgOperand(i: 2), P: m_ImmConstant(C&: ShAmtC))) {
2570 // Canonicalize a shift amount constant operand to modulo the bit-width.
2571 Constant *WidthC = ConstantInt::get(Ty, V: BitWidth);
2572 Constant *ModuloC =
2573 ConstantFoldBinaryOpOperands(Opcode: Instruction::URem, LHS: ShAmtC, RHS: WidthC, DL);
2574 if (!ModuloC)
2575 return nullptr;
2576 if (ModuloC != ShAmtC)
2577 return CallInst::Create(Func: II->getCalledFunction(), Args: {Op0, Op1, ModuloC});
2578
2579 assert(match(ConstantFoldCompareInstOperands(ICmpInst::ICMP_UGT, WidthC,
2580 ShAmtC, DL),
2581 m_One()) &&
2582 "Shift amount expected to be modulo bitwidth");
2583
2584 // Canonicalize funnel shift right by constant to funnel shift left. This
2585 // is not entirely arbitrary. For historical reasons, the backend may
2586 // recognize rotate left patterns but miss rotate right patterns.
2587 if (IID == Intrinsic::fshr) {
2588 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) if C is not zero.
2589 if (!isKnownNonZero(V: ShAmtC, Q: SQ.getWithInstruction(I: II)))
2590 return nullptr;
2591
2592 Constant *LeftShiftC = ConstantExpr::getSub(C1: WidthC, C2: ShAmtC);
2593 Module *Mod = II->getModule();
2594 Function *Fshl =
2595 Intrinsic::getOrInsertDeclaration(M: Mod, id: Intrinsic::fshl, OverloadTys: Ty);
2596 return CallInst::Create(Func: Fshl, Args: { Op0, Op1, LeftShiftC });
2597 }
2598 assert(IID == Intrinsic::fshl &&
2599 "All funnel shifts by simple constants should go left");
2600
2601 // fshl(X, 0, C) --> shl X, C
2602 // fshl(X, undef, C) --> shl X, C
2603 if (match(V: Op1, P: m_ZeroInt()) || match(V: Op1, P: m_Undef()))
2604 return BinaryOperator::CreateShl(V1: Op0, V2: ShAmtC);
2605
2606 // fshl(0, X, C) --> lshr X, (BW-C)
2607 // fshl(undef, X, C) --> lshr X, (BW-C)
2608 if (match(V: Op0, P: m_ZeroInt()) || match(V: Op0, P: m_Undef()))
2609 return BinaryOperator::CreateLShr(V1: Op1,
2610 V2: ConstantExpr::getSub(C1: WidthC, C2: ShAmtC));
2611
2612 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
2613 if (Op0 == Op1 && BitWidth == 16 && match(V: ShAmtC, P: m_SpecificInt(V: 8))) {
2614 Module *Mod = II->getModule();
2615 Function *Bswap =
2616 Intrinsic::getOrInsertDeclaration(M: Mod, id: Intrinsic::bswap, OverloadTys: Ty);
2617 return CallInst::Create(Func: Bswap, Args: { Op0 });
2618 }
2619 if (Instruction *BitOp =
2620 matchBSwapOrBitReverse(I&: *II, /*MatchBSwaps*/ true,
2621 /*MatchBitReversals*/ true))
2622 return BitOp;
2623
2624 // R = fshl(X, X, C2)
2625 // fshl(R, R, C1) --> fshl(X, X, (C1 + C2) % bitsize)
2626 Value *InnerOp;
2627 const APInt *ShAmtInnerC, *ShAmtOuterC;
2628 if (match(V: Op0, P: m_FShl(Op0: m_Value(V&: InnerOp), Op1: m_Deferred(V: InnerOp),
2629 Op2: m_APInt(Res&: ShAmtInnerC))) &&
2630 match(V: ShAmtC, P: m_APInt(Res&: ShAmtOuterC)) && Op0 == Op1) {
2631 APInt Sum = *ShAmtOuterC + *ShAmtInnerC;
2632 APInt Modulo = Sum.urem(RHS: APInt(Sum.getBitWidth(), BitWidth));
2633 if (Modulo.isZero())
2634 return replaceInstUsesWith(I&: *II, V: InnerOp);
2635 Constant *ModuloC = ConstantInt::get(Ty, V: Modulo);
2636 return CallInst::Create(Func: cast<IntrinsicInst>(Val: Op0)->getCalledFunction(),
2637 Args: {InnerOp, InnerOp, ModuloC});
2638 }
2639 }
2640
2641 // fshl(X, X, Neg(Y)) --> fshr(X, X, Y)
2642 // fshr(X, X, Neg(Y)) --> fshl(X, X, Y)
2643 // if BitWidth is a power-of-2
2644 Value *Y;
2645 if (Op0 == Op1 && isPowerOf2_32(Value: BitWidth) &&
2646 match(V: II->getArgOperand(i: 2), P: m_Neg(V: m_Value(V&: Y)))) {
2647 Module *Mod = II->getModule();
2648 Function *OppositeShift = Intrinsic::getOrInsertDeclaration(
2649 M: Mod, id: IID == Intrinsic::fshl ? Intrinsic::fshr : Intrinsic::fshl, OverloadTys: Ty);
2650 return CallInst::Create(Func: OppositeShift, Args: {Op0, Op1, Y});
2651 }
2652
2653 // fshl(X, 0, Y) --> shl(X, and(Y, BitWidth - 1)) if bitwidth is a
2654 // power-of-2
2655 if (IID == Intrinsic::fshl && isPowerOf2_32(Value: BitWidth) &&
2656 match(V: Op1, P: m_ZeroInt())) {
2657 Value *Op2 = II->getArgOperand(i: 2);
2658 Value *And = Builder.CreateAnd(LHS: Op2, RHS: ConstantInt::get(Ty, V: BitWidth - 1));
2659 return BinaryOperator::CreateShl(V1: Op0, V2: And);
2660 }
2661
2662 // Left or right might be masked.
2663 if (SimplifyDemandedInstructionBits(Inst&: *II))
2664 return &CI;
2665
2666 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2667 // so only the low bits of the shift amount are demanded if the bitwidth is
2668 // a power-of-2.
2669 if (!isPowerOf2_32(Value: BitWidth))
2670 break;
2671 APInt Op2Demanded = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Log2_32_Ceil(Value: BitWidth));
2672 KnownBits Op2Known(BitWidth);
2673 if (SimplifyDemandedBits(I: II, OpNo: 2, DemandedMask: Op2Demanded, Known&: Op2Known))
2674 return &CI;
2675 break;
2676 }
2677 case Intrinsic::pdep: {
2678 const APInt *MaskC;
2679 if (match(V: II->getArgOperand(i: 1), P: m_APInt(Res&: MaskC))) {
2680 unsigned MaskIdx, MaskLen;
2681 if (MaskC->isShiftedMask(MaskIdx, MaskLen)) {
2682 // any single contiguous sequence of 1s anywhere in the mask simply
2683 // describes a subset of the input bits shifted to the appropriate
2684 // position. Replace with the straight forward IR.
2685 Value *Input = II->getArgOperand(i: 0);
2686 Value *ShiftAmt = ConstantInt::get(Ty: II->getType(), V: MaskIdx);
2687 Value *Shifted = Builder.CreateShl(LHS: Input, RHS: ShiftAmt);
2688 Value *Masked = Builder.CreateAnd(LHS: Shifted, RHS: II->getArgOperand(i: 1));
2689 return replaceInstUsesWith(I&: *II, V: Masked);
2690 }
2691 }
2692 break;
2693 }
2694 case Intrinsic::pext: {
2695 const APInt *MaskC;
2696 if (match(V: II->getArgOperand(i: 1), P: m_APInt(Res&: MaskC))) {
2697 unsigned MaskIdx, MaskLen;
2698 if (MaskC->isShiftedMask(MaskIdx, MaskLen)) {
2699 // any single contiguous sequence of 1s anywhere in the mask simply
2700 // describes a subset of the input bits shifted to the appropriate
2701 // position. Replace with the straight forward IR.
2702 Value *Input = II->getArgOperand(i: 0);
2703 Value *Masked = Builder.CreateAnd(LHS: Input, RHS: II->getArgOperand(i: 1));
2704 Value *ShiftAmt = ConstantInt::get(Ty: II->getType(), V: MaskIdx);
2705 Value *Shifted = Builder.CreateLShr(LHS: Masked, RHS: ShiftAmt);
2706 return replaceInstUsesWith(I&: *II, V: Shifted);
2707 }
2708 }
2709 break;
2710 }
2711 case Intrinsic::ptrmask: {
2712 unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());
2713 KnownBits Known(BitWidth);
2714 if (SimplifyDemandedInstructionBits(Inst&: *II, Known))
2715 return II;
2716
2717 Value *InnerPtr, *InnerMask;
2718 bool Changed = false;
2719 // Combine:
2720 // (ptrmask (ptrmask p, A), B)
2721 // -> (ptrmask p, (and A, B))
2722 if (match(V: II->getArgOperand(i: 0),
2723 P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::ptrmask>(Op0: m_Value(V&: InnerPtr),
2724 Op1: m_Value(V&: InnerMask))))) {
2725 assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&
2726 "Mask types must match");
2727 // TODO: If InnerMask == Op1, we could copy attributes from inner
2728 // callsite -> outer callsite.
2729 Value *NewMask = Builder.CreateAnd(LHS: II->getArgOperand(i: 1), RHS: InnerMask);
2730 replaceOperand(I&: CI, OpNum: 0, V: InnerPtr);
2731 replaceOperand(I&: CI, OpNum: 1, V: NewMask);
2732 Changed = true;
2733 }
2734
2735 // See if we can deduce non-null.
2736 if (!CI.hasRetAttr(Kind: Attribute::NonNull) &&
2737 (Known.isNonZero() ||
2738 isKnownNonZero(V: II, Q: getSimplifyQuery().getWithInstruction(I: II)))) {
2739 CI.addRetAttr(Kind: Attribute::NonNull);
2740 Changed = true;
2741 }
2742
2743 unsigned NewAlignmentLog =
2744 std::min(a: Value::MaxAlignmentExponent,
2745 b: std::min(a: BitWidth - 1, b: Known.countMinTrailingZeros()));
2746 // Known bits will capture if we had alignment information associated with
2747 // the pointer argument.
2748 if (NewAlignmentLog > Log2(A: CI.getRetAlign().valueOrOne())) {
2749 CI.addRetAttr(Attr: Attribute::getWithAlignment(
2750 Context&: CI.getContext(), Alignment: Align(uint64_t(1) << NewAlignmentLog)));
2751 Changed = true;
2752 }
2753 if (Changed)
2754 return &CI;
2755 break;
2756 }
2757 case Intrinsic::uadd_with_overflow:
2758 case Intrinsic::sadd_with_overflow: {
2759 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2760 return I;
2761
2762 // Given 2 constant operands whose sum does not overflow:
2763 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2764 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2765 Value *X;
2766 const APInt *C0, *C1;
2767 Value *Arg0 = II->getArgOperand(i: 0);
2768 Value *Arg1 = II->getArgOperand(i: 1);
2769 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2770 bool HasNWAdd = IsSigned
2771 ? match(V: Arg0, P: m_NSWAddLike(L: m_Value(V&: X), R: m_APInt(Res&: C0)))
2772 : match(V: Arg0, P: m_NUWAddLike(L: m_Value(V&: X), R: m_APInt(Res&: C0)));
2773 if (HasNWAdd && match(V: Arg1, P: m_APInt(Res&: C1))) {
2774 bool Overflow;
2775 APInt NewC =
2776 IsSigned ? C1->sadd_ov(RHS: *C0, Overflow) : C1->uadd_ov(RHS: *C0, Overflow);
2777 if (!Overflow)
2778 return replaceInstUsesWith(
2779 I&: *II, V: Builder.CreateBinaryIntrinsic(
2780 ID: IID, LHS: X, RHS: ConstantInt::get(Ty: Arg1->getType(), V: NewC)));
2781 }
2782 break;
2783 }
2784
2785 case Intrinsic::umul_with_overflow:
2786 case Intrinsic::smul_with_overflow:
2787 case Intrinsic::usub_with_overflow:
2788 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2789 return I;
2790 break;
2791
2792 case Intrinsic::ssub_with_overflow: {
2793 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2794 return I;
2795
2796 Constant *C;
2797 Value *Arg0 = II->getArgOperand(i: 0);
2798 Value *Arg1 = II->getArgOperand(i: 1);
2799 // Given a constant C that is not the minimum signed value
2800 // for an integer of a given bit width:
2801 //
2802 // ssubo X, C -> saddo X, -C
2803 if (match(V: Arg1, P: m_Constant(C)) && C->isNotMinSignedValue()) {
2804 Value *NegVal = ConstantExpr::getNeg(C);
2805 // Build a saddo call that is equivalent to the discovered
2806 // ssubo call.
2807 return replaceInstUsesWith(
2808 I&: *II, V: Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_with_overflow,
2809 LHS: Arg0, RHS: NegVal));
2810 }
2811
2812 break;
2813 }
2814
2815 case Intrinsic::uadd_sat:
2816 case Intrinsic::sadd_sat:
2817 case Intrinsic::usub_sat:
2818 case Intrinsic::ssub_sat: {
2819 SaturatingInst *SI = cast<SaturatingInst>(Val: II);
2820 Type *Ty = SI->getType();
2821 Value *Arg0 = SI->getLHS();
2822 Value *Arg1 = SI->getRHS();
2823
2824 // Make use of known overflow information.
2825 OverflowResult OR = computeOverflow(BinaryOp: SI->getBinaryOp(), IsSigned: SI->isSigned(),
2826 LHS: Arg0, RHS: Arg1, CxtI: SI);
2827 switch (OR) {
2828 case OverflowResult::MayOverflow:
2829 break;
2830 case OverflowResult::NeverOverflows:
2831 if (SI->isSigned())
2832 return BinaryOperator::CreateNSW(Opc: SI->getBinaryOp(), V1: Arg0, V2: Arg1);
2833 else
2834 return BinaryOperator::CreateNUW(Opc: SI->getBinaryOp(), V1: Arg0, V2: Arg1);
2835 case OverflowResult::AlwaysOverflowsLow: {
2836 unsigned BitWidth = Ty->getScalarSizeInBits();
2837 APInt Min = APSInt::getMinValue(numBits: BitWidth, Unsigned: !SI->isSigned());
2838 return replaceInstUsesWith(I&: *SI, V: ConstantInt::get(Ty, V: Min));
2839 }
2840 case OverflowResult::AlwaysOverflowsHigh: {
2841 unsigned BitWidth = Ty->getScalarSizeInBits();
2842 APInt Max = APSInt::getMaxValue(numBits: BitWidth, Unsigned: !SI->isSigned());
2843 return replaceInstUsesWith(I&: *SI, V: ConstantInt::get(Ty, V: Max));
2844 }
2845 }
2846
2847 // usub_sat((sub nuw C, A), C1) -> usub_sat(usub_sat(C, C1), A)
2848 // which after that:
2849 // usub_sat((sub nuw C, A), C1) -> usub_sat(C - C1, A) if C1 u< C
2850 // usub_sat((sub nuw C, A), C1) -> 0 otherwise
2851 Constant *C, *C1;
2852 Value *A;
2853 if (IID == Intrinsic::usub_sat &&
2854 match(V: Arg0, P: m_NUWSub(L: m_ImmConstant(C), R: m_Value(V&: A))) &&
2855 match(V: Arg1, P: m_ImmConstant(C&: C1))) {
2856 auto *NewC = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: C, RHS: C1);
2857 auto *NewSub =
2858 Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: NewC, RHS: A);
2859 return replaceInstUsesWith(I&: *SI, V: NewSub);
2860 }
2861
2862 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2863 if (IID == Intrinsic::ssub_sat && match(V: Arg1, P: m_Constant(C)) &&
2864 C->isNotMinSignedValue()) {
2865 Value *NegVal = ConstantExpr::getNeg(C);
2866 return replaceInstUsesWith(
2867 I&: *II, V: Builder.CreateBinaryIntrinsic(
2868 ID: Intrinsic::sadd_sat, LHS: Arg0, RHS: NegVal));
2869 }
2870
2871 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2872 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2873 // if Val and Val2 have the same sign
2874 if (auto *Other = dyn_cast<IntrinsicInst>(Val: Arg0)) {
2875 Value *X;
2876 const APInt *Val, *Val2;
2877 APInt NewVal;
2878 bool IsUnsigned =
2879 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2880 if (Other->getIntrinsicID() == IID &&
2881 match(V: Arg1, P: m_APInt(Res&: Val)) &&
2882 match(V: Other->getArgOperand(i: 0), P: m_Value(V&: X)) &&
2883 match(V: Other->getArgOperand(i: 1), P: m_APInt(Res&: Val2))) {
2884 if (IsUnsigned)
2885 NewVal = Val->uadd_sat(RHS: *Val2);
2886 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2887 bool Overflow;
2888 NewVal = Val->sadd_ov(RHS: *Val2, Overflow);
2889 if (Overflow) {
2890 // Both adds together may add more than SignedMaxValue
2891 // without saturating the final result.
2892 break;
2893 }
2894 } else {
2895 // Cannot fold saturated addition with different signs.
2896 break;
2897 }
2898
2899 return replaceInstUsesWith(
2900 I&: *II, V: Builder.CreateBinaryIntrinsic(
2901 ID: IID, LHS: X, RHS: ConstantInt::get(Ty: II->getType(), V: NewVal)));
2902 }
2903 }
2904 break;
2905 }
2906
2907 case Intrinsic::minnum:
2908 case Intrinsic::maxnum:
2909 case Intrinsic::minimumnum:
2910 case Intrinsic::maximumnum:
2911 case Intrinsic::minimum:
2912 case Intrinsic::maximum: {
2913 Value *Arg0 = II->getArgOperand(i: 0);
2914 Value *Arg1 = II->getArgOperand(i: 1);
2915 Value *X, *Y;
2916 if (match(V: Arg0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Arg1, P: m_FNeg(X: m_Value(V&: Y))) &&
2917 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2918 // If both operands are negated, invert the call and negate the result:
2919 // min(-X, -Y) --> -(max(X, Y))
2920 // max(-X, -Y) --> -(min(X, Y))
2921 Intrinsic::ID NewIID;
2922 switch (IID) {
2923 case Intrinsic::maxnum:
2924 NewIID = Intrinsic::minnum;
2925 break;
2926 case Intrinsic::minnum:
2927 NewIID = Intrinsic::maxnum;
2928 break;
2929 case Intrinsic::maximumnum:
2930 NewIID = Intrinsic::minimumnum;
2931 break;
2932 case Intrinsic::minimumnum:
2933 NewIID = Intrinsic::maximumnum;
2934 break;
2935 case Intrinsic::maximum:
2936 NewIID = Intrinsic::minimum;
2937 break;
2938 case Intrinsic::minimum:
2939 NewIID = Intrinsic::maximum;
2940 break;
2941 default:
2942 llvm_unreachable("unexpected intrinsic ID");
2943 }
2944 Value *NewCall = Builder.CreateBinaryIntrinsic(ID: NewIID, LHS: X, RHS: Y, FMFSource: II);
2945 Instruction *FNeg = UnaryOperator::CreateFNeg(V: NewCall);
2946 FNeg->copyIRFlags(V: II);
2947 return FNeg;
2948 }
2949
2950 // m(m(X, C2), C1) -> m(X, C)
2951 const APFloat *C1, *C2;
2952 if (auto *M = dyn_cast<IntrinsicInst>(Val: Arg0)) {
2953 if (M->getIntrinsicID() == IID && match(V: Arg1, P: m_APFloat(Res&: C1)) &&
2954 ((match(V: M->getArgOperand(i: 0), P: m_Value(V&: X)) &&
2955 match(V: M->getArgOperand(i: 1), P: m_APFloat(Res&: C2))) ||
2956 (match(V: M->getArgOperand(i: 1), P: m_Value(V&: X)) &&
2957 match(V: M->getArgOperand(i: 0), P: m_APFloat(Res&: C2))))) {
2958 APFloat Res(0.0);
2959 switch (IID) {
2960 case Intrinsic::maxnum:
2961 Res = maxnum(A: *C1, B: *C2);
2962 break;
2963 case Intrinsic::minnum:
2964 Res = minnum(A: *C1, B: *C2);
2965 break;
2966 case Intrinsic::maximumnum:
2967 Res = maximumnum(A: *C1, B: *C2);
2968 break;
2969 case Intrinsic::minimumnum:
2970 Res = minimumnum(A: *C1, B: *C2);
2971 break;
2972 case Intrinsic::maximum:
2973 Res = maximum(A: *C1, B: *C2);
2974 break;
2975 case Intrinsic::minimum:
2976 Res = minimum(A: *C1, B: *C2);
2977 break;
2978 default:
2979 llvm_unreachable("unexpected intrinsic ID");
2980 }
2981 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
2982 // was a simplification (so Arg0 and its original flags could
2983 // propagate?)
2984 Value *V = Builder.CreateBinaryIntrinsic(
2985 ID: IID, LHS: X, RHS: ConstantFP::get(Ty: Arg0->getType(), V: Res),
2986 FMFSource: FMFSource::intersect(A: II, B: M));
2987 return replaceInstUsesWith(I&: *II, V);
2988 }
2989 }
2990
2991 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
2992 if (match(V: Arg0, P: m_FPExt(Op: m_Value(V&: X))) && match(V: Arg1, P: m_FPExt(Op: m_Value(V&: Y))) &&
2993 (Arg0->hasOneUse() || Arg1->hasOneUse()) &&
2994 X->getType() == Y->getType()) {
2995 Value *NewCall =
2996 Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: Y, FMFSource: II, Name: II->getName());
2997 return new FPExtInst(NewCall, II->getType());
2998 }
2999
3000 // m(fpext X, C) -> fpext m(X, TruncC) if C can be losslessly truncated.
3001 Constant *C;
3002 if (match(V: Arg0, P: m_OneUse(SubPattern: m_FPExt(Op: m_Value(V&: X)))) &&
3003 match(V: Arg1, P: m_ImmConstant(C))) {
3004 if (Constant *TruncC =
3005 getLosslessInvCast(C, InvCastTo: X->getType(), CastOp: Instruction::FPExt, DL)) {
3006 Value *NewCall =
3007 Builder.CreateBinaryIntrinsic(ID: IID, LHS: X, RHS: TruncC, FMFSource: II, Name: II->getName());
3008 return new FPExtInst(NewCall, II->getType());
3009 }
3010 }
3011
3012 // max X, -X --> fabs X
3013 // min X, -X --> -(fabs X)
3014 // TODO: Remove one-use limitation? That is obviously better for max,
3015 // hence why we don't check for one-use for that. However,
3016 // it would be an extra instruction for min (fnabs), but
3017 // that is still likely better for analysis and codegen.
3018 auto IsMinMaxOrXNegX = [IID, &X](Value *Op0, Value *Op1) {
3019 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_Specific(V: X)))
3020 return Op0->hasOneUse() ||
3021 (IID != Intrinsic::minimum && IID != Intrinsic::minnum &&
3022 IID != Intrinsic::minimumnum);
3023 return false;
3024 };
3025
3026 if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {
3027 Value *R = Builder.CreateFAbs(V: X, FMFSource: II);
3028 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum ||
3029 IID == Intrinsic::minimumnum)
3030 R = Builder.CreateFNegFMF(V: R, FMFSource: II);
3031 return replaceInstUsesWith(I&: *II, V: R);
3032 }
3033
3034 break;
3035 }
3036 case Intrinsic::matrix_multiply: {
3037 // Optimize negation in matrix multiplication.
3038
3039 // -A * -B -> A * B
3040 Value *A, *B;
3041 if (match(V: II->getArgOperand(i: 0), P: m_FNeg(X: m_Value(V&: A))) &&
3042 match(V: II->getArgOperand(i: 1), P: m_FNeg(X: m_Value(V&: B)))) {
3043 replaceOperand(I&: *II, OpNum: 0, V: A);
3044 replaceOperand(I&: *II, OpNum: 1, V: B);
3045 return II;
3046 }
3047
3048 Value *Op0 = II->getOperand(i_nocapture: 0);
3049 Value *Op1 = II->getOperand(i_nocapture: 1);
3050 Value *OpNotNeg, *NegatedOp;
3051 unsigned NegatedOpArg, OtherOpArg;
3052 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: OpNotNeg)))) {
3053 NegatedOp = Op0;
3054 NegatedOpArg = 0;
3055 OtherOpArg = 1;
3056 } else if (match(V: Op1, P: m_FNeg(X: m_Value(V&: OpNotNeg)))) {
3057 NegatedOp = Op1;
3058 NegatedOpArg = 1;
3059 OtherOpArg = 0;
3060 } else
3061 // Multiplication doesn't have a negated operand.
3062 break;
3063
3064 // Only optimize if the negated operand has only one use.
3065 if (!NegatedOp->hasOneUse())
3066 break;
3067
3068 Value *OtherOp = II->getOperand(i_nocapture: OtherOpArg);
3069 VectorType *RetTy = cast<VectorType>(Val: II->getType());
3070 VectorType *NegatedOpTy = cast<VectorType>(Val: NegatedOp->getType());
3071 VectorType *OtherOpTy = cast<VectorType>(Val: OtherOp->getType());
3072 ElementCount NegatedCount = NegatedOpTy->getElementCount();
3073 ElementCount OtherCount = OtherOpTy->getElementCount();
3074 ElementCount RetCount = RetTy->getElementCount();
3075 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
3076 if (ElementCount::isKnownGT(LHS: NegatedCount, RHS: OtherCount) &&
3077 ElementCount::isKnownLT(LHS: OtherCount, RHS: RetCount)) {
3078 Value *InverseOtherOp = Builder.CreateFNeg(V: OtherOp);
3079 replaceOperand(I&: *II, OpNum: NegatedOpArg, V: OpNotNeg);
3080 replaceOperand(I&: *II, OpNum: OtherOpArg, V: InverseOtherOp);
3081 return II;
3082 }
3083 // (-A) * B -> -(A * B), if it is cheaper to negate the result
3084 if (ElementCount::isKnownGT(LHS: NegatedCount, RHS: RetCount)) {
3085 SmallVector<Value *, 5> NewArgs(II->args());
3086 NewArgs[NegatedOpArg] = OpNotNeg;
3087 Value *NewMul = Builder.CreateIntrinsic(RetTy: II->getType(), ID: IID, Args: NewArgs, FMFSource: II);
3088 return replaceInstUsesWith(I&: *II, V: Builder.CreateFNegFMF(V: NewMul, FMFSource: II));
3089 }
3090 break;
3091 }
3092 case Intrinsic::fmuladd: {
3093 // Try to simplify the underlying FMul.
3094 if (Value *V =
3095 simplifyFMulInst(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1),
3096 FMF: II->getFastMathFlags(), Q: SQ.getWithInstruction(I: II)))
3097 return BinaryOperator::CreateFAddFMF(V1: V, V2: II->getArgOperand(i: 2),
3098 FMF: II->getFastMathFlags());
3099
3100 [[fallthrough]];
3101 }
3102 case Intrinsic::fma: {
3103 // fma fneg(x), fneg(y), z -> fma x, y, z
3104 Value *Src0 = II->getArgOperand(i: 0);
3105 Value *Src1 = II->getArgOperand(i: 1);
3106 Value *Src2 = II->getArgOperand(i: 2);
3107 Value *X, *Y;
3108 if (match(V: Src0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Src1, P: m_FNeg(X: m_Value(V&: Y))))
3109 return replaceInstUsesWith(
3110 I&: *II, V: Builder.CreateIntrinsic(ID: IID, OverloadTypes: II->getType(), Args: {X, Y, Src2}, FMFSource: II));
3111
3112 // fma fabs(x), fabs(x), z -> fma x, x, z
3113 if (match(V: Src0, P: m_FAbs(Op0: m_Value(V&: X))) && match(V: Src1, P: m_FAbs(Op0: m_Specific(V: X))))
3114 return replaceInstUsesWith(
3115 I&: *II, V: Builder.CreateIntrinsic(ID: IID, OverloadTypes: II->getType(), Args: {X, X, Src2}, FMFSource: II));
3116
3117 // Try to simplify the underlying FMul. We can only apply simplifications
3118 // that do not require rounding.
3119 if (Value *V = simplifyFMAFMul(LHS: Src0, RHS: Src1, FMF: II->getFastMathFlags(),
3120 Q: SQ.getWithInstruction(I: II)))
3121 return BinaryOperator::CreateFAddFMF(V1: V, V2: Src2, FMF: II->getFastMathFlags());
3122
3123 // fma x, y, 0 -> fmul x, y
3124 // This is always valid for -0.0, but requires nsz for +0.0 as
3125 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
3126 if (match(V: Src2, P: m_NegZeroFP()) ||
3127 (match(V: Src2, P: m_PosZeroFP()) && II->getFastMathFlags().noSignedZeros()))
3128 return BinaryOperator::CreateFMulFMF(V1: Src0, V2: Src1, FMFSource: II);
3129
3130 // fma x, -1.0, y -> fsub y, x
3131 if (match(V: Src1, P: m_SpecificFP(V: -1.0)))
3132 return BinaryOperator::CreateFSubFMF(V1: Src2, V2: Src0, FMFSource: II);
3133
3134 break;
3135 }
3136 case Intrinsic::copysign: {
3137 Value *Mag = II->getArgOperand(i: 0), *Sign = II->getArgOperand(i: 1);
3138 if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(
3139 V: Sign, SQ: getSimplifyQuery().getWithInstruction(I: II))) {
3140 if (*KnownSignBit) {
3141 // If we know that the sign argument is negative, reduce to FNABS:
3142 // copysign Mag, -Sign --> fneg (fabs Mag)
3143 Value *Fabs = Builder.CreateFAbs(V: Mag, FMFSource: II);
3144 return replaceInstUsesWith(I&: *II, V: Builder.CreateFNegFMF(V: Fabs, FMFSource: II));
3145 }
3146
3147 // If we know that the sign argument is positive, reduce to FABS:
3148 // copysign Mag, +Sign --> fabs Mag
3149 Value *Fabs = Builder.CreateFAbs(V: Mag, FMFSource: II);
3150 return replaceInstUsesWith(I&: *II, V: Fabs);
3151 }
3152
3153 // Propagate sign argument through nested calls:
3154 // copysign Mag, (copysign ?, X) --> copysign Mag, X
3155 Value *X;
3156 if (match(V: Sign, P: m_Intrinsic<Intrinsic::copysign>(Op0: m_Value(), Op1: m_Value(V&: X)))) {
3157 Value *CopySign =
3158 Builder.CreateCopySign(LHS: Mag, RHS: X, FMFSource: FMFSource::intersect(A: II, B: Sign));
3159 return replaceInstUsesWith(I&: *II, V: CopySign);
3160 }
3161
3162 // Clear sign-bit of constant magnitude:
3163 // copysign -MagC, X --> copysign MagC, X
3164 // TODO: Support constant folding for fabs
3165 const APFloat *MagC;
3166 if (match(V: Mag, P: m_APFloat(Res&: MagC)) && MagC->isNegative()) {
3167 APFloat PosMagC = *MagC;
3168 PosMagC.clearSign();
3169 return replaceInstUsesWith(
3170 I&: *II, V: Builder.CreateCopySign(LHS: ConstantFP::get(Ty: Mag->getType(), V: PosMagC),
3171 RHS: Sign, FMFSource: II));
3172 }
3173
3174 // Peek through changes of magnitude's sign-bit. This call rewrites those:
3175 // copysign (fabs X), Sign --> copysign X, Sign
3176 // copysign (fneg X), Sign --> copysign X, Sign
3177 if (match(V: Mag, P: m_FAbs(Op0: m_Value(V&: X))) || match(V: Mag, P: m_FNeg(X: m_Value(V&: X))))
3178 return replaceInstUsesWith(I&: *II, V: Builder.CreateCopySign(LHS: X, RHS: Sign, FMFSource: II));
3179
3180 // copysign(floor(fabs(X)), X) --> copysign(trunc(X), X)
3181 // copysign ignores the sign bit of its magnitude argument (implicit fabs),
3182 // so replacing floor(fabs(X)) with trunc(X) is correct for all inputs
3183 // including NaN without requiring nnan. The m_FAbs match also ensures
3184 // the floor argument is non-negative, so floor == trunc.
3185 Value *FAbsArg;
3186 if (match(V: Mag, P: m_Intrinsic<Intrinsic::floor>(Op0: m_FAbs(Op0: m_Value(V&: FAbsArg)))) &&
3187 FAbsArg == Sign) {
3188 Value *Trunc = Builder.CreateUnaryIntrinsic(ID: Intrinsic::trunc, Op: Sign, FMFSource: II);
3189 return replaceInstUsesWith(I&: *II, V: Builder.CreateCopySign(LHS: Trunc, RHS: Sign, FMFSource: II));
3190 }
3191
3192 Type *SignEltTy = Sign->getType()->getScalarType();
3193
3194 Value *CastSrc;
3195 if (match(V: Sign,
3196 P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_OneUse(SubPattern: m_Value(V&: CastSrc))))) &&
3197 CastSrc->getType()->isIntOrIntVectorTy() &&
3198 APFloat::hasSignBitInMSB(SignEltTy->getFltSemantics())) {
3199 KnownBits Known(SignEltTy->getPrimitiveSizeInBits());
3200 if (SimplifyDemandedBits(I: cast<Instruction>(Val: Sign), Op: 0,
3201 DemandedMask: APInt::getSignMask(BitWidth: Known.getBitWidth()), Known,
3202 Q: SQ))
3203 return II;
3204 }
3205
3206 break;
3207 }
3208 case Intrinsic::fabs: {
3209 Value *Cond, *TVal, *FVal;
3210 Value *Arg = II->getArgOperand(i: 0);
3211 Value *X;
3212 // fabs (-X) --> fabs (X)
3213 if (match(V: Arg, P: m_FNeg(X: m_Value(V&: X)))) {
3214 Value *Fabs = Builder.CreateFAbs(V: X, FMFSource: II);
3215 return replaceInstUsesWith(I&: CI, V: Fabs);
3216 }
3217
3218 if (match(V: Arg, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))) {
3219 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
3220 if (Arg->hasOneUse() ? (isa<Constant>(Val: TVal) || isa<Constant>(Val: FVal))
3221 : (isa<Constant>(Val: TVal) && isa<Constant>(Val: FVal))) {
3222 CallInst *AbsT = Builder.CreateCall(Callee: II->getCalledFunction(), Args: {TVal});
3223 CallInst *AbsF = Builder.CreateCall(Callee: II->getCalledFunction(), Args: {FVal});
3224 SelectInst *SI = SelectInst::Create(C: Cond, S1: AbsT, S2: AbsF);
3225 SI->setFastMathFlags(II->getFastMathFlags() |
3226 cast<SelectInst>(Val: Arg)->getFastMathFlags());
3227 // Can't copy nsz to select, as even with the nsz flag the fabs result
3228 // always has the sign bit unset.
3229 SI->setHasNoSignedZeros(false);
3230 return SI;
3231 }
3232 // fabs (select Cond, -FVal, FVal) --> fabs FVal
3233 if (match(V: TVal, P: m_FNeg(X: m_Specific(V: FVal))))
3234 return replaceInstUsesWith(I&: *II, V: Builder.CreateFAbs(V: FVal, FMFSource: II));
3235 // fabs (select Cond, TVal, -TVal) --> fabs TVal
3236 if (match(V: FVal, P: m_FNeg(X: m_Specific(V: TVal))))
3237 return replaceInstUsesWith(I&: *II, V: Builder.CreateFAbs(V: TVal, FMFSource: II));
3238 }
3239
3240 Value *Magnitude, *Sign;
3241 if (match(V: II->getArgOperand(i: 0),
3242 P: m_CopySign(Op0: m_Value(V&: Magnitude), Op1: m_Value(V&: Sign)))) {
3243 // fabs (copysign x, y) -> (fabs x)
3244 Value *AbsSign = Builder.CreateFAbs(V: Magnitude, FMFSource: II);
3245 return replaceInstUsesWith(I&: *II, V: AbsSign);
3246 }
3247
3248 [[fallthrough]];
3249 }
3250 case Intrinsic::ceil:
3251 case Intrinsic::floor:
3252 case Intrinsic::round:
3253 case Intrinsic::roundeven:
3254 case Intrinsic::nearbyint:
3255 case Intrinsic::rint:
3256 case Intrinsic::trunc: {
3257 Value *ExtSrc;
3258 if (match(V: II->getArgOperand(i: 0), P: m_OneUse(SubPattern: m_FPExt(Op: m_Value(V&: ExtSrc))))) {
3259 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
3260 Value *NarrowII = Builder.CreateUnaryIntrinsic(ID: IID, Op: ExtSrc, FMFSource: II);
3261 return new FPExtInst(NarrowII, II->getType());
3262 }
3263 break;
3264 }
3265 case Intrinsic::cos:
3266 case Intrinsic::amdgcn_cos:
3267 case Intrinsic::cosh: {
3268 Value *X, *Sign;
3269 Value *Src = II->getArgOperand(i: 0);
3270 if (match(V: Src, P: m_FNeg(X: m_Value(V&: X))) || match(V: Src, P: m_FAbs(Op0: m_Value(V&: X))) ||
3271 match(V: Src, P: m_CopySign(Op0: m_Value(V&: X), Op1: m_Value(V&: Sign)))) {
3272 // f(-x) --> f(x)
3273 // f(fabs(x)) --> f(x)
3274 // f(copysign(x, y)) --> f(x)
3275 // for f in {cos, cosh}
3276 return replaceInstUsesWith(I&: *II, V: Builder.CreateUnaryIntrinsic(ID: IID, Op: X, FMFSource: II));
3277 }
3278 break;
3279 }
3280 case Intrinsic::sin:
3281 case Intrinsic::amdgcn_sin:
3282 case Intrinsic::sinh:
3283 case Intrinsic::tan:
3284 case Intrinsic::tanh: {
3285 Value *X;
3286 if (match(V: II->getArgOperand(i: 0), P: m_OneUse(SubPattern: m_FNeg(X: m_Value(V&: X))))) {
3287 // f(-x) --> -f(x)
3288 // for f in {sin, sinh, tan, tanh}
3289 Value *NewFunc = Builder.CreateUnaryIntrinsic(ID: IID, Op: X, FMFSource: II);
3290 return UnaryOperator::CreateFNegFMF(Op: NewFunc, FMFSource: II);
3291 }
3292 break;
3293 }
3294 case Intrinsic::ldexp: {
3295 Value *Src = II->getArgOperand(i: 0);
3296 Value *Exp = II->getArgOperand(i: 1);
3297
3298 // ldexp(x, K) -> fmul x, 2^K
3299 uint64_t ConstExp;
3300 if (match(V: Exp, P: m_ConstantInt(V&: ConstExp))) {
3301 const fltSemantics &FPTy =
3302 Src->getType()->getScalarType()->getFltSemantics();
3303
3304 APFloat Scaled = scalbn(X: APFloat::getOne(Sem: FPTy), Exp: static_cast<int>(ConstExp),
3305 RM: APFloat::rmNearestTiesToEven);
3306 if (!Scaled.isZero() && !Scaled.isInfinity()) {
3307 // Skip overflow and underflow cases.
3308 Constant *FPConst = ConstantFP::get(Ty: Src->getType(), V: Scaled);
3309 return BinaryOperator::CreateFMulFMF(V1: Src, V2: FPConst, FMFSource: II);
3310 }
3311 }
3312
3313 // ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b))
3314 //
3315 // A danger is if the first ldexp would overflow to infinity or underflow to
3316 // zero, but the combined exponent avoids it.
3317 //
3318 // We ignore this with reassoc, or if we know both exponents have the same
3319 // sign (since then we'd just double down on the over/underflow which would
3320 // occur anyway).
3321 //
3322 // ldexp can take arbitrary integer types, so we also need to ensure that
3323 // our exponent type is wide enough so that if sadd.sat(a, b) saturates,
3324 // then ldexp at the saturated exponent saturates to inf or zero as well.
3325 //
3326 // TODO: Could do better if we had range tracking for the input value
3327 // exponent. Also could broaden sign check to cover == 0 case.
3328 Value *InnerSrc;
3329 Value *InnerExp;
3330 if (match(V: Src, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::ldexp>(
3331 Op0: m_Value(V&: InnerSrc), Op1: m_Value(V&: InnerExp)))) &&
3332 Exp->getType() == InnerExp->getType()) {
3333 FastMathFlags FMF = II->getFastMathFlags();
3334 FastMathFlags InnerFlags = cast<FPMathOperator>(Val: Src)->getFastMathFlags();
3335
3336 if (ldexpSaturatingAddIsSafe(FpTy: II->getType(), ExpTy: Exp->getType()) &&
3337 ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
3338 signBitMustBeTheSame(Op0: Exp, Op1: InnerExp, SQ: SQ.getWithInstruction(I: II)))) {
3339 Value *NewExp =
3340 Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: InnerExp, RHS: Exp);
3341 return replaceInstUsesWith(
3342 I&: *II, V: Builder.CreateLdexp(Src: InnerSrc, Exp: NewExp, FMFSource: FMF | InnerFlags));
3343 }
3344 }
3345
3346 // ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)
3347 // ldexp(x, sext(i1 y)) -> fmul x, (select y, 0.5, 1.0)
3348 Value *ExtSrc;
3349 if (match(V: Exp, P: m_ZExt(Op: m_Value(V&: ExtSrc))) &&
3350 ExtSrc->getType()->getScalarSizeInBits() == 1) {
3351 Value *Select =
3352 Builder.CreateSelect(C: ExtSrc, True: ConstantFP::get(Ty: II->getType(), V: 2.0),
3353 False: ConstantFP::get(Ty: II->getType(), V: 1.0));
3354 return BinaryOperator::CreateFMulFMF(V1: Src, V2: Select, FMFSource: II);
3355 }
3356 if (match(V: Exp, P: m_SExt(Op: m_Value(V&: ExtSrc))) &&
3357 ExtSrc->getType()->getScalarSizeInBits() == 1) {
3358 Value *Select =
3359 Builder.CreateSelect(C: ExtSrc, True: ConstantFP::get(Ty: II->getType(), V: 0.5),
3360 False: ConstantFP::get(Ty: II->getType(), V: 1.0));
3361 return BinaryOperator::CreateFMulFMF(V1: Src, V2: Select, FMFSource: II);
3362 }
3363
3364 // ldexp(x, c ? exp : 0) -> c ? ldexp(x, exp) : x
3365 // ldexp(x, c ? 0 : exp) -> c ? x : ldexp(x, exp)
3366 ///
3367 // TODO: If we cared, should insert a canonicalize for x
3368 Value *SelectCond, *SelectLHS, *SelectRHS;
3369 if (match(V: II->getArgOperand(i: 1),
3370 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: SelectCond), L: m_Value(V&: SelectLHS),
3371 R: m_Value(V&: SelectRHS))))) {
3372 Value *NewLdexp = nullptr;
3373 Value *Select = nullptr;
3374 if (match(V: SelectRHS, P: m_ZeroInt())) {
3375 NewLdexp = Builder.CreateLdexp(Src, Exp: SelectLHS, FMFSource: II);
3376 Select = Builder.CreateSelect(C: SelectCond, True: NewLdexp, False: Src);
3377 } else if (match(V: SelectLHS, P: m_ZeroInt())) {
3378 NewLdexp = Builder.CreateLdexp(Src, Exp: SelectRHS, FMFSource: II);
3379 Select = Builder.CreateSelect(C: SelectCond, True: Src, False: NewLdexp);
3380 }
3381
3382 if (NewLdexp) {
3383 Select->takeName(V: II);
3384 return replaceInstUsesWith(I&: *II, V: Select);
3385 }
3386 }
3387
3388 break;
3389 }
3390 case Intrinsic::ptrauth_auth:
3391 case Intrinsic::ptrauth_resign: {
3392 // (sign|resign) + (auth|resign) can be folded by omitting the middle
3393 // sign+auth component if the key and discriminator match.
3394 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
3395 Value *Ptr = II->getArgOperand(i: 0);
3396 Value *Key = II->getArgOperand(i: 1);
3397 Value *Disc = II->getArgOperand(i: 2);
3398 Value *DS = nullptr;
3399 if (auto Bundle = II->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
3400 DS = Bundle->Inputs[0];
3401
3402 // AuthKey will be the key we need to end up authenticating against in
3403 // whatever we replace this sequence with.
3404 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
3405 if (const auto *CI = dyn_cast<CallBase>(Val: Ptr)) {
3406 Value *OtherDS = nullptr;
3407 if (auto Bundle =
3408 CI->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
3409 OtherDS = Bundle->Inputs[0];
3410 if (DS != OtherDS)
3411 break;
3412
3413 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
3414 if (CI->getArgOperand(i: 1) != Key || CI->getArgOperand(i: 2) != Disc)
3415 break;
3416 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
3417 // The resign intrinsic does not support deactivation symbols.
3418 assert(!DS);
3419 if (CI->getArgOperand(i: 3) != Key || CI->getArgOperand(i: 4) != Disc)
3420 break;
3421 AuthKey = CI->getArgOperand(i: 1);
3422 AuthDisc = CI->getArgOperand(i: 2);
3423 } else
3424 break;
3425 BasePtr = CI->getArgOperand(i: 0);
3426 } else if (const auto *PtrToInt = dyn_cast<PtrToIntOperator>(Val: Ptr)) {
3427 // ptrauth constants are equivalent to a call to @llvm.ptrauth.sign for
3428 // our purposes, so check for that too.
3429 const auto *CPA = dyn_cast<ConstantPtrAuth>(Val: PtrToInt->getOperand(i_nocapture: 0));
3430 if (!CPA || DS || !CPA->isKnownCompatibleWith(Key, Discriminator: Disc, DL))
3431 break;
3432
3433 // resign(ptrauth(p,ks,ds),ks,ds,kr,dr) -> ptrauth(p,kr,dr)
3434 if (NeedSign && isa<ConstantInt>(Val: II->getArgOperand(i: 4))) {
3435 auto *SignKey = cast<ConstantInt>(Val: II->getArgOperand(i: 3));
3436 auto *SignDisc = cast<ConstantInt>(Val: II->getArgOperand(i: 4));
3437 auto *Null = ConstantPointerNull::get(T: Builder.getPtrTy());
3438 auto *NewCPA = ConstantPtrAuth::get(Ptr: CPA->getPointer(), Key: SignKey,
3439 Disc: SignDisc, /*AddrDisc=*/Null,
3440 /*DeactivationSymbol=*/Null);
3441 replaceInstUsesWith(
3442 I&: *II, V: ConstantExpr::getPointerCast(C: NewCPA, Ty: II->getType()));
3443 return eraseInstFromFunction(I&: *II);
3444 }
3445
3446 // auth(ptrauth(p,k,d),k,d) -> p
3447 BasePtr = Builder.CreatePtrToInt(V: CPA->getPointer(), DestTy: II->getType());
3448 } else
3449 break;
3450
3451 unsigned NewIntrin;
3452 if (AuthKey && NeedSign) {
3453 // resign(0,1) + resign(1,2) = resign(0, 2)
3454 NewIntrin = Intrinsic::ptrauth_resign;
3455 } else if (AuthKey) {
3456 // resign(0,1) + auth(1) = auth(0)
3457 NewIntrin = Intrinsic::ptrauth_auth;
3458 } else if (NeedSign) {
3459 // sign(0) + resign(0, 1) = sign(1)
3460 NewIntrin = Intrinsic::ptrauth_sign;
3461 } else {
3462 // sign(0) + auth(0) = nop
3463 replaceInstUsesWith(I&: *II, V: BasePtr);
3464 return eraseInstFromFunction(I&: *II);
3465 }
3466
3467 SmallVector<Value *, 4> CallArgs;
3468 CallArgs.push_back(Elt: BasePtr);
3469 if (AuthKey) {
3470 CallArgs.push_back(Elt: AuthKey);
3471 CallArgs.push_back(Elt: AuthDisc);
3472 }
3473
3474 if (NeedSign) {
3475 CallArgs.push_back(Elt: II->getArgOperand(i: 3));
3476 CallArgs.push_back(Elt: II->getArgOperand(i: 4));
3477 }
3478
3479 std::vector<OperandBundleDef> Bundles;
3480 if (DS)
3481 Bundles.push_back(x: OperandBundleDef("deactivation-symbol", DS));
3482
3483 Function *NewFn =
3484 Intrinsic::getOrInsertDeclaration(M: II->getModule(), id: NewIntrin);
3485 return CallInst::Create(Func: NewFn, Args: CallArgs, Bundles);
3486 }
3487 case Intrinsic::arm_neon_vtbl1:
3488 case Intrinsic::arm_neon_vtbl2:
3489 case Intrinsic::arm_neon_vtbl3:
3490 case Intrinsic::arm_neon_vtbl4:
3491 case Intrinsic::aarch64_neon_tbl1:
3492 case Intrinsic::aarch64_neon_tbl2:
3493 case Intrinsic::aarch64_neon_tbl3:
3494 case Intrinsic::aarch64_neon_tbl4:
3495 return simplifyNeonTbl(II&: *II, IC&: *this, /*IsExtension=*/false);
3496 case Intrinsic::arm_neon_vtbx1:
3497 case Intrinsic::arm_neon_vtbx2:
3498 case Intrinsic::arm_neon_vtbx3:
3499 case Intrinsic::arm_neon_vtbx4:
3500 case Intrinsic::aarch64_neon_tbx1:
3501 case Intrinsic::aarch64_neon_tbx2:
3502 case Intrinsic::aarch64_neon_tbx3:
3503 case Intrinsic::aarch64_neon_tbx4:
3504 return simplifyNeonTbl(II&: *II, IC&: *this, /*IsExtension=*/true);
3505
3506 case Intrinsic::arm_neon_vmulls:
3507 case Intrinsic::arm_neon_vmullu:
3508 case Intrinsic::aarch64_neon_smull:
3509 case Intrinsic::aarch64_neon_umull: {
3510 Value *Arg0 = II->getArgOperand(i: 0);
3511 Value *Arg1 = II->getArgOperand(i: 1);
3512
3513 // Handle mul by zero first:
3514 if (isa<ConstantAggregateZero>(Val: Arg0) || isa<ConstantAggregateZero>(Val: Arg1)) {
3515 return replaceInstUsesWith(I&: CI, V: ConstantAggregateZero::get(Ty: II->getType()));
3516 }
3517
3518 // Check for constant LHS & RHS - in this case we just simplify.
3519 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3520 IID == Intrinsic::aarch64_neon_umull);
3521 VectorType *NewVT = cast<VectorType>(Val: II->getType());
3522 if (Constant *CV0 = dyn_cast<Constant>(Val: Arg0)) {
3523 if (Constant *CV1 = dyn_cast<Constant>(Val: Arg1)) {
3524 Value *V0 = Builder.CreateIntCast(V: CV0, DestTy: NewVT, /*isSigned=*/!Zext);
3525 Value *V1 = Builder.CreateIntCast(V: CV1, DestTy: NewVT, /*isSigned=*/!Zext);
3526 return replaceInstUsesWith(I&: CI, V: Builder.CreateMul(LHS: V0, RHS: V1));
3527 }
3528
3529 // Couldn't simplify - canonicalize constant to the RHS.
3530 std::swap(a&: Arg0, b&: Arg1);
3531 }
3532
3533 // Handle mul by one:
3534 if (Constant *CV1 = dyn_cast<Constant>(Val: Arg1))
3535 if (ConstantInt *Splat =
3536 dyn_cast_or_null<ConstantInt>(Val: CV1->getSplatValue()))
3537 if (Splat->isOne())
3538 return CastInst::CreateIntegerCast(S: Arg0, Ty: II->getType(),
3539 /*isSigned=*/!Zext);
3540
3541 break;
3542 }
3543 case Intrinsic::arm_neon_aesd:
3544 case Intrinsic::arm_neon_aese:
3545 case Intrinsic::aarch64_crypto_aesd:
3546 case Intrinsic::aarch64_crypto_aese:
3547 case Intrinsic::aarch64_sve_aesd:
3548 case Intrinsic::aarch64_sve_aese: {
3549 Value *DataArg = II->getArgOperand(i: 0);
3550 Value *KeyArg = II->getArgOperand(i: 1);
3551
3552 // Accept zero on either operand.
3553 if (!match(V: KeyArg, P: m_ZeroInt()))
3554 std::swap(a&: KeyArg, b&: DataArg);
3555
3556 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3557 Value *Data, *Key;
3558 if (match(V: KeyArg, P: m_ZeroInt()) &&
3559 match(V: DataArg, P: m_Xor(L: m_Value(V&: Data), R: m_Value(V&: Key)))) {
3560 replaceOperand(I&: *II, OpNum: 0, V: Data);
3561 replaceOperand(I&: *II, OpNum: 1, V: Key);
3562 return II;
3563 }
3564 break;
3565 }
3566 case Intrinsic::arm_neon_vshifts:
3567 case Intrinsic::arm_neon_vshiftu:
3568 case Intrinsic::aarch64_neon_sshl:
3569 case Intrinsic::aarch64_neon_ushl:
3570 return foldNeonShift(II, IC&: *this);
3571 case Intrinsic::hexagon_V6_vandvrt:
3572 case Intrinsic::hexagon_V6_vandvrt_128B: {
3573 // Simplify Q -> V -> Q conversion.
3574 if (auto Op0 = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0))) {
3575 Intrinsic::ID ID0 = Op0->getIntrinsicID();
3576 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
3577 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
3578 break;
3579 Value *Bytes = Op0->getArgOperand(i: 1), *Mask = II->getArgOperand(i: 1);
3580 uint64_t Bytes1 = computeKnownBits(V: Bytes, CxtI: Op0).One.getZExtValue();
3581 uint64_t Mask1 = computeKnownBits(V: Mask, CxtI: II).One.getZExtValue();
3582 // Check if every byte has common bits in Bytes and Mask.
3583 uint64_t C = Bytes1 & Mask1;
3584 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
3585 return replaceInstUsesWith(I&: *II, V: Op0->getArgOperand(i: 0));
3586 }
3587 break;
3588 }
3589 case Intrinsic::stackrestore: {
3590 enum class ClassifyResult {
3591 None,
3592 Alloca,
3593 StackRestore,
3594 CallWithSideEffects,
3595 };
3596 auto Classify = [](const Instruction *I) {
3597 if (isa<AllocaInst>(Val: I))
3598 return ClassifyResult::Alloca;
3599
3600 if (auto *CI = dyn_cast<CallInst>(Val: I)) {
3601 if (auto *II = dyn_cast<IntrinsicInst>(Val: CI)) {
3602 if (II->getIntrinsicID() == Intrinsic::stackrestore)
3603 return ClassifyResult::StackRestore;
3604
3605 if (II->mayHaveSideEffects())
3606 return ClassifyResult::CallWithSideEffects;
3607 } else {
3608 // Consider all non-intrinsic calls to be side effects
3609 return ClassifyResult::CallWithSideEffects;
3610 }
3611 }
3612
3613 return ClassifyResult::None;
3614 };
3615
3616 // If the stacksave and the stackrestore are in the same BB, and there is
3617 // no intervening call, alloca, or stackrestore of a different stacksave,
3618 // remove the restore. This can happen when variable allocas are DCE'd.
3619 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(Val: II->getArgOperand(i: 0))) {
3620 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
3621 SS->getParent() == II->getParent()) {
3622 BasicBlock::iterator BI(SS);
3623 bool CannotRemove = false;
3624 for (++BI; &*BI != II; ++BI) {
3625 switch (Classify(&*BI)) {
3626 case ClassifyResult::None:
3627 // So far so good, look at next instructions.
3628 break;
3629
3630 case ClassifyResult::StackRestore:
3631 // If we found an intervening stackrestore for a different
3632 // stacksave, we can't remove the stackrestore. Otherwise, continue.
3633 if (cast<IntrinsicInst>(Val&: *BI).getArgOperand(i: 0) != SS)
3634 CannotRemove = true;
3635 break;
3636
3637 case ClassifyResult::Alloca:
3638 case ClassifyResult::CallWithSideEffects:
3639 // If we found an alloca, a non-intrinsic call, or an intrinsic
3640 // call with side effects, we can't remove the stackrestore.
3641 CannotRemove = true;
3642 break;
3643 }
3644 if (CannotRemove)
3645 break;
3646 }
3647
3648 if (!CannotRemove)
3649 return eraseInstFromFunction(I&: CI);
3650 }
3651 }
3652
3653 // Scan down this block to see if there is another stack restore in the
3654 // same block without an intervening call/alloca.
3655 BasicBlock::iterator BI(II);
3656 Instruction *TI = II->getParent()->getTerminator();
3657 bool CannotRemove = false;
3658 for (++BI; &*BI != TI; ++BI) {
3659 switch (Classify(&*BI)) {
3660 case ClassifyResult::None:
3661 // So far so good, look at next instructions.
3662 break;
3663
3664 case ClassifyResult::StackRestore:
3665 // If there is a stackrestore below this one, remove this one.
3666 return eraseInstFromFunction(I&: CI);
3667
3668 case ClassifyResult::Alloca:
3669 case ClassifyResult::CallWithSideEffects:
3670 // If we found an alloca, a non-intrinsic call, or an intrinsic call
3671 // with side effects (such as llvm.stacksave and llvm.read_register),
3672 // we can't remove the stack restore.
3673 CannotRemove = true;
3674 break;
3675 }
3676 if (CannotRemove)
3677 break;
3678 }
3679
3680 // If the stack restore is in a return, resume, or unwind block and if there
3681 // are no allocas or calls between the restore and the return, nuke the
3682 // restore.
3683 if (!CannotRemove && (isa<ReturnInst>(Val: TI) || isa<ResumeInst>(Val: TI)))
3684 return eraseInstFromFunction(I&: CI);
3685 break;
3686 }
3687 case Intrinsic::lifetime_end:
3688 // Asan needs to poison memory to detect invalid access which is possible
3689 // even for empty lifetime range.
3690 if (II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeAddress) ||
3691 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeMemory) ||
3692 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeHWAddress) ||
3693 II->getFunction()->hasFnAttribute(Kind: Attribute::SanitizeMemTag))
3694 break;
3695
3696 if (removeTriviallyEmptyRange(EndI&: *II, IC&: *this, IsStart: [](const IntrinsicInst &I) {
3697 return I.getIntrinsicID() == Intrinsic::lifetime_start;
3698 }))
3699 return nullptr;
3700 break;
3701 case Intrinsic::assume: {
3702 for (auto [Idx, OBU] : llvm::enumerate(First: II->operand_bundles())) {
3703 auto RemoveBundle = [&, Idx = Idx]() -> Instruction * {
3704 if (II->getNumOperandBundles() == 1)
3705 return eraseInstFromFunction(I&: *II);
3706 return CallBase::removeOperandBundleAt(CB: II, Offset: Idx);
3707 };
3708
3709 switch (getBundleAttrFromOBU(OBU)) {
3710 case BundleAttr::None:
3711 llvm_unreachable("Unexpected Attribute");
3712 case BundleAttr::Align: {
3713 // Try to remove redundant alignment assumptions.
3714 auto [Ptr, _, OffsetPtr, Alignment, Offset] = getAssumeAlignInfo(OBU);
3715
3716 if (!Alignment)
3717 break;
3718
3719 // Remove align 1 and non-power-of-two bundles; they don't add any
3720 // useful information.
3721 if (*Alignment == 1 || !isPowerOf2_64(Value: *Alignment))
3722 return RemoveBundle();
3723
3724 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr);
3725 GEP &&
3726 GEP->getMaxPreservedAlignment(DL: getDataLayout()) >= *Alignment) {
3727 Builder.CreateAlignmentAssumption(
3728 DL: getDataLayout(), PtrValue: GEP->getPointerOperand(), Alignment: *Alignment,
3729 OffsetValue: OffsetPtr ? const_cast<Value *>(OffsetPtr->get()) : nullptr);
3730 return RemoveBundle();
3731 }
3732
3733 if (!Offset)
3734 break;
3735
3736 Value *BasePtr;
3737 const APInt *PtrOffset;
3738 if (match(V: Ptr.get(), P: m_PtrAdd(PointerOp: m_Value(V&: BasePtr), OffsetOp: m_APInt(Res&: PtrOffset)))) {
3739 auto PtrOffsetVal =
3740 PtrOffset->sextOrTrunc(width: DL.getIndexTypeSizeInBits(Ty: Ptr->getType()))
3741 .trySExtValue();
3742 if (!PtrOffsetVal)
3743 break;
3744 Builder.CreateAlignmentAssumption(
3745 DL, PtrValue: BasePtr, Alignment: *Alignment,
3746 OffsetValue: Builder.getInt64(C: *Offset - *PtrOffsetVal));
3747 return RemoveBundle();
3748 }
3749
3750 // Don't try to remove align assumptions for pointers derived from
3751 // arguments. We might lose information if the function gets inline and
3752 // the align argument attribute disappears.
3753 Value *UO = getUnderlyingObject(V: Ptr);
3754 if (!UO || isa<Argument>(Val: UO))
3755 break;
3756
3757 // Compute known bits for the pointer and drop the assume if the
3758 // known alignment isn't increased by it.
3759 auto AlignMask = (*Alignment - 1);
3760 if (KnownBits KB = computeKnownBits(V: Ptr, CxtI: II);
3761 (KB.Zero & AlignMask) == (~*Offset & AlignMask) &&
3762 (KB.One & AlignMask) == (*Offset & AlignMask))
3763 return RemoveBundle();
3764 break;
3765 }
3766
3767 case BundleAttr::Dereferenceable: {
3768 auto [Ptr, _, Count] = getAssumeDereferenceableInfo(OBU);
3769
3770 if (!Count)
3771 break;
3772
3773 if (*Count == 0 ||
3774 isDereferenceablePointer(V: Ptr, Size: APInt(64, *Count),
3775 Q: getSimplifyQuery().getWithInstruction(I: II)))
3776 return RemoveBundle();
3777
3778 break;
3779 }
3780
3781 case BundleAttr::Ignore:
3782 return RemoveBundle();
3783
3784 case BundleAttr::NonNull: {
3785 auto [Ptr] = llvm::getAssumeNonNullInfo(OBU);
3786
3787 // Drop assume if we can prove nonnull without it
3788 if (isKnownNonZero(V: Ptr, Q: getSimplifyQuery().getWithInstruction(I: II)))
3789 return RemoveBundle();
3790
3791 // Fold the assume into metadata if it's valid at the load
3792 if (auto *LI = dyn_cast<LoadInst>(Val: Ptr);
3793 LI &&
3794 isValidAssumeForContext(I: II, CxtI: LI, DT: &DT, /*AllowEphemerals=*/true)) {
3795 MDNode *MD = MDNode::get(Context&: II->getContext(), MDs: {});
3796 LI->setMetadata(KindID: LLVMContext::MD_nonnull, Node: MD);
3797 LI->setMetadata(KindID: LLVMContext::MD_noundef, Node: MD);
3798 return RemoveBundle();
3799 }
3800
3801 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr);
3802 GEP && GEP->isInBounds() &&
3803 !NullPointerIsDefined(F: II->getFunction(),
3804 AS: Ptr->getType()->getPointerAddressSpace())) {
3805 Builder.CreateNonnullAssumption(PtrValue: GEP->stripInBoundsOffsets());
3806 return RemoveBundle();
3807 }
3808
3809 // TODO: apply nonnull return attributes to calls and invokes
3810 break;
3811 }
3812
3813 case BundleAttr::NoUndef: {
3814 auto [Val] = getAssumeNoUndefInfo(OBU);
3815
3816 if (isGuaranteedNotToBeUndefOrPoison(V: Val, AC: &AC, CtxI: II, DT: &DT))
3817 return RemoveBundle();
3818
3819 if (auto *LI = dyn_cast<LoadInst>(Val);
3820 LI &&
3821 isValidAssumeForContext(I: II, CxtI: LI, DT: &DT, /*AllowEphemerals=*/true)) {
3822 LI->setMetadata(KindID: LLVMContext::MD_noundef,
3823 Node: MDNode::get(Context&: II->getContext(), MDs: {}));
3824 return RemoveBundle();
3825 }
3826
3827 } break;
3828
3829 case BundleAttr::SeparateStorage: {
3830 auto [Ptr1, Ptr2] = getAssumeSeparateStorageInfo(OBU);
3831 // Separate storage assumptions apply to the underlying allocations, not
3832 // any particular pointer within them. When evaluating the hints for AA
3833 // purposes we getUnderlyingObject them; by precomputing the answers
3834 // here we can avoid having to do so repeatedly there.
3835 auto MaybeSimplifyHint = [&](const Use &U) {
3836 Value *Hint = U.get();
3837 // Not having a limit is safe because InstCombine removes unreachable
3838 // code.
3839 Value *UnderlyingObject = getUnderlyingObject(V: Hint, /*MaxLookup*/ 0);
3840 if (Hint != UnderlyingObject)
3841 replaceUse(U&: const_cast<Use &>(U), NewValue: UnderlyingObject);
3842 };
3843 MaybeSimplifyHint(Ptr1);
3844 MaybeSimplifyHint(Ptr2);
3845 } break;
3846
3847 // TODO: Drop these assumes when they are redundant
3848 case BundleAttr::DereferenceableOrNull:
3849 break;
3850
3851 // This cannot be simplified
3852 case BundleAttr::Cold:
3853 break;
3854 }
3855 }
3856
3857 // If the assume has operand bundles, the folds below will never work, so
3858 // don't bother trying.
3859 if (II->hasOperandBundles())
3860 break;
3861
3862 Value *IIOperand = II->getArgOperand(i: 0);
3863
3864 // Canonicalize assume(a && b) -> assume(a); assume(b);
3865 // Note: New assumption intrinsics created here are registered by
3866 // the InstCombineIRInserter object.
3867 Value *A, *B;
3868 if (match(V: IIOperand, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3869 Builder.CreateAssumption(Cond: A);
3870 Builder.CreateAssumption(Cond: B);
3871 return eraseInstFromFunction(I&: *II);
3872 }
3873 // assume(!(a || b)) -> assume(!a); assume(!b);
3874 if (match(V: IIOperand, P: m_Not(V: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))))) {
3875 Builder.CreateAssumption(Cond: Builder.CreateNot(V: A));
3876 Builder.CreateAssumption(Cond: Builder.CreateNot(V: B));
3877 return eraseInstFromFunction(I&: *II);
3878 }
3879
3880 // Convert nonnull assume like:
3881 // %A = icmp ne i32* %PTR, null
3882 // call void @llvm.assume(i1 %A)
3883 // into
3884 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
3885 if (match(V: IIOperand,
3886 P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: m_Value(V&: A), R: m_Zero())) &&
3887 A->getType()->isPointerTy()) {
3888 Builder.CreateNonnullAssumption(PtrValue: A);
3889 return eraseInstFromFunction(I&: *II);
3890 }
3891
3892 // Convert alignment assume like:
3893 // %B = ptrtoint i32* %A to i64
3894 // %C = and i64 %B, Constant
3895 // %D = icmp eq i64 %C, 0
3896 // call void @llvm.assume(i1 %D)
3897 // into
3898 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
3899 uint64_t AlignMask = 1;
3900 if ((match(V: IIOperand, P: m_Not(V: m_Trunc(Op: m_Value(V&: A)))) ||
3901 match(V: IIOperand,
3902 P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
3903 L: m_And(L: m_Value(V&: A), R: m_ConstantInt(V&: AlignMask)),
3904 R: m_Zero())))) {
3905 if (isPowerOf2_64(Value: AlignMask + 1)) {
3906 uint64_t Offset = 0;
3907 match(V: A, P: m_Add(L: m_Value(V&: A), R: m_ConstantInt(V&: Offset)));
3908 if (match(V: A, P: m_PtrToIntOrAddr(Op: m_Value(V&: A)))) {
3909 /// Note: this doesn't preserve the offset information but merges
3910 /// offset and alignment.
3911 /// TODO: we can generate a GEP instead of merging the alignment with
3912 /// the offset.
3913 Builder.CreateAlignmentAssumption(DL: getDataLayout(), PtrValue: A,
3914 Alignment: MinAlign(A: Offset, B: AlignMask + 1));
3915 return eraseInstFromFunction(I&: *II);
3916 }
3917 }
3918 }
3919
3920 // Remove assumes on true/false
3921 if (auto *CI = dyn_cast<ConstantInt>(Val: IIOperand);
3922 CI || isa<UndefValue, PoisonValue>(Val: IIOperand)) {
3923 if (!CI || CI->isZero())
3924 CreateNonTerminatorUnreachable(InsertAt: II);
3925 return eraseInstFromFunction(I&: *II);
3926 }
3927
3928 // Update the cache of affected values for this assumption (we might be
3929 // here because we just simplified the condition).
3930 AC.updateAffectedValues(CI: cast<AssumeInst>(Val: II));
3931 break;
3932 }
3933 case Intrinsic::experimental_guard: {
3934 // Is this guard followed by another guard? We scan forward over a small
3935 // fixed window of instructions to handle common cases with conditions
3936 // computed between guards.
3937 Instruction *NextInst = II->getNextNode();
3938 for (unsigned i = 0; i < GuardWideningWindow; i++) {
3939 // Note: Using context-free form to avoid compile time blow up
3940 if (!isSafeToSpeculativelyExecute(I: NextInst))
3941 break;
3942 NextInst = NextInst->getNextNode();
3943 }
3944 Value *NextCond = nullptr;
3945 if (match(V: NextInst,
3946 P: m_Intrinsic<Intrinsic::experimental_guard>(Op0: m_Value(V&: NextCond)))) {
3947 Value *CurrCond = II->getArgOperand(i: 0);
3948
3949 // Remove a guard that it is immediately preceded by an identical guard.
3950 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3951 if (CurrCond != NextCond) {
3952 Instruction *MoveI = II->getNextNode();
3953 while (MoveI != NextInst) {
3954 auto *Temp = MoveI;
3955 MoveI = MoveI->getNextNode();
3956 Temp->moveBefore(InsertPos: II->getIterator());
3957 }
3958 replaceOperand(I&: *II, OpNum: 0, V: Builder.CreateAnd(LHS: CurrCond, RHS: NextCond));
3959 }
3960 eraseInstFromFunction(I&: *NextInst);
3961 return II;
3962 }
3963 break;
3964 }
3965 case Intrinsic::vector_insert: {
3966 Value *Vec = II->getArgOperand(i: 0);
3967 Value *SubVec = II->getArgOperand(i: 1);
3968 Value *Idx = II->getArgOperand(i: 2);
3969 auto *DstTy = dyn_cast<FixedVectorType>(Val: II->getType());
3970 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
3971 auto *SubVecTy = dyn_cast<FixedVectorType>(Val: SubVec->getType());
3972
3973 // Only canonicalize if the destination vector, Vec, and SubVec are all
3974 // fixed vectors.
3975 if (DstTy && VecTy && SubVecTy) {
3976 unsigned DstNumElts = DstTy->getNumElements();
3977 unsigned VecNumElts = VecTy->getNumElements();
3978 unsigned SubVecNumElts = SubVecTy->getNumElements();
3979 unsigned IdxN = cast<ConstantInt>(Val: Idx)->getZExtValue();
3980
3981 // An insert that entirely overwrites Vec with SubVec is a nop.
3982 if (VecNumElts == SubVecNumElts)
3983 return replaceInstUsesWith(I&: CI, V: SubVec);
3984
3985 // Widen SubVec into a vector of the same width as Vec, since
3986 // shufflevector requires the two input vectors to be the same width.
3987 // Elements beyond the bounds of SubVec within the widened vector are
3988 // undefined.
3989 SmallVector<int, 8> WidenMask;
3990 unsigned i;
3991 for (i = 0; i != SubVecNumElts; ++i)
3992 WidenMask.push_back(Elt: i);
3993 for (; i != VecNumElts; ++i)
3994 WidenMask.push_back(Elt: PoisonMaskElem);
3995
3996 Value *WidenShuffle = Builder.CreateShuffleVector(V: SubVec, Mask: WidenMask);
3997
3998 SmallVector<int, 8> Mask;
3999 for (unsigned i = 0; i != IdxN; ++i)
4000 Mask.push_back(Elt: i);
4001 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
4002 Mask.push_back(Elt: i);
4003 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
4004 Mask.push_back(Elt: i);
4005
4006 Value *Shuffle = Builder.CreateShuffleVector(V1: Vec, V2: WidenShuffle, Mask);
4007 return replaceInstUsesWith(I&: CI, V: Shuffle);
4008 }
4009 break;
4010 }
4011 case Intrinsic::vector_extract: {
4012 Value *Vec = II->getArgOperand(i: 0);
4013 Value *Idx = II->getArgOperand(i: 1);
4014
4015 Type *ReturnType = II->getType();
4016 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
4017 // ExtractIdx)
4018 unsigned ExtractIdx = cast<ConstantInt>(Val: Idx)->getZExtValue();
4019 Value *InsertTuple, *InsertIdx, *InsertValue;
4020 if (match(V: Vec, P: m_Intrinsic<Intrinsic::vector_insert>(Op0: m_Value(V&: InsertTuple),
4021 Op1: m_Value(V&: InsertValue),
4022 Op2: m_Value(V&: InsertIdx))) &&
4023 InsertValue->getType() == ReturnType) {
4024 unsigned Index = cast<ConstantInt>(Val: InsertIdx)->getZExtValue();
4025 // Case where we get the same index right after setting it.
4026 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
4027 // InsertValue
4028 if (ExtractIdx == Index)
4029 return replaceInstUsesWith(I&: CI, V: InsertValue);
4030 // If we are getting a different index than what was set in the
4031 // insert.vector intrinsic. We can just set the input tuple to the one up
4032 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
4033 // InsertIndex), ExtractIndex)
4034 // --> extract.vector(InsertTuple, ExtractIndex)
4035 else
4036 return replaceOperand(I&: CI, OpNum: 0, V: InsertTuple);
4037 }
4038
4039 ConstantInt *ALMUpperBound;
4040 if (match(V: Vec, P: m_Intrinsic<Intrinsic::get_active_lane_mask>(
4041 Op0: m_Value(), Op1: m_ConstantInt(CI&: ALMUpperBound)))) {
4042 const auto &Attrs = II->getFunction()->getAttributes().getFnAttrs();
4043 unsigned VScaleMin = Attrs.getVScaleRangeMin();
4044 unsigned ScaleFactor =
4045 cast<VectorType>(Val: ReturnType)->isScalableTy() ? VScaleMin : 1;
4046 if (ExtractIdx * ScaleFactor >= ALMUpperBound->getZExtValue())
4047 return replaceInstUsesWith(I&: CI,
4048 V: ConstantVector::getNullValue(Ty: ReturnType));
4049 }
4050
4051 auto *DstTy = dyn_cast<VectorType>(Val: ReturnType);
4052 auto *VecTy = dyn_cast<VectorType>(Val: Vec->getType());
4053
4054 if (DstTy && VecTy) {
4055 auto DstEltCnt = DstTy->getElementCount();
4056 auto VecEltCnt = VecTy->getElementCount();
4057 unsigned IdxN = cast<ConstantInt>(Val: Idx)->getZExtValue();
4058
4059 // Extracting the entirety of Vec is a nop.
4060 if (DstEltCnt == VecTy->getElementCount()) {
4061 replaceInstUsesWith(I&: CI, V: Vec);
4062 return eraseInstFromFunction(I&: CI);
4063 }
4064
4065 // Only canonicalize to shufflevector if the destination vector and
4066 // Vec are fixed vectors.
4067 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
4068 break;
4069
4070 SmallVector<int, 8> Mask;
4071 for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
4072 Mask.push_back(Elt: IdxN + i);
4073
4074 Value *Shuffle = Builder.CreateShuffleVector(V: Vec, Mask);
4075 return replaceInstUsesWith(I&: CI, V: Shuffle);
4076 }
4077 break;
4078 }
4079 case Intrinsic::experimental_vp_reverse: {
4080 Value *X;
4081 Value *Vec = II->getArgOperand(i: 0);
4082 Value *Mask = II->getArgOperand(i: 1);
4083 if (!match(V: Mask, P: m_AllOnes()))
4084 break;
4085 Value *EVL = II->getArgOperand(i: 2);
4086 // TODO: Canonicalize experimental.vp.reverse after unop/binops?
4087 // rev(unop rev(X)) --> unop X
4088 if (match(V: Vec,
4089 P: m_OneUse(SubPattern: m_UnOp(X: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
4090 Op0: m_Value(V&: X), Op1: m_AllOnes(), Op2: m_Specific(V: EVL)))))) {
4091 auto *OldUnOp = cast<UnaryOperator>(Val: Vec);
4092 auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(
4093 Opc: OldUnOp->getOpcode(), V: X, CopyO: OldUnOp, Name: OldUnOp->getName(),
4094 InsertBefore: II->getIterator());
4095 return replaceInstUsesWith(I&: CI, V: NewUnOp);
4096 }
4097 break;
4098 }
4099 case Intrinsic::vector_reduce_or:
4100 case Intrinsic::vector_reduce_and: {
4101 // Canonicalize logical or/and reductions:
4102 // Or reduction for i1 is represented as:
4103 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
4104 // %res = cmp ne iReduxWidth %val, 0
4105 // And reduction for i1 is represented as:
4106 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
4107 // %res = cmp eq iReduxWidth %val, 11111
4108 Value *Arg = II->getArgOperand(i: 0);
4109 Value *Vect;
4110
4111 if (Value *NewOp =
4112 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4113 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4114 return II;
4115 }
4116
4117 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4118 if (auto *FTy = dyn_cast<FixedVectorType>(Val: Vect->getType()))
4119 if (FTy->getElementType() == Builder.getInt1Ty()) {
4120 Value *Res = Builder.CreateBitCast(
4121 V: Vect, DestTy: Builder.getIntNTy(N: FTy->getNumElements()));
4122 if (IID == Intrinsic::vector_reduce_and) {
4123 Res = Builder.CreateICmpEQ(
4124 LHS: Res, RHS: ConstantInt::getAllOnesValue(Ty: Res->getType()));
4125 } else {
4126 assert(IID == Intrinsic::vector_reduce_or &&
4127 "Expected or reduction.");
4128 Res = Builder.CreateIsNotNull(Arg: Res);
4129 }
4130 if (Arg != Vect)
4131 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4132 DestTy: II->getType());
4133 return replaceInstUsesWith(I&: CI, V: Res);
4134 }
4135 }
4136 [[fallthrough]];
4137 }
4138 case Intrinsic::vector_reduce_add: {
4139 if (IID == Intrinsic::vector_reduce_add) {
4140 // Convert vector_reduce_add(ZExt(<n x i1>)) to
4141 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
4142 // Convert vector_reduce_add(SExt(<n x i1>)) to
4143 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
4144 // Convert vector_reduce_add(<n x i1>) to
4145 // Trunc(ctpop(bitcast <n x i1> to in)).
4146 Value *Arg = II->getArgOperand(i: 0);
4147 Value *Vect;
4148
4149 if (Value *NewOp =
4150 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4151 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4152 return II;
4153 }
4154
4155 // vector.reduce.add.vNiM(splat(%x)) -> mul(%x, N)
4156 if (Value *Splat = getSplatValue(V: Arg)) {
4157 ElementCount VecToReduceCount =
4158 cast<VectorType>(Val: Arg->getType())->getElementCount();
4159 if (VecToReduceCount.isFixed()) {
4160 unsigned VectorSize = VecToReduceCount.getFixedValue();
4161 return BinaryOperator::CreateMul(
4162 V1: Splat,
4163 V2: ConstantInt::get(Ty: Splat->getType(), V: VectorSize, /*IsSigned=*/false,
4164 /*ImplicitTrunc=*/true));
4165 }
4166 }
4167
4168 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4169 if (auto *FTy = dyn_cast<FixedVectorType>(Val: Vect->getType()))
4170 if (FTy->getElementType() == Builder.getInt1Ty()) {
4171 Value *V = Builder.CreateBitCast(
4172 V: Vect, DestTy: Builder.getIntNTy(N: FTy->getNumElements()));
4173 Value *Res = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: V);
4174 Res = Builder.CreateZExtOrTrunc(V: Res, DestTy: II->getType());
4175 if (Arg != Vect &&
4176 cast<Instruction>(Val: Arg)->getOpcode() == Instruction::SExt)
4177 Res = Builder.CreateNeg(V: Res);
4178 return replaceInstUsesWith(I&: CI, V: Res);
4179 }
4180 }
4181 }
4182 [[fallthrough]];
4183 }
4184 case Intrinsic::vector_reduce_xor: {
4185 if (IID == Intrinsic::vector_reduce_xor) {
4186 // Exclusive disjunction reduction over the vector with
4187 // (potentially-extended) i1 element type is actually a
4188 // (potentially-extended) arithmetic `add` reduction over the original
4189 // non-extended value:
4190 // vector_reduce_xor(?ext(<n x i1>))
4191 // -->
4192 // ?ext(vector_reduce_add(<n x i1>))
4193 Value *Arg = II->getArgOperand(i: 0);
4194 Value *Vect;
4195
4196 if (Value *NewOp =
4197 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4198 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4199 return II;
4200 }
4201
4202 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4203 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4204 if (VTy->getElementType() == Builder.getInt1Ty()) {
4205 Value *Res = Builder.CreateAddReduce(Src: Vect);
4206 if (Arg != Vect)
4207 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4208 DestTy: II->getType());
4209 return replaceInstUsesWith(I&: CI, V: Res);
4210 }
4211 }
4212 }
4213 [[fallthrough]];
4214 }
4215 case Intrinsic::vector_reduce_mul: {
4216 if (IID == Intrinsic::vector_reduce_mul) {
4217 Value *Arg = II->getArgOperand(i: 0);
4218
4219 if (Value *NewOp =
4220 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4221 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4222 return II;
4223 }
4224
4225 // vector_reduce_mul(zext(<n x i1>)), or
4226 // vector_reduce_mul(sext(<n x i1>)) (if n is even) -->
4227 // zext(vector_reduce_and(<n x i1>)).
4228 // (The sext case doesn't work if n is odd because multiplying an odd
4229 // number of -1's produces -1, not 1.)
4230 Value *Vect;
4231 bool IsZext = match(V: Arg, P: m_ZExt(Op: m_Value(V&: Vect))) &&
4232 Vect->getType()->isIntOrIntVectorTy(BitWidth: 1);
4233 bool IsSext =
4234 match(V: Arg, P: m_SExt(Op: m_Value(V&: Vect))) &&
4235 Vect->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
4236 cast<VectorType>(Val: Vect->getType())->getElementCount().isKnownEven();
4237 if (IsZext || IsSext) {
4238 Value *Res = Builder.CreateAndReduce(Src: Vect);
4239 return CastInst::Create(Instruction::ZExt, S: Res, Ty: II->getType());
4240 }
4241
4242 // vector_reduce_mul(<n x i1>) --> vector_reduce_and(<n x i1>)
4243 if (Arg->getType()->isIntOrIntVectorTy(BitWidth: 1))
4244 return replaceInstUsesWith(I&: CI, V: Builder.CreateAndReduce(Src: Arg));
4245 }
4246 [[fallthrough]];
4247 }
4248 case Intrinsic::vector_reduce_umin:
4249 case Intrinsic::vector_reduce_umax: {
4250 if (IID == Intrinsic::vector_reduce_umin ||
4251 IID == Intrinsic::vector_reduce_umax) {
4252 // UMin/UMax reduction over the vector with (potentially-extended)
4253 // i1 element type is actually a (potentially-extended)
4254 // logical `and`/`or` reduction over the original non-extended value:
4255 // vector_reduce_u{min,max}(?ext(<n x i1>))
4256 // -->
4257 // ?ext(vector_reduce_{and,or}(<n x i1>))
4258 Value *Arg = II->getArgOperand(i: 0);
4259 Value *Vect;
4260
4261 if (Value *NewOp =
4262 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4263 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4264 return II;
4265 }
4266
4267 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4268 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4269 if (VTy->getElementType() == Builder.getInt1Ty()) {
4270 Value *Res = IID == Intrinsic::vector_reduce_umin
4271 ? Builder.CreateAndReduce(Src: Vect)
4272 : Builder.CreateOrReduce(Src: Vect);
4273 if (Arg != Vect)
4274 Res = Builder.CreateCast(Op: cast<CastInst>(Val: Arg)->getOpcode(), V: Res,
4275 DestTy: II->getType());
4276 return replaceInstUsesWith(I&: CI, V: Res);
4277 }
4278 }
4279 }
4280 [[fallthrough]];
4281 }
4282 case Intrinsic::vector_reduce_smin:
4283 case Intrinsic::vector_reduce_smax: {
4284 if (IID == Intrinsic::vector_reduce_smin ||
4285 IID == Intrinsic::vector_reduce_smax) {
4286 // SMin/SMax reduction over the vector with (potentially-extended)
4287 // i1 element type is actually a (potentially-extended)
4288 // logical `and`/`or` reduction over the original non-extended value:
4289 // vector_reduce_s{min,max}(<n x i1>)
4290 // -->
4291 // vector_reduce_{or,and}(<n x i1>)
4292 // and
4293 // vector_reduce_s{min,max}(sext(<n x i1>))
4294 // -->
4295 // sext(vector_reduce_{or,and}(<n x i1>))
4296 // and
4297 // vector_reduce_s{min,max}(zext(<n x i1>))
4298 // -->
4299 // zext(vector_reduce_{and,or}(<n x i1>))
4300 Value *Arg = II->getArgOperand(i: 0);
4301 Value *Vect;
4302
4303 if (Value *NewOp =
4304 simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {
4305 replaceUse(U&: II->getOperandUse(i: 0), NewValue: NewOp);
4306 return II;
4307 }
4308
4309 if (match(V: Arg, P: m_ZExtOrSExtOrSelf(Op: m_Value(V&: Vect)))) {
4310 if (auto *VTy = dyn_cast<VectorType>(Val: Vect->getType()))
4311 if (VTy->getElementType() == Builder.getInt1Ty()) {
4312 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
4313 if (Arg != Vect)
4314 ExtOpc = cast<CastInst>(Val: Arg)->getOpcode();
4315 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
4316 (ExtOpc == Instruction::CastOps::ZExt))
4317 ? Builder.CreateAndReduce(Src: Vect)
4318 : Builder.CreateOrReduce(Src: Vect);
4319 if (Arg != Vect)
4320 Res = Builder.CreateCast(Op: ExtOpc, V: Res, DestTy: II->getType());
4321 return replaceInstUsesWith(I&: CI, V: Res);
4322 }
4323 }
4324 }
4325 [[fallthrough]];
4326 }
4327 case Intrinsic::vector_reduce_fmax:
4328 case Intrinsic::vector_reduce_fmin:
4329 case Intrinsic::vector_reduce_fadd:
4330 case Intrinsic::vector_reduce_fmul: {
4331 bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&
4332 IID != Intrinsic::vector_reduce_fmul) ||
4333 II->hasAllowReassoc();
4334 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
4335 IID == Intrinsic::vector_reduce_fmul)
4336 ? 1
4337 : 0;
4338 Value *Arg = II->getArgOperand(i: ArgIdx);
4339 if (Value *NewOp = simplifyReductionOperand(Arg, CanReorderLanes)) {
4340 replaceUse(U&: II->getOperandUse(i: ArgIdx), NewValue: NewOp);
4341 return nullptr;
4342 }
4343 break;
4344 }
4345 case Intrinsic::is_fpclass: {
4346 if (Instruction *I = foldIntrinsicIsFPClass(II&: *II))
4347 return I;
4348 break;
4349 }
4350 case Intrinsic::threadlocal_address: {
4351 Align MinAlign = getKnownAlignment(V: II->getArgOperand(i: 0), DL, CxtI: II, AC: &AC, DT: &DT);
4352 MaybeAlign Align = II->getRetAlign();
4353 if (MinAlign > Align.valueOrOne()) {
4354 II->addRetAttr(Attr: Attribute::getWithAlignment(Context&: II->getContext(), Alignment: MinAlign));
4355 return II;
4356 }
4357 break;
4358 }
4359 case Intrinsic::fptoui_sat:
4360 case Intrinsic::fptosi_sat:
4361 if (Instruction *I = foldItoFPtoI(FI&: *II))
4362 return I;
4363 break;
4364 case Intrinsic::frexp: {
4365 // frexp(frexp(x).fract) -> { frexp(x).fract, 0 }: the fraction operand is
4366 // already normalized, so the first result is idempotent and the second is
4367 // zero.
4368 if (match(V: II->getArgOperand(i: 0),
4369 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::frexp>(Op0: m_Value())))) {
4370 Value *Res = Builder.CreateInsertValue(Agg: PoisonValue::get(T: II->getType()),
4371 Val: II->getArgOperand(i: 0), Idxs: 0);
4372 Res = Builder.CreateInsertValue(
4373 Agg: Res, Val: Constant::getNullValue(Ty: II->getType()->getStructElementType(N: 1)),
4374 Idxs: 1);
4375 return replaceInstUsesWith(I&: *II, V: Res);
4376 }
4377 break;
4378 }
4379 case Intrinsic::get_active_lane_mask: {
4380 const APInt *Op0, *Op1;
4381 if (match(V: II->getOperand(i_nocapture: 0), P: m_StrictlyPositive(V&: Op0)) &&
4382 match(V: II->getOperand(i_nocapture: 1), P: m_APInt(Res&: Op1))) {
4383 Type *OpTy = II->getOperand(i_nocapture: 0)->getType();
4384 return replaceInstUsesWith(
4385 I&: *II, V: Builder.CreateIntrinsic(
4386 RetTy: II->getType(), ID: Intrinsic::get_active_lane_mask,
4387 Args: {Constant::getNullValue(Ty: OpTy),
4388 ConstantInt::get(Ty: OpTy, V: Op1->usub_sat(RHS: *Op0))}));
4389 }
4390 break;
4391 }
4392 case Intrinsic::experimental_get_vector_length: {
4393 // get.vector.length(Cnt, MaxLanes) --> Cnt when Cnt <= MaxLanes
4394 unsigned BitWidth =
4395 std::max(a: II->getArgOperand(i: 0)->getType()->getScalarSizeInBits(),
4396 b: II->getType()->getScalarSizeInBits());
4397 ConstantRange Cnt =
4398 computeConstantRangeIncludingKnownBits(V: II->getArgOperand(i: 0), ForSigned: false,
4399 SQ: SQ.getWithInstruction(I: II))
4400 .zextOrTrunc(BitWidth);
4401 ConstantRange MaxLanes = cast<ConstantInt>(Val: II->getArgOperand(i: 1))
4402 ->getValue()
4403 .zextOrTrunc(width: Cnt.getBitWidth());
4404 if (cast<ConstantInt>(Val: II->getArgOperand(i: 2))->isOne())
4405 MaxLanes = MaxLanes.multiply(
4406 Other: getVScaleRange(F: II->getFunction(), BitWidth: Cnt.getBitWidth()));
4407
4408 if (Cnt.icmp(Pred: CmpInst::ICMP_ULE, Other: MaxLanes))
4409 return replaceInstUsesWith(
4410 I&: *II, V: Builder.CreateZExtOrTrunc(V: II->getArgOperand(i: 0), DestTy: II->getType()));
4411 return nullptr;
4412 }
4413 default: {
4414 // Handle target specific intrinsics
4415 std::optional<Instruction *> V = targetInstCombineIntrinsic(II&: *II);
4416 if (V)
4417 return *V;
4418 break;
4419 }
4420 }
4421
4422 // Try to fold intrinsic into select/phi operands. This is legal if:
4423 // * The intrinsic is speculatable.
4424 // * The operand is one of the following:
4425 // - a phi.
4426 // - a select with a scalar condition.
4427 // - a select with a vector condition and II is not a cross lane operation.
4428 if (isSafeToSpeculativelyExecuteWithVariableReplaced(I: &CI)) {
4429 for (Value *Op : II->args()) {
4430 if (auto *Sel = dyn_cast<SelectInst>(Val: Op)) {
4431 bool IsVectorCond = Sel->getCondition()->getType()->isVectorTy();
4432 if (IsVectorCond &&
4433 (!isNotCrossLaneOperation(I: II) || !II->getType()->isVectorTy()))
4434 continue;
4435 // Don't replace a scalar select with a more expensive vector select if
4436 // we can't simplify both arms of the select.
4437 bool SimplifyBothArms =
4438 !Op->getType()->isVectorTy() && II->getType()->isVectorTy();
4439 if (Instruction *R = FoldOpIntoSelect(
4440 Op&: *II, SI: Sel, /*FoldWithMultiUse=*/false, SimplifyBothArms))
4441 return R;
4442 }
4443 if (auto *Phi = dyn_cast<PHINode>(Val: Op))
4444 if (Instruction *R = foldOpIntoPhi(I&: *II, PN: Phi))
4445 return R;
4446 }
4447 }
4448
4449 if (Instruction *Shuf = foldShuffledIntrinsicOperands(II))
4450 return Shuf;
4451
4452 if (Value *Reverse = foldReversedIntrinsicOperands(II))
4453 return replaceInstUsesWith(I&: *II, V: Reverse);
4454
4455 if (Value *Res = foldIdempotentBinaryIntrinsicRecurrence(IC&: *this, II))
4456 return replaceInstUsesWith(I&: *II, V: Res);
4457
4458 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
4459 // context, so it is handled in visitCallBase and we should trigger it.
4460 return visitCallBase(Call&: *II);
4461}
4462
4463// Fence instruction simplification
4464Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {
4465 auto *NFI = dyn_cast<FenceInst>(Val: FI.getNextNode());
4466 // This check is solely here to handle arbitrary target-dependent syncscopes.
4467 // TODO: Can remove if does not matter in practice.
4468 if (NFI && FI.isIdenticalTo(I: NFI))
4469 return eraseInstFromFunction(I&: FI);
4470
4471 // Returns true if FI1 is identical or stronger fence than FI2.
4472 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
4473 auto FI1SyncScope = FI1->getSyncScopeID();
4474 // Consider same scope, where scope is global or single-thread.
4475 if (FI1SyncScope != FI2->getSyncScopeID() ||
4476 (FI1SyncScope != SyncScope::System &&
4477 FI1SyncScope != SyncScope::SingleThread))
4478 return false;
4479
4480 return isAtLeastOrStrongerThan(AO: FI1->getOrdering(), Other: FI2->getOrdering());
4481 };
4482 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
4483 return eraseInstFromFunction(I&: FI);
4484
4485 if (auto *PFI = dyn_cast_or_null<FenceInst>(Val: FI.getPrevNode()))
4486 if (isIdenticalOrStrongerFence(PFI, &FI))
4487 return eraseInstFromFunction(I&: FI);
4488 return nullptr;
4489}
4490
4491// InvokeInst simplification
4492Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {
4493 return visitCallBase(Call&: II);
4494}
4495
4496// CallBrInst simplification
4497Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
4498 return visitCallBase(Call&: CBI);
4499}
4500
4501// A simple parser for format string specifiers for the purposes of the
4502// modular-format attribute. In the case of malformed format strings this might
4503// under or over report the specifiers present, but such cases are undefined
4504// behavior.
4505static Bitset<256> parseFormatStringSpecifiers(StringRef FormatStr) {
4506 Bitset<256> Specifiers;
4507 for (size_t I = 0; I < FormatStr.size(); ++I) {
4508 if (FormatStr[I] != '%')
4509 continue;
4510
4511 // Check for escaped '%'.
4512 if (I + 1 < FormatStr.size() && FormatStr[I + 1] == '%') {
4513 ++I; // Skip the second '%'.
4514 continue;
4515 }
4516
4517 // Scan past allowed prefix characters.
4518 size_t J =
4519 FormatStr.find_first_not_of(Chars: "0123456789-+ #0$.*'hlLjztqwvI", From: I + 1);
4520 if (J == StringRef::npos)
4521 break;
4522
4523 Specifiers.set(static_cast<unsigned char>(FormatStr[J]));
4524 I = J; // Resume search from after the specifier.
4525 }
4526 return Specifiers;
4527}
4528
4529static bool isAspectNeeded(StringRef Aspect, CallInst *CI,
4530 std::optional<unsigned> FirstArgIdx,
4531 const std::optional<Bitset<256>> &Specifiers) {
4532 if (Aspect == "float") {
4533 if (Specifiers) {
4534 static constexpr Bitset<256> FloatSpecifiers{'f', 'F', 'e', 'E',
4535 'g', 'G', 'a', 'A'};
4536 return (*Specifiers & FloatSpecifiers).any();
4537 }
4538 // Fallback to type-based check for dynamic format string.
4539 if (!FirstArgIdx)
4540 return true;
4541 return llvm::any_of(
4542 Range: llvm::make_range(x: std::next(x: CI->arg_begin(), n: *FirstArgIdx),
4543 y: CI->arg_end()),
4544 P: [](Value *V) { return V->getType()->isFloatingPointTy(); });
4545 }
4546 if (Aspect == "fixed") {
4547 if (Specifiers) {
4548 static constexpr Bitset<256> FixedSpecifiers{'r', 'R', 'k', 'K'};
4549 return (*Specifiers & FixedSpecifiers).any();
4550 }
4551 // Fallback for fixed-point: assume needed if format is dynamic.
4552 return true;
4553 }
4554 // Unknown aspects are always considered to be needed.
4555 return true;
4556}
4557
4558static void referenceAspect(StringRef Aspect, StringRef ImplName, Module *M,
4559 IRBuilderBase &B) {
4560 SmallString<20> Name = ImplName;
4561 Name += '_';
4562 Name += Aspect;
4563 LLVMContext &Ctx = M->getContext();
4564 Function *RelocNoneFn =
4565 Intrinsic::getOrInsertDeclaration(M, id: Intrinsic::reloc_none);
4566 B.CreateCall(Callee: RelocNoneFn,
4567 Args: {MetadataAsValue::get(Context&: Ctx, MD: MDString::get(Context&: Ctx, Str: Name))});
4568}
4569
4570static Value *optimizeModularFormat(CallInst *CI, IRBuilderBase &B) {
4571 if (!CI->hasFnAttr(Kind: "modular-format"))
4572 return nullptr;
4573
4574 SmallVector<StringRef> Args(
4575 llvm::split(Str: CI->getFnAttr(Kind: "modular-format").getValueAsString(), Separator: ','));
4576 if (Args.size() < 5)
4577 return nullptr;
4578
4579 StringRef FormatIdxStr = Args[1];
4580 StringRef FirstArgIdxStr = Args[2];
4581 StringRef FnName = Args[3];
4582 StringRef ImplName = Args[4];
4583 ArrayRef<StringRef> AllAspects = ArrayRef<StringRef>(Args).drop_front(N: 5);
4584
4585 unsigned FormatIdx;
4586 std::optional<unsigned> FirstArgIdx;
4587 [[maybe_unused]] bool Error;
4588 Error = FormatIdxStr.getAsInteger(Radix: 10, Result&: FormatIdx);
4589 assert(!Error && "invalid format arg index");
4590 --FormatIdx; // 1-based to 0-based
4591
4592 FirstArgIdx.emplace();
4593 Error = FirstArgIdxStr.getAsInteger(Radix: 10, Result&: *FirstArgIdx);
4594 assert(!Error && "invalid first arg index");
4595 if (*FirstArgIdx > 0)
4596 --*FirstArgIdx; // 1-based to 0-based
4597 else
4598 FirstArgIdx.reset();
4599
4600 if (AllAspects.empty())
4601 return nullptr;
4602
4603 Value *FormatVal = CI->getArgOperand(i: FormatIdx);
4604 StringRef FormatStr;
4605
4606 std::optional<Bitset<256>> Specifiers;
4607 if (getConstantStringInfo(V: FormatVal, Str&: FormatStr))
4608 Specifiers = parseFormatStringSpecifiers(FormatStr);
4609
4610 SmallVector<StringRef> NeededAspects;
4611 for (StringRef Aspect : AllAspects)
4612 if (isAspectNeeded(Aspect, CI, FirstArgIdx, Specifiers))
4613 NeededAspects.push_back(Elt: Aspect);
4614
4615 if (NeededAspects.size() == AllAspects.size())
4616 return nullptr;
4617
4618 Module *M = CI->getModule();
4619 LLVMContext &Ctx = M->getContext();
4620 Function *Callee = CI->getCalledFunction();
4621 FunctionCallee ModularFn = M->getOrInsertFunction(
4622 Name: FnName, T: Callee->getFunctionType(),
4623 AttributeList: Callee->getAttributes().removeFnAttribute(C&: Ctx, Kind: "modular-format"));
4624 CallInst *New = cast<CallInst>(Val: CI->clone());
4625 New->setCalledFunction(ModularFn);
4626 New->removeFnAttr(Kind: "modular-format");
4627 B.Insert(I: New);
4628
4629 llvm::sort(C&: NeededAspects);
4630 for (StringRef Request : NeededAspects)
4631 referenceAspect(Aspect: Request, ImplName, M, B);
4632
4633 return New;
4634}
4635
4636Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
4637 if (!CI->getCalledFunction()) return nullptr;
4638
4639 // Skip optimizing notail and musttail calls so
4640 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
4641 // LibCallSimplifier::optimizeCall should try to preserve tail calls though.
4642 if (CI->isMustTailCall() || CI->isNoTailCall())
4643 return nullptr;
4644
4645 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
4646 replaceInstUsesWith(I&: *From, V: With);
4647 };
4648 auto InstCombineErase = [this](Instruction *I) {
4649 eraseInstFromFunction(I&: *I);
4650 };
4651 LibCallSimplifier Simplifier(DL, &TLI, &DT, &DC, &AC, ORE, BFI, PSI,
4652 InstCombineRAUW, InstCombineErase);
4653 if (Value *With = Simplifier.optimizeCall(CI, B&: Builder)) {
4654 ++NumSimplified;
4655 return CI->use_empty() ? CI : replaceInstUsesWith(I&: *CI, V: With);
4656 }
4657 if (Value *With = optimizeModularFormat(CI, B&: Builder)) {
4658 ++NumSimplified;
4659 return CI->use_empty() ? CI : replaceInstUsesWith(I&: *CI, V: With);
4660 }
4661
4662 return nullptr;
4663}
4664
4665static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
4666 // Strip off at most one level of pointer casts, looking for an alloca. This
4667 // is good enough in practice and simpler than handling any number of casts.
4668 Value *Underlying = TrampMem->stripPointerCasts();
4669 if (Underlying != TrampMem &&
4670 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4671 return nullptr;
4672 if (!isa<AllocaInst>(Val: Underlying))
4673 return nullptr;
4674
4675 IntrinsicInst *InitTrampoline = nullptr;
4676 for (User *U : TrampMem->users()) {
4677 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: U);
4678 if (!II)
4679 return nullptr;
4680 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4681 if (InitTrampoline)
4682 // More than one init_trampoline writes to this value. Give up.
4683 return nullptr;
4684 InitTrampoline = II;
4685 continue;
4686 }
4687 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4688 // Allow any number of calls to adjust.trampoline.
4689 continue;
4690 return nullptr;
4691 }
4692
4693 // No call to init.trampoline found.
4694 if (!InitTrampoline)
4695 return nullptr;
4696
4697 // Check that the alloca is being used in the expected way.
4698 if (InitTrampoline->getOperand(i_nocapture: 0) != TrampMem)
4699 return nullptr;
4700
4701 return InitTrampoline;
4702}
4703
4704static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
4705 Value *TrampMem) {
4706 // Visit all the previous instructions in the basic block, and try to find a
4707 // init.trampoline which has a direct path to the adjust.trampoline.
4708 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4709 E = AdjustTramp->getParent()->begin();
4710 I != E;) {
4711 Instruction *Inst = &*--I;
4712 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val&: I))
4713 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4714 II->getOperand(i_nocapture: 0) == TrampMem)
4715 return II;
4716 if (Inst->mayWriteToMemory())
4717 return nullptr;
4718 }
4719 return nullptr;
4720}
4721
4722// Given a call to llvm.adjust.trampoline, find and return the corresponding
4723// call to llvm.init.trampoline if the call to the trampoline can be optimized
4724// to a direct call to a function. Otherwise return NULL.
4725static IntrinsicInst *findInitTrampoline(Value *Callee) {
4726 Callee = Callee->stripPointerCasts();
4727 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Val: Callee);
4728 if (!AdjustTramp ||
4729 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
4730 return nullptr;
4731
4732 Value *TrampMem = AdjustTramp->getOperand(i_nocapture: 0);
4733
4734 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
4735 return IT;
4736 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
4737 return IT;
4738 return nullptr;
4739}
4740
4741Instruction *InstCombinerImpl::foldPtrAuthIntrinsicCallee(CallBase &Call) {
4742 const Value *Callee = Call.getCalledOperand();
4743 const auto *IPC = dyn_cast<IntToPtrInst>(Val: Callee);
4744 if (!IPC || !IPC->isNoopCast(DL))
4745 return nullptr;
4746
4747 const auto *II = dyn_cast<IntrinsicInst>(Val: IPC->getOperand(i_nocapture: 0));
4748 if (!II)
4749 return nullptr;
4750
4751 Intrinsic::ID IIID = II->getIntrinsicID();
4752 if (IIID != Intrinsic::ptrauth_resign && IIID != Intrinsic::ptrauth_sign)
4753 return nullptr;
4754
4755 // Isolate the ptrauth bundle from the others.
4756 std::optional<OperandBundleUse> PtrAuthBundleOrNone;
4757 SmallVector<OperandBundleDef, 2> NewBundles;
4758 for (unsigned BI = 0, BE = Call.getNumOperandBundles(); BI != BE; ++BI) {
4759 OperandBundleUse Bundle = Call.getOperandBundleAt(Index: BI);
4760 if (Bundle.getTagID() == LLVMContext::OB_ptrauth)
4761 PtrAuthBundleOrNone = Bundle;
4762 else
4763 NewBundles.emplace_back(Args&: Bundle);
4764 }
4765
4766 if (!PtrAuthBundleOrNone)
4767 return nullptr;
4768
4769 Value *NewCallee = nullptr;
4770 switch (IIID) {
4771 // call(ptrauth.resign(p)), ["ptrauth"()] -> call p, ["ptrauth"()]
4772 // assuming the call bundle and the sign operands match.
4773 case Intrinsic::ptrauth_resign: {
4774 // Resign result key should match bundle.
4775 if (II->getOperand(i_nocapture: 3) != PtrAuthBundleOrNone->Inputs[0])
4776 return nullptr;
4777 // Resign result discriminator should match bundle.
4778 if (II->getOperand(i_nocapture: 4) != PtrAuthBundleOrNone->Inputs[1])
4779 return nullptr;
4780
4781 // Resign input (auth) key should also match: we can't change the key on
4782 // the new call we're generating, because we don't know what keys are valid.
4783 if (II->getOperand(i_nocapture: 1) != PtrAuthBundleOrNone->Inputs[0])
4784 return nullptr;
4785
4786 Value *NewBundleOps[] = {II->getOperand(i_nocapture: 1), II->getOperand(i_nocapture: 2)};
4787 NewBundles.emplace_back(Args: "ptrauth", Args&: NewBundleOps);
4788 NewCallee = II->getOperand(i_nocapture: 0);
4789 break;
4790 }
4791
4792 // call(ptrauth.sign(p)), ["ptrauth"()] -> call p
4793 // assuming the call bundle and the sign operands match.
4794 // Non-ptrauth indirect calls are undesirable, but so is ptrauth.sign.
4795 case Intrinsic::ptrauth_sign: {
4796 // Sign key should match bundle.
4797 if (II->getOperand(i_nocapture: 1) != PtrAuthBundleOrNone->Inputs[0])
4798 return nullptr;
4799 // Sign discriminator should match bundle.
4800 if (II->getOperand(i_nocapture: 2) != PtrAuthBundleOrNone->Inputs[1])
4801 return nullptr;
4802 NewCallee = II->getOperand(i_nocapture: 0);
4803 break;
4804 }
4805 default:
4806 llvm_unreachable("unexpected intrinsic ID");
4807 }
4808
4809 if (!NewCallee)
4810 return nullptr;
4811
4812 NewCallee = Builder.CreateBitOrPointerCast(V: NewCallee, DestTy: Callee->getType());
4813 CallBase *NewCall = CallBase::Create(CB: &Call, Bundles: NewBundles);
4814 NewCall->setCalledOperand(NewCallee);
4815 return NewCall;
4816}
4817
4818Instruction *InstCombinerImpl::foldPtrAuthConstantCallee(CallBase &Call) {
4819 auto *CPA = dyn_cast<ConstantPtrAuth>(Val: Call.getCalledOperand());
4820 if (!CPA)
4821 return nullptr;
4822
4823 auto *CalleeF = dyn_cast<Function>(Val: CPA->getPointer());
4824 // If the ptrauth constant isn't based on a function pointer, bail out.
4825 if (!CalleeF)
4826 return nullptr;
4827
4828 // Inspect the call ptrauth bundle to check it matches the ptrauth constant.
4829 auto PAB = Call.getOperandBundle(ID: LLVMContext::OB_ptrauth);
4830 if (!PAB)
4831 return nullptr;
4832
4833 auto *Key = cast<ConstantInt>(Val: PAB->Inputs[0]);
4834 Value *Discriminator = PAB->Inputs[1];
4835
4836 // If the bundle doesn't match, this is probably going to fail to auth.
4837 if (!CPA->isKnownCompatibleWith(Key, Discriminator, DL))
4838 return nullptr;
4839
4840 // If the bundle matches the constant, proceed in making this a direct call.
4841 auto *NewCall = CallBase::removeOperandBundle(CB: &Call, ID: LLVMContext::OB_ptrauth);
4842 NewCall->setCalledOperand(CalleeF);
4843 return NewCall;
4844}
4845
4846bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
4847 const TargetLibraryInfo *TLI) {
4848 // Note: We only handle cases which can't be driven from generic attributes
4849 // here. So, for example, nonnull and noalias (which are common properties
4850 // of some allocation functions) are expected to be handled via annotation
4851 // of the respective allocator declaration with generic attributes.
4852 bool Changed = false;
4853
4854 if (!Call.getType()->isPointerTy())
4855 return Changed;
4856
4857 std::optional<APInt> Size = getAllocSize(CB: &Call, TLI);
4858 if (Size && *Size != 0) {
4859 // TODO: We really should just emit deref_or_null here and then
4860 // let the generic inference code combine that with nonnull.
4861 if (Call.hasRetAttr(Kind: Attribute::NonNull)) {
4862 Changed = !Call.hasRetAttr(Kind: Attribute::Dereferenceable);
4863 Call.addRetAttr(Attr: Attribute::getWithDereferenceableBytes(
4864 Context&: Call.getContext(), Bytes: Size->getLimitedValue()));
4865 } else {
4866 Changed = !Call.hasRetAttr(Kind: Attribute::DereferenceableOrNull);
4867 Call.addRetAttr(Attr: Attribute::getWithDereferenceableOrNullBytes(
4868 Context&: Call.getContext(), Bytes: Size->getLimitedValue()));
4869 }
4870 }
4871
4872 // Add alignment attribute if alignment is a power of two constant.
4873 Value *Alignment = getAllocAlignment(V: &Call, TLI);
4874 if (!Alignment)
4875 return Changed;
4876
4877 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Val: Alignment);
4878 if (AlignOpC && AlignOpC->getValue().ult(RHS: llvm::Value::MaximumAlignment)) {
4879 uint64_t AlignmentVal = AlignOpC->getZExtValue();
4880 if (llvm::isPowerOf2_64(Value: AlignmentVal)) {
4881 Align ExistingAlign = Call.getRetAlign().valueOrOne();
4882 Align NewAlign = Align(AlignmentVal);
4883 if (NewAlign > ExistingAlign) {
4884 Call.addRetAttr(
4885 Attr: Attribute::getWithAlignment(Context&: Call.getContext(), Alignment: NewAlign));
4886 Changed = true;
4887 }
4888 }
4889 }
4890 return Changed;
4891}
4892
4893/// Improvements for call, callbr and invoke instructions.
4894Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
4895 bool Changed = annotateAnyAllocSite(Call, TLI: &TLI);
4896
4897 // Mark any parameters that are known to be non-null with the nonnull
4898 // attribute. This is helpful for inlining calls to functions with null
4899 // checks on their arguments.
4900 SmallVector<unsigned, 4> ArgNos;
4901 unsigned ArgNo = 0;
4902
4903 for (Value *V : Call.args()) {
4904 if (V->getType()->isPointerTy()) {
4905 // Simplify the nonnull operand if the parameter is known to be nonnull.
4906 // Otherwise, try to infer nonnull for it.
4907 bool HasDereferenceable = Call.getParamDereferenceableBytes(i: ArgNo) > 0;
4908 if (Call.paramHasAttr(ArgNo, Kind: Attribute::NonNull) ||
4909 (HasDereferenceable &&
4910 !NullPointerIsDefined(F: Call.getFunction(),
4911 AS: V->getType()->getPointerAddressSpace()))) {
4912 if (Value *Res = simplifyNonNullOperand(V, HasDereferenceable)) {
4913 replaceOperand(I&: Call, OpNum: ArgNo, V: Res);
4914 Changed = true;
4915 }
4916 } else if (isKnownNonZero(V,
4917 Q: getSimplifyQuery().getWithInstruction(I: &Call))) {
4918 ArgNos.push_back(Elt: ArgNo);
4919 }
4920 }
4921 ArgNo++;
4922 }
4923
4924 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
4925
4926 if (!ArgNos.empty()) {
4927 AttributeList AS = Call.getAttributes();
4928 LLVMContext &Ctx = Call.getContext();
4929 AS = AS.addParamAttribute(C&: Ctx, ArgNos,
4930 A: Attribute::get(Context&: Ctx, Kind: Attribute::NonNull));
4931 Call.setAttributes(AS);
4932 Changed = true;
4933 }
4934
4935 // If the callee is a pointer to a function, attempt to move any casts to the
4936 // arguments of the call/callbr/invoke.
4937 Value *Callee = Call.getCalledOperand();
4938 Function *CalleeF = dyn_cast<Function>(Val: Callee);
4939 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
4940 transformConstExprCastCall(Call))
4941 return nullptr;
4942
4943 if (CalleeF) {
4944 // Remove the convergent attr on calls when the callee is not convergent.
4945 if (Call.isConvergent() && !CalleeF->isConvergent() &&
4946 !CalleeF->isIntrinsic()) {
4947 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4948 << "\n");
4949 Call.setNotConvergent();
4950 return &Call;
4951 }
4952
4953 // If the call and callee calling conventions don't match, and neither one
4954 // of the calling conventions is compatible with C calling convention
4955 // this call must be unreachable, as the call is undefined.
4956 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
4957 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
4958 TargetLibraryInfoImpl::isCallingConvCCompatible(CI: &Call)) &&
4959 !(Call.getCallingConv() == llvm::CallingConv::C &&
4960 TargetLibraryInfoImpl::isCallingConvCCompatible(Callee: CalleeF))) &&
4961 // Only do this for calls to a function with a body. A prototype may
4962 // not actually end up matching the implementation's calling conv for a
4963 // variety of reasons (e.g. it may be written in assembly).
4964 !CalleeF->isDeclaration()) {
4965 Instruction *OldCall = &Call;
4966 CreateNonTerminatorUnreachable(InsertAt: OldCall);
4967 // If OldCall does not return void then replaceInstUsesWith poison.
4968 // This allows ValueHandlers and custom metadata to adjust itself.
4969 if (!OldCall->getType()->isVoidTy())
4970 replaceInstUsesWith(I&: *OldCall, V: PoisonValue::get(T: OldCall->getType()));
4971 if (isa<CallInst>(Val: OldCall))
4972 return eraseInstFromFunction(I&: *OldCall);
4973
4974 // We cannot remove an invoke or a callbr, because it would change thexi
4975 // CFG, just change the callee to a null pointer.
4976 cast<CallBase>(Val: OldCall)->setCalledFunction(
4977 FTy: CalleeF->getFunctionType(),
4978 Fn: Constant::getNullValue(Ty: CalleeF->getType()));
4979 return nullptr;
4980 }
4981 }
4982
4983 // Calling a null function pointer is undefined if a null address isn't
4984 // dereferenceable.
4985 if ((isa<ConstantPointerNull>(Val: Callee) &&
4986 !NullPointerIsDefined(F: Call.getFunction())) ||
4987 isa<UndefValue>(Val: Callee)) {
4988 // If Call does not return void then replaceInstUsesWith poison.
4989 // This allows ValueHandlers and custom metadata to adjust itself.
4990 if (!Call.getType()->isVoidTy())
4991 replaceInstUsesWith(I&: Call, V: PoisonValue::get(T: Call.getType()));
4992
4993 if (Call.isTerminator()) {
4994 // Can't remove an invoke or callbr because we cannot change the CFG.
4995 return nullptr;
4996 }
4997
4998 // This instruction is not reachable, just remove it.
4999 CreateNonTerminatorUnreachable(InsertAt: &Call);
5000 return eraseInstFromFunction(I&: Call);
5001 }
5002
5003 if (IntrinsicInst *II = findInitTrampoline(Callee))
5004 return transformCallThroughTrampoline(Call, Tramp&: *II);
5005
5006 // Combine calls involving pointer authentication intrinsics.
5007 if (Instruction *NewCall = foldPtrAuthIntrinsicCallee(Call))
5008 return NewCall;
5009
5010 // Combine calls to ptrauth constants.
5011 if (Instruction *NewCall = foldPtrAuthConstantCallee(Call))
5012 return NewCall;
5013
5014 if (isa<InlineAsm>(Val: Callee) && !Call.doesNotThrow()) {
5015 InlineAsm *IA = cast<InlineAsm>(Val: Callee);
5016 if (!IA->canThrow()) {
5017 // Normal inline asm calls cannot throw - mark them
5018 // 'nounwind'.
5019 Call.setDoesNotThrow();
5020 Changed = true;
5021 }
5022 }
5023
5024 // Try to optimize the call if possible, we require DataLayout for most of
5025 // this. None of these calls are seen as possibly dead so go ahead and
5026 // delete the instruction now.
5027 if (CallInst *CI = dyn_cast<CallInst>(Val: &Call)) {
5028 Instruction *I = tryOptimizeCall(CI);
5029 // If we changed something return the result, etc. Otherwise let
5030 // the fallthrough check.
5031 if (I) return eraseInstFromFunction(I&: *I);
5032 }
5033
5034 if (!Call.use_empty() && !Call.isMustTailCall())
5035 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
5036 Type *CallTy = Call.getType();
5037 Type *RetArgTy = ReturnedArg->getType();
5038 if (RetArgTy->canLosslesslyBitCastTo(Ty: CallTy))
5039 return replaceInstUsesWith(
5040 I&: Call, V: Builder.CreateBitOrPointerCast(V: ReturnedArg, DestTy: CallTy));
5041 }
5042
5043 // Drop unnecessary callee_type metadata from calls that were converted
5044 // into direct calls.
5045 if (Call.getMetadata(KindID: LLVMContext::MD_callee_type) && !Call.isIndirectCall()) {
5046 Call.setMetadata(KindID: LLVMContext::MD_callee_type, Node: nullptr);
5047 Changed = true;
5048 }
5049
5050 // Drop unnecessary kcfi operand bundles from calls that were converted
5051 // into direct calls.
5052 auto Bundle = Call.getOperandBundle(ID: LLVMContext::OB_kcfi);
5053 if (Bundle && !Call.isIndirectCall()) {
5054 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
5055 if (CalleeF) {
5056 ConstantInt *FunctionType = nullptr;
5057 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
5058
5059 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
5060 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
5061
5062 if (FunctionType &&
5063 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
5064 dbgs() << Call.getModule()->getName()
5065 << ": warning: kcfi: " << Call.getCaller()->getName()
5066 << ": call to " << CalleeF->getName()
5067 << " using a mismatching function pointer type\n";
5068 }
5069 });
5070
5071 return CallBase::removeOperandBundle(CB: &Call, ID: LLVMContext::OB_kcfi);
5072 }
5073
5074 if (isRemovableAlloc(V: &Call, TLI: &TLI))
5075 return visitAllocSite(FI&: Call);
5076
5077 // Handle intrinsics which can be used in both call and invoke context.
5078 switch (Call.getIntrinsicID()) {
5079 case Intrinsic::experimental_gc_statepoint: {
5080 GCStatepointInst &GCSP = *cast<GCStatepointInst>(Val: &Call);
5081 SmallPtrSet<Value *, 32> LiveGcValues;
5082 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
5083 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
5084
5085 // Remove the relocation if unused.
5086 if (GCR.use_empty()) {
5087 eraseInstFromFunction(I&: GCR);
5088 continue;
5089 }
5090
5091 Value *DerivedPtr = GCR.getDerivedPtr();
5092 Value *BasePtr = GCR.getBasePtr();
5093
5094 // Undef is undef, even after relocation.
5095 if (isa<UndefValue>(Val: DerivedPtr) || isa<UndefValue>(Val: BasePtr)) {
5096 replaceInstUsesWith(I&: GCR, V: UndefValue::get(T: GCR.getType()));
5097 eraseInstFromFunction(I&: GCR);
5098 continue;
5099 }
5100
5101 if (auto *PT = dyn_cast<PointerType>(Val: GCR.getType())) {
5102 // The relocation of null will be null for most any collector.
5103 // TODO: provide a hook for this in GCStrategy. There might be some
5104 // weird collector this property does not hold for.
5105 if (isa<ConstantPointerNull>(Val: DerivedPtr)) {
5106 // Use null-pointer of gc_relocate's type to replace it.
5107 replaceInstUsesWith(I&: GCR, V: ConstantPointerNull::get(T: PT));
5108 eraseInstFromFunction(I&: GCR);
5109 continue;
5110 }
5111
5112 // isKnownNonNull -> nonnull attribute
5113 if (!GCR.hasRetAttr(Kind: Attribute::NonNull) &&
5114 isKnownNonZero(V: DerivedPtr,
5115 Q: getSimplifyQuery().getWithInstruction(I: &Call))) {
5116 GCR.addRetAttr(Kind: Attribute::NonNull);
5117 // We discovered new fact, re-check users.
5118 Worklist.pushUsersToWorkList(I&: GCR);
5119 }
5120 }
5121
5122 // If we have two copies of the same pointer in the statepoint argument
5123 // list, canonicalize to one. This may let us common gc.relocates.
5124 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
5125 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
5126 auto *OpIntTy = GCR.getOperand(i_nocapture: 2)->getType();
5127 GCR.setOperand(i_nocapture: 2, Val_nocapture: ConstantInt::get(Ty: OpIntTy, V: GCR.getBasePtrIndex()));
5128 }
5129
5130 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
5131 // Canonicalize on the type from the uses to the defs
5132
5133 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
5134 LiveGcValues.insert(Ptr: BasePtr);
5135 LiveGcValues.insert(Ptr: DerivedPtr);
5136 }
5137 std::optional<OperandBundleUse> Bundle =
5138 GCSP.getOperandBundle(ID: LLVMContext::OB_gc_live);
5139 unsigned NumOfGCLives = LiveGcValues.size();
5140 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
5141 break;
5142 // We can reduce the size of gc live bundle.
5143 DenseMap<Value *, unsigned> Val2Idx;
5144 std::vector<Value *> NewLiveGc;
5145 for (Value *V : Bundle->Inputs) {
5146 auto [It, Inserted] = Val2Idx.try_emplace(Key: V);
5147 if (!Inserted)
5148 continue;
5149 if (LiveGcValues.count(Ptr: V)) {
5150 It->second = NewLiveGc.size();
5151 NewLiveGc.push_back(x: V);
5152 } else
5153 It->second = NumOfGCLives;
5154 }
5155 // Update all gc.relocates
5156 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
5157 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
5158 Value *BasePtr = GCR.getBasePtr();
5159 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
5160 "Missed live gc for base pointer");
5161 auto *OpIntTy1 = GCR.getOperand(i_nocapture: 1)->getType();
5162 GCR.setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::get(Ty: OpIntTy1, V: Val2Idx[BasePtr]));
5163 Value *DerivedPtr = GCR.getDerivedPtr();
5164 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
5165 "Missed live gc for derived pointer");
5166 auto *OpIntTy2 = GCR.getOperand(i_nocapture: 2)->getType();
5167 GCR.setOperand(i_nocapture: 2, Val_nocapture: ConstantInt::get(Ty: OpIntTy2, V: Val2Idx[DerivedPtr]));
5168 }
5169 // Create new statepoint instruction.
5170 OperandBundleDef NewBundle("gc-live", std::move(NewLiveGc));
5171 return CallBase::Create(CB: &Call, Bundle: NewBundle);
5172 }
5173 default: { break; }
5174 }
5175
5176 return Changed ? &Call : nullptr;
5177}
5178
5179/// If the callee is a constexpr cast of a function, attempt to move the cast to
5180/// the arguments of the call/invoke.
5181/// CallBrInst is not supported.
5182bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
5183 auto *Callee =
5184 dyn_cast<Function>(Val: Call.getCalledOperand()->stripPointerCasts());
5185 if (!Callee)
5186 return false;
5187
5188 assert(!isa<CallBrInst>(Call) &&
5189 "CallBr's don't have a single point after a def to insert at");
5190
5191 // Don't perform the transform for declarations, which may not be fully
5192 // accurate. For example, void @foo() is commonly used as a placeholder for
5193 // unknown prototypes.
5194 if (Callee->isDeclaration())
5195 return false;
5196
5197 // If this is a call to a thunk function, don't remove the cast. Thunks are
5198 // used to transparently forward all incoming parameters and outgoing return
5199 // values, so it's important to leave the cast in place.
5200 if (Callee->hasFnAttribute(Kind: "thunk"))
5201 return false;
5202
5203 // If this is a call to a naked function, the assembly might be
5204 // using an argument, or otherwise rely on the frame layout,
5205 // the function prototype will mismatch.
5206 if (Callee->hasFnAttribute(Kind: Attribute::Naked))
5207 return false;
5208
5209 // If this is a musttail call, the callee's prototype must match the caller's
5210 // prototype with the exception of pointee types. The code below doesn't
5211 // implement that, so we can't do this transform.
5212 // TODO: Do the transform if it only requires adding pointer casts.
5213 if (Call.isMustTailCall())
5214 return false;
5215
5216 Instruction *Caller = &Call;
5217 const AttributeList &CallerPAL = Call.getAttributes();
5218
5219 // Okay, this is a cast from a function to a different type. Unless doing so
5220 // would cause a type conversion of one of our arguments, change this call to
5221 // be a direct call with arguments casted to the appropriate types.
5222 FunctionType *FT = Callee->getFunctionType();
5223 Type *OldRetTy = Caller->getType();
5224 Type *NewRetTy = FT->getReturnType();
5225
5226 // Check to see if we are changing the return type...
5227 if (OldRetTy != NewRetTy) {
5228
5229 if (NewRetTy->isStructTy())
5230 return false; // TODO: Handle multiple return values.
5231
5232 if (!CastInst::isBitOrNoopPointerCastable(SrcTy: NewRetTy, DestTy: OldRetTy, DL)) {
5233 if (!Caller->use_empty())
5234 return false; // Cannot transform this return value.
5235 }
5236
5237 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
5238 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5239 if (RAttrs.overlaps(AM: AttributeFuncs::typeIncompatible(
5240 Ty: NewRetTy, AS: CallerPAL.getRetAttrs())))
5241 return false; // Attribute not compatible with transformed value.
5242 }
5243
5244 // If the callbase is an invoke instruction, and the return value is
5245 // used by a PHI node in a successor, we cannot change the return type of
5246 // the call because there is no place to put the cast instruction (without
5247 // breaking the critical edge). Bail out in this case.
5248 if (!Caller->use_empty()) {
5249 BasicBlock *PhisNotSupportedBlock = nullptr;
5250 if (auto *II = dyn_cast<InvokeInst>(Val: Caller))
5251 PhisNotSupportedBlock = II->getNormalDest();
5252 if (PhisNotSupportedBlock)
5253 for (User *U : Caller->users())
5254 if (PHINode *PN = dyn_cast<PHINode>(Val: U))
5255 if (PN->getParent() == PhisNotSupportedBlock)
5256 return false;
5257 }
5258 }
5259
5260 unsigned NumActualArgs = Call.arg_size();
5261 unsigned NumCommonArgs = std::min(a: FT->getNumParams(), b: NumActualArgs);
5262
5263 // Prevent us turning:
5264 // declare void @takes_i32_inalloca(i32* inalloca)
5265 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
5266 //
5267 // into:
5268 // call void @takes_i32_inalloca(i32* null)
5269 //
5270 // Similarly, avoid folding away bitcasts of byval calls.
5271 if (Callee->getAttributes().hasAttrSomewhere(Kind: Attribute::InAlloca) ||
5272 Callee->getAttributes().hasAttrSomewhere(Kind: Attribute::Preallocated))
5273 return false;
5274
5275 auto AI = Call.arg_begin();
5276 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5277 Type *ParamTy = FT->getParamType(i);
5278 Type *ActTy = (*AI)->getType();
5279
5280 if (!CastInst::isBitOrNoopPointerCastable(SrcTy: ActTy, DestTy: ParamTy, DL))
5281 return false; // Cannot transform this parameter value.
5282
5283 // Check if there are any incompatible attributes we cannot drop safely.
5284 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(ArgNo: i))
5285 .overlaps(AM: AttributeFuncs::typeIncompatible(
5286 Ty: ParamTy, AS: CallerPAL.getParamAttrs(ArgNo: i),
5287 ASK: AttributeFuncs::ASK_UNSAFE_TO_DROP)))
5288 return false; // Attribute not compatible with transformed value.
5289
5290 if (Call.isInAllocaArgument(ArgNo: i) ||
5291 CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::Preallocated))
5292 return false; // Cannot transform to and from inalloca/preallocated.
5293
5294 if (CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::SwiftError))
5295 return false;
5296
5297 if (CallerPAL.hasParamAttr(ArgNo: i, Kind: Attribute::ByVal) !=
5298 Callee->getAttributes().hasParamAttr(ArgNo: i, Kind: Attribute::ByVal))
5299 return false; // Cannot transform to or from byval.
5300 }
5301
5302 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5303 !CallerPAL.isEmpty()) {
5304 // In this case we have more arguments than the new function type, but we
5305 // won't be dropping them. Check that these extra arguments have attributes
5306 // that are compatible with being a vararg call argument.
5307 unsigned SRetIdx;
5308 if (CallerPAL.hasAttrSomewhere(Kind: Attribute::StructRet, Index: &SRetIdx) &&
5309 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
5310 return false;
5311 }
5312
5313 // Okay, we decided that this is a safe thing to do: go ahead and start
5314 // inserting cast instructions as necessary.
5315 SmallVector<Value *, 8> Args;
5316 SmallVector<AttributeSet, 8> ArgAttrs;
5317 Args.reserve(N: NumActualArgs);
5318 ArgAttrs.reserve(N: NumActualArgs);
5319
5320 // Get any return attributes.
5321 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5322
5323 // If the return value is not being used, the type may not be compatible
5324 // with the existing attributes. Wipe out any problematic attributes.
5325 RAttrs.remove(
5326 AM: AttributeFuncs::typeIncompatible(Ty: NewRetTy, AS: CallerPAL.getRetAttrs()));
5327
5328 LLVMContext &Ctx = Call.getContext();
5329 AI = Call.arg_begin();
5330 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5331 Type *ParamTy = FT->getParamType(i);
5332
5333 Value *NewArg = *AI;
5334 if ((*AI)->getType() != ParamTy)
5335 NewArg = Builder.CreateBitOrPointerCast(V: *AI, DestTy: ParamTy);
5336 Args.push_back(Elt: NewArg);
5337
5338 // Add any parameter attributes except the ones incompatible with the new
5339 // type. Note that we made sure all incompatible ones are safe to drop.
5340 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
5341 Ty: ParamTy, AS: CallerPAL.getParamAttrs(ArgNo: i), ASK: AttributeFuncs::ASK_SAFE_TO_DROP);
5342 ArgAttrs.push_back(
5343 Elt: CallerPAL.getParamAttrs(ArgNo: i).removeAttributes(C&: Ctx, AttrsToRemove: IncompatibleAttrs));
5344 }
5345
5346 // If the function takes more arguments than the call was taking, add them
5347 // now.
5348 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
5349 Args.push_back(Elt: Constant::getNullValue(Ty: FT->getParamType(i)));
5350 ArgAttrs.push_back(Elt: AttributeSet());
5351 }
5352
5353 // If we are removing arguments to the function, emit an obnoxious warning.
5354 if (FT->getNumParams() < NumActualArgs) {
5355 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
5356 if (FT->isVarArg()) {
5357 // Add all of the arguments in their promoted form to the arg list.
5358 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5359 Type *PTy = getPromotedType(Ty: (*AI)->getType());
5360 Value *NewArg = *AI;
5361 if (PTy != (*AI)->getType()) {
5362 // Must promote to pass through va_arg area!
5363 Instruction::CastOps opcode =
5364 CastInst::getCastOpcode(Val: *AI, SrcIsSigned: false, Ty: PTy, DstIsSigned: false);
5365 NewArg = Builder.CreateCast(Op: opcode, V: *AI, DestTy: PTy);
5366 }
5367 Args.push_back(Elt: NewArg);
5368
5369 // Add any parameter attributes.
5370 ArgAttrs.push_back(Elt: CallerPAL.getParamAttrs(ArgNo: i));
5371 }
5372 }
5373 }
5374
5375 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
5376
5377 if (NewRetTy->isVoidTy())
5378 Caller->setName(""); // Void type should not have a name.
5379
5380 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
5381 "missing argument attributes");
5382 AttributeList NewCallerPAL = AttributeList::get(
5383 C&: Ctx, FnAttrs, RetAttrs: AttributeSet::get(C&: Ctx, B: RAttrs), ArgAttrs);
5384
5385 SmallVector<OperandBundleDef, 1> OpBundles;
5386 Call.getOperandBundlesAsDefs(Defs&: OpBundles);
5387
5388 CallBase *NewCall;
5389 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: Caller)) {
5390 NewCall = Builder.CreateInvoke(Callee, NormalDest: II->getNormalDest(),
5391 UnwindDest: II->getUnwindDest(), Args, OpBundles);
5392 } else {
5393 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
5394 cast<CallInst>(Val: NewCall)->setTailCallKind(
5395 cast<CallInst>(Val: Caller)->getTailCallKind());
5396 }
5397 NewCall->takeName(V: Caller);
5398 NewCall->setCallingConv(Call.getCallingConv());
5399 NewCall->setAttributes(NewCallerPAL);
5400
5401 // Preserve prof metadata if any.
5402 NewCall->copyMetadata(SrcInst: *Caller, WL: {LLVMContext::MD_prof});
5403
5404 // Insert a cast of the return type as necessary.
5405 Instruction *NC = NewCall;
5406 Value *NV = NC;
5407 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
5408 assert(!NV->getType()->isVoidTy());
5409 NV = NC = CastInst::CreateBitOrPointerCast(S: NC, Ty: OldRetTy);
5410 NC->setDebugLoc(Caller->getDebugLoc());
5411
5412 auto OptInsertPt = NewCall->getInsertionPointAfterDef();
5413 assert(OptInsertPt && "No place to insert cast");
5414 InsertNewInstBefore(New: NC, Old: *OptInsertPt);
5415 Worklist.pushUsersToWorkList(I&: *Caller);
5416 }
5417
5418 if (!Caller->use_empty())
5419 replaceInstUsesWith(I&: *Caller, V: NV);
5420 else if (Caller->hasValueHandle()) {
5421 if (OldRetTy == NV->getType())
5422 ValueHandleBase::ValueIsRAUWd(Old: Caller, New: NV);
5423 else
5424 // We cannot call ValueIsRAUWd with a different type, and the
5425 // actual tracked value will disappear.
5426 ValueHandleBase::ValueIsDeleted(V: Caller);
5427 }
5428
5429 eraseInstFromFunction(I&: *Caller);
5430 return true;
5431}
5432
5433/// Turn a call to a function created by init_trampoline / adjust_trampoline
5434/// intrinsic pair into a direct call to the underlying function.
5435Instruction *
5436InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
5437 IntrinsicInst &Tramp) {
5438 FunctionType *FTy = Call.getFunctionType();
5439 AttributeList Attrs = Call.getAttributes();
5440
5441 // If the call already has the 'nest' attribute somewhere then give up -
5442 // otherwise 'nest' would occur twice after splicing in the chain.
5443 if (Attrs.hasAttrSomewhere(Kind: Attribute::Nest))
5444 return nullptr;
5445
5446 Function *NestF = cast<Function>(Val: Tramp.getArgOperand(i: 1)->stripPointerCasts());
5447 FunctionType *NestFTy = NestF->getFunctionType();
5448
5449 AttributeList NestAttrs = NestF->getAttributes();
5450 if (!NestAttrs.isEmpty()) {
5451 unsigned NestArgNo = 0;
5452 Type *NestTy = nullptr;
5453 AttributeSet NestAttr;
5454
5455 // Look for a parameter marked with the 'nest' attribute.
5456 for (FunctionType::param_iterator I = NestFTy->param_begin(),
5457 E = NestFTy->param_end();
5458 I != E; ++NestArgNo, ++I) {
5459 AttributeSet AS = NestAttrs.getParamAttrs(ArgNo: NestArgNo);
5460 if (AS.hasAttribute(Kind: Attribute::Nest)) {
5461 // Record the parameter type and any other attributes.
5462 NestTy = *I;
5463 NestAttr = AS;
5464 break;
5465 }
5466 }
5467
5468 if (NestTy) {
5469 std::vector<Value*> NewArgs;
5470 std::vector<AttributeSet> NewArgAttrs;
5471 NewArgs.reserve(n: Call.arg_size() + 1);
5472 NewArgAttrs.reserve(n: Call.arg_size());
5473
5474 // Insert the nest argument into the call argument list, which may
5475 // mean appending it. Likewise for attributes.
5476
5477 {
5478 unsigned ArgNo = 0;
5479 auto I = Call.arg_begin(), E = Call.arg_end();
5480 do {
5481 if (ArgNo == NestArgNo) {
5482 // Add the chain argument and attributes.
5483 Value *NestVal = Tramp.getArgOperand(i: 2);
5484 if (NestVal->getType() != NestTy)
5485 NestVal = Builder.CreateBitCast(V: NestVal, DestTy: NestTy, Name: "nest");
5486 NewArgs.push_back(x: NestVal);
5487 NewArgAttrs.push_back(x: NestAttr);
5488 }
5489
5490 if (I == E)
5491 break;
5492
5493 // Add the original argument and attributes.
5494 NewArgs.push_back(x: *I);
5495 NewArgAttrs.push_back(x: Attrs.getParamAttrs(ArgNo));
5496
5497 ++ArgNo;
5498 ++I;
5499 } while (true);
5500 }
5501
5502 // The trampoline may have been bitcast to a bogus type (FTy).
5503 // Handle this by synthesizing a new function type, equal to FTy
5504 // with the chain parameter inserted.
5505
5506 std::vector<Type*> NewTypes;
5507 NewTypes.reserve(n: FTy->getNumParams()+1);
5508
5509 // Insert the chain's type into the list of parameter types, which may
5510 // mean appending it.
5511 {
5512 unsigned ArgNo = 0;
5513 FunctionType::param_iterator I = FTy->param_begin(),
5514 E = FTy->param_end();
5515
5516 do {
5517 if (ArgNo == NestArgNo)
5518 // Add the chain's type.
5519 NewTypes.push_back(x: NestTy);
5520
5521 if (I == E)
5522 break;
5523
5524 // Add the original type.
5525 NewTypes.push_back(x: *I);
5526
5527 ++ArgNo;
5528 ++I;
5529 } while (true);
5530 }
5531
5532 // Replace the trampoline call with a direct call. Let the generic
5533 // code sort out any function type mismatches.
5534 FunctionType *NewFTy =
5535 FunctionType::get(Result: FTy->getReturnType(), Params: NewTypes, isVarArg: FTy->isVarArg());
5536 AttributeList NewPAL =
5537 AttributeList::get(C&: FTy->getContext(), FnAttrs: Attrs.getFnAttrs(),
5538 RetAttrs: Attrs.getRetAttrs(), ArgAttrs: NewArgAttrs);
5539
5540 SmallVector<OperandBundleDef, 1> OpBundles;
5541 Call.getOperandBundlesAsDefs(Defs&: OpBundles);
5542
5543 Instruction *NewCaller;
5544 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &Call)) {
5545 NewCaller = InvokeInst::Create(Ty: NewFTy, Func: NestF, IfNormal: II->getNormalDest(),
5546 IfException: II->getUnwindDest(), Args: NewArgs, Bundles: OpBundles);
5547 cast<InvokeInst>(Val: NewCaller)->setCallingConv(II->getCallingConv());
5548 cast<InvokeInst>(Val: NewCaller)->setAttributes(NewPAL);
5549 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Val: &Call)) {
5550 NewCaller =
5551 CallBrInst::Create(Ty: NewFTy, Func: NestF, DefaultDest: CBI->getDefaultDest(),
5552 IndirectDests: CBI->getIndirectDests(), Args: NewArgs, Bundles: OpBundles);
5553 cast<CallBrInst>(Val: NewCaller)->setCallingConv(CBI->getCallingConv());
5554 cast<CallBrInst>(Val: NewCaller)->setAttributes(NewPAL);
5555 } else {
5556 NewCaller = CallInst::Create(Ty: NewFTy, Func: NestF, Args: NewArgs, Bundles: OpBundles);
5557 cast<CallInst>(Val: NewCaller)->setTailCallKind(
5558 cast<CallInst>(Val&: Call).getTailCallKind());
5559 cast<CallInst>(Val: NewCaller)->setCallingConv(
5560 cast<CallInst>(Val&: Call).getCallingConv());
5561 cast<CallInst>(Val: NewCaller)->setAttributes(NewPAL);
5562 }
5563 NewCaller->setDebugLoc(Call.getDebugLoc());
5564
5565 return NewCaller;
5566 }
5567 }
5568
5569 // Replace the trampoline call with a direct call. Since there is no 'nest'
5570 // parameter, there is no need to adjust the argument list. Let the generic
5571 // code sort out any function type mismatches.
5572 Call.setCalledFunction(FTy, Fn: NestF);
5573 return &Call;
5574}
5575