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