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