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/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> 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 /// Apply 'Func' to Ptr. If this returns nullptr, introspect the pointer's 178 /// type and walk down through the initial elements to obtain additional 179 /// pointers to try. Returns the first non-null return value from Func, or 180 /// nullptr if the type can't be introspected further. 181 static Constant * 182 evaluateBitcastFromPtr(Constant *Ptr, const DataLayout &DL, 183 const TargetLibraryInfo *TLI, 184 std::function<Constant *(Constant *)> Func) { 185 Constant *Val; 186 while (!(Val = Func(Ptr))) { 187 // If Ty is a struct, we can convert the pointer to the struct 188 // into a pointer to its first member. 189 // FIXME: This could be extended to support arrays as well. 190 Type *Ty = cast<PointerType>(Ptr->getType())->getElementType(); 191 if (!isa<StructType>(Ty)) 192 break; 193 194 IntegerType *IdxTy = IntegerType::get(Ty->getContext(), 32); 195 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false); 196 Constant *const IdxList[] = {IdxZero, IdxZero}; 197 198 Ptr = ConstantExpr::getGetElementPtr(Ty, Ptr, IdxList); 199 Ptr = ConstantFoldConstant(Ptr, DL, TLI); 200 } 201 return Val; 202 } 203 204 static Constant *getInitializer(Constant *C) { 205 auto *GV = dyn_cast<GlobalVariable>(C); 206 return GV && GV->hasDefinitiveInitializer() ? GV->getInitializer() : nullptr; 207 } 208 209 /// Return the value that would be computed by a load from P after the stores 210 /// reflected by 'memory' have been performed. If we can't decide, return null. 211 Constant *Evaluator::ComputeLoadResult(Constant *P) { 212 // If this memory location has been recently stored, use the stored value: it 213 // is the most up-to-date. 214 auto findMemLoc = [this](Constant *Ptr) { 215 DenseMap<Constant *, Constant *>::const_iterator I = 216 MutatedMemory.find(Ptr); 217 return I != MutatedMemory.end() ? I->second : nullptr; 218 }; 219 220 if (Constant *Val = findMemLoc(P)) 221 return Val; 222 223 // Access it. 224 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { 225 if (GV->hasDefinitiveInitializer()) 226 return GV->getInitializer(); 227 return nullptr; 228 } 229 230 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) { 231 switch (CE->getOpcode()) { 232 // Handle a constantexpr getelementptr. 233 case Instruction::GetElementPtr: 234 if (auto *I = getInitializer(CE->getOperand(0))) 235 return ConstantFoldLoadThroughGEPConstantExpr(I, CE); 236 break; 237 // Handle a constantexpr bitcast. 238 case Instruction::BitCast: 239 // We're evaluating a load through a pointer that was bitcast to a 240 // different type. See if the "from" pointer has recently been stored. 241 // If it hasn't, we may still be able to find a stored pointer by 242 // introspecting the type. 243 Constant *Val = 244 evaluateBitcastFromPtr(CE->getOperand(0), DL, TLI, findMemLoc); 245 if (!Val) 246 Val = getInitializer(CE->getOperand(0)); 247 if (Val) 248 return ConstantFoldLoadThroughBitcast( 249 Val, P->getType()->getPointerElementType(), DL); 250 break; 251 } 252 } 253 254 return nullptr; // don't know how to evaluate. 255 } 256 257 static Function *getFunction(Constant *C) { 258 if (auto *Fn = dyn_cast<Function>(C)) 259 return Fn; 260 261 if (auto *Alias = dyn_cast<GlobalAlias>(C)) 262 if (auto *Fn = dyn_cast<Function>(Alias->getAliasee())) 263 return Fn; 264 return nullptr; 265 } 266 267 Function * 268 Evaluator::getCalleeWithFormalArgs(CallSite &CS, 269 SmallVector<Constant *, 8> &Formals) { 270 auto *V = CS.getCalledValue(); 271 if (auto *Fn = getFunction(getVal(V))) 272 return getFormalParams(CS, Fn, Formals) ? Fn : nullptr; 273 274 auto *CE = dyn_cast<ConstantExpr>(V); 275 if (!CE || CE->getOpcode() != Instruction::BitCast || 276 !getFormalParams(CS, getFunction(CE->getOperand(0)), Formals)) 277 return nullptr; 278 279 return dyn_cast<Function>( 280 ConstantFoldLoadThroughBitcast(CE, CE->getOperand(0)->getType(), DL)); 281 } 282 283 bool Evaluator::getFormalParams(CallSite &CS, Function *F, 284 SmallVector<Constant *, 8> &Formals) { 285 if (!F) 286 return false; 287 288 auto *FTy = F->getFunctionType(); 289 if (FTy->getNumParams() > CS.getNumArgOperands()) { 290 LLVM_DEBUG(dbgs() << "Too few arguments for function.\n"); 291 return false; 292 } 293 294 auto ArgI = CS.arg_begin(); 295 for (auto ParI = FTy->param_begin(), ParE = FTy->param_end(); ParI != ParE; 296 ++ParI) { 297 auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), *ParI, DL); 298 if (!ArgC) { 299 LLVM_DEBUG(dbgs() << "Can not convert function argument.\n"); 300 return false; 301 } 302 Formals.push_back(ArgC); 303 ++ArgI; 304 } 305 return true; 306 } 307 308 /// If call expression contains bitcast then we may need to cast 309 /// evaluated return value to a type of the call expression. 310 Constant *Evaluator::castCallResultIfNeeded(Value *CallExpr, Constant *RV) { 311 ConstantExpr *CE = dyn_cast<ConstantExpr>(CallExpr); 312 if (!RV || !CE || CE->getOpcode() != Instruction::BitCast) 313 return RV; 314 315 if (auto *FT = 316 dyn_cast<FunctionType>(CE->getType()->getPointerElementType())) { 317 RV = ConstantFoldLoadThroughBitcast(RV, FT->getReturnType(), DL); 318 if (!RV) 319 LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n"); 320 } 321 return RV; 322 } 323 324 /// Evaluate all instructions in block BB, returning true if successful, false 325 /// if we can't evaluate it. NewBB returns the next BB that control flows into, 326 /// or null upon return. 327 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, 328 BasicBlock *&NextBB) { 329 // This is the main evaluation loop. 330 while (true) { 331 Constant *InstResult = nullptr; 332 333 LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n"); 334 335 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) { 336 if (!SI->isSimple()) { 337 LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n"); 338 return false; // no volatile/atomic accesses. 339 } 340 Constant *Ptr = getVal(SI->getOperand(1)); 341 Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI); 342 if (Ptr != FoldedPtr) { 343 LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr); 344 Ptr = FoldedPtr; 345 LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n"); 346 } 347 if (!isSimpleEnoughPointerToCommit(Ptr)) { 348 // If this is too complex for us to commit, reject it. 349 LLVM_DEBUG( 350 dbgs() << "Pointer is too complex for us to evaluate store."); 351 return false; 352 } 353 354 Constant *Val = getVal(SI->getOperand(0)); 355 356 // If this might be too difficult for the backend to handle (e.g. the addr 357 // of one global variable divided by another) then we can't commit it. 358 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) { 359 LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. " 360 << *Val << "\n"); 361 return false; 362 } 363 364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) { 365 if (CE->getOpcode() == Instruction::BitCast) { 366 LLVM_DEBUG(dbgs() 367 << "Attempting to resolve bitcast on constant ptr.\n"); 368 // If we're evaluating a store through a bitcast, then we need 369 // to pull the bitcast off the pointer type and push it onto the 370 // stored value. In order to push the bitcast onto the stored value, 371 // a bitcast from the pointer's element type to Val's type must be 372 // legal. If it's not, we can try introspecting the type to find a 373 // legal conversion. 374 375 auto castValTy = [&](Constant *P) -> Constant * { 376 Type *Ty = cast<PointerType>(P->getType())->getElementType(); 377 if (Constant *FV = ConstantFoldLoadThroughBitcast(Val, Ty, DL)) { 378 Ptr = P; 379 return FV; 380 } 381 return nullptr; 382 }; 383 384 Constant *NewVal = 385 evaluateBitcastFromPtr(CE->getOperand(0), DL, TLI, castValTy); 386 if (!NewVal) { 387 LLVM_DEBUG(dbgs() << "Failed to bitcast constant ptr, can not " 388 "evaluate.\n"); 389 return false; 390 } 391 392 Val = NewVal; 393 LLVM_DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n"); 394 } 395 } 396 397 MutatedMemory[Ptr] = Val; 398 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) { 399 InstResult = ConstantExpr::get(BO->getOpcode(), 400 getVal(BO->getOperand(0)), 401 getVal(BO->getOperand(1))); 402 LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " 403 << *InstResult << "\n"); 404 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) { 405 InstResult = ConstantExpr::getCompare(CI->getPredicate(), 406 getVal(CI->getOperand(0)), 407 getVal(CI->getOperand(1))); 408 LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult 409 << "\n"); 410 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) { 411 InstResult = ConstantExpr::getCast(CI->getOpcode(), 412 getVal(CI->getOperand(0)), 413 CI->getType()); 414 LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult 415 << "\n"); 416 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) { 417 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)), 418 getVal(SI->getOperand(1)), 419 getVal(SI->getOperand(2))); 420 LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult 421 << "\n"); 422 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) { 423 InstResult = ConstantExpr::getExtractValue( 424 getVal(EVI->getAggregateOperand()), EVI->getIndices()); 425 LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " 426 << *InstResult << "\n"); 427 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) { 428 InstResult = ConstantExpr::getInsertValue( 429 getVal(IVI->getAggregateOperand()), 430 getVal(IVI->getInsertedValueOperand()), IVI->getIndices()); 431 LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " 432 << *InstResult << "\n"); 433 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) { 434 Constant *P = getVal(GEP->getOperand(0)); 435 SmallVector<Constant*, 8> GEPOps; 436 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); 437 i != e; ++i) 438 GEPOps.push_back(getVal(*i)); 439 InstResult = 440 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps, 441 cast<GEPOperator>(GEP)->isInBounds()); 442 LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n"); 443 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) { 444 if (!LI->isSimple()) { 445 LLVM_DEBUG( 446 dbgs() << "Found a Load! Not a simple load, can not evaluate.\n"); 447 return false; // no volatile/atomic accesses. 448 } 449 450 Constant *Ptr = getVal(LI->getOperand(0)); 451 Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI); 452 if (Ptr != FoldedPtr) { 453 Ptr = FoldedPtr; 454 LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant " 455 "folding: " 456 << *Ptr << "\n"); 457 } 458 InstResult = ComputeLoadResult(Ptr); 459 if (!InstResult) { 460 LLVM_DEBUG( 461 dbgs() << "Failed to compute load result. Can not evaluate load." 462 "\n"); 463 return false; // Could not evaluate load. 464 } 465 466 LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n"); 467 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) { 468 if (AI->isArrayAllocation()) { 469 LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n"); 470 return false; // Cannot handle array allocs. 471 } 472 Type *Ty = AI->getAllocatedType(); 473 AllocaTmps.push_back(std::make_unique<GlobalVariable>( 474 Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty), 475 AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal, 476 AI->getType()->getPointerAddressSpace())); 477 InstResult = AllocaTmps.back().get(); 478 LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n"); 479 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) { 480 CallSite CS(&*CurInst); 481 482 // Debug info can safely be ignored here. 483 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) { 484 LLVM_DEBUG(dbgs() << "Ignoring debug info.\n"); 485 ++CurInst; 486 continue; 487 } 488 489 // Cannot handle inline asm. 490 if (isa<InlineAsm>(CS.getCalledValue())) { 491 LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n"); 492 return false; 493 } 494 495 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) { 496 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) { 497 if (MSI->isVolatile()) { 498 LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset " 499 << "intrinsic.\n"); 500 return false; 501 } 502 Constant *Ptr = getVal(MSI->getDest()); 503 Constant *Val = getVal(MSI->getValue()); 504 Constant *DestVal = ComputeLoadResult(getVal(Ptr)); 505 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) { 506 // This memset is a no-op. 507 LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n"); 508 ++CurInst; 509 continue; 510 } 511 } 512 513 if (II->isLifetimeStartOrEnd()) { 514 LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n"); 515 ++CurInst; 516 continue; 517 } 518 519 if (II->getIntrinsicID() == Intrinsic::invariant_start) { 520 // We don't insert an entry into Values, as it doesn't have a 521 // meaningful return value. 522 if (!II->use_empty()) { 523 LLVM_DEBUG(dbgs() 524 << "Found unused invariant_start. Can't evaluate.\n"); 525 return false; 526 } 527 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0)); 528 Value *PtrArg = getVal(II->getArgOperand(1)); 529 Value *Ptr = PtrArg->stripPointerCasts(); 530 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { 531 Type *ElemTy = GV->getValueType(); 532 if (!Size->isMinusOne() && 533 Size->getValue().getLimitedValue() >= 534 DL.getTypeStoreSize(ElemTy)) { 535 Invariants.insert(GV); 536 LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: " 537 << *GV << "\n"); 538 } else { 539 LLVM_DEBUG(dbgs() 540 << "Found a global var, but can not treat it as an " 541 "invariant.\n"); 542 } 543 } 544 // Continue even if we do nothing. 545 ++CurInst; 546 continue; 547 } else if (II->getIntrinsicID() == Intrinsic::assume) { 548 LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n"); 549 ++CurInst; 550 continue; 551 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) { 552 LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n"); 553 ++CurInst; 554 continue; 555 } 556 557 LLVM_DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n"); 558 return false; 559 } 560 561 // Resolve function pointers. 562 SmallVector<Constant *, 8> Formals; 563 Function *Callee = getCalleeWithFormalArgs(CS, Formals); 564 if (!Callee || Callee->isInterposable()) { 565 LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n"); 566 return false; // Cannot resolve. 567 } 568 569 if (Callee->isDeclaration()) { 570 // If this is a function we can constant fold, do it. 571 if (Constant *C = ConstantFoldCall(cast<CallBase>(CS.getInstruction()), 572 Callee, Formals, TLI)) { 573 InstResult = castCallResultIfNeeded(CS.getCalledValue(), C); 574 if (!InstResult) 575 return false; 576 LLVM_DEBUG(dbgs() << "Constant folded function call. Result: " 577 << *InstResult << "\n"); 578 } else { 579 LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n"); 580 return false; 581 } 582 } else { 583 if (Callee->getFunctionType()->isVarArg()) { 584 LLVM_DEBUG(dbgs() << "Can not constant fold vararg function call.\n"); 585 return false; 586 } 587 588 Constant *RetVal = nullptr; 589 // Execute the call, if successful, use the return value. 590 ValueStack.emplace_back(); 591 if (!EvaluateFunction(Callee, RetVal, Formals)) { 592 LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n"); 593 return false; 594 } 595 ValueStack.pop_back(); 596 InstResult = castCallResultIfNeeded(CS.getCalledValue(), RetVal); 597 if (RetVal && !InstResult) 598 return false; 599 600 if (InstResult) { 601 LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: " 602 << *InstResult << "\n\n"); 603 } else { 604 LLVM_DEBUG(dbgs() 605 << "Successfully evaluated function. Result: 0\n\n"); 606 } 607 } 608 } else if (CurInst->isTerminator()) { 609 LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n"); 610 611 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) { 612 if (BI->isUnconditional()) { 613 NextBB = BI->getSuccessor(0); 614 } else { 615 ConstantInt *Cond = 616 dyn_cast<ConstantInt>(getVal(BI->getCondition())); 617 if (!Cond) return false; // Cannot determine. 618 619 NextBB = BI->getSuccessor(!Cond->getZExtValue()); 620 } 621 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) { 622 ConstantInt *Val = 623 dyn_cast<ConstantInt>(getVal(SI->getCondition())); 624 if (!Val) return false; // Cannot determine. 625 NextBB = SI->findCaseValue(Val)->getCaseSuccessor(); 626 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) { 627 Value *Val = getVal(IBI->getAddress())->stripPointerCasts(); 628 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val)) 629 NextBB = BA->getBasicBlock(); 630 else 631 return false; // Cannot determine. 632 } else if (isa<ReturnInst>(CurInst)) { 633 NextBB = nullptr; 634 } else { 635 // invoke, unwind, resume, unreachable. 636 LLVM_DEBUG(dbgs() << "Can not handle terminator."); 637 return false; // Cannot handle this terminator. 638 } 639 640 // We succeeded at evaluating this block! 641 LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n"); 642 return true; 643 } else { 644 // Did not know how to evaluate this! 645 LLVM_DEBUG( 646 dbgs() << "Failed to evaluate block due to unhandled instruction." 647 "\n"); 648 return false; 649 } 650 651 if (!CurInst->use_empty()) { 652 InstResult = ConstantFoldConstant(InstResult, DL, TLI); 653 setVal(&*CurInst, InstResult); 654 } 655 656 // If we just processed an invoke, we finished evaluating the block. 657 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) { 658 NextBB = II->getNormalDest(); 659 LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n"); 660 return true; 661 } 662 663 // Advance program counter. 664 ++CurInst; 665 } 666 } 667 668 /// Evaluate a call to function F, returning true if successful, false if we 669 /// can't evaluate it. ActualArgs contains the formal arguments for the 670 /// function. 671 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal, 672 const SmallVectorImpl<Constant*> &ActualArgs) { 673 // Check to see if this function is already executing (recursion). If so, 674 // bail out. TODO: we might want to accept limited recursion. 675 if (is_contained(CallStack, F)) 676 return false; 677 678 CallStack.push_back(F); 679 680 // Initialize arguments to the incoming values specified. 681 unsigned ArgNo = 0; 682 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; 683 ++AI, ++ArgNo) 684 setVal(&*AI, ActualArgs[ArgNo]); 685 686 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such, 687 // we can only evaluate any one basic block at most once. This set keeps 688 // track of what we have executed so we can detect recursive cases etc. 689 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks; 690 691 // CurBB - The current basic block we're evaluating. 692 BasicBlock *CurBB = &F->front(); 693 694 BasicBlock::iterator CurInst = CurBB->begin(); 695 696 while (true) { 697 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings. 698 LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n"); 699 700 if (!EvaluateBlock(CurInst, NextBB)) 701 return false; 702 703 if (!NextBB) { 704 // Successfully running until there's no next block means that we found 705 // the return. Fill it the return value and pop the call stack. 706 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator()); 707 if (RI->getNumOperands()) 708 RetVal = getVal(RI->getOperand(0)); 709 CallStack.pop_back(); 710 return true; 711 } 712 713 // Okay, we succeeded in evaluating this control flow. See if we have 714 // executed the new block before. If so, we have a looping function, 715 // which we cannot evaluate in reasonable time. 716 if (!ExecutedBlocks.insert(NextBB).second) 717 return false; // looped! 718 719 // Okay, we have never been in this block before. Check to see if there 720 // are any PHI nodes. If so, evaluate them with information about where 721 // we came from. 722 PHINode *PN = nullptr; 723 for (CurInst = NextBB->begin(); 724 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst) 725 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB))); 726 727 // Advance to the next block. 728 CurBB = NextBB; 729 } 730 } 731