Evaluator.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Function evaluator for LLVM IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/Evaluator.h"
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/IR/BasicBlock.h"
  16. #include "llvm/IR/CallSite.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/IR/DerivedTypes.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/IR/GlobalVariable.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Operator.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #define DEBUG_TYPE "evaluator"
  28. using namespace llvm;
  29. static inline bool
  30. isSimpleEnoughValueToCommit(Constant *C,
  31. SmallPtrSetImpl<Constant *> &SimpleConstants,
  32. const DataLayout &DL);
  33. /// Return true if the specified constant can be handled by the code generator.
  34. /// We don't want to generate something like:
  35. /// void *X = &X/42;
  36. /// because the code generator doesn't have a relocation that can handle that.
  37. ///
  38. /// This function should be called if C was not found (but just got inserted)
  39. /// in SimpleConstants to avoid having to rescan the same constants all the
  40. /// time.
  41. static bool
  42. isSimpleEnoughValueToCommitHelper(Constant *C,
  43. SmallPtrSetImpl<Constant *> &SimpleConstants,
  44. const DataLayout &DL) {
  45. // Simple global addresses are supported, do not allow dllimport or
  46. // thread-local globals.
  47. if (auto *GV = dyn_cast<GlobalValue>(C))
  48. return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
  49. // Simple integer, undef, constant aggregate zero, etc are all supported.
  50. if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
  51. return true;
  52. // Aggregate values are safe if all their elements are.
  53. if (isa<ConstantAggregate>(C)) {
  54. for (Value *Op : C->operands())
  55. if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
  56. return false;
  57. return true;
  58. }
  59. // We don't know exactly what relocations are allowed in constant expressions,
  60. // so we allow &global+constantoffset, which is safe and uniformly supported
  61. // across targets.
  62. ConstantExpr *CE = cast<ConstantExpr>(C);
  63. switch (CE->getOpcode()) {
  64. case Instruction::BitCast:
  65. // Bitcast is fine if the casted value is fine.
  66. return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
  67. case Instruction::IntToPtr:
  68. case Instruction::PtrToInt:
  69. // int <=> ptr is fine if the int type is the same size as the
  70. // pointer type.
  71. if (DL.getTypeSizeInBits(CE->getType()) !=
  72. DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
  73. return false;
  74. return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
  75. // GEP is fine if it is simple + constant offset.
  76. case Instruction::GetElementPtr:
  77. for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
  78. if (!isa<ConstantInt>(CE->getOperand(i)))
  79. return false;
  80. return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
  81. case Instruction::Add:
  82. // We allow simple+cst.
  83. if (!isa<ConstantInt>(CE->getOperand(1)))
  84. return false;
  85. return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
  86. }
  87. return false;
  88. }
  89. static inline bool
  90. isSimpleEnoughValueToCommit(Constant *C,
  91. SmallPtrSetImpl<Constant *> &SimpleConstants,
  92. const DataLayout &DL) {
  93. // If we already checked this constant, we win.
  94. if (!SimpleConstants.insert(C).second)
  95. return true;
  96. // Check the constant.
  97. return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
  98. }
  99. /// Return true if this constant is simple enough for us to understand. In
  100. /// particular, if it is a cast to anything other than from one pointer type to
  101. /// another pointer type, we punt. We basically just support direct accesses to
  102. /// globals and GEP's of globals. This should be kept up to date with
  103. /// CommitValueTo.
  104. static bool isSimpleEnoughPointerToCommit(Constant *C) {
  105. // Conservatively, avoid aggregate types. This is because we don't
  106. // want to worry about them partially overlapping other stores.
  107. if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
  108. return false;
  109. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
  110. // Do not allow weak/*_odr/linkonce linkage or external globals.
  111. return GV->hasUniqueInitializer();
  112. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  113. // Handle a constantexpr gep.
  114. if (CE->getOpcode() == Instruction::GetElementPtr &&
  115. isa<GlobalVariable>(CE->getOperand(0)) &&
  116. cast<GEPOperator>(CE)->isInBounds()) {
  117. GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
  118. // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
  119. // external globals.
  120. if (!GV->hasUniqueInitializer())
  121. return false;
  122. // The first index must be zero.
  123. ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
  124. if (!CI || !CI->isZero()) return false;
  125. // The remaining indices must be compile-time known integers within the
  126. // notional bounds of the corresponding static array types.
  127. if (!CE->isGEPWithNoNotionalOverIndexing())
  128. return false;
  129. return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
  130. // A constantexpr bitcast from a pointer to another pointer is a no-op,
  131. // and we know how to evaluate it by moving the bitcast from the pointer
  132. // operand to the value operand.
  133. } else if (CE->getOpcode() == Instruction::BitCast &&
  134. isa<GlobalVariable>(CE->getOperand(0))) {
  135. // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
  136. // external globals.
  137. return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
  138. }
  139. }
  140. return false;
  141. }
  142. /// Return the value that would be computed by a load from P after the stores
  143. /// reflected by 'memory' have been performed. If we can't decide, return null.
  144. Constant *Evaluator::ComputeLoadResult(Constant *P) {
  145. // If this memory location has been recently stored, use the stored value: it
  146. // is the most up-to-date.
  147. DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
  148. if (I != MutatedMemory.end()) return I->second;
  149. // Access it.
  150. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
  151. if (GV->hasDefinitiveInitializer())
  152. return GV->getInitializer();
  153. return nullptr;
  154. }
  155. // Handle a constantexpr getelementptr.
  156. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
  157. if (CE->getOpcode() == Instruction::GetElementPtr &&
  158. isa<GlobalVariable>(CE->getOperand(0))) {
  159. GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
  160. if (GV->hasDefinitiveInitializer())
  161. return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
  162. }
  163. return nullptr; // don't know how to evaluate.
  164. }
  165. /// Evaluate all instructions in block BB, returning true if successful, false
  166. /// if we can't evaluate it. NewBB returns the next BB that control flows into,
  167. /// or null upon return.
  168. bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
  169. BasicBlock *&NextBB) {
  170. // This is the main evaluation loop.
  171. while (1) {
  172. Constant *InstResult = nullptr;
  173. DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
  174. if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
  175. if (!SI->isSimple()) {
  176. DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
  177. return false; // no volatile/atomic accesses.
  178. }
  179. Constant *Ptr = getVal(SI->getOperand(1));
  180. if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
  181. DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
  182. Ptr = FoldedPtr;
  183. DEBUG(dbgs() << "; To: " << *Ptr << "\n");
  184. }
  185. if (!isSimpleEnoughPointerToCommit(Ptr)) {
  186. // If this is too complex for us to commit, reject it.
  187. DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
  188. return false;
  189. }
  190. Constant *Val = getVal(SI->getOperand(0));
  191. // If this might be too difficult for the backend to handle (e.g. the addr
  192. // of one global variable divided by another) then we can't commit it.
  193. if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
  194. DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
  195. << "\n");
  196. return false;
  197. }
  198. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  199. if (CE->getOpcode() == Instruction::BitCast) {
  200. DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
  201. // If we're evaluating a store through a bitcast, then we need
  202. // to pull the bitcast off the pointer type and push it onto the
  203. // stored value.
  204. Ptr = CE->getOperand(0);
  205. Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
  206. // In order to push the bitcast onto the stored value, a bitcast
  207. // from NewTy to Val's type must be legal. If it's not, we can try
  208. // introspecting NewTy to find a legal conversion.
  209. while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
  210. // If NewTy is a struct, we can convert the pointer to the struct
  211. // into a pointer to its first member.
  212. // FIXME: This could be extended to support arrays as well.
  213. if (StructType *STy = dyn_cast<StructType>(NewTy)) {
  214. NewTy = STy->getTypeAtIndex(0U);
  215. IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
  216. Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
  217. Constant * const IdxList[] = {IdxZero, IdxZero};
  218. Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
  219. if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
  220. Ptr = FoldedPtr;
  221. // If we can't improve the situation by introspecting NewTy,
  222. // we have to give up.
  223. } else {
  224. DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
  225. "evaluate.\n");
  226. return false;
  227. }
  228. }
  229. // If we found compatible types, go ahead and push the bitcast
  230. // onto the stored value.
  231. Val = ConstantExpr::getBitCast(Val, NewTy);
  232. DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
  233. }
  234. }
  235. MutatedMemory[Ptr] = Val;
  236. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
  237. InstResult = ConstantExpr::get(BO->getOpcode(),
  238. getVal(BO->getOperand(0)),
  239. getVal(BO->getOperand(1)));
  240. DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
  241. << "\n");
  242. } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
  243. InstResult = ConstantExpr::getCompare(CI->getPredicate(),
  244. getVal(CI->getOperand(0)),
  245. getVal(CI->getOperand(1)));
  246. DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
  247. << "\n");
  248. } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
  249. InstResult = ConstantExpr::getCast(CI->getOpcode(),
  250. getVal(CI->getOperand(0)),
  251. CI->getType());
  252. DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
  253. << "\n");
  254. } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
  255. InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
  256. getVal(SI->getOperand(1)),
  257. getVal(SI->getOperand(2)));
  258. DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
  259. << "\n");
  260. } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
  261. InstResult = ConstantExpr::getExtractValue(
  262. getVal(EVI->getAggregateOperand()), EVI->getIndices());
  263. DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
  264. << "\n");
  265. } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
  266. InstResult = ConstantExpr::getInsertValue(
  267. getVal(IVI->getAggregateOperand()),
  268. getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
  269. DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
  270. << "\n");
  271. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
  272. Constant *P = getVal(GEP->getOperand(0));
  273. SmallVector<Constant*, 8> GEPOps;
  274. for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
  275. i != e; ++i)
  276. GEPOps.push_back(getVal(*i));
  277. InstResult =
  278. ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
  279. cast<GEPOperator>(GEP)->isInBounds());
  280. DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
  281. << "\n");
  282. } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
  283. if (!LI->isSimple()) {
  284. DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
  285. return false; // no volatile/atomic accesses.
  286. }
  287. Constant *Ptr = getVal(LI->getOperand(0));
  288. if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
  289. Ptr = FoldedPtr;
  290. DEBUG(dbgs() << "Found a constant pointer expression, constant "
  291. "folding: " << *Ptr << "\n");
  292. }
  293. InstResult = ComputeLoadResult(Ptr);
  294. if (!InstResult) {
  295. DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
  296. "\n");
  297. return false; // Could not evaluate load.
  298. }
  299. DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
  300. } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
  301. if (AI->isArrayAllocation()) {
  302. DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
  303. return false; // Cannot handle array allocs.
  304. }
  305. Type *Ty = AI->getAllocatedType();
  306. AllocaTmps.push_back(
  307. make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
  308. UndefValue::get(Ty), AI->getName()));
  309. InstResult = AllocaTmps.back().get();
  310. DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
  311. } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
  312. CallSite CS(&*CurInst);
  313. // Debug info can safely be ignored here.
  314. if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
  315. DEBUG(dbgs() << "Ignoring debug info.\n");
  316. ++CurInst;
  317. continue;
  318. }
  319. // Cannot handle inline asm.
  320. if (isa<InlineAsm>(CS.getCalledValue())) {
  321. DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
  322. return false;
  323. }
  324. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
  325. if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
  326. if (MSI->isVolatile()) {
  327. DEBUG(dbgs() << "Can not optimize a volatile memset " <<
  328. "intrinsic.\n");
  329. return false;
  330. }
  331. Constant *Ptr = getVal(MSI->getDest());
  332. Constant *Val = getVal(MSI->getValue());
  333. Constant *DestVal = ComputeLoadResult(getVal(Ptr));
  334. if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
  335. // This memset is a no-op.
  336. DEBUG(dbgs() << "Ignoring no-op memset.\n");
  337. ++CurInst;
  338. continue;
  339. }
  340. }
  341. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  342. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  343. DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
  344. ++CurInst;
  345. continue;
  346. }
  347. if (II->getIntrinsicID() == Intrinsic::invariant_start) {
  348. // We don't insert an entry into Values, as it doesn't have a
  349. // meaningful return value.
  350. if (!II->use_empty()) {
  351. DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
  352. return false;
  353. }
  354. ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
  355. Value *PtrArg = getVal(II->getArgOperand(1));
  356. Value *Ptr = PtrArg->stripPointerCasts();
  357. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
  358. Type *ElemTy = GV->getValueType();
  359. if (!Size->isAllOnesValue() &&
  360. Size->getValue().getLimitedValue() >=
  361. DL.getTypeStoreSize(ElemTy)) {
  362. Invariants.insert(GV);
  363. DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
  364. << "\n");
  365. } else {
  366. DEBUG(dbgs() << "Found a global var, but can not treat it as an "
  367. "invariant.\n");
  368. }
  369. }
  370. // Continue even if we do nothing.
  371. ++CurInst;
  372. continue;
  373. } else if (II->getIntrinsicID() == Intrinsic::assume) {
  374. DEBUG(dbgs() << "Skipping assume intrinsic.\n");
  375. ++CurInst;
  376. continue;
  377. }
  378. DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
  379. return false;
  380. }
  381. // Resolve function pointers.
  382. Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
  383. if (!Callee || Callee->isInterposable()) {
  384. DEBUG(dbgs() << "Can not resolve function pointer.\n");
  385. return false; // Cannot resolve.
  386. }
  387. SmallVector<Constant*, 8> Formals;
  388. for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
  389. Formals.push_back(getVal(*i));
  390. if (Callee->isDeclaration()) {
  391. // If this is a function we can constant fold, do it.
  392. if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
  393. InstResult = C;
  394. DEBUG(dbgs() << "Constant folded function call. Result: " <<
  395. *InstResult << "\n");
  396. } else {
  397. DEBUG(dbgs() << "Can not constant fold function call.\n");
  398. return false;
  399. }
  400. } else {
  401. if (Callee->getFunctionType()->isVarArg()) {
  402. DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
  403. return false;
  404. }
  405. Constant *RetVal = nullptr;
  406. // Execute the call, if successful, use the return value.
  407. ValueStack.emplace_back();
  408. if (!EvaluateFunction(Callee, RetVal, Formals)) {
  409. DEBUG(dbgs() << "Failed to evaluate function.\n");
  410. return false;
  411. }
  412. ValueStack.pop_back();
  413. InstResult = RetVal;
  414. if (InstResult) {
  415. DEBUG(dbgs() << "Successfully evaluated function. Result: "
  416. << *InstResult << "\n\n");
  417. } else {
  418. DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
  419. }
  420. }
  421. } else if (isa<TerminatorInst>(CurInst)) {
  422. DEBUG(dbgs() << "Found a terminator instruction.\n");
  423. if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
  424. if (BI->isUnconditional()) {
  425. NextBB = BI->getSuccessor(0);
  426. } else {
  427. ConstantInt *Cond =
  428. dyn_cast<ConstantInt>(getVal(BI->getCondition()));
  429. if (!Cond) return false; // Cannot determine.
  430. NextBB = BI->getSuccessor(!Cond->getZExtValue());
  431. }
  432. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
  433. ConstantInt *Val =
  434. dyn_cast<ConstantInt>(getVal(SI->getCondition()));
  435. if (!Val) return false; // Cannot determine.
  436. NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
  437. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
  438. Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
  439. if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
  440. NextBB = BA->getBasicBlock();
  441. else
  442. return false; // Cannot determine.
  443. } else if (isa<ReturnInst>(CurInst)) {
  444. NextBB = nullptr;
  445. } else {
  446. // invoke, unwind, resume, unreachable.
  447. DEBUG(dbgs() << "Can not handle terminator.");
  448. return false; // Cannot handle this terminator.
  449. }
  450. // We succeeded at evaluating this block!
  451. DEBUG(dbgs() << "Successfully evaluated block.\n");
  452. return true;
  453. } else {
  454. // Did not know how to evaluate this!
  455. DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
  456. "\n");
  457. return false;
  458. }
  459. if (!CurInst->use_empty()) {
  460. if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
  461. InstResult = FoldedInstResult;
  462. setVal(&*CurInst, InstResult);
  463. }
  464. // If we just processed an invoke, we finished evaluating the block.
  465. if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
  466. NextBB = II->getNormalDest();
  467. DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
  468. return true;
  469. }
  470. // Advance program counter.
  471. ++CurInst;
  472. }
  473. }
  474. /// Evaluate a call to function F, returning true if successful, false if we
  475. /// can't evaluate it. ActualArgs contains the formal arguments for the
  476. /// function.
  477. bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
  478. const SmallVectorImpl<Constant*> &ActualArgs) {
  479. // Check to see if this function is already executing (recursion). If so,
  480. // bail out. TODO: we might want to accept limited recursion.
  481. if (is_contained(CallStack, F))
  482. return false;
  483. CallStack.push_back(F);
  484. // Initialize arguments to the incoming values specified.
  485. unsigned ArgNo = 0;
  486. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
  487. ++AI, ++ArgNo)
  488. setVal(&*AI, ActualArgs[ArgNo]);
  489. // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
  490. // we can only evaluate any one basic block at most once. This set keeps
  491. // track of what we have executed so we can detect recursive cases etc.
  492. SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
  493. // CurBB - The current basic block we're evaluating.
  494. BasicBlock *CurBB = &F->front();
  495. BasicBlock::iterator CurInst = CurBB->begin();
  496. while (1) {
  497. BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
  498. DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
  499. if (!EvaluateBlock(CurInst, NextBB))
  500. return false;
  501. if (!NextBB) {
  502. // Successfully running until there's no next block means that we found
  503. // the return. Fill it the return value and pop the call stack.
  504. ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
  505. if (RI->getNumOperands())
  506. RetVal = getVal(RI->getOperand(0));
  507. CallStack.pop_back();
  508. return true;
  509. }
  510. // Okay, we succeeded in evaluating this control flow. See if we have
  511. // executed the new block before. If so, we have a looping function,
  512. // which we cannot evaluate in reasonable time.
  513. if (!ExecutedBlocks.insert(NextBB).second)
  514. return false; // looped!
  515. // Okay, we have never been in this block before. Check to see if there
  516. // are any PHI nodes. If so, evaluate them with information about where
  517. // we came from.
  518. PHINode *PN = nullptr;
  519. for (CurInst = NextBB->begin();
  520. (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
  521. setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
  522. // Advance to the next block.
  523. CurBB = NextBB;
  524. }
  525. }