LLVM 19.0.0git
InstCombineCalls.cpp
Go to the documentation of this file.
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"
21#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/Loads.h"
31#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/IntrinsicsAArch64.h"
47#include "llvm/IR/IntrinsicsAMDGPU.h"
48#include "llvm/IR/IntrinsicsARM.h"
49#include "llvm/IR/IntrinsicsHexagon.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
53#include "llvm/IR/Statepoint.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/User.h"
56#include "llvm/IR/Value.h"
57#include "llvm/IR/ValueHandle.h"
62#include "llvm/Support/Debug.h"
71#include <algorithm>
72#include <cassert>
73#include <cstdint>
74#include <optional>
75#include <utility>
76#include <vector>
77
78#define DEBUG_TYPE "instcombine"
80
81using namespace llvm;
82using namespace PatternMatch;
83
84STATISTIC(NumSimplified, "Number of library calls simplified");
85
87 "instcombine-guard-widening-window",
88 cl::init(3),
89 cl::desc("How wide an instruction window to bypass looking for "
90 "another guard"));
91
92/// Return the specified type promoted as it would be to pass though a va_arg
93/// area.
95 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
96 if (ITy->getBitWidth() < 32)
97 return Type::getInt32Ty(Ty->getContext());
98 }
99 return Ty;
100}
101
102/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.
103/// TODO: This should probably be integrated with visitAllocSites, but that
104/// requires a deeper change to allow either unread or unwritten objects.
106 auto *Src = MI->getRawSource();
107 while (isa<GetElementPtrInst>(Src) || isa<BitCastInst>(Src)) {
108 if (!Src->hasOneUse())
109 return false;
110 Src = cast<Instruction>(Src)->getOperand(0);
111 }
112 return isa<AllocaInst>(Src) && Src->hasOneUse();
113}
114
116 Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
117 MaybeAlign CopyDstAlign = MI->getDestAlign();
118 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
119 MI->setDestAlignment(DstAlign);
120 return MI;
121 }
122
123 Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
124 MaybeAlign CopySrcAlign = MI->getSourceAlign();
125 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
126 MI->setSourceAlignment(SrcAlign);
127 return MI;
128 }
129
130 // If we have a store to a location which is known constant, we can conclude
131 // that the store must be storing the constant value (else the memory
132 // wouldn't be constant), and this must be a noop.
133 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
134 // Set the size of the copy to 0, it will be deleted on the next iteration.
135 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
136 return MI;
137 }
138
139 // If the source is provably undef, the memcpy/memmove doesn't do anything
140 // (unless the transfer is volatile).
141 if (hasUndefSource(MI) && !MI->isVolatile()) {
142 // Set the size of the copy to 0, it will be deleted on the next iteration.
143 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
144 return MI;
145 }
146
147 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
148 // load/store.
149 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
150 if (!MemOpLength) return nullptr;
151
152 // Source and destination pointer types are always "i8*" for intrinsic. See
153 // if the size is something we can handle with a single primitive load/store.
154 // A single load+store correctly handles overlapping memory in the memmove
155 // case.
156 uint64_t Size = MemOpLength->getLimitedValue();
157 assert(Size && "0-sized memory transferring should be removed already.");
158
159 if (Size > 8 || (Size&(Size-1)))
160 return nullptr; // If not 1/2/4/8 bytes, exit.
161
162 // If it is an atomic and alignment is less than the size then we will
163 // introduce the unaligned memory access which will be later transformed
164 // into libcall in CodeGen. This is not evident performance gain so disable
165 // it now.
166 if (isa<AtomicMemTransferInst>(MI))
167 if (*CopyDstAlign < Size || *CopySrcAlign < Size)
168 return nullptr;
169
170 // Use an integer load+store unless we can find something better.
171 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
172
173 // If the memcpy has metadata describing the members, see if we can get the
174 // TBAA tag describing our copy.
175 AAMDNodes AACopyMD = MI->getAAMetadata().adjustForAccess(Size);
176
177 Value *Src = MI->getArgOperand(1);
178 Value *Dest = MI->getArgOperand(0);
179 LoadInst *L = Builder.CreateLoad(IntType, Src);
180 // Alignment from the mem intrinsic will be better, so use it.
181 L->setAlignment(*CopySrcAlign);
182 L->setAAMetadata(AACopyMD);
183 MDNode *LoopMemParallelMD =
184 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
185 if (LoopMemParallelMD)
186 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
187 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
188 if (AccessGroupMD)
189 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
190
191 StoreInst *S = Builder.CreateStore(L, Dest);
192 // Alignment from the mem intrinsic will be better, so use it.
193 S->setAlignment(*CopyDstAlign);
194 S->setAAMetadata(AACopyMD);
195 if (LoopMemParallelMD)
196 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
197 if (AccessGroupMD)
198 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
199 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
200
201 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
202 // non-atomics can be volatile
203 L->setVolatile(MT->isVolatile());
204 S->setVolatile(MT->isVolatile());
205 }
206 if (isa<AtomicMemTransferInst>(MI)) {
207 // atomics have to be unordered
208 L->setOrdering(AtomicOrdering::Unordered);
210 }
211
212 // Set the size of the copy to 0, it will be deleted on the next iteration.
213 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
214 return MI;
215}
216
218 const Align KnownAlignment =
219 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
220 MaybeAlign MemSetAlign = MI->getDestAlign();
221 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
222 MI->setDestAlignment(KnownAlignment);
223 return MI;
224 }
225
226 // If we have a store to a location which is known constant, we can conclude
227 // that the store must be storing the constant value (else the memory
228 // wouldn't be constant), and this must be a noop.
229 if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {
230 // Set the size of the copy to 0, it will be deleted on the next iteration.
231 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
232 return MI;
233 }
234
235 // Remove memset with an undef value.
236 // FIXME: This is technically incorrect because it might overwrite a poison
237 // value. Change to PoisonValue once #52930 is resolved.
238 if (isa<UndefValue>(MI->getValue())) {
239 // Set the size of the copy to 0, it will be deleted on the next iteration.
240 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241 return MI;
242 }
243
244 // Extract the length and alignment and fill if they are constant.
245 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
247 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
248 return nullptr;
249 const uint64_t Len = LenC->getLimitedValue();
250 assert(Len && "0-sized memory setting should be removed already.");
251 const Align Alignment = MI->getDestAlign().valueOrOne();
252
253 // If it is an atomic and alignment is less than the size then we will
254 // introduce the unaligned memory access which will be later transformed
255 // into libcall in CodeGen. This is not evident performance gain so disable
256 // it now.
257 if (isa<AtomicMemSetInst>(MI))
258 if (Alignment < Len)
259 return nullptr;
260
261 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
263 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
264
265 Value *Dest = MI->getDest();
266
267 // Extract the fill value and store.
268 const uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
269 Constant *FillVal = ConstantInt::get(ITy, Fill);
270 StoreInst *S = Builder.CreateStore(FillVal, Dest, MI->isVolatile());
271 S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);
272 auto replaceOpForAssignmentMarkers = [FillC, FillVal](auto *DbgAssign) {
273 if (llvm::is_contained(DbgAssign->location_ops(), FillC))
274 DbgAssign->replaceVariableLocationOp(FillC, FillVal);
275 };
276 for_each(at::getAssignmentMarkers(S), replaceOpForAssignmentMarkers);
277 for_each(at::getDPVAssignmentMarkers(S), replaceOpForAssignmentMarkers);
278
279 S->setAlignment(Alignment);
280 if (isa<AtomicMemSetInst>(MI))
282
283 // Set the size of the copy to 0, it will be deleted on the next iteration.
284 MI->setLength(Constant::getNullValue(LenC->getType()));
285 return MI;
286 }
287
288 return nullptr;
289}
290
291// TODO, Obvious Missing Transforms:
292// * Narrow width by halfs excluding zero/undef lanes
293Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {
294 Value *LoadPtr = II.getArgOperand(0);
295 const Align Alignment =
296 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
297
298 // If the mask is all ones or undefs, this is a plain vector load of the 1st
299 // argument.
301 LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
302 "unmaskedload");
303 L->copyMetadata(II);
304 return L;
305 }
306
307 // If we can unconditionally load from this address, replace with a
308 // load/select idiom. TODO: use DT for context sensitive query
309 if (isDereferenceablePointer(LoadPtr, II.getType(),
310 II.getModule()->getDataLayout(), &II, &AC)) {
311 LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
312 "unmaskedload");
313 LI->copyMetadata(II);
314 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
315 }
316
317 return nullptr;
318}
319
320// TODO, Obvious Missing Transforms:
321// * Single constant active lane -> store
322// * Narrow width by halfs excluding zero/undef lanes
323Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {
324 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
325 if (!ConstMask)
326 return nullptr;
327
328 // If the mask is all zeros, this instruction does nothing.
329 if (ConstMask->isNullValue())
330 return eraseInstFromFunction(II);
331
332 // If the mask is all ones, this is a plain vector store of the 1st argument.
333 if (ConstMask->isAllOnesValue()) {
334 Value *StorePtr = II.getArgOperand(1);
335 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
336 StoreInst *S =
337 new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
338 S->copyMetadata(II);
339 return S;
340 }
341
342 if (isa<ScalableVectorType>(ConstMask->getType()))
343 return nullptr;
344
345 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
346 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
347 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
348 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,
349 PoisonElts))
350 return replaceOperand(II, 0, V);
351
352 return nullptr;
353}
354
355// TODO, Obvious Missing Transforms:
356// * Single constant active lane load -> load
357// * Dereferenceable address & few lanes -> scalarize speculative load/selects
358// * Adjacent vector addresses -> masked.load
359// * Narrow width by halfs excluding zero/undef lanes
360// * Vector incrementing address -> vector masked load
361Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {
362 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
363 if (!ConstMask)
364 return nullptr;
365
366 // Vector splat address w/known mask -> scalar load
367 // Fold the gather to load the source vector first lane
368 // because it is reloading the same value each time
369 if (ConstMask->isAllOnesValue())
370 if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {
371 auto *VecTy = cast<VectorType>(II.getType());
372 const Align Alignment =
373 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
374 LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
375 Alignment, "load.scalar");
376 Value *Shuf =
377 Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");
378 return replaceInstUsesWith(II, cast<Instruction>(Shuf));
379 }
380
381 return nullptr;
382}
383
384// TODO, Obvious Missing Transforms:
385// * Single constant active lane -> store
386// * Adjacent vector addresses -> masked.store
387// * Narrow store width by halfs excluding zero/undef lanes
388// * Vector incrementing address -> vector masked store
389Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {
390 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
391 if (!ConstMask)
392 return nullptr;
393
394 // If the mask is all zeros, a scatter does nothing.
395 if (ConstMask->isNullValue())
396 return eraseInstFromFunction(II);
397
398 // Vector splat address -> scalar store
399 if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {
400 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr
401 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {
402 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
403 StoreInst *S =
404 new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment);
405 S->copyMetadata(II);
406 return S;
407 }
408 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector,
409 // lastlane), ptr
410 if (ConstMask->isAllOnesValue()) {
411 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();
412 VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());
413 ElementCount VF = WideLoadTy->getElementCount();
415 Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));
416 Value *Extract =
418 StoreInst *S =
419 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);
420 S->copyMetadata(II);
421 return S;
422 }
423 }
424 if (isa<ScalableVectorType>(ConstMask->getType()))
425 return nullptr;
426
427 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
428 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
429 APInt PoisonElts(DemandedElts.getBitWidth(), 0);
430 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,
431 PoisonElts))
432 return replaceOperand(II, 0, V);
433 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts,
434 PoisonElts))
435 return replaceOperand(II, 1, V);
436
437 return nullptr;
438}
439
440/// This function transforms launder.invariant.group and strip.invariant.group
441/// like:
442/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
443/// launder(strip(%x)) -> launder(%x)
444/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
445/// strip(launder(%x)) -> strip(%x)
446/// This is legal because it preserves the most recent information about
447/// the presence or absence of invariant.group.
449 InstCombinerImpl &IC) {
450 auto *Arg = II.getArgOperand(0);
451 auto *StrippedArg = Arg->stripPointerCasts();
452 auto *StrippedInvariantGroupsArg = StrippedArg;
453 while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {
454 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&
455 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)
456 break;
457 StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
458 }
459 if (StrippedArg == StrippedInvariantGroupsArg)
460 return nullptr; // No launders/strips to remove.
461
462 Value *Result = nullptr;
463
464 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
465 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
466 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
467 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
468 else
470 "simplifyInvariantGroupIntrinsic only handles launder and strip");
471 if (Result->getType()->getPointerAddressSpace() !=
473 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
474
475 return cast<Instruction>(Result);
476}
477
479 assert((II.getIntrinsicID() == Intrinsic::cttz ||
480 II.getIntrinsicID() == Intrinsic::ctlz) &&
481 "Expected cttz or ctlz intrinsic");
482 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
483 Value *Op0 = II.getArgOperand(0);
484 Value *Op1 = II.getArgOperand(1);
485 Value *X;
486 // ctlz(bitreverse(x)) -> cttz(x)
487 // cttz(bitreverse(x)) -> ctlz(x)
488 if (match(Op0, m_BitReverse(m_Value(X)))) {
489 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
491 return CallInst::Create(F, {X, II.getArgOperand(1)});
492 }
493
494 if (II.getType()->isIntOrIntVectorTy(1)) {
495 // ctlz/cttz i1 Op0 --> not Op0
496 if (match(Op1, m_Zero()))
497 return BinaryOperator::CreateNot(Op0);
498 // If zero is poison, then the input can be assumed to be "true", so the
499 // instruction simplifies to "false".
500 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");
502 }
503
504 Constant *C;
505
506 if (IsTZ) {
507 // cttz(-x) -> cttz(x)
508 if (match(Op0, m_Neg(m_Value(X))))
509 return IC.replaceOperand(II, 0, X);
510
511 // cttz(-x & x) -> cttz(x)
512 if (match(Op0, m_c_And(m_Neg(m_Value(X)), m_Deferred(X))))
513 return IC.replaceOperand(II, 0, X);
514
515 // cttz(sext(x)) -> cttz(zext(x))
516 if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {
517 auto *Zext = IC.Builder.CreateZExt(X, II.getType());
518 auto *CttzZext =
519 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);
520 return IC.replaceInstUsesWith(II, CttzZext);
521 }
522
523 // Zext doesn't change the number of trailing zeros, so narrow:
524 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.
525 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {
526 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,
527 IC.Builder.getTrue());
528 auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());
529 return IC.replaceInstUsesWith(II, ZextCttz);
530 }
531
532 // cttz(abs(x)) -> cttz(x)
533 // cttz(nabs(x)) -> cttz(x)
534 Value *Y;
536 if (SPF == SPF_ABS || SPF == SPF_NABS)
537 return IC.replaceOperand(II, 0, X);
538
539 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
540 return IC.replaceOperand(II, 0, X);
541
542 // cttz(shl(%const, %val), 1) --> add(cttz(%const, 1), %val)
543 if (match(Op0, m_Shl(m_ImmConstant(C), m_Value(X))) &&
544 match(Op1, m_One())) {
545 Value *ConstCttz =
546 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);
547 return BinaryOperator::CreateAdd(ConstCttz, X);
548 }
549
550 // cttz(lshr exact (%const, %val), 1) --> sub(cttz(%const, 1), %val)
551 if (match(Op0, m_Exact(m_LShr(m_ImmConstant(C), m_Value(X)))) &&
552 match(Op1, m_One())) {
553 Value *ConstCttz =
554 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);
555 return BinaryOperator::CreateSub(ConstCttz, X);
556 }
557 } else {
558 // ctlz(lshr(%const, %val), 1) --> add(ctlz(%const, 1), %val)
559 if (match(Op0, m_LShr(m_ImmConstant(C), m_Value(X))) &&
560 match(Op1, m_One())) {
561 Value *ConstCtlz =
562 IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);
563 return BinaryOperator::CreateAdd(ConstCtlz, X);
564 }
565
566 // ctlz(shl nuw (%const, %val), 1) --> sub(ctlz(%const, 1), %val)
567 if (match(Op0, m_NUWShl(m_ImmConstant(C), m_Value(X))) &&
568 match(Op1, m_One())) {
569 Value *ConstCtlz =
570 IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);
571 return BinaryOperator::CreateSub(ConstCtlz, X);
572 }
573 }
574
575 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
576
577 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
578 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
579 : Known.countMaxLeadingZeros();
580 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
581 : Known.countMinLeadingZeros();
582
583 // If all bits above (ctlz) or below (cttz) the first known one are known
584 // zero, this value is constant.
585 // FIXME: This should be in InstSimplify because we're replacing an
586 // instruction with a constant.
587 if (PossibleZeros == DefiniteZeros) {
588 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
589 return IC.replaceInstUsesWith(II, C);
590 }
591
592 // If the input to cttz/ctlz is known to be non-zero,
593 // then change the 'ZeroIsPoison' parameter to 'true'
594 // because we know the zero behavior can't affect the result.
595 if (!Known.One.isZero() ||
596 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
597 &IC.getDominatorTree())) {
598 if (!match(II.getArgOperand(1), m_One()))
599 return IC.replaceOperand(II, 1, IC.Builder.getTrue());
600 }
601
602 // Add range metadata since known bits can't completely reflect what we know.
603 auto *IT = cast<IntegerType>(Op0->getType()->getScalarType());
604 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
605 Metadata *LowAndHigh[] = {
606 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
607 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
608 II.setMetadata(LLVMContext::MD_range,
610 return &II;
611 }
612
613 return nullptr;
614}
615
617 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
618 "Expected ctpop intrinsic");
619 Type *Ty = II.getType();
620 unsigned BitWidth = Ty->getScalarSizeInBits();
621 Value *Op0 = II.getArgOperand(0);
622 Value *X, *Y;
623
624 // ctpop(bitreverse(x)) -> ctpop(x)
625 // ctpop(bswap(x)) -> ctpop(x)
626 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))
627 return IC.replaceOperand(II, 0, X);
628
629 // ctpop(rot(x)) -> ctpop(x)
630 if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||
631 match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&
632 X == Y)
633 return IC.replaceOperand(II, 0, X);
634
635 // ctpop(x | -x) -> bitwidth - cttz(x, false)
636 if (Op0->hasOneUse() &&
637 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {
638 Function *F =
639 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
640 auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});
641 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));
642 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));
643 }
644
645 // ctpop(~x & (x - 1)) -> cttz(x, false)
646 if (match(Op0,
648 Function *F =
649 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);
650 return CallInst::Create(F, {X, IC.Builder.getFalse()});
651 }
652
653 // Zext doesn't change the number of set bits, so narrow:
654 // ctpop (zext X) --> zext (ctpop X)
655 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
656 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);
657 return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);
658 }
659
660 KnownBits Known(BitWidth);
661 IC.computeKnownBits(Op0, Known, 0, &II);
662
663 // If all bits are zero except for exactly one fixed bit, then the result
664 // must be 0 or 1, and we can get that answer by shifting to LSB:
665 // ctpop (X & 32) --> (X & 32) >> 5
666 // TODO: Investigate removing this as its likely unnecessary given the below
667 // `isKnownToBeAPowerOfTwo` check.
668 if ((~Known.Zero).isPowerOf2())
669 return BinaryOperator::CreateLShr(
670 Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));
671
672 // More generally we can also handle non-constant power of 2 patterns such as
673 // shl/shr(Pow2, X), (X & -X), etc... by transforming:
674 // ctpop(Pow2OrZero) --> icmp ne X, 0
675 if (IC.isKnownToBeAPowerOfTwo(Op0, /* OrZero */ true))
676 return CastInst::Create(Instruction::ZExt,
679 Ty);
680
681 // Add range metadata since known bits can't completely reflect what we know.
682 auto *IT = cast<IntegerType>(Ty->getScalarType());
683 unsigned MinCount = Known.countMinPopulation();
684 unsigned MaxCount = Known.countMaxPopulation();
685 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
686 Metadata *LowAndHigh[] = {
687 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
688 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
689 II.setMetadata(LLVMContext::MD_range,
691 return &II;
692 }
693
694 return nullptr;
695}
696
697/// Convert a table lookup to shufflevector if the mask is constant.
698/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
699/// which case we could lower the shufflevector with rev64 instructions
700/// as it's actually a byte reverse.
702 InstCombiner::BuilderTy &Builder) {
703 // Bail out if the mask is not a constant.
704 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
705 if (!C)
706 return nullptr;
707
708 auto *VecTy = cast<FixedVectorType>(II.getType());
709 unsigned NumElts = VecTy->getNumElements();
710
711 // Only perform this transformation for <8 x i8> vector types.
712 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
713 return nullptr;
714
715 int Indexes[8];
716
717 for (unsigned I = 0; I < NumElts; ++I) {
718 Constant *COp = C->getAggregateElement(I);
719
720 if (!COp || !isa<ConstantInt>(COp))
721 return nullptr;
722
723 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
724
725 // Make sure the mask indices are in range.
726 if ((unsigned)Indexes[I] >= NumElts)
727 return nullptr;
728 }
729
730 auto *V1 = II.getArgOperand(0);
731 auto *V2 = Constant::getNullValue(V1->getType());
732 return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes));
733}
734
735// Returns true iff the 2 intrinsics have the same operands, limiting the
736// comparison to the first NumOperands.
737static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
738 unsigned NumOperands) {
739 assert(I.arg_size() >= NumOperands && "Not enough operands");
740 assert(E.arg_size() >= NumOperands && "Not enough operands");
741 for (unsigned i = 0; i < NumOperands; i++)
742 if (I.getArgOperand(i) != E.getArgOperand(i))
743 return false;
744 return true;
745}
746
747// Remove trivially empty start/end intrinsic ranges, i.e. a start
748// immediately followed by an end (ignoring debuginfo or other
749// start/end intrinsics in between). As this handles only the most trivial
750// cases, tracking the nesting level is not needed:
751//
752// call @llvm.foo.start(i1 0)
753// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed
754// call @llvm.foo.end(i1 0)
755// call @llvm.foo.end(i1 0) ; &I
756static bool
758 std::function<bool(const IntrinsicInst &)> IsStart) {
759 // We start from the end intrinsic and scan backwards, so that InstCombine
760 // has already processed (and potentially removed) all the instructions
761 // before the end intrinsic.
762 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());
763 for (; BI != BE; ++BI) {
764 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {
765 if (I->isDebugOrPseudoInst() ||
766 I->getIntrinsicID() == EndI.getIntrinsicID())
767 continue;
768 if (IsStart(*I)) {
769 if (haveSameOperands(EndI, *I, EndI.arg_size())) {
771 IC.eraseInstFromFunction(EndI);
772 return true;
773 }
774 // Skip start intrinsics that don't pair with this end intrinsic.
775 continue;
776 }
777 }
778 break;
779 }
780
781 return false;
782}
783
785 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {
786 return I.getIntrinsicID() == Intrinsic::vastart ||
787 I.getIntrinsicID() == Intrinsic::vacopy;
788 });
789 return nullptr;
790}
791
793 assert(Call.arg_size() > 1 && "Need at least 2 args to swap");
794 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
795 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
796 Call.setArgOperand(0, Arg1);
797 Call.setArgOperand(1, Arg0);
798 return &Call;
799 }
800 return nullptr;
801}
802
803/// Creates a result tuple for an overflow intrinsic \p II with a given
804/// \p Result and a constant \p Overflow value.
806 Constant *Overflow) {
807 Constant *V[] = {PoisonValue::get(Result->getType()), Overflow};
808 StructType *ST = cast<StructType>(II->getType());
810 return InsertValueInst::Create(Struct, Result, 0);
811}
812
814InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
815 WithOverflowInst *WO = cast<WithOverflowInst>(II);
816 Value *OperationResult = nullptr;
817 Constant *OverflowResult = nullptr;
818 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
819 WO->getRHS(), *WO, OperationResult, OverflowResult))
820 return createOverflowTuple(WO, OperationResult, OverflowResult);
821 return nullptr;
822}
823
824static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
825 Ty = Ty->getScalarType();
826 return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;
827}
828
829static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {
830 Ty = Ty->getScalarType();
831 return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();
832}
833
834/// \returns the compare predicate type if the test performed by
835/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the
836/// floating-point environment assumed for \p F for type \p Ty
838 const Function &F, Type *Ty) {
839 switch (static_cast<unsigned>(Mask)) {
840 case fcZero:
841 if (inputDenormalIsIEEE(F, Ty))
842 return FCmpInst::FCMP_OEQ;
843 break;
844 case fcZero | fcSubnormal:
845 if (inputDenormalIsDAZ(F, Ty))
846 return FCmpInst::FCMP_OEQ;
847 break;
848 case fcPositive | fcNegZero:
849 if (inputDenormalIsIEEE(F, Ty))
850 return FCmpInst::FCMP_OGE;
851 break;
853 if (inputDenormalIsDAZ(F, Ty))
854 return FCmpInst::FCMP_OGE;
855 break;
857 if (inputDenormalIsIEEE(F, Ty))
858 return FCmpInst::FCMP_OGT;
859 break;
860 case fcNegative | fcPosZero:
861 if (inputDenormalIsIEEE(F, Ty))
862 return FCmpInst::FCMP_OLE;
863 break;
865 if (inputDenormalIsDAZ(F, Ty))
866 return FCmpInst::FCMP_OLE;
867 break;
869 if (inputDenormalIsIEEE(F, Ty))
870 return FCmpInst::FCMP_OLT;
871 break;
872 case fcPosNormal | fcPosInf:
873 if (inputDenormalIsDAZ(F, Ty))
874 return FCmpInst::FCMP_OGT;
875 break;
876 case fcNegNormal | fcNegInf:
877 if (inputDenormalIsDAZ(F, Ty))
878 return FCmpInst::FCMP_OLT;
879 break;
880 case ~fcZero & ~fcNan:
881 if (inputDenormalIsIEEE(F, Ty))
882 return FCmpInst::FCMP_ONE;
883 break;
884 case ~(fcZero | fcSubnormal) & ~fcNan:
885 if (inputDenormalIsDAZ(F, Ty))
886 return FCmpInst::FCMP_ONE;
887 break;
888 default:
889 break;
890 }
891
893}
894
895Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {
896 Value *Src0 = II.getArgOperand(0);
897 Value *Src1 = II.getArgOperand(1);
898 const ConstantInt *CMask = cast<ConstantInt>(Src1);
899 FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());
900 const bool IsUnordered = (Mask & fcNan) == fcNan;
901 const bool IsOrdered = (Mask & fcNan) == fcNone;
902 const FPClassTest OrderedMask = Mask & ~fcNan;
903 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
904
905 const bool IsStrict =
906 II.getFunction()->getAttributes().hasFnAttr(Attribute::StrictFP);
907
908 Value *FNegSrc;
909 if (match(Src0, m_FNeg(m_Value(FNegSrc)))) {
910 // is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)
911
912 II.setArgOperand(1, ConstantInt::get(Src1->getType(), fneg(Mask)));
913 return replaceOperand(II, 0, FNegSrc);
914 }
915
916 Value *FAbsSrc;
917 if (match(Src0, m_FAbs(m_Value(FAbsSrc)))) {
918 II.setArgOperand(1, ConstantInt::get(Src1->getType(), inverse_fabs(Mask)));
919 return replaceOperand(II, 0, FAbsSrc);
920 }
921
922 if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&
923 (IsOrdered || IsUnordered) && !IsStrict) {
924 // is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf
925 // is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf
926 // is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf
927 // is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf
931 if (OrderedInvertedMask == fcInf)
932 Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;
933
934 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Src0);
935 Value *CmpInf = Builder.CreateFCmp(Pred, Fabs, Inf);
936 CmpInf->takeName(&II);
937 return replaceInstUsesWith(II, CmpInf);
938 }
939
940 if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&
941 (IsOrdered || IsUnordered) && !IsStrict) {
942 // is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf
943 // is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf
944 // is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf
945 // is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf
946 Constant *Inf =
947 ConstantFP::getInfinity(Src0->getType(), OrderedMask == fcNegInf);
948 Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(Src0, Inf)
949 : Builder.CreateFCmpOEQ(Src0, Inf);
950
951 EqInf->takeName(&II);
952 return replaceInstUsesWith(II, EqInf);
953 }
954
955 if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&
956 (IsOrdered || IsUnordered) && !IsStrict) {
957 // is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf
958 // is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf
959 // is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf
960 // is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf
962 OrderedInvertedMask == fcNegInf);
963 Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(Src0, Inf)
964 : Builder.CreateFCmpONE(Src0, Inf);
965 NeInf->takeName(&II);
966 return replaceInstUsesWith(II, NeInf);
967 }
968
969 if (Mask == fcNan && !IsStrict) {
970 // Equivalent of isnan. Replace with standard fcmp if we don't care about FP
971 // exceptions.
972 Value *IsNan =
974 IsNan->takeName(&II);
975 return replaceInstUsesWith(II, IsNan);
976 }
977
978 if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {
979 // Equivalent of !isnan. Replace with standard fcmp.
980 Value *FCmp =
982 FCmp->takeName(&II);
983 return replaceInstUsesWith(II, FCmp);
984 }
985
987
988 // Try to replace with an fcmp with 0
989 //
990 // is.fpclass(x, fcZero) -> fcmp oeq x, 0.0
991 // is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.0
992 // is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.0
993 // is.fpclass(x, ~fcZero) -> fcmp une x, 0.0
994 //
995 // is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.0
996 // is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.0
997 //
998 // is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.0
999 // is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.0
1000 //
1001 if (!IsStrict && (IsOrdered || IsUnordered) &&
1002 (PredType = fpclassTestIsFCmp0(OrderedMask, *II.getFunction(),
1003 Src0->getType())) !=
1006 // Equivalent of == 0.
1007 Value *FCmp = Builder.CreateFCmp(
1008 IsUnordered ? FCmpInst::getUnorderedPredicate(PredType) : PredType,
1009 Src0, Zero);
1010
1011 FCmp->takeName(&II);
1012 return replaceInstUsesWith(II, FCmp);
1013 }
1014
1015 KnownFPClass Known = computeKnownFPClass(Src0, Mask, &II);
1016
1017 // Clear test bits we know must be false from the source value.
1018 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
1019 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
1020 if ((Mask & Known.KnownFPClasses) != Mask) {
1021 II.setArgOperand(
1022 1, ConstantInt::get(Src1->getType(), Mask & Known.KnownFPClasses));
1023 return &II;
1024 }
1025
1026 // If none of the tests which can return false are possible, fold to true.
1027 // fp_class (nnan x), ~(qnan|snan) -> true
1028 // fp_class (ninf x), ~(ninf|pinf) -> true
1029 if (Mask == Known.KnownFPClasses)
1030 return replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));
1031
1032 return nullptr;
1033}
1034
1035static std::optional<bool> getKnownSign(Value *Op, Instruction *CxtI,
1036 const DataLayout &DL, AssumptionCache *AC,
1037 DominatorTree *DT) {
1038 KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT);
1039 if (Known.isNonNegative())
1040 return false;
1041 if (Known.isNegative())
1042 return true;
1043
1044 Value *X, *Y;
1045 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1047
1049 ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL);
1050}
1051
1052static std::optional<bool> getKnownSignOrZero(Value *Op, Instruction *CxtI,
1053 const DataLayout &DL,
1054 AssumptionCache *AC,
1055 DominatorTree *DT) {
1056 if (std::optional<bool> Sign = getKnownSign(Op, CxtI, DL, AC, DT))
1057 return Sign;
1058
1059 Value *X, *Y;
1060 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))
1062
1063 return std::nullopt;
1064}
1065
1066/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.
1067static bool signBitMustBeTheSame(Value *Op0, Value *Op1, Instruction *CxtI,
1068 const DataLayout &DL, AssumptionCache *AC,
1069 DominatorTree *DT) {
1070 std::optional<bool> Known1 = getKnownSign(Op1, CxtI, DL, AC, DT);
1071 if (!Known1)
1072 return false;
1073 std::optional<bool> Known0 = getKnownSign(Op0, CxtI, DL, AC, DT);
1074 if (!Known0)
1075 return false;
1076 return *Known0 == *Known1;
1077}
1078
1079/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
1080/// can trigger other combines.
1082 InstCombiner::BuilderTy &Builder) {
1083 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1084 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1085 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1086 "Expected a min or max intrinsic");
1087
1088 // TODO: Match vectors with undef elements, but undef may not propagate.
1089 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1090 Value *X;
1091 const APInt *C0, *C1;
1092 if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||
1093 !match(Op1, m_APInt(C1)))
1094 return nullptr;
1095
1096 // Check for necessary no-wrap and overflow constraints.
1097 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1098 auto *Add = cast<BinaryOperator>(Op0);
1099 if ((IsSigned && !Add->hasNoSignedWrap()) ||
1100 (!IsSigned && !Add->hasNoUnsignedWrap()))
1101 return nullptr;
1102
1103 // If the constant difference overflows, then instsimplify should reduce the
1104 // min/max to the add or C1.
1105 bool Overflow;
1106 APInt CDiff =
1107 IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);
1108 assert(!Overflow && "Expected simplify of min/max");
1109
1110 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0
1111 // Note: the "mismatched" no-overflow setting does not propagate.
1112 Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);
1113 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);
1114 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))
1115 : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));
1116}
1117/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
1118Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {
1119 Type *Ty = MinMax1.getType();
1120
1121 // We are looking for a tree of:
1122 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
1123 // Where the min and max could be reversed
1124 Instruction *MinMax2;
1126 const APInt *MinValue, *MaxValue;
1127 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
1128 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
1129 return nullptr;
1130 } else if (match(&MinMax1,
1131 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
1132 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
1133 return nullptr;
1134 } else
1135 return nullptr;
1136
1137 // Check that the constants clamp a saturate, and that the new type would be
1138 // sensible to convert to.
1139 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1140 return nullptr;
1141 // In what bitwidth can this be treated as saturating arithmetics?
1142 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1143 // FIXME: This isn't quite right for vectors, but using the scalar type is a
1144 // good first approximation for what should be done there.
1145 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
1146 return nullptr;
1147
1148 // Also make sure that the inner min/max and the add/sub have one use.
1149 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())
1150 return nullptr;
1151
1152 // Create the new type (which can be a vector type)
1153 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
1154
1155 Intrinsic::ID IntrinsicID;
1156 if (AddSub->getOpcode() == Instruction::Add)
1157 IntrinsicID = Intrinsic::sadd_sat;
1158 else if (AddSub->getOpcode() == Instruction::Sub)
1159 IntrinsicID = Intrinsic::ssub_sat;
1160 else
1161 return nullptr;
1162
1163 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This
1164 // is usually achieved via a sext from a smaller type.
1165 if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >
1166 NewBitWidth ||
1167 ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)
1168 return nullptr;
1169
1170 // Finally create and return the sat intrinsic, truncated to the new type
1171 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
1172 Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);
1173 Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);
1174 Value *Sat = Builder.CreateCall(F, {AT, BT});
1175 return CastInst::Create(Instruction::SExt, Sat, Ty);
1176}
1177
1178
1179/// If we have a clamp pattern like max (min X, 42), 41 -- where the output
1180/// can only be one of two possible constant values -- turn that into a select
1181/// of constants.
1183 InstCombiner::BuilderTy &Builder) {
1184 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1185 Value *X;
1186 const APInt *C0, *C1;
1187 if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())
1188 return nullptr;
1189
1191 switch (II->getIntrinsicID()) {
1192 case Intrinsic::smax:
1193 if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1194 Pred = ICmpInst::ICMP_SGT;
1195 break;
1196 case Intrinsic::smin:
1197 if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1198 Pred = ICmpInst::ICMP_SLT;
1199 break;
1200 case Intrinsic::umax:
1201 if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)
1202 Pred = ICmpInst::ICMP_UGT;
1203 break;
1204 case Intrinsic::umin:
1205 if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)
1206 Pred = ICmpInst::ICMP_ULT;
1207 break;
1208 default:
1209 llvm_unreachable("Expected min/max intrinsic");
1210 }
1211 if (Pred == CmpInst::BAD_ICMP_PREDICATE)
1212 return nullptr;
1213
1214 // max (min X, 42), 41 --> X > 41 ? 42 : 41
1215 // min (max X, 42), 43 --> X < 43 ? 42 : 43
1216 Value *Cmp = Builder.CreateICmp(Pred, X, I1);
1217 return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);
1218}
1219
1220/// If this min/max has a constant operand and an operand that is a matching
1221/// min/max with a constant operand, constant-fold the 2 constant operands.
1223 IRBuilderBase &Builder,
1224 const SimplifyQuery &SQ) {
1225 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1226 auto *LHS = dyn_cast<MinMaxIntrinsic>(II->getArgOperand(0));
1227 if (!LHS)
1228 return nullptr;
1229
1230 Constant *C0, *C1;
1231 if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||
1232 !match(II->getArgOperand(1), m_ImmConstant(C1)))
1233 return nullptr;
1234
1235 // max (max X, C0), C1 --> max X, (max C0, C1)
1236 // min (min X, C0), C1 --> min X, (min C0, C1)
1237 // umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)
1238 // smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)
1239 Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();
1240 if (InnerMinMaxID != MinMaxID &&
1241 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1242 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1243 isKnownNonNegative(C0, SQ) && isKnownNonNegative(C1, SQ)))
1244 return nullptr;
1245
1247 Value *CondC = Builder.CreateICmp(Pred, C0, C1);
1248 Value *NewC = Builder.CreateSelect(CondC, C0, C1);
1249 return Builder.CreateIntrinsic(InnerMinMaxID, II->getType(),
1250 {LHS->getArgOperand(0), NewC});
1251}
1252
1253/// If this min/max has a matching min/max operand with a constant, try to push
1254/// the constant operand into this instruction. This can enable more folds.
1255static Instruction *
1257 InstCombiner::BuilderTy &Builder) {
1258 // Match and capture a min/max operand candidate.
1259 Value *X, *Y;
1260 Constant *C;
1261 Instruction *Inner;
1263 m_Instruction(Inner),
1265 m_Value(Y))))
1266 return nullptr;
1267
1268 // The inner op must match. Check for constants to avoid infinite loops.
1269 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1270 auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);
1271 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1273 return nullptr;
1274
1275 // max (max X, C), Y --> max (max X, Y), C
1276 Function *MinMax =
1277 Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType());
1278 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);
1279 NewInner->takeName(Inner);
1280 return CallInst::Create(MinMax, {NewInner, C});
1281}
1282
1283/// Reduce a sequence of min/max intrinsics with a common operand.
1285 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1286 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1287 auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));
1288 Intrinsic::ID MinMaxID = II->getIntrinsicID();
1289 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||
1290 RHS->getIntrinsicID() != MinMaxID ||
1291 (!LHS->hasOneUse() && !RHS->hasOneUse()))
1292 return nullptr;
1293
1294 Value *A = LHS->getArgOperand(0);
1295 Value *B = LHS->getArgOperand(1);
1296 Value *C = RHS->getArgOperand(0);
1297 Value *D = RHS->getArgOperand(1);
1298
1299 // Look for a common operand.
1300 Value *MinMaxOp = nullptr;
1301 Value *ThirdOp = nullptr;
1302 if (LHS->hasOneUse()) {
1303 // If the LHS is only used in this chain and the RHS is used outside of it,
1304 // reuse the RHS min/max because that will eliminate the LHS.
1305 if (D == A || C == A) {
1306 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1307 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1308 MinMaxOp = RHS;
1309 ThirdOp = B;
1310 } else if (D == B || C == B) {
1311 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1312 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1313 MinMaxOp = RHS;
1314 ThirdOp = A;
1315 }
1316 } else {
1317 assert(RHS->hasOneUse() && "Expected one-use operand");
1318 // Reuse the LHS. This will eliminate the RHS.
1319 if (D == A || D == B) {
1320 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1321 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1322 MinMaxOp = LHS;
1323 ThirdOp = C;
1324 } else if (C == A || C == B) {
1325 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1326 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1327 MinMaxOp = LHS;
1328 ThirdOp = D;
1329 }
1330 }
1331
1332 if (!MinMaxOp || !ThirdOp)
1333 return nullptr;
1334
1335 Module *Mod = II->getModule();
1337 return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });
1338}
1339
1340/// If all arguments of the intrinsic are unary shuffles with the same mask,
1341/// try to shuffle after the intrinsic.
1342static Instruction *
1344 InstCombiner::BuilderTy &Builder) {
1345 // TODO: This should be extended to handle other intrinsics like fshl, ctpop,
1346 // etc. Use llvm::isTriviallyVectorizable() and related to determine
1347 // which intrinsics are safe to shuffle?
1348 switch (II->getIntrinsicID()) {
1349 case Intrinsic::smax:
1350 case Intrinsic::smin:
1351 case Intrinsic::umax:
1352 case Intrinsic::umin:
1353 case Intrinsic::fma:
1354 case Intrinsic::fshl:
1355 case Intrinsic::fshr:
1356 break;
1357 default:
1358 return nullptr;
1359 }
1360
1361 Value *X;
1362 ArrayRef<int> Mask;
1363 if (!match(II->getArgOperand(0),
1364 m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))
1365 return nullptr;
1366
1367 // At least 1 operand must have 1 use because we are creating 2 instructions.
1368 if (none_of(II->args(), [](Value *V) { return V->hasOneUse(); }))
1369 return nullptr;
1370
1371 // See if all arguments are shuffled with the same mask.
1372 SmallVector<Value *, 4> NewArgs(II->arg_size());
1373 NewArgs[0] = X;
1374 Type *SrcTy = X->getType();
1375 for (unsigned i = 1, e = II->arg_size(); i != e; ++i) {
1376 if (!match(II->getArgOperand(i),
1377 m_Shuffle(m_Value(X), m_Undef(), m_SpecificMask(Mask))) ||
1378 X->getType() != SrcTy)
1379 return nullptr;
1380 NewArgs[i] = X;
1381 }
1382
1383 // intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M
1384 Instruction *FPI = isa<FPMathOperator>(II) ? II : nullptr;
1385 Value *NewIntrinsic =
1386 Builder.CreateIntrinsic(II->getIntrinsicID(), SrcTy, NewArgs, FPI);
1387 return new ShuffleVectorInst(NewIntrinsic, Mask);
1388}
1389
1390/// Fold the following cases and accepts bswap and bitreverse intrinsics:
1391/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))
1392/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)
1393template <Intrinsic::ID IntrID>
1395 InstCombiner::BuilderTy &Builder) {
1396 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1397 "This helper only supports BSWAP and BITREVERSE intrinsics");
1398
1399 Value *X, *Y;
1400 // Find bitwise logic op. Check that it is a BinaryOperator explicitly so we
1401 // don't match ConstantExpr that aren't meaningful for this transform.
1403 isa<BinaryOperator>(V)) {
1404 Value *OldReorderX, *OldReorderY;
1405 BinaryOperator::BinaryOps Op = cast<BinaryOperator>(V)->getOpcode();
1406
1407 // If both X and Y are bswap/bitreverse, the transform reduces the number
1408 // of instructions even if there's multiuse.
1409 // If only one operand is bswap/bitreverse, we need to ensure the operand
1410 // have only one use.
1411 if (match(X, m_Intrinsic<IntrID>(m_Value(OldReorderX))) &&
1412 match(Y, m_Intrinsic<IntrID>(m_Value(OldReorderY)))) {
1413 return BinaryOperator::Create(Op, OldReorderX, OldReorderY);
1414 }
1415
1416 if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderX))))) {
1417 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, Y);
1418 return BinaryOperator::Create(Op, OldReorderX, NewReorder);
1419 }
1420
1421 if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderY))))) {
1422 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, X);
1423 return BinaryOperator::Create(Op, NewReorder, OldReorderY);
1424 }
1425 }
1426 return nullptr;
1427}
1428
1429/// CallInst simplification. This mostly only handles folding of intrinsic
1430/// instructions. For normal calls, it allows visitCallBase to do the heavy
1431/// lifting.
1433 // Don't try to simplify calls without uses. It will not do anything useful,
1434 // but will result in the following folds being skipped.
1435 if (!CI.use_empty()) {
1437 Args.reserve(CI.arg_size());
1438 for (Value *Op : CI.args())
1439 Args.push_back(Op);
1440 if (Value *V = simplifyCall(&CI, CI.getCalledOperand(), Args,
1441 SQ.getWithInstruction(&CI)))
1442 return replaceInstUsesWith(CI, V);
1443 }
1444
1445 if (Value *FreedOp = getFreedOperand(&CI, &TLI))
1446 return visitFree(CI, FreedOp);
1447
1448 // If the caller function (i.e. us, the function that contains this CallInst)
1449 // is nounwind, mark the call as nounwind, even if the callee isn't.
1450 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1451 CI.setDoesNotThrow();
1452 return &CI;
1453 }
1454
1455 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1456 if (!II) return visitCallBase(CI);
1457
1458 // For atomic unordered mem intrinsics if len is not a positive or
1459 // not a multiple of element size then behavior is undefined.
1460 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))
1461 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))
1462 if (NumBytes->isNegative() ||
1463 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {
1465 assert(AMI->getType()->isVoidTy() &&
1466 "non void atomic unordered mem intrinsic");
1467 return eraseInstFromFunction(*AMI);
1468 }
1469
1470 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1471 // instead of in visitCallBase.
1472 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1473 bool Changed = false;
1474
1475 // memmove/cpy/set of zero bytes is a noop.
1476 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1477 if (NumBytes->isNullValue())
1478 return eraseInstFromFunction(CI);
1479 }
1480
1481 // No other transformations apply to volatile transfers.
1482 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1483 if (M->isVolatile())
1484 return nullptr;
1485
1486 // If we have a memmove and the source operation is a constant global,
1487 // then the source and dest pointers can't alias, so we can change this
1488 // into a call to memcpy.
1489 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1490 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1491 if (GVSrc->isConstant()) {
1492 Module *M = CI.getModule();
1493 Intrinsic::ID MemCpyID =
1494 isa<AtomicMemMoveInst>(MMI)
1495 ? Intrinsic::memcpy_element_unordered_atomic
1496 : Intrinsic::memcpy;
1497 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1498 CI.getArgOperand(1)->getType(),
1499 CI.getArgOperand(2)->getType() };
1500 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1501 Changed = true;
1502 }
1503 }
1504
1505 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1506 // memmove(x,x,size) -> noop.
1507 if (MTI->getSource() == MTI->getDest())
1508 return eraseInstFromFunction(CI);
1509 }
1510
1511 // If we can determine a pointer alignment that is bigger than currently
1512 // set, update the alignment.
1513 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1515 return I;
1516 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1517 if (Instruction *I = SimplifyAnyMemSet(MSI))
1518 return I;
1519 }
1520
1521 if (Changed) return II;
1522 }
1523
1524 // For fixed width vector result intrinsics, use the generic demanded vector
1525 // support.
1526 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {
1527 auto VWidth = IIFVTy->getNumElements();
1528 APInt PoisonElts(VWidth, 0);
1529 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1530 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, PoisonElts)) {
1531 if (V != II)
1532 return replaceInstUsesWith(*II, V);
1533 return II;
1534 }
1535 }
1536
1537 if (II->isCommutative()) {
1538 if (auto Pair = matchSymmetricPair(II->getOperand(0), II->getOperand(1))) {
1539 replaceOperand(*II, 0, Pair->first);
1540 replaceOperand(*II, 1, Pair->second);
1541 return II;
1542 }
1543
1544 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))
1545 return NewCall;
1546 }
1547
1548 // Unused constrained FP intrinsic calls may have declared side effect, which
1549 // prevents it from being removed. In some cases however the side effect is
1550 // actually absent. To detect this case, call SimplifyConstrainedFPCall. If it
1551 // returns a replacement, the call may be removed.
1552 if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(CI)) {
1554 return eraseInstFromFunction(CI);
1555 }
1556
1557 Intrinsic::ID IID = II->getIntrinsicID();
1558 switch (IID) {
1559 case Intrinsic::objectsize: {
1560 SmallVector<Instruction *> InsertedInstructions;
1561 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false,
1562 &InsertedInstructions)) {
1563 for (Instruction *Inserted : InsertedInstructions)
1564 Worklist.add(Inserted);
1565 return replaceInstUsesWith(CI, V);
1566 }
1567 return nullptr;
1568 }
1569 case Intrinsic::abs: {
1570 Value *IIOperand = II->getArgOperand(0);
1571 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
1572
1573 // abs(-x) -> abs(x)
1574 // TODO: Copy nsw if it was present on the neg?
1575 Value *X;
1576 if (match(IIOperand, m_Neg(m_Value(X))))
1577 return replaceOperand(*II, 0, X);
1578 if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
1579 return replaceOperand(*II, 0, X);
1580 if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
1581 return replaceOperand(*II, 0, X);
1582
1583 Value *Y;
1584 // abs(a * abs(b)) -> abs(a * b)
1585 if (match(IIOperand,
1587 m_Intrinsic<Intrinsic::abs>(m_Value(Y)))))) {
1588 bool NSW =
1589 cast<Instruction>(IIOperand)->hasNoSignedWrap() && IntMinIsPoison;
1590 auto *XY = NSW ? Builder.CreateNSWMul(X, Y) : Builder.CreateMul(X, Y);
1591 return replaceOperand(*II, 0, XY);
1592 }
1593
1594 if (std::optional<bool> Known =
1595 getKnownSignOrZero(IIOperand, II, DL, &AC, &DT)) {
1596 // abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)
1597 // abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)
1598 if (!*Known)
1599 return replaceInstUsesWith(*II, IIOperand);
1600
1601 // abs(x) -> -x if x < 0
1602 // abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)
1603 if (IntMinIsPoison)
1604 return BinaryOperator::CreateNSWNeg(IIOperand);
1605 return BinaryOperator::CreateNeg(IIOperand);
1606 }
1607
1608 // abs (sext X) --> zext (abs X*)
1609 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing.
1610 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {
1611 Value *NarrowAbs =
1612 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());
1613 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());
1614 }
1615
1616 // Match a complicated way to check if a number is odd/even:
1617 // abs (srem X, 2) --> and X, 1
1618 const APInt *C;
1619 if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)
1620 return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));
1621
1622 break;
1623 }
1624 case Intrinsic::umin: {
1625 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1626 // umin(x, 1) == zext(x != 0)
1627 if (match(I1, m_One())) {
1628 assert(II->getType()->getScalarSizeInBits() != 1 &&
1629 "Expected simplify of umin with max constant");
1630 Value *Zero = Constant::getNullValue(I0->getType());
1631 Value *Cmp = Builder.CreateICmpNE(I0, Zero);
1632 return CastInst::Create(Instruction::ZExt, Cmp, II->getType());
1633 }
1634 [[fallthrough]];
1635 }
1636 case Intrinsic::umax: {
1637 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1638 Value *X, *Y;
1639 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&
1640 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1641 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1642 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1643 }
1644 Constant *C;
1645 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1646 I0->hasOneUse()) {
1647 if (Constant *NarrowC = getLosslessUnsignedTrunc(C, X->getType())) {
1648 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1649 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());
1650 }
1651 }
1652 // If both operands of unsigned min/max are sign-extended, it is still ok
1653 // to narrow the operation.
1654 [[fallthrough]];
1655 }
1656 case Intrinsic::smax:
1657 case Intrinsic::smin: {
1658 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);
1659 Value *X, *Y;
1660 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&
1661 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {
1662 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);
1663 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1664 }
1665
1666 Constant *C;
1667 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&
1668 I0->hasOneUse()) {
1669 if (Constant *NarrowC = getLosslessSignedTrunc(C, X->getType())) {
1670 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);
1671 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());
1672 }
1673 }
1674
1675 // umin(i1 X, i1 Y) -> and i1 X, Y
1676 // smax(i1 X, i1 Y) -> and i1 X, Y
1677 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
1678 II->getType()->isIntOrIntVectorTy(1)) {
1679 return BinaryOperator::CreateAnd(I0, I1);
1680 }
1681
1682 // umax(i1 X, i1 Y) -> or i1 X, Y
1683 // smin(i1 X, i1 Y) -> or i1 X, Y
1684 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
1685 II->getType()->isIntOrIntVectorTy(1)) {
1686 return BinaryOperator::CreateOr(I0, I1);
1687 }
1688
1689 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1690 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)
1691 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)
1692 // TODO: Canonicalize neg after min/max if I1 is constant.
1693 if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&
1694 (I0->hasOneUse() || I1->hasOneUse())) {
1696 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);
1697 return BinaryOperator::CreateNSWNeg(InvMaxMin);
1698 }
1699 }
1700
1701 // (umax X, (xor X, Pow2))
1702 // -> (or X, Pow2)
1703 // (umin X, (xor X, Pow2))
1704 // -> (and X, ~Pow2)
1705 // (smax X, (xor X, Pos_Pow2))
1706 // -> (or X, Pos_Pow2)
1707 // (smin X, (xor X, Pos_Pow2))
1708 // -> (and X, ~Pos_Pow2)
1709 // (smax X, (xor X, Neg_Pow2))
1710 // -> (and X, ~Neg_Pow2)
1711 // (smin X, (xor X, Neg_Pow2))
1712 // -> (or X, Neg_Pow2)
1713 if ((match(I0, m_c_Xor(m_Specific(I1), m_Value(X))) ||
1714 match(I1, m_c_Xor(m_Specific(I0), m_Value(X)))) &&
1715 isKnownToBeAPowerOfTwo(X, /* OrZero */ true)) {
1716 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
1717 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
1718
1719 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
1720 auto KnownSign = getKnownSign(X, II, DL, &AC, &DT);
1721 if (KnownSign == std::nullopt) {
1722 UseOr = false;
1723 UseAndN = false;
1724 } else if (*KnownSign /* true is Signed. */) {
1725 UseOr ^= true;
1726 UseAndN ^= true;
1727 Type *Ty = I0->getType();
1728 // Negative power of 2 must be IntMin. It's possible to be able to
1729 // prove negative / power of 2 without actually having known bits, so
1730 // just get the value by hand.
1733 }
1734 }
1735 if (UseOr)
1736 return BinaryOperator::CreateOr(I0, X);
1737 else if (UseAndN)
1738 return BinaryOperator::CreateAnd(I0, Builder.CreateNot(X));
1739 }
1740
1741 // If we can eliminate ~A and Y is free to invert:
1742 // max ~A, Y --> ~(min A, ~Y)
1743 //
1744 // Examples:
1745 // max ~A, ~Y --> ~(min A, Y)
1746 // max ~A, C --> ~(min A, ~C)
1747 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))
1748 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1749 Value *A;
1750 if (match(X, m_OneUse(m_Not(m_Value(A)))) &&
1751 !isFreeToInvert(A, A->hasOneUse())) {
1752 if (Value *NotY = getFreelyInverted(Y, Y->hasOneUse(), &Builder)) {
1754 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);
1755 return BinaryOperator::CreateNot(InvMaxMin);
1756 }
1757 }
1758 return nullptr;
1759 };
1760
1761 if (Instruction *I = moveNotAfterMinMax(I0, I1))
1762 return I;
1763 if (Instruction *I = moveNotAfterMinMax(I1, I0))
1764 return I;
1765
1767 return I;
1768
1769 // smax(X, -X) --> abs(X)
1770 // smin(X, -X) --> -abs(X)
1771 // umax(X, -X) --> -abs(X)
1772 // umin(X, -X) --> abs(X)
1773 if (isKnownNegation(I0, I1)) {
1774 // We can choose either operand as the input to abs(), but if we can
1775 // eliminate the only use of a value, that's better for subsequent
1776 // transforms/analysis.
1777 if (I0->hasOneUse() && !I1->hasOneUse())
1778 std::swap(I0, I1);
1779
1780 // This is some variant of abs(). See if we can propagate 'nsw' to the abs
1781 // operation and potentially its negation.
1782 bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);
1784 Intrinsic::abs, I0,
1785 ConstantInt::getBool(II->getContext(), IntMinIsPoison));
1786
1787 // We don't have a "nabs" intrinsic, so negate if needed based on the
1788 // max/min operation.
1789 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
1790 Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison);
1791 return replaceInstUsesWith(CI, Abs);
1792 }
1793
1794 if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))
1795 return Sel;
1796
1797 if (Instruction *SAdd = matchSAddSubSat(*II))
1798 return SAdd;
1799
1800 if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))
1801 return replaceInstUsesWith(*II, NewMinMax);
1802
1804 return R;
1805
1806 if (Instruction *NewMinMax = factorizeMinMaxTree(II))
1807 return NewMinMax;
1808
1809 // Try to fold minmax with constant RHS based on range information
1810 const APInt *RHSC;
1811 if (match(I1, m_APIntAllowUndef(RHSC))) {
1812 ICmpInst::Predicate Pred =
1814 bool IsSigned = MinMaxIntrinsic::isSigned(IID);
1816 I0, IsSigned, SQ.getWithInstruction(II));
1817 if (!LHS_CR.isFullSet()) {
1818 if (LHS_CR.icmp(Pred, *RHSC))
1819 return replaceInstUsesWith(*II, I0);
1820 if (LHS_CR.icmp(ICmpInst::getSwappedPredicate(Pred), *RHSC))
1821 return replaceInstUsesWith(*II,
1822 ConstantInt::get(II->getType(), *RHSC));
1823 }
1824 }
1825
1826 break;
1827 }
1828 case Intrinsic::bitreverse: {
1829 Value *IIOperand = II->getArgOperand(0);
1830 // bitrev (zext i1 X to ?) --> X ? SignBitC : 0
1831 Value *X;
1832 if (match(IIOperand, m_ZExt(m_Value(X))) &&
1833 X->getType()->isIntOrIntVectorTy(1)) {
1834 Type *Ty = II->getType();
1836 return SelectInst::Create(X, ConstantInt::get(Ty, SignBit),
1838 }
1839
1840 if (Instruction *crossLogicOpFold =
1841 foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(IIOperand, Builder))
1842 return crossLogicOpFold;
1843
1844 break;
1845 }
1846 case Intrinsic::bswap: {
1847 Value *IIOperand = II->getArgOperand(0);
1848
1849 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
1850 // inverse-shift-of-bswap:
1851 // bswap (shl X, Y) --> lshr (bswap X), Y
1852 // bswap (lshr X, Y) --> shl (bswap X), Y
1853 Value *X, *Y;
1854 if (match(IIOperand, m_OneUse(m_LogicalShift(m_Value(X), m_Value(Y))))) {
1855 // The transform allows undef vector elements, so try a constant match
1856 // first. If knownbits can handle that case, that clause could be removed.
1857 unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();
1858 const APInt *C;
1859 if ((match(Y, m_APIntAllowUndef(C)) && (*C & 7) == 0) ||
1861 Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1862 BinaryOperator::BinaryOps InverseShift =
1863 cast<BinaryOperator>(IIOperand)->getOpcode() == Instruction::Shl
1864 ? Instruction::LShr
1865 : Instruction::Shl;
1866 return BinaryOperator::Create(InverseShift, NewSwap, Y);
1867 }
1868 }
1869
1870 KnownBits Known = computeKnownBits(IIOperand, 0, II);
1871 uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);
1872 uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);
1873 unsigned BW = Known.getBitWidth();
1874
1875 // bswap(x) -> shift(x) if x has exactly one "active byte"
1876 if (BW - LZ - TZ == 8) {
1877 assert(LZ != TZ && "active byte cannot be in the middle");
1878 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x
1879 return BinaryOperator::CreateNUWShl(
1880 IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));
1881 // -> lshr(x) if the "active byte" is in the high part of x
1882 return BinaryOperator::CreateExactLShr(
1883 IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));
1884 }
1885
1886 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1887 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1888 unsigned C = X->getType()->getScalarSizeInBits() - BW;
1889 Value *CV = ConstantInt::get(X->getType(), C);
1890 Value *V = Builder.CreateLShr(X, CV);
1891 return new TruncInst(V, IIOperand->getType());
1892 }
1893
1894 if (Instruction *crossLogicOpFold =
1895 foldBitOrderCrossLogicOp<Intrinsic::bswap>(IIOperand, Builder)) {
1896 return crossLogicOpFold;
1897 }
1898
1899 // Try to fold into bitreverse if bswap is the root of the expression tree.
1900 if (Instruction *BitOp = matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ false,
1901 /*MatchBitReversals*/ true))
1902 return BitOp;
1903 break;
1904 }
1905 case Intrinsic::masked_load:
1906 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
1907 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1908 break;
1909 case Intrinsic::masked_store:
1910 return simplifyMaskedStore(*II);
1911 case Intrinsic::masked_gather:
1912 return simplifyMaskedGather(*II);
1913 case Intrinsic::masked_scatter:
1914 return simplifyMaskedScatter(*II);
1915 case Intrinsic::launder_invariant_group:
1916 case Intrinsic::strip_invariant_group:
1917 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1918 return replaceInstUsesWith(*II, SkippedBarrier);
1919 break;
1920 case Intrinsic::powi:
1921 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1922 // 0 and 1 are handled in instsimplify
1923 // powi(x, -1) -> 1/x
1924 if (Power->isMinusOne())
1925 return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),
1926 II->getArgOperand(0), II);
1927 // powi(x, 2) -> x*x
1928 if (Power->equalsInt(2))
1930 II->getArgOperand(0), II);
1931
1932 if (!Power->getValue()[0]) {
1933 Value *X;
1934 // If power is even:
1935 // powi(-x, p) -> powi(x, p)
1936 // powi(fabs(x), p) -> powi(x, p)
1937 // powi(copysign(x, y), p) -> powi(x, p)
1938 if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||
1939 match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||
1940 match(II->getArgOperand(0),
1941 m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))
1942 return replaceOperand(*II, 0, X);
1943 }
1944 }
1945 break;
1946
1947 case Intrinsic::cttz:
1948 case Intrinsic::ctlz:
1949 if (auto *I = foldCttzCtlz(*II, *this))
1950 return I;
1951 break;
1952
1953 case Intrinsic::ctpop:
1954 if (auto *I = foldCtpop(*II, *this))
1955 return I;
1956 break;
1957
1958 case Intrinsic::fshl:
1959 case Intrinsic::fshr: {
1960 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1961 Type *Ty = II->getType();
1962 unsigned BitWidth = Ty->getScalarSizeInBits();
1963 Constant *ShAmtC;
1964 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC))) {
1965 // Canonicalize a shift amount constant operand to modulo the bit-width.
1966 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
1967 Constant *ModuloC =
1968 ConstantFoldBinaryOpOperands(Instruction::URem, ShAmtC, WidthC, DL);
1969 if (!ModuloC)
1970 return nullptr;
1971 if (ModuloC != ShAmtC)
1972 return replaceOperand(*II, 2, ModuloC);
1973
1976 "Shift amount expected to be modulo bitwidth");
1977
1978 // Canonicalize funnel shift right by constant to funnel shift left. This
1979 // is not entirely arbitrary. For historical reasons, the backend may
1980 // recognize rotate left patterns but miss rotate right patterns.
1981 if (IID == Intrinsic::fshr) {
1982 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
1983 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1984 Module *Mod = II->getModule();
1985 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
1986 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
1987 }
1988 assert(IID == Intrinsic::fshl &&
1989 "All funnel shifts by simple constants should go left");
1990
1991 // fshl(X, 0, C) --> shl X, C
1992 // fshl(X, undef, C) --> shl X, C
1993 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1994 return BinaryOperator::CreateShl(Op0, ShAmtC);
1995
1996 // fshl(0, X, C) --> lshr X, (BW-C)
1997 // fshl(undef, X, C) --> lshr X, (BW-C)
1998 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1999 return BinaryOperator::CreateLShr(Op1,
2000 ConstantExpr::getSub(WidthC, ShAmtC));
2001
2002 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
2003 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
2004 Module *Mod = II->getModule();
2005 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
2006 return CallInst::Create(Bswap, { Op0 });
2007 }
2008 if (Instruction *BitOp =
2009 matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ true,
2010 /*MatchBitReversals*/ true))
2011 return BitOp;
2012 }
2013
2014 // Left or right might be masked.
2016 return &CI;
2017
2018 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2019 // so only the low bits of the shift amount are demanded if the bitwidth is
2020 // a power-of-2.
2021 if (!isPowerOf2_32(BitWidth))
2022 break;
2024 KnownBits Op2Known(BitWidth);
2025 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2026 return &CI;
2027 break;
2028 }
2029 case Intrinsic::ptrmask: {
2030 unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());
2031 KnownBits Known(BitWidth);
2032 if (SimplifyDemandedInstructionBits(*II, Known))
2033 return II;
2034
2035 Value *InnerPtr, *InnerMask;
2036 bool Changed = false;
2037 // Combine:
2038 // (ptrmask (ptrmask p, A), B)
2039 // -> (ptrmask p, (and A, B))
2040 if (match(II->getArgOperand(0),
2041 m_OneUse(m_Intrinsic<Intrinsic::ptrmask>(m_Value(InnerPtr),
2042 m_Value(InnerMask))))) {
2043 assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&
2044 "Mask types must match");
2045 // TODO: If InnerMask == Op1, we could copy attributes from inner
2046 // callsite -> outer callsite.
2047 Value *NewMask = Builder.CreateAnd(II->getArgOperand(1), InnerMask);
2048 replaceOperand(CI, 0, InnerPtr);
2049 replaceOperand(CI, 1, NewMask);
2050 Changed = true;
2051 }
2052
2053 // See if we can deduce non-null.
2054 if (!CI.hasRetAttr(Attribute::NonNull) &&
2055 (Known.isNonZero() ||
2056 isKnownNonZero(II, DL, /*Depth*/ 0, &AC, II, &DT))) {
2057 CI.addRetAttr(Attribute::NonNull);
2058 Changed = true;
2059 }
2060
2061 unsigned NewAlignmentLog =
2063 std::min(BitWidth - 1, Known.countMinTrailingZeros()));
2064 // Known bits will capture if we had alignment information associated with
2065 // the pointer argument.
2066 if (NewAlignmentLog > Log2(CI.getRetAlign().valueOrOne())) {
2068 CI.getContext(), Align(uint64_t(1) << NewAlignmentLog)));
2069 Changed = true;
2070 }
2071 if (Changed)
2072 return &CI;
2073 break;
2074 }
2075 case Intrinsic::uadd_with_overflow:
2076 case Intrinsic::sadd_with_overflow: {
2077 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2078 return I;
2079
2080 // Given 2 constant operands whose sum does not overflow:
2081 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
2082 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2083 Value *X;
2084 const APInt *C0, *C1;
2085 Value *Arg0 = II->getArgOperand(0);
2086 Value *Arg1 = II->getArgOperand(1);
2087 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2088 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2089 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2090 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
2091 bool Overflow;
2092 APInt NewC =
2093 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
2094 if (!Overflow)
2095 return replaceInstUsesWith(
2097 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
2098 }
2099 break;
2100 }
2101
2102 case Intrinsic::umul_with_overflow:
2103 case Intrinsic::smul_with_overflow:
2104 case Intrinsic::usub_with_overflow:
2105 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2106 return I;
2107 break;
2108
2109 case Intrinsic::ssub_with_overflow: {
2110 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2111 return I;
2112
2113 Constant *C;
2114 Value *Arg0 = II->getArgOperand(0);
2115 Value *Arg1 = II->getArgOperand(1);
2116 // Given a constant C that is not the minimum signed value
2117 // for an integer of a given bit width:
2118 //
2119 // ssubo X, C -> saddo X, -C
2120 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2121 Value *NegVal = ConstantExpr::getNeg(C);
2122 // Build a saddo call that is equivalent to the discovered
2123 // ssubo call.
2124 return replaceInstUsesWith(
2125 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2126 Arg0, NegVal));
2127 }
2128
2129 break;
2130 }
2131
2132 case Intrinsic::uadd_sat:
2133 case Intrinsic::sadd_sat:
2134 case Intrinsic::usub_sat:
2135 case Intrinsic::ssub_sat: {
2136 SaturatingInst *SI = cast<SaturatingInst>(II);
2137 Type *Ty = SI->getType();
2138 Value *Arg0 = SI->getLHS();
2139 Value *Arg1 = SI->getRHS();
2140
2141 // Make use of known overflow information.
2142 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2143 Arg0, Arg1, SI);
2144 switch (OR) {
2146 break;
2148 if (SI->isSigned())
2149 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2150 else
2151 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
2153 unsigned BitWidth = Ty->getScalarSizeInBits();
2154 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2155 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2156 }
2158 unsigned BitWidth = Ty->getScalarSizeInBits();
2159 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2160 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2161 }
2162 }
2163
2164 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2165 Constant *C;
2166 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2167 C->isNotMinSignedValue()) {
2168 Value *NegVal = ConstantExpr::getNeg(C);
2169 return replaceInstUsesWith(
2171 Intrinsic::sadd_sat, Arg0, NegVal));
2172 }
2173
2174 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2175 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2176 // if Val and Val2 have the same sign
2177 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2178 Value *X;
2179 const APInt *Val, *Val2;
2180 APInt NewVal;
2181 bool IsUnsigned =
2182 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2183 if (Other->getIntrinsicID() == IID &&
2184 match(Arg1, m_APInt(Val)) &&
2185 match(Other->getArgOperand(0), m_Value(X)) &&
2186 match(Other->getArgOperand(1), m_APInt(Val2))) {
2187 if (IsUnsigned)
2188 NewVal = Val->uadd_sat(*Val2);
2189 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2190 bool Overflow;
2191 NewVal = Val->sadd_ov(*Val2, Overflow);
2192 if (Overflow) {
2193 // Both adds together may add more than SignedMaxValue
2194 // without saturating the final result.
2195 break;
2196 }
2197 } else {
2198 // Cannot fold saturated addition with different signs.
2199 break;
2200 }
2201
2202 return replaceInstUsesWith(
2204 IID, X, ConstantInt::get(II->getType(), NewVal)));
2205 }
2206 }
2207 break;
2208 }
2209
2210 case Intrinsic::minnum:
2211 case Intrinsic::maxnum:
2212 case Intrinsic::minimum:
2213 case Intrinsic::maximum: {
2214 Value *Arg0 = II->getArgOperand(0);
2215 Value *Arg1 = II->getArgOperand(1);
2216 Value *X, *Y;
2217 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2218 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2219 // If both operands are negated, invert the call and negate the result:
2220 // min(-X, -Y) --> -(max(X, Y))
2221 // max(-X, -Y) --> -(min(X, Y))
2222 Intrinsic::ID NewIID;
2223 switch (IID) {
2224 case Intrinsic::maxnum:
2225 NewIID = Intrinsic::minnum;
2226 break;
2227 case Intrinsic::minnum:
2228 NewIID = Intrinsic::maxnum;
2229 break;
2230 case Intrinsic::maximum:
2231 NewIID = Intrinsic::minimum;
2232 break;
2233 case Intrinsic::minimum:
2234 NewIID = Intrinsic::maximum;
2235 break;
2236 default:
2237 llvm_unreachable("unexpected intrinsic ID");
2238 }
2239 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2240 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
2241 FNeg->copyIRFlags(II);
2242 return FNeg;
2243 }
2244
2245 // m(m(X, C2), C1) -> m(X, C)
2246 const APFloat *C1, *C2;
2247 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2248 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2249 ((match(M->getArgOperand(0), m_Value(X)) &&
2250 match(M->getArgOperand(1), m_APFloat(C2))) ||
2251 (match(M->getArgOperand(1), m_Value(X)) &&
2252 match(M->getArgOperand(0), m_APFloat(C2))))) {
2253 APFloat Res(0.0);
2254 switch (IID) {
2255 case Intrinsic::maxnum:
2256 Res = maxnum(*C1, *C2);
2257 break;
2258 case Intrinsic::minnum:
2259 Res = minnum(*C1, *C2);
2260 break;
2261 case Intrinsic::maximum:
2262 Res = maximum(*C1, *C2);
2263 break;
2264 case Intrinsic::minimum:
2265 Res = minimum(*C1, *C2);
2266 break;
2267 default:
2268 llvm_unreachable("unexpected intrinsic ID");
2269 }
2271 IID, X, ConstantFP::get(Arg0->getType(), Res), II);
2272 // TODO: Conservatively intersecting FMF. If Res == C2, the transform
2273 // was a simplification (so Arg0 and its original flags could
2274 // propagate?)
2275 NewCall->andIRFlags(M);
2276 return replaceInstUsesWith(*II, NewCall);
2277 }
2278 }
2279
2280 // m((fpext X), (fpext Y)) -> fpext (m(X, Y))
2281 if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&
2282 match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&
2283 X->getType() == Y->getType()) {
2284 Value *NewCall =
2285 Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());
2286 return new FPExtInst(NewCall, II->getType());
2287 }
2288
2289 // max X, -X --> fabs X
2290 // min X, -X --> -(fabs X)
2291 // TODO: Remove one-use limitation? That is obviously better for max.
2292 // It would be an extra instruction for min (fnabs), but that is
2293 // still likely better for analysis and codegen.
2294 if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) ||
2295 (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) {
2296 Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);
2297 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)
2298 R = Builder.CreateFNegFMF(R, II);
2299 return replaceInstUsesWith(*II, R);
2300 }
2301
2302 break;
2303 }
2304 case Intrinsic::matrix_multiply: {
2305 // Optimize negation in matrix multiplication.
2306
2307 // -A * -B -> A * B
2308 Value *A, *B;
2309 if (match(II->getArgOperand(0), m_FNeg(m_Value(A))) &&
2310 match(II->getArgOperand(1), m_FNeg(m_Value(B)))) {
2311 replaceOperand(*II, 0, A);
2312 replaceOperand(*II, 1, B);
2313 return II;
2314 }
2315
2316 Value *Op0 = II->getOperand(0);
2317 Value *Op1 = II->getOperand(1);
2318 Value *OpNotNeg, *NegatedOp;
2319 unsigned NegatedOpArg, OtherOpArg;
2320 if (match(Op0, m_FNeg(m_Value(OpNotNeg)))) {
2321 NegatedOp = Op0;
2322 NegatedOpArg = 0;
2323 OtherOpArg = 1;
2324 } else if (match(Op1, m_FNeg(m_Value(OpNotNeg)))) {
2325 NegatedOp = Op1;
2326 NegatedOpArg = 1;
2327 OtherOpArg = 0;
2328 } else
2329 // Multiplication doesn't have a negated operand.
2330 break;
2331
2332 // Only optimize if the negated operand has only one use.
2333 if (!NegatedOp->hasOneUse())
2334 break;
2335
2336 Value *OtherOp = II->getOperand(OtherOpArg);
2337 VectorType *RetTy = cast<VectorType>(II->getType());
2338 VectorType *NegatedOpTy = cast<VectorType>(NegatedOp->getType());
2339 VectorType *OtherOpTy = cast<VectorType>(OtherOp->getType());
2340 ElementCount NegatedCount = NegatedOpTy->getElementCount();
2341 ElementCount OtherCount = OtherOpTy->getElementCount();
2342 ElementCount RetCount = RetTy->getElementCount();
2343 // (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.
2344 if (ElementCount::isKnownGT(NegatedCount, OtherCount) &&
2345 ElementCount::isKnownLT(OtherCount, RetCount)) {
2346 Value *InverseOtherOp = Builder.CreateFNeg(OtherOp);
2347 replaceOperand(*II, NegatedOpArg, OpNotNeg);
2348 replaceOperand(*II, OtherOpArg, InverseOtherOp);
2349 return II;
2350 }
2351 // (-A) * B -> -(A * B), if it is cheaper to negate the result
2352 if (ElementCount::isKnownGT(NegatedCount, RetCount)) {
2353 SmallVector<Value *, 5> NewArgs(II->args());
2354 NewArgs[NegatedOpArg] = OpNotNeg;
2355 Instruction *NewMul =
2356 Builder.CreateIntrinsic(II->getType(), IID, NewArgs, II);
2357 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(NewMul, II));
2358 }
2359 break;
2360 }
2361 case Intrinsic::fmuladd: {
2362 // Canonicalize fast fmuladd to the separate fmul + fadd.
2363 if (II->isFast()) {
2367 II->getArgOperand(1));
2369 Add->takeName(II);
2370 return replaceInstUsesWith(*II, Add);
2371 }
2372
2373 // Try to simplify the underlying FMul.
2374 if (Value *V = simplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2375 II->getFastMathFlags(),
2376 SQ.getWithInstruction(II))) {
2377 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2378 FAdd->copyFastMathFlags(II);
2379 return FAdd;
2380 }
2381
2382 [[fallthrough]];
2383 }
2384 case Intrinsic::fma: {
2385 // fma fneg(x), fneg(y), z -> fma x, y, z
2386 Value *Src0 = II->getArgOperand(0);
2387 Value *Src1 = II->getArgOperand(1);
2388 Value *X, *Y;
2389 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2390 replaceOperand(*II, 0, X);
2391 replaceOperand(*II, 1, Y);
2392 return II;
2393 }
2394
2395 // fma fabs(x), fabs(x), z -> fma x, x, z
2396 if (match(Src0, m_FAbs(m_Value(X))) &&
2397 match(Src1, m_FAbs(m_Specific(X)))) {
2398 replaceOperand(*II, 0, X);
2399 replaceOperand(*II, 1, X);
2400 return II;
2401 }
2402
2403 // Try to simplify the underlying FMul. We can only apply simplifications
2404 // that do not require rounding.
2405 if (Value *V = simplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
2406 II->getFastMathFlags(),
2407 SQ.getWithInstruction(II))) {
2408 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2409 FAdd->copyFastMathFlags(II);
2410 return FAdd;
2411 }
2412
2413 // fma x, y, 0 -> fmul x, y
2414 // This is always valid for -0.0, but requires nsz for +0.0 as
2415 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.
2416 if (match(II->getArgOperand(2), m_NegZeroFP()) ||
2417 (match(II->getArgOperand(2), m_PosZeroFP()) &&
2419 return BinaryOperator::CreateFMulFMF(Src0, Src1, II);
2420
2421 break;
2422 }
2423 case Intrinsic::copysign: {
2424 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);
2425 if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(
2426 Sign, /*Depth=*/0, getSimplifyQuery().getWithInstruction(II))) {
2427 if (*KnownSignBit) {
2428 // If we know that the sign argument is negative, reduce to FNABS:
2429 // copysign Mag, -Sign --> fneg (fabs Mag)
2430 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2431 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
2432 }
2433
2434 // If we know that the sign argument is positive, reduce to FABS:
2435 // copysign Mag, +Sign --> fabs Mag
2436 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);
2437 return replaceInstUsesWith(*II, Fabs);
2438 }
2439
2440 // Propagate sign argument through nested calls:
2441 // copysign Mag, (copysign ?, X) --> copysign Mag, X
2442 Value *X;
2443 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))
2444 return replaceOperand(*II, 1, X);
2445
2446 // Peek through changes of magnitude's sign-bit. This call rewrites those:
2447 // copysign (fabs X), Sign --> copysign X, Sign
2448 // copysign (fneg X), Sign --> copysign X, Sign
2449 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))
2450 return replaceOperand(*II, 0, X);
2451
2452 break;
2453 }
2454 case Intrinsic::fabs: {
2455 Value *Cond, *TVal, *FVal;
2456 if (match(II->getArgOperand(0),
2457 m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {
2458 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF
2459 if (isa<Constant>(TVal) && isa<Constant>(FVal)) {
2460 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});
2461 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});
2462 return SelectInst::Create(Cond, AbsT, AbsF);
2463 }
2464 // fabs (select Cond, -FVal, FVal) --> fabs FVal
2465 if (match(TVal, m_FNeg(m_Specific(FVal))))
2466 return replaceOperand(*II, 0, FVal);
2467 // fabs (select Cond, TVal, -TVal) --> fabs TVal
2468 if (match(FVal, m_FNeg(m_Specific(TVal))))
2469 return replaceOperand(*II, 0, TVal);
2470 }
2471
2472 Value *Magnitude, *Sign;
2473 if (match(II->getArgOperand(0),
2474 m_CopySign(m_Value(Magnitude), m_Value(Sign)))) {
2475 // fabs (copysign x, y) -> (fabs x)
2476 CallInst *AbsSign =
2477 Builder.CreateCall(II->getCalledFunction(), {Magnitude});
2478 AbsSign->copyFastMathFlags(II);
2479 return replaceInstUsesWith(*II, AbsSign);
2480 }
2481
2482 [[fallthrough]];
2483 }
2484 case Intrinsic::ceil:
2485 case Intrinsic::floor:
2486 case Intrinsic::round:
2487 case Intrinsic::roundeven:
2488 case Intrinsic::nearbyint:
2489 case Intrinsic::rint:
2490 case Intrinsic::trunc: {
2491 Value *ExtSrc;
2492 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2493 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2494 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
2495 return new FPExtInst(NarrowII, II->getType());
2496 }
2497 break;
2498 }
2499 case Intrinsic::cos:
2500 case Intrinsic::amdgcn_cos: {
2501 Value *X, *Sign;
2502 Value *Src = II->getArgOperand(0);
2503 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X))) ||
2504 match(Src, m_CopySign(m_Value(X), m_Value(Sign)))) {
2505 // cos(-x) --> cos(x)
2506 // cos(fabs(x)) --> cos(x)
2507 // cos(copysign(x, y)) --> cos(x)
2508 return replaceOperand(*II, 0, X);
2509 }
2510 break;
2511 }
2512 case Intrinsic::sin: {
2513 Value *X;
2514 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2515 // sin(-x) --> -sin(x)
2516 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
2517 Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin);
2518 FNeg->copyFastMathFlags(II);
2519 return FNeg;
2520 }
2521 break;
2522 }
2523 case Intrinsic::ldexp: {
2524 // ldexp(ldexp(x, a), b) -> ldexp(x, a + b)
2525 //
2526 // The danger is if the first ldexp would overflow to infinity or underflow
2527 // to zero, but the combined exponent avoids it. We ignore this with
2528 // reassoc.
2529 //
2530 // It's also safe to fold if we know both exponents are >= 0 or <= 0 since
2531 // it would just double down on the overflow/underflow which would occur
2532 // anyway.
2533 //
2534 // TODO: Could do better if we had range tracking for the input value
2535 // exponent. Also could broaden sign check to cover == 0 case.
2536 Value *Src = II->getArgOperand(0);
2537 Value *Exp = II->getArgOperand(1);
2538 Value *InnerSrc;
2539 Value *InnerExp;
2540 if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ldexp>(
2541 m_Value(InnerSrc), m_Value(InnerExp)))) &&
2542 Exp->getType() == InnerExp->getType()) {
2543 FastMathFlags FMF = II->getFastMathFlags();
2544 FastMathFlags InnerFlags = cast<FPMathOperator>(Src)->getFastMathFlags();
2545
2546 if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
2547 signBitMustBeTheSame(Exp, InnerExp, II, DL, &AC, &DT)) {
2548 // TODO: Add nsw/nuw probably safe if integer type exceeds exponent
2549 // width.
2550 Value *NewExp = Builder.CreateAdd(InnerExp, Exp);
2551 II->setArgOperand(1, NewExp);
2552 II->setFastMathFlags(InnerFlags); // Or the inner flags.
2553 return replaceOperand(*II, 0, InnerSrc);
2554 }
2555 }
2556
2557 break;
2558 }
2559 case Intrinsic::ptrauth_auth:
2560 case Intrinsic::ptrauth_resign: {
2561 // (sign|resign) + (auth|resign) can be folded by omitting the middle
2562 // sign+auth component if the key and discriminator match.
2563 bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;
2564 Value *Key = II->getArgOperand(1);
2565 Value *Disc = II->getArgOperand(2);
2566
2567 // AuthKey will be the key we need to end up authenticating against in
2568 // whatever we replace this sequence with.
2569 Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;
2570 if (auto CI = dyn_cast<CallBase>(II->getArgOperand(0))) {
2571 BasePtr = CI->getArgOperand(0);
2572 if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {
2573 if (CI->getArgOperand(1) != Key || CI->getArgOperand(2) != Disc)
2574 break;
2575 } else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {
2576 if (CI->getArgOperand(3) != Key || CI->getArgOperand(4) != Disc)
2577 break;
2578 AuthKey = CI->getArgOperand(1);
2579 AuthDisc = CI->getArgOperand(2);
2580 } else
2581 break;
2582 } else
2583 break;
2584
2585 unsigned NewIntrin;
2586 if (AuthKey && NeedSign) {
2587 // resign(0,1) + resign(1,2) = resign(0, 2)
2588 NewIntrin = Intrinsic::ptrauth_resign;
2589 } else if (AuthKey) {
2590 // resign(0,1) + auth(1) = auth(0)
2591 NewIntrin = Intrinsic::ptrauth_auth;
2592 } else if (NeedSign) {
2593 // sign(0) + resign(0, 1) = sign(1)
2594 NewIntrin = Intrinsic::ptrauth_sign;
2595 } else {
2596 // sign(0) + auth(0) = nop
2597 replaceInstUsesWith(*II, BasePtr);
2599 return nullptr;
2600 }
2601
2602 SmallVector<Value *, 4> CallArgs;
2603 CallArgs.push_back(BasePtr);
2604 if (AuthKey) {
2605 CallArgs.push_back(AuthKey);
2606 CallArgs.push_back(AuthDisc);
2607 }
2608
2609 if (NeedSign) {
2610 CallArgs.push_back(II->getArgOperand(3));
2611 CallArgs.push_back(II->getArgOperand(4));
2612 }
2613
2614 Function *NewFn = Intrinsic::getDeclaration(II->getModule(), NewIntrin);
2615 return CallInst::Create(NewFn, CallArgs);
2616 }
2617 case Intrinsic::arm_neon_vtbl1:
2618 case Intrinsic::aarch64_neon_tbl1:
2619 if (Value *V = simplifyNeonTbl1(*II, Builder))
2620 return replaceInstUsesWith(*II, V);
2621 break;
2622
2623 case Intrinsic::arm_neon_vmulls:
2624 case Intrinsic::arm_neon_vmullu:
2625 case Intrinsic::aarch64_neon_smull:
2626 case Intrinsic::aarch64_neon_umull: {
2627 Value *Arg0 = II->getArgOperand(0);
2628 Value *Arg1 = II->getArgOperand(1);
2629
2630 // Handle mul by zero first:
2631 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2633 }
2634
2635 // Check for constant LHS & RHS - in this case we just simplify.
2636 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
2637 IID == Intrinsic::aarch64_neon_umull);
2638 VectorType *NewVT = cast<VectorType>(II->getType());
2639 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2640 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2641 Value *V0 = Builder.CreateIntCast(CV0, NewVT, /*isSigned=*/!Zext);
2642 Value *V1 = Builder.CreateIntCast(CV1, NewVT, /*isSigned=*/!Zext);
2643 return replaceInstUsesWith(CI, Builder.CreateMul(V0, V1));
2644 }
2645
2646 // Couldn't simplify - canonicalize constant to the RHS.
2647 std::swap(Arg0, Arg1);
2648 }
2649
2650 // Handle mul by one:
2651 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2652 if (ConstantInt *Splat =
2653 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2654 if (Splat->isOne())
2655 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2656 /*isSigned=*/!Zext);
2657
2658 break;
2659 }
2660 case Intrinsic::arm_neon_aesd:
2661 case Intrinsic::arm_neon_aese:
2662 case Intrinsic::aarch64_crypto_aesd:
2663 case Intrinsic::aarch64_crypto_aese: {
2664 Value *DataArg = II->getArgOperand(0);
2665 Value *KeyArg = II->getArgOperand(1);
2666
2667 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
2668 Value *Data, *Key;
2669 if (match(KeyArg, m_ZeroInt()) &&
2670 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
2671 replaceOperand(*II, 0, Data);
2672 replaceOperand(*II, 1, Key);
2673 return II;
2674 }
2675 break;
2676 }
2677 case Intrinsic::hexagon_V6_vandvrt:
2678 case Intrinsic::hexagon_V6_vandvrt_128B: {
2679 // Simplify Q -> V -> Q conversion.
2680 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2681 Intrinsic::ID ID0 = Op0->getIntrinsicID();
2682 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
2683 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
2684 break;
2685 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);
2686 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();
2687 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();
2688 // Check if every byte has common bits in Bytes and Mask.
2689 uint64_t C = Bytes1 & Mask1;
2690 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))
2691 return replaceInstUsesWith(*II, Op0->getArgOperand(0));
2692 }
2693 break;
2694 }
2695 case Intrinsic::stackrestore: {
2696 enum class ClassifyResult {
2697 None,
2698 Alloca,
2699 StackRestore,
2700 CallWithSideEffects,
2701 };
2702 auto Classify = [](const Instruction *I) {
2703 if (isa<AllocaInst>(I))
2704 return ClassifyResult::Alloca;
2705
2706 if (auto *CI = dyn_cast<CallInst>(I)) {
2707 if (auto *II = dyn_cast<IntrinsicInst>(CI)) {
2708 if (II->getIntrinsicID() == Intrinsic::stackrestore)
2709 return ClassifyResult::StackRestore;
2710
2711 if (II->mayHaveSideEffects())
2712 return ClassifyResult::CallWithSideEffects;
2713 } else {
2714 // Consider all non-intrinsic calls to be side effects
2715 return ClassifyResult::CallWithSideEffects;
2716 }
2717 }
2718
2719 return ClassifyResult::None;
2720 };
2721
2722 // If the stacksave and the stackrestore are in the same BB, and there is
2723 // no intervening call, alloca, or stackrestore of a different stacksave,
2724 // remove the restore. This can happen when variable allocas are DCE'd.
2725 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2726 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
2727 SS->getParent() == II->getParent()) {
2728 BasicBlock::iterator BI(SS);
2729 bool CannotRemove = false;
2730 for (++BI; &*BI != II; ++BI) {
2731 switch (Classify(&*BI)) {
2732 case ClassifyResult::None:
2733 // So far so good, look at next instructions.
2734 break;
2735
2736 case ClassifyResult::StackRestore:
2737 // If we found an intervening stackrestore for a different
2738 // stacksave, we can't remove the stackrestore. Otherwise, continue.
2739 if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)
2740 CannotRemove = true;
2741 break;
2742
2743 case ClassifyResult::Alloca:
2744 case ClassifyResult::CallWithSideEffects:
2745 // If we found an alloca, a non-intrinsic call, or an intrinsic
2746 // call with side effects, we can't remove the stackrestore.
2747 CannotRemove = true;
2748 break;
2749 }
2750 if (CannotRemove)
2751 break;
2752 }
2753
2754 if (!CannotRemove)
2755 return eraseInstFromFunction(CI);
2756 }
2757 }
2758
2759 // Scan down this block to see if there is another stack restore in the
2760 // same block without an intervening call/alloca.
2761 BasicBlock::iterator BI(II);
2762 Instruction *TI = II->getParent()->getTerminator();
2763 bool CannotRemove = false;
2764 for (++BI; &*BI != TI; ++BI) {
2765 switch (Classify(&*BI)) {
2766 case ClassifyResult::None:
2767 // So far so good, look at next instructions.
2768 break;
2769
2770 case ClassifyResult::StackRestore:
2771 // If there is a stackrestore below this one, remove this one.
2772 return eraseInstFromFunction(CI);
2773
2774 case ClassifyResult::Alloca:
2775 case ClassifyResult::CallWithSideEffects:
2776 // If we found an alloca, a non-intrinsic call, or an intrinsic call
2777 // with side effects (such as llvm.stacksave and llvm.read_register),
2778 // we can't remove the stack restore.
2779 CannotRemove = true;
2780 break;
2781 }
2782 if (CannotRemove)
2783 break;
2784 }
2785
2786 // If the stack restore is in a return, resume, or unwind block and if there
2787 // are no allocas or calls between the restore and the return, nuke the
2788 // restore.
2789 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
2790 return eraseInstFromFunction(CI);
2791 break;
2792 }
2793 case Intrinsic::lifetime_end:
2794 // Asan needs to poison memory to detect invalid access which is possible
2795 // even for empty lifetime range.
2796 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2797 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
2798 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2799 break;
2800
2801 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {
2802 return I.getIntrinsicID() == Intrinsic::lifetime_start;
2803 }))
2804 return nullptr;
2805 break;
2806 case Intrinsic::assume: {
2807 Value *IIOperand = II->getArgOperand(0);
2809 II->getOperandBundlesAsDefs(OpBundles);
2810
2811 /// This will remove the boolean Condition from the assume given as
2812 /// argument and remove the assume if it becomes useless.
2813 /// always returns nullptr for use as a return values.
2814 auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {
2815 assert(isa<AssumeInst>(Assume));
2816 if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))
2817 return eraseInstFromFunction(CI);
2819 return nullptr;
2820 };
2821 // Remove an assume if it is followed by an identical assume.
2822 // TODO: Do we need this? Unless there are conflicting assumptions, the
2823 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
2825 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2826 return RemoveConditionFromAssume(Next);
2827
2828 // Canonicalize assume(a && b) -> assume(a); assume(b);
2829 // Note: New assumption intrinsics created here are registered by
2830 // the InstCombineIRInserter object.
2831 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
2832 Value *AssumeIntrinsic = II->getCalledOperand();
2833 Value *A, *B;
2834 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {
2835 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,
2836 II->getName());
2837 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
2838 return eraseInstFromFunction(*II);
2839 }
2840 // assume(!(a || b)) -> assume(!a); assume(!b);
2841 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {
2842 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2843 Builder.CreateNot(A), OpBundles, II->getName());
2844 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
2845 Builder.CreateNot(B), II->getName());
2846 return eraseInstFromFunction(*II);
2847 }
2848
2849 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2850 // (if assume is valid at the load)
2851 CmpInst::Predicate Pred;
2853 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2854 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2855 LHS->getType()->isPointerTy() &&
2857 MDNode *MD = MDNode::get(II->getContext(), std::nullopt);
2858 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2859 LHS->setMetadata(LLVMContext::MD_noundef, MD);
2860 return RemoveConditionFromAssume(II);
2861
2862 // TODO: apply nonnull return attributes to calls and invokes
2863 // TODO: apply range metadata for range check patterns?
2864 }
2865
2866 // Separate storage assumptions apply to the underlying allocations, not any
2867 // particular pointer within them. When evaluating the hints for AA purposes
2868 // we getUnderlyingObject them; by precomputing the answers here we can
2869 // avoid having to do so repeatedly there.
2870 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2872 if (OBU.getTagName() == "separate_storage") {
2873 assert(OBU.Inputs.size() == 2);
2874 auto MaybeSimplifyHint = [&](const Use &U) {
2875 Value *Hint = U.get();
2876 // Not having a limit is safe because InstCombine removes unreachable
2877 // code.
2878 Value *UnderlyingObject = getUnderlyingObject(Hint, /*MaxLookup*/ 0);
2879 if (Hint != UnderlyingObject)
2880 replaceUse(const_cast<Use &>(U), UnderlyingObject);
2881 };
2882 MaybeSimplifyHint(OBU.Inputs[0]);
2883 MaybeSimplifyHint(OBU.Inputs[1]);
2884 }
2885 }
2886
2887 // Convert nonnull assume like:
2888 // %A = icmp ne i32* %PTR, null
2889 // call void @llvm.assume(i1 %A)
2890 // into
2891 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]
2893 match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&
2894 Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {
2895 if (auto *Replacement = buildAssumeFromKnowledge(
2896 {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {
2897
2898 Replacement->insertBefore(Next);
2899 AC.registerAssumption(Replacement);
2900 return RemoveConditionFromAssume(II);
2901 }
2902 }
2903
2904 // Convert alignment assume like:
2905 // %B = ptrtoint i32* %A to i64
2906 // %C = and i64 %B, Constant
2907 // %D = icmp eq i64 %C, 0
2908 // call void @llvm.assume(i1 %D)
2909 // into
2910 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]
2911 uint64_t AlignMask;
2913 match(IIOperand,
2914 m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),
2915 m_Zero())) &&
2916 Pred == CmpInst::ICMP_EQ) {
2917 if (isPowerOf2_64(AlignMask + 1)) {
2918 uint64_t Offset = 0;
2920 if (match(A, m_PtrToInt(m_Value(A)))) {
2921 /// Note: this doesn't preserve the offset information but merges
2922 /// offset and alignment.
2923 /// TODO: we can generate a GEP instead of merging the alignment with
2924 /// the offset.
2925 RetainedKnowledge RK{Attribute::Alignment,
2926 (unsigned)MinAlign(Offset, AlignMask + 1), A};
2927 if (auto *Replacement =
2928 buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {
2929
2930 Replacement->insertAfter(II);
2931 AC.registerAssumption(Replacement);
2932 }
2933 return RemoveConditionFromAssume(II);
2934 }
2935 }
2936 }
2937
2938 /// Canonicalize Knowledge in operand bundles.
2940 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {
2941 auto &BOI = II->bundle_op_info_begin()[Idx];
2943 llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);
2944 if (BOI.End - BOI.Begin > 2)
2945 continue; // Prevent reducing knowledge in an align with offset since
2946 // extracting a RetainedKnowledge from them looses offset
2947 // information
2948 RetainedKnowledge CanonRK =
2949 llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,
2951 &getDominatorTree());
2952 if (CanonRK == RK)
2953 continue;
2954 if (!CanonRK) {
2955 if (BOI.End - BOI.Begin > 0) {
2956 Worklist.pushValue(II->op_begin()[BOI.Begin]);
2957 Value::dropDroppableUse(II->op_begin()[BOI.Begin]);
2958 }
2959 continue;
2960 }
2961 assert(RK.AttrKind == CanonRK.AttrKind);
2962 if (BOI.End - BOI.Begin > 0)
2963 II->op_begin()[BOI.Begin].set(CanonRK.WasOn);
2964 if (BOI.End - BOI.Begin > 1)
2965 II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(
2966 Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));
2967 if (RK.WasOn)
2969 return II;
2970 }
2971 }
2972
2973 // If there is a dominating assume with the same condition as this one,
2974 // then this one is redundant, and should be removed.
2975 KnownBits Known(1);
2976 computeKnownBits(IIOperand, Known, 0, II);
2977 if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))
2978 return eraseInstFromFunction(*II);
2979
2980 // assume(false) is unreachable.
2981 if (match(IIOperand, m_CombineOr(m_Zero(), m_Undef()))) {
2983 return eraseInstFromFunction(*II);
2984 }
2985
2986 // Update the cache of affected values for this assumption (we might be
2987 // here because we just simplified the condition).
2988 AC.updateAffectedValues(cast<AssumeInst>(II));
2989 break;
2990 }
2991 case Intrinsic::experimental_guard: {
2992 // Is this guard followed by another guard? We scan forward over a small
2993 // fixed window of instructions to handle common cases with conditions
2994 // computed between guards.
2995 Instruction *NextInst = II->getNextNonDebugInstruction();
2996 for (unsigned i = 0; i < GuardWideningWindow; i++) {
2997 // Note: Using context-free form to avoid compile time blow up
2998 if (!isSafeToSpeculativelyExecute(NextInst))
2999 break;
3000 NextInst = NextInst->getNextNonDebugInstruction();
3001 }
3002 Value *NextCond = nullptr;
3003 if (match(NextInst,
3004 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3005 Value *CurrCond = II->getArgOperand(0);
3006
3007 // Remove a guard that it is immediately preceded by an identical guard.
3008 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3009 if (CurrCond != NextCond) {
3011 while (MoveI != NextInst) {
3012 auto *Temp = MoveI;
3013 MoveI = MoveI->getNextNonDebugInstruction();
3014 Temp->moveBefore(II);
3015 }
3016 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));
3017 }
3018 eraseInstFromFunction(*NextInst);
3019 return II;
3020 }
3021 break;
3022 }
3023 case Intrinsic::vector_insert: {
3024 Value *Vec = II->getArgOperand(0);
3025 Value *SubVec = II->getArgOperand(1);
3026 Value *Idx = II->getArgOperand(2);
3027 auto *DstTy = dyn_cast<FixedVectorType>(II->getType());
3028 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
3029 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());
3030
3031 // Only canonicalize if the destination vector, Vec, and SubVec are all
3032 // fixed vectors.
3033 if (DstTy && VecTy && SubVecTy) {
3034 unsigned DstNumElts = DstTy->getNumElements();
3035 unsigned VecNumElts = VecTy->getNumElements();
3036 unsigned SubVecNumElts = SubVecTy->getNumElements();
3037 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3038
3039 // An insert that entirely overwrites Vec with SubVec is a nop.
3040 if (VecNumElts == SubVecNumElts)
3041 return replaceInstUsesWith(CI, SubVec);
3042
3043 // Widen SubVec into a vector of the same width as Vec, since
3044 // shufflevector requires the two input vectors to be the same width.
3045 // Elements beyond the bounds of SubVec within the widened vector are
3046 // undefined.
3047 SmallVector<int, 8> WidenMask;
3048 unsigned i;
3049 for (i = 0; i != SubVecNumElts; ++i)
3050 WidenMask.push_back(i);
3051 for (; i != VecNumElts; ++i)
3052 WidenMask.push_back(PoisonMaskElem);
3053
3054 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);
3055
3057 for (unsigned i = 0; i != IdxN; ++i)
3058 Mask.push_back(i);
3059 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
3060 Mask.push_back(i);
3061 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
3062 Mask.push_back(i);
3063
3064 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
3065 return replaceInstUsesWith(CI, Shuffle);
3066 }
3067 break;
3068 }
3069 case Intrinsic::vector_extract: {
3070 Value *Vec = II->getArgOperand(0);
3071 Value *Idx = II->getArgOperand(1);
3072
3073 Type *ReturnType = II->getType();
3074 // (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),
3075 // ExtractIdx)
3076 unsigned ExtractIdx = cast<ConstantInt>(Idx)->getZExtValue();
3077 Value *InsertTuple, *InsertIdx, *InsertValue;
3078 if (match(Vec, m_Intrinsic<Intrinsic::vector_insert>(m_Value(InsertTuple),
3079 m_Value(InsertValue),
3080 m_Value(InsertIdx))) &&
3081 InsertValue->getType() == ReturnType) {
3082 unsigned Index = cast<ConstantInt>(InsertIdx)->getZExtValue();
3083 // Case where we get the same index right after setting it.
3084 // extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->
3085 // InsertValue
3086 if (ExtractIdx == Index)
3087 return replaceInstUsesWith(CI, InsertValue);
3088 // If we are getting a different index than what was set in the
3089 // insert.vector intrinsic. We can just set the input tuple to the one up
3090 // in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,
3091 // InsertIndex), ExtractIndex)
3092 // --> extract.vector(InsertTuple, ExtractIndex)
3093 else
3094 return replaceOperand(CI, 0, InsertTuple);
3095 }
3096
3097 auto *DstTy = dyn_cast<VectorType>(ReturnType);
3098 auto *VecTy = dyn_cast<VectorType>(Vec->getType());
3099
3100 if (DstTy && VecTy) {
3101 auto DstEltCnt = DstTy->getElementCount();
3102 auto VecEltCnt = VecTy->getElementCount();
3103 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
3104
3105 // Extracting the entirety of Vec is a nop.
3106 if (DstEltCnt == VecTy->getElementCount()) {
3107 replaceInstUsesWith(CI, Vec);
3108 return eraseInstFromFunction(CI);
3109 }
3110
3111 // Only canonicalize to shufflevector if the destination vector and
3112 // Vec are fixed vectors.
3113 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
3114 break;
3115
3117 for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
3118 Mask.push_back(IdxN + i);
3119
3120 Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);
3121 return replaceInstUsesWith(CI, Shuffle);
3122 }
3123 break;
3124 }
3125 case Intrinsic::experimental_vector_reverse: {
3126 Value *BO0, *BO1, *X, *Y;
3127 Value *Vec = II->getArgOperand(0);
3128 if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {
3129 auto *OldBinOp = cast<BinaryOperator>(Vec);
3130 if (match(BO0, m_VecReverse(m_Value(X)))) {
3131 // rev(binop rev(X), rev(Y)) --> binop X, Y
3132 if (match(BO1, m_VecReverse(m_Value(Y))))
3133 return replaceInstUsesWith(CI,
3135 OldBinOp->getOpcode(), X, Y, OldBinOp,
3136 OldBinOp->getName(), II));
3137 // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat
3138 if (isSplatValue(BO1))
3139 return replaceInstUsesWith(CI,
3141 OldBinOp->getOpcode(), X, BO1,
3142 OldBinOp, OldBinOp->getName(), II));
3143 }
3144 // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y
3145 if (match(BO1, m_VecReverse(m_Value(Y))) && isSplatValue(BO0))
3147 OldBinOp->getOpcode(), BO0, Y,
3148 OldBinOp, OldBinOp->getName(), II));
3149 }
3150 // rev(unop rev(X)) --> unop X
3151 if (match(Vec, m_OneUse(m_UnOp(m_VecReverse(m_Value(X)))))) {
3152 auto *OldUnOp = cast<UnaryOperator>(Vec);
3154 OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II);
3155 return replaceInstUsesWith(CI, NewUnOp);
3156 }
3157 break;
3158 }
3159 case Intrinsic::vector_reduce_or:
3160 case Intrinsic::vector_reduce_and: {
3161 // Canonicalize logical or/and reductions:
3162 // Or reduction for i1 is represented as:
3163 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3164 // %res = cmp ne iReduxWidth %val, 0
3165 // And reduction for i1 is represented as:
3166 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3167 // %res = cmp eq iReduxWidth %val, 11111
3168 Value *Arg = II->getArgOperand(0);
3169 Value *Vect;
3170 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3171 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3172 if (FTy->getElementType() == Builder.getInt1Ty()) {
3174 Vect, Builder.getIntNTy(FTy->getNumElements()));
3175 if (IID == Intrinsic::vector_reduce_and) {
3176 Res = Builder.CreateICmpEQ(
3178 } else {
3179 assert(IID == Intrinsic::vector_reduce_or &&
3180 "Expected or reduction.");
3181 Res = Builder.CreateIsNotNull(Res);
3182 }
3183 if (Arg != Vect)
3184 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3185 II->getType());
3186 return replaceInstUsesWith(CI, Res);
3187 }
3188 }
3189 [[fallthrough]];
3190 }
3191 case Intrinsic::vector_reduce_add: {
3192 if (IID == Intrinsic::vector_reduce_add) {
3193 // Convert vector_reduce_add(ZExt(<n x i1>)) to
3194 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3195 // Convert vector_reduce_add(SExt(<n x i1>)) to
3196 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3197 // Convert vector_reduce_add(<n x i1>) to
3198 // Trunc(ctpop(bitcast <n x i1> to in)).
3199 Value *Arg = II->getArgOperand(0);
3200 Value *Vect;
3201 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3202 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3203 if (FTy->getElementType() == Builder.getInt1Ty()) {
3205 Vect, Builder.getIntNTy(FTy->getNumElements()));
3206 Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
3207 if (Res->getType() != II->getType())
3208 Res = Builder.CreateZExtOrTrunc(Res, II->getType());
3209 if (Arg != Vect &&
3210 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)
3211 Res = Builder.CreateNeg(Res);
3212 return replaceInstUsesWith(CI, Res);
3213 }
3214 }
3215 }
3216 [[fallthrough]];
3217 }
3218 case Intrinsic::vector_reduce_xor: {
3219 if (IID == Intrinsic::vector_reduce_xor) {
3220 // Exclusive disjunction reduction over the vector with
3221 // (potentially-extended) i1 element type is actually a
3222 // (potentially-extended) arithmetic `add` reduction over the original
3223 // non-extended value:
3224 // vector_reduce_xor(?ext(<n x i1>))
3225 // -->
3226 // ?ext(vector_reduce_add(<n x i1>))
3227 Value *Arg = II->getArgOperand(0);
3228 Value *Vect;
3229 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3230 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3231 if (FTy->getElementType() == Builder.getInt1Ty()) {
3232 Value *Res = Builder.CreateAddReduce(Vect);
3233 if (Arg != Vect)
3234 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3235 II->getType());
3236 return replaceInstUsesWith(CI, Res);
3237 }
3238 }
3239 }
3240 [[fallthrough]];
3241 }
3242 case Intrinsic::vector_reduce_mul: {
3243 if (IID == Intrinsic::vector_reduce_mul) {
3244 // Multiplicative reduction over the vector with (potentially-extended)
3245 // i1 element type is actually a (potentially zero-extended)
3246 // logical `and` reduction over the original non-extended value:
3247 // vector_reduce_mul(?ext(<n x i1>))
3248 // -->
3249 // zext(vector_reduce_and(<n x i1>))
3250 Value *Arg = II->getArgOperand(0);
3251 Value *Vect;
3252 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3253 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3254 if (FTy->getElementType() == Builder.getInt1Ty()) {
3255 Value *Res = Builder.CreateAndReduce(Vect);
3256 if (Res->getType() != II->getType())
3257 Res = Builder.CreateZExt(Res, II->getType());
3258 return replaceInstUsesWith(CI, Res);
3259 }
3260 }
3261 }
3262 [[fallthrough]];
3263 }
3264 case Intrinsic::vector_reduce_umin:
3265 case Intrinsic::vector_reduce_umax: {
3266 if (IID == Intrinsic::vector_reduce_umin ||
3267 IID == Intrinsic::vector_reduce_umax) {
3268 // UMin/UMax reduction over the vector with (potentially-extended)
3269 // i1 element type is actually a (potentially-extended)
3270 // logical `and`/`or` reduction over the original non-extended value:
3271 // vector_reduce_u{min,max}(?ext(<n x i1>))
3272 // -->
3273 // ?ext(vector_reduce_{and,or}(<n x i1>))
3274 Value *Arg = II->getArgOperand(0);
3275 Value *Vect;
3276 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3277 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3278 if (FTy->getElementType() == Builder.getInt1Ty()) {
3279 Value *Res = IID == Intrinsic::vector_reduce_umin
3280 ? Builder.CreateAndReduce(Vect)
3281 : Builder.CreateOrReduce(Vect);
3282 if (Arg != Vect)
3283 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,
3284 II->getType());
3285 return replaceInstUsesWith(CI, Res);
3286 }
3287 }
3288 }
3289 [[fallthrough]];
3290 }
3291 case Intrinsic::vector_reduce_smin:
3292 case Intrinsic::vector_reduce_smax: {
3293 if (IID == Intrinsic::vector_reduce_smin ||
3294 IID == Intrinsic::vector_reduce_smax) {
3295 // SMin/SMax reduction over the vector with (potentially-extended)
3296 // i1 element type is actually a (potentially-extended)
3297 // logical `and`/`or` reduction over the original non-extended value:
3298 // vector_reduce_s{min,max}(<n x i1>)
3299 // -->
3300 // vector_reduce_{or,and}(<n x i1>)
3301 // and
3302 // vector_reduce_s{min,max}(sext(<n x i1>))
3303 // -->
3304 // sext(vector_reduce_{or,and}(<n x i1>))
3305 // and
3306 // vector_reduce_s{min,max}(zext(<n x i1>))
3307 // -->
3308 // zext(vector_reduce_{and,or}(<n x i1>))
3309 Value *Arg = II->getArgOperand(0);
3310 Value *Vect;
3311 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {
3312 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))
3313 if (FTy->getElementType() == Builder.getInt1Ty()) {
3314 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;
3315 if (Arg != Vect)
3316 ExtOpc = cast<CastInst>(Arg)->getOpcode();
3317 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
3318 (ExtOpc == Instruction::CastOps::ZExt))
3319 ? Builder.CreateAndReduce(Vect)
3320 : Builder.CreateOrReduce(Vect);
3321 if (Arg != Vect)
3322 Res = Builder.CreateCast(ExtOpc, Res, II->getType());
3323 return replaceInstUsesWith(CI, Res);
3324 }
3325 }
3326 }
3327 [[fallthrough]];
3328 }
3329 case Intrinsic::vector_reduce_fmax:
3330 case Intrinsic::vector_reduce_fmin:
3331 case Intrinsic::vector_reduce_fadd:
3332 case Intrinsic::vector_reduce_fmul: {
3333 bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd &&
3334 IID != Intrinsic::vector_reduce_fmul) ||
3335 II->hasAllowReassoc();
3336 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
3337 IID == Intrinsic::vector_reduce_fmul)
3338 ? 1
3339 : 0;
3340 Value *Arg = II->getArgOperand(ArgIdx);
3341 Value *V;
3342 ArrayRef<int> Mask;
3343 if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated ||
3344 !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||
3345 !cast<ShuffleVectorInst>(Arg)->isSingleSource())
3346 break;
3347 int Sz = Mask.size();
3348 SmallBitVector UsedIndices(Sz);
3349 for (int Idx : Mask) {
3350 if (Idx == PoisonMaskElem || UsedIndices.test(Idx))
3351 break;
3352 UsedIndices.set(Idx);
3353 }
3354 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or
3355 // other changes.
3356 if (UsedIndices.all()) {
3357 replaceUse(II->getOperandUse(ArgIdx), V);
3358 return nullptr;
3359 }
3360 break;
3361 }
3362 case Intrinsic::is_fpclass: {
3363 if (Instruction *I = foldIntrinsicIsFPClass(*II))
3364 return I;
3365 break;
3366 }
3367 default: {
3368 // Handle target specific intrinsics
3369 std::optional<Instruction *> V = targetInstCombineIntrinsic(*II);
3370 if (V)
3371 return *V;
3372 break;
3373 }
3374 }
3375
3376 // Try to fold intrinsic into select operands. This is legal if:
3377 // * The intrinsic is speculatable.
3378 // * The select condition is not a vector, or the intrinsic does not
3379 // perform cross-lane operations.
3380 switch (IID) {
3381 case Intrinsic::ctlz:
3382 case Intrinsic::cttz:
3383 case Intrinsic::ctpop:
3384 case Intrinsic::umin:
3385 case Intrinsic::umax:
3386 case Intrinsic::smin:
3387 case Intrinsic::smax:
3388 case Intrinsic::usub_sat:
3389 case Intrinsic::uadd_sat:
3390 case Intrinsic::ssub_sat:
3391 case Intrinsic::sadd_sat:
3392 for (Value *Op : II->args())
3393 if (auto *Sel = dyn_cast<SelectInst>(Op))
3394 if (Instruction *R = FoldOpIntoSelect(*II, Sel))
3395 return R;
3396 [[fallthrough]];
3397 default:
3398 break;
3399 }
3400
3402 return Shuf;
3403
3404 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke
3405 // context, so it is handled in visitCallBase and we should trigger it.
3406 return visitCallBase(*II);
3407}
3408
3409// Fence instruction simplification
3411 auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());
3412 // This check is solely here to handle arbitrary target-dependent syncscopes.
3413 // TODO: Can remove if does not matter in practice.
3414 if (NFI && FI.isIdenticalTo(NFI))
3415 return eraseInstFromFunction(FI);
3416
3417 // Returns true if FI1 is identical or stronger fence than FI2.
3418 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {
3419 auto FI1SyncScope = FI1->getSyncScopeID();
3420 // Consider same scope, where scope is global or single-thread.
3421 if (FI1SyncScope != FI2->getSyncScopeID() ||
3422 (FI1SyncScope != SyncScope::System &&
3423 FI1SyncScope != SyncScope::SingleThread))
3424 return false;
3425
3426 return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());
3427 };
3428 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
3429 return eraseInstFromFunction(FI);
3430
3431 if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))
3432 if (isIdenticalOrStrongerFence(PFI, &FI))
3433 return eraseInstFromFunction(FI);
3434 return nullptr;
3435}
3436
3437// InvokeInst simplification
3439 return visitCallBase(II);
3440}
3441
3442// CallBrInst simplification
3444 return visitCallBase(CBI);
3445}
3446
3447Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
3448 if (!CI->getCalledFunction()) return nullptr;
3449
3450 // Skip optimizing notail and musttail calls so
3451 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.
3452 // LibCallSimplifier::optimizeCall should try to preseve tail calls though.
3453 if (CI->isMustTailCall() || CI->isNoTailCall())
3454 return nullptr;
3455
3456 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
3457 replaceInstUsesWith(*From, With);
3458 };
3459 auto InstCombineErase = [this](Instruction *I) {
3461 };
3462 LibCallSimplifier Simplifier(DL, &TLI, &AC, ORE, BFI, PSI, InstCombineRAUW,
3463 InstCombineErase);
3464 if (Value *With = Simplifier.optimizeCall(CI, Builder)) {
3465 ++NumSimplified;
3466 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
3467 }
3468
3469 return nullptr;
3470}
3471
3473 // Strip off at most one level of pointer casts, looking for an alloca. This
3474 // is good enough in practice and simpler than handling any number of casts.
3475 Value *Underlying = TrampMem->stripPointerCasts();
3476 if (Underlying != TrampMem &&
3477 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
3478 return nullptr;
3479 if (!isa<AllocaInst>(Underlying))
3480 return nullptr;
3481
3482 IntrinsicInst *InitTrampoline = nullptr;
3483 for (User *U : TrampMem->users()) {
3484 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3485 if (!II)
3486 return nullptr;
3487 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3488 if (InitTrampoline)
3489 // More than one init_trampoline writes to this value. Give up.
3490 return nullptr;
3491 InitTrampoline = II;
3492 continue;
3493 }
3494 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3495 // Allow any number of calls to adjust.trampoline.
3496 continue;
3497 return nullptr;
3498 }
3499
3500 // No call to init.trampoline found.
3501 if (!InitTrampoline)
3502 return nullptr;
3503
3504 // Check that the alloca is being used in the expected way.
3505 if (InitTrampoline->getOperand(0) != TrampMem)
3506 return nullptr;
3507
3508 return InitTrampoline;
3509}
3510
3512 Value *TrampMem) {
3513 // Visit all the previous instructions in the basic block, and try to find a
3514 // init.trampoline which has a direct path to the adjust.trampoline.
3515 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3516 E = AdjustTramp->getParent()->begin();
3517 I != E;) {
3518 Instruction *Inst = &*--I;
3519 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3520 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3521 II->getOperand(0) == TrampMem)
3522 return II;
3523 if (Inst->mayWriteToMemory())
3524 return nullptr;
3525 }
3526 return nullptr;
3527}
3528
3529// Given a call to llvm.adjust.trampoline, find and return the corresponding
3530// call to llvm.init.trampoline if the call to the trampoline can be optimized
3531// to a direct call to a function. Otherwise return NULL.
3533 Callee = Callee->stripPointerCasts();
3534 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3535 if (!AdjustTramp ||
3536 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
3537 return nullptr;
3538
3539 Value *TrampMem = AdjustTramp->getOperand(0);
3540
3542 return IT;
3543 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
3544 return IT;
3545 return nullptr;
3546}
3547
3548bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,
3549 const TargetLibraryInfo *TLI) {
3550 // Note: We only handle cases which can't be driven from generic attributes
3551 // here. So, for example, nonnull and noalias (which are common properties
3552 // of some allocation functions) are expected to be handled via annotation
3553 // of the respective allocator declaration with generic attributes.
3554 bool Changed = false;
3555
3556 if (!Call.getType()->isPointerTy())
3557 return Changed;
3558
3559 std::optional<APInt> Size = getAllocSize(&Call, TLI);
3560 if (Size && *Size != 0) {
3561 // TODO: We really should just emit deref_or_null here and then
3562 // let the generic inference code combine that with nonnull.
3563 if (Call.hasRetAttr(Attribute::NonNull)) {
3564 Changed = !Call.hasRetAttr(Attribute::Dereferenceable);
3566 Call.getContext(), Size->getLimitedValue()));
3567 } else {
3568 Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull);
3570 Call.getContext(), Size->getLimitedValue()));
3571 }
3572 }
3573
3574 // Add alignment attribute if alignment is a power of two constant.
3575 Value *Alignment = getAllocAlignment(&Call, TLI);
3576 if (!Alignment)
3577 return Changed;
3578
3579 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);
3580 if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {
3581 uint64_t AlignmentVal = AlignOpC->getZExtValue();
3582 if (llvm::isPowerOf2_64(AlignmentVal)) {
3583 Align ExistingAlign = Call.getRetAlign().valueOrOne();
3584 Align NewAlign = Align(AlignmentVal);
3585 if (NewAlign > ExistingAlign) {
3586 Call.addRetAttr(
3587 Attribute::getWithAlignment(Call.getContext(), NewAlign));
3588 Changed = true;
3589 }
3590 }
3591 }
3592 return Changed;
3593}
3594
3595/// Improvements for call, callbr and invoke instructions.
3596Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {
3597 bool Changed = annotateAnyAllocSite(Call, &TLI);
3598
3599 // Mark any parameters that are known to be non-null with the nonnull
3600 // attribute. This is helpful for inlining calls to functions with null
3601 // checks on their arguments.
3603 unsigned ArgNo = 0;
3604
3605 for (Value *V : Call.args()) {
3606 if (V->getType()->isPointerTy() &&
3607 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
3608 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
3609 ArgNos.push_back(ArgNo);
3610 ArgNo++;
3611 }
3612
3613 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");
3614
3615 if (!ArgNos.empty()) {
3616 AttributeList AS = Call.getAttributes();
3617 LLVMContext &Ctx = Call.getContext();
3618 AS = AS.addParamAttribute(Ctx, ArgNos,
3619 Attribute::get(Ctx, Attribute::NonNull));
3620 Call.setAttributes(AS);
3621 Changed = true;
3622 }
3623
3624 // If the callee is a pointer to a function, attempt to move any casts to the
3625 // arguments of the call/callbr/invoke.
3626 Value *Callee = Call.getCalledOperand();
3627 Function *CalleeF = dyn_cast<Function>(Callee);
3628 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&
3629 transformConstExprCastCall(Call))
3630 return nullptr;
3631
3632 if (CalleeF) {
3633 // Remove the convergent attr on calls when the callee is not convergent.
3634 if (Call.isConvergent() && !CalleeF->isConvergent() &&
3635 !CalleeF->isIntrinsic()) {
3636 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
3637 << "\n");
3638 Call.setNotConvergent();
3639 return &Call;
3640 }
3641
3642 // If the call and callee calling conventions don't match, and neither one
3643 // of the calling conventions is compatible with C calling convention
3644 // this call must be unreachable, as the call is undefined.
3645 if ((CalleeF->getCallingConv() != Call.getCallingConv() &&
3646 !(CalleeF->getCallingConv() == llvm::CallingConv::C &&
3648 !(Call.getCallingConv() == llvm::CallingConv::C &&
3650 // Only do this for calls to a function with a body. A prototype may
3651 // not actually end up matching the implementation's calling conv for a
3652 // variety of reasons (e.g. it may be written in assembly).
3653 !CalleeF->isDeclaration()) {
3654 Instruction *OldCall = &Call;
3656 // If OldCall does not return void then replaceInstUsesWith poison.
3657 // This allows ValueHandlers and custom metadata to adjust itself.
3658 if (!OldCall->getType()->isVoidTy())
3659 replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));
3660 if (isa<CallInst>(OldCall))
3661 return eraseInstFromFunction(*OldCall);
3662
3663 // We cannot remove an invoke or a callbr, because it would change thexi
3664 // CFG, just change the callee to a null pointer.
3665 cast<CallBase>(OldCall)->setCalledFunction(
3666 CalleeF->getFunctionType(),
3667 Constant::getNullValue(CalleeF->getType()));
3668 return nullptr;
3669 }
3670 }
3671
3672 // Calling a null function pointer is undefined if a null address isn't
3673 // dereferenceable.
3674 if ((isa<ConstantPointerNull>(Callee) &&
3675 !NullPointerIsDefined(Call.getFunction())) ||
3676 isa<UndefValue>(Callee)) {
3677 // If Call does not return void then replaceInstUsesWith poison.
3678 // This allows ValueHandlers and custom metadata to adjust itself.
3679 if (!Call.getType()->isVoidTy())
3680 replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));
3681
3682 if (Call.isTerminator()) {
3683 // Can't remove an invoke or callbr because we cannot change the CFG.
3684 return nullptr;
3685 }
3686
3687 // This instruction is not reachable, just remove it.
3689 return eraseInstFromFunction(Call);
3690 }
3691
3692 if (IntrinsicInst *II = findInitTrampoline(Callee))
3693 return transformCallThroughTrampoline(Call, *II);
3694
3695 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
3696 InlineAsm *IA = cast<InlineAsm>(Callee);
3697 if (!IA->canThrow()) {
3698 // Normal inline asm calls cannot throw - mark them
3699 // 'nounwind'.
3700 Call.setDoesNotThrow();
3701 Changed = true;
3702 }
3703 }
3704
3705 // Try to optimize the call if possible, we require DataLayout for most of
3706 // this. None of these calls are seen as possibly dead so go ahead and
3707 // delete the instruction now.
3708 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
3709 Instruction *I = tryOptimizeCall(CI);
3710 // If we changed something return the result, etc. Otherwise let
3711 // the fallthrough check.
3712 if (I) return eraseInstFromFunction(*I);
3713 }
3714
3715 if (!Call.use_empty() && !Call.isMustTailCall())
3716 if (Value *ReturnedArg = Call.getReturnedArgOperand()) {
3717 Type *CallTy = Call.getType();
3718 Type *RetArgTy = ReturnedArg->getType();
3719 if (RetArgTy->canLosslesslyBitCastTo(CallTy))
3720 return replaceInstUsesWith(
3721 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
3722 }
3723
3724 // Drop unnecessary kcfi operand bundles from calls that were converted
3725 // into direct calls.
3726 auto Bundle = Call.getOperandBundle(LLVMContext::OB_kcfi);
3727 if (Bundle && !Call.isIndirectCall()) {
3728 DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {
3729 if (CalleeF) {
3730 ConstantInt *FunctionType = nullptr;
3731 ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);
3732
3733 if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))
3734 FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));
3735
3736 if (FunctionType &&
3737 FunctionType->getZExtValue() != ExpectedType->getZExtValue())
3738 dbgs() << Call.getModule()->getName()
3739 << ": warning: kcfi: " << Call.getCaller()->getName()
3740 << ": call to " << CalleeF->getName()
3741 << " using a mismatching function pointer type\n";
3742 }
3743 });
3744
3746 }
3747
3748 if (isRemovableAlloc(&Call, &TLI))
3749 return visitAllocSite(Call);
3750
3751 // Handle intrinsics which can be used in both call and invoke context.
3752 switch (Call.getIntrinsicID()) {
3753 case Intrinsic::experimental_gc_statepoint: {
3754 GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);
3755 SmallPtrSet<Value *, 32> LiveGcValues;
3756 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
3757 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
3758
3759 // Remove the relocation if unused.
3760 if (GCR.use_empty()) {
3762 continue;
3763 }
3764
3765 Value *DerivedPtr = GCR.getDerivedPtr();
3766 Value *BasePtr = GCR.getBasePtr();
3767
3768 // Undef is undef, even after relocation.
3769 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {
3772 continue;
3773 }
3774
3775 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {
3776 // The relocation of null will be null for most any collector.
3777 // TODO: provide a hook for this in GCStrategy. There might be some
3778 // weird collector this property does not hold for.
3779 if (isa<ConstantPointerNull>(DerivedPtr)) {
3780 // Use null-pointer of gc_relocate's type to replace it.
3783 continue;
3784 }
3785
3786 // isKnownNonNull -> nonnull attribute
3787 if (!GCR.hasRetAttr(Attribute::NonNull) &&
3788 isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) {
3789 GCR.addRetAttr(Attribute::NonNull);
3790 // We discovered new fact, re-check users.
3792 }
3793 }
3794
3795 // If we have two copies of the same pointer in the statepoint argument
3796 // list, canonicalize to one. This may let us common gc.relocates.
3797 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
3798 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
3799 auto *OpIntTy = GCR.getOperand(2)->getType();
3800 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
3801 }
3802
3803 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3804 // Canonicalize on the type from the uses to the defs
3805
3806 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3807 LiveGcValues.insert(BasePtr);
3808 LiveGcValues.insert(DerivedPtr);
3809 }
3810 std::optional<OperandBundleUse> Bundle =
3812 unsigned NumOfGCLives = LiveGcValues.size();
3813 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
3814 break;
3815 // We can reduce the size of gc live bundle.
3817 std::vector<Value *> NewLiveGc;
3818 for (Value *V : Bundle->Inputs) {
3819 if (Val2Idx.count(V))
3820 continue;
3821 if (LiveGcValues.count(V)) {
3822 Val2Idx[V] = NewLiveGc.size();
3823 NewLiveGc.push_back(V);
3824 } else
3825 Val2Idx[V] = NumOfGCLives;
3826 }
3827 // Update all gc.relocates
3828 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {
3829 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);
3830 Value *BasePtr = GCR.getBasePtr();
3831 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
3832 "Missed live gc for base pointer");
3833 auto *OpIntTy1 = GCR.getOperand(1)->getType();
3834 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
3835 Value *DerivedPtr = GCR.getDerivedPtr();
3836 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
3837 "Missed live gc for derived pointer");
3838 auto *OpIntTy2 = GCR.getOperand(2)->getType();
3839 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
3840 }
3841 // Create new statepoint instruction.
3842 OperandBundleDef NewBundle("gc-live", NewLiveGc);
3843 return CallBase::Create(&Call, NewBundle);
3844 }
3845 default: { break; }
3846 }
3847
3848 return Changed ? &Call : nullptr;
3849}
3850
3851/// If the callee is a constexpr cast of a function, attempt to move the cast to
3852/// the arguments of the call/invoke.
3853/// CallBrInst is not supported.
3854bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {
3855 auto *Callee =
3856 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3857 if (!Callee)
3858 return false;
3859
3860 assert(!isa<CallBrInst>(Call) &&
3861 "CallBr's don't have a single point after a def to insert at");
3862
3863 // If this is a call to a thunk function, don't remove the cast. Thunks are
3864 // used to transparently forward all incoming parameters and outgoing return
3865 // values, so it's important to leave the cast in place.
3866 if (Callee->hasFnAttribute("thunk"))
3867 return false;
3868
3869 // If this is a call to a naked function, the assembly might be
3870 // using an argument, or otherwise rely on the frame layout,
3871 // the function prototype will mismatch.
3872 if (Callee->hasFnAttribute(Attribute::Naked))
3873 return false;
3874
3875 // If this is a musttail call, the callee's prototype must match the caller's
3876 // prototype with the exception of pointee types. The code below doesn't
3877 // implement that, so we can't do this transform.
3878 // TODO: Do the transform if it only requires adding pointer casts.
3879 if (Call.isMustTailCall())
3880 return false;
3881
3883 const AttributeList &CallerPAL = Call.getAttributes();
3884
3885 // Okay, this is a cast from a function to a different type. Unless doing so
3886 // would cause a type conversion of one of our arguments, change this call to
3887 // be a direct call with arguments casted to the appropriate types.
3888 FunctionType *FT = Callee->getFunctionType();
3889 Type *OldRetTy = Caller->getType();
3890 Type *NewRetTy = FT->getReturnType();
3891
3892 // Check to see if we are changing the return type...
3893 if (OldRetTy != NewRetTy) {
3894
3895 if (NewRetTy->isStructTy())
3896 return false; // TODO: Handle multiple return values.
3897
3898 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
3899 if (Callee->isDeclaration())
3900 return false; // Cannot transform this return value.
3901
3902 if (!Caller->use_empty() &&
3903 // void -> non-void is handled specially
3904 !NewRetTy->isVoidTy())
3905 return false; // Cannot transform this return value.
3906 }
3907
3908 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
3909 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
3910 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
3911 return false; // Attribute not compatible with transformed value.
3912 }
3913
3914 // If the callbase is an invoke instruction, and the return value is
3915 // used by a PHI node in a successor, we cannot change the return type of
3916 // the call because there is no place to put the cast instruction (without
3917 // breaking the critical edge). Bail out in this case.
3918 if (!Caller->use_empty()) {
3919 BasicBlock *PhisNotSupportedBlock = nullptr;
3920 if (auto *II = dyn_cast<InvokeInst>(Caller))
3921 PhisNotSupportedBlock = II->getNormalDest();
3922 if (PhisNotSupportedBlock)
3923 for (User *U : Caller->users())
3924 if (PHINode *PN = dyn_cast<PHINode>(U))
3925 if (PN->getParent() == PhisNotSupportedBlock)
3926 return false;
3927 }
3928 }
3929
3930 unsigned NumActualArgs = Call.arg_size();
3931 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3932
3933 // Prevent us turning:
3934 // declare void @takes_i32_inalloca(i32* inalloca)
3935 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3936 //
3937 // into:
3938 // call void @takes_i32_inalloca(i32* null)
3939 //
3940 // Similarly, avoid folding away bitcasts of byval calls.
3941 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3942 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))
3943 return false;
3944
3945 auto AI = Call.arg_begin();
3946 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3947 Type *ParamTy = FT->getParamType(i);
3948 Type *ActTy = (*AI)->getType();
3949
3950 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
3951 return false; // Cannot transform this parameter value.
3952
3953 // Check if there are any incompatible attributes we cannot drop safely.
3954 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
3957 return false; // Attribute not compatible with transformed value.
3958
3959 if (Call.isInAllocaArgument(i) ||
3960 CallerPAL.hasParamAttr(i, Attribute::Preallocated))
3961 return false; // Cannot transform to and from inalloca/preallocated.
3962
3963 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
3964 return false;
3965
3966 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=
3967 Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))
3968 return false; // Cannot transform to or from byval.
3969 }
3970
3971 if (Callee->isDeclaration()) {
3972 // Do not delete arguments unless we have a function body.
3973 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3974 return false;
3975
3976 // If the callee is just a declaration, don't change the varargsness of the
3977 // call. We don't want to introduce a varargs call where one doesn't
3978 // already exist.
3979 if (FT->isVarArg() != Call.getFunctionType()->isVarArg())
3980 return false;
3981
3982 // If both the callee and the cast type are varargs, we still have to make
3983 // sure the number of fixed parameters are the same or we have the same
3984 // ABI issues as if we introduce a varargs call.
3985 if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&
3986 FT->getNumParams() != Call.getFunctionType()->getNumParams())
3987 return false;
3988 }
3989
3990 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3991 !CallerPAL.isEmpty()) {
3992 // In this case we have more arguments than the new function type, but we
3993 // won't be dropping them. Check that these extra arguments have attributes
3994 // that are compatible with being a vararg call argument.
3995 unsigned SRetIdx;
3996 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
3997 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
3998 return false;
3999 }
4000
4001 // Okay, we decided that this is a safe thing to do: go ahead and start
4002 // inserting cast instructions as necessary.
4005 Args.reserve(NumActualArgs);
4006 ArgAttrs.reserve(NumActualArgs);
4007
4008 // Get any return attributes.
4009 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
4010
4011 // If the return value is not being used, the type may not be compatible
4012 // with the existing attributes. Wipe out any problematic attributes.
4013 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
4014
4015 LLVMContext &Ctx = Call.getContext();
4016 AI = Call.arg_begin();
4017 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4018 Type *ParamTy = FT->getParamType(i);
4019
4020 Value *NewArg = *AI;
4021 if ((*AI)->getType() != ParamTy)
4022 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4023 Args.push_back(NewArg);
4024
4025 // Add any parameter attributes except the ones incompatible with the new
4026 // type. Note that we made sure all incompatible ones are safe to drop.
4029 ArgAttrs.push_back(
4030 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));
4031 }
4032
4033 // If the function takes more arguments than the call was taking, add them
4034 // now.
4035 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4036 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4037 ArgAttrs.push_back(AttributeSet());
4038 }
4039
4040 // If we are removing arguments to the function, emit an obnoxious warning.
4041 if (FT->getNumParams() < NumActualArgs) {
4042 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4043 if (FT->isVarArg()) {
4044 // Add all of the arguments in their promoted form to the arg list.
4045 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4046 Type *PTy = getPromotedType((*AI)->getType());
4047 Value *NewArg = *AI;
4048 if (PTy != (*AI)->getType()) {
4049 // Must promote to pass through va_arg area!
4050 Instruction::CastOps opcode =
4051 CastInst::getCastOpcode(*AI, false, PTy, false);
4052 NewArg = Builder.CreateCast(opcode, *AI, PTy);
4053 }
4054 Args.push_back(NewArg);
4055
4056 // Add any parameter attributes.
4057 ArgAttrs.push_back(CallerPAL.getParamAttrs(i));
4058 }
4059 }
4060 }
4061
4062 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
4063
4064 if (NewRetTy->isVoidTy())
4065 Caller->setName(""); // Void type should not have a name.
4066
4067 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4068 "missing argument attributes");
4069 AttributeList NewCallerPAL = AttributeList::get(
4070 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4071
4073 Call.getOperandBundlesAsDefs(OpBundles);
4074
4075 CallBase *NewCall;
4076 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4077 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4078 II->getUnwindDest(), Args, OpBundles);
4079 } else {
4080 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4081 cast<CallInst>(NewCall)->setTailCallKind(
4082 cast<CallInst>(Caller)->getTailCallKind());
4083 }
4084 NewCall->takeName(Caller);
4085 NewCall->setCallingConv(Call.getCallingConv());
4086 NewCall->setAttributes(NewCallerPAL);
4087
4088 // Preserve prof metadata if any.
4089 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});
4090
4091 // Insert a cast of the return type as necessary.
4092 Instruction *NC = NewCall;
4093 Value *NV = NC;
4094 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4095 if (!NV->getType()->isVoidTy()) {
4097 NC->setDebugLoc(Caller->getDebugLoc());
4098
4099 auto OptInsertPt = NewCall->getInsertionPointAfterDef();
4100 assert(OptInsertPt && "No place to insert cast");
4101 InsertNewInstBefore(NC, *OptInsertPt);
4103 } else {
4104 NV = PoisonValue::get(Caller->getType());
4105 }
4106 }
4107
4108 if (!Caller->use_empty())
4109 replaceInstUsesWith(*Caller, NV);
4110 else if (Caller->hasValueHandle()) {
4111 if (OldRetTy == NV->getType())
4113 else
4114 // We cannot call ValueIsRAUWd with a different type, and the
4115 // actual tracked value will disappear.
4117 }
4118
4119 eraseInstFromFunction(*Caller);
4120 return true;
4121}
4122
4123/// Turn a call to a function created by init_trampoline / adjust_trampoline
4124/// intrinsic pair into a direct call to the underlying function.
4126InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,
4127 IntrinsicInst &Tramp) {
4128 FunctionType *FTy = Call.getFunctionType();
4129 AttributeList Attrs = Call.getAttributes();
4130
4131 // If the call already has the 'nest' attribute somewhere then give up -
4132 // otherwise 'nest' would occur twice after splicing in the chain.
4133 if (Attrs.hasAttrSomewhere(Attribute::Nest))
4134 return nullptr;
4135
4136 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
4137 FunctionType *NestFTy = NestF->getFunctionType();
4138
4139 AttributeList NestAttrs = NestF->getAttributes();
4140 if (!NestAttrs.isEmpty()) {
4141 unsigned NestArgNo = 0;
4142 Type *NestTy = nullptr;
4143 AttributeSet NestAttr;
4144
4145 // Look for a parameter marked with the 'nest' attribute.
4146 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4147 E = NestFTy->param_end();
4148 I != E; ++NestArgNo, ++I) {
4149 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
4150 if (AS.hasAttribute(Attribute::Nest)) {
4151 // Record the parameter type and any other attributes.
4152 NestTy = *I;
4153 NestAttr = AS;
4154 break;
4155 }
4156 }
4157
4158 if (NestTy) {
4159 std::vector<Value*> NewArgs;
4160 std::vector<AttributeSet> NewArgAttrs;
4161 NewArgs.reserve(Call.arg_size() + 1);
4162 NewArgAttrs.reserve(Call.arg_size());
4163
4164 // Insert the nest argument into the call argument list, which may
4165 // mean appending it. Likewise for attributes.
4166
4167 {
4168 unsigned ArgNo = 0;
4169 auto I = Call.arg_begin(), E = Call.arg_end();
4170 do {
4171 if (ArgNo == NestArgNo) {
4172 // Add the chain argument and attributes.
4173 Value *NestVal = Tramp.getArgOperand(2);
4174 if (NestVal->getType() != NestTy)
4175 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4176 NewArgs.push_back(NestVal);
4177 NewArgAttrs.push_back(NestAttr);
4178 }
4179
4180 if (I == E)
4181 break;
4182
4183 // Add the original argument and attributes.
4184 NewArgs.push_back(*I);
4185 NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
4186
4187 ++ArgNo;
4188 ++I;
4189 } while (true);
4190 }
4191
4192 // The trampoline may have been bitcast to a bogus type (FTy).
4193 // Handle this by synthesizing a new function type, equal to FTy
4194 // with the chain parameter inserted.
4195
4196 std::vector<Type*> NewTypes;
4197 NewTypes.reserve(FTy->getNumParams()+1);
4198
4199 // Insert the chain's type into the list of parameter types, which may
4200 // mean appending it.
4201 {
4202 unsigned ArgNo = 0;
4203 FunctionType::param_iterator I = FTy->param_begin(),
4204 E = FTy->param_end();
4205
4206 do {
4207 if (ArgNo == NestArgNo)
4208 // Add the chain's type.
4209 NewTypes.push_back(NestTy);
4210
4211 if (I == E)
4212 break;
4213
4214 // Add the original type.
4215 NewTypes.push_back(*I);
4216
4217 ++ArgNo;
4218 ++I;
4219 } while (true);
4220 }
4221
4222 // Replace the trampoline call with a direct call. Let the generic
4223 // code sort out any function type mismatches.
4224 FunctionType *NewFTy =
4225 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
4226 AttributeList NewPAL =
4227 AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),
4228 Attrs.getRetAttrs(), NewArgAttrs);
4229
4231 Call.getOperandBundlesAsDefs(OpBundles);
4232
4233 Instruction *NewCaller;
4234 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
4235 NewCaller = InvokeInst::Create(NewFTy, NestF, II->getNormalDest(),
4236 II->getUnwindDest(), NewArgs, OpBundles);
4237 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4238 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4239 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4240 NewCaller =
4241 CallBrInst::Create(NewFTy, NestF, CBI->getDefaultDest(),
4242 CBI->getIndirectDests(), NewArgs, OpBundles);
4243 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4244 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
4245 } else {
4246 NewCaller = CallInst::Create(NewFTy, NestF, NewArgs, OpBundles);
4247 cast<CallInst>(NewCaller)->setTailCallKind(
4248 cast<CallInst>(Call).getTailCallKind());
4249 cast<CallInst>(NewCaller)->setCallingConv(
4250 cast<CallInst>(Call).getCallingConv());
4251 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4252 }
4253 NewCaller->setDebugLoc(Call.getDebugLoc());
4254
4255 return NewCaller;
4256 }
4257 }
4258
4259 // Replace the trampoline call with a direct call. Since there is no 'nest'
4260 // parameter, there is no need to adjust the argument list. Let the generic
4261 // code sort out any function type mismatches.
4262 Call.setCalledFunction(FTy, NestF);
4263 return &Call;
4264}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
unsigned Intr
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static SDValue foldBitOrderCrossLogicOp(SDNode *N, SelectionDAG &DAG)
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
static Type * getPromotedType(Type *Ty)
Return the specified type promoted as it would be to pass though a va_arg area.
static Instruction * createOverflowTuple(IntrinsicInst *II, Value *Result, Constant *Overflow)
Creates a result tuple for an overflow intrinsic II with a given Result and a constant Overflow value...
static IntrinsicInst * findInitTrampolineFromAlloca(Value *TrampMem)
static bool removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC, std::function< bool(const IntrinsicInst &)> IsStart)
static bool inputDenormalIsDAZ(const Function &F, const Type *Ty)
static Instruction * reassociateMinMaxWithConstantInOperand(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If this min/max has a matching min/max operand with a constant, try to push the constant operand into...
static bool signBitMustBeTheSame(Value *Op0, Value *Op1, Instruction *CxtI, const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT)
Return true if two values Op0 and Op1 are known to have the same sign.
static Instruction * moveAddAfterMinMax(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0.
static Instruction * simplifyInvariantGroupIntrinsic(IntrinsicInst &II, InstCombinerImpl &IC)
This function transforms launder.invariant.group and strip.invariant.group like: launder(launder(x)) ...
static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, unsigned NumOperands)
static cl::opt< unsigned > GuardWideningWindow("instcombine-guard-widening-window", cl::init(3), cl::desc("How wide an instruction window to bypass looking for " "another guard"))
static bool hasUndefSource(AnyMemTransferInst *MI)
Recognize a memcpy/memmove from a trivially otherwise unused alloca.
static Instruction * foldShuffledIntrinsicOperands(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If all arguments of the intrinsic are unary shuffles with the same mask, try to shuffle after the int...
static Instruction * factorizeMinMaxTree(IntrinsicInst *II)
Reduce a sequence of min/max intrinsics with a common operand.
static Value * simplifyNeonTbl1(const IntrinsicInst &II, InstCombiner::BuilderTy &Builder)
Convert a table lookup to shufflevector if the mask is constant.
static Instruction * foldClampRangeOfTwo(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If we have a clamp pattern like max (min X, 42), 41 – where the output can only be one of two possibl...
static IntrinsicInst * findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, Value *TrampMem)
static std::optional< bool > getKnownSignOrZero(Value *Op, Instruction *CxtI, const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT)
static Instruction * foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC)
static Instruction * foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC)
static IntrinsicInst * findInitTrampoline(Value *Callee)
static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask, const Function &F, Type *Ty)
static Value * reassociateMinMaxWithConstants(IntrinsicInst *II, IRBuilderBase &Builder, const SimplifyQuery &SQ)
If this min/max has a constant operand and an operand that is a matching min/max with a constant oper...
static std::optional< bool > getKnownSign(Value *Op, Instruction *CxtI, const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT)
static CallInst * canonicalizeConstantArg0ToArg1(CallInst &Call)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Metadata * LowAndHigh[]
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
@ Struct
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static bool inputDenormalIsIEEE(const Function &F, const Type *Ty)
Return true if it's possible to assume IEEE treatment of input denormals in F for Val.
Value * RHS
Value * LHS
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
Class for arbitrary precision integers.
Definition: APInt.h:76
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:212
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:207
APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1954
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1433
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1083
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1934
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1941
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2035
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:312
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:284
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1947
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition: APSInt.h:311
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition: APSInt.h:303
This class represents any memset intrinsic.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void updateAffectedValues(AssumeInst *CI)
Update the cache of values being affected by this assumption (i.e.
bool overlaps(const AttributeMask &AM) const
Return true if the builder has any attribute that's in the specified builder.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
bool isEmpty() const
Return true if there are no attributes.
Definition: Attributes.h:951
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:767
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:573