24 #define DEBUG_TYPE "instcombine" 28 cl::desc(
"Maximum number phis to handle in intptr/ptrint folding"));
38 assert(!isa<CallInst>(Inst));
109 Value *Ptr =
nullptr;
110 if (
LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
111 Ptr = LoadI->getPointerOperand();
112 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
113 Ptr =
SI->getPointerOperand();
115 Ptr = GI->getPointerOperand();
118 if (Ptr && Ptr == IIP)
124 if (!HasPointerUse(IntToPtr))
127 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
128 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
136 if (
auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
142 Value *ArgIntToPtr =
nullptr;
144 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
159 if (isa<PHINode>(Arg)) {
169 if (!LoadI->hasOneUse())
181 "Not enough available ptr typed incoming values");
182 PHINode *MatchingPtrPHI =
nullptr;
183 unsigned NumPhis = 0;
185 II != EI; II++, NumPhis++) {
190 if (!PtrPHI || PtrPHI == &PN || PtrPHI->
getType() != IntToPtr->getType())
192 MatchingPtrPHI = PtrPHI;
194 if (AvailablePtrVals[i] !=
196 MatchingPtrPHI =
nullptr;
205 if (MatchingPtrPHI) {
206 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
207 "Phi's Type does not match with IntToPtr");
210 IntToPtr->getOperand(0)->getType());
215 return (V->
getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
222 if (V->
getType() == IntToPtr->getType())
233 InsertNewInstBefore(NewPtrPHI, PN);
237 auto *IncomingVal = AvailablePtrVals[i];
239 if (IncomingVal->getType() == IntToPtr->getType()) {
246 assert((isa<PHINode>(IncomingVal) ||
247 IncomingVal->getType()->isPointerTy() ||
249 "Can not replace LoadInst with multiple uses");
262 IncomingVal->getName() +
".ptr");
263 if (
auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
266 if (isa<PHINode>(IncomingI))
267 InsertPos = IncomingI->getParent()->getFirstInsertionPt();
268 InsertNewInstBefore(CI, *InsertPos);
270 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
271 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
286 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
305 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
306 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->
getPredicate())
310 if (I->
getOperand(0) != LHSVal) LHSVal =
nullptr;
311 if (I->
getOperand(1) != RHSVal) RHSVal =
nullptr;
318 if (!LHSVal && !RHSVal)
325 PHINode *NewLHS =
nullptr, *NewRHS =
nullptr;
330 InsertNewInstBefore(NewLHS, PN);
338 InsertNewInstBefore(NewRHS, PN);
343 if (NewLHS || NewRHS) {
357 if (
CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
360 PHIArgMergedDebugLoc(NewCI, PN);
373 PHIArgMergedDebugLoc(NewBinOp, PN);
384 bool AllBasePointersAreAllocas =
true;
389 bool NeededPhi =
false;
391 bool AllInBounds =
true;
403 if (AllBasePointersAreAllocas &&
406 AllBasePointersAreAllocas =
false;
432 FixedOperands[
op] =
nullptr;
443 if (AllBasePointersAreAllocas)
450 bool HasAnyPHIs =
false;
451 for (
unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
452 if (FixedOperands[i])
continue;
456 InsertNewInstBefore(NewPN, PN);
459 OperandPhis[i] = NewPN;
460 FixedOperands[i] = NewPN;
471 for (
unsigned op = 0, e = OperandPhis.size();
op != e; ++
op)
473 OpPhi->addIncoming(InGEP->
getOperand(op), InBB);
482 PHIArgMergedDebugLoc(NewGEP, PN);
497 for (++BBI; BBI !=
E; ++BBI)
498 if (BBI->mayWriteToMemory())
504 bool isAddressTaken =
false;
506 if (isa<LoadInst>(U))
continue;
509 if (
SI->getOperand(1) == AI)
continue;
511 isAddressTaken =
true;
515 if (!isAddressTaken && AI->isStaticAlloca())
581 LoadAlignment = std::min(LoadAlignment, LI->
getAlignment());
601 unsigned KnownIDs[] = {
614 for (
unsigned ID : KnownIDs)
622 if (NewInVal != InVal)
633 InsertNewInstBefore(NewPN, PN);
641 cast<LoadInst>(IncValue)->setVolatile(
false);
643 PHIArgMergedDebugLoc(NewLI, PN);
661 if (NumIncomingValues < 3)
665 Type *NarrowType =
nullptr;
667 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
668 NarrowType = Zext->getSrcTy();
678 unsigned NumZexts = 0;
679 unsigned NumConsts = 0;
681 if (
auto *Zext = dyn_cast<ZExtInst>(V)) {
683 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
685 NewIncoming.
push_back(Zext->getOperand(0));
687 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
706 if (NumConsts == 0 || NumZexts < 2)
714 for (
unsigned i = 0; i != NumIncomingValues; ++i)
717 InsertNewInstBefore(NewPhi, Phi);
733 if (isa<GetElementPtrInst>(FirstInst))
734 return FoldPHIArgGEPIntoPHI(PN);
735 if (isa<LoadInst>(FirstInst))
736 return FoldPHIArgLoadIntoPHI(PN);
743 Type *CastSrcTy =
nullptr;
745 if (isa<CastInst>(FirstInst)) {
751 if (!shouldChangeType(PN.
getType(), CastSrcTy))
754 }
else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
759 return FoldPHIArgBinOpIntoPHI(PN);
789 if (NewInVal != InVal)
801 InsertNewInstBefore(NewPN, PN);
806 if (
CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
809 PHIArgMergedDebugLoc(NewCI, PN);
813 if (
BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
820 PHIArgMergedDebugLoc(BinOp, PN);
824 CmpInst *CIOp = cast<CmpInst>(FirstInst);
827 PHIArgMergedDebugLoc(NewCI, PN);
838 if (!PotentiallyDeadPHIs.
insert(PN).second)
842 if (PotentiallyDeadPHIs.
size() == 16)
857 if (!ValueEqualPHIs.
insert(PN).second)
861 if (ValueEqualPHIs.
size() == 16)
867 if (
PHINode *OpPN = dyn_cast<PHINode>(
Op)) {
870 }
else if (
Op != NonPhiInVal)
880 assert(isa<IntegerType>(PN.
getType()) &&
"Expect only integer type phi");
882 if (
auto *ConstVA = dyn_cast<ConstantInt>(V))
883 if (!ConstVA->isZero())
889 struct PHIUsageRecord {
895 : PHIId(pn), Shift(Sh), Inst(User) {}
897 bool operator<(
const PHIUsageRecord &RHS)
const {
898 if (PHIId < RHS.PHIId)
return true;
899 if (PHIId > RHS.PHIId)
return false;
900 if (Shift < RHS.Shift)
return true;
901 if (Shift > RHS.Shift)
return false;
903 RHS.Inst->getType()->getPrimitiveSizeInBits();
907 struct LoweredPHIRecord {
912 LoweredPHIRecord(
PHINode *pn,
unsigned Sh,
Type *Ty)
916 LoweredPHIRecord(
PHINode *pn,
unsigned Sh)
917 : PN(pn), Shift(Sh), Width(0) {}
925 return LoweredPHIRecord(
nullptr, 0);
928 return LoweredPHIRecord(
nullptr, 1);
934 static bool isEqual(
const LoweredPHIRecord &LHS,
935 const LoweredPHIRecord &RHS) {
936 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
937 LHS.Width == RHS.Width;
964 PHIsInspected.
insert(&FirstPhi);
966 for (
unsigned PHIId = 0; PHIId != PHIsToSlice.
size(); ++PHIId) {
967 PHINode *PN = PHIsToSlice[PHIId];
989 if (
PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
990 if (PHIsInspected.
insert(UserPN).second)
996 if (isa<TruncInst>(UserI)) {
997 PHIUsers.
push_back(PHIUsageRecord(PHIId, 0, UserI));
1002 if (UserI->
getOpcode() != Instruction::LShr ||
1007 unsigned Shift = cast<ConstantInt>(UserI->
getOperand(1))->getZExtValue();
1013 if (PHIUsers.
empty())
1021 for (
unsigned i = 1, e = PHIsToSlice.
size(); i != e; ++i)
dbgs()
1022 <<
"AND USER PHI #" << i <<
": " << *PHIsToSlice[i] <<
'\n';);
1032 for (
unsigned UserI = 0, UserE = PHIUsers.
size(); UserI != UserE; ++UserI) {
1033 unsigned PHIId = PHIUsers[UserI].PHIId;
1034 PHINode *PN = PHIsToSlice[PHIId];
1035 unsigned Offset = PHIUsers[UserI].Shift;
1036 Type *Ty = PHIUsers[UserI].Inst->getType();
1042 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) ==
nullptr) {
1048 "Truncate didn't shrink phi?");
1052 Value *&PredVal = PredValues[Pred];
1068 if (
PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1071 if (
Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1084 Res = Builder.CreateTrunc(Res, Ty,
"extract.t");
1093 if (PHIsInspected.
count(OldInVal)) {
1095 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1096 PHIUsers.
push_back(PHIUsageRecord(RefPHIId, Offset,
1097 cast<Instruction>(Res)));
1103 LLVM_DEBUG(
dbgs() <<
" Made element PHI for offset " << Offset <<
": " 1104 << *EltPHI <<
'\n');
1105 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1109 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1115 for (
unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1116 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1117 return replaceInstUsesWith(FirstPhi, Undef);
1124 return replaceInstUsesWith(PN, V);
1126 if (
Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1138 if (
Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1145 if (
Instruction *Result = FoldIntegerTypedPHI(PN))
1149 if (
PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1151 PotentiallyDeadPHIs.
insert(&PN);
1163 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1201 while (InValNo != NumIncomingVals &&
1205 if (InValNo != NumIncomingVals) {
1210 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1212 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1219 if (InValNo == NumIncomingVals) {
1222 return replaceInstUsesWith(PN, NonPhiInVal);
1257 if (
Instruction *Res = SliceUpIllegalIntegerPHI(PN))
This class is the base class for the comparison instructions.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
This class represents lattice values for constants.
BinaryOps getOpcode() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
void push_back(const T &Elt)
static LoweredPHIRecord getEmptyKey()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool isTerminator() const
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
An instruction for reading from memory.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
static ConstantInt * GetAnyNonZeroConstInt(PHINode &PN)
Return an existing non-zero constant if this phi node has one, otherwise return constant 1...
static bool isSafeAndProfitableToSinkLoad(LoadInst *L)
Return true if we know that it is safe to sink the load out of the block that defines it...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool match(Val *V, const Pattern &P)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Instruction * SliceUpIllegalIntegerPHI(PHINode &PN)
This is an integer PHI and we know that it has an illegal type: see if it is only used by trunc or tr...
static bool isEqual(const LoweredPHIRecord &LHS, const LoweredPHIRecord &RHS)
Type * getSourceElementType() const
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
OtherOps getOpcode() const
Get the opcode casted to the right type.
Type * getType() const
All values are typed, get the type of this value.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
This class represents a cast from an integer to a pointer.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Instruction * visitPHINode(PHINode &PN)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
static cl::opt< unsigned > MaxNumPhis("instcombine-max-num-phis", cl::init(512), cl::desc("Maximum number phis to handle in intptr/ptrint folding"))
static LoweredPHIRecord getTombstoneKey()
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
amdgpu Simplify well known AMD library false Value Value * Arg
static bool DeadPHICycle(PHINode *PN, SmallPtrSetImpl< PHINode *> &PotentiallyDeadPHIs)
Return true if this PHI node is only used by a PHI node cycle that is dead.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
bool isEquality() const
This is just a convenience that dispatches to the subclasses.
This file provides internal interfaces used to implement the InstCombine.
static unsigned getHashValue(const LoweredPHIRecord &Val)
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool isVolatile(Instruction *Inst)
void setIncomingValue(unsigned i, Value *V)
op_range incoming_values()
static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, SmallPtrSetImpl< PHINode *> &ValueEqualPHIs)
Return true if this phi node is always equal to NonPhiInVal.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack