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