1 //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===// 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 #include "llvm/Analysis/CGSCCPassManager.h" 11 #include "llvm/IR/CallSite.h" 12 #include "llvm/IR/InstIterator.h" 13 14 using namespace llvm; 15 16 namespace llvm { 17 18 // Explicit instantiations for the core proxy templates. 19 template class AllAnalysesOn<LazyCallGraph::SCC>; 20 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>; 21 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, 22 LazyCallGraph &, CGSCCUpdateResult &>; 23 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>; 24 template class OuterAnalysisManagerProxy<ModuleAnalysisManager, 25 LazyCallGraph::SCC>; 26 template class InnerAnalysisManagerProxy<FunctionAnalysisManager, 27 LazyCallGraph::SCC>; 28 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>; 29 30 /// Explicitly specialize the pass manager run method to handle call graph 31 /// updates. 32 template <> 33 PreservedAnalyses 34 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, 35 CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC, 36 CGSCCAnalysisManager &AM, 37 LazyCallGraph &G, CGSCCUpdateResult &UR) { 38 PreservedAnalyses PA = PreservedAnalyses::all(); 39 40 if (DebugLogging) 41 dbgs() << "Starting CGSCC pass manager run.\n"; 42 43 // The SCC may be refined while we are running passes over it, so set up 44 // a pointer that we can update. 45 LazyCallGraph::SCC *C = &InitialC; 46 47 for (auto &Pass : Passes) { 48 if (DebugLogging) 49 dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n"; 50 51 PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR); 52 53 // Update the SCC if necessary. 54 C = UR.UpdatedC ? UR.UpdatedC : C; 55 56 // Check that we didn't miss any update scenario. 57 assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!"); 58 assert(C->begin() != C->end() && "Cannot have an empty SCC!"); 59 60 // Update the analysis manager as each pass runs and potentially 61 // invalidates analyses. 62 AM.invalidate(*C, PassPA); 63 64 // Finally, we intersect the final preserved analyses to compute the 65 // aggregate preserved set for this pass manager. 66 PA.intersect(std::move(PassPA)); 67 68 // FIXME: Historically, the pass managers all called the LLVM context's 69 // yield function here. We don't have a generic way to acquire the 70 // context and it isn't yet clear what the right pattern is for yielding 71 // in the new pass manager so it is currently omitted. 72 // ...getContext().yield(); 73 } 74 75 // Invaliadtion was handled after each pass in the above loop for the current 76 // SCC. Therefore, the remaining analysis results in the AnalysisManager are 77 // preserved. We mark this with a set so that we don't need to inspect each 78 // one individually. 79 PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>(); 80 81 if (DebugLogging) 82 dbgs() << "Finished CGSCC pass manager run.\n"; 83 84 return PA; 85 } 86 87 } // End llvm namespace 88 89 namespace { 90 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c 91 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly 92 /// added SCCs. 93 /// 94 /// The range of new SCCs must be in postorder already. The SCC they were split 95 /// out of must be provided as \p C. The current node being mutated and 96 /// triggering updates must be passed as \p N. 97 /// 98 /// This function returns the SCC containing \p N. This will be either \p C if 99 /// no new SCCs have been split out, or it will be the new SCC containing \p N. 100 template <typename SCCRangeT> 101 LazyCallGraph::SCC * 102 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G, 103 LazyCallGraph::Node &N, LazyCallGraph::SCC *C, 104 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 105 bool DebugLogging = false) { 106 typedef LazyCallGraph::SCC SCC; 107 108 if (NewSCCRange.begin() == NewSCCRange.end()) 109 return C; 110 111 // Invalidate the analyses of the current SCC and add it to the worklist since 112 // it has changed its shape. 113 AM.invalidate(*C, PreservedAnalyses::none()); 114 UR.CWorklist.insert(C); 115 if (DebugLogging) 116 dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n"; 117 118 SCC *OldC = C; 119 (void)OldC; 120 121 // Update the current SCC. Note that if we have new SCCs, this must actually 122 // change the SCC. 123 assert(C != &*NewSCCRange.begin() && 124 "Cannot insert new SCCs without changing current SCC!"); 125 C = &*NewSCCRange.begin(); 126 assert(G.lookupSCC(N) == C && "Failed to update current SCC!"); 127 128 for (SCC &NewC : 129 reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) { 130 assert(C != &NewC && "No need to re-visit the current SCC!"); 131 assert(OldC != &NewC && "Already handled the original SCC!"); 132 UR.CWorklist.insert(&NewC); 133 if (DebugLogging) 134 dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n"; 135 } 136 return C; 137 } 138 } 139 140 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass( 141 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N, 142 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) { 143 typedef LazyCallGraph::Node Node; 144 typedef LazyCallGraph::Edge Edge; 145 typedef LazyCallGraph::SCC SCC; 146 typedef LazyCallGraph::RefSCC RefSCC; 147 148 RefSCC &InitialRC = InitialC.getOuterRefSCC(); 149 SCC *C = &InitialC; 150 RefSCC *RC = &InitialRC; 151 Function &F = N.getFunction(); 152 153 // Walk the function body and build up the set of retained, promoted, and 154 // demoted edges. 155 SmallVector<Constant *, 16> Worklist; 156 SmallPtrSet<Constant *, 16> Visited; 157 SmallPtrSet<Function *, 16> RetainedEdges; 158 SmallSetVector<Function *, 4> PromotedRefTargets; 159 SmallSetVector<Function *, 4> DemotedCallTargets; 160 161 // First walk the function and handle all called functions. We do this first 162 // because if there is a single call edge, whether there are ref edges is 163 // irrelevant. 164 for (Instruction &I : instructions(F)) 165 if (auto CS = CallSite(&I)) 166 if (Function *Callee = CS.getCalledFunction()) 167 if (Visited.insert(Callee).second && !Callee->isDeclaration()) { 168 const Edge *E = N.lookup(*Callee); 169 // FIXME: We should really handle adding new calls. While it will 170 // make downstream usage more complex, there is no fundamental 171 // limitation and it will allow passes within the CGSCC to be a bit 172 // more flexible in what transforms they can do. Until then, we 173 // verify that new calls haven't been introduced. 174 assert(E && "No function transformations should introduce *new* " 175 "call edges! Any new calls should be modeled as " 176 "promoted existing ref edges!"); 177 RetainedEdges.insert(Callee); 178 if (!E->isCall()) 179 PromotedRefTargets.insert(Callee); 180 } 181 182 // Now walk all references. 183 for (Instruction &I : instructions(F)) 184 for (Value *Op : I.operand_values()) 185 if (Constant *C = dyn_cast<Constant>(Op)) 186 if (Visited.insert(C).second) 187 Worklist.push_back(C); 188 189 LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) { 190 const Edge *E = N.lookup(Referee); 191 // FIXME: Similarly to new calls, we also currently preclude 192 // introducing new references. See above for details. 193 assert(E && "No function transformations should introduce *new* ref " 194 "edges! Any new ref edges would require IPO which " 195 "function passes aren't allowed to do!"); 196 RetainedEdges.insert(&Referee); 197 if (E->isCall()) 198 DemotedCallTargets.insert(&Referee); 199 }); 200 201 // First remove all of the edges that are no longer present in this function. 202 // We have to build a list of dead targets first and then remove them as the 203 // data structures will all be invalidated by removing them. 204 SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets; 205 for (Edge &E : N) 206 if (!RetainedEdges.count(&E.getFunction())) 207 DeadTargets.push_back({E.getNode(), E.getKind()}); 208 for (auto DeadTarget : DeadTargets) { 209 Node &TargetN = *DeadTarget.getPointer(); 210 bool IsCall = DeadTarget.getInt() == Edge::Call; 211 SCC &TargetC = *G.lookupSCC(TargetN); 212 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 213 214 if (&TargetRC != RC) { 215 RC->removeOutgoingEdge(N, TargetN); 216 if (DebugLogging) 217 dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN 218 << "'\n"; 219 continue; 220 } 221 if (DebugLogging) 222 dbgs() << "Deleting internal " << (IsCall ? "call" : "ref") 223 << " edge from '" << N << "' to '" << TargetN << "'\n"; 224 225 if (IsCall) 226 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, 227 C, AM, UR, DebugLogging); 228 229 auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN); 230 if (!NewRefSCCs.empty()) { 231 // Note that we don't bother to invalidate analyses as ref-edge 232 // connectivity is not really observable in any way and is intended 233 // exclusively to be used for ordering of transforms rather than for 234 // analysis conclusions. 235 236 // The RC worklist is in reverse postorder, so we first enqueue the 237 // current RefSCC as it will remain the parent of all split RefSCCs, then 238 // we enqueue the new ones in RPO except for the one which contains the 239 // source node as that is the "bottom" we will continue processing in the 240 // bottom-up walk. 241 UR.RCWorklist.insert(RC); 242 if (DebugLogging) 243 dbgs() << "Enqueuing the existing RefSCC in the update worklist: " 244 << *RC << "\n"; 245 // Update the RC to the "bottom". 246 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!"); 247 RC = &C->getOuterRefSCC(); 248 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!"); 249 for (RefSCC *NewRC : reverse(NewRefSCCs)) 250 if (NewRC != RC) { 251 UR.RCWorklist.insert(NewRC); 252 if (DebugLogging) 253 dbgs() << "Enqueuing a new RefSCC in the update worklist: " 254 << *NewRC << "\n"; 255 } 256 } 257 } 258 259 // Next demote all the call edges that are now ref edges. This helps make 260 // the SCCs small which should minimize the work below as we don't want to 261 // form cycles that this would break. 262 for (Function *RefTarget : DemotedCallTargets) { 263 Node &TargetN = *G.lookup(*RefTarget); 264 SCC &TargetC = *G.lookupSCC(TargetN); 265 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 266 267 // The easy case is when the target RefSCC is not this RefSCC. This is 268 // only supported when the target RefSCC is a child of this RefSCC. 269 if (&TargetRC != RC) { 270 assert(RC->isAncestorOf(TargetRC) && 271 "Cannot potentially form RefSCC cycles here!"); 272 RC->switchOutgoingEdgeToRef(N, TargetN); 273 if (DebugLogging) 274 dbgs() << "Switch outgoing call edge to a ref edge from '" << N 275 << "' to '" << TargetN << "'\n"; 276 continue; 277 } 278 279 // Otherwise we are switching an internal call edge to a ref edge. This 280 // may split up some SCCs. 281 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C, 282 AM, UR, DebugLogging); 283 } 284 285 // Now promote ref edges into call edges. 286 for (Function *CallTarget : PromotedRefTargets) { 287 Node &TargetN = *G.lookup(*CallTarget); 288 SCC &TargetC = *G.lookupSCC(TargetN); 289 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 290 291 // The easy case is when the target RefSCC is not this RefSCC. This is 292 // only supported when the target RefSCC is a child of this RefSCC. 293 if (&TargetRC != RC) { 294 assert(RC->isAncestorOf(TargetRC) && 295 "Cannot potentially form RefSCC cycles here!"); 296 RC->switchOutgoingEdgeToCall(N, TargetN); 297 if (DebugLogging) 298 dbgs() << "Switch outgoing ref edge to a call edge from '" << N 299 << "' to '" << TargetN << "'\n"; 300 continue; 301 } 302 if (DebugLogging) 303 dbgs() << "Switch an internal ref edge to a call edge from '" << N 304 << "' to '" << TargetN << "'\n"; 305 306 // Otherwise we are switching an internal ref edge to a call edge. This 307 // may merge away some SCCs, and we add those to the UpdateResult. We also 308 // need to make sure to update the worklist in the event SCCs have moved 309 // before the current one in the post-order sequence. 310 auto InitialSCCIndex = RC->find(*C) - RC->begin(); 311 auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN); 312 if (!InvalidatedSCCs.empty()) { 313 C = &TargetC; 314 assert(G.lookupSCC(N) == C && "Failed to update current SCC!"); 315 316 // Any analyses cached for this SCC are no longer precise as the shape 317 // has changed by introducing this cycle. 318 AM.invalidate(*C, PreservedAnalyses::none()); 319 320 for (SCC *InvalidatedC : InvalidatedSCCs) { 321 assert(InvalidatedC != C && "Cannot invalidate the current SCC!"); 322 UR.InvalidatedSCCs.insert(InvalidatedC); 323 324 // Also clear any cached analyses for the SCCs that are dead. This 325 // isn't really necessary for correctness but can release memory. 326 AM.clear(*InvalidatedC); 327 } 328 } 329 auto NewSCCIndex = RC->find(*C) - RC->begin(); 330 if (InitialSCCIndex < NewSCCIndex) { 331 // Put our current SCC back onto the worklist as we'll visit other SCCs 332 // that are now definitively ordered prior to the current one in the 333 // post-order sequence, and may end up observing more precise context to 334 // optimize the current SCC. 335 UR.CWorklist.insert(C); 336 if (DebugLogging) 337 dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n"; 338 // Enqueue in reverse order as we pop off the back of the worklist. 339 for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex, 340 RC->begin() + NewSCCIndex))) { 341 UR.CWorklist.insert(&MovedC); 342 if (DebugLogging) 343 dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC 344 << "\n"; 345 } 346 } 347 } 348 349 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!"); 350 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!"); 351 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!"); 352 353 // Record the current RefSCC and SCC for higher layers of the CGSCC pass 354 // manager now that all the updates have been applied. 355 if (RC != &InitialRC) 356 UR.UpdatedRC = RC; 357 if (C != &InitialC) 358 UR.UpdatedC = C; 359 360 return *C; 361 } 362