Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / Transforms / Utils / Evaluator.cpp
blobfb8cb3ddea66aaf0e770d2a8185c4a5692225042
1 //===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Function evaluator for LLVM IR.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Utils/Evaluator.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/InstrTypes.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <iterator>
43 #define DEBUG_TYPE "evaluator"
45 using namespace llvm;
47 static inline bool
48 isSimpleEnoughValueToCommit(Constant *C,
49 SmallPtrSetImpl<Constant *> &SimpleConstants,
50 const DataLayout &DL);
52 /// Return true if the specified constant can be handled by the code generator.
53 /// We don't want to generate something like:
54 /// void *X = &X/42;
55 /// because the code generator doesn't have a relocation that can handle that.
56 ///
57 /// This function should be called if C was not found (but just got inserted)
58 /// in SimpleConstants to avoid having to rescan the same constants all the
59 /// time.
60 static bool
61 isSimpleEnoughValueToCommitHelper(Constant *C,
62 SmallPtrSetImpl<Constant *> &SimpleConstants,
63 const DataLayout &DL) {
64 // Simple global addresses are supported, do not allow dllimport or
65 // thread-local globals.
66 if (auto *GV = dyn_cast<GlobalValue>(C))
67 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
69 // Simple integer, undef, constant aggregate zero, etc are all supported.
70 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
71 return true;
73 // Aggregate values are safe if all their elements are.
74 if (isa<ConstantAggregate>(C)) {
75 for (Value *Op : C->operands())
76 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
77 return false;
78 return true;
81 // We don't know exactly what relocations are allowed in constant expressions,
82 // so we allow &global+constantoffset, which is safe and uniformly supported
83 // across targets.
84 ConstantExpr *CE = cast<ConstantExpr>(C);
85 switch (CE->getOpcode()) {
86 case Instruction::BitCast:
87 // Bitcast is fine if the casted value is fine.
88 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
90 case Instruction::IntToPtr:
91 case Instruction::PtrToInt:
92 // int <=> ptr is fine if the int type is the same size as the
93 // pointer type.
94 if (DL.getTypeSizeInBits(CE->getType()) !=
95 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
96 return false;
97 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
99 // GEP is fine if it is simple + constant offset.
100 case Instruction::GetElementPtr:
101 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
102 if (!isa<ConstantInt>(CE->getOperand(i)))
103 return false;
104 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
106 case Instruction::Add:
107 // We allow simple+cst.
108 if (!isa<ConstantInt>(CE->getOperand(1)))
109 return false;
110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
112 return false;
115 static inline bool
116 isSimpleEnoughValueToCommit(Constant *C,
117 SmallPtrSetImpl<Constant *> &SimpleConstants,
118 const DataLayout &DL) {
119 // If we already checked this constant, we win.
120 if (!SimpleConstants.insert(C).second)
121 return true;
122 // Check the constant.
123 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
126 /// Return true if this constant is simple enough for us to understand. In
127 /// particular, if it is a cast to anything other than from one pointer type to
128 /// another pointer type, we punt. We basically just support direct accesses to
129 /// globals and GEP's of globals. This should be kept up to date with
130 /// CommitValueTo.
131 static bool isSimpleEnoughPointerToCommit(Constant *C) {
132 // Conservatively, avoid aggregate types. This is because we don't
133 // want to worry about them partially overlapping other stores.
134 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
135 return false;
137 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
138 // Do not allow weak/*_odr/linkonce linkage or external globals.
139 return GV->hasUniqueInitializer();
141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
142 // Handle a constantexpr gep.
143 if (CE->getOpcode() == Instruction::GetElementPtr &&
144 isa<GlobalVariable>(CE->getOperand(0)) &&
145 cast<GEPOperator>(CE)->isInBounds()) {
146 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
147 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
148 // external globals.
149 if (!GV->hasUniqueInitializer())
150 return false;
152 // The first index must be zero.
153 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
154 if (!CI || !CI->isZero()) return false;
156 // The remaining indices must be compile-time known integers within the
157 // notional bounds of the corresponding static array types.
158 if (!CE->isGEPWithNoNotionalOverIndexing())
159 return false;
161 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
163 // A constantexpr bitcast from a pointer to another pointer is a no-op,
164 // and we know how to evaluate it by moving the bitcast from the pointer
165 // operand to the value operand.
166 } else if (CE->getOpcode() == Instruction::BitCast &&
167 isa<GlobalVariable>(CE->getOperand(0))) {
168 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
169 // external globals.
170 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
174 return false;
177 static Constant *getInitializer(Constant *C) {
178 auto *GV = dyn_cast<GlobalVariable>(C);
179 return GV && GV->hasDefinitiveInitializer() ? GV->getInitializer() : nullptr;
182 /// Return the value that would be computed by a load from P after the stores
183 /// reflected by 'memory' have been performed. If we can't decide, return null.
184 Constant *Evaluator::ComputeLoadResult(Constant *P) {
185 // If this memory location has been recently stored, use the stored value: it
186 // is the most up-to-date.
187 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
188 if (I != MutatedMemory.end()) return I->second;
190 // Access it.
191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
192 if (GV->hasDefinitiveInitializer())
193 return GV->getInitializer();
194 return nullptr;
197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) {
198 switch (CE->getOpcode()) {
199 // Handle a constantexpr getelementptr.
200 case Instruction::GetElementPtr:
201 if (auto *I = getInitializer(CE->getOperand(0)))
202 return ConstantFoldLoadThroughGEPConstantExpr(I, CE);
203 break;
204 // Handle a constantexpr bitcast.
205 case Instruction::BitCast:
206 Constant *Val = getVal(CE->getOperand(0));
207 auto MM = MutatedMemory.find(Val);
208 auto *I = (MM != MutatedMemory.end()) ? MM->second
209 : getInitializer(CE->getOperand(0));
210 if (I)
211 return ConstantFoldLoadThroughBitcast(
212 I, P->getType()->getPointerElementType(), DL);
213 break;
217 return nullptr; // don't know how to evaluate.
220 static Function *getFunction(Constant *C) {
221 if (auto *Fn = dyn_cast<Function>(C))
222 return Fn;
224 if (auto *Alias = dyn_cast<GlobalAlias>(C))
225 if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
226 return Fn;
227 return nullptr;
230 Function *
231 Evaluator::getCalleeWithFormalArgs(CallSite &CS,
232 SmallVector<Constant *, 8> &Formals) {
233 auto *V = CS.getCalledValue();
234 if (auto *Fn = getFunction(getVal(V)))
235 return getFormalParams(CS, Fn, Formals) ? Fn : nullptr;
237 auto *CE = dyn_cast<ConstantExpr>(V);
238 if (!CE || CE->getOpcode() != Instruction::BitCast ||
239 !getFormalParams(CS, getFunction(CE->getOperand(0)), Formals))
240 return nullptr;
242 return dyn_cast<Function>(
243 ConstantFoldLoadThroughBitcast(CE, CE->getOperand(0)->getType(), DL));
246 bool Evaluator::getFormalParams(CallSite &CS, Function *F,
247 SmallVector<Constant *, 8> &Formals) {
248 if (!F)
249 return false;
251 auto *FTy = F->getFunctionType();
252 if (FTy->getNumParams() > CS.getNumArgOperands()) {
253 LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");
254 return false;
257 auto ArgI = CS.arg_begin();
258 for (auto ParI = FTy->param_begin(), ParE = FTy->param_end(); ParI != ParE;
259 ++ParI) {
260 auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), *ParI, DL);
261 if (!ArgC) {
262 LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");
263 return false;
265 Formals.push_back(ArgC);
266 ++ArgI;
268 return true;
271 /// If call expression contains bitcast then we may need to cast
272 /// evaluated return value to a type of the call expression.
273 Constant *Evaluator::castCallResultIfNeeded(Value *CallExpr, Constant *RV) {
274 ConstantExpr *CE = dyn_cast<ConstantExpr>(CallExpr);
275 if (!RV || !CE || CE->getOpcode() != Instruction::BitCast)
276 return RV;
278 if (auto *FT =
279 dyn_cast<FunctionType>(CE->getType()->getPointerElementType())) {
280 RV = ConstantFoldLoadThroughBitcast(RV, FT->getReturnType(), DL);
281 if (!RV)
282 LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");
284 return RV;
287 /// Evaluate all instructions in block BB, returning true if successful, false
288 /// if we can't evaluate it. NewBB returns the next BB that control flows into,
289 /// or null upon return.
290 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
291 BasicBlock *&NextBB) {
292 // This is the main evaluation loop.
293 while (true) {
294 Constant *InstResult = nullptr;
296 LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
298 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
299 if (!SI->isSimple()) {
300 LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
301 return false; // no volatile/atomic accesses.
303 Constant *Ptr = getVal(SI->getOperand(1));
304 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
305 LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
306 Ptr = FoldedPtr;
307 LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
309 if (!isSimpleEnoughPointerToCommit(Ptr)) {
310 // If this is too complex for us to commit, reject it.
311 LLVM_DEBUG(
312 dbgs() << "Pointer is too complex for us to evaluate store.");
313 return false;
316 Constant *Val = getVal(SI->getOperand(0));
318 // If this might be too difficult for the backend to handle (e.g. the addr
319 // of one global variable divided by another) then we can't commit it.
320 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
321 LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
322 << *Val << "\n");
323 return false;
326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
327 if (CE->getOpcode() == Instruction::BitCast) {
328 LLVM_DEBUG(dbgs()
329 << "Attempting to resolve bitcast on constant ptr.\n");
330 // If we're evaluating a store through a bitcast, then we need
331 // to pull the bitcast off the pointer type and push it onto the
332 // stored value.
333 Ptr = CE->getOperand(0);
335 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
337 // In order to push the bitcast onto the stored value, a bitcast
338 // from NewTy to Val's type must be legal. If it's not, we can try
339 // introspecting NewTy to find a legal conversion.
340 Constant *NewVal;
341 while (!(NewVal = ConstantFoldLoadThroughBitcast(Val, NewTy, DL))) {
342 // If NewTy is a struct, we can convert the pointer to the struct
343 // into a pointer to its first member.
344 // FIXME: This could be extended to support arrays as well.
345 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
347 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
348 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
349 Constant * const IdxList[] = {IdxZero, IdxZero};
351 Ptr = ConstantExpr::getGetElementPtr(NewTy, Ptr, IdxList);
352 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
353 Ptr = FoldedPtr;
354 NewTy = STy->getTypeAtIndex(0U);
356 // If we can't improve the situation by introspecting NewTy,
357 // we have to give up.
358 } else {
359 LLVM_DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
360 "evaluate.\n");
361 return false;
365 Val = NewVal;
366 LLVM_DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
370 MutatedMemory[Ptr] = Val;
371 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
372 InstResult = ConstantExpr::get(BO->getOpcode(),
373 getVal(BO->getOperand(0)),
374 getVal(BO->getOperand(1)));
375 LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: "
376 << *InstResult << "\n");
377 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
378 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
379 getVal(CI->getOperand(0)),
380 getVal(CI->getOperand(1)));
381 LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
382 << "\n");
383 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
384 InstResult = ConstantExpr::getCast(CI->getOpcode(),
385 getVal(CI->getOperand(0)),
386 CI->getType());
387 LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
388 << "\n");
389 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
390 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
391 getVal(SI->getOperand(1)),
392 getVal(SI->getOperand(2)));
393 LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
394 << "\n");
395 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
396 InstResult = ConstantExpr::getExtractValue(
397 getVal(EVI->getAggregateOperand()), EVI->getIndices());
398 LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: "
399 << *InstResult << "\n");
400 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
401 InstResult = ConstantExpr::getInsertValue(
402 getVal(IVI->getAggregateOperand()),
403 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
404 LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: "
405 << *InstResult << "\n");
406 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
407 Constant *P = getVal(GEP->getOperand(0));
408 SmallVector<Constant*, 8> GEPOps;
409 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
410 i != e; ++i)
411 GEPOps.push_back(getVal(*i));
412 InstResult =
413 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
414 cast<GEPOperator>(GEP)->isInBounds());
415 LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n");
416 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
417 if (!LI->isSimple()) {
418 LLVM_DEBUG(
419 dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
420 return false; // no volatile/atomic accesses.
423 Constant *Ptr = getVal(LI->getOperand(0));
424 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
425 Ptr = FoldedPtr;
426 LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
427 "folding: "
428 << *Ptr << "\n");
430 InstResult = ComputeLoadResult(Ptr);
431 if (!InstResult) {
432 LLVM_DEBUG(
433 dbgs() << "Failed to compute load result. Can not evaluate load."
434 "\n");
435 return false; // Could not evaluate load.
438 LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
439 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
440 if (AI->isArrayAllocation()) {
441 LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
442 return false; // Cannot handle array allocs.
444 Type *Ty = AI->getAllocatedType();
445 AllocaTmps.push_back(llvm::make_unique<GlobalVariable>(
446 Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
447 AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
448 AI->getType()->getPointerAddressSpace()));
449 InstResult = AllocaTmps.back().get();
450 LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
451 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
452 CallSite CS(&*CurInst);
454 // Debug info can safely be ignored here.
455 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
456 LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
457 ++CurInst;
458 continue;
461 // Cannot handle inline asm.
462 if (isa<InlineAsm>(CS.getCalledValue())) {
463 LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
464 return false;
467 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
468 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
469 if (MSI->isVolatile()) {
470 LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
471 << "intrinsic.\n");
472 return false;
474 Constant *Ptr = getVal(MSI->getDest());
475 Constant *Val = getVal(MSI->getValue());
476 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
477 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
478 // This memset is a no-op.
479 LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
480 ++CurInst;
481 continue;
485 if (II->isLifetimeStartOrEnd()) {
486 LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
487 ++CurInst;
488 continue;
491 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
492 // We don't insert an entry into Values, as it doesn't have a
493 // meaningful return value.
494 if (!II->use_empty()) {
495 LLVM_DEBUG(dbgs()
496 << "Found unused invariant_start. Can't evaluate.\n");
497 return false;
499 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
500 Value *PtrArg = getVal(II->getArgOperand(1));
501 Value *Ptr = PtrArg->stripPointerCasts();
502 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
503 Type *ElemTy = GV->getValueType();
504 if (!Size->isMinusOne() &&
505 Size->getValue().getLimitedValue() >=
506 DL.getTypeStoreSize(ElemTy)) {
507 Invariants.insert(GV);
508 LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
509 << *GV << "\n");
510 } else {
511 LLVM_DEBUG(dbgs()
512 << "Found a global var, but can not treat it as an "
513 "invariant.\n");
516 // Continue even if we do nothing.
517 ++CurInst;
518 continue;
519 } else if (II->getIntrinsicID() == Intrinsic::assume) {
520 LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
521 ++CurInst;
522 continue;
523 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
524 LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
525 ++CurInst;
526 continue;
529 LLVM_DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
530 return false;
533 // Resolve function pointers.
534 SmallVector<Constant *, 8> Formals;
535 Function *Callee = getCalleeWithFormalArgs(CS, Formals);
536 if (!Callee || Callee->isInterposable()) {
537 LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
538 return false; // Cannot resolve.
541 if (Callee->isDeclaration()) {
542 // If this is a function we can constant fold, do it.
543 if (Constant *C = ConstantFoldCall(cast<CallBase>(CS.getInstruction()),
544 Callee, Formals, TLI)) {
545 InstResult = castCallResultIfNeeded(CS.getCalledValue(), C);
546 if (!InstResult)
547 return false;
548 LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
549 << *InstResult << "\n");
550 } else {
551 LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
552 return false;
554 } else {
555 if (Callee->getFunctionType()->isVarArg()) {
556 LLVM_DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
557 return false;
560 Constant *RetVal = nullptr;
561 // Execute the call, if successful, use the return value.
562 ValueStack.emplace_back();
563 if (!EvaluateFunction(Callee, RetVal, Formals)) {
564 LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
565 return false;
567 ValueStack.pop_back();
568 InstResult = castCallResultIfNeeded(CS.getCalledValue(), RetVal);
569 if (RetVal && !InstResult)
570 return false;
572 if (InstResult) {
573 LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
574 << *InstResult << "\n\n");
575 } else {
576 LLVM_DEBUG(dbgs()
577 << "Successfully evaluated function. Result: 0\n\n");
580 } else if (CurInst->isTerminator()) {
581 LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
583 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
584 if (BI->isUnconditional()) {
585 NextBB = BI->getSuccessor(0);
586 } else {
587 ConstantInt *Cond =
588 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
589 if (!Cond) return false; // Cannot determine.
591 NextBB = BI->getSuccessor(!Cond->getZExtValue());
593 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
594 ConstantInt *Val =
595 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
596 if (!Val) return false; // Cannot determine.
597 NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
598 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
599 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
600 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
601 NextBB = BA->getBasicBlock();
602 else
603 return false; // Cannot determine.
604 } else if (isa<ReturnInst>(CurInst)) {
605 NextBB = nullptr;
606 } else {
607 // invoke, unwind, resume, unreachable.
608 LLVM_DEBUG(dbgs() << "Can not handle terminator.");
609 return false; // Cannot handle this terminator.
612 // We succeeded at evaluating this block!
613 LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
614 return true;
615 } else {
616 // Did not know how to evaluate this!
617 LLVM_DEBUG(
618 dbgs() << "Failed to evaluate block due to unhandled instruction."
619 "\n");
620 return false;
623 if (!CurInst->use_empty()) {
624 if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
625 InstResult = FoldedInstResult;
627 setVal(&*CurInst, InstResult);
630 // If we just processed an invoke, we finished evaluating the block.
631 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
632 NextBB = II->getNormalDest();
633 LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
634 return true;
637 // Advance program counter.
638 ++CurInst;
642 /// Evaluate a call to function F, returning true if successful, false if we
643 /// can't evaluate it. ActualArgs contains the formal arguments for the
644 /// function.
645 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
646 const SmallVectorImpl<Constant*> &ActualArgs) {
647 // Check to see if this function is already executing (recursion). If so,
648 // bail out. TODO: we might want to accept limited recursion.
649 if (is_contained(CallStack, F))
650 return false;
652 CallStack.push_back(F);
654 // Initialize arguments to the incoming values specified.
655 unsigned ArgNo = 0;
656 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
657 ++AI, ++ArgNo)
658 setVal(&*AI, ActualArgs[ArgNo]);
660 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
661 // we can only evaluate any one basic block at most once. This set keeps
662 // track of what we have executed so we can detect recursive cases etc.
663 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
665 // CurBB - The current basic block we're evaluating.
666 BasicBlock *CurBB = &F->front();
668 BasicBlock::iterator CurInst = CurBB->begin();
670 while (true) {
671 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
672 LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
674 if (!EvaluateBlock(CurInst, NextBB))
675 return false;
677 if (!NextBB) {
678 // Successfully running until there's no next block means that we found
679 // the return. Fill it the return value and pop the call stack.
680 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
681 if (RI->getNumOperands())
682 RetVal = getVal(RI->getOperand(0));
683 CallStack.pop_back();
684 return true;
687 // Okay, we succeeded in evaluating this control flow. See if we have
688 // executed the new block before. If so, we have a looping function,
689 // which we cannot evaluate in reasonable time.
690 if (!ExecutedBlocks.insert(NextBB).second)
691 return false; // looped!
693 // Okay, we have never been in this block before. Check to see if there
694 // are any PHI nodes. If so, evaluate them with information about where
695 // we came from.
696 PHINode *PN = nullptr;
697 for (CurInst = NextBB->begin();
698 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
699 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
701 // Advance to the next block.
702 CurBB = NextBB;