CallGraph.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
  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. #include "llvm/Analysis/CallGraph.h"
  10. #include "llvm/IR/CallSite.h"
  11. #include "llvm/IR/Instructions.h"
  12. #include "llvm/IR/IntrinsicInst.h"
  13. #include "llvm/IR/Module.h"
  14. #include "llvm/Support/Debug.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "dxc/HLSL/HLModule.h" // HLSL Change
  17. using namespace llvm;
  18. //===----------------------------------------------------------------------===//
  19. // Implementations of the CallGraph class methods.
  20. //
  21. CallGraph::CallGraph(Module &M)
  22. : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
  23. CallsExternalNode(new CallGraphNode(nullptr)) {
  24. // Add every function to the call graph.
  25. for (Function &F : M)
  26. addToCallGraph(&F);
  27. // If we didn't find a main function, use the external call graph node
  28. if (!Root)
  29. Root = ExternalCallingNode;
  30. }
  31. CallGraph::~CallGraph() {
  32. // CallsExternalNode is not in the function map, delete it explicitly.
  33. CallsExternalNode->allReferencesDropped();
  34. delete CallsExternalNode;
  35. // Reset all node's use counts to zero before deleting them to prevent an
  36. // assertion from firing.
  37. #ifndef NDEBUG
  38. for (auto &I : FunctionMap)
  39. I.second->allReferencesDropped();
  40. #endif
  41. for (auto &I : FunctionMap)
  42. delete I.second;
  43. }
  44. void CallGraph::addToCallGraph(Function *F) {
  45. CallGraphNode *Node = getOrInsertFunction(F);
  46. // If this function has external linkage, anything could call it.
  47. if (!F->hasLocalLinkage()) {
  48. ExternalCallingNode->addCalledFunction(CallSite(), Node);
  49. // HLSL Change Begins.
  50. if (M.HasHLModule()) {
  51. if (M.GetHLModule().GetEntryFunction() == F)
  52. Root = Node;
  53. } else // Make sure Root not overwrite by main.
  54. // HLSL Change Ends.
  55. // Found the entry point?
  56. if (F->getName() == "main") {
  57. if (Root) // Found multiple external mains? Don't pick one.
  58. Root = ExternalCallingNode;
  59. else
  60. Root = Node; // Found a main, keep track of it!
  61. }
  62. }
  63. // If this function has its address taken, anything could call it.
  64. if (F->hasAddressTaken())
  65. ExternalCallingNode->addCalledFunction(CallSite(), Node);
  66. // If this function is not defined in this translation unit, it could call
  67. // anything.
  68. if (F->isDeclaration() && !F->isIntrinsic())
  69. Node->addCalledFunction(CallSite(), CallsExternalNode);
  70. // Look for calls by this function.
  71. for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
  72. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
  73. ++II) {
  74. CallSite CS(cast<Value>(II));
  75. if (CS) {
  76. const Function *Callee = CS.getCalledFunction();
  77. if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
  78. // Indirect calls of intrinsics are not allowed so no need to check.
  79. // We can be more precise here by using TargetArg returned by
  80. // Intrinsic::isLeaf.
  81. Node->addCalledFunction(CS, CallsExternalNode);
  82. else if (!Callee->isIntrinsic())
  83. Node->addCalledFunction(CS, getOrInsertFunction(Callee));
  84. }
  85. }
  86. }
  87. void CallGraph::print(raw_ostream &OS) const {
  88. OS << "CallGraph Root is: ";
  89. if (Function *F = Root->getFunction())
  90. OS << F->getName() << "\n";
  91. else {
  92. OS << "<<null function: 0x" << Root << ">>\n";
  93. }
  94. // Print in a deterministic order by sorting CallGraphNodes by name. We do
  95. // this here to avoid slowing down the non-printing fast path.
  96. SmallVector<CallGraphNode *, 16> Nodes;
  97. Nodes.reserve(FunctionMap.size());
  98. for (auto I = begin(), E = end(); I != E; ++I)
  99. Nodes.push_back(I->second);
  100. std::sort(Nodes.begin(), Nodes.end(),
  101. [](CallGraphNode *LHS, CallGraphNode *RHS) {
  102. if (Function *LF = LHS->getFunction())
  103. if (Function *RF = RHS->getFunction())
  104. return LF->getName() < RF->getName();
  105. return RHS->getFunction() != nullptr;
  106. });
  107. for (CallGraphNode *CN : Nodes)
  108. CN->print(OS);
  109. }
  110. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  111. void CallGraph::dump() const { print(dbgs()); }
  112. #endif
  113. // removeFunctionFromModule - Unlink the function from this module, returning
  114. // it. Because this removes the function from the module, the call graph node
  115. // is destroyed. This is only valid if the function does not call any other
  116. // functions (ie, there are no edges in it's CGN). The easiest way to do this
  117. // is to dropAllReferences before calling this.
  118. //
  119. Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
  120. assert(CGN->empty() && "Cannot remove function from call "
  121. "graph if it references other functions!");
  122. Function *F = CGN->getFunction(); // Get the function for the call graph node
  123. delete CGN; // Delete the call graph node for this func
  124. FunctionMap.erase(F); // Remove the call graph node from the map
  125. if (M.HasHLModule()) M.GetHLModule().RemoveFunction(F); // HLSL Change
  126. M.getFunctionList().remove(F);
  127. return F;
  128. }
  129. /// spliceFunction - Replace the function represented by this node by another.
  130. /// This does not rescan the body of the function, so it is suitable when
  131. /// splicing the body of the old function to the new while also updating all
  132. /// callers from old to new.
  133. ///
  134. void CallGraph::spliceFunction(const Function *From, const Function *To) {
  135. assert(FunctionMap.count(From) && "No CallGraphNode for function!");
  136. assert(!FunctionMap.count(To) &&
  137. "Pointing CallGraphNode at a function that already exists");
  138. FunctionMapTy::iterator I = FunctionMap.find(From);
  139. I->second->F = const_cast<Function*>(To);
  140. FunctionMap[To] = I->second;
  141. FunctionMap.erase(I);
  142. }
  143. // getOrInsertFunction - This method is identical to calling operator[], but
  144. // it will insert a new CallGraphNode for the specified function if one does
  145. // not already exist.
  146. CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
  147. CallGraphNode *&CGN = FunctionMap[F];
  148. if (CGN)
  149. return CGN;
  150. assert((!F || F->getParent() == &M) && "Function not in current module!");
  151. return CGN = new CallGraphNode(const_cast<Function*>(F));
  152. }
  153. //===----------------------------------------------------------------------===//
  154. // Implementations of the CallGraphNode class methods.
  155. //
  156. void CallGraphNode::print(raw_ostream &OS) const {
  157. if (Function *F = getFunction())
  158. OS << "Call graph node for function: '" << F->getName() << "'";
  159. else
  160. OS << "Call graph node <<null function>>";
  161. OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
  162. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  163. OS << " CS<" << I->first << "> calls ";
  164. if (Function *FI = I->second->getFunction())
  165. OS << "function '" << FI->getName() <<"'\n";
  166. else
  167. OS << "external node\n";
  168. }
  169. OS << '\n';
  170. }
  171. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  172. void CallGraphNode::dump() const { print(dbgs()); }
  173. #endif
  174. /// removeCallEdgeFor - This method removes the edge in the node for the
  175. /// specified call site. Note that this method takes linear time, so it
  176. /// should be used sparingly.
  177. void CallGraphNode::removeCallEdgeFor(CallSite CS) {
  178. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  179. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  180. if (I->first == CS.getInstruction()) {
  181. I->second->DropRef();
  182. *I = CalledFunctions.back();
  183. CalledFunctions.pop_back();
  184. return;
  185. }
  186. }
  187. }
  188. // removeAnyCallEdgeTo - This method removes any call edges from this node to
  189. // the specified callee function. This takes more time to execute than
  190. // removeCallEdgeTo, so it should not be used unless necessary.
  191. void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
  192. for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
  193. if (CalledFunctions[i].second == Callee) {
  194. Callee->DropRef();
  195. CalledFunctions[i] = CalledFunctions.back();
  196. CalledFunctions.pop_back();
  197. --i; --e;
  198. }
  199. }
  200. /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
  201. /// from this node to the specified callee function.
  202. void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
  203. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  204. assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
  205. CallRecord &CR = *I;
  206. if (CR.second == Callee && CR.first == nullptr) {
  207. Callee->DropRef();
  208. *I = CalledFunctions.back();
  209. CalledFunctions.pop_back();
  210. return;
  211. }
  212. }
  213. }
  214. /// replaceCallEdge - This method replaces the edge in the node for the
  215. /// specified call site with a new one. Note that this method takes linear
  216. /// time, so it should be used sparingly.
  217. void CallGraphNode::replaceCallEdge(CallSite CS,
  218. CallSite NewCS, CallGraphNode *NewNode){
  219. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  220. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  221. if (I->first == CS.getInstruction()) {
  222. I->second->DropRef();
  223. I->first = NewCS.getInstruction();
  224. I->second = NewNode;
  225. NewNode->AddRef();
  226. return;
  227. }
  228. }
  229. }
  230. //===----------------------------------------------------------------------===//
  231. // Out-of-line definitions of CallGraphAnalysis class members.
  232. //
  233. char CallGraphAnalysis::PassID;
  234. //===----------------------------------------------------------------------===//
  235. // Implementations of the CallGraphWrapperPass class methods.
  236. //
  237. CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
  238. initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
  239. }
  240. CallGraphWrapperPass::~CallGraphWrapperPass() {}
  241. void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  242. AU.setPreservesAll();
  243. }
  244. bool CallGraphWrapperPass::runOnModule(Module &M) {
  245. // All the real work is done in the constructor for the CallGraph.
  246. G.reset(new CallGraph(M));
  247. return false;
  248. }
  249. INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
  250. false, true)
  251. char CallGraphWrapperPass::ID = 0;
  252. void CallGraphWrapperPass::releaseMemory() { G.reset(); }
  253. void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
  254. if (!G) {
  255. OS << "No call graph has been built!\n";
  256. return;
  257. }
  258. // Just delegate.
  259. G->print(OS);
  260. }
  261. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  262. void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
  263. #endif