43 #define DEBUG_TYPE "evaluator" 66 if (
auto *GV = dyn_cast<GlobalValue>(C))
67 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
74 if (isa<ConstantAggregate>(C)) {
86 case Instruction::BitCast:
90 case Instruction::IntToPtr:
91 case Instruction::PtrToInt:
100 case Instruction::GetElementPtr:
120 if (!SimpleConstants.
insert(C).second)
134 if (!cast<PointerType>(C->
getType())->getElementType()->isSingleValueType())
139 return GV->hasUniqueInitializer();
143 if (CE->getOpcode() == Instruction::GetElementPtr &&
144 isa<GlobalVariable>(CE->getOperand(0)) &&
145 cast<GEPOperator>(CE)->isInBounds()) {
154 if (!CI || !CI->
isZero())
return false;
158 if (!CE->isGEPWithNoNotionalOverIndexing())
166 }
else if (CE->getOpcode() == Instruction::BitCast &&
167 isa<GlobalVariable>(CE->getOperand(0))) {
170 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
186 while (!(Val = Func(Ptr))) {
190 Type *Ty = cast<PointerType>(Ptr->
getType())->getElementType();
191 if (!isa<StructType>(Ty))
196 Constant *
const IdxList[] = {IdxZero, IdxZero};
215 auto findMemLoc = [
this](
Constant *Ptr) {
217 MutatedMemory.find(Ptr);
218 return I != MutatedMemory.end() ? I->second :
nullptr;
226 if (GV->hasDefinitiveInitializer())
227 return GV->getInitializer();
232 switch (CE->getOpcode()) {
234 case Instruction::GetElementPtr:
239 case Instruction::BitCast:
259 if (
auto *Fn = dyn_cast<Function>(C))
262 if (
auto *Alias = dyn_cast<GlobalAlias>(C))
263 if (
auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
276 if (!CE || CE->getOpcode() != Instruction::BitCast ||
296 for (
auto ParI = FTy->param_begin(), ParE = FTy->param_end(); ParI != ParE;
313 if (!RV || !CE || CE->
getOpcode() != Instruction::BitCast)
334 LLVM_DEBUG(
dbgs() <<
"Evaluating Instruction: " << *CurInst <<
"\n");
336 if (
StoreInst *
SI = dyn_cast<StoreInst>(CurInst)) {
337 if (!
SI->isSimple()) {
343 LLVM_DEBUG(
dbgs() <<
"Folding constant ptr expression: " << *Ptr);
350 dbgs() <<
"Pointer is too complex for us to evaluate store.");
359 LLVM_DEBUG(
dbgs() <<
"Store value is too complex to evaluate store. " 365 if (CE->getOpcode() == Instruction::BitCast) {
367 <<
"Attempting to resolve bitcast on constant ptr.\n");
376 Type *Ty = cast<PointerType>(P->
getType())->getElementType();
397 MutatedMemory[Ptr] = Val;
398 }
else if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
400 getVal(BO->getOperand(0)),
401 getVal(BO->getOperand(1)));
403 << *InstResult <<
"\n");
404 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
406 getVal(CI->getOperand(0)),
407 getVal(CI->getOperand(1)));
408 LLVM_DEBUG(
dbgs() <<
"Found a CmpInst! Simplifying: " << *InstResult
410 }
else if (
CastInst *CI = dyn_cast<CastInst>(CurInst)) {
412 getVal(CI->getOperand(0)),
416 }
else if (
SelectInst *
SI = dyn_cast<SelectInst>(CurInst)) {
420 LLVM_DEBUG(
dbgs() <<
"Found a Select! Simplifying: " << *InstResult
422 }
else if (
auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
424 getVal(EVI->getAggregateOperand()), EVI->getIndices());
426 << *InstResult <<
"\n");
427 }
else if (
auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
429 getVal(IVI->getAggregateOperand()),
430 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
432 << *InstResult <<
"\n");
441 cast<GEPOperator>(
GEP)->isInBounds());
442 LLVM_DEBUG(
dbgs() <<
"Found a GEP! Simplifying: " << *InstResult <<
"\n");
443 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
444 if (!LI->isSimple()) {
446 dbgs() <<
"Found a Load! Not a simple load, can not evaluate.\n");
453 LLVM_DEBUG(
dbgs() <<
"Found a constant pointer expression, constant " 457 InstResult = ComputeLoadResult(Ptr);
460 dbgs() <<
"Failed to compute load result. Can not evaluate load." 466 }
else if (
AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
467 if (AI->isArrayAllocation()) {
468 LLVM_DEBUG(
dbgs() <<
"Found an array alloca. Can not evaluate.\n");
471 Type *Ty = AI->getAllocatedType();
472 AllocaTmps.push_back(std::make_unique<GlobalVariable>(
475 AI->getType()->getPointerAddressSpace()));
476 InstResult = AllocaTmps.back().get();
477 LLVM_DEBUG(
dbgs() <<
"Found an alloca. Result: " << *InstResult <<
"\n");
478 }
else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
495 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
496 if (MSI->isVolatile()) {
504 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
512 if (II->isLifetimeStartOrEnd()) {
518 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
521 if (!II->use_empty()) {
523 <<
"Found unused invariant_start. Can't evaluate.\n");
530 Type *ElemTy = GV->getValueType();
534 Invariants.insert(GV);
539 <<
"Found a global var, but can not treat it as an " 546 }
else if (II->getIntrinsicID() == Intrinsic::assume) {
550 }
else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
571 Callee, Formals, TLI)) {
576 << *InstResult <<
"\n");
583 LLVM_DEBUG(
dbgs() <<
"Can not constant fold vararg function call.\n");
589 ValueStack.emplace_back();
594 ValueStack.pop_back();
596 if (RetVal && !InstResult)
601 << *InstResult <<
"\n\n");
604 <<
"Successfully evaluated function. Result: 0\n\n");
607 }
else if (CurInst->isTerminator()) {
610 if (
BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
611 if (BI->isUnconditional()) {
612 NextBB = BI->getSuccessor(0);
616 if (!Cond)
return false;
620 }
else if (
SwitchInst *
SI = dyn_cast<SwitchInst>(CurInst)) {
623 if (!Val)
return false;
624 NextBB =
SI->findCaseValue(Val)->getCaseSuccessor();
625 }
else if (
IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
626 Value *Val =
getVal(IBI->getAddress())->stripPointerCasts();
628 NextBB = BA->getBasicBlock();
631 }
else if (isa<ReturnInst>(CurInst)) {
645 dbgs() <<
"Failed to evaluate block due to unhandled instruction." 650 if (!CurInst->use_empty()) {
652 InstResult = FoldedInstResult;
654 setVal(&*CurInst, InstResult);
658 if (
InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
659 NextBB = II->getNormalDest();
660 LLVM_DEBUG(
dbgs() <<
"Found an invoke instruction. Finished Block.\n\n");
679 CallStack.push_back(F);
685 setVal(&*AI, ActualArgs[ArgNo]);
699 LLVM_DEBUG(
dbgs() <<
"Trying to evaluate BB: " << *CurBB <<
"\n");
710 CallStack.pop_back();
717 if (!ExecutedBlocks.
insert(NextBB).second)
724 for (CurInst = NextBB->
begin();
Return a value (possibly void), from a function.
A parsed version of the target data layout string in and methods for querying it. ...
This class is the base class for the comparison instructions.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
This class represents an incoming formal argument to a Function.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Constant * ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE)
ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a getelementptr constantexpr, return the constant value being addressed by the constant expression, or null if something is funny and we can't decide.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant *> Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
void push_back(const T &Elt)
bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB)
Evaluate all instructions in block BB, returning true if successful, false if we can't evaluate it...
bool getFormalParams(CallSite &CS, Function *F, SmallVector< Constant *, 8 > &Formals)
Given call site and callee returns list of callee formal argument values converting them when necessa...
bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
This class wraps the llvm.memset intrinsic.
An instruction for reading from memory.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
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...
bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant *> &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
The address of a basic block.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
This is the base class for all instructions that perform data casts.
A Use represents the edge between a Value definition and its users.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
InstrTy * getInstruction() const
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
A constant value that is initialized with an expression using other constant values.
Type * getType() const
All values are typed, get the type of this value.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
static Constant * evaluateBitcastFromPtr(Constant *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, std::function< Constant *(Constant *)> Func)
Apply 'Func' to Ptr.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
const APInt & getValue() const
Return the constant as an APInt value reference.
An instruction for storing to memory.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
static Function * getFunction(Constant *C)
Value * getOperand(unsigned i) const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
unsigned getNumArgOperands() const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void setVal(Value *V, Constant *C)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Indirect Branch Instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
static bool isSimpleEnoughValueToCommit(Constant *C, SmallPtrSetImpl< Constant *> &SimpleConstants, const DataLayout &DL)
static bool isSimpleEnoughValueToCommitHelper(Constant *C, SmallPtrSetImpl< Constant *> &SimpleConstants, const DataLayout &DL)
Return true if the specified constant can be handled by the code generator.
Class to represent integer types.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
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.
Constant * getVal(Value *V)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
static Constant * getInitializer(Constant *C)
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
amdgpu Simplify well known AMD library false FunctionCallee Callee
static bool isSimpleEnoughPointerToCommit(Constant *C)
Return true if this constant is simple enough for us to understand.
InstListType::iterator iterator
Instruction iterators...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Function * getCalleeWithFormalArgs(CallSite &CS, SmallVector< Constant *, 8 > &Formals)
Given call site return callee and list of its formal arguments.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
StringRef getName() const
Return a constant reference to the value's name.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Constant * castCallResultIfNeeded(Value *CallExpr, Constant *RV)
Casts call result to a type of bitcast call expression.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const BasicBlock & front() const
LLVM Value Representation.
Constant * ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, const DataLayout &DL)
ConstantFoldLoadThroughBitcast - try to cast constant to destination type returning null if unsuccess...
print Print MemDeps of function
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
A wrapper class for inspecting calls to intrinsic functions.
an instruction to allocate memory on the stack
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.