1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 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 // This file implements sparse conditional constant propagation and merging: 11 // 12 // Specifically, this: 13 // * Assumes values are constant unless proven otherwise 14 // * Assumes BasicBlocks are dead unless proven otherwise 15 // * Proves values to be constant, and replaces them with constants 16 // * Proves conditional branches to be unconditional 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/IPO/SCCP.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/ConstantFolding.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueLatticeUtils.h" 31 #include "llvm/IR/CallSite.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/InstVisitor.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Transforms/IPO.h" 42 #include "llvm/Transforms/Scalar.h" 43 #include "llvm/Transforms/Scalar/SCCP.h" 44 #include "llvm/Transforms/Utils/Local.h" 45 #include <algorithm> 46 using namespace llvm; 47 48 #define DEBUG_TYPE "sccp" 49 50 STATISTIC(NumInstRemoved, "Number of instructions removed"); 51 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 52 53 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 54 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 55 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 56 57 namespace { 58 /// LatticeVal class - This class represents the different lattice values that 59 /// an LLVM value may occupy. It is a simple class with value semantics. 60 /// 61 class LatticeVal { 62 enum LatticeValueTy { 63 /// unknown - This LLVM Value has no known value yet. 64 unknown, 65 66 /// constant - This LLVM Value has a specific constant value. 67 constant, 68 69 /// forcedconstant - This LLVM Value was thought to be undef until 70 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged 71 /// with another (different) constant, it goes to overdefined, instead of 72 /// asserting. 73 forcedconstant, 74 75 /// overdefined - This instruction is not known to be constant, and we know 76 /// it has a value. 77 overdefined 78 }; 79 80 /// Val: This stores the current lattice value along with the Constant* for 81 /// the constant if this is a 'constant' or 'forcedconstant' value. 82 PointerIntPair<Constant *, 2, LatticeValueTy> Val; 83 84 LatticeValueTy getLatticeValue() const { 85 return Val.getInt(); 86 } 87 88 public: 89 LatticeVal() : Val(nullptr, unknown) {} 90 91 bool isUnknown() const { return getLatticeValue() == unknown; } 92 bool isConstant() const { 93 return getLatticeValue() == constant || getLatticeValue() == forcedconstant; 94 } 95 bool isOverdefined() const { return getLatticeValue() == overdefined; } 96 97 Constant *getConstant() const { 98 assert(isConstant() && "Cannot get the constant of a non-constant!"); 99 return Val.getPointer(); 100 } 101 102 /// markOverdefined - Return true if this is a change in status. 103 bool markOverdefined() { 104 if (isOverdefined()) 105 return false; 106 107 Val.setInt(overdefined); 108 return true; 109 } 110 111 /// markConstant - Return true if this is a change in status. 112 bool markConstant(Constant *V) { 113 if (getLatticeValue() == constant) { // Constant but not forcedconstant. 114 assert(getConstant() == V && "Marking constant with different value"); 115 return false; 116 } 117 118 if (isUnknown()) { 119 Val.setInt(constant); 120 assert(V && "Marking constant with NULL"); 121 Val.setPointer(V); 122 } else { 123 assert(getLatticeValue() == forcedconstant && 124 "Cannot move from overdefined to constant!"); 125 // Stay at forcedconstant if the constant is the same. 126 if (V == getConstant()) return false; 127 128 // Otherwise, we go to overdefined. Assumptions made based on the 129 // forced value are possibly wrong. Assuming this is another constant 130 // could expose a contradiction. 131 Val.setInt(overdefined); 132 } 133 return true; 134 } 135 136 /// getConstantInt - If this is a constant with a ConstantInt value, return it 137 /// otherwise return null. 138 ConstantInt *getConstantInt() const { 139 if (isConstant()) 140 return dyn_cast<ConstantInt>(getConstant()); 141 return nullptr; 142 } 143 144 /// getBlockAddress - If this is a constant with a BlockAddress value, return 145 /// it, otherwise return null. 146 BlockAddress *getBlockAddress() const { 147 if (isConstant()) 148 return dyn_cast<BlockAddress>(getConstant()); 149 return nullptr; 150 } 151 152 void markForcedConstant(Constant *V) { 153 assert(isUnknown() && "Can't force a defined value!"); 154 Val.setInt(forcedconstant); 155 Val.setPointer(V); 156 } 157 }; 158 } // end anonymous namespace. 159 160 161 namespace { 162 163 //===----------------------------------------------------------------------===// 164 // 165 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional 166 /// Constant Propagation. 167 /// 168 class SCCPSolver : public InstVisitor<SCCPSolver> { 169 const DataLayout &DL; 170 const TargetLibraryInfo *TLI; 171 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable. 172 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in. 173 174 /// StructValueState - This maintains ValueState for values that have 175 /// StructType, for example for formal arguments, calls, insertelement, etc. 176 /// 177 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState; 178 179 /// GlobalValue - If we are tracking any values for the contents of a global 180 /// variable, we keep a mapping from the constant accessor to the element of 181 /// the global, to the currently known value. If the value becomes 182 /// overdefined, it's entry is simply removed from this map. 183 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals; 184 185 /// TrackedRetVals - If we are tracking arguments into and the return 186 /// value out of a function, it will have an entry in this map, indicating 187 /// what the known return value for the function is. 188 DenseMap<Function*, LatticeVal> TrackedRetVals; 189 190 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 191 /// that return multiple values. 192 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals; 193 194 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is 195 /// represented here for efficient lookup. 196 SmallPtrSet<Function*, 16> MRVFunctionsTracked; 197 198 /// TrackingIncomingArguments - This is the set of functions for whose 199 /// arguments we make optimistic assumptions about and try to prove as 200 /// constants. 201 SmallPtrSet<Function*, 16> TrackingIncomingArguments; 202 203 /// The reason for two worklists is that overdefined is the lowest state 204 /// on the lattice, and moving things to overdefined as fast as possible 205 /// makes SCCP converge much faster. 206 /// 207 /// By having a separate worklist, we accomplish this because everything 208 /// possibly overdefined will become overdefined at the soonest possible 209 /// point. 210 SmallVector<Value*, 64> OverdefinedInstWorkList; 211 SmallVector<Value*, 64> InstWorkList; 212 213 214 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list 215 216 /// KnownFeasibleEdges - Entries in this set are edges which have already had 217 /// PHI nodes retriggered. 218 typedef std::pair<BasicBlock*, BasicBlock*> Edge; 219 DenseSet<Edge> KnownFeasibleEdges; 220 public: 221 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli) 222 : DL(DL), TLI(tli) {} 223 224 /// MarkBlockExecutable - This method can be used by clients to mark all of 225 /// the blocks that are known to be intrinsically live in the processed unit. 226 /// 227 /// This returns true if the block was not considered live before. 228 bool MarkBlockExecutable(BasicBlock *BB) { 229 if (!BBExecutable.insert(BB).second) 230 return false; 231 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); 232 BBWorkList.push_back(BB); // Add the block to the work list! 233 return true; 234 } 235 236 /// TrackValueOfGlobalVariable - Clients can use this method to 237 /// inform the SCCPSolver that it should track loads and stores to the 238 /// specified global variable if it can. This is only legal to call if 239 /// performing Interprocedural SCCP. 240 void TrackValueOfGlobalVariable(GlobalVariable *GV) { 241 // We only track the contents of scalar globals. 242 if (GV->getValueType()->isSingleValueType()) { 243 LatticeVal &IV = TrackedGlobals[GV]; 244 if (!isa<UndefValue>(GV->getInitializer())) 245 IV.markConstant(GV->getInitializer()); 246 } 247 } 248 249 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 250 /// and out of the specified function (which cannot have its address taken), 251 /// this method must be called. 252 void AddTrackedFunction(Function *F) { 253 // Add an entry, F -> undef. 254 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 255 MRVFunctionsTracked.insert(F); 256 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 257 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i), 258 LatticeVal())); 259 } else 260 TrackedRetVals.insert(std::make_pair(F, LatticeVal())); 261 } 262 263 void AddArgumentTrackedFunction(Function *F) { 264 TrackingIncomingArguments.insert(F); 265 } 266 267 /// Returns true if the given function is in the solver's set of 268 /// argument-tracked functions. 269 bool isArgumentTrackedFunction(Function *F) { 270 return TrackingIncomingArguments.count(F); 271 } 272 273 /// Solve - Solve for constants and executable blocks. 274 /// 275 void Solve(); 276 277 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 278 /// that branches on undef values cannot reach any of their successors. 279 /// However, this is not a safe assumption. After we solve dataflow, this 280 /// method should be use to handle this. If this returns true, the solver 281 /// should be rerun. 282 bool ResolvedUndefsIn(Function &F); 283 284 bool isBlockExecutable(BasicBlock *BB) const { 285 return BBExecutable.count(BB); 286 } 287 288 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const { 289 std::vector<LatticeVal> StructValues; 290 auto *STy = dyn_cast<StructType>(V->getType()); 291 assert(STy && "getStructLatticeValueFor() can be called only on structs"); 292 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 293 auto I = StructValueState.find(std::make_pair(V, i)); 294 assert(I != StructValueState.end() && "Value not in valuemap!"); 295 StructValues.push_back(I->second); 296 } 297 return StructValues; 298 } 299 300 LatticeVal getLatticeValueFor(Value *V) const { 301 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V); 302 assert(I != ValueState.end() && "V is not in valuemap!"); 303 return I->second; 304 } 305 306 /// getTrackedRetVals - Get the inferred return value map. 307 /// 308 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() { 309 return TrackedRetVals; 310 } 311 312 /// getTrackedGlobals - Get and return the set of inferred initializers for 313 /// global variables. 314 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 315 return TrackedGlobals; 316 } 317 318 /// getMRVFunctionsTracked - Get the set of functions which return multiple 319 /// values tracked by the pass. 320 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() { 321 return MRVFunctionsTracked; 322 } 323 324 /// markOverdefined - Mark the specified value overdefined. This 325 /// works with both scalars and structs. 326 void markOverdefined(Value *V) { 327 if (auto *STy = dyn_cast<StructType>(V->getType())) 328 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 329 markOverdefined(getStructValueState(V, i), V); 330 else 331 markOverdefined(ValueState[V], V); 332 } 333 334 // isStructLatticeConstant - Return true if all the lattice values 335 // corresponding to elements of the structure are not overdefined, 336 // false otherwise. 337 bool isStructLatticeConstant(Function *F, StructType *STy) { 338 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 339 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 340 assert(It != TrackedMultipleRetVals.end()); 341 LatticeVal LV = It->second; 342 if (LV.isOverdefined()) 343 return false; 344 } 345 return true; 346 } 347 348 private: 349 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined 350 void pushToWorkList(LatticeVal &IV, Value *V) { 351 if (IV.isOverdefined()) 352 return OverdefinedInstWorkList.push_back(V); 353 InstWorkList.push_back(V); 354 } 355 356 // markConstant - Make a value be marked as "constant". If the value 357 // is not already a constant, add it to the instruction work list so that 358 // the users of the instruction are updated later. 359 // 360 void markConstant(LatticeVal &IV, Value *V, Constant *C) { 361 if (!IV.markConstant(C)) return; 362 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); 363 pushToWorkList(IV, V); 364 } 365 366 void markConstant(Value *V, Constant *C) { 367 assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); 368 markConstant(ValueState[V], V, C); 369 } 370 371 void markForcedConstant(Value *V, Constant *C) { 372 assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); 373 LatticeVal &IV = ValueState[V]; 374 IV.markForcedConstant(C); 375 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n'); 376 pushToWorkList(IV, V); 377 } 378 379 380 // markOverdefined - Make a value be marked as "overdefined". If the 381 // value is not already overdefined, add it to the overdefined instruction 382 // work list so that the users of the instruction are updated later. 383 void markOverdefined(LatticeVal &IV, Value *V) { 384 if (!IV.markOverdefined()) return; 385 386 DEBUG(dbgs() << "markOverdefined: "; 387 if (auto *F = dyn_cast<Function>(V)) 388 dbgs() << "Function '" << F->getName() << "'\n"; 389 else 390 dbgs() << *V << '\n'); 391 // Only instructions go on the work list 392 pushToWorkList(IV, V); 393 } 394 395 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) { 396 if (IV.isOverdefined() || MergeWithV.isUnknown()) 397 return; // Noop. 398 if (MergeWithV.isOverdefined()) 399 return markOverdefined(IV, V); 400 if (IV.isUnknown()) 401 return markConstant(IV, V, MergeWithV.getConstant()); 402 if (IV.getConstant() != MergeWithV.getConstant()) 403 return markOverdefined(IV, V); 404 } 405 406 void mergeInValue(Value *V, LatticeVal MergeWithV) { 407 assert(!V->getType()->isStructTy() && 408 "non-structs should use markConstant"); 409 mergeInValue(ValueState[V], V, MergeWithV); 410 } 411 412 413 /// getValueState - Return the LatticeVal object that corresponds to the 414 /// value. This function handles the case when the value hasn't been seen yet 415 /// by properly seeding constants etc. 416 LatticeVal &getValueState(Value *V) { 417 assert(!V->getType()->isStructTy() && "Should use getStructValueState"); 418 419 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I = 420 ValueState.insert(std::make_pair(V, LatticeVal())); 421 LatticeVal &LV = I.first->second; 422 423 if (!I.second) 424 return LV; // Common case, already in the map. 425 426 if (auto *C = dyn_cast<Constant>(V)) { 427 // Undef values remain unknown. 428 if (!isa<UndefValue>(V)) 429 LV.markConstant(C); // Constants are constant 430 } 431 432 // All others are underdefined by default. 433 return LV; 434 } 435 436 /// getStructValueState - Return the LatticeVal object that corresponds to the 437 /// value/field pair. This function handles the case when the value hasn't 438 /// been seen yet by properly seeding constants etc. 439 LatticeVal &getStructValueState(Value *V, unsigned i) { 440 assert(V->getType()->isStructTy() && "Should use getValueState"); 441 assert(i < cast<StructType>(V->getType())->getNumElements() && 442 "Invalid element #"); 443 444 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator, 445 bool> I = StructValueState.insert( 446 std::make_pair(std::make_pair(V, i), LatticeVal())); 447 LatticeVal &LV = I.first->second; 448 449 if (!I.second) 450 return LV; // Common case, already in the map. 451 452 if (auto *C = dyn_cast<Constant>(V)) { 453 Constant *Elt = C->getAggregateElement(i); 454 455 if (!Elt) 456 LV.markOverdefined(); // Unknown sort of constant. 457 else if (isa<UndefValue>(Elt)) 458 ; // Undef values remain unknown. 459 else 460 LV.markConstant(Elt); // Constants are constant. 461 } 462 463 // All others are underdefined by default. 464 return LV; 465 } 466 467 468 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB 469 /// work list if it is not already executable. 470 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 471 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 472 return; // This edge is already known to be executable! 473 474 if (!MarkBlockExecutable(Dest)) { 475 // If the destination is already executable, we just made an *edge* 476 // feasible that wasn't before. Revisit the PHI nodes in the block 477 // because they have potentially new operands. 478 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() 479 << " -> " << Dest->getName() << '\n'); 480 481 PHINode *PN; 482 for (BasicBlock::iterator I = Dest->begin(); 483 (PN = dyn_cast<PHINode>(I)); ++I) 484 visitPHINode(*PN); 485 } 486 } 487 488 // getFeasibleSuccessors - Return a vector of booleans to indicate which 489 // successors are reachable from a given terminator instruction. 490 // 491 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs); 492 493 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 494 // block to the 'To' basic block is currently feasible. 495 // 496 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 497 498 // OperandChangedState - This method is invoked on all of the users of an 499 // instruction that was just changed state somehow. Based on this 500 // information, we need to update the specified user of this instruction. 501 // 502 void OperandChangedState(Instruction *I) { 503 if (BBExecutable.count(I->getParent())) // Inst is executable? 504 visit(*I); 505 } 506 507 private: 508 friend class InstVisitor<SCCPSolver>; 509 510 // visit implementations - Something changed in this instruction. Either an 511 // operand made a transition, or the instruction is newly executable. Change 512 // the value type of I to reflect these changes if appropriate. 513 void visitPHINode(PHINode &I); 514 515 // Terminators 516 void visitReturnInst(ReturnInst &I); 517 void visitTerminatorInst(TerminatorInst &TI); 518 519 void visitCastInst(CastInst &I); 520 void visitSelectInst(SelectInst &I); 521 void visitBinaryOperator(Instruction &I); 522 void visitCmpInst(CmpInst &I); 523 void visitExtractValueInst(ExtractValueInst &EVI); 524 void visitInsertValueInst(InsertValueInst &IVI); 525 void visitCatchSwitchInst(CatchSwitchInst &CPI) { 526 markOverdefined(&CPI); 527 visitTerminatorInst(CPI); 528 } 529 530 // Instructions that cannot be folded away. 531 void visitStoreInst (StoreInst &I); 532 void visitLoadInst (LoadInst &I); 533 void visitGetElementPtrInst(GetElementPtrInst &I); 534 void visitCallInst (CallInst &I) { 535 visitCallSite(&I); 536 } 537 void visitInvokeInst (InvokeInst &II) { 538 visitCallSite(&II); 539 visitTerminatorInst(II); 540 } 541 void visitCallSite (CallSite CS); 542 void visitResumeInst (TerminatorInst &I) { /*returns void*/ } 543 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 544 void visitFenceInst (FenceInst &I) { /*returns void*/ } 545 void visitInstruction(Instruction &I) { 546 // All the instructions we don't do any special handling for just 547 // go to overdefined. 548 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); 549 markOverdefined(&I); 550 } 551 }; 552 553 } // end anonymous namespace 554 555 556 // getFeasibleSuccessors - Return a vector of booleans to indicate which 557 // successors are reachable from a given terminator instruction. 558 // 559 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 560 SmallVectorImpl<bool> &Succs) { 561 Succs.resize(TI.getNumSuccessors()); 562 if (auto *BI = dyn_cast<BranchInst>(&TI)) { 563 if (BI->isUnconditional()) { 564 Succs[0] = true; 565 return; 566 } 567 568 LatticeVal BCValue = getValueState(BI->getCondition()); 569 ConstantInt *CI = BCValue.getConstantInt(); 570 if (!CI) { 571 // Overdefined condition variables, and branches on unfoldable constant 572 // conditions, mean the branch could go either way. 573 if (!BCValue.isUnknown()) 574 Succs[0] = Succs[1] = true; 575 return; 576 } 577 578 // Constant condition variables mean the branch can only go a single way. 579 Succs[CI->isZero()] = true; 580 return; 581 } 582 583 // Unwinding instructions successors are always executable. 584 if (TI.isExceptional()) { 585 Succs.assign(TI.getNumSuccessors(), true); 586 return; 587 } 588 589 if (auto *SI = dyn_cast<SwitchInst>(&TI)) { 590 if (!SI->getNumCases()) { 591 Succs[0] = true; 592 return; 593 } 594 LatticeVal SCValue = getValueState(SI->getCondition()); 595 ConstantInt *CI = SCValue.getConstantInt(); 596 597 if (!CI) { // Overdefined or unknown condition? 598 // All destinations are executable! 599 if (!SCValue.isUnknown()) 600 Succs.assign(TI.getNumSuccessors(), true); 601 return; 602 } 603 604 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true; 605 return; 606 } 607 608 // In case of indirect branch and its address is a blockaddress, we mark 609 // the target as executable. 610 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) { 611 // Casts are folded by visitCastInst. 612 LatticeVal IBRValue = getValueState(IBR->getAddress()); 613 BlockAddress *Addr = IBRValue.getBlockAddress(); 614 if (!Addr) { // Overdefined or unknown condition? 615 // All destinations are executable! 616 if (!IBRValue.isUnknown()) 617 Succs.assign(TI.getNumSuccessors(), true); 618 return; 619 } 620 621 BasicBlock* T = Addr->getBasicBlock(); 622 assert(Addr->getFunction() == T->getParent() && 623 "Block address of a different function ?"); 624 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) { 625 // This is the target. 626 if (IBR->getDestination(i) == T) { 627 Succs[i] = true; 628 return; 629 } 630 } 631 632 // If we didn't find our destination in the IBR successor list, then we 633 // have undefined behavior. Its ok to assume no successor is executable. 634 return; 635 } 636 637 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n'); 638 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 639 } 640 641 642 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 643 // block to the 'To' basic block is currently feasible. 644 // 645 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 646 assert(BBExecutable.count(To) && "Dest should always be alive!"); 647 648 // Make sure the source basic block is executable!! 649 if (!BBExecutable.count(From)) return false; 650 651 // Check to make sure this edge itself is actually feasible now. 652 TerminatorInst *TI = From->getTerminator(); 653 if (auto *BI = dyn_cast<BranchInst>(TI)) { 654 if (BI->isUnconditional()) 655 return true; 656 657 LatticeVal BCValue = getValueState(BI->getCondition()); 658 659 // Overdefined condition variables mean the branch could go either way, 660 // undef conditions mean that neither edge is feasible yet. 661 ConstantInt *CI = BCValue.getConstantInt(); 662 if (!CI) 663 return !BCValue.isUnknown(); 664 665 // Constant condition variables mean the branch can only go a single way. 666 return BI->getSuccessor(CI->isZero()) == To; 667 } 668 669 // Unwinding instructions successors are always executable. 670 if (TI->isExceptional()) 671 return true; 672 673 if (auto *SI = dyn_cast<SwitchInst>(TI)) { 674 if (SI->getNumCases() < 1) 675 return true; 676 677 LatticeVal SCValue = getValueState(SI->getCondition()); 678 ConstantInt *CI = SCValue.getConstantInt(); 679 680 if (!CI) 681 return !SCValue.isUnknown(); 682 683 return SI->findCaseValue(CI)->getCaseSuccessor() == To; 684 } 685 686 // In case of indirect branch and its address is a blockaddress, we mark 687 // the target as executable. 688 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) { 689 LatticeVal IBRValue = getValueState(IBR->getAddress()); 690 BlockAddress *Addr = IBRValue.getBlockAddress(); 691 692 if (!Addr) 693 return !IBRValue.isUnknown(); 694 695 // At this point, the indirectbr is branching on a blockaddress. 696 return Addr->getBasicBlock() == To; 697 } 698 699 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n'); 700 llvm_unreachable("SCCP: Don't know how to handle this terminator!"); 701 } 702 703 // visit Implementations - Something changed in this instruction, either an 704 // operand made a transition, or the instruction is newly executable. Change 705 // the value type of I to reflect these changes if appropriate. This method 706 // makes sure to do the following actions: 707 // 708 // 1. If a phi node merges two constants in, and has conflicting value coming 709 // from different branches, or if the PHI node merges in an overdefined 710 // value, then the PHI node becomes overdefined. 711 // 2. If a phi node merges only constants in, and they all agree on value, the 712 // PHI node becomes a constant value equal to that. 713 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 714 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 715 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 716 // 6. If a conditional branch has a value that is constant, make the selected 717 // destination executable 718 // 7. If a conditional branch has a value that is overdefined, make all 719 // successors executable. 720 // 721 void SCCPSolver::visitPHINode(PHINode &PN) { 722 // If this PN returns a struct, just mark the result overdefined. 723 // TODO: We could do a lot better than this if code actually uses this. 724 if (PN.getType()->isStructTy()) 725 return markOverdefined(&PN); 726 727 if (getValueState(&PN).isOverdefined()) 728 return; // Quick exit 729 730 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 731 // and slow us down a lot. Just mark them overdefined. 732 if (PN.getNumIncomingValues() > 64) 733 return markOverdefined(&PN); 734 735 // Look at all of the executable operands of the PHI node. If any of them 736 // are overdefined, the PHI becomes overdefined as well. If they are all 737 // constant, and they agree with each other, the PHI becomes the identical 738 // constant. If they are constant and don't agree, the PHI is overdefined. 739 // If there are no executable operands, the PHI remains unknown. 740 // 741 Constant *OperandVal = nullptr; 742 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 743 LatticeVal IV = getValueState(PN.getIncomingValue(i)); 744 if (IV.isUnknown()) continue; // Doesn't influence PHI node. 745 746 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) 747 continue; 748 749 if (IV.isOverdefined()) // PHI node becomes overdefined! 750 return markOverdefined(&PN); 751 752 if (!OperandVal) { // Grab the first value. 753 OperandVal = IV.getConstant(); 754 continue; 755 } 756 757 // There is already a reachable operand. If we conflict with it, 758 // then the PHI node becomes overdefined. If we agree with it, we 759 // can continue on. 760 761 // Check to see if there are two different constants merging, if so, the PHI 762 // node is overdefined. 763 if (IV.getConstant() != OperandVal) 764 return markOverdefined(&PN); 765 } 766 767 // If we exited the loop, this means that the PHI node only has constant 768 // arguments that agree with each other(and OperandVal is the constant) or 769 // OperandVal is null because there are no defined incoming arguments. If 770 // this is the case, the PHI remains unknown. 771 // 772 if (OperandVal) 773 markConstant(&PN, OperandVal); // Acquire operand value 774 } 775 776 void SCCPSolver::visitReturnInst(ReturnInst &I) { 777 if (I.getNumOperands() == 0) return; // ret void 778 779 Function *F = I.getParent()->getParent(); 780 Value *ResultOp = I.getOperand(0); 781 782 // If we are tracking the return value of this function, merge it in. 783 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) { 784 DenseMap<Function*, LatticeVal>::iterator TFRVI = 785 TrackedRetVals.find(F); 786 if (TFRVI != TrackedRetVals.end()) { 787 mergeInValue(TFRVI->second, F, getValueState(ResultOp)); 788 return; 789 } 790 } 791 792 // Handle functions that return multiple values. 793 if (!TrackedMultipleRetVals.empty()) { 794 if (auto *STy = dyn_cast<StructType>(ResultOp->getType())) 795 if (MRVFunctionsTracked.count(F)) 796 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 797 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F, 798 getStructValueState(ResultOp, i)); 799 800 } 801 } 802 803 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 804 SmallVector<bool, 16> SuccFeasible; 805 getFeasibleSuccessors(TI, SuccFeasible); 806 807 BasicBlock *BB = TI.getParent(); 808 809 // Mark all feasible successors executable. 810 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 811 if (SuccFeasible[i]) 812 markEdgeExecutable(BB, TI.getSuccessor(i)); 813 } 814 815 void SCCPSolver::visitCastInst(CastInst &I) { 816 LatticeVal OpSt = getValueState(I.getOperand(0)); 817 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand 818 markOverdefined(&I); 819 else if (OpSt.isConstant()) { 820 // Fold the constant as we build. 821 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(), 822 I.getType(), DL); 823 if (isa<UndefValue>(C)) 824 return; 825 // Propagate constant value 826 markConstant(&I, C); 827 } 828 } 829 830 831 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) { 832 // If this returns a struct, mark all elements over defined, we don't track 833 // structs in structs. 834 if (EVI.getType()->isStructTy()) 835 return markOverdefined(&EVI); 836 837 // If this is extracting from more than one level of struct, we don't know. 838 if (EVI.getNumIndices() != 1) 839 return markOverdefined(&EVI); 840 841 Value *AggVal = EVI.getAggregateOperand(); 842 if (AggVal->getType()->isStructTy()) { 843 unsigned i = *EVI.idx_begin(); 844 LatticeVal EltVal = getStructValueState(AggVal, i); 845 mergeInValue(getValueState(&EVI), &EVI, EltVal); 846 } else { 847 // Otherwise, must be extracting from an array. 848 return markOverdefined(&EVI); 849 } 850 } 851 852 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) { 853 auto *STy = dyn_cast<StructType>(IVI.getType()); 854 if (!STy) 855 return markOverdefined(&IVI); 856 857 // If this has more than one index, we can't handle it, drive all results to 858 // undef. 859 if (IVI.getNumIndices() != 1) 860 return markOverdefined(&IVI); 861 862 Value *Aggr = IVI.getAggregateOperand(); 863 unsigned Idx = *IVI.idx_begin(); 864 865 // Compute the result based on what we're inserting. 866 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 867 // This passes through all values that aren't the inserted element. 868 if (i != Idx) { 869 LatticeVal EltVal = getStructValueState(Aggr, i); 870 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal); 871 continue; 872 } 873 874 Value *Val = IVI.getInsertedValueOperand(); 875 if (Val->getType()->isStructTy()) 876 // We don't track structs in structs. 877 markOverdefined(getStructValueState(&IVI, i), &IVI); 878 else { 879 LatticeVal InVal = getValueState(Val); 880 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal); 881 } 882 } 883 } 884 885 void SCCPSolver::visitSelectInst(SelectInst &I) { 886 // If this select returns a struct, just mark the result overdefined. 887 // TODO: We could do a lot better than this if code actually uses this. 888 if (I.getType()->isStructTy()) 889 return markOverdefined(&I); 890 891 LatticeVal CondValue = getValueState(I.getCondition()); 892 if (CondValue.isUnknown()) 893 return; 894 895 if (ConstantInt *CondCB = CondValue.getConstantInt()) { 896 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue(); 897 mergeInValue(&I, getValueState(OpVal)); 898 return; 899 } 900 901 // Otherwise, the condition is overdefined or a constant we can't evaluate. 902 // See if we can produce something better than overdefined based on the T/F 903 // value. 904 LatticeVal TVal = getValueState(I.getTrueValue()); 905 LatticeVal FVal = getValueState(I.getFalseValue()); 906 907 // select ?, C, C -> C. 908 if (TVal.isConstant() && FVal.isConstant() && 909 TVal.getConstant() == FVal.getConstant()) 910 return markConstant(&I, FVal.getConstant()); 911 912 if (TVal.isUnknown()) // select ?, undef, X -> X. 913 return mergeInValue(&I, FVal); 914 if (FVal.isUnknown()) // select ?, X, undef -> X. 915 return mergeInValue(&I, TVal); 916 markOverdefined(&I); 917 } 918 919 // Handle Binary Operators. 920 void SCCPSolver::visitBinaryOperator(Instruction &I) { 921 LatticeVal V1State = getValueState(I.getOperand(0)); 922 LatticeVal V2State = getValueState(I.getOperand(1)); 923 924 LatticeVal &IV = ValueState[&I]; 925 if (IV.isOverdefined()) return; 926 927 if (V1State.isConstant() && V2State.isConstant()) { 928 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(), 929 V2State.getConstant()); 930 // X op Y -> undef. 931 if (isa<UndefValue>(C)) 932 return; 933 return markConstant(IV, &I, C); 934 } 935 936 // If something is undef, wait for it to resolve. 937 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 938 return; 939 940 // Otherwise, one of our operands is overdefined. Try to produce something 941 // better than overdefined with some tricks. 942 // If this is 0 / Y, it doesn't matter that the second operand is 943 // overdefined, and we can replace it with zero. 944 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv) 945 if (V1State.isConstant() && V1State.getConstant()->isNullValue()) 946 return markConstant(IV, &I, V1State.getConstant()); 947 948 // If this is: 949 // -> AND/MUL with 0 950 // -> OR with -1 951 // it doesn't matter that the other operand is overdefined. 952 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul || 953 I.getOpcode() == Instruction::Or) { 954 LatticeVal *NonOverdefVal = nullptr; 955 if (!V1State.isOverdefined()) 956 NonOverdefVal = &V1State; 957 else if (!V2State.isOverdefined()) 958 NonOverdefVal = &V2State; 959 960 if (NonOverdefVal) { 961 if (NonOverdefVal->isUnknown()) 962 return; 963 964 if (I.getOpcode() == Instruction::And || 965 I.getOpcode() == Instruction::Mul) { 966 // X and 0 = 0 967 // X * 0 = 0 968 if (NonOverdefVal->getConstant()->isNullValue()) 969 return markConstant(IV, &I, NonOverdefVal->getConstant()); 970 } else { 971 // X or -1 = -1 972 if (ConstantInt *CI = NonOverdefVal->getConstantInt()) 973 if (CI->isMinusOne()) 974 return markConstant(IV, &I, NonOverdefVal->getConstant()); 975 } 976 } 977 } 978 979 980 markOverdefined(&I); 981 } 982 983 // Handle ICmpInst instruction. 984 void SCCPSolver::visitCmpInst(CmpInst &I) { 985 LatticeVal V1State = getValueState(I.getOperand(0)); 986 LatticeVal V2State = getValueState(I.getOperand(1)); 987 988 LatticeVal &IV = ValueState[&I]; 989 if (IV.isOverdefined()) return; 990 991 if (V1State.isConstant() && V2State.isConstant()) { 992 Constant *C = ConstantExpr::getCompare( 993 I.getPredicate(), V1State.getConstant(), V2State.getConstant()); 994 if (isa<UndefValue>(C)) 995 return; 996 return markConstant(IV, &I, C); 997 } 998 999 // If operands are still unknown, wait for it to resolve. 1000 if (!V1State.isOverdefined() && !V2State.isOverdefined()) 1001 return; 1002 1003 markOverdefined(&I); 1004 } 1005 1006 // Handle getelementptr instructions. If all operands are constants then we 1007 // can turn this into a getelementptr ConstantExpr. 1008 // 1009 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 1010 if (ValueState[&I].isOverdefined()) return; 1011 1012 SmallVector<Constant*, 8> Operands; 1013 Operands.reserve(I.getNumOperands()); 1014 1015 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1016 LatticeVal State = getValueState(I.getOperand(i)); 1017 if (State.isUnknown()) 1018 return; // Operands are not resolved yet. 1019 1020 if (State.isOverdefined()) 1021 return markOverdefined(&I); 1022 1023 assert(State.isConstant() && "Unknown state!"); 1024 Operands.push_back(State.getConstant()); 1025 } 1026 1027 Constant *Ptr = Operands[0]; 1028 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end()); 1029 Constant *C = 1030 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices); 1031 if (isa<UndefValue>(C)) 1032 return; 1033 markConstant(&I, C); 1034 } 1035 1036 void SCCPSolver::visitStoreInst(StoreInst &SI) { 1037 // If this store is of a struct, ignore it. 1038 if (SI.getOperand(0)->getType()->isStructTy()) 1039 return; 1040 1041 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 1042 return; 1043 1044 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 1045 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 1046 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 1047 1048 // Get the value we are storing into the global, then merge it. 1049 mergeInValue(I->second, GV, getValueState(SI.getOperand(0))); 1050 if (I->second.isOverdefined()) 1051 TrackedGlobals.erase(I); // No need to keep tracking this! 1052 } 1053 1054 1055 // Handle load instructions. If the operand is a constant pointer to a constant 1056 // global, we can replace the load with the loaded constant value! 1057 void SCCPSolver::visitLoadInst(LoadInst &I) { 1058 // If this load is of a struct, just mark the result overdefined. 1059 if (I.getType()->isStructTy()) 1060 return markOverdefined(&I); 1061 1062 LatticeVal PtrVal = getValueState(I.getOperand(0)); 1063 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet! 1064 1065 LatticeVal &IV = ValueState[&I]; 1066 if (IV.isOverdefined()) return; 1067 1068 if (!PtrVal.isConstant() || I.isVolatile()) 1069 return markOverdefined(IV, &I); 1070 1071 Constant *Ptr = PtrVal.getConstant(); 1072 1073 // load null is undefined. 1074 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) 1075 return; 1076 1077 // Transform load (constant global) into the value loaded. 1078 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) { 1079 if (!TrackedGlobals.empty()) { 1080 // If we are tracking this global, merge in the known value for it. 1081 DenseMap<GlobalVariable*, LatticeVal>::iterator It = 1082 TrackedGlobals.find(GV); 1083 if (It != TrackedGlobals.end()) { 1084 mergeInValue(IV, &I, It->second); 1085 return; 1086 } 1087 } 1088 } 1089 1090 // Transform load from a constant into a constant if possible. 1091 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) { 1092 if (isa<UndefValue>(C)) 1093 return; 1094 return markConstant(IV, &I, C); 1095 } 1096 1097 // Otherwise we cannot say for certain what value this load will produce. 1098 // Bail out. 1099 markOverdefined(IV, &I); 1100 } 1101 1102 void SCCPSolver::visitCallSite(CallSite CS) { 1103 Function *F = CS.getCalledFunction(); 1104 Instruction *I = CS.getInstruction(); 1105 1106 // The common case is that we aren't tracking the callee, either because we 1107 // are not doing interprocedural analysis or the callee is indirect, or is 1108 // external. Handle these cases first. 1109 if (!F || F->isDeclaration()) { 1110 CallOverdefined: 1111 // Void return and not tracking callee, just bail. 1112 if (I->getType()->isVoidTy()) return; 1113 1114 // Otherwise, if we have a single return value case, and if the function is 1115 // a declaration, maybe we can constant fold it. 1116 if (F && F->isDeclaration() && !I->getType()->isStructTy() && 1117 canConstantFoldCallTo(CS, F)) { 1118 1119 SmallVector<Constant*, 8> Operands; 1120 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 1121 AI != E; ++AI) { 1122 LatticeVal State = getValueState(*AI); 1123 1124 if (State.isUnknown()) 1125 return; // Operands are not resolved yet. 1126 if (State.isOverdefined()) 1127 return markOverdefined(I); 1128 assert(State.isConstant() && "Unknown state!"); 1129 Operands.push_back(State.getConstant()); 1130 } 1131 1132 if (getValueState(I).isOverdefined()) 1133 return; 1134 1135 // If we can constant fold this, mark the result of the call as a 1136 // constant. 1137 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) { 1138 // call -> undef. 1139 if (isa<UndefValue>(C)) 1140 return; 1141 return markConstant(I, C); 1142 } 1143 } 1144 1145 // Otherwise, we don't know anything about this call, mark it overdefined. 1146 return markOverdefined(I); 1147 } 1148 1149 // If this is a local function that doesn't have its address taken, mark its 1150 // entry block executable and merge in the actual arguments to the call into 1151 // the formal arguments of the function. 1152 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){ 1153 MarkBlockExecutable(&F->front()); 1154 1155 // Propagate information from this call site into the callee. 1156 CallSite::arg_iterator CAI = CS.arg_begin(); 1157 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1158 AI != E; ++AI, ++CAI) { 1159 // If this argument is byval, and if the function is not readonly, there 1160 // will be an implicit copy formed of the input aggregate. 1161 if (AI->hasByValAttr() && !F->onlyReadsMemory()) { 1162 markOverdefined(&*AI); 1163 continue; 1164 } 1165 1166 if (auto *STy = dyn_cast<StructType>(AI->getType())) { 1167 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1168 LatticeVal CallArg = getStructValueState(*CAI, i); 1169 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg); 1170 } 1171 } else { 1172 mergeInValue(&*AI, getValueState(*CAI)); 1173 } 1174 } 1175 } 1176 1177 // If this is a single/zero retval case, see if we're tracking the function. 1178 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) { 1179 if (!MRVFunctionsTracked.count(F)) 1180 goto CallOverdefined; // Not tracking this callee. 1181 1182 // If we are tracking this callee, propagate the result of the function 1183 // into this call site. 1184 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1185 mergeInValue(getStructValueState(I, i), I, 1186 TrackedMultipleRetVals[std::make_pair(F, i)]); 1187 } else { 1188 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F); 1189 if (TFRVI == TrackedRetVals.end()) 1190 goto CallOverdefined; // Not tracking this callee. 1191 1192 // If so, propagate the return value of the callee into this call result. 1193 mergeInValue(I, TFRVI->second); 1194 } 1195 } 1196 1197 void SCCPSolver::Solve() { 1198 // Process the work lists until they are empty! 1199 while (!BBWorkList.empty() || !InstWorkList.empty() || 1200 !OverdefinedInstWorkList.empty()) { 1201 // Process the overdefined instruction's work list first, which drives other 1202 // things to overdefined more quickly. 1203 while (!OverdefinedInstWorkList.empty()) { 1204 Value *I = OverdefinedInstWorkList.pop_back_val(); 1205 1206 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n'); 1207 1208 // "I" got into the work list because it either made the transition from 1209 // bottom to constant, or to overdefined. 1210 // 1211 // Anything on this worklist that is overdefined need not be visited 1212 // since all of its users will have already been marked as overdefined 1213 // Update all of the users of this instruction's value. 1214 // 1215 for (User *U : I->users()) 1216 if (auto *UI = dyn_cast<Instruction>(U)) 1217 OperandChangedState(UI); 1218 } 1219 1220 // Process the instruction work list. 1221 while (!InstWorkList.empty()) { 1222 Value *I = InstWorkList.pop_back_val(); 1223 1224 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n'); 1225 1226 // "I" got into the work list because it made the transition from undef to 1227 // constant. 1228 // 1229 // Anything on this worklist that is overdefined need not be visited 1230 // since all of its users will have already been marked as overdefined. 1231 // Update all of the users of this instruction's value. 1232 // 1233 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined()) 1234 for (User *U : I->users()) 1235 if (auto *UI = dyn_cast<Instruction>(U)) 1236 OperandChangedState(UI); 1237 } 1238 1239 // Process the basic block work list. 1240 while (!BBWorkList.empty()) { 1241 BasicBlock *BB = BBWorkList.back(); 1242 BBWorkList.pop_back(); 1243 1244 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n'); 1245 1246 // Notify all instructions in this basic block that they are newly 1247 // executable. 1248 visit(BB); 1249 } 1250 } 1251 } 1252 1253 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 1254 /// that branches on undef values cannot reach any of their successors. 1255 /// However, this is not a safe assumption. After we solve dataflow, this 1256 /// method should be use to handle this. If this returns true, the solver 1257 /// should be rerun. 1258 /// 1259 /// This method handles this by finding an unresolved branch and marking it one 1260 /// of the edges from the block as being feasible, even though the condition 1261 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the 1262 /// CFG and only slightly pessimizes the analysis results (by marking one, 1263 /// potentially infeasible, edge feasible). This cannot usefully modify the 1264 /// constraints on the condition of the branch, as that would impact other users 1265 /// of the value. 1266 /// 1267 /// This scan also checks for values that use undefs, whose results are actually 1268 /// defined. For example, 'zext i8 undef to i32' should produce all zeros 1269 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero, 1270 /// even if X isn't defined. 1271 bool SCCPSolver::ResolvedUndefsIn(Function &F) { 1272 for (BasicBlock &BB : F) { 1273 if (!BBExecutable.count(&BB)) 1274 continue; 1275 1276 for (Instruction &I : BB) { 1277 // Look for instructions which produce undef values. 1278 if (I.getType()->isVoidTy()) continue; 1279 1280 if (auto *STy = dyn_cast<StructType>(I.getType())) { 1281 // Only a few things that can be structs matter for undef. 1282 1283 // Tracked calls must never be marked overdefined in ResolvedUndefsIn. 1284 if (CallSite CS = CallSite(&I)) 1285 if (Function *F = CS.getCalledFunction()) 1286 if (MRVFunctionsTracked.count(F)) 1287 continue; 1288 1289 // extractvalue and insertvalue don't need to be marked; they are 1290 // tracked as precisely as their operands. 1291 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)) 1292 continue; 1293 1294 // Send the results of everything else to overdefined. We could be 1295 // more precise than this but it isn't worth bothering. 1296 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1297 LatticeVal &LV = getStructValueState(&I, i); 1298 if (LV.isUnknown()) 1299 markOverdefined(LV, &I); 1300 } 1301 continue; 1302 } 1303 1304 LatticeVal &LV = getValueState(&I); 1305 if (!LV.isUnknown()) continue; 1306 1307 // extractvalue is safe; check here because the argument is a struct. 1308 if (isa<ExtractValueInst>(I)) 1309 continue; 1310 1311 // Compute the operand LatticeVals, for convenience below. 1312 // Anything taking a struct is conservatively assumed to require 1313 // overdefined markings. 1314 if (I.getOperand(0)->getType()->isStructTy()) { 1315 markOverdefined(&I); 1316 return true; 1317 } 1318 LatticeVal Op0LV = getValueState(I.getOperand(0)); 1319 LatticeVal Op1LV; 1320 if (I.getNumOperands() == 2) { 1321 if (I.getOperand(1)->getType()->isStructTy()) { 1322 markOverdefined(&I); 1323 return true; 1324 } 1325 1326 Op1LV = getValueState(I.getOperand(1)); 1327 } 1328 // If this is an instructions whose result is defined even if the input is 1329 // not fully defined, propagate the information. 1330 Type *ITy = I.getType(); 1331 switch (I.getOpcode()) { 1332 case Instruction::Add: 1333 case Instruction::Sub: 1334 case Instruction::Trunc: 1335 case Instruction::FPTrunc: 1336 case Instruction::BitCast: 1337 break; // Any undef -> undef 1338 case Instruction::FSub: 1339 case Instruction::FAdd: 1340 case Instruction::FMul: 1341 case Instruction::FDiv: 1342 case Instruction::FRem: 1343 // Floating-point binary operation: be conservative. 1344 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1345 markForcedConstant(&I, Constant::getNullValue(ITy)); 1346 else 1347 markOverdefined(&I); 1348 return true; 1349 case Instruction::ZExt: 1350 case Instruction::SExt: 1351 case Instruction::FPToUI: 1352 case Instruction::FPToSI: 1353 case Instruction::FPExt: 1354 case Instruction::PtrToInt: 1355 case Instruction::IntToPtr: 1356 case Instruction::SIToFP: 1357 case Instruction::UIToFP: 1358 // undef -> 0; some outputs are impossible 1359 markForcedConstant(&I, Constant::getNullValue(ITy)); 1360 return true; 1361 case Instruction::Mul: 1362 case Instruction::And: 1363 // Both operands undef -> undef 1364 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1365 break; 1366 // undef * X -> 0. X could be zero. 1367 // undef & X -> 0. X could be zero. 1368 markForcedConstant(&I, Constant::getNullValue(ITy)); 1369 return true; 1370 1371 case Instruction::Or: 1372 // Both operands undef -> undef 1373 if (Op0LV.isUnknown() && Op1LV.isUnknown()) 1374 break; 1375 // undef | X -> -1. X could be -1. 1376 markForcedConstant(&I, Constant::getAllOnesValue(ITy)); 1377 return true; 1378 1379 case Instruction::Xor: 1380 // undef ^ undef -> 0; strictly speaking, this is not strictly 1381 // necessary, but we try to be nice to people who expect this 1382 // behavior in simple cases 1383 if (Op0LV.isUnknown() && Op1LV.isUnknown()) { 1384 markForcedConstant(&I, Constant::getNullValue(ITy)); 1385 return true; 1386 } 1387 // undef ^ X -> undef 1388 break; 1389 1390 case Instruction::SDiv: 1391 case Instruction::UDiv: 1392 case Instruction::SRem: 1393 case Instruction::URem: 1394 // X / undef -> undef. No change. 1395 // X % undef -> undef. No change. 1396 if (Op1LV.isUnknown()) break; 1397 1398 // X / 0 -> undef. No change. 1399 // X % 0 -> undef. No change. 1400 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue()) 1401 break; 1402 1403 // undef / X -> 0. X could be maxint. 1404 // undef % X -> 0. X could be 1. 1405 markForcedConstant(&I, Constant::getNullValue(ITy)); 1406 return true; 1407 1408 case Instruction::AShr: 1409 // X >>a undef -> undef. 1410 if (Op1LV.isUnknown()) break; 1411 1412 // Shifting by the bitwidth or more is undefined. 1413 if (Op1LV.isConstant()) { 1414 if (auto *ShiftAmt = Op1LV.getConstantInt()) 1415 if (ShiftAmt->getLimitedValue() >= 1416 ShiftAmt->getType()->getScalarSizeInBits()) 1417 break; 1418 } 1419 1420 // undef >>a X -> 0 1421 markForcedConstant(&I, Constant::getNullValue(ITy)); 1422 return true; 1423 case Instruction::LShr: 1424 case Instruction::Shl: 1425 // X << undef -> undef. 1426 // X >> undef -> undef. 1427 if (Op1LV.isUnknown()) break; 1428 1429 // Shifting by the bitwidth or more is undefined. 1430 if (Op1LV.isConstant()) { 1431 if (auto *ShiftAmt = Op1LV.getConstantInt()) 1432 if (ShiftAmt->getLimitedValue() >= 1433 ShiftAmt->getType()->getScalarSizeInBits()) 1434 break; 1435 } 1436 1437 // undef << X -> 0 1438 // undef >> X -> 0 1439 markForcedConstant(&I, Constant::getNullValue(ITy)); 1440 return true; 1441 case Instruction::Select: 1442 Op1LV = getValueState(I.getOperand(1)); 1443 // undef ? X : Y -> X or Y. There could be commonality between X/Y. 1444 if (Op0LV.isUnknown()) { 1445 if (!Op1LV.isConstant()) // Pick the constant one if there is any. 1446 Op1LV = getValueState(I.getOperand(2)); 1447 } else if (Op1LV.isUnknown()) { 1448 // c ? undef : undef -> undef. No change. 1449 Op1LV = getValueState(I.getOperand(2)); 1450 if (Op1LV.isUnknown()) 1451 break; 1452 // Otherwise, c ? undef : x -> x. 1453 } else { 1454 // Leave Op1LV as Operand(1)'s LatticeValue. 1455 } 1456 1457 if (Op1LV.isConstant()) 1458 markForcedConstant(&I, Op1LV.getConstant()); 1459 else 1460 markOverdefined(&I); 1461 return true; 1462 case Instruction::Load: 1463 // A load here means one of two things: a load of undef from a global, 1464 // a load from an unknown pointer. Either way, having it return undef 1465 // is okay. 1466 break; 1467 case Instruction::ICmp: 1468 // X == undef -> undef. Other comparisons get more complicated. 1469 if (cast<ICmpInst>(&I)->isEquality()) 1470 break; 1471 markOverdefined(&I); 1472 return true; 1473 case Instruction::Call: 1474 case Instruction::Invoke: { 1475 // There are two reasons a call can have an undef result 1476 // 1. It could be tracked. 1477 // 2. It could be constant-foldable. 1478 // Because of the way we solve return values, tracked calls must 1479 // never be marked overdefined in ResolvedUndefsIn. 1480 if (Function *F = CallSite(&I).getCalledFunction()) 1481 if (TrackedRetVals.count(F)) 1482 break; 1483 1484 // If the call is constant-foldable, we mark it overdefined because 1485 // we do not know what return values are valid. 1486 markOverdefined(&I); 1487 return true; 1488 } 1489 default: 1490 // If we don't know what should happen here, conservatively mark it 1491 // overdefined. 1492 markOverdefined(&I); 1493 return true; 1494 } 1495 } 1496 1497 // Check to see if we have a branch or switch on an undefined value. If so 1498 // we force the branch to go one way or the other to make the successor 1499 // values live. It doesn't really matter which way we force it. 1500 TerminatorInst *TI = BB.getTerminator(); 1501 if (auto *BI = dyn_cast<BranchInst>(TI)) { 1502 if (!BI->isConditional()) continue; 1503 if (!getValueState(BI->getCondition()).isUnknown()) 1504 continue; 1505 1506 // If the input to SCCP is actually branch on undef, fix the undef to 1507 // false. 1508 if (isa<UndefValue>(BI->getCondition())) { 1509 BI->setCondition(ConstantInt::getFalse(BI->getContext())); 1510 markEdgeExecutable(&BB, TI->getSuccessor(1)); 1511 return true; 1512 } 1513 1514 // Otherwise, it is a branch on a symbolic value which is currently 1515 // considered to be undef. Handle this by forcing the input value to the 1516 // branch to false. 1517 markForcedConstant(BI->getCondition(), 1518 ConstantInt::getFalse(TI->getContext())); 1519 return true; 1520 } 1521 1522 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) { 1523 // Indirect branch with no successor ?. Its ok to assume it branches 1524 // to no target. 1525 if (IBR->getNumSuccessors() < 1) 1526 continue; 1527 1528 if (!getValueState(IBR->getAddress()).isUnknown()) 1529 continue; 1530 1531 // If the input to SCCP is actually branch on undef, fix the undef to 1532 // the first successor of the indirect branch. 1533 if (isa<UndefValue>(IBR->getAddress())) { 1534 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0))); 1535 markEdgeExecutable(&BB, IBR->getSuccessor(0)); 1536 return true; 1537 } 1538 1539 // Otherwise, it is a branch on a symbolic value which is currently 1540 // considered to be undef. Handle this by forcing the input value to the 1541 // branch to the first successor. 1542 markForcedConstant(IBR->getAddress(), 1543 BlockAddress::get(IBR->getSuccessor(0))); 1544 return true; 1545 } 1546 1547 if (auto *SI = dyn_cast<SwitchInst>(TI)) { 1548 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown()) 1549 continue; 1550 1551 // If the input to SCCP is actually switch on undef, fix the undef to 1552 // the first constant. 1553 if (isa<UndefValue>(SI->getCondition())) { 1554 SI->setCondition(SI->case_begin()->getCaseValue()); 1555 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor()); 1556 return true; 1557 } 1558 1559 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue()); 1560 return true; 1561 } 1562 } 1563 1564 return false; 1565 } 1566 1567 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) { 1568 Constant *Const = nullptr; 1569 if (V->getType()->isStructTy()) { 1570 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V); 1571 if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); })) 1572 return false; 1573 std::vector<Constant *> ConstVals; 1574 auto *ST = dyn_cast<StructType>(V->getType()); 1575 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 1576 LatticeVal V = IVs[i]; 1577 ConstVals.push_back(V.isConstant() 1578 ? V.getConstant() 1579 : UndefValue::get(ST->getElementType(i))); 1580 } 1581 Const = ConstantStruct::get(ST, ConstVals); 1582 } else { 1583 LatticeVal IV = Solver.getLatticeValueFor(V); 1584 if (IV.isOverdefined()) 1585 return false; 1586 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType()); 1587 } 1588 assert(Const && "Constant is nullptr here!"); 1589 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n'); 1590 1591 // Replaces all of the uses of a variable with uses of the constant. 1592 V->replaceAllUsesWith(Const); 1593 return true; 1594 } 1595 1596 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm, 1597 // and return true if the function was modified. 1598 // 1599 static bool runSCCP(Function &F, const DataLayout &DL, 1600 const TargetLibraryInfo *TLI) { 1601 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n"); 1602 SCCPSolver Solver(DL, TLI); 1603 1604 // Mark the first block of the function as being executable. 1605 Solver.MarkBlockExecutable(&F.front()); 1606 1607 // Mark all arguments to the function as being overdefined. 1608 for (Argument &AI : F.args()) 1609 Solver.markOverdefined(&AI); 1610 1611 // Solve for constants. 1612 bool ResolvedUndefs = true; 1613 while (ResolvedUndefs) { 1614 Solver.Solve(); 1615 DEBUG(dbgs() << "RESOLVING UNDEFs\n"); 1616 ResolvedUndefs = Solver.ResolvedUndefsIn(F); 1617 } 1618 1619 bool MadeChanges = false; 1620 1621 // If we decided that there are basic blocks that are dead in this function, 1622 // delete their contents now. Note that we cannot actually delete the blocks, 1623 // as we cannot modify the CFG of the function. 1624 1625 for (BasicBlock &BB : F) { 1626 if (!Solver.isBlockExecutable(&BB)) { 1627 DEBUG(dbgs() << " BasicBlock Dead:" << BB); 1628 1629 ++NumDeadBlocks; 1630 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB); 1631 1632 MadeChanges = true; 1633 continue; 1634 } 1635 1636 // Iterate over all of the instructions in a function, replacing them with 1637 // constants if we have found them to be of constant values. 1638 // 1639 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) { 1640 Instruction *Inst = &*BI++; 1641 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst)) 1642 continue; 1643 1644 if (tryToReplaceWithConstant(Solver, Inst)) { 1645 if (isInstructionTriviallyDead(Inst)) 1646 Inst->eraseFromParent(); 1647 // Hey, we just changed something! 1648 MadeChanges = true; 1649 ++NumInstRemoved; 1650 } 1651 } 1652 } 1653 1654 return MadeChanges; 1655 } 1656 1657 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) { 1658 const DataLayout &DL = F.getParent()->getDataLayout(); 1659 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1660 if (!runSCCP(F, DL, &TLI)) 1661 return PreservedAnalyses::all(); 1662 1663 auto PA = PreservedAnalyses(); 1664 PA.preserve<GlobalsAA>(); 1665 return PA; 1666 } 1667 1668 namespace { 1669 //===--------------------------------------------------------------------===// 1670 // 1671 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 1672 /// Sparse Conditional Constant Propagator. 1673 /// 1674 class SCCPLegacyPass : public FunctionPass { 1675 public: 1676 void getAnalysisUsage(AnalysisUsage &AU) const override { 1677 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1678 AU.addPreserved<GlobalsAAWrapperPass>(); 1679 } 1680 static char ID; // Pass identification, replacement for typeid 1681 SCCPLegacyPass() : FunctionPass(ID) { 1682 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry()); 1683 } 1684 1685 // runOnFunction - Run the Sparse Conditional Constant Propagation 1686 // algorithm, and return true if the function was modified. 1687 // 1688 bool runOnFunction(Function &F) override { 1689 if (skipFunction(F)) 1690 return false; 1691 const DataLayout &DL = F.getParent()->getDataLayout(); 1692 const TargetLibraryInfo *TLI = 1693 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1694 return runSCCP(F, DL, TLI); 1695 } 1696 }; 1697 } // end anonymous namespace 1698 1699 char SCCPLegacyPass::ID = 0; 1700 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp", 1701 "Sparse Conditional Constant Propagation", false, false) 1702 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1703 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp", 1704 "Sparse Conditional Constant Propagation", false, false) 1705 1706 // createSCCPPass - This is the public interface to this file. 1707 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); } 1708 1709 static void findReturnsToZap(Function &F, 1710 SmallVector<ReturnInst *, 8> &ReturnsToZap, 1711 SCCPSolver &Solver) { 1712 // We can only do this if we know that nothing else can call the function. 1713 if (!Solver.isArgumentTrackedFunction(&F)) 1714 return; 1715 1716 for (BasicBlock &BB : F) 1717 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) 1718 if (!isa<UndefValue>(RI->getOperand(0))) 1719 ReturnsToZap.push_back(RI); 1720 } 1721 1722 static bool runIPSCCP(Module &M, const DataLayout &DL, 1723 const TargetLibraryInfo *TLI) { 1724 SCCPSolver Solver(DL, TLI); 1725 1726 // Loop over all functions, marking arguments to those with their addresses 1727 // taken or that are external as overdefined. 1728 // 1729 for (Function &F : M) { 1730 if (F.isDeclaration()) 1731 continue; 1732 1733 // Determine if we can track the function's return values. If so, add the 1734 // function to the solver's set of return-tracked functions. 1735 if (canTrackReturnsInterprocedurally(&F)) 1736 Solver.AddTrackedFunction(&F); 1737 1738 // Determine if we can track the function's arguments. If so, add the 1739 // function to the solver's set of argument-tracked functions. 1740 if (canTrackArgumentsInterprocedurally(&F)) { 1741 Solver.AddArgumentTrackedFunction(&F); 1742 continue; 1743 } 1744 1745 // Assume the function is called. 1746 Solver.MarkBlockExecutable(&F.front()); 1747 1748 // Assume nothing about the incoming arguments. 1749 for (Argument &AI : F.args()) 1750 Solver.markOverdefined(&AI); 1751 } 1752 1753 // Determine if we can track any of the module's global variables. If so, add 1754 // the global variables we can track to the solver's set of tracked global 1755 // variables. 1756 for (GlobalVariable &G : M.globals()) { 1757 G.removeDeadConstantUsers(); 1758 if (canTrackGlobalVariableInterprocedurally(&G)) 1759 Solver.TrackValueOfGlobalVariable(&G); 1760 } 1761 1762 // Solve for constants. 1763 bool ResolvedUndefs = true; 1764 while (ResolvedUndefs) { 1765 Solver.Solve(); 1766 1767 DEBUG(dbgs() << "RESOLVING UNDEFS\n"); 1768 ResolvedUndefs = false; 1769 for (Function &F : M) 1770 ResolvedUndefs |= Solver.ResolvedUndefsIn(F); 1771 } 1772 1773 bool MadeChanges = false; 1774 1775 // Iterate over all of the instructions in the module, replacing them with 1776 // constants if we have found them to be of constant values. 1777 // 1778 SmallVector<BasicBlock*, 512> BlocksToErase; 1779 1780 for (Function &F : M) { 1781 if (F.isDeclaration()) 1782 continue; 1783 1784 if (Solver.isBlockExecutable(&F.front())) 1785 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; 1786 ++AI) 1787 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) 1788 ++IPNumArgsElimed; 1789 1790 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1791 if (!Solver.isBlockExecutable(&*BB)) { 1792 DEBUG(dbgs() << " BasicBlock Dead:" << *BB); 1793 1794 ++NumDeadBlocks; 1795 NumInstRemoved += 1796 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false); 1797 1798 MadeChanges = true; 1799 1800 if (&*BB != &F.front()) 1801 BlocksToErase.push_back(&*BB); 1802 continue; 1803 } 1804 1805 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1806 Instruction *Inst = &*BI++; 1807 if (Inst->getType()->isVoidTy()) 1808 continue; 1809 if (tryToReplaceWithConstant(Solver, Inst)) { 1810 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst)) 1811 Inst->eraseFromParent(); 1812 // Hey, we just changed something! 1813 MadeChanges = true; 1814 ++IPNumInstRemoved; 1815 } 1816 } 1817 } 1818 1819 // Now that all instructions in the function are constant folded, erase dead 1820 // blocks, because we can now use ConstantFoldTerminator to get rid of 1821 // in-edges. 1822 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 1823 // If there are any PHI nodes in this successor, drop entries for BB now. 1824 BasicBlock *DeadBB = BlocksToErase[i]; 1825 for (Value::user_iterator UI = DeadBB->user_begin(), 1826 UE = DeadBB->user_end(); 1827 UI != UE;) { 1828 // Grab the user and then increment the iterator early, as the user 1829 // will be deleted. Step past all adjacent uses from the same user. 1830 auto *I = dyn_cast<Instruction>(*UI); 1831 do { ++UI; } while (UI != UE && *UI == I); 1832 1833 // Ignore blockaddress users; BasicBlock's dtor will handle them. 1834 if (!I) continue; 1835 1836 bool Folded = ConstantFoldTerminator(I->getParent()); 1837 assert(Folded && 1838 "Expect TermInst on constantint or blockaddress to be folded"); 1839 (void) Folded; 1840 } 1841 1842 // Finally, delete the basic block. 1843 F.getBasicBlockList().erase(DeadBB); 1844 } 1845 BlocksToErase.clear(); 1846 } 1847 1848 // If we inferred constant or undef return values for a function, we replaced 1849 // all call uses with the inferred value. This means we don't need to bother 1850 // actually returning anything from the function. Replace all return 1851 // instructions with return undef. 1852 // 1853 // Do this in two stages: first identify the functions we should process, then 1854 // actually zap their returns. This is important because we can only do this 1855 // if the address of the function isn't taken. In cases where a return is the 1856 // last use of a function, the order of processing functions would affect 1857 // whether other functions are optimizable. 1858 SmallVector<ReturnInst*, 8> ReturnsToZap; 1859 1860 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals(); 1861 for (const auto &I : RV) { 1862 Function *F = I.first; 1863 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy()) 1864 continue; 1865 findReturnsToZap(*F, ReturnsToZap, Solver); 1866 } 1867 1868 for (const auto &F : Solver.getMRVFunctionsTracked()) { 1869 assert(F->getReturnType()->isStructTy() && 1870 "The return type should be a struct"); 1871 StructType *STy = cast<StructType>(F->getReturnType()); 1872 if (Solver.isStructLatticeConstant(F, STy)) 1873 findReturnsToZap(*F, ReturnsToZap, Solver); 1874 } 1875 1876 // Zap all returns which we've identified as zap to change. 1877 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) { 1878 Function *F = ReturnsToZap[i]->getParent()->getParent(); 1879 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType())); 1880 } 1881 1882 // If we inferred constant or undef values for globals variables, we can 1883 // delete the global and any stores that remain to it. 1884 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 1885 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 1886 E = TG.end(); I != E; ++I) { 1887 GlobalVariable *GV = I->first; 1888 assert(!I->second.isOverdefined() && 1889 "Overdefined values should have been taken out of the map!"); 1890 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n"); 1891 while (!GV->use_empty()) { 1892 StoreInst *SI = cast<StoreInst>(GV->user_back()); 1893 SI->eraseFromParent(); 1894 } 1895 M.getGlobalList().erase(GV); 1896 ++IPNumGlobalConst; 1897 } 1898 1899 return MadeChanges; 1900 } 1901 1902 PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) { 1903 const DataLayout &DL = M.getDataLayout(); 1904 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M); 1905 if (!runIPSCCP(M, DL, &TLI)) 1906 return PreservedAnalyses::all(); 1907 return PreservedAnalyses::none(); 1908 } 1909 1910 namespace { 1911 //===--------------------------------------------------------------------===// 1912 // 1913 /// IPSCCP Class - This class implements interprocedural Sparse Conditional 1914 /// Constant Propagation. 1915 /// 1916 class IPSCCPLegacyPass : public ModulePass { 1917 public: 1918 static char ID; 1919 1920 IPSCCPLegacyPass() : ModulePass(ID) { 1921 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry()); 1922 } 1923 1924 bool runOnModule(Module &M) override { 1925 if (skipModule(M)) 1926 return false; 1927 const DataLayout &DL = M.getDataLayout(); 1928 const TargetLibraryInfo *TLI = 1929 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1930 return runIPSCCP(M, DL, TLI); 1931 } 1932 1933 void getAnalysisUsage(AnalysisUsage &AU) const override { 1934 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1935 } 1936 }; 1937 } // end anonymous namespace 1938 1939 char IPSCCPLegacyPass::ID = 0; 1940 INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp", 1941 "Interprocedural Sparse Conditional Constant Propagation", 1942 false, false) 1943 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1944 INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp", 1945 "Interprocedural Sparse Conditional Constant Propagation", 1946 false, false) 1947 1948 // createIPSCCPPass - This is the public interface to this file. 1949 ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); } 1950