29#define DEBUG_TYPE "instcombine"
35STATISTIC(NumDeadStore,
"Number of dead stores eliminated");
36STATISTIC(NumGlobalCopies,
"Number of allocas copied from constant global");
39 "instcombine-max-copied-from-constant-users",
cl::init(300),
40 cl::desc(
"Maximum users to visit in copy from constant transform"),
62 while (!Worklist.
empty()) {
64 if (!Visited.
insert(Elem).second)
69 const auto [
Value, IsOffset] = Elem;
75 if (!LI->isSimple())
return false;
101 if (
Call->isCallee(&U))
104 unsigned DataOpNo =
Call->getDataOperandNo(&U);
105 bool IsArgOperand =
Call->isArgOperand(&U);
108 if (IsArgOperand &&
Call->isInAllocaArgument(DataOpNo))
114 bool NoCapture =
Call->doesNotCapture(DataOpNo);
116 (
Call->onlyReadsMemory() ||
Call->onlyReadsMemory(DataOpNo)))
121 if (
I->isLifetimeStartOrEnd()) {
122 assert(
I->use_empty() &&
"Lifetime markers have no result to use!");
134 if (
MI->isVolatile())
139 if (U.getOperandNo() == 1)
143 if (TheCopy)
return false;
147 if (IsOffset)
return false;
150 if (U.getOperandNo() != 0)
return false;
181 if (!AllocaSize || AllocaSize->isScalable())
201 if (
C->getValue().getActiveBits() <= 64) {
239class PointerReplacer {
241 PointerReplacer(InstCombinerImpl &IC, Instruction &Root,
unsigned SrcAS)
242 : IC(IC), Root(Root), FromAS(SrcAS) {}
245 void replacePointer(
Value *V);
249 Value *getReplacement(
Value *V)
const {
return WorkMap.lookup(V); }
251 return I == &Root || UsersToReplace.contains(
I);
254 bool isEqualOrValidAddrSpaceCast(
const Instruction *
I,
255 unsigned FromAS)
const {
259 unsigned ToAS = ASC->getDestAddressSpace();
260 return (FromAS == ToAS) || IC.isValidAddrSpaceCast(FromAS, ToAS);
263 SmallSetVector<Instruction *, 32> UsersToReplace;
264 DenseMap<Value *, Value *> WorkMap;
265 InstCombinerImpl &IC;
271bool PointerReplacer::collectUsers() {
272 SmallVector<Instruction *> Worklist;
273 SmallSetVector<Instruction *, 32> ValuesToRevisit;
275 auto PushUsersToWorklist = [&](
Instruction *Inst) {
276 for (
auto *U : Inst->users())
282 auto TryPushInstOperand = [&](
Instruction *InstOp) {
283 if (!UsersToReplace.contains(InstOp)) {
284 if (!ValuesToRevisit.
insert(InstOp))
291 PushUsersToWorklist(&Root);
292 while (!Worklist.
empty()) {
295 if (
Load->isVolatile())
297 UsersToReplace.insert(
Load);
302 bool IsReplaceable =
all_of(
PHI->incoming_values(),
303 [](
Value *V) { return isa<Instruction>(V); });
304 if (IsReplaceable &&
all_of(
PHI->incoming_values(), [&](
Value *V) {
305 return isAvailable(cast<Instruction>(V));
307 UsersToReplace.insert(
PHI);
308 PushUsersToWorklist(
PHI);
315 if (!IsReplaceable || !ValuesToRevisit.
insert(
PHI))
321 for (
unsigned Idx = 0; Idx <
PHI->getNumIncomingValues(); ++Idx) {
328 if (!TrueInst || !FalseInst)
332 UsersToReplace.insert(SI);
333 PushUsersToWorklist(SI);
340 if (!TryPushInstOperand(TrueInst) || !TryPushInstOperand(FalseInst))
347 UsersToReplace.insert(
GEP);
348 PushUsersToWorklist(
GEP);
353 if (!TryPushInstOperand(PtrOp))
356 if (
MI->isVolatile())
358 UsersToReplace.insert(Inst);
359 }
else if (isEqualOrValidAddrSpaceCast(Inst, FromAS)) {
360 UsersToReplace.insert(Inst);
361 PushUsersToWorklist(Inst);
367 LLVM_DEBUG(
dbgs() <<
"Cannot handle pointer user: " << *Inst <<
'\n');
375void PointerReplacer::replacePointer(
Value *V) {
379 SmallVector<Instruction *> Worklist;
380 SetVector<Instruction *> PostOrderWorklist;
381 SmallPtrSet<Instruction *, 32> Visited;
385 while (!Worklist.
empty()) {
390 if (Visited.
insert(
I).second) {
391 for (
auto *U :
I->users()) {
393 if (UsersToReplace.contains(UserInst) && !Visited.
contains(UserInst))
405 for (Instruction *
I :
reverse(PostOrderWorklist))
409void PointerReplacer::replace(Instruction *
I) {
410 if (getReplacement(
I))
414 auto *
V = getReplacement(
LT->getPointerOperand());
415 assert(V &&
"Operand not replaced");
416 auto *NewI =
new LoadInst(
LT->getType(), V,
"",
LT->getProperties());
418 NewI->copyMetadata(*LT);
425 WorkMap[NewI] = NewI;
427 Value *FirstIncoming =
PHI->getIncomingValue(0);
430 if (
PHI->getType() == NewType) {
431 for (
unsigned I = 0;
I <
PHI->getNumIncomingValues(); ++
I) {
433 PHI->setIncomingValue(
I, V ? V :
PHI->getIncomingValue(
I));
442 NewPHI->copyMetadata(*
PHI);
443 WorkMap[
PHI] = NewPHI;
444 for (
auto [IncomingValue, IncomingBlock] :
447 assert(V &&
V->getType() == NewType &&
448 "Type-changing PHI incoming value was not replaced");
449 NewPHI->addIncoming(V, IncomingBlock);
452 auto *
V = getReplacement(
GEP->getPointerOperand());
453 assert(V &&
"Operand not replaced");
454 SmallVector<Value *, 8> Indices(
GEP->indices());
459 NewI->setNoWrapFlags(
GEP->getNoWrapFlags());
462 Value *TrueValue =
SI->getTrueValue();
463 Value *FalseValue =
SI->getFalseValue();
464 if (
Value *Replacement = getReplacement(TrueValue))
465 TrueValue = Replacement;
466 if (
Value *Replacement = getReplacement(FalseValue))
467 FalseValue = Replacement;
469 SI->getName(),
nullptr, SI);
474 auto *DestV = MemCpy->getRawDest();
475 auto *SrcV = MemCpy->getRawSource();
477 if (
auto *DestReplace = getReplacement(DestV))
479 if (
auto *SrcReplace = getReplacement(SrcV))
484 MemCpy->getIntrinsicID(), DestV, MemCpy->getDestAlign(), SrcV,
485 MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile());
488 NewI->setAAMetadata(AAMD);
491 WorkMap[MemCpy] = NewI;
493 auto *
V = getReplacement(ASC->getPointerOperand());
494 assert(V &&
"Operand not replaced");
495 assert(isEqualOrValidAddrSpaceCast(
496 ASC,
V->getType()->getPointerAddressSpace()) &&
497 "Invalid address space cast!");
499 if (
V->getType()->getPointerAddressSpace() !=
500 ASC->getType()->getPointerAddressSpace()) {
501 auto *NewI =
new AddrSpaceCastInst(V, ASC->getType(),
"");
533 if (&*FirstInst != &AI) {
538 std::optional<TypeSize> EntryAISize =
540 if (!EntryAISize || !EntryAISize->isZero()) {
562 Value *TheSrc = Copy->getSource();
565 TheSrc, AllocaAlign,
DL, &AI, &
AC, &
DT);
566 if (AllocaAlign <= SourceAlign &&
571 LLVM_DEBUG(
dbgs() <<
"Found alloca equal to global: " << AI <<
'\n');
584 PointerReplacer PtrReplacer(*
this, AI, SrcAddrSpace);
585 if (PtrReplacer.collectUsers()) {
589 PtrReplacer.replacePointer(TheSrc);
602 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
615 const Twine &Suffix) {
617 "can't fold an atomic load to requested type");
631 "can't fold an atomic store of requested type");
633 Value *Ptr =
SI.getPointerOperand();
635 SI.getAllMetadata(MD);
638 for (
const auto &MDPair : MD) {
639 unsigned ID = MDPair.first;
650 case LLVMContext::MD_dbg:
651 case LLVMContext::MD_DIAssignID:
652 case LLVMContext::MD_tbaa:
653 case LLVMContext::MD_prof:
654 case LLVMContext::MD_fpmath:
655 case LLVMContext::MD_tbaa_struct:
656 case LLVMContext::MD_alias_scope:
657 case LLVMContext::MD_noalias:
658 case LLVMContext::MD_nontemporal:
659 case LLVMContext::MD_mem_parallel_loop_access:
660 case LLVMContext::MD_access_group:
664 case LLVMContext::MD_invariant_load:
665 case LLVMContext::MD_nonnull:
666 case LLVMContext::MD_noundef:
667 case LLVMContext::MD_range:
668 case LLVMContext::MD_align:
669 case LLVMContext::MD_dereferenceable:
670 case LLVMContext::MD_dereferenceable_or_null:
700 if (!
Load.isUnordered())
703 if (
Load.isElementwise())
706 if (
Load.use_empty())
710 if (
Load.getPointerOperand()->isSwiftError())
716 if (
Load.hasOneUse()) {
722 if (BC->getType()->isX86_AMXTy())
727 Type *DestTy = CastUser->getDestTy();
751 if (!
T->isAggregateType())
758 auto NumElements = ST->getNumElements();
759 if (NumElements == 1) {
764 NewLoad->
copyMetadata(LI, LLVMContext::MD_invariant_load);
772 auto *SL =
DL.getStructLayout(ST);
774 if (SL->hasPadding())
779 auto *IdxType =
DL.getIndexType(Addr->getType());
782 for (
unsigned i = 0; i < NumElements; i++) {
787 ST->getElementType(i), Ptr,
793 L->copyMetadata(LI, LLVMContext::MD_invariant_load);
802 auto *ET = AT->getElementType();
803 auto NumElements = AT->getNumElements();
804 if (NumElements == 1) {
824 auto *Zero = ConstantInt::get(IdxType, 0);
828 for (
uint64_t i = 0; i < NumElements; i++) {
829 Value *Indices[2] = {
831 ConstantInt::get(IdxType, i),
837 EltAlign, Name +
".unpack");
863 P =
P->stripPointerCasts();
880 if (GA->isInterposable())
889 std::optional<TypeSize> AllocSize = AI->getAllocationSize(
DL);
890 if (!AllocSize || AllocSize->isScalable() ||
891 AllocSize->getFixedValue() > MaxSize)
897 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
901 if (InitSize > MaxSize)
907 }
while (!Worklist.
empty());
951 Idx = FirstNZIdx(GEPI);
965 if (!AllocTy || !AllocTy->
isSized())
968 uint64_t TyAllocSize =
DL.getTypeAllocSize(AllocTy).getFixedValue();
974 auto IsAllNonNegative = [&]() {
975 for (
unsigned i = Idx+1, e = GEPI->
getNumOperands(); i != e; ++i) {
977 if (
Known.isNonNegative())
1009 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
1014 if (GEPI->getParent() == MemI.
getParent() &&
1031 auto *Ptr =
SI.getPointerOperand();
1033 Ptr = GEPI->getOperand(0);
1040 const Value *GEPI0 = GEPI->getOperand(0);
1052Value *InstCombinerImpl::simplifyNonNullOperand(
Value *V,
1053 bool HasDereferenceable,
1057 return Sel->getOperand(2);
1060 return Sel->getOperand(1);
1063 if (!
V->hasOneUse())
1071 if (HasDereferenceable ||
GEP->isInBounds()) {
1072 if (
auto *Res = simplifyNonNullOperand(
GEP->getPointerOperand(),
1073 HasDereferenceable,
Depth + 1)) {
1074 replaceOperand(*
GEP, 0, Res);
1083 for (Use &U :
PHI->incoming_values()) {
1085 if (
auto *Res = simplifyNonNullOperand(
U.get(), HasDereferenceable,
1118 bool IsLoadCSE =
false;
1141 if (
Op->hasOneUse()) {
1164 Alignment,
DL,
SI) &&
1166 Alignment,
DL,
SI)) {
1168 auto MaybeCastedLoadOperand = [&](
Value *
Op) {
1171 Op->getName() +
".cast");
1174 Value *LoadOp1 = MaybeCastedLoadOperand(
SI->getOperand(1));
1179 Value *LoadOp2 = MaybeCastedLoadOperand(
SI->getOperand(2));
1195 if (
Value *V = simplifyNonNullOperand(
Op,
true))
1201 if (
II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1202 std::vector<OperandBundleDef> DSBundle;
1212 NewLI->setOperand(0,
II->getOperand(0));
1216 F.getParent(), Intrinsic::ptrauth_auth, {});
1217 auto *LIInt =
Builder.CreatePtrToInt(NewLI,
Builder.getInt64Ty());
1252 auto *W =
E->getVectorOperand();
1258 if (!CI ||
IV->getNumIndices() != 1 || CI->getZExtValue() != *
IV->idx_begin())
1260 V =
IV->getAggregateOperand();
1266 auto *VT = V->getType();
1269 if (
DL.getTypeStoreSizeInBits(UT) !=
DL.getTypeStoreSizeInBits(VT)) {
1279 for (
const auto *EltT : ST->elements()) {
1280 if (EltT != UT->getElementType())
1310 if (!
SI.isUnordered())
1314 if (
SI.getPointerOperand()->isSwiftError())
1317 Value *V =
SI.getValueOperand();
1321 assert(!BC->getType()->isX86_AMXTy() &&
1322 "store to x86_amx* should not happen!");
1323 V = BC->getOperand(0);
1326 if (V->getType()->isX86_AMXTy())
1351 Value *V =
SI.getValueOperand();
1352 Type *
T = V->getType();
1354 if (!
T->isAggregateType())
1359 unsigned Count = ST->getNumElements();
1369 auto *SL =
DL.getStructLayout(ST);
1371 if (SL->hasPadding())
1374 const auto Align =
SI.getAlign();
1378 auto *Addr =
SI.getPointerOperand();
1380 AddrName +=
".repack";
1382 auto *IdxType =
DL.getIndexType(Addr->getType());
1383 for (
unsigned i = 0; i <
Count; i++) {
1399 auto NumElements = AT->getNumElements();
1400 if (NumElements == 1) {
1414 TypeSize EltSize =
DL.getTypeAllocSize(AT->getElementType());
1415 const auto Align =
SI.getAlign();
1419 auto *Addr =
SI.getPointerOperand();
1421 AddrName +=
".repack";
1424 auto *Zero = ConstantInt::get(IdxType, 0);
1427 for (
uint64_t i = 0; i < NumElements; i++) {
1428 Value *Indices[2] = {
1430 ConstantInt::get(IdxType, i),
1457 if (
A ==
B)
return true;
1477 Value *Val =
SI.getOperand(0);
1478 Value *Ptr =
SI.getOperand(1);
1494 if (!
SI.isUnordered())
return nullptr;
1503 if (
GEP->getOperand(0)->hasOneUse())
1519 for (
unsigned ScanInsts = 6; BBI !=
SI.getParent()->begin() && ScanInsts;
1524 if (BBI->isDebugOrPseudoInst()) {
1531 if (PrevSI->isUnordered() &&
1533 PrevSI->getValueOperand()->getType() ==
1534 SI.getValueOperand()->getType()) {
1551 assert(
SI.isUnordered() &&
"can't eliminate ordering operation");
1561 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1600 if (
Value *V = simplifyNonNullOperand(Ptr,
true))
1607 if (
II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1608 std::vector<OperandBundleDef> DSBundle;
1618 F.getParent(), Intrinsic::ptrauth_sign, {});
1619 auto *ValInt =
Builder.CreatePtrToInt(Val,
Builder.getInt64Ty());
1622 {ValInt,
Builder.getInt32( 2),
1643 if (!
SI.isUnordered())
1654 if (*PredIter == StoreBB)
1660 if (StoreBB == DestBB || OtherBB == DestBB)
1665 if (BBI == OtherBB->
begin())
1668 auto OtherStoreIsMergeable = [&](
StoreInst *OtherStore) ->
bool {
1670 OtherStore->getPointerOperand() !=
SI.getPointerOperand())
1673 auto *SIVTy =
SI.getValueOperand()->getType();
1674 auto *OSVTy = OtherStore->getValueOperand()->getType();
1676 SI.hasSameSpecialState(OtherStore);
1685 while (BBI->isDebugOrPseudoInst()) {
1686 if (BBI==OtherBB->
begin())
1693 if (!OtherStoreIsMergeable(OtherStore))
1698 if (OtherBr->getSuccessor(0) != StoreBB &&
1699 OtherBr->getSuccessor(1) != StoreBB)
1708 if (OtherStoreIsMergeable(OtherStore))
1713 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1714 BBI->mayWriteToMemory() || BBI == OtherBB->
begin())
1722 if (
I->mayReadFromMemory() ||
I->mayThrow() ||
I->mayWriteToMemory())
1733 if (MergedVal !=
SI.getValueOperand()) {
1737 Builder.SetInsertPoint(OtherStore);
1747 new StoreInst(MergedVal,
SI.getOperand(1),
SI.getProperties());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void addToWorklist(Instruction &I, SmallVector< Instruction *, 4 > &Worklist)
This file provides internal interfaces used to implement the InstCombine.
static StoreInst * combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
static Instruction * combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &Load)
Combine loads to match the type of their uses' value after looking through intervening bitcasts.
static Instruction * replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, Instruction &MemI)
static Instruction * simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI, DominatorTree &DT)
static bool canSimplifyNullStoreOrGEP(StoreInst &SI)
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op)
static bool isSupportedAtomicType(Type *Ty)
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL)
Returns true if V is dereferenceable for size of alloca.
static Instruction * unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI)
static cl::opt< unsigned > MaxCopiedFromConstantUsers("instcombine-max-copied-from-constant-users", cl::init(300), cl::desc("Maximum users to visit in copy from constant transform"), cl::Hidden)
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI)
static Value * likeBitCastFromVector(InstCombinerImpl &IC, Value *V)
Look for extractelement/insertvalue sequence that acts like a bitcast.
static bool isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete)
isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived) pointer to an alloca.
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static const uint32_t IV[8]
Class for arbitrary precision integers.
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
This is an important base class in LLVM.
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Type * getSourceElementType() const
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
LLVM_ABI Value * CreateTypeSize(Type *Ty, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
LLVM_ABI CallInst * CreateMemTransferInst(Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, Value *Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * visitLoadInst(LoadInst &LI)
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitStoreInst(StoreInst &SI)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; }...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
bool removeInstructionsBeforeUnreachable(Instruction &I)
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitAllocaInst(AllocaInst &AI)
const DataLayout & getDataLayout() const
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
LoadStoreInstProperties getProperties() const
Returns the properties of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
This class wraps the llvm.memcpy/memmove intrinsics.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static constexpr TypeSize getZero()
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static LLVM_ABI Type * getIntFromByteType(Type *)
Returns an integer (vector of integer) type with the same size of a byte of the given byte (vector of...
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isX86_AMXTy() const
Return true if this is X86 AMX.
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool isAvailable()
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto reverse(ContainerTy &&C)
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
bool isModSet(const ModRefInfo MRI)
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, Instruction *ScanFrom, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
LLVM_ABI Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
OperandBundleDefT< Value * > OperandBundleDef
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.