1 //===- Pass.cpp - Pass infrastructure implementation ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements common pass infrastructure. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Pass/Pass.h" 14 #include "PassDetail.h" 15 #include "mlir/Analysis/Verifier.h" 16 #include "mlir/IR/Diagnostics.h" 17 #include "mlir/IR/Dialect.h" 18 #include "mlir/IR/Module.h" 19 #include "mlir/Support/FileUtilities.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Support/CommandLine.h" 22 #include "llvm/Support/CrashRecoveryContext.h" 23 #include "llvm/Support/Mutex.h" 24 #include "llvm/Support/Parallel.h" 25 #include "llvm/Support/Threading.h" 26 #include "llvm/Support/ToolOutputFile.h" 27 28 using namespace mlir; 29 using namespace mlir::detail; 30 31 //===----------------------------------------------------------------------===// 32 // Pass 33 //===----------------------------------------------------------------------===// 34 35 /// Out of line virtual method to ensure vtables and metadata are emitted to a 36 /// single .o file. 37 void Pass::anchor() {} 38 39 /// Attempt to initialize the options of this pass from the given string. 40 LogicalResult Pass::initializeOptions(StringRef options) { 41 return passOptions.parseFromString(options); 42 } 43 44 /// Copy the option values from 'other', which is another instance of this 45 /// pass. 46 void Pass::copyOptionValuesFrom(const Pass *other) { 47 passOptions.copyOptionValuesFrom(other->passOptions); 48 } 49 50 /// Prints out the pass in the textual representation of pipelines. If this is 51 /// an adaptor pass, print with the op_name(sub_pass,...) format. 52 void Pass::printAsTextualPipeline(raw_ostream &os) { 53 // Special case for adaptors to use the 'op_name(sub_passes)' format. 54 if (auto *adaptor = getAdaptorPassBase(this)) { 55 interleaveComma(adaptor->getPassManagers(), os, [&](OpPassManager &pm) { 56 os << pm.getOpName() << "("; 57 pm.printAsTextualPipeline(os); 58 os << ")"; 59 }); 60 return; 61 } 62 // Otherwise, print the pass argument followed by its options. 63 if (const PassInfo *info = lookupPassInfo()) 64 os << info->getPassArgument(); 65 else 66 os << getName(); 67 passOptions.print(os); 68 } 69 70 /// Forwarding function to execute this pass. 71 LogicalResult Pass::run(Operation *op, AnalysisManager am) { 72 passState.emplace(op, am); 73 74 // Instrument before the pass has run. 75 auto pi = am.getPassInstrumentor(); 76 if (pi) 77 pi->runBeforePass(this, op); 78 79 // Invoke the virtual runOnOperation method. 80 runOnOperation(); 81 82 // Invalidate any non preserved analyses. 83 am.invalidate(passState->preservedAnalyses); 84 85 // Instrument after the pass has run. 86 bool passFailed = passState->irAndPassFailed.getInt(); 87 if (pi) { 88 if (passFailed) 89 pi->runAfterPassFailed(this, op); 90 else 91 pi->runAfterPass(this, op); 92 } 93 94 // Return if the pass signaled a failure. 95 return failure(passFailed); 96 } 97 98 //===----------------------------------------------------------------------===// 99 // Verifier Passes 100 //===----------------------------------------------------------------------===// 101 102 void VerifierPass::runOnOperation() { 103 if (failed(verify(getOperation()))) 104 signalPassFailure(); 105 markAllAnalysesPreserved(); 106 } 107 108 //===----------------------------------------------------------------------===// 109 // OpPassManagerImpl 110 //===----------------------------------------------------------------------===// 111 112 namespace mlir { 113 namespace detail { 114 struct OpPassManagerImpl { 115 OpPassManagerImpl(OperationName name, bool disableThreads, bool verifyPasses) 116 : name(name), disableThreads(disableThreads), verifyPasses(verifyPasses) { 117 } 118 119 /// Merge the passes of this pass manager into the one provided. 120 void mergeInto(OpPassManagerImpl &rhs) { 121 assert(name == rhs.name && "merging unrelated pass managers"); 122 for (auto &pass : passes) 123 rhs.passes.push_back(std::move(pass)); 124 passes.clear(); 125 } 126 127 /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs 128 /// recursively through the pipeline graph. 129 void coalesceAdjacentAdaptorPasses(); 130 131 /// The name of the operation that passes of this pass manager operate on. 132 OperationName name; 133 134 /// Flag to disable multi-threading of passes. 135 bool disableThreads : 1; 136 137 /// Flag that specifies if the IR should be verified after each pass has run. 138 bool verifyPasses : 1; 139 140 /// The set of passes to run as part of this pass manager. 141 std::vector<std::unique_ptr<Pass>> passes; 142 }; 143 } // end namespace detail 144 } // end namespace mlir 145 146 /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs 147 /// recursively through the pipeline graph. 148 void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() { 149 // Bail out early if there are no adaptor passes. 150 if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) { 151 return isAdaptorPass(pass.get()); 152 })) 153 return; 154 155 // Walk the pass list and merge adjacent adaptors. 156 OpToOpPassAdaptorBase *lastAdaptor = nullptr; 157 for (auto it = passes.begin(), e = passes.end(); it != e; ++it) { 158 // Check to see if this pass is an adaptor. 159 if (auto *currentAdaptor = getAdaptorPassBase(it->get())) { 160 // If it is the first adaptor in a possible chain, remember it and 161 // continue. 162 if (!lastAdaptor) { 163 lastAdaptor = currentAdaptor; 164 continue; 165 } 166 167 // Otherwise, merge into the existing adaptor and delete the current one. 168 currentAdaptor->mergeInto(*lastAdaptor); 169 it->reset(); 170 171 // If the verifier is enabled, then next pass is a verifier run so 172 // drop it. Verifier passes are inserted after every pass, so this one 173 // would be a duplicate. 174 if (verifyPasses) { 175 assert(std::next(it) != e && isa<VerifierPass>(*std::next(it))); 176 (++it)->reset(); 177 } 178 } else if (lastAdaptor && !isa<VerifierPass>(*it)) { 179 // If this pass is not an adaptor and not a verifier pass, then coalesce 180 // and forget any existing adaptor. 181 for (auto &pm : lastAdaptor->getPassManagers()) 182 pm.getImpl().coalesceAdjacentAdaptorPasses(); 183 lastAdaptor = nullptr; 184 } 185 } 186 187 // If there was an adaptor at the end of the manager, coalesce it as well. 188 if (lastAdaptor) { 189 for (auto &pm : lastAdaptor->getPassManagers()) 190 pm.getImpl().coalesceAdjacentAdaptorPasses(); 191 } 192 193 // Now that the adaptors have been merged, erase the empty slot corresponding 194 // to the merged adaptors that were nulled-out in the loop above. 195 llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>()); 196 } 197 198 //===----------------------------------------------------------------------===// 199 // OpPassManager 200 //===----------------------------------------------------------------------===// 201 202 OpPassManager::OpPassManager(OperationName name, bool disableThreads, 203 bool verifyPasses) 204 : impl(new OpPassManagerImpl(name, disableThreads, verifyPasses)) { 205 assert(name.getAbstractOperation() && 206 "OpPassManager can only operate on registered operations"); 207 assert(name.getAbstractOperation()->hasProperty( 208 OperationProperty::IsolatedFromAbove) && 209 "OpPassManager only supports operating on operations marked as " 210 "'IsolatedFromAbove'"); 211 } 212 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {} 213 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; } 214 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) { 215 impl.reset(new OpPassManagerImpl(rhs.impl->name, rhs.impl->disableThreads, 216 rhs.impl->verifyPasses)); 217 for (auto &pass : rhs.impl->passes) 218 impl->passes.emplace_back(pass->clone()); 219 return *this; 220 } 221 222 OpPassManager::~OpPassManager() {} 223 224 OpPassManager::pass_iterator OpPassManager::begin() { 225 return impl->passes.begin(); 226 } 227 OpPassManager::pass_iterator OpPassManager::end() { return impl->passes.end(); } 228 229 /// Run all of the passes in this manager over the current operation. 230 LogicalResult OpPassManager::run(Operation *op, AnalysisManager am) { 231 // Run each of the held passes. 232 for (auto &pass : impl->passes) 233 if (failed(pass->run(op, am))) 234 return failure(); 235 return success(); 236 } 237 238 /// Nest a new operation pass manager for the given operation kind under this 239 /// pass manager. 240 OpPassManager &OpPassManager::nest(const OperationName &nestedName) { 241 OpPassManager nested(nestedName, impl->disableThreads, impl->verifyPasses); 242 243 /// Create an adaptor for this pass. If multi-threading is disabled, then 244 /// create a synchronous adaptor. 245 if (impl->disableThreads || !llvm::llvm_is_multithreaded()) { 246 auto *adaptor = new OpToOpPassAdaptor(std::move(nested)); 247 addPass(std::unique_ptr<Pass>(adaptor)); 248 return adaptor->getPassManagers().front(); 249 } 250 251 auto *adaptor = new OpToOpPassAdaptorParallel(std::move(nested)); 252 addPass(std::unique_ptr<Pass>(adaptor)); 253 return adaptor->getPassManagers().front(); 254 } 255 OpPassManager &OpPassManager::nest(StringRef nestedName) { 256 return nest(OperationName(nestedName, getContext())); 257 } 258 259 /// Add the given pass to this pass manager. If this pass has a concrete 260 /// operation type, it must be the same type as this pass manager. 261 void OpPassManager::addPass(std::unique_ptr<Pass> pass) { 262 // If this pass runs on a different operation than this pass manager, then 263 // implicitly nest a pass manager for this operation. 264 auto passOpName = pass->getOpName(); 265 if (passOpName && passOpName != impl->name.getStringRef()) 266 return nest(*passOpName).addPass(std::move(pass)); 267 268 impl->passes.emplace_back(std::move(pass)); 269 if (impl->verifyPasses) 270 impl->passes.emplace_back(std::make_unique<VerifierPass>()); 271 } 272 273 /// Returns the number of passes held by this manager. 274 size_t OpPassManager::size() const { return impl->passes.size(); } 275 276 /// Returns the internal implementation instance. 277 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; } 278 279 /// Return an instance of the context. 280 MLIRContext *OpPassManager::getContext() const { 281 return impl->name.getAbstractOperation()->dialect.getContext(); 282 } 283 284 /// Return the operation name that this pass manager operates on. 285 const OperationName &OpPassManager::getOpName() const { return impl->name; } 286 287 /// Prints out the passes of the pass manager as the textual representation 288 /// of pipelines. 289 void OpPassManager::printAsTextualPipeline(raw_ostream &os) { 290 // Filter out passes that are not part of the public pipeline. 291 auto filteredPasses = llvm::make_filter_range( 292 impl->passes, [](const std::unique_ptr<Pass> &pass) { 293 return !isa<VerifierPass>(pass); 294 }); 295 interleaveComma(filteredPasses, os, [&](const std::unique_ptr<Pass> &pass) { 296 pass->printAsTextualPipeline(os); 297 }); 298 } 299 300 //===----------------------------------------------------------------------===// 301 // OpToOpPassAdaptor 302 //===----------------------------------------------------------------------===// 303 304 /// Utility to run the given operation and analysis manager on a provided op 305 /// pass manager. 306 static LogicalResult runPipeline(OpPassManager &pm, Operation *op, 307 AnalysisManager am) { 308 // Run the pipeline over the provided operation. 309 auto result = pm.run(op, am); 310 311 // Clear out any computed operation analyses. These analyses won't be used 312 // any more in this pipeline, and this helps reduce the current working set 313 // of memory. If preserving these analyses becomes important in the future 314 // we can re-evaluate this. 315 am.clear(); 316 return result; 317 } 318 319 /// Find an operation pass manager that can operate on an operation of the given 320 /// type, or nullptr if one does not exist. 321 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs, 322 const OperationName &name) { 323 auto it = llvm::find_if( 324 mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; }); 325 return it == mgrs.end() ? nullptr : &*it; 326 } 327 328 OpToOpPassAdaptorBase::OpToOpPassAdaptorBase(OpPassManager &&mgr) { 329 mgrs.emplace_back(std::move(mgr)); 330 } 331 332 /// Merge the current pass adaptor into given 'rhs'. 333 void OpToOpPassAdaptorBase::mergeInto(OpToOpPassAdaptorBase &rhs) { 334 for (auto &pm : mgrs) { 335 // If an existing pass manager exists, then merge the given pass manager 336 // into it. 337 if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) { 338 pm.getImpl().mergeInto(existingPM->getImpl()); 339 } else { 340 // Otherwise, add the given pass manager to the list. 341 rhs.mgrs.emplace_back(std::move(pm)); 342 } 343 } 344 mgrs.clear(); 345 346 // After coalescing, sort the pass managers within rhs by name. 347 llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(), 348 [](const OpPassManager *lhs, const OpPassManager *rhs) { 349 return lhs->getOpName().getStringRef().compare( 350 rhs->getOpName().getStringRef()); 351 }); 352 } 353 354 /// Returns the adaptor pass name. 355 std::string OpToOpPassAdaptorBase::getName() { 356 std::string name = "Pipeline Collection : ["; 357 llvm::raw_string_ostream os(name); 358 interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) { 359 os << '\'' << pm.getOpName() << '\''; 360 }); 361 os << ']'; 362 return os.str(); 363 } 364 365 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) 366 : OpToOpPassAdaptorBase(std::move(mgr)) {} 367 368 /// Run the held pipeline over all nested operations. 369 void OpToOpPassAdaptor::runOnOperation() { 370 auto am = getAnalysisManager(); 371 PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(), 372 this}; 373 auto *instrumentor = am.getPassInstrumentor(); 374 for (auto ®ion : getOperation()->getRegions()) { 375 for (auto &block : region) { 376 for (auto &op : block) { 377 auto *mgr = findPassManagerFor(mgrs, op.getName()); 378 if (!mgr) 379 continue; 380 381 // Run the held pipeline over the current operation. 382 if (instrumentor) 383 instrumentor->runBeforePipeline(mgr->getOpName(), parentInfo); 384 auto result = runPipeline(*mgr, &op, am.slice(&op)); 385 if (instrumentor) 386 instrumentor->runAfterPipeline(mgr->getOpName(), parentInfo); 387 388 if (failed(result)) 389 return signalPassFailure(); 390 } 391 } 392 } 393 } 394 395 OpToOpPassAdaptorParallel::OpToOpPassAdaptorParallel(OpPassManager &&mgr) 396 : OpToOpPassAdaptorBase(std::move(mgr)) {} 397 398 /// Utility functor that checks if the two ranges of pass managers have a size 399 /// mismatch. 400 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs, 401 ArrayRef<OpPassManager> rhs) { 402 return lhs.size() != rhs.size() || 403 llvm::any_of(llvm::seq<size_t>(0, lhs.size()), 404 [&](size_t i) { return lhs[i].size() != rhs[i].size(); }); 405 } 406 407 // Run the held pipeline asynchronously across the functions within the module. 408 void OpToOpPassAdaptorParallel::runOnOperation() { 409 AnalysisManager am = getAnalysisManager(); 410 411 // Create the async executors if they haven't been created, or if the main 412 // pipeline has changed. 413 if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs)) 414 asyncExecutors.assign(llvm::hardware_concurrency().compute_thread_count(), 415 mgrs); 416 417 // Run a prepass over the module to collect the operations to execute over. 418 // This ensures that an analysis manager exists for each operation, as well as 419 // providing a queue of operations to execute over. 420 std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs; 421 for (auto ®ion : getOperation()->getRegions()) { 422 for (auto &block : region) { 423 for (auto &op : block) { 424 // Add this operation iff the name matches the any of the pass managers. 425 if (findPassManagerFor(mgrs, op.getName())) 426 opAMPairs.emplace_back(&op, am.slice(&op)); 427 } 428 } 429 } 430 431 // A parallel diagnostic handler that provides deterministic diagnostic 432 // ordering. 433 ParallelDiagnosticHandler diagHandler(&getContext()); 434 435 // An index for the current operation/analysis manager pair. 436 std::atomic<unsigned> opIt(0); 437 438 // Get the current thread for this adaptor. 439 PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(), 440 this}; 441 auto *instrumentor = am.getPassInstrumentor(); 442 443 // An atomic failure variable for the async executors. 444 std::atomic<bool> passFailed(false); 445 llvm::parallel::for_each( 446 llvm::parallel::par, asyncExecutors.begin(), 447 std::next(asyncExecutors.begin(), 448 std::min(asyncExecutors.size(), opAMPairs.size())), 449 [&](MutableArrayRef<OpPassManager> pms) { 450 for (auto e = opAMPairs.size(); !passFailed && opIt < e;) { 451 // Get the next available operation index. 452 unsigned nextID = opIt++; 453 if (nextID >= e) 454 break; 455 456 // Set the order id for this thread in the diagnostic handler. 457 diagHandler.setOrderIDForThread(nextID); 458 459 // Get the pass manager for this operation and execute it. 460 auto &it = opAMPairs[nextID]; 461 auto *pm = findPassManagerFor(pms, it.first->getName()); 462 assert(pm && "expected valid pass manager for operation"); 463 464 if (instrumentor) 465 instrumentor->runBeforePipeline(pm->getOpName(), parentInfo); 466 auto pipelineResult = runPipeline(*pm, it.first, it.second); 467 if (instrumentor) 468 instrumentor->runAfterPipeline(pm->getOpName(), parentInfo); 469 470 // Drop this thread from being tracked by the diagnostic handler. 471 // After this task has finished, the thread may be used outside of 472 // this pass manager context meaning that we don't want to track 473 // diagnostics from it anymore. 474 diagHandler.eraseOrderIDForThread(); 475 476 // Handle a failed pipeline result. 477 if (failed(pipelineResult)) { 478 passFailed = true; 479 break; 480 } 481 } 482 }); 483 484 // Signal a failure if any of the executors failed. 485 if (passFailed) 486 signalPassFailure(); 487 } 488 489 /// Utility function to convert the given class to the base adaptor it is an 490 /// adaptor pass, returns nullptr otherwise. 491 OpToOpPassAdaptorBase *mlir::detail::getAdaptorPassBase(Pass *pass) { 492 if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass)) 493 return adaptor; 494 if (auto *adaptor = dyn_cast<OpToOpPassAdaptorParallel>(pass)) 495 return adaptor; 496 return nullptr; 497 } 498 499 //===----------------------------------------------------------------------===// 500 // PassCrashReproducer 501 //===----------------------------------------------------------------------===// 502 503 /// Safely run the pass manager over the given module, creating a reproducible 504 /// on failure or crash. 505 static LogicalResult runWithCrashRecovery(OpPassManager &pm, 506 ModuleAnalysisManager &am, 507 ModuleOp module, 508 StringRef crashReproducerFileName) { 509 /// Enable crash recovery. 510 llvm::CrashRecoveryContext::Enable(); 511 512 // Grab the textual pipeline executing within the pass manager first, just in 513 // case the pass manager becomes compromised. 514 std::string pipeline; 515 { 516 llvm::raw_string_ostream pipelineOS(pipeline); 517 pm.printAsTextualPipeline(pipelineOS); 518 } 519 520 // Clone the initial module before running it through the pass pipeline. 521 OwningModuleRef reproducerModule = module.clone(); 522 523 // Safely invoke the pass manager within a recovery context. 524 LogicalResult passManagerResult = failure(); 525 llvm::CrashRecoveryContext recoveryContext; 526 recoveryContext.RunSafelyOnThread( 527 [&] { passManagerResult = pm.run(module, am); }); 528 529 /// Disable crash recovery. 530 llvm::CrashRecoveryContext::Disable(); 531 if (succeeded(passManagerResult)) 532 return success(); 533 534 // The conversion failed, so generate a reproducible. 535 std::string error; 536 std::unique_ptr<llvm::ToolOutputFile> outputFile = 537 mlir::openOutputFile(crashReproducerFileName, &error); 538 if (!outputFile) 539 return emitError(UnknownLoc::get(pm.getContext()), 540 "<MLIR-PassManager-Crash-Reproducer>: ") 541 << error; 542 auto &outputOS = outputFile->os(); 543 544 // Output the current pass manager configuration. 545 outputOS << "// configuration: -pass-pipeline='" << pipeline << "'"; 546 if (pm.getImpl().disableThreads) 547 outputOS << " -disable-pass-threading"; 548 549 // TODO(riverriddle) Should this also be configured with a pass manager flag? 550 outputOS << "\n// note: verifyPasses=" 551 << (pm.getImpl().verifyPasses ? "true" : "false") << "\n"; 552 553 // Output the .mlir module. 554 reproducerModule->print(outputOS); 555 outputFile->keep(); 556 557 return reproducerModule->emitError() 558 << "A failure has been detected while processing the MLIR module, a " 559 "reproducer has been generated in '" 560 << crashReproducerFileName << "'"; 561 } 562 563 //===----------------------------------------------------------------------===// 564 // PassManager 565 //===----------------------------------------------------------------------===// 566 567 PassManager::PassManager(MLIRContext *ctx, bool verifyPasses) 568 : OpPassManager(OperationName(ModuleOp::getOperationName(), ctx), 569 /*disableThreads=*/false, verifyPasses), 570 passTiming(false) {} 571 572 PassManager::~PassManager() {} 573 574 /// Run the passes within this manager on the provided module. 575 LogicalResult PassManager::run(ModuleOp module) { 576 // Before running, make sure to coalesce any adjacent pass adaptors in the 577 // pipeline. 578 getImpl().coalesceAdjacentAdaptorPasses(); 579 580 // Construct an analysis manager for the pipeline. 581 ModuleAnalysisManager am(module, instrumentor.get()); 582 583 // If reproducer generation is enabled, run the pass manager with crash 584 // handling enabled. 585 LogicalResult result = 586 crashReproducerFileName 587 ? runWithCrashRecovery(*this, am, module, *crashReproducerFileName) 588 : OpPassManager::run(module, am); 589 590 // Dump all of the pass statistics if necessary. 591 if (passStatisticsMode) 592 dumpStatistics(); 593 return result; 594 } 595 596 /// Disable support for multi-threading within the pass manager. 597 void PassManager::disableMultithreading(bool disable) { 598 getImpl().disableThreads = disable; 599 } 600 601 /// Enable support for the pass manager to generate a reproducer on the event 602 /// of a crash or a pass failure. `outputFile` is a .mlir filename used to write 603 /// the generated reproducer. 604 void PassManager::enableCrashReproducerGeneration(StringRef outputFile) { 605 crashReproducerFileName = std::string(outputFile); 606 } 607 608 /// Add the provided instrumentation to the pass manager. 609 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) { 610 if (!instrumentor) 611 instrumentor = std::make_unique<PassInstrumentor>(); 612 613 instrumentor->addInstrumentation(std::move(pi)); 614 } 615 616 //===----------------------------------------------------------------------===// 617 // AnalysisManager 618 //===----------------------------------------------------------------------===// 619 620 /// Returns a pass instrumentation object for the current operation. 621 PassInstrumentor *AnalysisManager::getPassInstrumentor() const { 622 ParentPointerT curParent = parent; 623 while (auto *parentAM = curParent.dyn_cast<const AnalysisManager *>()) 624 curParent = parentAM->parent; 625 return curParent.get<const ModuleAnalysisManager *>()->getPassInstrumentor(); 626 } 627 628 /// Get an analysis manager for the given child operation. 629 AnalysisManager AnalysisManager::slice(Operation *op) { 630 assert(op->getParentOp() == impl->getOperation() && 631 "'op' has a different parent operation"); 632 auto it = impl->childAnalyses.find(op); 633 if (it == impl->childAnalyses.end()) 634 it = impl->childAnalyses 635 .try_emplace(op, std::make_unique<NestedAnalysisMap>(op)) 636 .first; 637 return {this, it->second.get()}; 638 } 639 640 /// Invalidate any non preserved analyses. 641 void detail::NestedAnalysisMap::invalidate( 642 const detail::PreservedAnalyses &pa) { 643 // If all analyses were preserved, then there is nothing to do here. 644 if (pa.isAll()) 645 return; 646 647 // Invalidate the analyses for the current operation directly. 648 analyses.invalidate(pa); 649 650 // If no analyses were preserved, then just simply clear out the child 651 // analysis results. 652 if (pa.isNone()) { 653 childAnalyses.clear(); 654 return; 655 } 656 657 // Otherwise, invalidate each child analysis map. 658 SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this); 659 while (!mapsToInvalidate.empty()) { 660 auto *map = mapsToInvalidate.pop_back_val(); 661 for (auto &analysisPair : map->childAnalyses) { 662 analysisPair.second->invalidate(pa); 663 if (!analysisPair.second->childAnalyses.empty()) 664 mapsToInvalidate.push_back(analysisPair.second.get()); 665 } 666 } 667 } 668 669 //===----------------------------------------------------------------------===// 670 // PassInstrumentation 671 //===----------------------------------------------------------------------===// 672 673 PassInstrumentation::~PassInstrumentation() {} 674 675 //===----------------------------------------------------------------------===// 676 // PassInstrumentor 677 //===----------------------------------------------------------------------===// 678 679 namespace mlir { 680 namespace detail { 681 struct PassInstrumentorImpl { 682 /// Mutex to keep instrumentation access thread-safe. 683 llvm::sys::SmartMutex<true> mutex; 684 685 /// Set of registered instrumentations. 686 std::vector<std::unique_ptr<PassInstrumentation>> instrumentations; 687 }; 688 } // end namespace detail 689 } // end namespace mlir 690 691 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {} 692 PassInstrumentor::~PassInstrumentor() {} 693 694 /// See PassInstrumentation::runBeforePipeline for details. 695 void PassInstrumentor::runBeforePipeline( 696 const OperationName &name, 697 const PassInstrumentation::PipelineParentInfo &parentInfo) { 698 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 699 for (auto &instr : impl->instrumentations) 700 instr->runBeforePipeline(name, parentInfo); 701 } 702 703 /// See PassInstrumentation::runAfterPipeline for details. 704 void PassInstrumentor::runAfterPipeline( 705 const OperationName &name, 706 const PassInstrumentation::PipelineParentInfo &parentInfo) { 707 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 708 for (auto &instr : llvm::reverse(impl->instrumentations)) 709 instr->runAfterPipeline(name, parentInfo); 710 } 711 712 /// See PassInstrumentation::runBeforePass for details. 713 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) { 714 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 715 for (auto &instr : impl->instrumentations) 716 instr->runBeforePass(pass, op); 717 } 718 719 /// See PassInstrumentation::runAfterPass for details. 720 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) { 721 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 722 for (auto &instr : llvm::reverse(impl->instrumentations)) 723 instr->runAfterPass(pass, op); 724 } 725 726 /// See PassInstrumentation::runAfterPassFailed for details. 727 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) { 728 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 729 for (auto &instr : llvm::reverse(impl->instrumentations)) 730 instr->runAfterPassFailed(pass, op); 731 } 732 733 /// See PassInstrumentation::runBeforeAnalysis for details. 734 void PassInstrumentor::runBeforeAnalysis(StringRef name, AnalysisID *id, 735 Operation *op) { 736 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 737 for (auto &instr : impl->instrumentations) 738 instr->runBeforeAnalysis(name, id, op); 739 } 740 741 /// See PassInstrumentation::runAfterAnalysis for details. 742 void PassInstrumentor::runAfterAnalysis(StringRef name, AnalysisID *id, 743 Operation *op) { 744 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 745 for (auto &instr : llvm::reverse(impl->instrumentations)) 746 instr->runAfterAnalysis(name, id, op); 747 } 748 749 /// Add the given instrumentation to the collection. 750 void PassInstrumentor::addInstrumentation( 751 std::unique_ptr<PassInstrumentation> pi) { 752 llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex); 753 impl->instrumentations.emplace_back(std::move(pi)); 754 } 755 756 constexpr AnalysisID mlir::detail::PreservedAnalyses::allAnalysesID; 757