SCCP.cpp revision fd93908ae8b9684fe71c239e3c6cfe13ff6a2663
17baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 27aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan// 37baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// The LLVM Compiler Infrastructure 47baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 57baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// This file was developed by the LLVM research group and is distributed under 67baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// the University of Illinois Open Source License. See LICENSE.TXT for details. 77baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 87baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan//===----------------------------------------------------------------------===// 9159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan// 10159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan// This file implements sparse conditional constant propagation and merging: 11159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan// 127baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// Specifically, this: 137baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// * Assumes values are constant unless proven otherwise 147baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// * Assumes BasicBlocks are dead unless proven otherwise 157baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// * Proves values to be constant, and replaces them with constants 16907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan// * Proves conditional branches to be unconditional 177baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 187baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// Notice that: 19c2a25909b2c4d989e49cdedcac4dd52c45f0570bAndrew G. Morgan// * This pass has a habit of making definitions be dead. It is a good idea 207baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// to to run a DCE pass sometime after running this pass. 217baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 227baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan//===----------------------------------------------------------------------===// 237baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 247baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#define DEBUG_TYPE "sccp" 257baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/Transforms/Scalar.h" 2632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan#include "llvm/Transforms/IPO.h" 2732423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan#include "llvm/Constants.h" 283f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan#include "llvm/DerivedTypes.h" 297baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/Instructions.h" 307baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/Pass.h" 313f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan#include "llvm/Support/InstVisitor.h" 3232423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan#include "llvm/Transforms/Utils/Local.h" 3332423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan#include "llvm/Support/CallSite.h" 347baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/Support/Debug.h" 357baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/ADT/hash_map" 363f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan#include "llvm/ADT/Statistic.h" 377baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include "llvm/ADT/STLExtras.h" 387baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan#include <algorithm> 393f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan#include <set> 4032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morganusing namespace llvm; 417baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 427baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// LatticeVal class - This class represents the different lattice values that an 437baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// instruction may occupy. It is a simple class with value semantics. 447baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 457baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgannamespace { 467baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 477baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morganclass LatticeVal { 487baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan enum { 497baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan undefined, // This instruction has no known value 507baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan constant, // This instruction has a constant value 517baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan overdefined // This instruction has an unknown value 527baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } LatticeValue; // The current lattice position 537baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan Constant *ConstantVal; // If Constant value, the current value 543f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morganpublic: 5532423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {} 5632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan 5732423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // markOverdefined - Return true if this is a new status to be in... 583f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan inline bool markOverdefined() { 5932423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan if (LatticeValue != overdefined) { 6032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan LatticeValue = overdefined; 6132423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan return true; 6232423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan } 637baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return false; 647baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 65ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan 66ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan // markConstant - Return true if this is a new status for us... 67ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan inline bool markConstant(Constant *V) { 68ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan if (LatticeValue != constant) { 69ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan LatticeValue = constant; 70ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan ConstantVal = V; 71ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan return true; 72ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan } else { 73c2a25909b2c4d989e49cdedcac4dd52c45f0570bAndrew G. Morgan assert(ConstantVal == V && "Marking constant with different value"); 747baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 75ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan return false; 767baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 777baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 783184213774c3fb3e467c7bea080a88f6b984b4e4Andrew G. Morgan inline bool isUndefined() const { return LatticeValue == undefined; } 797aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan inline bool isConstant() const { return LatticeValue == constant; } 807aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan inline bool isOverdefined() const { return LatticeValue == overdefined; } 817aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan 827aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan inline Constant *getConstant() const { 837aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan assert(isConstant() && "Cannot get the constant of a non-constant!"); 847aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan return ConstantVal; 857aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan } 86159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan}; 87159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan 88159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan} // end anonymous namespace 89159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan 907aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan 917aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan//===----------------------------------------------------------------------===// 927aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan// 937aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan/// SCCPSolver - This class is a general purpose solver for Sparse Conditional 947aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan/// Constant Propagation. 957aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan/// 967baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morganclass SCCPSolver : public InstVisitor<SCCPSolver> { 973184213774c3fb3e467c7bea080a88f6b984b4e4Andrew G. Morgan std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable 98159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan hash_map<Value*, LatticeVal> ValueState; // The state each value is in... 997baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 100ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan /// GlobalValue - If we are tracking any values for the contents of a global 1017baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// variable, we keep a mapping from the constant accessor to the element of 1027baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// the global, to the currently known value. If the value becomes 1037baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// overdefined, it's entry is simply removed from this map. 1047aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan hash_map<GlobalVariable*, LatticeVal> TrackedGlobals; 1057aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan 1067aff2edf61f96087e7ac47def97acb638bb7bca2Andrew G. Morgan /// TrackedFunctionRetVals - If we are tracking arguments into and the return 1077baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// value out of a function, it will have an entry in this map, indicating 1087baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// what the known return value for the function is. 1097baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan hash_map<Function*, LatticeVal> TrackedFunctionRetVals; 1107baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1117baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // The reason for two worklists is that overdefined is the lowest state 1127baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // on the lattice, and moving things to overdefined as fast as possible 1137baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // makes SCCP converge much faster. 1143f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan // By having a separate worklist, we accomplish this because everything 1157baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // possibly overdefined will become overdefined at the soonest possible 1167baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // point. 1177baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan std::vector<Value*> OverdefinedInstWorkList; 1187baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan std::vector<Value*> InstWorkList; 1197baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1207baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1217baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list 1227baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1237baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not 12432423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// overdefined, despite the fact that the PHI node is overdefined. 1253f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs; 1263f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan 1273f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan /// KnownFeasibleEdges - Entries in this set are edges which have already had 1283f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan /// PHI nodes retriggered. 1293f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan typedef std::pair<BasicBlock*,BasicBlock*> Edge; 1303f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan std::set<Edge> KnownFeasibleEdges; 1313f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morganpublic: 132d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan 133d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan /// MarkBlockExecutable - This method can be used by clients to mark all of 134d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan /// the blocks that are known to be intrinsically live in the processed unit. 1353f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void MarkBlockExecutable(BasicBlock *BB) { 1363f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n"); 1373f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan BBExecutable.insert(BB); // Basic block is executable! 1383f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan BBWorkList.push_back(BB); // Add the block to the work list! 1393f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan } 1407baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1417baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// TrackValueOfGlobalVariable - Clients can use this method to 1427baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// inform the SCCPSolver that it should track loads and stores to the 14332423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// specified global variable if it can. This is only legal to call if 1447baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// performing Interprocedural SCCP. 1457baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void TrackValueOfGlobalVariable(GlobalVariable *GV) { 14632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan const Type *ElTy = GV->getType()->getElementType(); 1473f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan if (ElTy->isFirstClassType()) { 1487baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan LatticeVal &IV = TrackedGlobals[GV]; 1497baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (!isa<UndefValue>(GV->getInitializer())) 1507baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan IV.markConstant(GV->getInitializer()); 1517baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 1527baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 15332423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan 15432423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 15532423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// and out of the specified function (which cannot have its address taken), 15632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// this method must be called. 1577baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void AddTrackedFunction(Function *F) { 1587baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan assert(F->hasInternalLinkage() && "Can only track internal functions!"); 1597baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Add an entry, F -> undef. 1607baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan TrackedFunctionRetVals[F]; 1617baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 1627baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1637baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// Solve - Solve for constants and executable blocks. 1647baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// 1653f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void Solve(); 1667baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1677baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// ResolveBranchesIn - While solving the dataflow for a function, we assume 1687baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// that branches on undef values cannot reach any of their successors. 1697baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// However, this is not a safe assumption. After we solve dataflow, this 17032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// method should be use to handle this. If this returns true, the solver 1717baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// should be rerun. 1727baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan bool ResolveBranchesIn(Function &F); 1737baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1747baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// getExecutableBlocks - Once we have solved for constants, return the set of 1757baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// blocks that is known to be executable. 1767baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan std::set<BasicBlock*> &getExecutableBlocks() { 1777baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return BBExecutable; 17832423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan } 1797baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 18032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan /// getValueMapping - Once we have solved for constants, return the mapping of 1813f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan /// LLVM values to LatticeVals. 18232423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan hash_map<Value*, LatticeVal> &getValueMapping() { 1837baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return ValueState; 1847baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 1857baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1867baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// getTrackedFunctionRetVals - Get the inferred return value map. 1877baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// 1887baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() { 1897baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return TrackedFunctionRetVals; 1907baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 1917baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1927baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// getTrackedGlobals - Get and return the set of inferred initializers for 1937baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan /// global variables. 1947baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 1957baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return TrackedGlobals; 1967baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 1977baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1987baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 1997baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morganprivate: 2007baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // markConstant - Make a value be marked as "constant". If the value 2017baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // is not already a constant, add it to the instruction work list so that 2027baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // the users of the instruction are updated later. 2037baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // 2047baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline void markConstant(LatticeVal &IV, Value *V, Constant *C) { 2057baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (IV.markConstant(C)) { 2067baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan DEBUG(std::cerr << "markConstant: " << *C << ": " << *V); 2077baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan InstWorkList.push_back(V); 2087baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2097baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2107baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline void markConstant(Value *V, Constant *C) { 2117baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan markConstant(ValueState[V], V, C); 2127baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2137baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 2147baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // markOverdefined - Make a value be marked as "overdefined". If the 2157baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // value is not already overdefined, add it to the overdefined instruction 2167baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // work list so that the users of the instruction are updated later. 2177baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 2187baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline void markOverdefined(LatticeVal &IV, Value *V) { 2197baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (IV.markOverdefined()) { 2203f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan DEBUG(std::cerr << "markOverdefined: "; 2213f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan if (Function *F = dyn_cast<Function>(V)) 2223f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan std::cerr << "Function '" << F->getName() << "'\n"; 2237baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan else 2247baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan std::cerr << *V); 22532423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // Only instructions go on the work list 2267baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan OverdefinedInstWorkList.push_back(V); 2277baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2283f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan } 2297baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline void markOverdefined(Value *V) { 2303f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan markOverdefined(ValueState[V], V); 23132423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan } 2323f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan 2337baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) { 2347baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (IV.isOverdefined() || MergeWithV.isUndefined()) 2357baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return; // Noop. 23632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan if (MergeWithV.isOverdefined()) 2373f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan markOverdefined(IV, V); 2387baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan else if (IV.isUndefined()) 2393f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan markConstant(IV, V, MergeWithV.getConstant()); 24032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan else if (IV.getConstant() != MergeWithV.getConstant()) 2413f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan markOverdefined(IV, V); 2427baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2437baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 2447baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // getValueState - Return the LatticeVal object that corresponds to the value. 2457baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // This function is necessary because not all values should start out in the 2467baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // underdefined state... Argument's should be overdefined, and 2477baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // constants should be marked as constants. If a value is not known to be an 2487baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Instruction object, then use this accessor to get its value from the map. 2497baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // 2507baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan inline LatticeVal &getValueState(Value *V) { 2517baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V); 2527baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (I != ValueState.end()) return I->second; // Common case, in the map 2537baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 2547baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (Constant *CPV = dyn_cast<Constant>(V)) { 2557baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (isa<UndefValue>(V)) { 2567baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Nothing to do, remain undefined. 2577baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } else { 2587baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan ValueState[CPV].markConstant(CPV); // Constants are constant 2597baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 2607baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 261ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan // All others are underdefined by default... 262ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan return ValueState[V]; 2637baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 264ec25bd9b420ab62bcc3ec709f467eb43d434b66dAndrew Morgan 2657baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // markEdgeExecutable - Mark a basic block as executable, adding it to the BB 2667baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // work list if it is not already executable... 2677baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // 268907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 269907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 270907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan return; // This edge is already known to be executable! 271907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan 272907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan if (BBExecutable.count(Dest)) { 273907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName() 274597369a007f20080e13ffbe3a4dfed38897c7edcAndrew G. Morgan << " -> " << Dest->getName() << "\n"); 275907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan 276907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // The destination is already executable, but we just made an edge 277907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // feasible that wasn't before. Revisit the PHI nodes in the block 278907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // because they have potentially new operands. 279907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) 280907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan visitPHINode(*cast<PHINode>(I)); 281907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan 282907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan } else { 283907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan MarkBlockExecutable(Dest); 284907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan } 285907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan } 286907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan 287907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // getFeasibleSuccessors - Return a vector of booleans to indicate which 288907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // successors are reachable from a given terminator instruction. 289159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan // 290907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs); 2913184213774c3fb3e467c7bea080a88f6b984b4e4Andrew G. Morgan 292159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 293159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan // block to the 'To' basic block is currently feasible... 294159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan // 295159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 296907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan 297907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // OperandChangedState - This method is invoked on all of the users of an 298907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // instruction that was just changed state somehow.... Based on this 299907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // information, we need to update the specified user of this instruction. 300907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan // 301907393e8d611fc887440d77335bc87adc0bed0bdAndrew G. Morgan void OperandChangedState(User *U) { 3027baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Only instructions use other variable values! 3037baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan Instruction &I = cast<Instruction>(*U); 3047baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (BBExecutable.count(I.getParent())) // Inst is executable? 3057baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan visit(I); 3067baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 3077baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 3087baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morganprivate: 3097baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan friend class InstVisitor<SCCPSolver>; 3107baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 31132423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // visit implementations - Something changed in this instruction... Either an 3127baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // operand made a transition, or the instruction is newly executable. Change 31332423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // the value type of I to reflect these changes if appropriate. 31432423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // 3157baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitPHINode(PHINode &I); 31632423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan 31732423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan // Terminators 31832423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan void visitReturnInst(ReturnInst &I); 31932423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan void visitTerminatorInst(TerminatorInst &TI); 3207baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 3217baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitCastInst(CastInst &I); 3227baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitSelectInst(SelectInst &I); 3237baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitBinaryOperator(Instruction &I); 3247baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); } 3257baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 3267baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Instructions that cannot be folded away... 3277baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitStoreInst (Instruction &I); 3283f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void visitLoadInst (LoadInst &I); 3297baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitGetElementPtrInst(GetElementPtrInst &I); 3303f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); } 331c2a25909b2c4d989e49cdedcac4dd52c45f0570bAndrew G. Morgan void visitInvokeInst (InvokeInst &II) { 332c2a25909b2c4d989e49cdedcac4dd52c45f0570bAndrew G. Morgan visitCallSite(CallSite::get(&II)); 3333f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan visitTerminatorInst(II); 3347baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 3357baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitCallSite (CallSite CS); 3362153ffce3a55344869504792a7aaf365990cc3f0Andrew Morgan void visitUnwindInst (TerminatorInst &I) { /*returns void*/ } 3377baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 3387baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitAllocationInst(Instruction &I) { markOverdefined(&I); } 3397baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitVANextInst (Instruction &I) { markOverdefined(&I); } 3407baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan void visitVAArgInst (Instruction &I) { markOverdefined(&I); } 3413f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void visitFreeInst (Instruction &I) { /*returns void*/ } 3423f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan 3433f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan void visitInstruction(Instruction &I) { 3443f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan // If a new instruction is added to LLVM that we don't handle... 3453f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan std::cerr << "SCCP: Don't know how to handle: " << I; 3463f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan markOverdefined(&I); // Just in case 3473f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan } 348d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan}; 349d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan 350d62769b6fc69244bd9922b018787d8bb7e332118Andrew G. Morgan// getFeasibleSuccessors - Return a vector of booleans to indicate which 3513f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan// successors are reachable from a given terminator instruction. 3523f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan// 3533f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morganvoid SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 3543f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan std::vector<bool> &Succs) { 3553f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan Succs.resize(TI.getNumSuccessors()); 3563f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) { 3573f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan if (BI->isUnconditional()) { 35832423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan Succs[0] = true; 35932423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan } else { 36032423d46c83c639c2df7db7ee74b8ec7be2b1234Andrew Morgan LatticeVal &BCValue = getValueState(BI->getCondition()); 3617baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (BCValue.isOverdefined() || 3623f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) { 3633f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan // Overdefined condition variables, and branches on unfoldable constant 364e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan // conditions, mean the branch could go either way. 365e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan Succs[0] = Succs[1] = true; 3667baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } else if (BCValue.isConstant()) { 3677baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Constant condition variables mean the branch can only go a single way 368d718c084e9f95b793d16a66788670610a37774f9Andrew G. Morgan Succs[BCValue.getConstant() == ConstantBool::False] = true; 369d718c084e9f95b793d16a66788670610a37774f9Andrew G. Morgan } 370d718c084e9f95b793d16a66788670610a37774f9Andrew G. Morgan } 371d718c084e9f95b793d16a66788670610a37774f9Andrew G. Morgan } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) { 3727baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Invoke instructions successors are always executable. 373d718c084e9f95b793d16a66788670610a37774f9Andrew G. Morgan Succs[0] = Succs[1] = true; 3747baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) { 3757baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan LatticeVal &SCValue = getValueState(SI->getCondition()); 376e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan if (SCValue.isOverdefined() || // Overdefined condition? 377e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) { 378e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan // All destinations are executable! 379e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan Succs.assign(TI.getNumSuccessors(), true); 380e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan } else if (SCValue.isConstant()) { 381e482cc22ad687f50882f0029ed4b9adebb01911cAndrew G. Morgan Constant *CPV = SCValue.getConstant(); 3827baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Make sure to skip the "default value" which isn't a value 3837baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) { 3847baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (SI->getSuccessorValue(i) == CPV) {// Found the right branch... 3857baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan Succs[i] = true; 3867baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return; 3877baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 3887baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 3897baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 3907baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Constant value not equal to any of the branches... must execute 3913f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan // default branch then... 3927baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan Succs[0] = true; 393159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan } 394159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan } else { 395159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan std::cerr << "SCCP: Don't know how to handle: " << TI; 3963f7da3c2259741354f4e55105c466ae1443a0490Andrew G. Morgan Succs.assign(TI.getNumSuccessors(), true); 397159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan } 3987baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan} 3997baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 4007baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 401159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan// isEdgeFeasible - Return true if the control flow edge from the 'From' basic 402159fc80362a68a54ca72d1a0419975ac76333d4bAndrew G. Morgan// block to the 'To' basic block is currently feasible... 4037baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan// 4047baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morganbool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 4057baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan assert(BBExecutable.count(To) && "Dest should always be alive!"); 4067baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 4077baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Make sure the source basic block is executable!! 4087baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (!BBExecutable.count(From)) return false; 4097baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 4107baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Check to make sure this edge itself is actually feasible now... 4117baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan TerminatorInst *TI = From->getTerminator(); 4127baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 4137baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (BI->isUnconditional()) 4147baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return true; 4157baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan else { 4167baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan LatticeVal &BCValue = getValueState(BI->getCondition()); 4177baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (BCValue.isOverdefined()) { 4187baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Overdefined condition variables mean the branch could go either way. 4197baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan return true; 4207baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } else if (BCValue.isConstant()) { 4217baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan // Not branching on an evaluatable constant? 4227baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan if (!isa<ConstantBool>(BCValue.getConstant())) return true; 4237baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan 4242153ffce3a55344869504792a7aaf365990cc3f0Andrew Morgan // Constant condition variables mean the branch can only go a single way 4252153ffce3a55344869504792a7aaf365990cc3f0Andrew Morgan return BI->getSuccessor(BCValue.getConstant() == 4262153ffce3a55344869504792a7aaf365990cc3f0Andrew Morgan ConstantBool::False) == To; 4272153ffce3a55344869504792a7aaf365990cc3f0Andrew Morgan } 428f9c44c45c23630bcf24135d7972a298aad5949eaAndrew Morgan return false; 4297baf3be8302d9a7ba63c8c57131ecbc3fbd6d3ebAndrew Morgan } 430 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { 431 // Invoke instructions successors are always executable. 432 return true; 433 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 434 LatticeVal &SCValue = getValueState(SI->getCondition()); 435 if (SCValue.isOverdefined()) { // Overdefined condition? 436 // All destinations are executable! 437 return true; 438 } else if (SCValue.isConstant()) { 439 Constant *CPV = SCValue.getConstant(); 440 if (!isa<ConstantInt>(CPV)) 441 return true; // not a foldable constant? 442 443 // Make sure to skip the "default value" which isn't a value 444 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) 445 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch... 446 return SI->getSuccessor(i) == To; 447 448 // Constant value not equal to any of the branches... must execute 449 // default branch then... 450 return SI->getDefaultDest() == To; 451 } 452 return false; 453 } else { 454 std::cerr << "Unknown terminator instruction: " << *TI; 455 abort(); 456 } 457} 458 459// visit Implementations - Something changed in this instruction... Either an 460// operand made a transition, or the instruction is newly executable. Change 461// the value type of I to reflect these changes if appropriate. This method 462// makes sure to do the following actions: 463// 464// 1. If a phi node merges two constants in, and has conflicting value coming 465// from different branches, or if the PHI node merges in an overdefined 466// value, then the PHI node becomes overdefined. 467// 2. If a phi node merges only constants in, and they all agree on value, the 468// PHI node becomes a constant value equal to that. 469// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 470// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 471// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 472// 6. If a conditional branch has a value that is constant, make the selected 473// destination executable 474// 7. If a conditional branch has a value that is overdefined, make all 475// successors executable. 476// 477void SCCPSolver::visitPHINode(PHINode &PN) { 478 LatticeVal &PNIV = getValueState(&PN); 479 if (PNIV.isOverdefined()) { 480 // There may be instructions using this PHI node that are not overdefined 481 // themselves. If so, make sure that they know that the PHI node operand 482 // changed. 483 std::multimap<PHINode*, Instruction*>::iterator I, E; 484 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN); 485 if (I != E) { 486 std::vector<Instruction*> Users; 487 Users.reserve(std::distance(I, E)); 488 for (; I != E; ++I) Users.push_back(I->second); 489 while (!Users.empty()) { 490 visit(Users.back()); 491 Users.pop_back(); 492 } 493 } 494 return; // Quick exit 495 } 496 497 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 498 // and slow us down a lot. Just mark them overdefined. 499 if (PN.getNumIncomingValues() > 64) { 500 markOverdefined(PNIV, &PN); 501 return; 502 } 503 504 // Look at all of the executable operands of the PHI node. If any of them 505 // are overdefined, the PHI becomes overdefined as well. If they are all 506 // constant, and they agree with each other, the PHI becomes the identical 507 // constant. If they are constant and don't agree, the PHI is overdefined. 508 // If there are no executable operands, the PHI remains undefined. 509 // 510 Constant *OperandVal = 0; 511 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 512 LatticeVal &IV = getValueState(PN.getIncomingValue(i)); 513 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 514 515 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) { 516 if (IV.isOverdefined()) { // PHI node becomes overdefined! 517 markOverdefined(PNIV, &PN); 518 return; 519 } 520 521 if (OperandVal == 0) { // Grab the first value... 522 OperandVal = IV.getConstant(); 523 } else { // Another value is being merged in! 524 // There is already a reachable operand. If we conflict with it, 525 // then the PHI node becomes overdefined. If we agree with it, we 526 // can continue on. 527 528 // Check to see if there are two different constants merging... 529 if (IV.getConstant() != OperandVal) { 530 // Yes there is. This means the PHI node is not constant. 531 // You must be overdefined poor PHI. 532 // 533 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined 534 return; // I'm done analyzing you 535 } 536 } 537 } 538 } 539 540 // If we exited the loop, this means that the PHI node only has constant 541 // arguments that agree with each other(and OperandVal is the constant) or 542 // OperandVal is null because there are no defined incoming arguments. If 543 // this is the case, the PHI remains undefined. 544 // 545 if (OperandVal) 546 markConstant(PNIV, &PN, OperandVal); // Acquire operand value 547} 548 549void SCCPSolver::visitReturnInst(ReturnInst &I) { 550 if (I.getNumOperands() == 0) return; // Ret void 551 552 // If we are tracking the return value of this function, merge it in. 553 Function *F = I.getParent()->getParent(); 554 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) { 555 hash_map<Function*, LatticeVal>::iterator TFRVI = 556 TrackedFunctionRetVals.find(F); 557 if (TFRVI != TrackedFunctionRetVals.end() && 558 !TFRVI->second.isOverdefined()) { 559 LatticeVal &IV = getValueState(I.getOperand(0)); 560 mergeInValue(TFRVI->second, F, IV); 561 } 562 } 563} 564 565 566void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 567 std::vector<bool> SuccFeasible; 568 getFeasibleSuccessors(TI, SuccFeasible); 569 570 BasicBlock *BB = TI.getParent(); 571 572 // Mark all feasible successors executable... 573 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 574 if (SuccFeasible[i]) 575 markEdgeExecutable(BB, TI.getSuccessor(i)); 576} 577 578void SCCPSolver::visitCastInst(CastInst &I) { 579 Value *V = I.getOperand(0); 580 LatticeVal &VState = getValueState(V); 581 if (VState.isOverdefined()) // Inherit overdefinedness of operand 582 markOverdefined(&I); 583 else if (VState.isConstant()) // Propagate constant value 584 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType())); 585} 586 587void SCCPSolver::visitSelectInst(SelectInst &I) { 588 LatticeVal &CondValue = getValueState(I.getCondition()); 589 if (CondValue.isOverdefined()) 590 markOverdefined(&I); 591 else if (CondValue.isConstant()) { 592 if (CondValue.getConstant() == ConstantBool::True) { 593 LatticeVal &Val = getValueState(I.getTrueValue()); 594 if (Val.isOverdefined()) 595 markOverdefined(&I); 596 else if (Val.isConstant()) 597 markConstant(&I, Val.getConstant()); 598 } else if (CondValue.getConstant() == ConstantBool::False) { 599 LatticeVal &Val = getValueState(I.getFalseValue()); 600 if (Val.isOverdefined()) 601 markOverdefined(&I); 602 else if (Val.isConstant()) 603 markConstant(&I, Val.getConstant()); 604 } else 605 markOverdefined(&I); 606 } 607} 608 609// Handle BinaryOperators and Shift Instructions... 610void SCCPSolver::visitBinaryOperator(Instruction &I) { 611 LatticeVal &IV = ValueState[&I]; 612 if (IV.isOverdefined()) return; 613 614 LatticeVal &V1State = getValueState(I.getOperand(0)); 615 LatticeVal &V2State = getValueState(I.getOperand(1)); 616 617 if (V1State.isOverdefined() || V2State.isOverdefined()) { 618 // If this is an AND or OR with 0 or -1, it doesn't matter that the other 619 // operand is overdefined. 620 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) { 621 LatticeVal *NonOverdefVal = 0; 622 if (!V1State.isOverdefined()) { 623 NonOverdefVal = &V1State; 624 } else if (!V2State.isOverdefined()) { 625 NonOverdefVal = &V2State; 626 } 627 628 if (NonOverdefVal) { 629 if (NonOverdefVal->isUndefined()) { 630 // Could annihilate value. 631 if (I.getOpcode() == Instruction::And) 632 markConstant(IV, &I, Constant::getNullValue(I.getType())); 633 else 634 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType())); 635 return; 636 } else { 637 if (I.getOpcode() == Instruction::And) { 638 if (NonOverdefVal->getConstant()->isNullValue()) { 639 markConstant(IV, &I, NonOverdefVal->getConstant()); 640 return; // X or 0 = -1 641 } 642 } else { 643 if (ConstantIntegral *CI = 644 dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant())) 645 if (CI->isAllOnesValue()) { 646 markConstant(IV, &I, NonOverdefVal->getConstant()); 647 return; // X or -1 = -1 648 } 649 } 650 } 651 } 652 } 653 654 655 // If both operands are PHI nodes, it is possible that this instruction has 656 // a constant value, despite the fact that the PHI node doesn't. Check for 657 // this condition now. 658 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0))) 659 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1))) 660 if (PN1->getParent() == PN2->getParent()) { 661 // Since the two PHI nodes are in the same basic block, they must have 662 // entries for the same predecessors. Walk the predecessor list, and 663 // if all of the incoming values are constants, and the result of 664 // evaluating this expression with all incoming value pairs is the 665 // same, then this expression is a constant even though the PHI node 666 // is not a constant! 667 LatticeVal Result; 668 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) { 669 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i)); 670 BasicBlock *InBlock = PN1->getIncomingBlock(i); 671 LatticeVal &In2 = 672 getValueState(PN2->getIncomingValueForBlock(InBlock)); 673 674 if (In1.isOverdefined() || In2.isOverdefined()) { 675 Result.markOverdefined(); 676 break; // Cannot fold this operation over the PHI nodes! 677 } else if (In1.isConstant() && In2.isConstant()) { 678 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(), 679 In2.getConstant()); 680 if (Result.isUndefined()) 681 Result.markConstant(V); 682 else if (Result.isConstant() && Result.getConstant() != V) { 683 Result.markOverdefined(); 684 break; 685 } 686 } 687 } 688 689 // If we found a constant value here, then we know the instruction is 690 // constant despite the fact that the PHI nodes are overdefined. 691 if (Result.isConstant()) { 692 markConstant(IV, &I, Result.getConstant()); 693 // Remember that this instruction is virtually using the PHI node 694 // operands. 695 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I)); 696 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I)); 697 return; 698 } else if (Result.isUndefined()) { 699 return; 700 } 701 702 // Okay, this really is overdefined now. Since we might have 703 // speculatively thought that this was not overdefined before, and 704 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs, 705 // make sure to clean out any entries that we put there, for 706 // efficiency. 707 std::multimap<PHINode*, Instruction*>::iterator It, E; 708 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1); 709 while (It != E) { 710 if (It->second == &I) { 711 UsersOfOverdefinedPHIs.erase(It++); 712 } else 713 ++It; 714 } 715 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2); 716 while (It != E) { 717 if (It->second == &I) { 718 UsersOfOverdefinedPHIs.erase(It++); 719 } else 720 ++It; 721 } 722 } 723 724 markOverdefined(IV, &I); 725 } else if (V1State.isConstant() && V2State.isConstant()) { 726 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(), 727 V2State.getConstant())); 728 } 729} 730 731// Handle getelementptr instructions... if all operands are constants then we 732// can turn this into a getelementptr ConstantExpr. 733// 734void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 735 LatticeVal &IV = ValueState[&I]; 736 if (IV.isOverdefined()) return; 737 738 std::vector<Constant*> Operands; 739 Operands.reserve(I.getNumOperands()); 740 741 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 742 LatticeVal &State = getValueState(I.getOperand(i)); 743 if (State.isUndefined()) 744 return; // Operands are not resolved yet... 745 else if (State.isOverdefined()) { 746 markOverdefined(IV, &I); 747 return; 748 } 749 assert(State.isConstant() && "Unknown state!"); 750 Operands.push_back(State.getConstant()); 751 } 752 753 Constant *Ptr = Operands[0]; 754 Operands.erase(Operands.begin()); // Erase the pointer from idx list... 755 756 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands)); 757} 758 759/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr, 760/// return the constant value being addressed by the constant expression, or 761/// null if something is funny. 762/// 763static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) { 764 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) 765 return 0; // Do not allow stepping over the value! 766 767 // Loop over all of the operands, tracking down which value we are 768 // addressing... 769 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) 770 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) { 771 ConstantStruct *CS = dyn_cast<ConstantStruct>(C); 772 if (CS == 0) return 0; 773 if (CU->getValue() >= CS->getNumOperands()) return 0; 774 C = CS->getOperand((unsigned)CU->getValue()); 775 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) { 776 ConstantArray *CA = dyn_cast<ConstantArray>(C); 777 if (CA == 0) return 0; 778 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0; 779 C = CA->getOperand((unsigned)CS->getValue()); 780 } else 781 return 0; 782 return C; 783} 784 785void SCCPSolver::visitStoreInst(Instruction &SI) { 786 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 787 return; 788 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 789 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 790 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 791 792 // Get the value we are storing into the global. 793 LatticeVal &PtrVal = getValueState(SI.getOperand(0)); 794 795 mergeInValue(I->second, GV, PtrVal); 796 if (I->second.isOverdefined()) 797 TrackedGlobals.erase(I); // No need to keep tracking this! 798} 799 800 801// Handle load instructions. If the operand is a constant pointer to a constant 802// global, we can replace the load with the loaded constant value! 803void SCCPSolver::visitLoadInst(LoadInst &I) { 804 LatticeVal &IV = ValueState[&I]; 805 if (IV.isOverdefined()) return; 806 807 LatticeVal &PtrVal = getValueState(I.getOperand(0)); 808 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet! 809 if (PtrVal.isConstant() && !I.isVolatile()) { 810 Value *Ptr = PtrVal.getConstant(); 811 if (isa<ConstantPointerNull>(Ptr)) { 812 // load null -> null 813 markConstant(IV, &I, Constant::getNullValue(I.getType())); 814 return; 815 } 816 817 // Transform load (constant global) into the value loaded. 818 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { 819 if (GV->isConstant()) { 820 if (!GV->isExternal()) { 821 markConstant(IV, &I, GV->getInitializer()); 822 return; 823 } 824 } else if (!TrackedGlobals.empty()) { 825 // If we are tracking this global, merge in the known value for it. 826 hash_map<GlobalVariable*, LatticeVal>::iterator It = 827 TrackedGlobals.find(GV); 828 if (It != TrackedGlobals.end()) { 829 mergeInValue(IV, &I, It->second); 830 return; 831 } 832 } 833 } 834 835 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded. 836 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) 837 if (CE->getOpcode() == Instruction::GetElementPtr) 838 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) 839 if (GV->isConstant() && !GV->isExternal()) 840 if (Constant *V = 841 GetGEPGlobalInitializer(GV->getInitializer(), CE)) { 842 markConstant(IV, &I, V); 843 return; 844 } 845 } 846 847 // Otherwise we cannot say for certain what value this load will produce. 848 // Bail out. 849 markOverdefined(IV, &I); 850} 851 852void SCCPSolver::visitCallSite(CallSite CS) { 853 Function *F = CS.getCalledFunction(); 854 855 // If we are tracking this function, we must make sure to bind arguments as 856 // appropriate. 857 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end(); 858 if (F && F->hasInternalLinkage()) 859 TFRVI = TrackedFunctionRetVals.find(F); 860 861 if (TFRVI != TrackedFunctionRetVals.end()) { 862 // If this is the first call to the function hit, mark its entry block 863 // executable. 864 if (!BBExecutable.count(F->begin())) 865 MarkBlockExecutable(F->begin()); 866 867 CallSite::arg_iterator CAI = CS.arg_begin(); 868 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 869 AI != E; ++AI, ++CAI) { 870 LatticeVal &IV = ValueState[AI]; 871 if (!IV.isOverdefined()) 872 mergeInValue(IV, AI, getValueState(*CAI)); 873 } 874 } 875 Instruction *I = CS.getInstruction(); 876 if (I->getType() == Type::VoidTy) return; 877 878 LatticeVal &IV = ValueState[I]; 879 if (IV.isOverdefined()) return; 880 881 // Propagate the return value of the function to the value of the instruction. 882 if (TFRVI != TrackedFunctionRetVals.end()) { 883 mergeInValue(IV, I, TFRVI->second); 884 return; 885 } 886 887 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) { 888 markOverdefined(IV, I); 889 return; 890 } 891 892 std::vector<Constant*> Operands; 893 Operands.reserve(I->getNumOperands()-1); 894 895 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 896 AI != E; ++AI) { 897 LatticeVal &State = getValueState(*AI); 898 if (State.isUndefined()) 899 return; // Operands are not resolved yet... 900 else if (State.isOverdefined()) { 901 markOverdefined(IV, I); 902 return; 903 } 904 assert(State.isConstant() && "Unknown state!"); 905 Operands.push_back(State.getConstant()); 906 } 907 908 if (Constant *C = ConstantFoldCall(F, Operands)) 909 markConstant(IV, I, C); 910 else 911 markOverdefined(IV, I); 912} 913 914 915void SCCPSolver::Solve() { 916 // Process the work lists until they are empty! 917 while (!BBWorkList.empty() || !InstWorkList.empty() || 918 !OverdefinedInstWorkList.empty()) { 919 // Process the instruction work list... 920 while (!OverdefinedInstWorkList.empty()) { 921 Value *I = OverdefinedInstWorkList.back(); 922 OverdefinedInstWorkList.pop_back(); 923 924 DEBUG(std::cerr << "\nPopped off OI-WL: " << *I); 925 926 // "I" got into the work list because it either made the transition from 927 // bottom to constant 928 // 929 // Anything on this worklist that is overdefined need not be visited 930 // since all of its users will have already been marked as overdefined 931 // Update all of the users of this instruction's value... 932 // 933 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 934 UI != E; ++UI) 935 OperandChangedState(*UI); 936 } 937 // Process the instruction work list... 938 while (!InstWorkList.empty()) { 939 Value *I = InstWorkList.back(); 940 InstWorkList.pop_back(); 941 942 DEBUG(std::cerr << "\nPopped off I-WL: " << *I); 943 944 // "I" got into the work list because it either made the transition from 945 // bottom to constant 946 // 947 // Anything on this worklist that is overdefined need not be visited 948 // since all of its users will have already been marked as overdefined. 949 // Update all of the users of this instruction's value... 950 // 951 if (!getValueState(I).isOverdefined()) 952 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 953 UI != E; ++UI) 954 OperandChangedState(*UI); 955 } 956 957 // Process the basic block work list... 958 while (!BBWorkList.empty()) { 959 BasicBlock *BB = BBWorkList.back(); 960 BBWorkList.pop_back(); 961 962 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB); 963 964 // Notify all instructions in this basic block that they are newly 965 // executable. 966 visit(BB); 967 } 968 } 969} 970 971/// ResolveBranchesIn - While solving the dataflow for a function, we assume 972/// that branches on undef values cannot reach any of their successors. 973/// However, this is not a safe assumption. After we solve dataflow, this 974/// method should be use to handle this. If this returns true, the solver 975/// should be rerun. 976bool SCCPSolver::ResolveBranchesIn(Function &F) { 977 bool BranchesResolved = false; 978 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 979 if (BBExecutable.count(BB)) { 980 TerminatorInst *TI = BB->getTerminator(); 981 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 982 if (BI->isConditional()) { 983 LatticeVal &BCValue = getValueState(BI->getCondition()); 984 if (BCValue.isUndefined()) { 985 BI->setCondition(ConstantBool::True); 986 BranchesResolved = true; 987 visit(BI); 988 } 989 } 990 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 991 LatticeVal &SCValue = getValueState(SI->getCondition()); 992 if (SCValue.isUndefined()) { 993 const Type *CondTy = SI->getCondition()->getType(); 994 SI->setCondition(Constant::getNullValue(CondTy)); 995 BranchesResolved = true; 996 visit(SI); 997 } 998 } 999 } 1000 1001 return BranchesResolved; 1002} 1003 1004 1005namespace { 1006 Statistic<> NumInstRemoved("sccp", "Number of instructions removed"); 1007 Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable"); 1008 1009 //===--------------------------------------------------------------------===// 1010 // 1011 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 1012 /// Sparse Conditional COnstant Propagator. 1013 /// 1014 struct SCCP : public FunctionPass { 1015 // runOnFunction - Run the Sparse Conditional Constant Propagation 1016 // algorithm, and return true if the function was modified. 1017 // 1018 bool runOnFunction(Function &F); 1019 1020 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1021 AU.setPreservesCFG(); 1022 } 1023 }; 1024 1025 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation"); 1026} // end anonymous namespace 1027 1028 1029// createSCCPPass - This is the public interface to this file... 1030FunctionPass *llvm::createSCCPPass() { 1031 return new SCCP(); 1032} 1033 1034 1035// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm, 1036// and return true if the function was modified. 1037// 1038bool SCCP::runOnFunction(Function &F) { 1039 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n"); 1040 SCCPSolver Solver; 1041 1042 // Mark the first block of the function as being executable. 1043 Solver.MarkBlockExecutable(F.begin()); 1044 1045 // Mark all arguments to the function as being overdefined. 1046 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 1047 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI) 1048 Values[AI].markOverdefined(); 1049 1050 // Solve for constants. 1051 bool ResolvedBranches = true; 1052 while (ResolvedBranches) { 1053 Solver.Solve(); 1054 DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n"); 1055 ResolvedBranches = Solver.ResolveBranchesIn(F); 1056 } 1057 1058 bool MadeChanges = false; 1059 1060 // If we decided that there are basic blocks that are dead in this function, 1061 // delete their contents now. Note that we cannot actually delete the blocks, 1062 // as we cannot modify the CFG of the function. 1063 // 1064 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks(); 1065 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1066 if (!ExecutableBBs.count(BB)) { 1067 DEBUG(std::cerr << " BasicBlock Dead:" << *BB); 1068 ++NumDeadBlocks; 1069 1070 // Delete the instructions backwards, as it has a reduced likelihood of 1071 // having to update as many def-use and use-def chains. 1072 std::vector<Instruction*> Insts; 1073 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator(); 1074 I != E; ++I) 1075 Insts.push_back(I); 1076 while (!Insts.empty()) { 1077 Instruction *I = Insts.back(); 1078 Insts.pop_back(); 1079 if (!I->use_empty()) 1080 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1081 BB->getInstList().erase(I); 1082 MadeChanges = true; 1083 ++NumInstRemoved; 1084 } 1085 } else { 1086 // Iterate over all of the instructions in a function, replacing them with 1087 // constants if we have found them to be of constant values. 1088 // 1089 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1090 Instruction *Inst = BI++; 1091 if (Inst->getType() != Type::VoidTy) { 1092 LatticeVal &IV = Values[Inst]; 1093 if (IV.isConstant() || IV.isUndefined() && 1094 !isa<TerminatorInst>(Inst)) { 1095 Constant *Const = IV.isConstant() 1096 ? IV.getConstant() : UndefValue::get(Inst->getType()); 1097 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst); 1098 1099 // Replaces all of the uses of a variable with uses of the constant. 1100 Inst->replaceAllUsesWith(Const); 1101 1102 // Delete the instruction. 1103 BB->getInstList().erase(Inst); 1104 1105 // Hey, we just changed something! 1106 MadeChanges = true; 1107 ++NumInstRemoved; 1108 } 1109 } 1110 } 1111 } 1112 1113 return MadeChanges; 1114} 1115 1116namespace { 1117 Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed"); 1118 Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable"); 1119 Statistic<> IPNumArgsElimed ("ipsccp", 1120 "Number of arguments constant propagated"); 1121 Statistic<> IPNumGlobalConst("ipsccp", 1122 "Number of globals found to be constant"); 1123 1124 //===--------------------------------------------------------------------===// 1125 // 1126 /// IPSCCP Class - This class implements interprocedural Sparse Conditional 1127 /// Constant Propagation. 1128 /// 1129 struct IPSCCP : public ModulePass { 1130 bool runOnModule(Module &M); 1131 }; 1132 1133 RegisterOpt<IPSCCP> 1134 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation"); 1135} // end anonymous namespace 1136 1137// createIPSCCPPass - This is the public interface to this file... 1138ModulePass *llvm::createIPSCCPPass() { 1139 return new IPSCCP(); 1140} 1141 1142 1143static bool AddressIsTaken(GlobalValue *GV) { 1144 // Delete any dead constantexpr klingons. 1145 GV->removeDeadConstantUsers(); 1146 1147 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); 1148 UI != E; ++UI) 1149 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 1150 if (SI->getOperand(0) == GV || SI->isVolatile()) 1151 return true; // Storing addr of GV. 1152 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) { 1153 // Make sure we are calling the function, not passing the address. 1154 CallSite CS = CallSite::get(cast<Instruction>(*UI)); 1155 for (CallSite::arg_iterator AI = CS.arg_begin(), 1156 E = CS.arg_end(); AI != E; ++AI) 1157 if (*AI == GV) 1158 return true; 1159 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 1160 if (LI->isVolatile()) 1161 return true; 1162 } else { 1163 return true; 1164 } 1165 return false; 1166} 1167 1168bool IPSCCP::runOnModule(Module &M) { 1169 SCCPSolver Solver; 1170 1171 // Loop over all functions, marking arguments to those with their addresses 1172 // taken or that are external as overdefined. 1173 // 1174 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 1175 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 1176 if (!F->hasInternalLinkage() || AddressIsTaken(F)) { 1177 if (!F->isExternal()) 1178 Solver.MarkBlockExecutable(F->begin()); 1179 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1180 AI != E; ++AI) 1181 Values[AI].markOverdefined(); 1182 } else { 1183 Solver.AddTrackedFunction(F); 1184 } 1185 1186 // Loop over global variables. We inform the solver about any internal global 1187 // variables that do not have their 'addresses taken'. If they don't have 1188 // their addresses taken, we can propagate constants through them. 1189 for (Module::global_iterator G = M.global_begin(), E = M.global_end(); 1190 G != E; ++G) 1191 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G)) 1192 Solver.TrackValueOfGlobalVariable(G); 1193 1194 // Solve for constants. 1195 bool ResolvedBranches = true; 1196 while (ResolvedBranches) { 1197 Solver.Solve(); 1198 1199 DEBUG(std::cerr << "RESOLVING UNDEF BRANCHES\n"); 1200 ResolvedBranches = false; 1201 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 1202 ResolvedBranches |= Solver.ResolveBranchesIn(*F); 1203 } 1204 1205 bool MadeChanges = false; 1206 1207 // Iterate over all of the instructions in the module, replacing them with 1208 // constants if we have found them to be of constant values. 1209 // 1210 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks(); 1211 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 1212 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1213 AI != E; ++AI) 1214 if (!AI->use_empty()) { 1215 LatticeVal &IV = Values[AI]; 1216 if (IV.isConstant() || IV.isUndefined()) { 1217 Constant *CST = IV.isConstant() ? 1218 IV.getConstant() : UndefValue::get(AI->getType()); 1219 DEBUG(std::cerr << "*** Arg " << *AI << " = " << *CST <<"\n"); 1220 1221 // Replaces all of the uses of a variable with uses of the 1222 // constant. 1223 AI->replaceAllUsesWith(CST); 1224 ++IPNumArgsElimed; 1225 } 1226 } 1227 1228 std::vector<BasicBlock*> BlocksToErase; 1229 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 1230 if (!ExecutableBBs.count(BB)) { 1231 DEBUG(std::cerr << " BasicBlock Dead:" << *BB); 1232 ++IPNumDeadBlocks; 1233 1234 // Delete the instructions backwards, as it has a reduced likelihood of 1235 // having to update as many def-use and use-def chains. 1236 std::vector<Instruction*> Insts; 1237 TerminatorInst *TI = BB->getTerminator(); 1238 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I) 1239 Insts.push_back(I); 1240 1241 while (!Insts.empty()) { 1242 Instruction *I = Insts.back(); 1243 Insts.pop_back(); 1244 if (!I->use_empty()) 1245 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1246 BB->getInstList().erase(I); 1247 MadeChanges = true; 1248 ++IPNumInstRemoved; 1249 } 1250 1251 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1252 BasicBlock *Succ = TI->getSuccessor(i); 1253 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin())) 1254 TI->getSuccessor(i)->removePredecessor(BB); 1255 } 1256 if (!TI->use_empty()) 1257 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 1258 BB->getInstList().erase(TI); 1259 1260 if (&*BB != &F->front()) 1261 BlocksToErase.push_back(BB); 1262 else 1263 new UnreachableInst(BB); 1264 1265 } else { 1266 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1267 Instruction *Inst = BI++; 1268 if (Inst->getType() != Type::VoidTy) { 1269 LatticeVal &IV = Values[Inst]; 1270 if (IV.isConstant() || IV.isUndefined() && 1271 !isa<TerminatorInst>(Inst)) { 1272 Constant *Const = IV.isConstant() 1273 ? IV.getConstant() : UndefValue::get(Inst->getType()); 1274 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst); 1275 1276 // Replaces all of the uses of a variable with uses of the 1277 // constant. 1278 Inst->replaceAllUsesWith(Const); 1279 1280 // Delete the instruction. 1281 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst)) 1282 BB->getInstList().erase(Inst); 1283 1284 // Hey, we just changed something! 1285 MadeChanges = true; 1286 ++IPNumInstRemoved; 1287 } 1288 } 1289 } 1290 } 1291 1292 // Now that all instructions in the function are constant folded, erase dead 1293 // blocks, because we can now use ConstantFoldTerminator to get rid of 1294 // in-edges. 1295 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 1296 // If there are any PHI nodes in this successor, drop entries for BB now. 1297 BasicBlock *DeadBB = BlocksToErase[i]; 1298 while (!DeadBB->use_empty()) { 1299 Instruction *I = cast<Instruction>(DeadBB->use_back()); 1300 bool Folded = ConstantFoldTerminator(I->getParent()); 1301 assert(Folded && "Didn't fold away reference to block!"); 1302 } 1303 1304 // Finally, delete the basic block. 1305 F->getBasicBlockList().erase(DeadBB); 1306 } 1307 } 1308 1309 // If we inferred constant or undef return values for a function, we replaced 1310 // all call uses with the inferred value. This means we don't need to bother 1311 // actually returning anything from the function. Replace all return 1312 // instructions with return undef. 1313 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals(); 1314 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(), 1315 E = RV.end(); I != E; ++I) 1316 if (!I->second.isOverdefined() && 1317 I->first->getReturnType() != Type::VoidTy) { 1318 Function *F = I->first; 1319 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 1320 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 1321 if (!isa<UndefValue>(RI->getOperand(0))) 1322 RI->setOperand(0, UndefValue::get(F->getReturnType())); 1323 } 1324 1325 // If we infered constant or undef values for globals variables, we can delete 1326 // the global and any stores that remain to it. 1327 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 1328 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 1329 E = TG.end(); I != E; ++I) { 1330 GlobalVariable *GV = I->first; 1331 assert(!I->second.isOverdefined() && 1332 "Overdefined values should have been taken out of the map!"); 1333 DEBUG(std::cerr << "Found that GV '" << GV->getName()<< "' is constant!\n"); 1334 while (!GV->use_empty()) { 1335 StoreInst *SI = cast<StoreInst>(GV->use_back()); 1336 SI->eraseFromParent(); 1337 } 1338 M.getGlobalList().erase(GV); 1339 ++IPNumGlobalConst; 1340 } 1341 1342 return MadeChanges; 1343} 1344