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