Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/Evaluator.cpp
35271 views
//===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Function evaluator for LLVM IR.9//10//===----------------------------------------------------------------------===//1112#include "llvm/Transforms/Utils/Evaluator.h"13#include "llvm/ADT/DenseMap.h"14#include "llvm/ADT/STLExtras.h"15#include "llvm/ADT/SmallPtrSet.h"16#include "llvm/ADT/SmallVector.h"17#include "llvm/Analysis/ConstantFolding.h"18#include "llvm/IR/BasicBlock.h"19#include "llvm/IR/Constant.h"20#include "llvm/IR/Constants.h"21#include "llvm/IR/DataLayout.h"22#include "llvm/IR/DerivedTypes.h"23#include "llvm/IR/Function.h"24#include "llvm/IR/GlobalAlias.h"25#include "llvm/IR/GlobalValue.h"26#include "llvm/IR/GlobalVariable.h"27#include "llvm/IR/InstrTypes.h"28#include "llvm/IR/Instruction.h"29#include "llvm/IR/Instructions.h"30#include "llvm/IR/IntrinsicInst.h"31#include "llvm/IR/Operator.h"32#include "llvm/IR/Type.h"33#include "llvm/IR/User.h"34#include "llvm/IR/Value.h"35#include "llvm/Support/Casting.h"36#include "llvm/Support/Debug.h"37#include "llvm/Support/raw_ostream.h"3839#define DEBUG_TYPE "evaluator"4041using namespace llvm;4243static inline bool44isSimpleEnoughValueToCommit(Constant *C,45SmallPtrSetImpl<Constant *> &SimpleConstants,46const DataLayout &DL);4748/// Return true if the specified constant can be handled by the code generator.49/// We don't want to generate something like:50/// void *X = &X/42;51/// because the code generator doesn't have a relocation that can handle that.52///53/// This function should be called if C was not found (but just got inserted)54/// in SimpleConstants to avoid having to rescan the same constants all the55/// time.56static bool57isSimpleEnoughValueToCommitHelper(Constant *C,58SmallPtrSetImpl<Constant *> &SimpleConstants,59const DataLayout &DL) {60// Simple global addresses are supported, do not allow dllimport or61// thread-local globals.62if (auto *GV = dyn_cast<GlobalValue>(C))63return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();6465// Simple integer, undef, constant aggregate zero, etc are all supported.66if (C->getNumOperands() == 0 || isa<BlockAddress>(C))67return true;6869// Aggregate values are safe if all their elements are.70if (isa<ConstantAggregate>(C)) {71for (Value *Op : C->operands())72if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))73return false;74return true;75}7677// We don't know exactly what relocations are allowed in constant expressions,78// so we allow &global+constantoffset, which is safe and uniformly supported79// across targets.80ConstantExpr *CE = cast<ConstantExpr>(C);81switch (CE->getOpcode()) {82case Instruction::BitCast:83// Bitcast is fine if the casted value is fine.84return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);8586case Instruction::IntToPtr:87case Instruction::PtrToInt:88// int <=> ptr is fine if the int type is the same size as the89// pointer type.90if (DL.getTypeSizeInBits(CE->getType()) !=91DL.getTypeSizeInBits(CE->getOperand(0)->getType()))92return false;93return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);9495// GEP is fine if it is simple + constant offset.96case Instruction::GetElementPtr:97for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)98if (!isa<ConstantInt>(CE->getOperand(i)))99return false;100return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);101102case Instruction::Add:103// We allow simple+cst.104if (!isa<ConstantInt>(CE->getOperand(1)))105return false;106return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);107}108return false;109}110111static inline bool112isSimpleEnoughValueToCommit(Constant *C,113SmallPtrSetImpl<Constant *> &SimpleConstants,114const DataLayout &DL) {115// If we already checked this constant, we win.116if (!SimpleConstants.insert(C).second)117return true;118// Check the constant.119return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);120}121122void Evaluator::MutableValue::clear() {123if (auto *Agg = dyn_cast_if_present<MutableAggregate *>(Val))124delete Agg;125Val = nullptr;126}127128Constant *Evaluator::MutableValue::read(Type *Ty, APInt Offset,129const DataLayout &DL) const {130TypeSize TySize = DL.getTypeStoreSize(Ty);131const MutableValue *V = this;132while (const auto *Agg = dyn_cast_if_present<MutableAggregate *>(V->Val)) {133Type *AggTy = Agg->Ty;134std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);135if (!Index || Index->uge(Agg->Elements.size()) ||136!TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))137return nullptr;138139V = &Agg->Elements[Index->getZExtValue()];140}141142return ConstantFoldLoadFromConst(cast<Constant *>(V->Val), Ty, Offset, DL);143}144145bool Evaluator::MutableValue::makeMutable() {146Constant *C = cast<Constant *>(Val);147Type *Ty = C->getType();148unsigned NumElements;149if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {150NumElements = VT->getNumElements();151} else if (auto *AT = dyn_cast<ArrayType>(Ty))152NumElements = AT->getNumElements();153else if (auto *ST = dyn_cast<StructType>(Ty))154NumElements = ST->getNumElements();155else156return false;157158MutableAggregate *MA = new MutableAggregate(Ty);159MA->Elements.reserve(NumElements);160for (unsigned I = 0; I < NumElements; ++I)161MA->Elements.push_back(C->getAggregateElement(I));162Val = MA;163return true;164}165166bool Evaluator::MutableValue::write(Constant *V, APInt Offset,167const DataLayout &DL) {168Type *Ty = V->getType();169TypeSize TySize = DL.getTypeStoreSize(Ty);170MutableValue *MV = this;171while (Offset != 0 ||172!CastInst::isBitOrNoopPointerCastable(Ty, MV->getType(), DL)) {173if (isa<Constant *>(MV->Val) && !MV->makeMutable())174return false;175176MutableAggregate *Agg = cast<MutableAggregate *>(MV->Val);177Type *AggTy = Agg->Ty;178std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);179if (!Index || Index->uge(Agg->Elements.size()) ||180!TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))181return false;182183MV = &Agg->Elements[Index->getZExtValue()];184}185186Type *MVType = MV->getType();187MV->clear();188if (Ty->isIntegerTy() && MVType->isPointerTy())189MV->Val = ConstantExpr::getIntToPtr(V, MVType);190else if (Ty->isPointerTy() && MVType->isIntegerTy())191MV->Val = ConstantExpr::getPtrToInt(V, MVType);192else if (Ty != MVType)193MV->Val = ConstantExpr::getBitCast(V, MVType);194else195MV->Val = V;196return true;197}198199Constant *Evaluator::MutableAggregate::toConstant() const {200SmallVector<Constant *, 32> Consts;201for (const MutableValue &MV : Elements)202Consts.push_back(MV.toConstant());203204if (auto *ST = dyn_cast<StructType>(Ty))205return ConstantStruct::get(ST, Consts);206if (auto *AT = dyn_cast<ArrayType>(Ty))207return ConstantArray::get(AT, Consts);208assert(isa<FixedVectorType>(Ty) && "Must be vector");209return ConstantVector::get(Consts);210}211212/// Return the value that would be computed by a load from P after the stores213/// reflected by 'memory' have been performed. If we can't decide, return null.214Constant *Evaluator::ComputeLoadResult(Constant *P, Type *Ty) {215APInt Offset(DL.getIndexTypeSizeInBits(P->getType()), 0);216P = cast<Constant>(P->stripAndAccumulateConstantOffsets(217DL, Offset, /* AllowNonInbounds */ true));218Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(P->getType()));219if (auto *GV = dyn_cast<GlobalVariable>(P))220return ComputeLoadResult(GV, Ty, Offset);221return nullptr;222}223224Constant *Evaluator::ComputeLoadResult(GlobalVariable *GV, Type *Ty,225const APInt &Offset) {226auto It = MutatedMemory.find(GV);227if (It != MutatedMemory.end())228return It->second.read(Ty, Offset, DL);229230if (!GV->hasDefinitiveInitializer())231return nullptr;232return ConstantFoldLoadFromConst(GV->getInitializer(), Ty, Offset, DL);233}234235static Function *getFunction(Constant *C) {236if (auto *Fn = dyn_cast<Function>(C))237return Fn;238239if (auto *Alias = dyn_cast<GlobalAlias>(C))240if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))241return Fn;242return nullptr;243}244245Function *246Evaluator::getCalleeWithFormalArgs(CallBase &CB,247SmallVectorImpl<Constant *> &Formals) {248auto *V = CB.getCalledOperand()->stripPointerCasts();249if (auto *Fn = getFunction(getVal(V)))250return getFormalParams(CB, Fn, Formals) ? Fn : nullptr;251return nullptr;252}253254bool Evaluator::getFormalParams(CallBase &CB, Function *F,255SmallVectorImpl<Constant *> &Formals) {256if (!F)257return false;258259auto *FTy = F->getFunctionType();260if (FTy->getNumParams() > CB.arg_size()) {261LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");262return false;263}264265auto ArgI = CB.arg_begin();266for (Type *PTy : FTy->params()) {267auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), PTy, DL);268if (!ArgC) {269LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");270return false;271}272Formals.push_back(ArgC);273++ArgI;274}275return true;276}277278/// If call expression contains bitcast then we may need to cast279/// evaluated return value to a type of the call expression.280Constant *Evaluator::castCallResultIfNeeded(Type *ReturnType, Constant *RV) {281if (!RV || RV->getType() == ReturnType)282return RV;283284RV = ConstantFoldLoadThroughBitcast(RV, ReturnType, DL);285if (!RV)286LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");287return RV;288}289290/// Evaluate all instructions in block BB, returning true if successful, false291/// if we can't evaluate it. NewBB returns the next BB that control flows into,292/// or null upon return. StrippedPointerCastsForAliasAnalysis is set to true if293/// we looked through pointer casts to evaluate something.294bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,295bool &StrippedPointerCastsForAliasAnalysis) {296// This is the main evaluation loop.297while (true) {298Constant *InstResult = nullptr;299300LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");301302if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {303if (SI->isVolatile()) {304LLVM_DEBUG(dbgs() << "Store is volatile! Can not evaluate.\n");305return false; // no volatile accesses.306}307Constant *Ptr = getVal(SI->getOperand(1));308Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);309if (Ptr != FoldedPtr) {310LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);311Ptr = FoldedPtr;312LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");313}314315APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);316Ptr = cast<Constant>(Ptr->stripAndAccumulateConstantOffsets(317DL, Offset, /* AllowNonInbounds */ true));318Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(Ptr->getType()));319auto *GV = dyn_cast<GlobalVariable>(Ptr);320if (!GV || !GV->hasUniqueInitializer()) {321LLVM_DEBUG(dbgs() << "Store is not to global with unique initializer: "322<< *Ptr << "\n");323return false;324}325326// If this might be too difficult for the backend to handle (e.g. the addr327// of one global variable divided by another) then we can't commit it.328Constant *Val = getVal(SI->getOperand(0));329if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {330LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "331<< *Val << "\n");332return false;333}334335auto Res = MutatedMemory.try_emplace(GV, GV->getInitializer());336if (!Res.first->second.write(Val, Offset, DL))337return false;338} else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {339if (LI->isVolatile()) {340LLVM_DEBUG(341dbgs() << "Found a Load! Volatile load, can not evaluate.\n");342return false; // no volatile accesses.343}344345Constant *Ptr = getVal(LI->getOperand(0));346Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);347if (Ptr != FoldedPtr) {348Ptr = FoldedPtr;349LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "350"folding: "351<< *Ptr << "\n");352}353InstResult = ComputeLoadResult(Ptr, LI->getType());354if (!InstResult) {355LLVM_DEBUG(356dbgs() << "Failed to compute load result. Can not evaluate load."357"\n");358return false; // Could not evaluate load.359}360361LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");362} else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {363if (AI->isArrayAllocation()) {364LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");365return false; // Cannot handle array allocs.366}367Type *Ty = AI->getAllocatedType();368AllocaTmps.push_back(std::make_unique<GlobalVariable>(369Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),370AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,371AI->getType()->getPointerAddressSpace()));372InstResult = AllocaTmps.back().get();373LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");374} else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {375CallBase &CB = *cast<CallBase>(&*CurInst);376377// Debug info can safely be ignored here.378if (isa<DbgInfoIntrinsic>(CB)) {379LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");380++CurInst;381continue;382}383384// Cannot handle inline asm.385if (CB.isInlineAsm()) {386LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");387return false;388}389390if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CB)) {391if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {392if (MSI->isVolatile()) {393LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "394<< "intrinsic.\n");395return false;396}397398auto *LenC = dyn_cast<ConstantInt>(getVal(MSI->getLength()));399if (!LenC) {400LLVM_DEBUG(dbgs() << "Memset with unknown length.\n");401return false;402}403404Constant *Ptr = getVal(MSI->getDest());405APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);406Ptr = cast<Constant>(Ptr->stripAndAccumulateConstantOffsets(407DL, Offset, /* AllowNonInbounds */ true));408auto *GV = dyn_cast<GlobalVariable>(Ptr);409if (!GV) {410LLVM_DEBUG(dbgs() << "Memset with unknown base.\n");411return false;412}413414Constant *Val = getVal(MSI->getValue());415// Avoid the byte-per-byte scan if we're memseting a zeroinitializer416// to zero.417if (!Val->isNullValue() || MutatedMemory.contains(GV) ||418!GV->hasDefinitiveInitializer() ||419!GV->getInitializer()->isNullValue()) {420APInt Len = LenC->getValue();421if (Len.ugt(64 * 1024)) {422LLVM_DEBUG(dbgs() << "Not evaluating large memset of size "423<< Len << "\n");424return false;425}426427while (Len != 0) {428Constant *DestVal = ComputeLoadResult(GV, Val->getType(), Offset);429if (DestVal != Val) {430LLVM_DEBUG(dbgs() << "Memset is not a no-op at offset "431<< Offset << " of " << *GV << ".\n");432return false;433}434++Offset;435--Len;436}437}438439LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");440++CurInst;441continue;442}443444if (II->isLifetimeStartOrEnd()) {445LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");446++CurInst;447continue;448}449450if (II->getIntrinsicID() == Intrinsic::invariant_start) {451// We don't insert an entry into Values, as it doesn't have a452// meaningful return value.453if (!II->use_empty()) {454LLVM_DEBUG(dbgs()455<< "Found unused invariant_start. Can't evaluate.\n");456return false;457}458ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));459Value *PtrArg = getVal(II->getArgOperand(1));460Value *Ptr = PtrArg->stripPointerCasts();461if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {462Type *ElemTy = GV->getValueType();463if (!Size->isMinusOne() &&464Size->getValue().getLimitedValue() >=465DL.getTypeStoreSize(ElemTy)) {466Invariants.insert(GV);467LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "468<< *GV << "\n");469} else {470LLVM_DEBUG(dbgs()471<< "Found a global var, but can not treat it as an "472"invariant.\n");473}474}475// Continue even if we do nothing.476++CurInst;477continue;478} else if (II->getIntrinsicID() == Intrinsic::assume) {479LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");480++CurInst;481continue;482} else if (II->getIntrinsicID() == Intrinsic::sideeffect) {483LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");484++CurInst;485continue;486} else if (II->getIntrinsicID() == Intrinsic::pseudoprobe) {487LLVM_DEBUG(dbgs() << "Skipping pseudoprobe intrinsic.\n");488++CurInst;489continue;490} else {491Value *Stripped = CurInst->stripPointerCastsForAliasAnalysis();492// Only attempt to getVal() if we've actually managed to strip493// anything away, or else we'll call getVal() on the current494// instruction.495if (Stripped != &*CurInst) {496InstResult = getVal(Stripped);497}498if (InstResult) {499LLVM_DEBUG(dbgs()500<< "Stripped pointer casts for alias analysis for "501"intrinsic call.\n");502StrippedPointerCastsForAliasAnalysis = true;503InstResult = ConstantExpr::getBitCast(InstResult, II->getType());504} else {505LLVM_DEBUG(dbgs() << "Unknown intrinsic. Cannot evaluate.\n");506return false;507}508}509}510511if (!InstResult) {512// Resolve function pointers.513SmallVector<Constant *, 8> Formals;514Function *Callee = getCalleeWithFormalArgs(CB, Formals);515if (!Callee || Callee->isInterposable()) {516LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");517return false; // Cannot resolve.518}519520if (Callee->isDeclaration()) {521// If this is a function we can constant fold, do it.522if (Constant *C = ConstantFoldCall(&CB, Callee, Formals, TLI)) {523InstResult = castCallResultIfNeeded(CB.getType(), C);524if (!InstResult)525return false;526LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "527<< *InstResult << "\n");528} else {529LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");530return false;531}532} else {533if (Callee->getFunctionType()->isVarArg()) {534LLVM_DEBUG(dbgs()535<< "Can not constant fold vararg function call.\n");536return false;537}538539Constant *RetVal = nullptr;540// Execute the call, if successful, use the return value.541ValueStack.emplace_back();542if (!EvaluateFunction(Callee, RetVal, Formals)) {543LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");544return false;545}546ValueStack.pop_back();547InstResult = castCallResultIfNeeded(CB.getType(), RetVal);548if (RetVal && !InstResult)549return false;550551if (InstResult) {552LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "553<< *InstResult << "\n\n");554} else {555LLVM_DEBUG(dbgs()556<< "Successfully evaluated function. Result: 0\n\n");557}558}559}560} else if (CurInst->isTerminator()) {561LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");562563if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {564if (BI->isUnconditional()) {565NextBB = BI->getSuccessor(0);566} else {567ConstantInt *Cond =568dyn_cast<ConstantInt>(getVal(BI->getCondition()));569if (!Cond) return false; // Cannot determine.570571NextBB = BI->getSuccessor(!Cond->getZExtValue());572}573} else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {574ConstantInt *Val =575dyn_cast<ConstantInt>(getVal(SI->getCondition()));576if (!Val) return false; // Cannot determine.577NextBB = SI->findCaseValue(Val)->getCaseSuccessor();578} else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {579Value *Val = getVal(IBI->getAddress())->stripPointerCasts();580if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))581NextBB = BA->getBasicBlock();582else583return false; // Cannot determine.584} else if (isa<ReturnInst>(CurInst)) {585NextBB = nullptr;586} else {587// invoke, unwind, resume, unreachable.588LLVM_DEBUG(dbgs() << "Can not handle terminator.");589return false; // Cannot handle this terminator.590}591592// We succeeded at evaluating this block!593LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");594return true;595} else {596SmallVector<Constant *> Ops;597for (Value *Op : CurInst->operands())598Ops.push_back(getVal(Op));599InstResult = ConstantFoldInstOperands(&*CurInst, Ops, DL, TLI);600if (!InstResult) {601LLVM_DEBUG(dbgs() << "Cannot fold instruction: " << *CurInst << "\n");602return false;603}604LLVM_DEBUG(dbgs() << "Folded instruction " << *CurInst << " to "605<< *InstResult << "\n");606}607608if (!CurInst->use_empty()) {609InstResult = ConstantFoldConstant(InstResult, DL, TLI);610setVal(&*CurInst, InstResult);611}612613// If we just processed an invoke, we finished evaluating the block.614if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {615NextBB = II->getNormalDest();616LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");617return true;618}619620// Advance program counter.621++CurInst;622}623}624625/// Evaluate a call to function F, returning true if successful, false if we626/// can't evaluate it. ActualArgs contains the formal arguments for the627/// function.628bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,629const SmallVectorImpl<Constant*> &ActualArgs) {630assert(ActualArgs.size() == F->arg_size() && "wrong number of arguments");631632// Check to see if this function is already executing (recursion). If so,633// bail out. TODO: we might want to accept limited recursion.634if (is_contained(CallStack, F))635return false;636637CallStack.push_back(F);638639// Initialize arguments to the incoming values specified.640for (const auto &[ArgNo, Arg] : llvm::enumerate(F->args()))641setVal(&Arg, ActualArgs[ArgNo]);642643// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,644// we can only evaluate any one basic block at most once. This set keeps645// track of what we have executed so we can detect recursive cases etc.646SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;647648// CurBB - The current basic block we're evaluating.649BasicBlock *CurBB = &F->front();650651BasicBlock::iterator CurInst = CurBB->begin();652653while (true) {654BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.655LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");656657bool StrippedPointerCastsForAliasAnalysis = false;658659if (!EvaluateBlock(CurInst, NextBB, StrippedPointerCastsForAliasAnalysis))660return false;661662if (!NextBB) {663// Successfully running until there's no next block means that we found664// the return. Fill it the return value and pop the call stack.665ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());666if (RI->getNumOperands()) {667// The Evaluator can look through pointer casts as long as alias668// analysis holds because it's just a simple interpreter and doesn't669// skip memory accesses due to invariant group metadata, but we can't670// let users of Evaluator use a value that's been gleaned looking671// through stripping pointer casts.672if (StrippedPointerCastsForAliasAnalysis &&673!RI->getReturnValue()->getType()->isVoidTy()) {674return false;675}676RetVal = getVal(RI->getOperand(0));677}678CallStack.pop_back();679return true;680}681682// Okay, we succeeded in evaluating this control flow. See if we have683// executed the new block before. If so, we have a looping function,684// which we cannot evaluate in reasonable time.685if (!ExecutedBlocks.insert(NextBB).second)686return false; // looped!687688// Okay, we have never been in this block before. Check to see if there689// are any PHI nodes. If so, evaluate them with information about where690// we came from.691PHINode *PN = nullptr;692for (CurInst = NextBB->begin();693(PN = dyn_cast<PHINode>(CurInst)); ++CurInst)694setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));695696// Advance to the next block.697CurBB = NextBB;698}699}700701702