29 #define DEBUG_TYPE "evaluator"
52 if (
auto *GV = dyn_cast<GlobalValue>(C))
53 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
60 if (isa<ConstantAggregate>(C)) {
72 case Instruction::BitCast:
76 case Instruction::IntToPtr:
77 case Instruction::PtrToInt:
86 case Instruction::GetElementPtr:
106 if (!SimpleConstants.
insert(C).second)
120 if (!cast<PointerType>(C->
getType())->getElementType()->isSingleValueType())
125 return GV->hasUniqueInitializer();
129 if (CE->getOpcode() == Instruction::GetElementPtr &&
130 isa<GlobalVariable>(CE->getOperand(0)) &&
131 cast<GEPOperator>(CE)->isInBounds()) {
140 if (!CI || !CI->
isZero())
return false;
144 if (!CE->isGEPWithNoNotionalOverIndexing())
152 }
else if (CE->getOpcode() == Instruction::BitCast &&
153 isa<GlobalVariable>(CE->getOperand(0))) {
156 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
169 if (I != MutatedMemory.end())
return I->second;
173 if (GV->hasDefinitiveInitializer())
174 return GV->getInitializer();
180 if (
CE->getOpcode() == Instruction::GetElementPtr &&
181 isa<GlobalVariable>(
CE->getOperand(0))) {
199 DEBUG(
dbgs() <<
"Evaluating Instruction: " << *CurInst <<
"\n");
201 if (
StoreInst *
SI = dyn_cast<StoreInst>(CurInst)) {
202 if (!
SI->isSimple()) {
203 DEBUG(
dbgs() <<
"Store is not simple! Can not evaluate.\n");
208 DEBUG(
dbgs() <<
"Folding constant ptr expression: " << *Ptr);
210 DEBUG(
dbgs() <<
"; To: " << *Ptr <<
"\n");
214 DEBUG(
dbgs() <<
"Pointer is too complex for us to evaluate store.");
223 DEBUG(
dbgs() <<
"Store value is too complex to evaluate store. " << *Val
229 if (CE->getOpcode() == Instruction::BitCast) {
230 DEBUG(
dbgs() <<
"Attempting to resolve bitcast on constant ptr.\n");
234 Ptr = CE->getOperand(0);
236 Type *NewTy = cast<PointerType>(Ptr->
getType())->getElementType();
245 if (
StructType *STy = dyn_cast<StructType>(NewTy)) {
246 NewTy = STy->getTypeAtIndex(0U);
250 Constant *
const IdxList[] = {IdxZero, IdxZero};
259 DEBUG(
dbgs() <<
"Failed to bitcast constant ptr, can not "
269 DEBUG(
dbgs() <<
"Evaluated bitcast: " << *Val <<
"\n");
273 MutatedMemory[
Ptr] = Val;
274 }
else if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
276 getVal(BO->getOperand(0)),
277 getVal(BO->getOperand(1)));
278 DEBUG(
dbgs() <<
"Found a BinaryOperator! Simplifying: " << *InstResult
280 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
282 getVal(CI->getOperand(0)),
283 getVal(CI->getOperand(1)));
284 DEBUG(
dbgs() <<
"Found a CmpInst! Simplifying: " << *InstResult
286 }
else if (
CastInst *CI = dyn_cast<CastInst>(CurInst)) {
288 getVal(CI->getOperand(0)),
290 DEBUG(
dbgs() <<
"Found a Cast! Simplifying: " << *InstResult
292 }
else if (
SelectInst *
SI = dyn_cast<SelectInst>(CurInst)) {
296 DEBUG(
dbgs() <<
"Found a Select! Simplifying: " << *InstResult
298 }
else if (
auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
300 getVal(EVI->getAggregateOperand()), EVI->getIndices());
301 DEBUG(
dbgs() <<
"Found an ExtractValueInst! Simplifying: " << *InstResult
303 }
else if (
auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
305 getVal(IVI->getAggregateOperand()),
306 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
307 DEBUG(
dbgs() <<
"Found an InsertValueInst! Simplifying: " << *InstResult
317 cast<GEPOperator>(
GEP)->isInBounds());
318 DEBUG(
dbgs() <<
"Found a GEP! Simplifying: " << *InstResult
320 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
322 if (!LI->isSimple()) {
323 DEBUG(
dbgs() <<
"Found a Load! Not a simple load, can not evaluate.\n");
330 DEBUG(
dbgs() <<
"Found a constant pointer expression, constant "
331 "folding: " << *Ptr <<
"\n");
333 InstResult = ComputeLoadResult(Ptr);
335 DEBUG(
dbgs() <<
"Failed to compute load result. Can not evaluate load."
340 DEBUG(
dbgs() <<
"Evaluated load: " << *InstResult <<
"\n");
341 }
else if (
AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
342 if (AI->isArrayAllocation()) {
343 DEBUG(
dbgs() <<
"Found an array alloca. Can not evaluate.\n");
346 Type *Ty = AI->getAllocatedType();
347 AllocaTmps.push_back(
350 InstResult = AllocaTmps.back().get();
351 DEBUG(
dbgs() <<
"Found an alloca. Result: " << *InstResult <<
"\n");
352 }
else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
357 DEBUG(
dbgs() <<
"Ignoring debug info.\n");
364 DEBUG(
dbgs() <<
"Found inline asm, can not evaluate.\n");
369 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
370 if (MSI->isVolatile()) {
371 DEBUG(
dbgs() <<
"Can not optimize a volatile memset " <<
378 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
380 DEBUG(
dbgs() <<
"Ignoring no-op memset.\n");
386 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
387 II->getIntrinsicID() == Intrinsic::lifetime_end) {
388 DEBUG(
dbgs() <<
"Ignoring lifetime intrinsic.\n");
393 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
396 if (!II->use_empty()) {
397 DEBUG(
dbgs() <<
"Found unused invariant_start. Can't evaluate.\n");
402 Value *
Ptr = PtrArg->stripPointerCasts();
408 Invariants.insert(GV);
409 DEBUG(
dbgs() <<
"Found a global var that is an invariant: " << *GV
412 DEBUG(
dbgs() <<
"Found a global var, but can not treat it as an "
419 }
else if (II->getIntrinsicID() == Intrinsic::assume) {
420 DEBUG(
dbgs() <<
"Skipping assume intrinsic.\n");
425 DEBUG(
dbgs() <<
"Unknown intrinsic. Can not evaluate.\n");
432 DEBUG(
dbgs() <<
"Can not resolve function pointer.\n");
444 DEBUG(
dbgs() <<
"Constant folded function call. Result: " <<
445 *InstResult <<
"\n");
447 DEBUG(
dbgs() <<
"Can not constant fold function call.\n");
452 DEBUG(
dbgs() <<
"Can not constant fold vararg function call.\n");
458 ValueStack.emplace_back();
460 DEBUG(
dbgs() <<
"Failed to evaluate function.\n");
463 ValueStack.pop_back();
467 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: "
468 << *InstResult <<
"\n\n");
470 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: 0\n\n");
473 }
else if (isa<TerminatorInst>(CurInst)) {
474 DEBUG(
dbgs() <<
"Found a terminator instruction.\n");
476 if (
BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
477 if (BI->isUnconditional()) {
478 NextBB = BI->getSuccessor(0);
482 if (!Cond)
return false;
486 }
else if (
SwitchInst *
SI = dyn_cast<SwitchInst>(CurInst)) {
489 if (!Val)
return false;
490 NextBB =
SI->findCaseValue(Val)->getCaseSuccessor();
491 }
else if (
IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
492 Value *Val =
getVal(IBI->getAddress())->stripPointerCasts();
494 NextBB = BA->getBasicBlock();
497 }
else if (isa<ReturnInst>(CurInst)) {
501 DEBUG(
dbgs() <<
"Can not handle terminator.");
506 DEBUG(
dbgs() <<
"Successfully evaluated block.\n");
510 DEBUG(
dbgs() <<
"Failed to evaluate block due to unhandled instruction."
515 if (!CurInst->use_empty()) {
517 InstResult = FoldedInstResult;
519 setVal(&*CurInst, InstResult);
523 if (
InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
524 NextBB = II->getNormalDest();
525 DEBUG(
dbgs() <<
"Found an invoke instruction. Finished Block.\n\n");
544 CallStack.push_back(F);
550 setVal(&*AI, ActualArgs[ArgNo]);
564 DEBUG(
dbgs() <<
"Trying to evaluate BB: " << *CurBB <<
"\n");
575 CallStack.pop_back();
582 if (!ExecutedBlocks.
insert(NextBB).second)
589 for (CurInst = NextBB->
begin();
Return a value (possibly void), from a function.
void push_back(const T &Elt)
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.
This class represents an incoming formal argument to a Function.
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.
unsigned getNumOperands() const
bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB)
Evaluate all instructions in block BB, returning true if successful, false if we can't evaluate it...
Type * getValueType() const
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
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.
Constant * ConstantFoldCall(ImmutableCallSite CS, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
StringRef getName() const
Return a constant reference to the value's name.
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.
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
Class to represent struct types.
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...
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...
bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'. ...
Windows NT (Windows on ARM)
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
A constant value that is initialized with an expression using other constant values.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
An instruction for storing to memory.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
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)
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
void setVal(Value *V, Constant *C)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSimpleEnoughValueToCommitHelper(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
Return true if the specified constant can be handled by the code generator.
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.
Value * getOperand(unsigned i) const
Class to represent integer types.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static bool isSimpleEnoughValueToCommit(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Iterator for intrusive lists based on ilist_node.
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...
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.
InstrTy * getInstruction() const
Constant * getVal(Value *V)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
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.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static bool isSimpleEnoughPointerToCommit(Constant *C)
Return true if this constant is simple enough for us to understand.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
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 isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
const BasicBlock & front() const
LLVM Value Representation.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
A wrapper class for inspecting calls to intrinsic functions.
an instruction to allocate memory on the stack
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.