15 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H 16 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H 47 #define DEBUG_TYPE "instcombine" 54 class AssumptionCache;
55 class BlockFrequencyInfo;
61 class OptimizationRemarkEmitter;
62 class ProfileSummaryInfo;
63 class TargetLibraryInfo;
84 if (isa<Instruction>(V)) {
92 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
120 bool &TrueIfSigned) {
129 TrueIfSigned =
false;
132 TrueIfSigned =
false;
144 TrueIfSigned =
false;
148 TrueIfSigned =
false;
162 if (
auto *BitCast = dyn_cast<BitCastInst>(V))
163 if (!OneUseOnly || BitCast->hasOneUse())
164 return BitCast->getOperand(0);
198 return WillInvertAllUses;
204 BO->getOpcode() == Instruction::Sub)
205 if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
206 return WillInvertAllUses;
210 return WillInvertAllUses;
221 if (U == IgnoredUser)
224 auto *
I = cast<Instruction>(U);
225 switch (
I->getOpcode()) {
227 case Instruction::Br:
229 case Instruction::Xor:
256 case Instruction::SRem:
257 case Instruction::URem:
260 case Instruction::FRem:
268 case Instruction::Shl:
269 case Instruction::LShr:
270 case Instruction::AShr:
271 case Instruction::SDiv:
272 case Instruction::UDiv:
273 case Instruction::SRem:
274 case Instruction::URem:
275 case Instruction::Sub:
276 case Instruction::FSub:
277 case Instruction::FDiv:
278 case Instruction::FRem:
286 assert(SafeC &&
"Must have safe constant for binop");
289 for (
unsigned i = 0; i != NumElts; ++i) {
291 Out[i] = isa<UndefValue>(
C) ? SafeC : C;
301 :
public InstVisitor<InstCombiner, Instruction *> {
314 const bool MinimizeSize;
317 const bool ExpensiveCombines;
335 bool MadeIRChange =
false;
339 bool MinimizeSize,
bool ExpensiveCombines,
AliasAnalysis *AA,
343 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
344 ExpensiveCombines(ExpensiveCombines), AA(AA), AC(AC), TLI(TLI), DT(DT),
345 DL(DL), SQ(DL, &TLI, &DT, &AC), ORE(ORE), BFI(BFI), PSI(PSI), LI(LI) {}
372 Value *OptimizePointerDifference(
394 Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
396 bool AnalyzeForSignBitExtraction =
false);
397 Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
399 Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
463 const unsigned SIOpd);
471 const Twine &Suffix =
"");
474 bool shouldChangeType(
unsigned FromBitWidth,
unsigned ToBitWidth)
const;
489 bool shouldOptimizeCast(
CastInst *CI);
510 bool transformConstExprCastCall(
CallBase &Call);
532 bool DoTransform =
true);
536 bool willNotOverflowSignedAdd(
const Value *LHS,
const Value *RHS,
542 bool willNotOverflowUnsignedAdd(
const Value *LHS,
const Value *RHS,
548 bool willNotOverflowAdd(
const Value *LHS,
const Value *RHS,
550 return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
551 : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
554 bool willNotOverflowSignedSub(
const Value *LHS,
const Value *RHS,
560 bool willNotOverflowUnsignedSub(
const Value *LHS,
const Value *RHS,
566 bool willNotOverflowSub(
const Value *LHS,
const Value *RHS,
568 return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
569 : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
572 bool willNotOverflowSignedMul(
const Value *LHS,
const Value *RHS,
578 bool willNotOverflowUnsignedMul(
const Value *LHS,
const Value *RHS,
584 bool willNotOverflowMul(
const Value *LHS,
const Value *RHS,
586 return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
587 : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
592 bool IsSigned)
const {
595 case Instruction::Sub:
return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
596 case Instruction::Mul:
return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
647 "New instruction already inserted into a basic block!");
657 return InsertNewInstBefore(New, Old);
679 <<
" with " << *V <<
'\n');
719 if (
auto *Inst = dyn_cast<Instruction>(Operand))
789 OverflowResult computeOverflow(
794 uint64_t MaxArraySizeForCombine = 0;
848 const APInt &DemandedMask,
854 Value *simplifyShrShlDemandedBits(
860 bool SimplifyDemandedInstructionBits(
Instruction &Inst);
868 bool AllowMultipleUsers =
false);
930 Value *foldUnsignedMultiplicationOverflowCheck(
ICmpInst &Cmp);
988 bool isSigned,
bool Inside);
990 bool mergeStoreIntoSuccessor(
StoreInst &SI);
999 Value *EvaluateInDifferentType(
Value *V,
Type *Ty,
bool isSigned);
1011 #endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H Type * getVectorElementType() const
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Return a value (possibly void), from a function.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * InsertNewInstWith(Instruction *New, Instruction &Old)
Same as InsertNewInstBefore, but also sets the debug loc.
A parsed version of the target data layout string in and methods for querying it. ...
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
Base class for instruction visitors.
This class represents lattice values for constants.
An instruction for ordering other memory operations.
This class represents zero extension of integer types.
Analysis providing profile information.
This class represents a function call, abstracting a target machine's calling convention.
static bool isCanonicalPredicate(CmpInst::Predicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
void Remove(Instruction *I)
A cache of @llvm.assume calls within a function.
This instruction constructs a fixed permutation of two input vectors.
LLVMContext & getContext() const
All values hold a context through their type.
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a sign extension of integer types.
An instruction for reading from memory.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
bool isVectorTy() const
True if this is an instance of VectorType.
This defines the Use class.
OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
static bool isFreeToInvert(Value *V, bool WillInvertAllUses)
Return true if the specified value is free to invert (apply ~ to).
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
bool match(Val *V, const Pattern &P)
This class represents a conversion between pointers from one address space to another.
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, 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 have exactly one bit set when defined. ...
This class represents the LLVM 'select' instruction.
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.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
Instruction * eraseInstFromFunction(Instruction &I)
Combiner aware instruction erasure.
The core instruction combiner logic.
static Constant * AddOne(Constant *C)
Add one to a Constant.
0 1 0 1 True if ordered and less than or equal
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if 'V & Mask' is known to be zero.
This class represents a cast from a pointer to an integer.
DominatorTree & getDominatorTree() const
static Value * peekThroughBitcast(Value *V, bool OneUseOnly=false)
Return the source operand of a potentially bitcasted value while optionally checking if it has one us...
Type * getType() const
All values are typed, get the type of this value.
This represents the llvm.va_start intrinsic.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
void salvageDebugInfoOrMarkUndef(Instruction &I)
Salvage all debug users of the instruction I or mark it as undef if it cannot be salvaged.
This instruction compares its operands according to the predicate given to the constructor.
This class represents a no-op cast from one type to another.
An instruction for storing to memory.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
Instruction * visitInstruction(Instruction &I)
Specify what to return for unhandled instructions.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
This class represents a cast from floating point to signed integer.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
This class represents a truncation of integer types.
Class to represent pointers.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
const DataLayout & getDataLayout() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
This instruction inserts a single (scalar) element into a VectorType value.
bool isAllOnesValue() const
Determine if all bits are set.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
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...
void AddUsersToWorkList(Instruction &I)
AddUsersToWorkList - When an instruction is simplified, add all users of the instruction to the work ...
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, unsigned Depth=0, const Instruction *CxtI=nullptr)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit...
bool isMinSignedValue() const
Determine if this is the smallest signed value.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
This class represents any memset intrinsic.
Instruction * CreateOverflowTuple(IntrinsicInst *II, Value *Result, Constant *Overflow)
Creates a result tuple for an overflow intrinsic II with a given Result and a constant Overflow value...
static Constant * get(StructType *T, ArrayRef< Constant *> V)
#define LLVM_LIBRARY_VISIBILITY
LLVM_LIBRARY_VISIBILITY - If a class marked with this attribute is linked into a shared library...
self_iterator getIterator()
This class represents a cast from an integer to a pointer.
InstCombineWorklist - This is the worklist management logic for InstCombine.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InstCombiner(InstCombineWorklist &Worklist, BuilderTy &Builder, bool MinimizeSize, bool ExpensiveCombines, AliasAnalysis *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, const DataLayout &DL, LoopInfo *LI)
TargetLibraryInfo & getTargetLibraryInfo() const
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
InstCombineWorklist & Worklist
A worklist of the instructions that need to be simplified.
const InstListType & getInstList() const
Return the underlying instruction list container.
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
unsigned getNumOperands() const
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
bool isMaxSignedValue() const
Determine if this is the largest signed value.
This is the shared class of boolean and integer constants.
BlockVerifier::State From
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
SelectPatternFlavor
Specific patterns of select instructions we can match.
Provides information about what library functions are available for the current target.
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
This class represents a freeze function that returns random concrete value if an operand is either a ...
This class represents a cast from floating point to unsigned integer.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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 Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
unsigned getVectorNumElements() const
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI)
For pattern like:
LoopInfo * getLoopInfo() const
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
static bool canFreelyInvertAllUsersOf(Value *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned greater or equal
KnownBits computeKnownBits(const Value *V, unsigned Depth, const Instruction *CxtI) const
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
llvm::Optional< std::pair< CmpInst::Predicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred, Constant *C)
0 1 1 0 True if ordered and operands are unequal
Instruction * InsertNewInstBefore(Instruction *New, Instruction &Old)
Inserts an instruction New before instruction Old.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
AssumptionCache & getAssumptionCache() const
This represents the llvm.va_copy intrinsic.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
This class represents a truncation of floating point types.
LLVM Value Representation.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
0 0 1 1 True if ordered and greater than or equal
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
static Constant * get(ArrayRef< Constant *> V)
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
bool isNullValue() const
Determine if all bits are clear.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
This instruction inserts a struct field of array element value into an aggregate value.