Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
35294 views
//===- InstCombineCalls.cpp -----------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the visitCall, visitInvoke, and visitCallBr functions.9//10//===----------------------------------------------------------------------===//1112#include "InstCombineInternal.h"13#include "llvm/ADT/APFloat.h"14#include "llvm/ADT/APInt.h"15#include "llvm/ADT/APSInt.h"16#include "llvm/ADT/ArrayRef.h"17#include "llvm/ADT/STLFunctionalExtras.h"18#include "llvm/ADT/SmallBitVector.h"19#include "llvm/ADT/SmallVector.h"20#include "llvm/ADT/Statistic.h"21#include "llvm/Analysis/AliasAnalysis.h"22#include "llvm/Analysis/AssumeBundleQueries.h"23#include "llvm/Analysis/AssumptionCache.h"24#include "llvm/Analysis/InstructionSimplify.h"25#include "llvm/Analysis/Loads.h"26#include "llvm/Analysis/MemoryBuiltins.h"27#include "llvm/Analysis/ValueTracking.h"28#include "llvm/Analysis/VectorUtils.h"29#include "llvm/IR/AttributeMask.h"30#include "llvm/IR/Attributes.h"31#include "llvm/IR/BasicBlock.h"32#include "llvm/IR/Constant.h"33#include "llvm/IR/Constants.h"34#include "llvm/IR/DataLayout.h"35#include "llvm/IR/DebugInfo.h"36#include "llvm/IR/DerivedTypes.h"37#include "llvm/IR/Function.h"38#include "llvm/IR/GlobalVariable.h"39#include "llvm/IR/InlineAsm.h"40#include "llvm/IR/InstrTypes.h"41#include "llvm/IR/Instruction.h"42#include "llvm/IR/Instructions.h"43#include "llvm/IR/IntrinsicInst.h"44#include "llvm/IR/Intrinsics.h"45#include "llvm/IR/IntrinsicsAArch64.h"46#include "llvm/IR/IntrinsicsAMDGPU.h"47#include "llvm/IR/IntrinsicsARM.h"48#include "llvm/IR/IntrinsicsHexagon.h"49#include "llvm/IR/LLVMContext.h"50#include "llvm/IR/Metadata.h"51#include "llvm/IR/PatternMatch.h"52#include "llvm/IR/Statepoint.h"53#include "llvm/IR/Type.h"54#include "llvm/IR/User.h"55#include "llvm/IR/Value.h"56#include "llvm/IR/ValueHandle.h"57#include "llvm/Support/AtomicOrdering.h"58#include "llvm/Support/Casting.h"59#include "llvm/Support/CommandLine.h"60#include "llvm/Support/Compiler.h"61#include "llvm/Support/Debug.h"62#include "llvm/Support/ErrorHandling.h"63#include "llvm/Support/KnownBits.h"64#include "llvm/Support/MathExtras.h"65#include "llvm/Support/raw_ostream.h"66#include "llvm/Transforms/InstCombine/InstCombiner.h"67#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"68#include "llvm/Transforms/Utils/Local.h"69#include "llvm/Transforms/Utils/SimplifyLibCalls.h"70#include <algorithm>71#include <cassert>72#include <cstdint>73#include <optional>74#include <utility>75#include <vector>7677#define DEBUG_TYPE "instcombine"78#include "llvm/Transforms/Utils/InstructionWorklist.h"7980using namespace llvm;81using namespace PatternMatch;8283STATISTIC(NumSimplified, "Number of library calls simplified");8485static cl::opt<unsigned> GuardWideningWindow(86"instcombine-guard-widening-window",87cl::init(3),88cl::desc("How wide an instruction window to bypass looking for "89"another guard"));9091/// Return the specified type promoted as it would be to pass though a va_arg92/// area.93static Type *getPromotedType(Type *Ty) {94if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {95if (ITy->getBitWidth() < 32)96return Type::getInt32Ty(Ty->getContext());97}98return Ty;99}100101/// Recognize a memcpy/memmove from a trivially otherwise unused alloca.102/// TODO: This should probably be integrated with visitAllocSites, but that103/// requires a deeper change to allow either unread or unwritten objects.104static bool hasUndefSource(AnyMemTransferInst *MI) {105auto *Src = MI->getRawSource();106while (isa<GetElementPtrInst>(Src) || isa<BitCastInst>(Src)) {107if (!Src->hasOneUse())108return false;109Src = cast<Instruction>(Src)->getOperand(0);110}111return isa<AllocaInst>(Src) && Src->hasOneUse();112}113114Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {115Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);116MaybeAlign CopyDstAlign = MI->getDestAlign();117if (!CopyDstAlign || *CopyDstAlign < DstAlign) {118MI->setDestAlignment(DstAlign);119return MI;120}121122Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);123MaybeAlign CopySrcAlign = MI->getSourceAlign();124if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {125MI->setSourceAlignment(SrcAlign);126return MI;127}128129// If we have a store to a location which is known constant, we can conclude130// that the store must be storing the constant value (else the memory131// wouldn't be constant), and this must be a noop.132if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {133// Set the size of the copy to 0, it will be deleted on the next iteration.134MI->setLength(Constant::getNullValue(MI->getLength()->getType()));135return MI;136}137138// If the source is provably undef, the memcpy/memmove doesn't do anything139// (unless the transfer is volatile).140if (hasUndefSource(MI) && !MI->isVolatile()) {141// Set the size of the copy to 0, it will be deleted on the next iteration.142MI->setLength(Constant::getNullValue(MI->getLength()->getType()));143return MI;144}145146// If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with147// load/store.148ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());149if (!MemOpLength) return nullptr;150151// Source and destination pointer types are always "i8*" for intrinsic. See152// 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 memmove154// case.155uint64_t Size = MemOpLength->getLimitedValue();156assert(Size && "0-sized memory transferring should be removed already.");157158if (Size > 8 || (Size&(Size-1)))159return nullptr; // If not 1/2/4/8 bytes, exit.160161// If it is an atomic and alignment is less than the size then we will162// introduce the unaligned memory access which will be later transformed163// into libcall in CodeGen. This is not evident performance gain so disable164// it now.165if (isa<AtomicMemTransferInst>(MI))166if (*CopyDstAlign < Size || *CopySrcAlign < Size)167return nullptr;168169// Use an integer load+store unless we can find something better.170IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);171172// If the memcpy has metadata describing the members, see if we can get the173// TBAA, scope and noalias tags describing our copy.174AAMDNodes AACopyMD = MI->getAAMetadata().adjustForAccess(Size);175176Value *Src = MI->getArgOperand(1);177Value *Dest = MI->getArgOperand(0);178LoadInst *L = Builder.CreateLoad(IntType, Src);179// Alignment from the mem intrinsic will be better, so use it.180L->setAlignment(*CopySrcAlign);181L->setAAMetadata(AACopyMD);182MDNode *LoopMemParallelMD =183MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);184if (LoopMemParallelMD)185L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);186MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);187if (AccessGroupMD)188L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);189190StoreInst *S = Builder.CreateStore(L, Dest);191// Alignment from the mem intrinsic will be better, so use it.192S->setAlignment(*CopyDstAlign);193S->setAAMetadata(AACopyMD);194if (LoopMemParallelMD)195S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);196if (AccessGroupMD)197S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);198S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);199200if (auto *MT = dyn_cast<MemTransferInst>(MI)) {201// non-atomics can be volatile202L->setVolatile(MT->isVolatile());203S->setVolatile(MT->isVolatile());204}205if (isa<AtomicMemTransferInst>(MI)) {206// atomics have to be unordered207L->setOrdering(AtomicOrdering::Unordered);208S->setOrdering(AtomicOrdering::Unordered);209}210211// Set the size of the copy to 0, it will be deleted on the next iteration.212MI->setLength(Constant::getNullValue(MemOpLength->getType()));213return MI;214}215216Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) {217const Align KnownAlignment =218getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);219MaybeAlign MemSetAlign = MI->getDestAlign();220if (!MemSetAlign || *MemSetAlign < KnownAlignment) {221MI->setDestAlignment(KnownAlignment);222return MI;223}224225// If we have a store to a location which is known constant, we can conclude226// that the store must be storing the constant value (else the memory227// wouldn't be constant), and this must be a noop.228if (!isModSet(AA->getModRefInfoMask(MI->getDest()))) {229// Set the size of the copy to 0, it will be deleted on the next iteration.230MI->setLength(Constant::getNullValue(MI->getLength()->getType()));231return MI;232}233234// Remove memset with an undef value.235// FIXME: This is technically incorrect because it might overwrite a poison236// value. Change to PoisonValue once #52930 is resolved.237if (isa<UndefValue>(MI->getValue())) {238// Set the size of the copy to 0, it will be deleted on the next iteration.239MI->setLength(Constant::getNullValue(MI->getLength()->getType()));240return MI;241}242243// Extract the length and alignment and fill if they are constant.244ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());245ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());246if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))247return nullptr;248const uint64_t Len = LenC->getLimitedValue();249assert(Len && "0-sized memory setting should be removed already.");250const Align Alignment = MI->getDestAlign().valueOrOne();251252// If it is an atomic and alignment is less than the size then we will253// introduce the unaligned memory access which will be later transformed254// into libcall in CodeGen. This is not evident performance gain so disable255// it now.256if (isa<AtomicMemSetInst>(MI))257if (Alignment < Len)258return nullptr;259260// memset(s,c,n) -> store s, c (for n=1,2,4,8)261if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {262Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.263264Value *Dest = MI->getDest();265266// Extract the fill value and store.267const uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;268Constant *FillVal = ConstantInt::get(ITy, Fill);269StoreInst *S = Builder.CreateStore(FillVal, Dest, MI->isVolatile());270S->copyMetadata(*MI, LLVMContext::MD_DIAssignID);271auto replaceOpForAssignmentMarkers = [FillC, FillVal](auto *DbgAssign) {272if (llvm::is_contained(DbgAssign->location_ops(), FillC))273DbgAssign->replaceVariableLocationOp(FillC, FillVal);274};275for_each(at::getAssignmentMarkers(S), replaceOpForAssignmentMarkers);276for_each(at::getDVRAssignmentMarkers(S), replaceOpForAssignmentMarkers);277278S->setAlignment(Alignment);279if (isa<AtomicMemSetInst>(MI))280S->setOrdering(AtomicOrdering::Unordered);281282// Set the size of the copy to 0, it will be deleted on the next iteration.283MI->setLength(Constant::getNullValue(LenC->getType()));284return MI;285}286287return nullptr;288}289290// TODO, Obvious Missing Transforms:291// * Narrow width by halfs excluding zero/undef lanes292Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) {293Value *LoadPtr = II.getArgOperand(0);294const Align Alignment =295cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();296297// If the mask is all ones or undefs, this is a plain vector load of the 1st298// argument.299if (maskIsAllOneOrUndef(II.getArgOperand(2))) {300LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,301"unmaskedload");302L->copyMetadata(II);303return L;304}305306// If we can unconditionally load from this address, replace with a307// load/select idiom. TODO: use DT for context sensitive query308if (isDereferenceablePointer(LoadPtr, II.getType(),309II.getDataLayout(), &II, &AC)) {310LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,311"unmaskedload");312LI->copyMetadata(II);313return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));314}315316return nullptr;317}318319// TODO, Obvious Missing Transforms:320// * Single constant active lane -> store321// * Narrow width by halfs excluding zero/undef lanes322Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) {323auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));324if (!ConstMask)325return nullptr;326327// If the mask is all zeros, this instruction does nothing.328if (ConstMask->isNullValue())329return eraseInstFromFunction(II);330331// If the mask is all ones, this is a plain vector store of the 1st argument.332if (ConstMask->isAllOnesValue()) {333Value *StorePtr = II.getArgOperand(1);334Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();335StoreInst *S =336new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);337S->copyMetadata(II);338return S;339}340341if (isa<ScalableVectorType>(ConstMask->getType()))342return nullptr;343344// Use masked off lanes to simplify operands via SimplifyDemandedVectorElts345APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);346APInt PoisonElts(DemandedElts.getBitWidth(), 0);347if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,348PoisonElts))349return replaceOperand(II, 0, V);350351return nullptr;352}353354// TODO, Obvious Missing Transforms:355// * Single constant active lane load -> load356// * Dereferenceable address & few lanes -> scalarize speculative load/selects357// * Adjacent vector addresses -> masked.load358// * Narrow width by halfs excluding zero/undef lanes359// * Vector incrementing address -> vector masked load360Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) {361auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));362if (!ConstMask)363return nullptr;364365// Vector splat address w/known mask -> scalar load366// Fold the gather to load the source vector first lane367// because it is reloading the same value each time368if (ConstMask->isAllOnesValue())369if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) {370auto *VecTy = cast<VectorType>(II.getType());371const Align Alignment =372cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();373LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,374Alignment, "load.scalar");375Value *Shuf =376Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast");377return replaceInstUsesWith(II, cast<Instruction>(Shuf));378}379380return nullptr;381}382383// TODO, Obvious Missing Transforms:384// * Single constant active lane -> store385// * Adjacent vector addresses -> masked.store386// * Narrow store width by halfs excluding zero/undef lanes387// * Vector incrementing address -> vector masked store388Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) {389auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));390if (!ConstMask)391return nullptr;392393// If the mask is all zeros, a scatter does nothing.394if (ConstMask->isNullValue())395return eraseInstFromFunction(II);396397// Vector splat address -> scalar store398if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) {399// scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr400if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) {401if (maskContainsAllOneOrUndef(ConstMask)) {402Align Alignment =403cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();404StoreInst *S = new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false,405Alignment);406S->copyMetadata(II);407return S;408}409}410// scatter(vector, splat(ptr), splat(true)) -> store extract(vector,411// lastlane), ptr412if (ConstMask->isAllOnesValue()) {413Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue();414VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType());415ElementCount VF = WideLoadTy->getElementCount();416Value *RunTimeVF = Builder.CreateElementCount(Builder.getInt32Ty(), VF);417Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1));418Value *Extract =419Builder.CreateExtractElement(II.getArgOperand(0), LastLane);420StoreInst *S =421new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment);422S->copyMetadata(II);423return S;424}425}426if (isa<ScalableVectorType>(ConstMask->getType()))427return nullptr;428429// Use masked off lanes to simplify operands via SimplifyDemandedVectorElts430APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);431APInt PoisonElts(DemandedElts.getBitWidth(), 0);432if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts,433PoisonElts))434return replaceOperand(II, 0, V);435if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts,436PoisonElts))437return replaceOperand(II, 1, V);438439return nullptr;440}441442/// This function transforms launder.invariant.group and strip.invariant.group443/// like:444/// launder(launder(%x)) -> launder(%x) (the result is not the argument)445/// launder(strip(%x)) -> launder(%x)446/// strip(strip(%x)) -> strip(%x) (the result is not the argument)447/// strip(launder(%x)) -> strip(%x)448/// This is legal because it preserves the most recent information about449/// the presence or absence of invariant.group.450static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,451InstCombinerImpl &IC) {452auto *Arg = II.getArgOperand(0);453auto *StrippedArg = Arg->stripPointerCasts();454auto *StrippedInvariantGroupsArg = StrippedArg;455while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) {456if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group &&457Intr->getIntrinsicID() != Intrinsic::strip_invariant_group)458break;459StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();460}461if (StrippedArg == StrippedInvariantGroupsArg)462return nullptr; // No launders/strips to remove.463464Value *Result = nullptr;465466if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)467Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);468else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)469Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);470else471llvm_unreachable(472"simplifyInvariantGroupIntrinsic only handles launder and strip");473if (Result->getType()->getPointerAddressSpace() !=474II.getType()->getPointerAddressSpace())475Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());476477return cast<Instruction>(Result);478}479480static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) {481assert((II.getIntrinsicID() == Intrinsic::cttz ||482II.getIntrinsicID() == Intrinsic::ctlz) &&483"Expected cttz or ctlz intrinsic");484bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;485Value *Op0 = II.getArgOperand(0);486Value *Op1 = II.getArgOperand(1);487Value *X;488// ctlz(bitreverse(x)) -> cttz(x)489// cttz(bitreverse(x)) -> ctlz(x)490if (match(Op0, m_BitReverse(m_Value(X)))) {491Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;492Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());493return CallInst::Create(F, {X, II.getArgOperand(1)});494}495496if (II.getType()->isIntOrIntVectorTy(1)) {497// ctlz/cttz i1 Op0 --> not Op0498if (match(Op1, m_Zero()))499return BinaryOperator::CreateNot(Op0);500// If zero is poison, then the input can be assumed to be "true", so the501// instruction simplifies to "false".502assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1");503return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType()));504}505506// If ctlz/cttz is only used as a shift amount, set is_zero_poison to true.507if (II.hasOneUse() && match(Op1, m_Zero()) &&508match(II.user_back(), m_Shift(m_Value(), m_Specific(&II)))) {509II.dropUBImplyingAttrsAndMetadata();510return IC.replaceOperand(II, 1, IC.Builder.getTrue());511}512513Constant *C;514515if (IsTZ) {516// cttz(-x) -> cttz(x)517if (match(Op0, m_Neg(m_Value(X))))518return IC.replaceOperand(II, 0, X);519520// cttz(-x & x) -> cttz(x)521if (match(Op0, m_c_And(m_Neg(m_Value(X)), m_Deferred(X))))522return IC.replaceOperand(II, 0, X);523524// cttz(sext(x)) -> cttz(zext(x))525if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) {526auto *Zext = IC.Builder.CreateZExt(X, II.getType());527auto *CttzZext =528IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1);529return IC.replaceInstUsesWith(II, CttzZext);530}531532// Zext doesn't change the number of trailing zeros, so narrow:533// cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'.534if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) {535auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X,536IC.Builder.getTrue());537auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType());538return IC.replaceInstUsesWith(II, ZextCttz);539}540541// cttz(abs(x)) -> cttz(x)542// cttz(nabs(x)) -> cttz(x)543Value *Y;544SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;545if (SPF == SPF_ABS || SPF == SPF_NABS)546return IC.replaceOperand(II, 0, X);547548if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))549return IC.replaceOperand(II, 0, X);550551// cttz(shl(%const, %val), 1) --> add(cttz(%const, 1), %val)552if (match(Op0, m_Shl(m_ImmConstant(C), m_Value(X))) &&553match(Op1, m_One())) {554Value *ConstCttz =555IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);556return BinaryOperator::CreateAdd(ConstCttz, X);557}558559// cttz(lshr exact (%const, %val), 1) --> sub(cttz(%const, 1), %val)560if (match(Op0, m_Exact(m_LShr(m_ImmConstant(C), m_Value(X)))) &&561match(Op1, m_One())) {562Value *ConstCttz =563IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, C, Op1);564return BinaryOperator::CreateSub(ConstCttz, X);565}566567// cttz(add(lshr(UINT_MAX, %val), 1)) --> sub(width, %val)568if (match(Op0, m_Add(m_LShr(m_AllOnes(), m_Value(X)), m_One()))) {569Value *Width =570ConstantInt::get(II.getType(), II.getType()->getScalarSizeInBits());571return BinaryOperator::CreateSub(Width, X);572}573} else {574// ctlz(lshr(%const, %val), 1) --> add(ctlz(%const, 1), %val)575if (match(Op0, m_LShr(m_ImmConstant(C), m_Value(X))) &&576match(Op1, m_One())) {577Value *ConstCtlz =578IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);579return BinaryOperator::CreateAdd(ConstCtlz, X);580}581582// ctlz(shl nuw (%const, %val), 1) --> sub(ctlz(%const, 1), %val)583if (match(Op0, m_NUWShl(m_ImmConstant(C), m_Value(X))) &&584match(Op1, m_One())) {585Value *ConstCtlz =586IC.Builder.CreateBinaryIntrinsic(Intrinsic::ctlz, C, Op1);587return BinaryOperator::CreateSub(ConstCtlz, X);588}589}590591KnownBits Known = IC.computeKnownBits(Op0, 0, &II);592593// Create a mask for bits above (ctlz) or below (cttz) the first known one.594unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()595: Known.countMaxLeadingZeros();596unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()597: Known.countMinLeadingZeros();598599// If all bits above (ctlz) or below (cttz) the first known one are known600// zero, this value is constant.601// FIXME: This should be in InstSimplify because we're replacing an602// instruction with a constant.603if (PossibleZeros == DefiniteZeros) {604auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);605return IC.replaceInstUsesWith(II, C);606}607608// If the input to cttz/ctlz is known to be non-zero,609// then change the 'ZeroIsPoison' parameter to 'true'610// because we know the zero behavior can't affect the result.611if (!Known.One.isZero() ||612isKnownNonZero(Op0, IC.getSimplifyQuery().getWithInstruction(&II))) {613if (!match(II.getArgOperand(1), m_One()))614return IC.replaceOperand(II, 1, IC.Builder.getTrue());615}616617// Add range attribute since known bits can't completely reflect what we know.618unsigned BitWidth = Op0->getType()->getScalarSizeInBits();619if (BitWidth != 1 && !II.hasRetAttr(Attribute::Range) &&620!II.getMetadata(LLVMContext::MD_range)) {621ConstantRange Range(APInt(BitWidth, DefiniteZeros),622APInt(BitWidth, PossibleZeros + 1));623II.addRangeRetAttr(Range);624return &II;625}626627return nullptr;628}629630static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) {631assert(II.getIntrinsicID() == Intrinsic::ctpop &&632"Expected ctpop intrinsic");633Type *Ty = II.getType();634unsigned BitWidth = Ty->getScalarSizeInBits();635Value *Op0 = II.getArgOperand(0);636Value *X, *Y;637638// ctpop(bitreverse(x)) -> ctpop(x)639// ctpop(bswap(x)) -> ctpop(x)640if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X))))641return IC.replaceOperand(II, 0, X);642643// ctpop(rot(x)) -> ctpop(x)644if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) ||645match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) &&646X == Y)647return IC.replaceOperand(II, 0, X);648649// ctpop(x | -x) -> bitwidth - cttz(x, false)650if (Op0->hasOneUse() &&651match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) {652Function *F =653Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);654auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()});655auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth));656return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz));657}658659// ctpop(~x & (x - 1)) -> cttz(x, false)660if (match(Op0,661m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) {662Function *F =663Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty);664return CallInst::Create(F, {X, IC.Builder.getFalse()});665}666667// Zext doesn't change the number of set bits, so narrow:668// ctpop (zext X) --> zext (ctpop X)669if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {670Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X);671return CastInst::Create(Instruction::ZExt, NarrowPop, Ty);672}673674KnownBits Known(BitWidth);675IC.computeKnownBits(Op0, Known, 0, &II);676677// If all bits are zero except for exactly one fixed bit, then the result678// must be 0 or 1, and we can get that answer by shifting to LSB:679// ctpop (X & 32) --> (X & 32) >> 5680// TODO: Investigate removing this as its likely unnecessary given the below681// `isKnownToBeAPowerOfTwo` check.682if ((~Known.Zero).isPowerOf2())683return BinaryOperator::CreateLShr(684Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2()));685686// More generally we can also handle non-constant power of 2 patterns such as687// shl/shr(Pow2, X), (X & -X), etc... by transforming:688// ctpop(Pow2OrZero) --> icmp ne X, 0689if (IC.isKnownToBeAPowerOfTwo(Op0, /* OrZero */ true))690return CastInst::Create(Instruction::ZExt,691IC.Builder.CreateICmp(ICmpInst::ICMP_NE, Op0,692Constant::getNullValue(Ty)),693Ty);694695// Add range attribute since known bits can't completely reflect what we know.696if (BitWidth != 1 && !II.hasRetAttr(Attribute::Range) &&697!II.getMetadata(LLVMContext::MD_range)) {698ConstantRange Range(APInt(BitWidth, Known.countMinPopulation()),699APInt(BitWidth, Known.countMaxPopulation() + 1));700II.addRangeRetAttr(Range);701return &II;702}703704return nullptr;705}706707/// Convert a table lookup to shufflevector if the mask is constant.708/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in709/// which case we could lower the shufflevector with rev64 instructions710/// as it's actually a byte reverse.711static Value *simplifyNeonTbl1(const IntrinsicInst &II,712InstCombiner::BuilderTy &Builder) {713// Bail out if the mask is not a constant.714auto *C = dyn_cast<Constant>(II.getArgOperand(1));715if (!C)716return nullptr;717718auto *VecTy = cast<FixedVectorType>(II.getType());719unsigned NumElts = VecTy->getNumElements();720721// Only perform this transformation for <8 x i8> vector types.722if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)723return nullptr;724725int Indexes[8];726727for (unsigned I = 0; I < NumElts; ++I) {728Constant *COp = C->getAggregateElement(I);729730if (!COp || !isa<ConstantInt>(COp))731return nullptr;732733Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();734735// Make sure the mask indices are in range.736if ((unsigned)Indexes[I] >= NumElts)737return nullptr;738}739740auto *V1 = II.getArgOperand(0);741auto *V2 = Constant::getNullValue(V1->getType());742return Builder.CreateShuffleVector(V1, V2, ArrayRef(Indexes));743}744745// Returns true iff the 2 intrinsics have the same operands, limiting the746// comparison to the first NumOperands.747static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,748unsigned NumOperands) {749assert(I.arg_size() >= NumOperands && "Not enough operands");750assert(E.arg_size() >= NumOperands && "Not enough operands");751for (unsigned i = 0; i < NumOperands; i++)752if (I.getArgOperand(i) != E.getArgOperand(i))753return false;754return true;755}756757// Remove trivially empty start/end intrinsic ranges, i.e. a start758// immediately followed by an end (ignoring debuginfo or other759// start/end intrinsics in between). As this handles only the most trivial760// cases, tracking the nesting level is not needed:761//762// call @llvm.foo.start(i1 0)763// call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed764// call @llvm.foo.end(i1 0)765// call @llvm.foo.end(i1 0) ; &I766static bool767removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC,768std::function<bool(const IntrinsicInst &)> IsStart) {769// We start from the end intrinsic and scan backwards, so that InstCombine770// has already processed (and potentially removed) all the instructions771// before the end intrinsic.772BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend());773for (; BI != BE; ++BI) {774if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) {775if (I->isDebugOrPseudoInst() ||776I->getIntrinsicID() == EndI.getIntrinsicID())777continue;778if (IsStart(*I)) {779if (haveSameOperands(EndI, *I, EndI.arg_size())) {780IC.eraseInstFromFunction(*I);781IC.eraseInstFromFunction(EndI);782return true;783}784// Skip start intrinsics that don't pair with this end intrinsic.785continue;786}787}788break;789}790791return false;792}793794Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) {795removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) {796return I.getIntrinsicID() == Intrinsic::vastart ||797I.getIntrinsicID() == Intrinsic::vacopy;798});799return nullptr;800}801802static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) {803assert(Call.arg_size() > 1 && "Need at least 2 args to swap");804Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);805if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {806Call.setArgOperand(0, Arg1);807Call.setArgOperand(1, Arg0);808return &Call;809}810return nullptr;811}812813/// Creates a result tuple for an overflow intrinsic \p II with a given814/// \p Result and a constant \p Overflow value.815static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result,816Constant *Overflow) {817Constant *V[] = {PoisonValue::get(Result->getType()), Overflow};818StructType *ST = cast<StructType>(II->getType());819Constant *Struct = ConstantStruct::get(ST, V);820return InsertValueInst::Create(Struct, Result, 0);821}822823Instruction *824InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {825WithOverflowInst *WO = cast<WithOverflowInst>(II);826Value *OperationResult = nullptr;827Constant *OverflowResult = nullptr;828if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),829WO->getRHS(), *WO, OperationResult, OverflowResult))830return createOverflowTuple(WO, OperationResult, OverflowResult);831return nullptr;832}833834static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {835Ty = Ty->getScalarType();836return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;837}838839static bool inputDenormalIsDAZ(const Function &F, const Type *Ty) {840Ty = Ty->getScalarType();841return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();842}843844/// \returns the compare predicate type if the test performed by845/// llvm.is.fpclass(x, \p Mask) is equivalent to fcmp o__ x, 0.0 with the846/// floating-point environment assumed for \p F for type \p Ty847static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask,848const Function &F, Type *Ty) {849switch (static_cast<unsigned>(Mask)) {850case fcZero:851if (inputDenormalIsIEEE(F, Ty))852return FCmpInst::FCMP_OEQ;853break;854case fcZero | fcSubnormal:855if (inputDenormalIsDAZ(F, Ty))856return FCmpInst::FCMP_OEQ;857break;858case fcPositive | fcNegZero:859if (inputDenormalIsIEEE(F, Ty))860return FCmpInst::FCMP_OGE;861break;862case fcPositive | fcNegZero | fcNegSubnormal:863if (inputDenormalIsDAZ(F, Ty))864return FCmpInst::FCMP_OGE;865break;866case fcPosSubnormal | fcPosNormal | fcPosInf:867if (inputDenormalIsIEEE(F, Ty))868return FCmpInst::FCMP_OGT;869break;870case fcNegative | fcPosZero:871if (inputDenormalIsIEEE(F, Ty))872return FCmpInst::FCMP_OLE;873break;874case fcNegative | fcPosZero | fcPosSubnormal:875if (inputDenormalIsDAZ(F, Ty))876return FCmpInst::FCMP_OLE;877break;878case fcNegSubnormal | fcNegNormal | fcNegInf:879if (inputDenormalIsIEEE(F, Ty))880return FCmpInst::FCMP_OLT;881break;882case fcPosNormal | fcPosInf:883if (inputDenormalIsDAZ(F, Ty))884return FCmpInst::FCMP_OGT;885break;886case fcNegNormal | fcNegInf:887if (inputDenormalIsDAZ(F, Ty))888return FCmpInst::FCMP_OLT;889break;890case ~fcZero & ~fcNan:891if (inputDenormalIsIEEE(F, Ty))892return FCmpInst::FCMP_ONE;893break;894case ~(fcZero | fcSubnormal) & ~fcNan:895if (inputDenormalIsDAZ(F, Ty))896return FCmpInst::FCMP_ONE;897break;898default:899break;900}901902return FCmpInst::BAD_FCMP_PREDICATE;903}904905Instruction *InstCombinerImpl::foldIntrinsicIsFPClass(IntrinsicInst &II) {906Value *Src0 = II.getArgOperand(0);907Value *Src1 = II.getArgOperand(1);908const ConstantInt *CMask = cast<ConstantInt>(Src1);909FPClassTest Mask = static_cast<FPClassTest>(CMask->getZExtValue());910const bool IsUnordered = (Mask & fcNan) == fcNan;911const bool IsOrdered = (Mask & fcNan) == fcNone;912const FPClassTest OrderedMask = Mask & ~fcNan;913const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;914915const bool IsStrict =916II.getFunction()->getAttributes().hasFnAttr(Attribute::StrictFP);917918Value *FNegSrc;919if (match(Src0, m_FNeg(m_Value(FNegSrc)))) {920// is.fpclass (fneg x), mask -> is.fpclass x, (fneg mask)921922II.setArgOperand(1, ConstantInt::get(Src1->getType(), fneg(Mask)));923return replaceOperand(II, 0, FNegSrc);924}925926Value *FAbsSrc;927if (match(Src0, m_FAbs(m_Value(FAbsSrc)))) {928II.setArgOperand(1, ConstantInt::get(Src1->getType(), inverse_fabs(Mask)));929return replaceOperand(II, 0, FAbsSrc);930}931932if ((OrderedMask == fcInf || OrderedInvertedMask == fcInf) &&933(IsOrdered || IsUnordered) && !IsStrict) {934// is.fpclass(x, fcInf) -> fcmp oeq fabs(x), +inf935// is.fpclass(x, ~fcInf) -> fcmp one fabs(x), +inf936// is.fpclass(x, fcInf|fcNan) -> fcmp ueq fabs(x), +inf937// is.fpclass(x, ~(fcInf|fcNan)) -> fcmp une fabs(x), +inf938Constant *Inf = ConstantFP::getInfinity(Src0->getType());939FCmpInst::Predicate Pred =940IsUnordered ? FCmpInst::FCMP_UEQ : FCmpInst::FCMP_OEQ;941if (OrderedInvertedMask == fcInf)942Pred = IsUnordered ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_ONE;943944Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Src0);945Value *CmpInf = Builder.CreateFCmp(Pred, Fabs, Inf);946CmpInf->takeName(&II);947return replaceInstUsesWith(II, CmpInf);948}949950if ((OrderedMask == fcPosInf || OrderedMask == fcNegInf) &&951(IsOrdered || IsUnordered) && !IsStrict) {952// is.fpclass(x, fcPosInf) -> fcmp oeq x, +inf953// is.fpclass(x, fcNegInf) -> fcmp oeq x, -inf954// is.fpclass(x, fcPosInf|fcNan) -> fcmp ueq x, +inf955// is.fpclass(x, fcNegInf|fcNan) -> fcmp ueq x, -inf956Constant *Inf =957ConstantFP::getInfinity(Src0->getType(), OrderedMask == fcNegInf);958Value *EqInf = IsUnordered ? Builder.CreateFCmpUEQ(Src0, Inf)959: Builder.CreateFCmpOEQ(Src0, Inf);960961EqInf->takeName(&II);962return replaceInstUsesWith(II, EqInf);963}964965if ((OrderedInvertedMask == fcPosInf || OrderedInvertedMask == fcNegInf) &&966(IsOrdered || IsUnordered) && !IsStrict) {967// is.fpclass(x, ~fcPosInf) -> fcmp one x, +inf968// is.fpclass(x, ~fcNegInf) -> fcmp one x, -inf969// is.fpclass(x, ~fcPosInf|fcNan) -> fcmp une x, +inf970// is.fpclass(x, ~fcNegInf|fcNan) -> fcmp une x, -inf971Constant *Inf = ConstantFP::getInfinity(Src0->getType(),972OrderedInvertedMask == fcNegInf);973Value *NeInf = IsUnordered ? Builder.CreateFCmpUNE(Src0, Inf)974: Builder.CreateFCmpONE(Src0, Inf);975NeInf->takeName(&II);976return replaceInstUsesWith(II, NeInf);977}978979if (Mask == fcNan && !IsStrict) {980// Equivalent of isnan. Replace with standard fcmp if we don't care about FP981// exceptions.982Value *IsNan =983Builder.CreateFCmpUNO(Src0, ConstantFP::getZero(Src0->getType()));984IsNan->takeName(&II);985return replaceInstUsesWith(II, IsNan);986}987988if (Mask == (~fcNan & fcAllFlags) && !IsStrict) {989// Equivalent of !isnan. Replace with standard fcmp.990Value *FCmp =991Builder.CreateFCmpORD(Src0, ConstantFP::getZero(Src0->getType()));992FCmp->takeName(&II);993return replaceInstUsesWith(II, FCmp);994}995996FCmpInst::Predicate PredType = FCmpInst::BAD_FCMP_PREDICATE;997998// Try to replace with an fcmp with 0999//1000// is.fpclass(x, fcZero) -> fcmp oeq x, 0.01001// is.fpclass(x, fcZero | fcNan) -> fcmp ueq x, 0.01002// is.fpclass(x, ~fcZero & ~fcNan) -> fcmp one x, 0.01003// is.fpclass(x, ~fcZero) -> fcmp une x, 0.01004//1005// is.fpclass(x, fcPosSubnormal | fcPosNormal | fcPosInf) -> fcmp ogt x, 0.01006// is.fpclass(x, fcPositive | fcNegZero) -> fcmp oge x, 0.01007//1008// is.fpclass(x, fcNegSubnormal | fcNegNormal | fcNegInf) -> fcmp olt x, 0.01009// is.fpclass(x, fcNegative | fcPosZero) -> fcmp ole x, 0.01010//1011if (!IsStrict && (IsOrdered || IsUnordered) &&1012(PredType = fpclassTestIsFCmp0(OrderedMask, *II.getFunction(),1013Src0->getType())) !=1014FCmpInst::BAD_FCMP_PREDICATE) {1015Constant *Zero = ConstantFP::getZero(Src0->getType());1016// Equivalent of == 0.1017Value *FCmp = Builder.CreateFCmp(1018IsUnordered ? FCmpInst::getUnorderedPredicate(PredType) : PredType,1019Src0, Zero);10201021FCmp->takeName(&II);1022return replaceInstUsesWith(II, FCmp);1023}10241025KnownFPClass Known = computeKnownFPClass(Src0, Mask, &II);10261027// Clear test bits we know must be false from the source value.1028// fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other1029// fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other1030if ((Mask & Known.KnownFPClasses) != Mask) {1031II.setArgOperand(10321, ConstantInt::get(Src1->getType(), Mask & Known.KnownFPClasses));1033return &II;1034}10351036// If none of the tests which can return false are possible, fold to true.1037// fp_class (nnan x), ~(qnan|snan) -> true1038// fp_class (ninf x), ~(ninf|pinf) -> true1039if (Mask == Known.KnownFPClasses)1040return replaceInstUsesWith(II, ConstantInt::get(II.getType(), true));10411042return nullptr;1043}10441045static std::optional<bool> getKnownSign(Value *Op, const SimplifyQuery &SQ) {1046KnownBits Known = computeKnownBits(Op, /*Depth=*/0, SQ);1047if (Known.isNonNegative())1048return false;1049if (Known.isNegative())1050return true;10511052Value *X, *Y;1053if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))1054return isImpliedByDomCondition(ICmpInst::ICMP_SLT, X, Y, SQ.CxtI, SQ.DL);10551056return std::nullopt;1057}10581059static std::optional<bool> getKnownSignOrZero(Value *Op,1060const SimplifyQuery &SQ) {1061if (std::optional<bool> Sign = getKnownSign(Op, SQ))1062return Sign;10631064Value *X, *Y;1065if (match(Op, m_NSWSub(m_Value(X), m_Value(Y))))1066return isImpliedByDomCondition(ICmpInst::ICMP_SLE, X, Y, SQ.CxtI, SQ.DL);10671068return std::nullopt;1069}10701071/// Return true if two values \p Op0 and \p Op1 are known to have the same sign.1072static bool signBitMustBeTheSame(Value *Op0, Value *Op1,1073const SimplifyQuery &SQ) {1074std::optional<bool> Known1 = getKnownSign(Op1, SQ);1075if (!Known1)1076return false;1077std::optional<bool> Known0 = getKnownSign(Op0, SQ);1078if (!Known0)1079return false;1080return *Known0 == *Known1;1081}10821083/// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This1084/// can trigger other combines.1085static Instruction *moveAddAfterMinMax(IntrinsicInst *II,1086InstCombiner::BuilderTy &Builder) {1087Intrinsic::ID MinMaxID = II->getIntrinsicID();1088assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||1089MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&1090"Expected a min or max intrinsic");10911092// TODO: Match vectors with undef elements, but undef may not propagate.1093Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);1094Value *X;1095const APInt *C0, *C1;1096if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) ||1097!match(Op1, m_APInt(C1)))1098return nullptr;10991100// Check for necessary no-wrap and overflow constraints.1101bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;1102auto *Add = cast<BinaryOperator>(Op0);1103if ((IsSigned && !Add->hasNoSignedWrap()) ||1104(!IsSigned && !Add->hasNoUnsignedWrap()))1105return nullptr;11061107// If the constant difference overflows, then instsimplify should reduce the1108// min/max to the add or C1.1109bool Overflow;1110APInt CDiff =1111IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow);1112assert(!Overflow && "Expected simplify of min/max");11131114// min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C01115// Note: the "mismatched" no-overflow setting does not propagate.1116Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff);1117Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC);1118return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1))1119: BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1));1120}1121/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.1122Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) {1123Type *Ty = MinMax1.getType();11241125// We are looking for a tree of:1126// max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))1127// Where the min and max could be reversed1128Instruction *MinMax2;1129BinaryOperator *AddSub;1130const APInt *MinValue, *MaxValue;1131if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {1132if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))1133return nullptr;1134} else if (match(&MinMax1,1135m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {1136if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))1137return nullptr;1138} else1139return nullptr;11401141// Check that the constants clamp a saturate, and that the new type would be1142// sensible to convert to.1143if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)1144return nullptr;1145// In what bitwidth can this be treated as saturating arithmetics?1146unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;1147// FIXME: This isn't quite right for vectors, but using the scalar type is a1148// good first approximation for what should be done there.1149if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))1150return nullptr;11511152// Also make sure that the inner min/max and the add/sub have one use.1153if (!MinMax2->hasOneUse() || !AddSub->hasOneUse())1154return nullptr;11551156// Create the new type (which can be a vector type)1157Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);11581159Intrinsic::ID IntrinsicID;1160if (AddSub->getOpcode() == Instruction::Add)1161IntrinsicID = Intrinsic::sadd_sat;1162else if (AddSub->getOpcode() == Instruction::Sub)1163IntrinsicID = Intrinsic::ssub_sat;1164else1165return nullptr;11661167// The two operands of the add/sub must be nsw-truncatable to the NewTy. This1168// is usually achieved via a sext from a smaller type.1169if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) >1170NewBitWidth ||1171ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth)1172return nullptr;11731174// Finally create and return the sat intrinsic, truncated to the new type1175Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);1176Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy);1177Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy);1178Value *Sat = Builder.CreateCall(F, {AT, BT});1179return CastInst::Create(Instruction::SExt, Sat, Ty);1180}118111821183/// If we have a clamp pattern like max (min X, 42), 41 -- where the output1184/// can only be one of two possible constant values -- turn that into a select1185/// of constants.1186static Instruction *foldClampRangeOfTwo(IntrinsicInst *II,1187InstCombiner::BuilderTy &Builder) {1188Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);1189Value *X;1190const APInt *C0, *C1;1191if (!match(I1, m_APInt(C1)) || !I0->hasOneUse())1192return nullptr;11931194CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;1195switch (II->getIntrinsicID()) {1196case Intrinsic::smax:1197if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)1198Pred = ICmpInst::ICMP_SGT;1199break;1200case Intrinsic::smin:1201if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)1202Pred = ICmpInst::ICMP_SLT;1203break;1204case Intrinsic::umax:1205if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1)1206Pred = ICmpInst::ICMP_UGT;1207break;1208case Intrinsic::umin:1209if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1)1210Pred = ICmpInst::ICMP_ULT;1211break;1212default:1213llvm_unreachable("Expected min/max intrinsic");1214}1215if (Pred == CmpInst::BAD_ICMP_PREDICATE)1216return nullptr;12171218// max (min X, 42), 41 --> X > 41 ? 42 : 411219// min (max X, 42), 43 --> X < 43 ? 42 : 431220Value *Cmp = Builder.CreateICmp(Pred, X, I1);1221return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1);1222}12231224/// If this min/max has a constant operand and an operand that is a matching1225/// min/max with a constant operand, constant-fold the 2 constant operands.1226static Value *reassociateMinMaxWithConstants(IntrinsicInst *II,1227IRBuilderBase &Builder,1228const SimplifyQuery &SQ) {1229Intrinsic::ID MinMaxID = II->getIntrinsicID();1230auto *LHS = dyn_cast<MinMaxIntrinsic>(II->getArgOperand(0));1231if (!LHS)1232return nullptr;12331234Constant *C0, *C1;1235if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) ||1236!match(II->getArgOperand(1), m_ImmConstant(C1)))1237return nullptr;12381239// max (max X, C0), C1 --> max X, (max C0, C1)1240// min (min X, C0), C1 --> min X, (min C0, C1)1241// umax (smax X, nneg C0), nneg C1 --> smax X, (umax C0, C1)1242// smin (umin X, nneg C0), nneg C1 --> umin X, (smin C0, C1)1243Intrinsic::ID InnerMinMaxID = LHS->getIntrinsicID();1244if (InnerMinMaxID != MinMaxID &&1245!(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||1246(MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&1247isKnownNonNegative(C0, SQ) && isKnownNonNegative(C1, SQ)))1248return nullptr;12491250ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(MinMaxID);1251Value *CondC = Builder.CreateICmp(Pred, C0, C1);1252Value *NewC = Builder.CreateSelect(CondC, C0, C1);1253return Builder.CreateIntrinsic(InnerMinMaxID, II->getType(),1254{LHS->getArgOperand(0), NewC});1255}12561257/// If this min/max has a matching min/max operand with a constant, try to push1258/// the constant operand into this instruction. This can enable more folds.1259static Instruction *1260reassociateMinMaxWithConstantInOperand(IntrinsicInst *II,1261InstCombiner::BuilderTy &Builder) {1262// Match and capture a min/max operand candidate.1263Value *X, *Y;1264Constant *C;1265Instruction *Inner;1266if (!match(II, m_c_MaxOrMin(m_OneUse(m_CombineAnd(1267m_Instruction(Inner),1268m_MaxOrMin(m_Value(X), m_ImmConstant(C)))),1269m_Value(Y))))1270return nullptr;12711272// The inner op must match. Check for constants to avoid infinite loops.1273Intrinsic::ID MinMaxID = II->getIntrinsicID();1274auto *InnerMM = dyn_cast<IntrinsicInst>(Inner);1275if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||1276match(X, m_ImmConstant()) || match(Y, m_ImmConstant()))1277return nullptr;12781279// max (max X, C), Y --> max (max X, Y), C1280Function *MinMax =1281Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType());1282Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y);1283NewInner->takeName(Inner);1284return CallInst::Create(MinMax, {NewInner, C});1285}12861287/// Reduce a sequence of min/max intrinsics with a common operand.1288static Instruction *factorizeMinMaxTree(IntrinsicInst *II) {1289// Match 3 of the same min/max ops. Example: umin(umin(), umin()).1290auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0));1291auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1));1292Intrinsic::ID MinMaxID = II->getIntrinsicID();1293if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID ||1294RHS->getIntrinsicID() != MinMaxID ||1295(!LHS->hasOneUse() && !RHS->hasOneUse()))1296return nullptr;12971298Value *A = LHS->getArgOperand(0);1299Value *B = LHS->getArgOperand(1);1300Value *C = RHS->getArgOperand(0);1301Value *D = RHS->getArgOperand(1);13021303// Look for a common operand.1304Value *MinMaxOp = nullptr;1305Value *ThirdOp = nullptr;1306if (LHS->hasOneUse()) {1307// If the LHS is only used in this chain and the RHS is used outside of it,1308// reuse the RHS min/max because that will eliminate the LHS.1309if (D == A || C == A) {1310// min(min(a, b), min(c, a)) --> min(min(c, a), b)1311// min(min(a, b), min(a, d)) --> min(min(a, d), b)1312MinMaxOp = RHS;1313ThirdOp = B;1314} else if (D == B || C == B) {1315// min(min(a, b), min(c, b)) --> min(min(c, b), a)1316// min(min(a, b), min(b, d)) --> min(min(b, d), a)1317MinMaxOp = RHS;1318ThirdOp = A;1319}1320} else {1321assert(RHS->hasOneUse() && "Expected one-use operand");1322// Reuse the LHS. This will eliminate the RHS.1323if (D == A || D == B) {1324// min(min(a, b), min(c, a)) --> min(min(a, b), c)1325// min(min(a, b), min(c, b)) --> min(min(a, b), c)1326MinMaxOp = LHS;1327ThirdOp = C;1328} else if (C == A || C == B) {1329// min(min(a, b), min(b, d)) --> min(min(a, b), d)1330// min(min(a, b), min(c, b)) --> min(min(a, b), d)1331MinMaxOp = LHS;1332ThirdOp = D;1333}1334}13351336if (!MinMaxOp || !ThirdOp)1337return nullptr;13381339Module *Mod = II->getModule();1340Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType());1341return CallInst::Create(MinMax, { MinMaxOp, ThirdOp });1342}13431344/// If all arguments of the intrinsic are unary shuffles with the same mask,1345/// try to shuffle after the intrinsic.1346static Instruction *1347foldShuffledIntrinsicOperands(IntrinsicInst *II,1348InstCombiner::BuilderTy &Builder) {1349// TODO: This should be extended to handle other intrinsics like fshl, ctpop,1350// etc. Use llvm::isTriviallyVectorizable() and related to determine1351// which intrinsics are safe to shuffle?1352switch (II->getIntrinsicID()) {1353case Intrinsic::smax:1354case Intrinsic::smin:1355case Intrinsic::umax:1356case Intrinsic::umin:1357case Intrinsic::fma:1358case Intrinsic::fshl:1359case Intrinsic::fshr:1360break;1361default:1362return nullptr;1363}13641365Value *X;1366ArrayRef<int> Mask;1367if (!match(II->getArgOperand(0),1368m_Shuffle(m_Value(X), m_Undef(), m_Mask(Mask))))1369return nullptr;13701371// At least 1 operand must have 1 use because we are creating 2 instructions.1372if (none_of(II->args(), [](Value *V) { return V->hasOneUse(); }))1373return nullptr;13741375// See if all arguments are shuffled with the same mask.1376SmallVector<Value *, 4> NewArgs(II->arg_size());1377NewArgs[0] = X;1378Type *SrcTy = X->getType();1379for (unsigned i = 1, e = II->arg_size(); i != e; ++i) {1380if (!match(II->getArgOperand(i),1381m_Shuffle(m_Value(X), m_Undef(), m_SpecificMask(Mask))) ||1382X->getType() != SrcTy)1383return nullptr;1384NewArgs[i] = X;1385}13861387// intrinsic (shuf X, M), (shuf Y, M), ... --> shuf (intrinsic X, Y, ...), M1388Instruction *FPI = isa<FPMathOperator>(II) ? II : nullptr;1389Value *NewIntrinsic =1390Builder.CreateIntrinsic(II->getIntrinsicID(), SrcTy, NewArgs, FPI);1391return new ShuffleVectorInst(NewIntrinsic, Mask);1392}13931394/// Fold the following cases and accepts bswap and bitreverse intrinsics:1395/// bswap(logic_op(bswap(x), y)) --> logic_op(x, bswap(y))1396/// bswap(logic_op(bswap(x), bswap(y))) --> logic_op(x, y) (ignores multiuse)1397template <Intrinsic::ID IntrID>1398static Instruction *foldBitOrderCrossLogicOp(Value *V,1399InstCombiner::BuilderTy &Builder) {1400static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,1401"This helper only supports BSWAP and BITREVERSE intrinsics");14021403Value *X, *Y;1404// Find bitwise logic op. Check that it is a BinaryOperator explicitly so we1405// don't match ConstantExpr that aren't meaningful for this transform.1406if (match(V, m_OneUse(m_BitwiseLogic(m_Value(X), m_Value(Y)))) &&1407isa<BinaryOperator>(V)) {1408Value *OldReorderX, *OldReorderY;1409BinaryOperator::BinaryOps Op = cast<BinaryOperator>(V)->getOpcode();14101411// If both X and Y are bswap/bitreverse, the transform reduces the number1412// of instructions even if there's multiuse.1413// If only one operand is bswap/bitreverse, we need to ensure the operand1414// have only one use.1415if (match(X, m_Intrinsic<IntrID>(m_Value(OldReorderX))) &&1416match(Y, m_Intrinsic<IntrID>(m_Value(OldReorderY)))) {1417return BinaryOperator::Create(Op, OldReorderX, OldReorderY);1418}14191420if (match(X, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderX))))) {1421Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, Y);1422return BinaryOperator::Create(Op, OldReorderX, NewReorder);1423}14241425if (match(Y, m_OneUse(m_Intrinsic<IntrID>(m_Value(OldReorderY))))) {1426Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID, X);1427return BinaryOperator::Create(Op, NewReorder, OldReorderY);1428}1429}1430return nullptr;1431}14321433static Value *simplifyReductionOperand(Value *Arg, bool CanReorderLanes) {1434if (!CanReorderLanes)1435return nullptr;14361437Value *V;1438if (match(Arg, m_VecReverse(m_Value(V))))1439return V;14401441ArrayRef<int> Mask;1442if (!isa<FixedVectorType>(Arg->getType()) ||1443!match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) ||1444!cast<ShuffleVectorInst>(Arg)->isSingleSource())1445return nullptr;14461447int Sz = Mask.size();1448SmallBitVector UsedIndices(Sz);1449for (int Idx : Mask) {1450if (Idx == PoisonMaskElem || UsedIndices.test(Idx))1451return nullptr;1452UsedIndices.set(Idx);1453}14541455// Can remove shuffle iff just shuffled elements, no repeats, undefs, or1456// other changes.1457return UsedIndices.all() ? V : nullptr;1458}14591460/// Fold an unsigned minimum of trailing or leading zero bits counts:1461/// umin(cttz(CtOp, ZeroUndef), ConstOp) --> cttz(CtOp | (1 << ConstOp))1462/// umin(ctlz(CtOp, ZeroUndef), ConstOp) --> ctlz(CtOp | (SignedMin1463/// >> ConstOp))1464template <Intrinsic::ID IntrID>1465static Value *1466foldMinimumOverTrailingOrLeadingZeroCount(Value *I0, Value *I1,1467const DataLayout &DL,1468InstCombiner::BuilderTy &Builder) {1469static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,1470"This helper only supports cttz and ctlz intrinsics");14711472Value *CtOp;1473Value *ZeroUndef;1474if (!match(I0,1475m_OneUse(m_Intrinsic<IntrID>(m_Value(CtOp), m_Value(ZeroUndef)))))1476return nullptr;14771478unsigned BitWidth = I1->getType()->getScalarSizeInBits();1479auto LessBitWidth = [BitWidth](auto &C) { return C.ult(BitWidth); };1480if (!match(I1, m_CheckedInt(LessBitWidth)))1481// We have a constant >= BitWidth (which can be handled by CVP)1482// or a non-splat vector with elements < and >= BitWidth1483return nullptr;14841485Type *Ty = I1->getType();1486Constant *NewConst = ConstantFoldBinaryOpOperands(1487IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,1488IntrID == Intrinsic::cttz1489? ConstantInt::get(Ty, 1)1490: ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth)),1491cast<Constant>(I1), DL);1492return Builder.CreateBinaryIntrinsic(1493IntrID, Builder.CreateOr(CtOp, NewConst),1494ConstantInt::getTrue(ZeroUndef->getType()));1495}14961497/// CallInst simplification. This mostly only handles folding of intrinsic1498/// instructions. For normal calls, it allows visitCallBase to do the heavy1499/// lifting.1500Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {1501// Don't try to simplify calls without uses. It will not do anything useful,1502// but will result in the following folds being skipped.1503if (!CI.use_empty()) {1504SmallVector<Value *, 4> Args;1505Args.reserve(CI.arg_size());1506for (Value *Op : CI.args())1507Args.push_back(Op);1508if (Value *V = simplifyCall(&CI, CI.getCalledOperand(), Args,1509SQ.getWithInstruction(&CI)))1510return replaceInstUsesWith(CI, V);1511}15121513if (Value *FreedOp = getFreedOperand(&CI, &TLI))1514return visitFree(CI, FreedOp);15151516// If the caller function (i.e. us, the function that contains this CallInst)1517// is nounwind, mark the call as nounwind, even if the callee isn't.1518if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {1519CI.setDoesNotThrow();1520return &CI;1521}15221523IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);1524if (!II) return visitCallBase(CI);15251526// For atomic unordered mem intrinsics if len is not a positive or1527// not a multiple of element size then behavior is undefined.1528if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II))1529if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength()))1530if (NumBytes->isNegative() ||1531(NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) {1532CreateNonTerminatorUnreachable(AMI);1533assert(AMI->getType()->isVoidTy() &&1534"non void atomic unordered mem intrinsic");1535return eraseInstFromFunction(*AMI);1536}15371538// Intrinsics cannot occur in an invoke or a callbr, so handle them here1539// instead of in visitCallBase.1540if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {1541bool Changed = false;15421543// memmove/cpy/set of zero bytes is a noop.1544if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {1545if (NumBytes->isNullValue())1546return eraseInstFromFunction(CI);1547}15481549// No other transformations apply to volatile transfers.1550if (auto *M = dyn_cast<MemIntrinsic>(MI))1551if (M->isVolatile())1552return nullptr;15531554// If we have a memmove and the source operation is a constant global,1555// then the source and dest pointers can't alias, so we can change this1556// into a call to memcpy.1557if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {1558if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))1559if (GVSrc->isConstant()) {1560Module *M = CI.getModule();1561Intrinsic::ID MemCpyID =1562isa<AtomicMemMoveInst>(MMI)1563? Intrinsic::memcpy_element_unordered_atomic1564: Intrinsic::memcpy;1565Type *Tys[3] = { CI.getArgOperand(0)->getType(),1566CI.getArgOperand(1)->getType(),1567CI.getArgOperand(2)->getType() };1568CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));1569Changed = true;1570}1571}15721573if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {1574// memmove(x,x,size) -> noop.1575if (MTI->getSource() == MTI->getDest())1576return eraseInstFromFunction(CI);1577}15781579// If we can determine a pointer alignment that is bigger than currently1580// set, update the alignment.1581if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {1582if (Instruction *I = SimplifyAnyMemTransfer(MTI))1583return I;1584} else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {1585if (Instruction *I = SimplifyAnyMemSet(MSI))1586return I;1587}15881589if (Changed) return II;1590}15911592// For fixed width vector result intrinsics, use the generic demanded vector1593// support.1594if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) {1595auto VWidth = IIFVTy->getNumElements();1596APInt PoisonElts(VWidth, 0);1597APInt AllOnesEltMask(APInt::getAllOnes(VWidth));1598if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, PoisonElts)) {1599if (V != II)1600return replaceInstUsesWith(*II, V);1601return II;1602}1603}16041605if (II->isCommutative()) {1606if (auto Pair = matchSymmetricPair(II->getOperand(0), II->getOperand(1))) {1607replaceOperand(*II, 0, Pair->first);1608replaceOperand(*II, 1, Pair->second);1609return II;1610}16111612if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI))1613return NewCall;1614}16151616// Unused constrained FP intrinsic calls may have declared side effect, which1617// prevents it from being removed. In some cases however the side effect is1618// actually absent. To detect this case, call SimplifyConstrainedFPCall. If it1619// returns a replacement, the call may be removed.1620if (CI.use_empty() && isa<ConstrainedFPIntrinsic>(CI)) {1621if (simplifyConstrainedFPCall(&CI, SQ.getWithInstruction(&CI)))1622return eraseInstFromFunction(CI);1623}16241625Intrinsic::ID IID = II->getIntrinsicID();1626switch (IID) {1627case Intrinsic::objectsize: {1628SmallVector<Instruction *> InsertedInstructions;1629if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false,1630&InsertedInstructions)) {1631for (Instruction *Inserted : InsertedInstructions)1632Worklist.add(Inserted);1633return replaceInstUsesWith(CI, V);1634}1635return nullptr;1636}1637case Intrinsic::abs: {1638Value *IIOperand = II->getArgOperand(0);1639bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();16401641// abs(-x) -> abs(x)1642// TODO: Copy nsw if it was present on the neg?1643Value *X;1644if (match(IIOperand, m_Neg(m_Value(X))))1645return replaceOperand(*II, 0, X);1646if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))1647return replaceOperand(*II, 0, X);1648if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))1649return replaceOperand(*II, 0, X);16501651Value *Y;1652// abs(a * abs(b)) -> abs(a * b)1653if (match(IIOperand,1654m_OneUse(m_c_Mul(m_Value(X),1655m_Intrinsic<Intrinsic::abs>(m_Value(Y)))))) {1656bool NSW =1657cast<Instruction>(IIOperand)->hasNoSignedWrap() && IntMinIsPoison;1658auto *XY = NSW ? Builder.CreateNSWMul(X, Y) : Builder.CreateMul(X, Y);1659return replaceOperand(*II, 0, XY);1660}16611662if (std::optional<bool> Known =1663getKnownSignOrZero(IIOperand, SQ.getWithInstruction(II))) {1664// abs(x) -> x if x >= 0 (include abs(x-y) --> x - y where x >= y)1665// abs(x) -> x if x > 0 (include abs(x-y) --> x - y where x > y)1666if (!*Known)1667return replaceInstUsesWith(*II, IIOperand);16681669// abs(x) -> -x if x < 01670// abs(x) -> -x if x < = 0 (include abs(x-y) --> y - x where x <= y)1671if (IntMinIsPoison)1672return BinaryOperator::CreateNSWNeg(IIOperand);1673return BinaryOperator::CreateNeg(IIOperand);1674}16751676// abs (sext X) --> zext (abs X*)1677// Clear the IsIntMin (nsw) bit on the abs to allow narrowing.1678if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) {1679Value *NarrowAbs =1680Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse());1681return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType());1682}16831684// Match a complicated way to check if a number is odd/even:1685// abs (srem X, 2) --> and X, 11686const APInt *C;1687if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2)1688return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1));16891690break;1691}1692case Intrinsic::umin: {1693Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);1694// umin(x, 1) == zext(x != 0)1695if (match(I1, m_One())) {1696assert(II->getType()->getScalarSizeInBits() != 1 &&1697"Expected simplify of umin with max constant");1698Value *Zero = Constant::getNullValue(I0->getType());1699Value *Cmp = Builder.CreateICmpNE(I0, Zero);1700return CastInst::Create(Instruction::ZExt, Cmp, II->getType());1701}1702// umin(cttz(x), const) --> cttz(x | (1 << const))1703if (Value *FoldedCttz =1704foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::cttz>(1705I0, I1, DL, Builder))1706return replaceInstUsesWith(*II, FoldedCttz);1707// umin(ctlz(x), const) --> ctlz(x | (SignedMin >> const))1708if (Value *FoldedCtlz =1709foldMinimumOverTrailingOrLeadingZeroCount<Intrinsic::ctlz>(1710I0, I1, DL, Builder))1711return replaceInstUsesWith(*II, FoldedCtlz);1712[[fallthrough]];1713}1714case Intrinsic::umax: {1715Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);1716Value *X, *Y;1717if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) &&1718(I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {1719Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);1720return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());1721}1722Constant *C;1723if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) &&1724I0->hasOneUse()) {1725if (Constant *NarrowC = getLosslessUnsignedTrunc(C, X->getType())) {1726Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);1727return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType());1728}1729}1730// If both operands of unsigned min/max are sign-extended, it is still ok1731// to narrow the operation.1732[[fallthrough]];1733}1734case Intrinsic::smax:1735case Intrinsic::smin: {1736Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1);1737Value *X, *Y;1738if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) &&1739(I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) {1740Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y);1741return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());1742}17431744Constant *C;1745if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) &&1746I0->hasOneUse()) {1747if (Constant *NarrowC = getLosslessSignedTrunc(C, X->getType())) {1748Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC);1749return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType());1750}1751}17521753// umin(i1 X, i1 Y) -> and i1 X, Y1754// smax(i1 X, i1 Y) -> and i1 X, Y1755if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&1756II->getType()->isIntOrIntVectorTy(1)) {1757return BinaryOperator::CreateAnd(I0, I1);1758}17591760// umax(i1 X, i1 Y) -> or i1 X, Y1761// smin(i1 X, i1 Y) -> or i1 X, Y1762if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&1763II->getType()->isIntOrIntVectorTy(1)) {1764return BinaryOperator::CreateOr(I0, I1);1765}17661767if (IID == Intrinsic::smax || IID == Intrinsic::smin) {1768// smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y)1769// smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y)1770// TODO: Canonicalize neg after min/max if I1 is constant.1771if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) &&1772(I0->hasOneUse() || I1->hasOneUse())) {1773Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);1774Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y);1775return BinaryOperator::CreateNSWNeg(InvMaxMin);1776}1777}17781779// (umax X, (xor X, Pow2))1780// -> (or X, Pow2)1781// (umin X, (xor X, Pow2))1782// -> (and X, ~Pow2)1783// (smax X, (xor X, Pos_Pow2))1784// -> (or X, Pos_Pow2)1785// (smin X, (xor X, Pos_Pow2))1786// -> (and X, ~Pos_Pow2)1787// (smax X, (xor X, Neg_Pow2))1788// -> (and X, ~Neg_Pow2)1789// (smin X, (xor X, Neg_Pow2))1790// -> (or X, Neg_Pow2)1791if ((match(I0, m_c_Xor(m_Specific(I1), m_Value(X))) ||1792match(I1, m_c_Xor(m_Specific(I0), m_Value(X)))) &&1793isKnownToBeAPowerOfTwo(X, /* OrZero */ true)) {1794bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;1795bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;17961797if (IID == Intrinsic::smax || IID == Intrinsic::smin) {1798auto KnownSign = getKnownSign(X, SQ.getWithInstruction(II));1799if (KnownSign == std::nullopt) {1800UseOr = false;1801UseAndN = false;1802} else if (*KnownSign /* true is Signed. */) {1803UseOr ^= true;1804UseAndN ^= true;1805Type *Ty = I0->getType();1806// Negative power of 2 must be IntMin. It's possible to be able to1807// prove negative / power of 2 without actually having known bits, so1808// just get the value by hand.1809X = Constant::getIntegerValue(1810Ty, APInt::getSignedMinValue(Ty->getScalarSizeInBits()));1811}1812}1813if (UseOr)1814return BinaryOperator::CreateOr(I0, X);1815else if (UseAndN)1816return BinaryOperator::CreateAnd(I0, Builder.CreateNot(X));1817}18181819// If we can eliminate ~A and Y is free to invert:1820// max ~A, Y --> ~(min A, ~Y)1821//1822// Examples:1823// max ~A, ~Y --> ~(min A, Y)1824// max ~A, C --> ~(min A, ~C)1825// max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z))1826auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {1827Value *A;1828if (match(X, m_OneUse(m_Not(m_Value(A)))) &&1829!isFreeToInvert(A, A->hasOneUse())) {1830if (Value *NotY = getFreelyInverted(Y, Y->hasOneUse(), &Builder)) {1831Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID);1832Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY);1833return BinaryOperator::CreateNot(InvMaxMin);1834}1835}1836return nullptr;1837};18381839if (Instruction *I = moveNotAfterMinMax(I0, I1))1840return I;1841if (Instruction *I = moveNotAfterMinMax(I1, I0))1842return I;18431844if (Instruction *I = moveAddAfterMinMax(II, Builder))1845return I;18461847// minmax (X & NegPow2C, Y & NegPow2C) --> minmax(X, Y) & NegPow2C1848const APInt *RHSC;1849if (match(I0, m_OneUse(m_And(m_Value(X), m_NegatedPower2(RHSC)))) &&1850match(I1, m_OneUse(m_And(m_Value(Y), m_SpecificInt(*RHSC)))))1851return BinaryOperator::CreateAnd(Builder.CreateBinaryIntrinsic(IID, X, Y),1852ConstantInt::get(II->getType(), *RHSC));18531854// smax(X, -X) --> abs(X)1855// smin(X, -X) --> -abs(X)1856// umax(X, -X) --> -abs(X)1857// umin(X, -X) --> abs(X)1858if (isKnownNegation(I0, I1)) {1859// We can choose either operand as the input to abs(), but if we can1860// eliminate the only use of a value, that's better for subsequent1861// transforms/analysis.1862if (I0->hasOneUse() && !I1->hasOneUse())1863std::swap(I0, I1);18641865// This is some variant of abs(). See if we can propagate 'nsw' to the abs1866// operation and potentially its negation.1867bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true);1868Value *Abs = Builder.CreateBinaryIntrinsic(1869Intrinsic::abs, I0,1870ConstantInt::getBool(II->getContext(), IntMinIsPoison));18711872// We don't have a "nabs" intrinsic, so negate if needed based on the1873// max/min operation.1874if (IID == Intrinsic::smin || IID == Intrinsic::umax)1875Abs = Builder.CreateNeg(Abs, "nabs", IntMinIsPoison);1876return replaceInstUsesWith(CI, Abs);1877}18781879if (Instruction *Sel = foldClampRangeOfTwo(II, Builder))1880return Sel;18811882if (Instruction *SAdd = matchSAddSubSat(*II))1883return SAdd;18841885if (Value *NewMinMax = reassociateMinMaxWithConstants(II, Builder, SQ))1886return replaceInstUsesWith(*II, NewMinMax);18871888if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder))1889return R;18901891if (Instruction *NewMinMax = factorizeMinMaxTree(II))1892return NewMinMax;18931894// Try to fold minmax with constant RHS based on range information1895if (match(I1, m_APIntAllowPoison(RHSC))) {1896ICmpInst::Predicate Pred =1897ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));1898bool IsSigned = MinMaxIntrinsic::isSigned(IID);1899ConstantRange LHS_CR = computeConstantRangeIncludingKnownBits(1900I0, IsSigned, SQ.getWithInstruction(II));1901if (!LHS_CR.isFullSet()) {1902if (LHS_CR.icmp(Pred, *RHSC))1903return replaceInstUsesWith(*II, I0);1904if (LHS_CR.icmp(ICmpInst::getSwappedPredicate(Pred), *RHSC))1905return replaceInstUsesWith(*II,1906ConstantInt::get(II->getType(), *RHSC));1907}1908}19091910break;1911}1912case Intrinsic::bitreverse: {1913Value *IIOperand = II->getArgOperand(0);1914// bitrev (zext i1 X to ?) --> X ? SignBitC : 01915Value *X;1916if (match(IIOperand, m_ZExt(m_Value(X))) &&1917X->getType()->isIntOrIntVectorTy(1)) {1918Type *Ty = II->getType();1919APInt SignBit = APInt::getSignMask(Ty->getScalarSizeInBits());1920return SelectInst::Create(X, ConstantInt::get(Ty, SignBit),1921ConstantInt::getNullValue(Ty));1922}19231924if (Instruction *crossLogicOpFold =1925foldBitOrderCrossLogicOp<Intrinsic::bitreverse>(IIOperand, Builder))1926return crossLogicOpFold;19271928break;1929}1930case Intrinsic::bswap: {1931Value *IIOperand = II->getArgOperand(0);19321933// Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as1934// inverse-shift-of-bswap:1935// bswap (shl X, Y) --> lshr (bswap X), Y1936// bswap (lshr X, Y) --> shl (bswap X), Y1937Value *X, *Y;1938if (match(IIOperand, m_OneUse(m_LogicalShift(m_Value(X), m_Value(Y))))) {1939unsigned BitWidth = IIOperand->getType()->getScalarSizeInBits();1940if (MaskedValueIsZero(Y, APInt::getLowBitsSet(BitWidth, 3))) {1941Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);1942BinaryOperator::BinaryOps InverseShift =1943cast<BinaryOperator>(IIOperand)->getOpcode() == Instruction::Shl1944? Instruction::LShr1945: Instruction::Shl;1946return BinaryOperator::Create(InverseShift, NewSwap, Y);1947}1948}19491950KnownBits Known = computeKnownBits(IIOperand, 0, II);1951uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8);1952uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8);1953unsigned BW = Known.getBitWidth();19541955// bswap(x) -> shift(x) if x has exactly one "active byte"1956if (BW - LZ - TZ == 8) {1957assert(LZ != TZ && "active byte cannot be in the middle");1958if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x1959return BinaryOperator::CreateNUWShl(1960IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ));1961// -> lshr(x) if the "active byte" is in the high part of x1962return BinaryOperator::CreateExactLShr(1963IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ));1964}19651966// bswap(trunc(bswap(x))) -> trunc(lshr(x, c))1967if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {1968unsigned C = X->getType()->getScalarSizeInBits() - BW;1969Value *CV = ConstantInt::get(X->getType(), C);1970Value *V = Builder.CreateLShr(X, CV);1971return new TruncInst(V, IIOperand->getType());1972}19731974if (Instruction *crossLogicOpFold =1975foldBitOrderCrossLogicOp<Intrinsic::bswap>(IIOperand, Builder)) {1976return crossLogicOpFold;1977}19781979// Try to fold into bitreverse if bswap is the root of the expression tree.1980if (Instruction *BitOp = matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ false,1981/*MatchBitReversals*/ true))1982return BitOp;1983break;1984}1985case Intrinsic::masked_load:1986if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))1987return replaceInstUsesWith(CI, SimplifiedMaskedOp);1988break;1989case Intrinsic::masked_store:1990return simplifyMaskedStore(*II);1991case Intrinsic::masked_gather:1992return simplifyMaskedGather(*II);1993case Intrinsic::masked_scatter:1994return simplifyMaskedScatter(*II);1995case Intrinsic::launder_invariant_group:1996case Intrinsic::strip_invariant_group:1997if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))1998return replaceInstUsesWith(*II, SkippedBarrier);1999break;2000case Intrinsic::powi:2001if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {2002// 0 and 1 are handled in instsimplify2003// powi(x, -1) -> 1/x2004if (Power->isMinusOne())2005return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0),2006II->getArgOperand(0), II);2007// powi(x, 2) -> x*x2008if (Power->equalsInt(2))2009return BinaryOperator::CreateFMulFMF(II->getArgOperand(0),2010II->getArgOperand(0), II);20112012if (!Power->getValue()[0]) {2013Value *X;2014// If power is even:2015// powi(-x, p) -> powi(x, p)2016// powi(fabs(x), p) -> powi(x, p)2017// powi(copysign(x, y), p) -> powi(x, p)2018if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) ||2019match(II->getArgOperand(0), m_FAbs(m_Value(X))) ||2020match(II->getArgOperand(0),2021m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value())))2022return replaceOperand(*II, 0, X);2023}2024}2025break;20262027case Intrinsic::cttz:2028case Intrinsic::ctlz:2029if (auto *I = foldCttzCtlz(*II, *this))2030return I;2031break;20322033case Intrinsic::ctpop:2034if (auto *I = foldCtpop(*II, *this))2035return I;2036break;20372038case Intrinsic::fshl:2039case Intrinsic::fshr: {2040Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);2041Type *Ty = II->getType();2042unsigned BitWidth = Ty->getScalarSizeInBits();2043Constant *ShAmtC;2044if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC))) {2045// Canonicalize a shift amount constant operand to modulo the bit-width.2046Constant *WidthC = ConstantInt::get(Ty, BitWidth);2047Constant *ModuloC =2048ConstantFoldBinaryOpOperands(Instruction::URem, ShAmtC, WidthC, DL);2049if (!ModuloC)2050return nullptr;2051if (ModuloC != ShAmtC)2052return replaceOperand(*II, 2, ModuloC);20532054assert(match(ConstantFoldCompareInstOperands(ICmpInst::ICMP_UGT, WidthC,2055ShAmtC, DL),2056m_One()) &&2057"Shift amount expected to be modulo bitwidth");20582059// Canonicalize funnel shift right by constant to funnel shift left. This2060// is not entirely arbitrary. For historical reasons, the backend may2061// recognize rotate left patterns but miss rotate right patterns.2062if (IID == Intrinsic::fshr) {2063// fshr X, Y, C --> fshl X, Y, (BitWidth - C) if C is not zero.2064if (!isKnownNonZero(ShAmtC, SQ.getWithInstruction(II)))2065return nullptr;20662067Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);2068Module *Mod = II->getModule();2069Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);2070return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });2071}2072assert(IID == Intrinsic::fshl &&2073"All funnel shifts by simple constants should go left");20742075// fshl(X, 0, C) --> shl X, C2076// fshl(X, undef, C) --> shl X, C2077if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))2078return BinaryOperator::CreateShl(Op0, ShAmtC);20792080// fshl(0, X, C) --> lshr X, (BW-C)2081// fshl(undef, X, C) --> lshr X, (BW-C)2082if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))2083return BinaryOperator::CreateLShr(Op1,2084ConstantExpr::getSub(WidthC, ShAmtC));20852086// fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)2087if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {2088Module *Mod = II->getModule();2089Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);2090return CallInst::Create(Bswap, { Op0 });2091}2092if (Instruction *BitOp =2093matchBSwapOrBitReverse(*II, /*MatchBSwaps*/ true,2094/*MatchBitReversals*/ true))2095return BitOp;2096}20972098// Left or right might be masked.2099if (SimplifyDemandedInstructionBits(*II))2100return &CI;21012102// The shift amount (operand 2) of a funnel shift is modulo the bitwidth,2103// so only the low bits of the shift amount are demanded if the bitwidth is2104// a power-of-2.2105if (!isPowerOf2_32(BitWidth))2106break;2107APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));2108KnownBits Op2Known(BitWidth);2109if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))2110return &CI;2111break;2112}2113case Intrinsic::ptrmask: {2114unsigned BitWidth = DL.getPointerTypeSizeInBits(II->getType());2115KnownBits Known(BitWidth);2116if (SimplifyDemandedInstructionBits(*II, Known))2117return II;21182119Value *InnerPtr, *InnerMask;2120bool Changed = false;2121// Combine:2122// (ptrmask (ptrmask p, A), B)2123// -> (ptrmask p, (and A, B))2124if (match(II->getArgOperand(0),2125m_OneUse(m_Intrinsic<Intrinsic::ptrmask>(m_Value(InnerPtr),2126m_Value(InnerMask))))) {2127assert(II->getArgOperand(1)->getType() == InnerMask->getType() &&2128"Mask types must match");2129// TODO: If InnerMask == Op1, we could copy attributes from inner2130// callsite -> outer callsite.2131Value *NewMask = Builder.CreateAnd(II->getArgOperand(1), InnerMask);2132replaceOperand(CI, 0, InnerPtr);2133replaceOperand(CI, 1, NewMask);2134Changed = true;2135}21362137// See if we can deduce non-null.2138if (!CI.hasRetAttr(Attribute::NonNull) &&2139(Known.isNonZero() ||2140isKnownNonZero(II, getSimplifyQuery().getWithInstruction(II)))) {2141CI.addRetAttr(Attribute::NonNull);2142Changed = true;2143}21442145unsigned NewAlignmentLog =2146std::min(Value::MaxAlignmentExponent,2147std::min(BitWidth - 1, Known.countMinTrailingZeros()));2148// Known bits will capture if we had alignment information associated with2149// the pointer argument.2150if (NewAlignmentLog > Log2(CI.getRetAlign().valueOrOne())) {2151CI.addRetAttr(Attribute::getWithAlignment(2152CI.getContext(), Align(uint64_t(1) << NewAlignmentLog)));2153Changed = true;2154}2155if (Changed)2156return &CI;2157break;2158}2159case Intrinsic::uadd_with_overflow:2160case Intrinsic::sadd_with_overflow: {2161if (Instruction *I = foldIntrinsicWithOverflowCommon(II))2162return I;21632164// Given 2 constant operands whose sum does not overflow:2165// uaddo (X +nuw C0), C1 -> uaddo X, C0 + C12166// saddo (X +nsw C0), C1 -> saddo X, C0 + C12167Value *X;2168const APInt *C0, *C1;2169Value *Arg0 = II->getArgOperand(0);2170Value *Arg1 = II->getArgOperand(1);2171bool IsSigned = IID == Intrinsic::sadd_with_overflow;2172bool HasNWAdd = IsSigned2173? match(Arg0, m_NSWAddLike(m_Value(X), m_APInt(C0)))2174: match(Arg0, m_NUWAddLike(m_Value(X), m_APInt(C0)));2175if (HasNWAdd && match(Arg1, m_APInt(C1))) {2176bool Overflow;2177APInt NewC =2178IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);2179if (!Overflow)2180return replaceInstUsesWith(2181*II, Builder.CreateBinaryIntrinsic(2182IID, X, ConstantInt::get(Arg1->getType(), NewC)));2183}2184break;2185}21862187case Intrinsic::umul_with_overflow:2188case Intrinsic::smul_with_overflow:2189case Intrinsic::usub_with_overflow:2190if (Instruction *I = foldIntrinsicWithOverflowCommon(II))2191return I;2192break;21932194case Intrinsic::ssub_with_overflow: {2195if (Instruction *I = foldIntrinsicWithOverflowCommon(II))2196return I;21972198Constant *C;2199Value *Arg0 = II->getArgOperand(0);2200Value *Arg1 = II->getArgOperand(1);2201// Given a constant C that is not the minimum signed value2202// for an integer of a given bit width:2203//2204// ssubo X, C -> saddo X, -C2205if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {2206Value *NegVal = ConstantExpr::getNeg(C);2207// Build a saddo call that is equivalent to the discovered2208// ssubo call.2209return replaceInstUsesWith(2210*II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,2211Arg0, NegVal));2212}22132214break;2215}22162217case Intrinsic::uadd_sat:2218case Intrinsic::sadd_sat:2219case Intrinsic::usub_sat:2220case Intrinsic::ssub_sat: {2221SaturatingInst *SI = cast<SaturatingInst>(II);2222Type *Ty = SI->getType();2223Value *Arg0 = SI->getLHS();2224Value *Arg1 = SI->getRHS();22252226// Make use of known overflow information.2227OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),2228Arg0, Arg1, SI);2229switch (OR) {2230case OverflowResult::MayOverflow:2231break;2232case OverflowResult::NeverOverflows:2233if (SI->isSigned())2234return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);2235else2236return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);2237case OverflowResult::AlwaysOverflowsLow: {2238unsigned BitWidth = Ty->getScalarSizeInBits();2239APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());2240return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));2241}2242case OverflowResult::AlwaysOverflowsHigh: {2243unsigned BitWidth = Ty->getScalarSizeInBits();2244APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());2245return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));2246}2247}22482249// usub_sat((sub nuw C, A), C1) -> usub_sat(usub_sat(C, C1), A)2250// which after that:2251// usub_sat((sub nuw C, A), C1) -> usub_sat(C - C1, A) if C1 u< C2252// usub_sat((sub nuw C, A), C1) -> 0 otherwise2253Constant *C, *C1;2254Value *A;2255if (IID == Intrinsic::usub_sat &&2256match(Arg0, m_NUWSub(m_ImmConstant(C), m_Value(A))) &&2257match(Arg1, m_ImmConstant(C1))) {2258auto *NewC = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, C, C1);2259auto *NewSub =2260Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, NewC, A);2261return replaceInstUsesWith(*SI, NewSub);2262}22632264// ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN2265if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&2266C->isNotMinSignedValue()) {2267Value *NegVal = ConstantExpr::getNeg(C);2268return replaceInstUsesWith(2269*II, Builder.CreateBinaryIntrinsic(2270Intrinsic::sadd_sat, Arg0, NegVal));2271}22722273// sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))2274// sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))2275// if Val and Val2 have the same sign2276if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {2277Value *X;2278const APInt *Val, *Val2;2279APInt NewVal;2280bool IsUnsigned =2281IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;2282if (Other->getIntrinsicID() == IID &&2283match(Arg1, m_APInt(Val)) &&2284match(Other->getArgOperand(0), m_Value(X)) &&2285match(Other->getArgOperand(1), m_APInt(Val2))) {2286if (IsUnsigned)2287NewVal = Val->uadd_sat(*Val2);2288else if (Val->isNonNegative() == Val2->isNonNegative()) {2289bool Overflow;2290NewVal = Val->sadd_ov(*Val2, Overflow);2291if (Overflow) {2292// Both adds together may add more than SignedMaxValue2293// without saturating the final result.2294break;2295}2296} else {2297// Cannot fold saturated addition with different signs.2298break;2299}23002301return replaceInstUsesWith(2302*II, Builder.CreateBinaryIntrinsic(2303IID, X, ConstantInt::get(II->getType(), NewVal)));2304}2305}2306break;2307}23082309case Intrinsic::minnum:2310case Intrinsic::maxnum:2311case Intrinsic::minimum:2312case Intrinsic::maximum: {2313Value *Arg0 = II->getArgOperand(0);2314Value *Arg1 = II->getArgOperand(1);2315Value *X, *Y;2316if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&2317(Arg0->hasOneUse() || Arg1->hasOneUse())) {2318// If both operands are negated, invert the call and negate the result:2319// min(-X, -Y) --> -(max(X, Y))2320// max(-X, -Y) --> -(min(X, Y))2321Intrinsic::ID NewIID;2322switch (IID) {2323case Intrinsic::maxnum:2324NewIID = Intrinsic::minnum;2325break;2326case Intrinsic::minnum:2327NewIID = Intrinsic::maxnum;2328break;2329case Intrinsic::maximum:2330NewIID = Intrinsic::minimum;2331break;2332case Intrinsic::minimum:2333NewIID = Intrinsic::maximum;2334break;2335default:2336llvm_unreachable("unexpected intrinsic ID");2337}2338Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);2339Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);2340FNeg->copyIRFlags(II);2341return FNeg;2342}23432344// m(m(X, C2), C1) -> m(X, C)2345const APFloat *C1, *C2;2346if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {2347if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&2348((match(M->getArgOperand(0), m_Value(X)) &&2349match(M->getArgOperand(1), m_APFloat(C2))) ||2350(match(M->getArgOperand(1), m_Value(X)) &&2351match(M->getArgOperand(0), m_APFloat(C2))))) {2352APFloat Res(0.0);2353switch (IID) {2354case Intrinsic::maxnum:2355Res = maxnum(*C1, *C2);2356break;2357case Intrinsic::minnum:2358Res = minnum(*C1, *C2);2359break;2360case Intrinsic::maximum:2361Res = maximum(*C1, *C2);2362break;2363case Intrinsic::minimum:2364Res = minimum(*C1, *C2);2365break;2366default:2367llvm_unreachable("unexpected intrinsic ID");2368}2369Value *V = Builder.CreateBinaryIntrinsic(2370IID, X, ConstantFP::get(Arg0->getType(), Res), II);2371// TODO: Conservatively intersecting FMF. If Res == C2, the transform2372// was a simplification (so Arg0 and its original flags could2373// propagate?)2374if (auto *CI = dyn_cast<CallInst>(V))2375CI->andIRFlags(M);2376return replaceInstUsesWith(*II, V);2377}2378}23792380// m((fpext X), (fpext Y)) -> fpext (m(X, Y))2381if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) &&2382match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) &&2383X->getType() == Y->getType()) {2384Value *NewCall =2385Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName());2386return new FPExtInst(NewCall, II->getType());2387}23882389// max X, -X --> fabs X2390// min X, -X --> -(fabs X)2391// TODO: Remove one-use limitation? That is obviously better for max,2392// hence why we don't check for one-use for that. However,2393// it would be an extra instruction for min (fnabs), but2394// that is still likely better for analysis and codegen.2395auto IsMinMaxOrXNegX = [IID, &X](Value *Op0, Value *Op1) {2396if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Specific(X)))2397return Op0->hasOneUse() ||2398(IID != Intrinsic::minimum && IID != Intrinsic::minnum);2399return false;2400};24012402if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {2403Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);2404if (IID == Intrinsic::minimum || IID == Intrinsic::minnum)2405R = Builder.CreateFNegFMF(R, II);2406return replaceInstUsesWith(*II, R);2407}24082409break;2410}2411case Intrinsic::matrix_multiply: {2412// Optimize negation in matrix multiplication.24132414// -A * -B -> A * B2415Value *A, *B;2416if (match(II->getArgOperand(0), m_FNeg(m_Value(A))) &&2417match(II->getArgOperand(1), m_FNeg(m_Value(B)))) {2418replaceOperand(*II, 0, A);2419replaceOperand(*II, 1, B);2420return II;2421}24222423Value *Op0 = II->getOperand(0);2424Value *Op1 = II->getOperand(1);2425Value *OpNotNeg, *NegatedOp;2426unsigned NegatedOpArg, OtherOpArg;2427if (match(Op0, m_FNeg(m_Value(OpNotNeg)))) {2428NegatedOp = Op0;2429NegatedOpArg = 0;2430OtherOpArg = 1;2431} else if (match(Op1, m_FNeg(m_Value(OpNotNeg)))) {2432NegatedOp = Op1;2433NegatedOpArg = 1;2434OtherOpArg = 0;2435} else2436// Multiplication doesn't have a negated operand.2437break;24382439// Only optimize if the negated operand has only one use.2440if (!NegatedOp->hasOneUse())2441break;24422443Value *OtherOp = II->getOperand(OtherOpArg);2444VectorType *RetTy = cast<VectorType>(II->getType());2445VectorType *NegatedOpTy = cast<VectorType>(NegatedOp->getType());2446VectorType *OtherOpTy = cast<VectorType>(OtherOp->getType());2447ElementCount NegatedCount = NegatedOpTy->getElementCount();2448ElementCount OtherCount = OtherOpTy->getElementCount();2449ElementCount RetCount = RetTy->getElementCount();2450// (-A) * B -> A * (-B), if it is cheaper to negate B and vice versa.2451if (ElementCount::isKnownGT(NegatedCount, OtherCount) &&2452ElementCount::isKnownLT(OtherCount, RetCount)) {2453Value *InverseOtherOp = Builder.CreateFNeg(OtherOp);2454replaceOperand(*II, NegatedOpArg, OpNotNeg);2455replaceOperand(*II, OtherOpArg, InverseOtherOp);2456return II;2457}2458// (-A) * B -> -(A * B), if it is cheaper to negate the result2459if (ElementCount::isKnownGT(NegatedCount, RetCount)) {2460SmallVector<Value *, 5> NewArgs(II->args());2461NewArgs[NegatedOpArg] = OpNotNeg;2462Instruction *NewMul =2463Builder.CreateIntrinsic(II->getType(), IID, NewArgs, II);2464return replaceInstUsesWith(*II, Builder.CreateFNegFMF(NewMul, II));2465}2466break;2467}2468case Intrinsic::fmuladd: {2469// Try to simplify the underlying FMul.2470if (Value *V = simplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),2471II->getFastMathFlags(),2472SQ.getWithInstruction(II))) {2473auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));2474FAdd->copyFastMathFlags(II);2475return FAdd;2476}24772478[[fallthrough]];2479}2480case Intrinsic::fma: {2481// fma fneg(x), fneg(y), z -> fma x, y, z2482Value *Src0 = II->getArgOperand(0);2483Value *Src1 = II->getArgOperand(1);2484Value *X, *Y;2485if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {2486replaceOperand(*II, 0, X);2487replaceOperand(*II, 1, Y);2488return II;2489}24902491// fma fabs(x), fabs(x), z -> fma x, x, z2492if (match(Src0, m_FAbs(m_Value(X))) &&2493match(Src1, m_FAbs(m_Specific(X)))) {2494replaceOperand(*II, 0, X);2495replaceOperand(*II, 1, X);2496return II;2497}24982499// Try to simplify the underlying FMul. We can only apply simplifications2500// that do not require rounding.2501if (Value *V = simplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),2502II->getFastMathFlags(),2503SQ.getWithInstruction(II))) {2504auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));2505FAdd->copyFastMathFlags(II);2506return FAdd;2507}25082509// fma x, y, 0 -> fmul x, y2510// This is always valid for -0.0, but requires nsz for +0.0 as2511// -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own.2512if (match(II->getArgOperand(2), m_NegZeroFP()) ||2513(match(II->getArgOperand(2), m_PosZeroFP()) &&2514II->getFastMathFlags().noSignedZeros()))2515return BinaryOperator::CreateFMulFMF(Src0, Src1, II);25162517break;2518}2519case Intrinsic::copysign: {2520Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1);2521if (std::optional<bool> KnownSignBit = computeKnownFPSignBit(2522Sign, /*Depth=*/0, getSimplifyQuery().getWithInstruction(II))) {2523if (*KnownSignBit) {2524// If we know that the sign argument is negative, reduce to FNABS:2525// copysign Mag, -Sign --> fneg (fabs Mag)2526Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);2527return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));2528}25292530// If we know that the sign argument is positive, reduce to FABS:2531// copysign Mag, +Sign --> fabs Mag2532Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II);2533return replaceInstUsesWith(*II, Fabs);2534}25352536// Propagate sign argument through nested calls:2537// copysign Mag, (copysign ?, X) --> copysign Mag, X2538Value *X;2539if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X))))2540return replaceOperand(*II, 1, X);25412542// Clear sign-bit of constant magnitude:2543// copysign -MagC, X --> copysign MagC, X2544// TODO: Support constant folding for fabs2545const APFloat *MagC;2546if (match(Mag, m_APFloat(MagC)) && MagC->isNegative()) {2547APFloat PosMagC = *MagC;2548PosMagC.clearSign();2549return replaceOperand(*II, 0, ConstantFP::get(Mag->getType(), PosMagC));2550}25512552// Peek through changes of magnitude's sign-bit. This call rewrites those:2553// copysign (fabs X), Sign --> copysign X, Sign2554// copysign (fneg X), Sign --> copysign X, Sign2555if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X))))2556return replaceOperand(*II, 0, X);25572558break;2559}2560case Intrinsic::fabs: {2561Value *Cond, *TVal, *FVal;2562Value *Arg = II->getArgOperand(0);2563Value *X;2564// fabs (-X) --> fabs (X)2565if (match(Arg, m_FNeg(m_Value(X)))) {2566CallInst *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II);2567return replaceInstUsesWith(CI, Fabs);2568}25692570if (match(Arg, m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) {2571// fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF2572if (isa<Constant>(TVal) || isa<Constant>(FVal)) {2573CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal});2574CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal});2575SelectInst *SI = SelectInst::Create(Cond, AbsT, AbsF);2576FastMathFlags FMF1 = II->getFastMathFlags();2577FastMathFlags FMF2 = cast<SelectInst>(Arg)->getFastMathFlags();2578FMF2.setNoSignedZeros(false);2579SI->setFastMathFlags(FMF1 | FMF2);2580return SI;2581}2582// fabs (select Cond, -FVal, FVal) --> fabs FVal2583if (match(TVal, m_FNeg(m_Specific(FVal))))2584return replaceOperand(*II, 0, FVal);2585// fabs (select Cond, TVal, -TVal) --> fabs TVal2586if (match(FVal, m_FNeg(m_Specific(TVal))))2587return replaceOperand(*II, 0, TVal);2588}25892590Value *Magnitude, *Sign;2591if (match(II->getArgOperand(0),2592m_CopySign(m_Value(Magnitude), m_Value(Sign)))) {2593// fabs (copysign x, y) -> (fabs x)2594CallInst *AbsSign =2595Builder.CreateCall(II->getCalledFunction(), {Magnitude});2596AbsSign->copyFastMathFlags(II);2597return replaceInstUsesWith(*II, AbsSign);2598}25992600[[fallthrough]];2601}2602case Intrinsic::ceil:2603case Intrinsic::floor:2604case Intrinsic::round:2605case Intrinsic::roundeven:2606case Intrinsic::nearbyint:2607case Intrinsic::rint:2608case Intrinsic::trunc: {2609Value *ExtSrc;2610if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {2611// Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)2612Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);2613return new FPExtInst(NarrowII, II->getType());2614}2615break;2616}2617case Intrinsic::cos:2618case Intrinsic::amdgcn_cos: {2619Value *X, *Sign;2620Value *Src = II->getArgOperand(0);2621if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X))) ||2622match(Src, m_CopySign(m_Value(X), m_Value(Sign)))) {2623// cos(-x) --> cos(x)2624// cos(fabs(x)) --> cos(x)2625// cos(copysign(x, y)) --> cos(x)2626return replaceOperand(*II, 0, X);2627}2628break;2629}2630case Intrinsic::sin:2631case Intrinsic::amdgcn_sin: {2632Value *X;2633if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {2634// sin(-x) --> -sin(x)2635Value *NewSin = Builder.CreateUnaryIntrinsic(IID, X, II);2636return UnaryOperator::CreateFNegFMF(NewSin, II);2637}2638break;2639}2640case Intrinsic::ldexp: {2641// ldexp(ldexp(x, a), b) -> ldexp(x, a + b)2642//2643// The danger is if the first ldexp would overflow to infinity or underflow2644// to zero, but the combined exponent avoids it. We ignore this with2645// reassoc.2646//2647// It's also safe to fold if we know both exponents are >= 0 or <= 0 since2648// it would just double down on the overflow/underflow which would occur2649// anyway.2650//2651// TODO: Could do better if we had range tracking for the input value2652// exponent. Also could broaden sign check to cover == 0 case.2653Value *Src = II->getArgOperand(0);2654Value *Exp = II->getArgOperand(1);2655Value *InnerSrc;2656Value *InnerExp;2657if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ldexp>(2658m_Value(InnerSrc), m_Value(InnerExp)))) &&2659Exp->getType() == InnerExp->getType()) {2660FastMathFlags FMF = II->getFastMathFlags();2661FastMathFlags InnerFlags = cast<FPMathOperator>(Src)->getFastMathFlags();26622663if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||2664signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II))) {2665// TODO: Add nsw/nuw probably safe if integer type exceeds exponent2666// width.2667Value *NewExp = Builder.CreateAdd(InnerExp, Exp);2668II->setArgOperand(1, NewExp);2669II->setFastMathFlags(InnerFlags); // Or the inner flags.2670return replaceOperand(*II, 0, InnerSrc);2671}2672}26732674// ldexp(x, zext(i1 y)) -> fmul x, (select y, 2.0, 1.0)2675// ldexp(x, sext(i1 y)) -> fmul x, (select y, 0.5, 1.0)2676Value *ExtSrc;2677if (match(Exp, m_ZExt(m_Value(ExtSrc))) &&2678ExtSrc->getType()->getScalarSizeInBits() == 1) {2679Value *Select =2680Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 2.0),2681ConstantFP::get(II->getType(), 1.0));2682return BinaryOperator::CreateFMulFMF(Src, Select, II);2683}2684if (match(Exp, m_SExt(m_Value(ExtSrc))) &&2685ExtSrc->getType()->getScalarSizeInBits() == 1) {2686Value *Select =2687Builder.CreateSelect(ExtSrc, ConstantFP::get(II->getType(), 0.5),2688ConstantFP::get(II->getType(), 1.0));2689return BinaryOperator::CreateFMulFMF(Src, Select, II);2690}26912692// ldexp(x, c ? exp : 0) -> c ? ldexp(x, exp) : x2693// ldexp(x, c ? 0 : exp) -> c ? x : ldexp(x, exp)2694///2695// TODO: If we cared, should insert a canonicalize for x2696Value *SelectCond, *SelectLHS, *SelectRHS;2697if (match(II->getArgOperand(1),2698m_OneUse(m_Select(m_Value(SelectCond), m_Value(SelectLHS),2699m_Value(SelectRHS))))) {2700Value *NewLdexp = nullptr;2701Value *Select = nullptr;2702if (match(SelectRHS, m_ZeroInt())) {2703NewLdexp = Builder.CreateLdexp(Src, SelectLHS);2704Select = Builder.CreateSelect(SelectCond, NewLdexp, Src);2705} else if (match(SelectLHS, m_ZeroInt())) {2706NewLdexp = Builder.CreateLdexp(Src, SelectRHS);2707Select = Builder.CreateSelect(SelectCond, Src, NewLdexp);2708}27092710if (NewLdexp) {2711Select->takeName(II);2712cast<Instruction>(NewLdexp)->copyFastMathFlags(II);2713return replaceInstUsesWith(*II, Select);2714}2715}27162717break;2718}2719case Intrinsic::ptrauth_auth:2720case Intrinsic::ptrauth_resign: {2721// (sign|resign) + (auth|resign) can be folded by omitting the middle2722// sign+auth component if the key and discriminator match.2723bool NeedSign = II->getIntrinsicID() == Intrinsic::ptrauth_resign;2724Value *Ptr = II->getArgOperand(0);2725Value *Key = II->getArgOperand(1);2726Value *Disc = II->getArgOperand(2);27272728// AuthKey will be the key we need to end up authenticating against in2729// whatever we replace this sequence with.2730Value *AuthKey = nullptr, *AuthDisc = nullptr, *BasePtr;2731if (const auto *CI = dyn_cast<CallBase>(Ptr)) {2732BasePtr = CI->getArgOperand(0);2733if (CI->getIntrinsicID() == Intrinsic::ptrauth_sign) {2734if (CI->getArgOperand(1) != Key || CI->getArgOperand(2) != Disc)2735break;2736} else if (CI->getIntrinsicID() == Intrinsic::ptrauth_resign) {2737if (CI->getArgOperand(3) != Key || CI->getArgOperand(4) != Disc)2738break;2739AuthKey = CI->getArgOperand(1);2740AuthDisc = CI->getArgOperand(2);2741} else2742break;2743} else if (const auto *PtrToInt = dyn_cast<PtrToIntOperator>(Ptr)) {2744// ptrauth constants are equivalent to a call to @llvm.ptrauth.sign for2745// our purposes, so check for that too.2746const auto *CPA = dyn_cast<ConstantPtrAuth>(PtrToInt->getOperand(0));2747if (!CPA || !CPA->isKnownCompatibleWith(Key, Disc, DL))2748break;27492750// resign(ptrauth(p,ks,ds),ks,ds,kr,dr) -> ptrauth(p,kr,dr)2751if (NeedSign && isa<ConstantInt>(II->getArgOperand(4))) {2752auto *SignKey = cast<ConstantInt>(II->getArgOperand(3));2753auto *SignDisc = cast<ConstantInt>(II->getArgOperand(4));2754auto *SignAddrDisc = ConstantPointerNull::get(Builder.getPtrTy());2755auto *NewCPA = ConstantPtrAuth::get(CPA->getPointer(), SignKey,2756SignDisc, SignAddrDisc);2757replaceInstUsesWith(2758*II, ConstantExpr::getPointerCast(NewCPA, II->getType()));2759return eraseInstFromFunction(*II);2760}27612762// auth(ptrauth(p,k,d),k,d) -> p2763BasePtr = Builder.CreatePtrToInt(CPA->getPointer(), II->getType());2764} else2765break;27662767unsigned NewIntrin;2768if (AuthKey && NeedSign) {2769// resign(0,1) + resign(1,2) = resign(0, 2)2770NewIntrin = Intrinsic::ptrauth_resign;2771} else if (AuthKey) {2772// resign(0,1) + auth(1) = auth(0)2773NewIntrin = Intrinsic::ptrauth_auth;2774} else if (NeedSign) {2775// sign(0) + resign(0, 1) = sign(1)2776NewIntrin = Intrinsic::ptrauth_sign;2777} else {2778// sign(0) + auth(0) = nop2779replaceInstUsesWith(*II, BasePtr);2780return eraseInstFromFunction(*II);2781}27822783SmallVector<Value *, 4> CallArgs;2784CallArgs.push_back(BasePtr);2785if (AuthKey) {2786CallArgs.push_back(AuthKey);2787CallArgs.push_back(AuthDisc);2788}27892790if (NeedSign) {2791CallArgs.push_back(II->getArgOperand(3));2792CallArgs.push_back(II->getArgOperand(4));2793}27942795Function *NewFn = Intrinsic::getDeclaration(II->getModule(), NewIntrin);2796return CallInst::Create(NewFn, CallArgs);2797}2798case Intrinsic::arm_neon_vtbl1:2799case Intrinsic::aarch64_neon_tbl1:2800if (Value *V = simplifyNeonTbl1(*II, Builder))2801return replaceInstUsesWith(*II, V);2802break;28032804case Intrinsic::arm_neon_vmulls:2805case Intrinsic::arm_neon_vmullu:2806case Intrinsic::aarch64_neon_smull:2807case Intrinsic::aarch64_neon_umull: {2808Value *Arg0 = II->getArgOperand(0);2809Value *Arg1 = II->getArgOperand(1);28102811// Handle mul by zero first:2812if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {2813return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));2814}28152816// Check for constant LHS & RHS - in this case we just simplify.2817bool Zext = (IID == Intrinsic::arm_neon_vmullu ||2818IID == Intrinsic::aarch64_neon_umull);2819VectorType *NewVT = cast<VectorType>(II->getType());2820if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {2821if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {2822Value *V0 = Builder.CreateIntCast(CV0, NewVT, /*isSigned=*/!Zext);2823Value *V1 = Builder.CreateIntCast(CV1, NewVT, /*isSigned=*/!Zext);2824return replaceInstUsesWith(CI, Builder.CreateMul(V0, V1));2825}28262827// Couldn't simplify - canonicalize constant to the RHS.2828std::swap(Arg0, Arg1);2829}28302831// Handle mul by one:2832if (Constant *CV1 = dyn_cast<Constant>(Arg1))2833if (ConstantInt *Splat =2834dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))2835if (Splat->isOne())2836return CastInst::CreateIntegerCast(Arg0, II->getType(),2837/*isSigned=*/!Zext);28382839break;2840}2841case Intrinsic::arm_neon_aesd:2842case Intrinsic::arm_neon_aese:2843case Intrinsic::aarch64_crypto_aesd:2844case Intrinsic::aarch64_crypto_aese: {2845Value *DataArg = II->getArgOperand(0);2846Value *KeyArg = II->getArgOperand(1);28472848// Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR2849Value *Data, *Key;2850if (match(KeyArg, m_ZeroInt()) &&2851match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {2852replaceOperand(*II, 0, Data);2853replaceOperand(*II, 1, Key);2854return II;2855}2856break;2857}2858case Intrinsic::hexagon_V6_vandvrt:2859case Intrinsic::hexagon_V6_vandvrt_128B: {2860// Simplify Q -> V -> Q conversion.2861if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {2862Intrinsic::ID ID0 = Op0->getIntrinsicID();2863if (ID0 != Intrinsic::hexagon_V6_vandqrt &&2864ID0 != Intrinsic::hexagon_V6_vandqrt_128B)2865break;2866Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1);2867uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue();2868uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue();2869// Check if every byte has common bits in Bytes and Mask.2870uint64_t C = Bytes1 & Mask1;2871if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000))2872return replaceInstUsesWith(*II, Op0->getArgOperand(0));2873}2874break;2875}2876case Intrinsic::stackrestore: {2877enum class ClassifyResult {2878None,2879Alloca,2880StackRestore,2881CallWithSideEffects,2882};2883auto Classify = [](const Instruction *I) {2884if (isa<AllocaInst>(I))2885return ClassifyResult::Alloca;28862887if (auto *CI = dyn_cast<CallInst>(I)) {2888if (auto *II = dyn_cast<IntrinsicInst>(CI)) {2889if (II->getIntrinsicID() == Intrinsic::stackrestore)2890return ClassifyResult::StackRestore;28912892if (II->mayHaveSideEffects())2893return ClassifyResult::CallWithSideEffects;2894} else {2895// Consider all non-intrinsic calls to be side effects2896return ClassifyResult::CallWithSideEffects;2897}2898}28992900return ClassifyResult::None;2901};29022903// If the stacksave and the stackrestore are in the same BB, and there is2904// no intervening call, alloca, or stackrestore of a different stacksave,2905// remove the restore. This can happen when variable allocas are DCE'd.2906if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {2907if (SS->getIntrinsicID() == Intrinsic::stacksave &&2908SS->getParent() == II->getParent()) {2909BasicBlock::iterator BI(SS);2910bool CannotRemove = false;2911for (++BI; &*BI != II; ++BI) {2912switch (Classify(&*BI)) {2913case ClassifyResult::None:2914// So far so good, look at next instructions.2915break;29162917case ClassifyResult::StackRestore:2918// If we found an intervening stackrestore for a different2919// stacksave, we can't remove the stackrestore. Otherwise, continue.2920if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS)2921CannotRemove = true;2922break;29232924case ClassifyResult::Alloca:2925case ClassifyResult::CallWithSideEffects:2926// If we found an alloca, a non-intrinsic call, or an intrinsic2927// call with side effects, we can't remove the stackrestore.2928CannotRemove = true;2929break;2930}2931if (CannotRemove)2932break;2933}29342935if (!CannotRemove)2936return eraseInstFromFunction(CI);2937}2938}29392940// Scan down this block to see if there is another stack restore in the2941// same block without an intervening call/alloca.2942BasicBlock::iterator BI(II);2943Instruction *TI = II->getParent()->getTerminator();2944bool CannotRemove = false;2945for (++BI; &*BI != TI; ++BI) {2946switch (Classify(&*BI)) {2947case ClassifyResult::None:2948// So far so good, look at next instructions.2949break;29502951case ClassifyResult::StackRestore:2952// If there is a stackrestore below this one, remove this one.2953return eraseInstFromFunction(CI);29542955case ClassifyResult::Alloca:2956case ClassifyResult::CallWithSideEffects:2957// If we found an alloca, a non-intrinsic call, or an intrinsic call2958// with side effects (such as llvm.stacksave and llvm.read_register),2959// we can't remove the stack restore.2960CannotRemove = true;2961break;2962}2963if (CannotRemove)2964break;2965}29662967// If the stack restore is in a return, resume, or unwind block and if there2968// are no allocas or calls between the restore and the return, nuke the2969// restore.2970if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))2971return eraseInstFromFunction(CI);2972break;2973}2974case Intrinsic::lifetime_end:2975// Asan needs to poison memory to detect invalid access which is possible2976// even for empty lifetime range.2977if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||2978II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||2979II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))2980break;29812982if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) {2983return I.getIntrinsicID() == Intrinsic::lifetime_start;2984}))2985return nullptr;2986break;2987case Intrinsic::assume: {2988Value *IIOperand = II->getArgOperand(0);2989SmallVector<OperandBundleDef, 4> OpBundles;2990II->getOperandBundlesAsDefs(OpBundles);29912992/// This will remove the boolean Condition from the assume given as2993/// argument and remove the assume if it becomes useless.2994/// always returns nullptr for use as a return values.2995auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * {2996assert(isa<AssumeInst>(Assume));2997if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II)))2998return eraseInstFromFunction(CI);2999replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext()));3000return nullptr;3001};3002// Remove an assume if it is followed by an identical assume.3003// TODO: Do we need this? Unless there are conflicting assumptions, the3004// computeKnownBits(IIOperand) below here eliminates redundant assumes.3005Instruction *Next = II->getNextNonDebugInstruction();3006if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))3007return RemoveConditionFromAssume(Next);30083009// Canonicalize assume(a && b) -> assume(a); assume(b);3010// Note: New assumption intrinsics created here are registered by3011// the InstCombineIRInserter object.3012FunctionType *AssumeIntrinsicTy = II->getFunctionType();3013Value *AssumeIntrinsic = II->getCalledOperand();3014Value *A, *B;3015if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) {3016Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles,3017II->getName());3018Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());3019return eraseInstFromFunction(*II);3020}3021// assume(!(a || b)) -> assume(!a); assume(!b);3022if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) {3023Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,3024Builder.CreateNot(A), OpBundles, II->getName());3025Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,3026Builder.CreateNot(B), II->getName());3027return eraseInstFromFunction(*II);3028}30293030// assume( (load addr) != null ) -> add 'nonnull' metadata to load3031// (if assume is valid at the load)3032CmpInst::Predicate Pred;3033Instruction *LHS;3034if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&3035Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&3036LHS->getType()->isPointerTy() &&3037isValidAssumeForContext(II, LHS, &DT)) {3038MDNode *MD = MDNode::get(II->getContext(), std::nullopt);3039LHS->setMetadata(LLVMContext::MD_nonnull, MD);3040LHS->setMetadata(LLVMContext::MD_noundef, MD);3041return RemoveConditionFromAssume(II);30423043// TODO: apply nonnull return attributes to calls and invokes3044// TODO: apply range metadata for range check patterns?3045}30463047// Separate storage assumptions apply to the underlying allocations, not any3048// particular pointer within them. When evaluating the hints for AA purposes3049// we getUnderlyingObject them; by precomputing the answers here we can3050// avoid having to do so repeatedly there.3051for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {3052OperandBundleUse OBU = II->getOperandBundleAt(Idx);3053if (OBU.getTagName() == "separate_storage") {3054assert(OBU.Inputs.size() == 2);3055auto MaybeSimplifyHint = [&](const Use &U) {3056Value *Hint = U.get();3057// Not having a limit is safe because InstCombine removes unreachable3058// code.3059Value *UnderlyingObject = getUnderlyingObject(Hint, /*MaxLookup*/ 0);3060if (Hint != UnderlyingObject)3061replaceUse(const_cast<Use &>(U), UnderlyingObject);3062};3063MaybeSimplifyHint(OBU.Inputs[0]);3064MaybeSimplifyHint(OBU.Inputs[1]);3065}3066}30673068// Convert nonnull assume like:3069// %A = icmp ne i32* %PTR, null3070// call void @llvm.assume(i1 %A)3071// into3072// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ]3073if (EnableKnowledgeRetention &&3074match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) &&3075Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) {3076if (auto *Replacement = buildAssumeFromKnowledge(3077{RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) {30783079Replacement->insertBefore(Next);3080AC.registerAssumption(Replacement);3081return RemoveConditionFromAssume(II);3082}3083}30843085// Convert alignment assume like:3086// %B = ptrtoint i32* %A to i643087// %C = and i64 %B, Constant3088// %D = icmp eq i64 %C, 03089// call void @llvm.assume(i1 %D)3090// into3091// call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)]3092uint64_t AlignMask;3093if (EnableKnowledgeRetention &&3094match(IIOperand,3095m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)),3096m_Zero())) &&3097Pred == CmpInst::ICMP_EQ) {3098if (isPowerOf2_64(AlignMask + 1)) {3099uint64_t Offset = 0;3100match(A, m_Add(m_Value(A), m_ConstantInt(Offset)));3101if (match(A, m_PtrToInt(m_Value(A)))) {3102/// Note: this doesn't preserve the offset information but merges3103/// offset and alignment.3104/// TODO: we can generate a GEP instead of merging the alignment with3105/// the offset.3106RetainedKnowledge RK{Attribute::Alignment,3107(unsigned)MinAlign(Offset, AlignMask + 1), A};3108if (auto *Replacement =3109buildAssumeFromKnowledge(RK, Next, &AC, &DT)) {31103111Replacement->insertAfter(II);3112AC.registerAssumption(Replacement);3113}3114return RemoveConditionFromAssume(II);3115}3116}3117}31183119/// Canonicalize Knowledge in operand bundles.3120if (EnableKnowledgeRetention && II->hasOperandBundles()) {3121for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) {3122auto &BOI = II->bundle_op_info_begin()[Idx];3123RetainedKnowledge RK =3124llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI);3125if (BOI.End - BOI.Begin > 2)3126continue; // Prevent reducing knowledge in an align with offset since3127// extracting a RetainedKnowledge from them looses offset3128// information3129RetainedKnowledge CanonRK =3130llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK,3131&getAssumptionCache(),3132&getDominatorTree());3133if (CanonRK == RK)3134continue;3135if (!CanonRK) {3136if (BOI.End - BOI.Begin > 0) {3137Worklist.pushValue(II->op_begin()[BOI.Begin]);3138Value::dropDroppableUse(II->op_begin()[BOI.Begin]);3139}3140continue;3141}3142assert(RK.AttrKind == CanonRK.AttrKind);3143if (BOI.End - BOI.Begin > 0)3144II->op_begin()[BOI.Begin].set(CanonRK.WasOn);3145if (BOI.End - BOI.Begin > 1)3146II->op_begin()[BOI.Begin + 1].set(ConstantInt::get(3147Type::getInt64Ty(II->getContext()), CanonRK.ArgValue));3148if (RK.WasOn)3149Worklist.pushValue(RK.WasOn);3150return II;3151}3152}31533154// If there is a dominating assume with the same condition as this one,3155// then this one is redundant, and should be removed.3156KnownBits Known(1);3157computeKnownBits(IIOperand, Known, 0, II);3158if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II)))3159return eraseInstFromFunction(*II);31603161// assume(false) is unreachable.3162if (match(IIOperand, m_CombineOr(m_Zero(), m_Undef()))) {3163CreateNonTerminatorUnreachable(II);3164return eraseInstFromFunction(*II);3165}31663167// Update the cache of affected values for this assumption (we might be3168// here because we just simplified the condition).3169AC.updateAffectedValues(cast<AssumeInst>(II));3170break;3171}3172case Intrinsic::experimental_guard: {3173// Is this guard followed by another guard? We scan forward over a small3174// fixed window of instructions to handle common cases with conditions3175// computed between guards.3176Instruction *NextInst = II->getNextNonDebugInstruction();3177for (unsigned i = 0; i < GuardWideningWindow; i++) {3178// Note: Using context-free form to avoid compile time blow up3179if (!isSafeToSpeculativelyExecute(NextInst))3180break;3181NextInst = NextInst->getNextNonDebugInstruction();3182}3183Value *NextCond = nullptr;3184if (match(NextInst,3185m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {3186Value *CurrCond = II->getArgOperand(0);31873188// Remove a guard that it is immediately preceded by an identical guard.3189// Otherwise canonicalize guard(a); guard(b) -> guard(a & b).3190if (CurrCond != NextCond) {3191Instruction *MoveI = II->getNextNonDebugInstruction();3192while (MoveI != NextInst) {3193auto *Temp = MoveI;3194MoveI = MoveI->getNextNonDebugInstruction();3195Temp->moveBefore(II);3196}3197replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond));3198}3199eraseInstFromFunction(*NextInst);3200return II;3201}3202break;3203}3204case Intrinsic::vector_insert: {3205Value *Vec = II->getArgOperand(0);3206Value *SubVec = II->getArgOperand(1);3207Value *Idx = II->getArgOperand(2);3208auto *DstTy = dyn_cast<FixedVectorType>(II->getType());3209auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());3210auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType());32113212// Only canonicalize if the destination vector, Vec, and SubVec are all3213// fixed vectors.3214if (DstTy && VecTy && SubVecTy) {3215unsigned DstNumElts = DstTy->getNumElements();3216unsigned VecNumElts = VecTy->getNumElements();3217unsigned SubVecNumElts = SubVecTy->getNumElements();3218unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();32193220// An insert that entirely overwrites Vec with SubVec is a nop.3221if (VecNumElts == SubVecNumElts)3222return replaceInstUsesWith(CI, SubVec);32233224// Widen SubVec into a vector of the same width as Vec, since3225// shufflevector requires the two input vectors to be the same width.3226// Elements beyond the bounds of SubVec within the widened vector are3227// undefined.3228SmallVector<int, 8> WidenMask;3229unsigned i;3230for (i = 0; i != SubVecNumElts; ++i)3231WidenMask.push_back(i);3232for (; i != VecNumElts; ++i)3233WidenMask.push_back(PoisonMaskElem);32343235Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask);32363237SmallVector<int, 8> Mask;3238for (unsigned i = 0; i != IdxN; ++i)3239Mask.push_back(i);3240for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)3241Mask.push_back(i);3242for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)3243Mask.push_back(i);32443245Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);3246return replaceInstUsesWith(CI, Shuffle);3247}3248break;3249}3250case Intrinsic::vector_extract: {3251Value *Vec = II->getArgOperand(0);3252Value *Idx = II->getArgOperand(1);32533254Type *ReturnType = II->getType();3255// (extract_vector (insert_vector InsertTuple, InsertValue, InsertIdx),3256// ExtractIdx)3257unsigned ExtractIdx = cast<ConstantInt>(Idx)->getZExtValue();3258Value *InsertTuple, *InsertIdx, *InsertValue;3259if (match(Vec, m_Intrinsic<Intrinsic::vector_insert>(m_Value(InsertTuple),3260m_Value(InsertValue),3261m_Value(InsertIdx))) &&3262InsertValue->getType() == ReturnType) {3263unsigned Index = cast<ConstantInt>(InsertIdx)->getZExtValue();3264// Case where we get the same index right after setting it.3265// extract.vector(insert.vector(InsertTuple, InsertValue, Idx), Idx) -->3266// InsertValue3267if (ExtractIdx == Index)3268return replaceInstUsesWith(CI, InsertValue);3269// If we are getting a different index than what was set in the3270// insert.vector intrinsic. We can just set the input tuple to the one up3271// in the chain. extract.vector(insert.vector(InsertTuple, InsertValue,3272// InsertIndex), ExtractIndex)3273// --> extract.vector(InsertTuple, ExtractIndex)3274else3275return replaceOperand(CI, 0, InsertTuple);3276}32773278auto *DstTy = dyn_cast<VectorType>(ReturnType);3279auto *VecTy = dyn_cast<VectorType>(Vec->getType());32803281if (DstTy && VecTy) {3282auto DstEltCnt = DstTy->getElementCount();3283auto VecEltCnt = VecTy->getElementCount();3284unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();32853286// Extracting the entirety of Vec is a nop.3287if (DstEltCnt == VecTy->getElementCount()) {3288replaceInstUsesWith(CI, Vec);3289return eraseInstFromFunction(CI);3290}32913292// Only canonicalize to shufflevector if the destination vector and3293// Vec are fixed vectors.3294if (VecEltCnt.isScalable() || DstEltCnt.isScalable())3295break;32963297SmallVector<int, 8> Mask;3298for (unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)3299Mask.push_back(IdxN + i);33003301Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask);3302return replaceInstUsesWith(CI, Shuffle);3303}3304break;3305}3306case Intrinsic::vector_reverse: {3307Value *BO0, *BO1, *X, *Y;3308Value *Vec = II->getArgOperand(0);3309if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) {3310auto *OldBinOp = cast<BinaryOperator>(Vec);3311if (match(BO0, m_VecReverse(m_Value(X)))) {3312// rev(binop rev(X), rev(Y)) --> binop X, Y3313if (match(BO1, m_VecReverse(m_Value(Y))))3314return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(3315OldBinOp->getOpcode(), X, Y,3316OldBinOp, OldBinOp->getName(),3317II->getIterator()));3318// rev(binop rev(X), BO1Splat) --> binop X, BO1Splat3319if (isSplatValue(BO1))3320return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags(3321OldBinOp->getOpcode(), X, BO1,3322OldBinOp, OldBinOp->getName(),3323II->getIterator()));3324}3325// rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y3326if (match(BO1, m_VecReverse(m_Value(Y))) && isSplatValue(BO0))3327return replaceInstUsesWith(CI,3328BinaryOperator::CreateWithCopiedFlags(3329OldBinOp->getOpcode(), BO0, Y, OldBinOp,3330OldBinOp->getName(), II->getIterator()));3331}3332// rev(unop rev(X)) --> unop X3333if (match(Vec, m_OneUse(m_UnOp(m_VecReverse(m_Value(X)))))) {3334auto *OldUnOp = cast<UnaryOperator>(Vec);3335auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags(3336OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(),3337II->getIterator());3338return replaceInstUsesWith(CI, NewUnOp);3339}3340break;3341}3342case Intrinsic::vector_reduce_or:3343case Intrinsic::vector_reduce_and: {3344// Canonicalize logical or/and reductions:3345// Or reduction for i1 is represented as:3346// %val = bitcast <ReduxWidth x i1> to iReduxWidth3347// %res = cmp ne iReduxWidth %val, 03348// And reduction for i1 is represented as:3349// %val = bitcast <ReduxWidth x i1> to iReduxWidth3350// %res = cmp eq iReduxWidth %val, 111113351Value *Arg = II->getArgOperand(0);3352Value *Vect;33533354if (Value *NewOp =3355simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3356replaceUse(II->getOperandUse(0), NewOp);3357return II;3358}33593360if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3361if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))3362if (FTy->getElementType() == Builder.getInt1Ty()) {3363Value *Res = Builder.CreateBitCast(3364Vect, Builder.getIntNTy(FTy->getNumElements()));3365if (IID == Intrinsic::vector_reduce_and) {3366Res = Builder.CreateICmpEQ(3367Res, ConstantInt::getAllOnesValue(Res->getType()));3368} else {3369assert(IID == Intrinsic::vector_reduce_or &&3370"Expected or reduction.");3371Res = Builder.CreateIsNotNull(Res);3372}3373if (Arg != Vect)3374Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,3375II->getType());3376return replaceInstUsesWith(CI, Res);3377}3378}3379[[fallthrough]];3380}3381case Intrinsic::vector_reduce_add: {3382if (IID == Intrinsic::vector_reduce_add) {3383// Convert vector_reduce_add(ZExt(<n x i1>)) to3384// ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).3385// Convert vector_reduce_add(SExt(<n x i1>)) to3386// -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).3387// Convert vector_reduce_add(<n x i1>) to3388// Trunc(ctpop(bitcast <n x i1> to in)).3389Value *Arg = II->getArgOperand(0);3390Value *Vect;33913392if (Value *NewOp =3393simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3394replaceUse(II->getOperandUse(0), NewOp);3395return II;3396}33973398if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3399if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType()))3400if (FTy->getElementType() == Builder.getInt1Ty()) {3401Value *V = Builder.CreateBitCast(3402Vect, Builder.getIntNTy(FTy->getNumElements()));3403Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);3404if (Res->getType() != II->getType())3405Res = Builder.CreateZExtOrTrunc(Res, II->getType());3406if (Arg != Vect &&3407cast<Instruction>(Arg)->getOpcode() == Instruction::SExt)3408Res = Builder.CreateNeg(Res);3409return replaceInstUsesWith(CI, Res);3410}3411}3412}3413[[fallthrough]];3414}3415case Intrinsic::vector_reduce_xor: {3416if (IID == Intrinsic::vector_reduce_xor) {3417// Exclusive disjunction reduction over the vector with3418// (potentially-extended) i1 element type is actually a3419// (potentially-extended) arithmetic `add` reduction over the original3420// non-extended value:3421// vector_reduce_xor(?ext(<n x i1>))3422// -->3423// ?ext(vector_reduce_add(<n x i1>))3424Value *Arg = II->getArgOperand(0);3425Value *Vect;34263427if (Value *NewOp =3428simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3429replaceUse(II->getOperandUse(0), NewOp);3430return II;3431}34323433if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3434if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))3435if (VTy->getElementType() == Builder.getInt1Ty()) {3436Value *Res = Builder.CreateAddReduce(Vect);3437if (Arg != Vect)3438Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,3439II->getType());3440return replaceInstUsesWith(CI, Res);3441}3442}3443}3444[[fallthrough]];3445}3446case Intrinsic::vector_reduce_mul: {3447if (IID == Intrinsic::vector_reduce_mul) {3448// Multiplicative reduction over the vector with (potentially-extended)3449// i1 element type is actually a (potentially zero-extended)3450// logical `and` reduction over the original non-extended value:3451// vector_reduce_mul(?ext(<n x i1>))3452// -->3453// zext(vector_reduce_and(<n x i1>))3454Value *Arg = II->getArgOperand(0);3455Value *Vect;34563457if (Value *NewOp =3458simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3459replaceUse(II->getOperandUse(0), NewOp);3460return II;3461}34623463if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3464if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))3465if (VTy->getElementType() == Builder.getInt1Ty()) {3466Value *Res = Builder.CreateAndReduce(Vect);3467if (Res->getType() != II->getType())3468Res = Builder.CreateZExt(Res, II->getType());3469return replaceInstUsesWith(CI, Res);3470}3471}3472}3473[[fallthrough]];3474}3475case Intrinsic::vector_reduce_umin:3476case Intrinsic::vector_reduce_umax: {3477if (IID == Intrinsic::vector_reduce_umin ||3478IID == Intrinsic::vector_reduce_umax) {3479// UMin/UMax reduction over the vector with (potentially-extended)3480// i1 element type is actually a (potentially-extended)3481// logical `and`/`or` reduction over the original non-extended value:3482// vector_reduce_u{min,max}(?ext(<n x i1>))3483// -->3484// ?ext(vector_reduce_{and,or}(<n x i1>))3485Value *Arg = II->getArgOperand(0);3486Value *Vect;34873488if (Value *NewOp =3489simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3490replaceUse(II->getOperandUse(0), NewOp);3491return II;3492}34933494if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3495if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))3496if (VTy->getElementType() == Builder.getInt1Ty()) {3497Value *Res = IID == Intrinsic::vector_reduce_umin3498? Builder.CreateAndReduce(Vect)3499: Builder.CreateOrReduce(Vect);3500if (Arg != Vect)3501Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res,3502II->getType());3503return replaceInstUsesWith(CI, Res);3504}3505}3506}3507[[fallthrough]];3508}3509case Intrinsic::vector_reduce_smin:3510case Intrinsic::vector_reduce_smax: {3511if (IID == Intrinsic::vector_reduce_smin ||3512IID == Intrinsic::vector_reduce_smax) {3513// SMin/SMax reduction over the vector with (potentially-extended)3514// i1 element type is actually a (potentially-extended)3515// logical `and`/`or` reduction over the original non-extended value:3516// vector_reduce_s{min,max}(<n x i1>)3517// -->3518// vector_reduce_{or,and}(<n x i1>)3519// and3520// vector_reduce_s{min,max}(sext(<n x i1>))3521// -->3522// sext(vector_reduce_{or,and}(<n x i1>))3523// and3524// vector_reduce_s{min,max}(zext(<n x i1>))3525// -->3526// zext(vector_reduce_{and,or}(<n x i1>))3527Value *Arg = II->getArgOperand(0);3528Value *Vect;35293530if (Value *NewOp =3531simplifyReductionOperand(Arg, /*CanReorderLanes=*/true)) {3532replaceUse(II->getOperandUse(0), NewOp);3533return II;3534}35353536if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) {3537if (auto *VTy = dyn_cast<VectorType>(Vect->getType()))3538if (VTy->getElementType() == Builder.getInt1Ty()) {3539Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd;3540if (Arg != Vect)3541ExtOpc = cast<CastInst>(Arg)->getOpcode();3542Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==3543(ExtOpc == Instruction::CastOps::ZExt))3544? Builder.CreateAndReduce(Vect)3545: Builder.CreateOrReduce(Vect);3546if (Arg != Vect)3547Res = Builder.CreateCast(ExtOpc, Res, II->getType());3548return replaceInstUsesWith(CI, Res);3549}3550}3551}3552[[fallthrough]];3553}3554case Intrinsic::vector_reduce_fmax:3555case Intrinsic::vector_reduce_fmin:3556case Intrinsic::vector_reduce_fadd:3557case Intrinsic::vector_reduce_fmul: {3558bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&3559IID != Intrinsic::vector_reduce_fmul) ||3560II->hasAllowReassoc();3561const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||3562IID == Intrinsic::vector_reduce_fmul)3563? 13564: 0;3565Value *Arg = II->getArgOperand(ArgIdx);3566if (Value *NewOp = simplifyReductionOperand(Arg, CanReorderLanes)) {3567replaceUse(II->getOperandUse(ArgIdx), NewOp);3568return nullptr;3569}3570break;3571}3572case Intrinsic::is_fpclass: {3573if (Instruction *I = foldIntrinsicIsFPClass(*II))3574return I;3575break;3576}3577case Intrinsic::threadlocal_address: {3578Align MinAlign = getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);3579MaybeAlign Align = II->getRetAlign();3580if (MinAlign > Align.valueOrOne()) {3581II->addRetAttr(Attribute::getWithAlignment(II->getContext(), MinAlign));3582return II;3583}3584break;3585}3586default: {3587// Handle target specific intrinsics3588std::optional<Instruction *> V = targetInstCombineIntrinsic(*II);3589if (V)3590return *V;3591break;3592}3593}35943595// Try to fold intrinsic into select operands. This is legal if:3596// * The intrinsic is speculatable.3597// * The select condition is not a vector, or the intrinsic does not3598// perform cross-lane operations.3599switch (IID) {3600case Intrinsic::ctlz:3601case Intrinsic::cttz:3602case Intrinsic::ctpop:3603case Intrinsic::umin:3604case Intrinsic::umax:3605case Intrinsic::smin:3606case Intrinsic::smax:3607case Intrinsic::usub_sat:3608case Intrinsic::uadd_sat:3609case Intrinsic::ssub_sat:3610case Intrinsic::sadd_sat:3611for (Value *Op : II->args())3612if (auto *Sel = dyn_cast<SelectInst>(Op))3613if (Instruction *R = FoldOpIntoSelect(*II, Sel))3614return R;3615[[fallthrough]];3616default:3617break;3618}36193620if (Instruction *Shuf = foldShuffledIntrinsicOperands(II, Builder))3621return Shuf;36223623// Some intrinsics (like experimental_gc_statepoint) can be used in invoke3624// context, so it is handled in visitCallBase and we should trigger it.3625return visitCallBase(*II);3626}36273628// Fence instruction simplification3629Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) {3630auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction());3631// This check is solely here to handle arbitrary target-dependent syncscopes.3632// TODO: Can remove if does not matter in practice.3633if (NFI && FI.isIdenticalTo(NFI))3634return eraseInstFromFunction(FI);36353636// Returns true if FI1 is identical or stronger fence than FI2.3637auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) {3638auto FI1SyncScope = FI1->getSyncScopeID();3639// Consider same scope, where scope is global or single-thread.3640if (FI1SyncScope != FI2->getSyncScopeID() ||3641(FI1SyncScope != SyncScope::System &&3642FI1SyncScope != SyncScope::SingleThread))3643return false;36443645return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering());3646};3647if (NFI && isIdenticalOrStrongerFence(NFI, &FI))3648return eraseInstFromFunction(FI);36493650if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction()))3651if (isIdenticalOrStrongerFence(PFI, &FI))3652return eraseInstFromFunction(FI);3653return nullptr;3654}36553656// InvokeInst simplification3657Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) {3658return visitCallBase(II);3659}36603661// CallBrInst simplification3662Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {3663return visitCallBase(CBI);3664}36653666Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {3667if (!CI->getCalledFunction()) return nullptr;36683669// Skip optimizing notail and musttail calls so3670// LibCallSimplifier::optimizeCall doesn't have to preserve those invariants.3671// LibCallSimplifier::optimizeCall should try to preseve tail calls though.3672if (CI->isMustTailCall() || CI->isNoTailCall())3673return nullptr;36743675auto InstCombineRAUW = [this](Instruction *From, Value *With) {3676replaceInstUsesWith(*From, With);3677};3678auto InstCombineErase = [this](Instruction *I) {3679eraseInstFromFunction(*I);3680};3681LibCallSimplifier Simplifier(DL, &TLI, &AC, ORE, BFI, PSI, InstCombineRAUW,3682InstCombineErase);3683if (Value *With = Simplifier.optimizeCall(CI, Builder)) {3684++NumSimplified;3685return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);3686}36873688return nullptr;3689}36903691static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {3692// Strip off at most one level of pointer casts, looking for an alloca. This3693// is good enough in practice and simpler than handling any number of casts.3694Value *Underlying = TrampMem->stripPointerCasts();3695if (Underlying != TrampMem &&3696(!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))3697return nullptr;3698if (!isa<AllocaInst>(Underlying))3699return nullptr;37003701IntrinsicInst *InitTrampoline = nullptr;3702for (User *U : TrampMem->users()) {3703IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);3704if (!II)3705return nullptr;3706if (II->getIntrinsicID() == Intrinsic::init_trampoline) {3707if (InitTrampoline)3708// More than one init_trampoline writes to this value. Give up.3709return nullptr;3710InitTrampoline = II;3711continue;3712}3713if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)3714// Allow any number of calls to adjust.trampoline.3715continue;3716return nullptr;3717}37183719// No call to init.trampoline found.3720if (!InitTrampoline)3721return nullptr;37223723// Check that the alloca is being used in the expected way.3724if (InitTrampoline->getOperand(0) != TrampMem)3725return nullptr;37263727return InitTrampoline;3728}37293730static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,3731Value *TrampMem) {3732// Visit all the previous instructions in the basic block, and try to find a3733// init.trampoline which has a direct path to the adjust.trampoline.3734for (BasicBlock::iterator I = AdjustTramp->getIterator(),3735E = AdjustTramp->getParent()->begin();3736I != E;) {3737Instruction *Inst = &*--I;3738if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))3739if (II->getIntrinsicID() == Intrinsic::init_trampoline &&3740II->getOperand(0) == TrampMem)3741return II;3742if (Inst->mayWriteToMemory())3743return nullptr;3744}3745return nullptr;3746}37473748// Given a call to llvm.adjust.trampoline, find and return the corresponding3749// call to llvm.init.trampoline if the call to the trampoline can be optimized3750// to a direct call to a function. Otherwise return NULL.3751static IntrinsicInst *findInitTrampoline(Value *Callee) {3752Callee = Callee->stripPointerCasts();3753IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);3754if (!AdjustTramp ||3755AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)3756return nullptr;37573758Value *TrampMem = AdjustTramp->getOperand(0);37593760if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))3761return IT;3762if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))3763return IT;3764return nullptr;3765}37663767bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call,3768const TargetLibraryInfo *TLI) {3769// Note: We only handle cases which can't be driven from generic attributes3770// here. So, for example, nonnull and noalias (which are common properties3771// of some allocation functions) are expected to be handled via annotation3772// of the respective allocator declaration with generic attributes.3773bool Changed = false;37743775if (!Call.getType()->isPointerTy())3776return Changed;37773778std::optional<APInt> Size = getAllocSize(&Call, TLI);3779if (Size && *Size != 0) {3780// TODO: We really should just emit deref_or_null here and then3781// let the generic inference code combine that with nonnull.3782if (Call.hasRetAttr(Attribute::NonNull)) {3783Changed = !Call.hasRetAttr(Attribute::Dereferenceable);3784Call.addRetAttr(Attribute::getWithDereferenceableBytes(3785Call.getContext(), Size->getLimitedValue()));3786} else {3787Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull);3788Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes(3789Call.getContext(), Size->getLimitedValue()));3790}3791}37923793// Add alignment attribute if alignment is a power of two constant.3794Value *Alignment = getAllocAlignment(&Call, TLI);3795if (!Alignment)3796return Changed;37973798ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment);3799if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) {3800uint64_t AlignmentVal = AlignOpC->getZExtValue();3801if (llvm::isPowerOf2_64(AlignmentVal)) {3802Align ExistingAlign = Call.getRetAlign().valueOrOne();3803Align NewAlign = Align(AlignmentVal);3804if (NewAlign > ExistingAlign) {3805Call.addRetAttr(3806Attribute::getWithAlignment(Call.getContext(), NewAlign));3807Changed = true;3808}3809}3810}3811return Changed;3812}38133814/// Improvements for call, callbr and invoke instructions.3815Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) {3816bool Changed = annotateAnyAllocSite(Call, &TLI);38173818// Mark any parameters that are known to be non-null with the nonnull3819// attribute. This is helpful for inlining calls to functions with null3820// checks on their arguments.3821SmallVector<unsigned, 4> ArgNos;3822unsigned ArgNo = 0;38233824for (Value *V : Call.args()) {3825if (V->getType()->isPointerTy() &&3826!Call.paramHasAttr(ArgNo, Attribute::NonNull) &&3827isKnownNonZero(V, getSimplifyQuery().getWithInstruction(&Call)))3828ArgNos.push_back(ArgNo);3829ArgNo++;3830}38313832assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly.");38333834if (!ArgNos.empty()) {3835AttributeList AS = Call.getAttributes();3836LLVMContext &Ctx = Call.getContext();3837AS = AS.addParamAttribute(Ctx, ArgNos,3838Attribute::get(Ctx, Attribute::NonNull));3839Call.setAttributes(AS);3840Changed = true;3841}38423843// If the callee is a pointer to a function, attempt to move any casts to the3844// arguments of the call/callbr/invoke.3845Value *Callee = Call.getCalledOperand();3846Function *CalleeF = dyn_cast<Function>(Callee);3847if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) &&3848transformConstExprCastCall(Call))3849return nullptr;38503851if (CalleeF) {3852// Remove the convergent attr on calls when the callee is not convergent.3853if (Call.isConvergent() && !CalleeF->isConvergent() &&3854!CalleeF->isIntrinsic()) {3855LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call3856<< "\n");3857Call.setNotConvergent();3858return &Call;3859}38603861// If the call and callee calling conventions don't match, and neither one3862// of the calling conventions is compatible with C calling convention3863// this call must be unreachable, as the call is undefined.3864if ((CalleeF->getCallingConv() != Call.getCallingConv() &&3865!(CalleeF->getCallingConv() == llvm::CallingConv::C &&3866TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) &&3867!(Call.getCallingConv() == llvm::CallingConv::C &&3868TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) &&3869// Only do this for calls to a function with a body. A prototype may3870// not actually end up matching the implementation's calling conv for a3871// variety of reasons (e.g. it may be written in assembly).3872!CalleeF->isDeclaration()) {3873Instruction *OldCall = &Call;3874CreateNonTerminatorUnreachable(OldCall);3875// If OldCall does not return void then replaceInstUsesWith poison.3876// This allows ValueHandlers and custom metadata to adjust itself.3877if (!OldCall->getType()->isVoidTy())3878replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType()));3879if (isa<CallInst>(OldCall))3880return eraseInstFromFunction(*OldCall);38813882// We cannot remove an invoke or a callbr, because it would change thexi3883// CFG, just change the callee to a null pointer.3884cast<CallBase>(OldCall)->setCalledFunction(3885CalleeF->getFunctionType(),3886Constant::getNullValue(CalleeF->getType()));3887return nullptr;3888}3889}38903891// Calling a null function pointer is undefined if a null address isn't3892// dereferenceable.3893if ((isa<ConstantPointerNull>(Callee) &&3894!NullPointerIsDefined(Call.getFunction())) ||3895isa<UndefValue>(Callee)) {3896// If Call does not return void then replaceInstUsesWith poison.3897// This allows ValueHandlers and custom metadata to adjust itself.3898if (!Call.getType()->isVoidTy())3899replaceInstUsesWith(Call, PoisonValue::get(Call.getType()));39003901if (Call.isTerminator()) {3902// Can't remove an invoke or callbr because we cannot change the CFG.3903return nullptr;3904}39053906// This instruction is not reachable, just remove it.3907CreateNonTerminatorUnreachable(&Call);3908return eraseInstFromFunction(Call);3909}39103911if (IntrinsicInst *II = findInitTrampoline(Callee))3912return transformCallThroughTrampoline(Call, *II);39133914if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {3915InlineAsm *IA = cast<InlineAsm>(Callee);3916if (!IA->canThrow()) {3917// Normal inline asm calls cannot throw - mark them3918// 'nounwind'.3919Call.setDoesNotThrow();3920Changed = true;3921}3922}39233924// Try to optimize the call if possible, we require DataLayout for most of3925// this. None of these calls are seen as possibly dead so go ahead and3926// delete the instruction now.3927if (CallInst *CI = dyn_cast<CallInst>(&Call)) {3928Instruction *I = tryOptimizeCall(CI);3929// If we changed something return the result, etc. Otherwise let3930// the fallthrough check.3931if (I) return eraseInstFromFunction(*I);3932}39333934if (!Call.use_empty() && !Call.isMustTailCall())3935if (Value *ReturnedArg = Call.getReturnedArgOperand()) {3936Type *CallTy = Call.getType();3937Type *RetArgTy = ReturnedArg->getType();3938if (RetArgTy->canLosslesslyBitCastTo(CallTy))3939return replaceInstUsesWith(3940Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));3941}39423943// Drop unnecessary kcfi operand bundles from calls that were converted3944// into direct calls.3945auto Bundle = Call.getOperandBundle(LLVMContext::OB_kcfi);3946if (Bundle && !Call.isIndirectCall()) {3947DEBUG_WITH_TYPE(DEBUG_TYPE "-kcfi", {3948if (CalleeF) {3949ConstantInt *FunctionType = nullptr;3950ConstantInt *ExpectedType = cast<ConstantInt>(Bundle->Inputs[0]);39513952if (MDNode *MD = CalleeF->getMetadata(LLVMContext::MD_kcfi_type))3953FunctionType = mdconst::extract<ConstantInt>(MD->getOperand(0));39543955if (FunctionType &&3956FunctionType->getZExtValue() != ExpectedType->getZExtValue())3957dbgs() << Call.getModule()->getName()3958<< ": warning: kcfi: " << Call.getCaller()->getName()3959<< ": call to " << CalleeF->getName()3960<< " using a mismatching function pointer type\n";3961}3962});39633964return CallBase::removeOperandBundle(&Call, LLVMContext::OB_kcfi);3965}39663967if (isRemovableAlloc(&Call, &TLI))3968return visitAllocSite(Call);39693970// Handle intrinsics which can be used in both call and invoke context.3971switch (Call.getIntrinsicID()) {3972case Intrinsic::experimental_gc_statepoint: {3973GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call);3974SmallPtrSet<Value *, 32> LiveGcValues;3975for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {3976GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);39773978// Remove the relocation if unused.3979if (GCR.use_empty()) {3980eraseInstFromFunction(GCR);3981continue;3982}39833984Value *DerivedPtr = GCR.getDerivedPtr();3985Value *BasePtr = GCR.getBasePtr();39863987// Undef is undef, even after relocation.3988if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) {3989replaceInstUsesWith(GCR, UndefValue::get(GCR.getType()));3990eraseInstFromFunction(GCR);3991continue;3992}39933994if (auto *PT = dyn_cast<PointerType>(GCR.getType())) {3995// The relocation of null will be null for most any collector.3996// TODO: provide a hook for this in GCStrategy. There might be some3997// weird collector this property does not hold for.3998if (isa<ConstantPointerNull>(DerivedPtr)) {3999// Use null-pointer of gc_relocate's type to replace it.4000replaceInstUsesWith(GCR, ConstantPointerNull::get(PT));4001eraseInstFromFunction(GCR);4002continue;4003}40044005// isKnownNonNull -> nonnull attribute4006if (!GCR.hasRetAttr(Attribute::NonNull) &&4007isKnownNonZero(DerivedPtr,4008getSimplifyQuery().getWithInstruction(&Call))) {4009GCR.addRetAttr(Attribute::NonNull);4010// We discovered new fact, re-check users.4011Worklist.pushUsersToWorkList(GCR);4012}4013}40144015// If we have two copies of the same pointer in the statepoint argument4016// list, canonicalize to one. This may let us common gc.relocates.4017if (GCR.getBasePtr() == GCR.getDerivedPtr() &&4018GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {4019auto *OpIntTy = GCR.getOperand(2)->getType();4020GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));4021}40224023// TODO: bitcast(relocate(p)) -> relocate(bitcast(p))4024// Canonicalize on the type from the uses to the defs40254026// TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)4027LiveGcValues.insert(BasePtr);4028LiveGcValues.insert(DerivedPtr);4029}4030std::optional<OperandBundleUse> Bundle =4031GCSP.getOperandBundle(LLVMContext::OB_gc_live);4032unsigned NumOfGCLives = LiveGcValues.size();4033if (!Bundle || NumOfGCLives == Bundle->Inputs.size())4034break;4035// We can reduce the size of gc live bundle.4036DenseMap<Value *, unsigned> Val2Idx;4037std::vector<Value *> NewLiveGc;4038for (Value *V : Bundle->Inputs) {4039if (Val2Idx.count(V))4040continue;4041if (LiveGcValues.count(V)) {4042Val2Idx[V] = NewLiveGc.size();4043NewLiveGc.push_back(V);4044} else4045Val2Idx[V] = NumOfGCLives;4046}4047// Update all gc.relocates4048for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) {4049GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc);4050Value *BasePtr = GCR.getBasePtr();4051assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&4052"Missed live gc for base pointer");4053auto *OpIntTy1 = GCR.getOperand(1)->getType();4054GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));4055Value *DerivedPtr = GCR.getDerivedPtr();4056assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&4057"Missed live gc for derived pointer");4058auto *OpIntTy2 = GCR.getOperand(2)->getType();4059GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));4060}4061// Create new statepoint instruction.4062OperandBundleDef NewBundle("gc-live", NewLiveGc);4063return CallBase::Create(&Call, NewBundle);4064}4065default: { break; }4066}40674068return Changed ? &Call : nullptr;4069}40704071/// If the callee is a constexpr cast of a function, attempt to move the cast to4072/// the arguments of the call/invoke.4073/// CallBrInst is not supported.4074bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) {4075auto *Callee =4076dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());4077if (!Callee)4078return false;40794080assert(!isa<CallBrInst>(Call) &&4081"CallBr's don't have a single point after a def to insert at");40824083// If this is a call to a thunk function, don't remove the cast. Thunks are4084// used to transparently forward all incoming parameters and outgoing return4085// values, so it's important to leave the cast in place.4086if (Callee->hasFnAttribute("thunk"))4087return false;40884089// If this is a call to a naked function, the assembly might be4090// using an argument, or otherwise rely on the frame layout,4091// the function prototype will mismatch.4092if (Callee->hasFnAttribute(Attribute::Naked))4093return false;40944095// If this is a musttail call, the callee's prototype must match the caller's4096// prototype with the exception of pointee types. The code below doesn't4097// implement that, so we can't do this transform.4098// TODO: Do the transform if it only requires adding pointer casts.4099if (Call.isMustTailCall())4100return false;41014102Instruction *Caller = &Call;4103const AttributeList &CallerPAL = Call.getAttributes();41044105// Okay, this is a cast from a function to a different type. Unless doing so4106// would cause a type conversion of one of our arguments, change this call to4107// be a direct call with arguments casted to the appropriate types.4108FunctionType *FT = Callee->getFunctionType();4109Type *OldRetTy = Caller->getType();4110Type *NewRetTy = FT->getReturnType();41114112// Check to see if we are changing the return type...4113if (OldRetTy != NewRetTy) {41144115if (NewRetTy->isStructTy())4116return false; // TODO: Handle multiple return values.41174118if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {4119if (Callee->isDeclaration())4120return false; // Cannot transform this return value.41214122if (!Caller->use_empty() &&4123// void -> non-void is handled specially4124!NewRetTy->isVoidTy())4125return false; // Cannot transform this return value.4126}41274128if (!CallerPAL.isEmpty() && !Caller->use_empty()) {4129AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());4130if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))4131return false; // Attribute not compatible with transformed value.4132}41334134// If the callbase is an invoke instruction, and the return value is4135// used by a PHI node in a successor, we cannot change the return type of4136// the call because there is no place to put the cast instruction (without4137// breaking the critical edge). Bail out in this case.4138if (!Caller->use_empty()) {4139BasicBlock *PhisNotSupportedBlock = nullptr;4140if (auto *II = dyn_cast<InvokeInst>(Caller))4141PhisNotSupportedBlock = II->getNormalDest();4142if (PhisNotSupportedBlock)4143for (User *U : Caller->users())4144if (PHINode *PN = dyn_cast<PHINode>(U))4145if (PN->getParent() == PhisNotSupportedBlock)4146return false;4147}4148}41494150unsigned NumActualArgs = Call.arg_size();4151unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);41524153// Prevent us turning:4154// declare void @takes_i32_inalloca(i32* inalloca)4155// call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)4156//4157// into:4158// call void @takes_i32_inalloca(i32* null)4159//4160// Similarly, avoid folding away bitcasts of byval calls.4161if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||4162Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))4163return false;41644165auto AI = Call.arg_begin();4166for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {4167Type *ParamTy = FT->getParamType(i);4168Type *ActTy = (*AI)->getType();41694170if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))4171return false; // Cannot transform this parameter value.41724173// Check if there are any incompatible attributes we cannot drop safely.4174if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))4175.overlaps(AttributeFuncs::typeIncompatible(4176ParamTy, AttributeFuncs::ASK_UNSAFE_TO_DROP)))4177return false; // Attribute not compatible with transformed value.41784179if (Call.isInAllocaArgument(i) ||4180CallerPAL.hasParamAttr(i, Attribute::Preallocated))4181return false; // Cannot transform to and from inalloca/preallocated.41824183if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))4184return false;41854186if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=4187Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))4188return false; // Cannot transform to or from byval.4189}41904191if (Callee->isDeclaration()) {4192// Do not delete arguments unless we have a function body.4193if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())4194return false;41954196// If the callee is just a declaration, don't change the varargsness of the4197// call. We don't want to introduce a varargs call where one doesn't4198// already exist.4199if (FT->isVarArg() != Call.getFunctionType()->isVarArg())4200return false;42014202// If both the callee and the cast type are varargs, we still have to make4203// sure the number of fixed parameters are the same or we have the same4204// ABI issues as if we introduce a varargs call.4205if (FT->isVarArg() && Call.getFunctionType()->isVarArg() &&4206FT->getNumParams() != Call.getFunctionType()->getNumParams())4207return false;4208}42094210if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&4211!CallerPAL.isEmpty()) {4212// In this case we have more arguments than the new function type, but we4213// won't be dropping them. Check that these extra arguments have attributes4214// that are compatible with being a vararg call argument.4215unsigned SRetIdx;4216if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&4217SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())4218return false;4219}42204221// Okay, we decided that this is a safe thing to do: go ahead and start4222// inserting cast instructions as necessary.4223SmallVector<Value *, 8> Args;4224SmallVector<AttributeSet, 8> ArgAttrs;4225Args.reserve(NumActualArgs);4226ArgAttrs.reserve(NumActualArgs);42274228// Get any return attributes.4229AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());42304231// If the return value is not being used, the type may not be compatible4232// with the existing attributes. Wipe out any problematic attributes.4233RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));42344235LLVMContext &Ctx = Call.getContext();4236AI = Call.arg_begin();4237for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {4238Type *ParamTy = FT->getParamType(i);42394240Value *NewArg = *AI;4241if ((*AI)->getType() != ParamTy)4242NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);4243Args.push_back(NewArg);42444245// Add any parameter attributes except the ones incompatible with the new4246// type. Note that we made sure all incompatible ones are safe to drop.4247AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(4248ParamTy, AttributeFuncs::ASK_SAFE_TO_DROP);4249ArgAttrs.push_back(4250CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));4251}42524253// If the function takes more arguments than the call was taking, add them4254// now.4255for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {4256Args.push_back(Constant::getNullValue(FT->getParamType(i)));4257ArgAttrs.push_back(AttributeSet());4258}42594260// If we are removing arguments to the function, emit an obnoxious warning.4261if (FT->getNumParams() < NumActualArgs) {4262// TODO: if (!FT->isVarArg()) this call may be unreachable. PR147224263if (FT->isVarArg()) {4264// Add all of the arguments in their promoted form to the arg list.4265for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {4266Type *PTy = getPromotedType((*AI)->getType());4267Value *NewArg = *AI;4268if (PTy != (*AI)->getType()) {4269// Must promote to pass through va_arg area!4270Instruction::CastOps opcode =4271CastInst::getCastOpcode(*AI, false, PTy, false);4272NewArg = Builder.CreateCast(opcode, *AI, PTy);4273}4274Args.push_back(NewArg);42754276// Add any parameter attributes.4277ArgAttrs.push_back(CallerPAL.getParamAttrs(i));4278}4279}4280}42814282AttributeSet FnAttrs = CallerPAL.getFnAttrs();42834284if (NewRetTy->isVoidTy())4285Caller->setName(""); // Void type should not have a name.42864287assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&4288"missing argument attributes");4289AttributeList NewCallerPAL = AttributeList::get(4290Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);42914292SmallVector<OperandBundleDef, 1> OpBundles;4293Call.getOperandBundlesAsDefs(OpBundles);42944295CallBase *NewCall;4296if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {4297NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),4298II->getUnwindDest(), Args, OpBundles);4299} else {4300NewCall = Builder.CreateCall(Callee, Args, OpBundles);4301cast<CallInst>(NewCall)->setTailCallKind(4302cast<CallInst>(Caller)->getTailCallKind());4303}4304NewCall->takeName(Caller);4305NewCall->setCallingConv(Call.getCallingConv());4306NewCall->setAttributes(NewCallerPAL);43074308// Preserve prof metadata if any.4309NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof});43104311// Insert a cast of the return type as necessary.4312Instruction *NC = NewCall;4313Value *NV = NC;4314if (OldRetTy != NV->getType() && !Caller->use_empty()) {4315if (!NV->getType()->isVoidTy()) {4316NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);4317NC->setDebugLoc(Caller->getDebugLoc());43184319auto OptInsertPt = NewCall->getInsertionPointAfterDef();4320assert(OptInsertPt && "No place to insert cast");4321InsertNewInstBefore(NC, *OptInsertPt);4322Worklist.pushUsersToWorkList(*Caller);4323} else {4324NV = PoisonValue::get(Caller->getType());4325}4326}43274328if (!Caller->use_empty())4329replaceInstUsesWith(*Caller, NV);4330else if (Caller->hasValueHandle()) {4331if (OldRetTy == NV->getType())4332ValueHandleBase::ValueIsRAUWd(Caller, NV);4333else4334// We cannot call ValueIsRAUWd with a different type, and the4335// actual tracked value will disappear.4336ValueHandleBase::ValueIsDeleted(Caller);4337}43384339eraseInstFromFunction(*Caller);4340return true;4341}43424343/// Turn a call to a function created by init_trampoline / adjust_trampoline4344/// intrinsic pair into a direct call to the underlying function.4345Instruction *4346InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call,4347IntrinsicInst &Tramp) {4348FunctionType *FTy = Call.getFunctionType();4349AttributeList Attrs = Call.getAttributes();43504351// If the call already has the 'nest' attribute somewhere then give up -4352// otherwise 'nest' would occur twice after splicing in the chain.4353if (Attrs.hasAttrSomewhere(Attribute::Nest))4354return nullptr;43554356Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());4357FunctionType *NestFTy = NestF->getFunctionType();43584359AttributeList NestAttrs = NestF->getAttributes();4360if (!NestAttrs.isEmpty()) {4361unsigned NestArgNo = 0;4362Type *NestTy = nullptr;4363AttributeSet NestAttr;43644365// Look for a parameter marked with the 'nest' attribute.4366for (FunctionType::param_iterator I = NestFTy->param_begin(),4367E = NestFTy->param_end();4368I != E; ++NestArgNo, ++I) {4369AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);4370if (AS.hasAttribute(Attribute::Nest)) {4371// Record the parameter type and any other attributes.4372NestTy = *I;4373NestAttr = AS;4374break;4375}4376}43774378if (NestTy) {4379std::vector<Value*> NewArgs;4380std::vector<AttributeSet> NewArgAttrs;4381NewArgs.reserve(Call.arg_size() + 1);4382NewArgAttrs.reserve(Call.arg_size());43834384// Insert the nest argument into the call argument list, which may4385// mean appending it. Likewise for attributes.43864387{4388unsigned ArgNo = 0;4389auto I = Call.arg_begin(), E = Call.arg_end();4390do {4391if (ArgNo == NestArgNo) {4392// Add the chain argument and attributes.4393Value *NestVal = Tramp.getArgOperand(2);4394if (NestVal->getType() != NestTy)4395NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");4396NewArgs.push_back(NestVal);4397NewArgAttrs.push_back(NestAttr);4398}43994400if (I == E)4401break;44024403// Add the original argument and attributes.4404NewArgs.push_back(*I);4405NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));44064407++ArgNo;4408++I;4409} while (true);4410}44114412// The trampoline may have been bitcast to a bogus type (FTy).4413// Handle this by synthesizing a new function type, equal to FTy4414// with the chain parameter inserted.44154416std::vector<Type*> NewTypes;4417NewTypes.reserve(FTy->getNumParams()+1);44184419// Insert the chain's type into the list of parameter types, which may4420// mean appending it.4421{4422unsigned ArgNo = 0;4423FunctionType::param_iterator I = FTy->param_begin(),4424E = FTy->param_end();44254426do {4427if (ArgNo == NestArgNo)4428// Add the chain's type.4429NewTypes.push_back(NestTy);44304431if (I == E)4432break;44334434// Add the original type.4435NewTypes.push_back(*I);44364437++ArgNo;4438++I;4439} while (true);4440}44414442// Replace the trampoline call with a direct call. Let the generic4443// code sort out any function type mismatches.4444FunctionType *NewFTy =4445FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());4446AttributeList NewPAL =4447AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(),4448Attrs.getRetAttrs(), NewArgAttrs);44494450SmallVector<OperandBundleDef, 1> OpBundles;4451Call.getOperandBundlesAsDefs(OpBundles);44524453Instruction *NewCaller;4454if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {4455NewCaller = InvokeInst::Create(NewFTy, NestF, II->getNormalDest(),4456II->getUnwindDest(), NewArgs, OpBundles);4457cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());4458cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);4459} else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {4460NewCaller =4461CallBrInst::Create(NewFTy, NestF, CBI->getDefaultDest(),4462CBI->getIndirectDests(), NewArgs, OpBundles);4463cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());4464cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);4465} else {4466NewCaller = CallInst::Create(NewFTy, NestF, NewArgs, OpBundles);4467cast<CallInst>(NewCaller)->setTailCallKind(4468cast<CallInst>(Call).getTailCallKind());4469cast<CallInst>(NewCaller)->setCallingConv(4470cast<CallInst>(Call).getCallingConv());4471cast<CallInst>(NewCaller)->setAttributes(NewPAL);4472}4473NewCaller->setDebugLoc(Call.getDebugLoc());44744475return NewCaller;4476}4477}44784479// Replace the trampoline call with a direct call. Since there is no 'nest'4480// parameter, there is no need to adjust the argument list. Let the generic4481// code sort out any function type mismatches.4482Call.setCalledFunction(FTy, NestF);4483return &Call;4484}448544864487