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