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