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