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