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 
14 #include "llvm/Transforms/Utils/Evaluator.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.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>
42 
43 #define DEBUG_TYPE "evaluator"
44 
45 using namespace llvm;
46 
47 static inline bool
48 isSimpleEnoughValueToCommit(Constant *C,
49                             SmallPtrSetImpl<Constant *> &SimpleConstants,
50                             const DataLayout &DL);
51 
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();
68 
69   // Simple integer, undef, constant aggregate zero, etc are all supported.
70   if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
71     return true;
72 
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;
79   }
80 
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);
89 
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);
98 
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);
105 
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);
111   }
112   return false;
113 }
114 
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);
124 }
125 
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;
136 
137   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
138     // Do not allow weak/*_odr/linkonce linkage or external globals.
139     return GV->hasUniqueInitializer();
140 
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;
151 
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;
155 
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;
160 
161       return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
162 
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();
171     }
172   }
173 
174   return false;
175 }
176 
177 static Constant *getInitializer(Constant *C) {
178   auto *GV = dyn_cast<GlobalVariable>(C);
179   return GV && GV->hasDefinitiveInitializer() ? GV->getInitializer() : nullptr;
180 }
181 
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;
189 
190   // Access it.
191   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
192     if (GV->hasDefinitiveInitializer())
193       return GV->getInitializer();
194     return nullptr;
195   }
196 
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;
214     }
215   }
216 
217   return nullptr;  // don't know how to evaluate.
218 }
219 
220 /// Evaluate all instructions in block BB, returning true if successful, false
221 /// if we can't evaluate it.  NewBB returns the next BB that control flows into,
222 /// or null upon return.
223 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
224                               BasicBlock *&NextBB) {
225   // This is the main evaluation loop.
226   while (true) {
227     Constant *InstResult = nullptr;
228 
229     LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
230 
231     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
232       if (!SI->isSimple()) {
233         LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
234         return false;  // no volatile/atomic accesses.
235       }
236       Constant *Ptr = getVal(SI->getOperand(1));
237       if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
238         LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
239         Ptr = FoldedPtr;
240         LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
241       }
242       if (!isSimpleEnoughPointerToCommit(Ptr)) {
243         // If this is too complex for us to commit, reject it.
244         LLVM_DEBUG(
245             dbgs() << "Pointer is too complex for us to evaluate store.");
246         return false;
247       }
248 
249       Constant *Val = getVal(SI->getOperand(0));
250 
251       // If this might be too difficult for the backend to handle (e.g. the addr
252       // of one global variable divided by another) then we can't commit it.
253       if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
254         LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
255                           << *Val << "\n");
256         return false;
257       }
258 
259       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
260         if (CE->getOpcode() == Instruction::BitCast) {
261           LLVM_DEBUG(dbgs()
262                      << "Attempting to resolve bitcast on constant ptr.\n");
263           // If we're evaluating a store through a bitcast, then we need
264           // to pull the bitcast off the pointer type and push it onto the
265           // stored value.
266           Ptr = CE->getOperand(0);
267 
268           Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
269 
270           // In order to push the bitcast onto the stored value, a bitcast
271           // from NewTy to Val's type must be legal.  If it's not, we can try
272           // introspecting NewTy to find a legal conversion.
273           Constant *NewVal;
274           while (!(NewVal = ConstantFoldLoadThroughBitcast(Val, NewTy, DL))) {
275             // If NewTy is a struct, we can convert the pointer to the struct
276             // into a pointer to its first member.
277             // FIXME: This could be extended to support arrays as well.
278             if (StructType *STy = dyn_cast<StructType>(NewTy)) {
279               NewTy = STy->getTypeAtIndex(0U);
280 
281               IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
282               Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
283               Constant * const IdxList[] = {IdxZero, IdxZero};
284 
285               Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
286               if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
287                 Ptr = FoldedPtr;
288 
289             // If we can't improve the situation by introspecting NewTy,
290             // we have to give up.
291             } else {
292               LLVM_DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
293                                    "evaluate.\n");
294               return false;
295             }
296           }
297 
298           Val = NewVal;
299           LLVM_DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
300         }
301       }
302 
303       MutatedMemory[Ptr] = Val;
304     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
305       InstResult = ConstantExpr::get(BO->getOpcode(),
306                                      getVal(BO->getOperand(0)),
307                                      getVal(BO->getOperand(1)));
308       LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: "
309                         << *InstResult << "\n");
310     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
311       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
312                                             getVal(CI->getOperand(0)),
313                                             getVal(CI->getOperand(1)));
314       LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
315                         << "\n");
316     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
317       InstResult = ConstantExpr::getCast(CI->getOpcode(),
318                                          getVal(CI->getOperand(0)),
319                                          CI->getType());
320       LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
321                         << "\n");
322     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
323       InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
324                                            getVal(SI->getOperand(1)),
325                                            getVal(SI->getOperand(2)));
326       LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
327                         << "\n");
328     } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
329       InstResult = ConstantExpr::getExtractValue(
330           getVal(EVI->getAggregateOperand()), EVI->getIndices());
331       LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: "
332                         << *InstResult << "\n");
333     } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
334       InstResult = ConstantExpr::getInsertValue(
335           getVal(IVI->getAggregateOperand()),
336           getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
337       LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: "
338                         << *InstResult << "\n");
339     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
340       Constant *P = getVal(GEP->getOperand(0));
341       SmallVector<Constant*, 8> GEPOps;
342       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
343            i != e; ++i)
344         GEPOps.push_back(getVal(*i));
345       InstResult =
346           ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
347                                          cast<GEPOperator>(GEP)->isInBounds());
348       LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n");
349     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
350       if (!LI->isSimple()) {
351         LLVM_DEBUG(
352             dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
353         return false;  // no volatile/atomic accesses.
354       }
355 
356       Constant *Ptr = getVal(LI->getOperand(0));
357       if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
358         Ptr = FoldedPtr;
359         LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
360                              "folding: "
361                           << *Ptr << "\n");
362       }
363       InstResult = ComputeLoadResult(Ptr);
364       if (!InstResult) {
365         LLVM_DEBUG(
366             dbgs() << "Failed to compute load result. Can not evaluate load."
367                       "\n");
368         return false; // Could not evaluate load.
369       }
370 
371       LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
372     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
373       if (AI->isArrayAllocation()) {
374         LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
375         return false;  // Cannot handle array allocs.
376       }
377       Type *Ty = AI->getAllocatedType();
378       AllocaTmps.push_back(llvm::make_unique<GlobalVariable>(
379           Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
380           AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
381           AI->getType()->getPointerAddressSpace()));
382       InstResult = AllocaTmps.back().get();
383       LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
384     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
385       CallSite CS(&*CurInst);
386 
387       // Debug info can safely be ignored here.
388       if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
389         LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
390         ++CurInst;
391         continue;
392       }
393 
394       // Cannot handle inline asm.
395       if (isa<InlineAsm>(CS.getCalledValue())) {
396         LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
397         return false;
398       }
399 
400       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
401         if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
402           if (MSI->isVolatile()) {
403             LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
404                               << "intrinsic.\n");
405             return false;
406           }
407           Constant *Ptr = getVal(MSI->getDest());
408           Constant *Val = getVal(MSI->getValue());
409           Constant *DestVal = ComputeLoadResult(getVal(Ptr));
410           if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
411             // This memset is a no-op.
412             LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
413             ++CurInst;
414             continue;
415           }
416         }
417 
418         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
419             II->getIntrinsicID() == Intrinsic::lifetime_end) {
420           LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
421           ++CurInst;
422           continue;
423         }
424 
425         if (II->getIntrinsicID() == Intrinsic::invariant_start) {
426           // We don't insert an entry into Values, as it doesn't have a
427           // meaningful return value.
428           if (!II->use_empty()) {
429             LLVM_DEBUG(dbgs()
430                        << "Found unused invariant_start. Can't evaluate.\n");
431             return false;
432           }
433           ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
434           Value *PtrArg = getVal(II->getArgOperand(1));
435           Value *Ptr = PtrArg->stripPointerCasts();
436           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
437             Type *ElemTy = GV->getValueType();
438             if (!Size->isMinusOne() &&
439                 Size->getValue().getLimitedValue() >=
440                     DL.getTypeStoreSize(ElemTy)) {
441               Invariants.insert(GV);
442               LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
443                                 << *GV << "\n");
444             } else {
445               LLVM_DEBUG(dbgs()
446                          << "Found a global var, but can not treat it as an "
447                             "invariant.\n");
448             }
449           }
450           // Continue even if we do nothing.
451           ++CurInst;
452           continue;
453         } else if (II->getIntrinsicID() == Intrinsic::assume) {
454           LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
455           ++CurInst;
456           continue;
457         } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
458           LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
459           ++CurInst;
460           continue;
461         }
462 
463         LLVM_DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
464         return false;
465       }
466 
467       // Resolve function pointers.
468       Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
469       if (!Callee || Callee->isInterposable()) {
470         LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
471         return false;  // Cannot resolve.
472       }
473 
474       SmallVector<Constant*, 8> Formals;
475       for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
476         Formals.push_back(getVal(*i));
477 
478       if (Callee->isDeclaration()) {
479         // If this is a function we can constant fold, do it.
480         if (Constant *C = ConstantFoldCall(CS, Callee, Formals, TLI)) {
481           InstResult = C;
482           LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
483                             << *InstResult << "\n");
484         } else {
485           LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
486           return false;
487         }
488       } else {
489         if (Callee->getFunctionType()->isVarArg()) {
490           LLVM_DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
491           return false;
492         }
493 
494         Constant *RetVal = nullptr;
495         // Execute the call, if successful, use the return value.
496         ValueStack.emplace_back();
497         if (!EvaluateFunction(Callee, RetVal, Formals)) {
498           LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
499           return false;
500         }
501         ValueStack.pop_back();
502         InstResult = RetVal;
503 
504         if (InstResult) {
505           LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
506                             << *InstResult << "\n\n");
507         } else {
508           LLVM_DEBUG(dbgs()
509                      << "Successfully evaluated function. Result: 0\n\n");
510         }
511       }
512     } else if (isa<TerminatorInst>(CurInst)) {
513       LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
514 
515       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
516         if (BI->isUnconditional()) {
517           NextBB = BI->getSuccessor(0);
518         } else {
519           ConstantInt *Cond =
520             dyn_cast<ConstantInt>(getVal(BI->getCondition()));
521           if (!Cond) return false;  // Cannot determine.
522 
523           NextBB = BI->getSuccessor(!Cond->getZExtValue());
524         }
525       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
526         ConstantInt *Val =
527           dyn_cast<ConstantInt>(getVal(SI->getCondition()));
528         if (!Val) return false;  // Cannot determine.
529         NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
530       } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
531         Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
532         if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
533           NextBB = BA->getBasicBlock();
534         else
535           return false;  // Cannot determine.
536       } else if (isa<ReturnInst>(CurInst)) {
537         NextBB = nullptr;
538       } else {
539         // invoke, unwind, resume, unreachable.
540         LLVM_DEBUG(dbgs() << "Can not handle terminator.");
541         return false;  // Cannot handle this terminator.
542       }
543 
544       // We succeeded at evaluating this block!
545       LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
546       return true;
547     } else {
548       // Did not know how to evaluate this!
549       LLVM_DEBUG(
550           dbgs() << "Failed to evaluate block due to unhandled instruction."
551                     "\n");
552       return false;
553     }
554 
555     if (!CurInst->use_empty()) {
556       if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
557         InstResult = FoldedInstResult;
558 
559       setVal(&*CurInst, InstResult);
560     }
561 
562     // If we just processed an invoke, we finished evaluating the block.
563     if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
564       NextBB = II->getNormalDest();
565       LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
566       return true;
567     }
568 
569     // Advance program counter.
570     ++CurInst;
571   }
572 }
573 
574 /// Evaluate a call to function F, returning true if successful, false if we
575 /// can't evaluate it.  ActualArgs contains the formal arguments for the
576 /// function.
577 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
578                                  const SmallVectorImpl<Constant*> &ActualArgs) {
579   // Check to see if this function is already executing (recursion).  If so,
580   // bail out.  TODO: we might want to accept limited recursion.
581   if (is_contained(CallStack, F))
582     return false;
583 
584   CallStack.push_back(F);
585 
586   // Initialize arguments to the incoming values specified.
587   unsigned ArgNo = 0;
588   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
589        ++AI, ++ArgNo)
590     setVal(&*AI, ActualArgs[ArgNo]);
591 
592   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
593   // we can only evaluate any one basic block at most once.  This set keeps
594   // track of what we have executed so we can detect recursive cases etc.
595   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
596 
597   // CurBB - The current basic block we're evaluating.
598   BasicBlock *CurBB = &F->front();
599 
600   BasicBlock::iterator CurInst = CurBB->begin();
601 
602   while (true) {
603     BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
604     LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
605 
606     if (!EvaluateBlock(CurInst, NextBB))
607       return false;
608 
609     if (!NextBB) {
610       // Successfully running until there's no next block means that we found
611       // the return.  Fill it the return value and pop the call stack.
612       ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
613       if (RI->getNumOperands())
614         RetVal = getVal(RI->getOperand(0));
615       CallStack.pop_back();
616       return true;
617     }
618 
619     // Okay, we succeeded in evaluating this control flow.  See if we have
620     // executed the new block before.  If so, we have a looping function,
621     // which we cannot evaluate in reasonable time.
622     if (!ExecutedBlocks.insert(NextBB).second)
623       return false;  // looped!
624 
625     // Okay, we have never been in this block before.  Check to see if there
626     // are any PHI nodes.  If so, evaluate them with information about where
627     // we came from.
628     PHINode *PN = nullptr;
629     for (CurInst = NextBB->begin();
630          (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
631       setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
632 
633     // Advance to the next block.
634     CurBB = NextBB;
635   }
636 }
637