xref: /llvm-project-15.0.7/mlir/lib/Pass/Pass.cpp (revision b9378690)
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/IR/Diagnostics.h"
16 #include "mlir/IR/Dialect.h"
17 #include "mlir/IR/Verifier.h"
18 #include "mlir/Support/FileUtilities.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/Parallel.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 
30 using namespace mlir;
31 using namespace mlir::detail;
32 
33 //===----------------------------------------------------------------------===//
34 // Pass
35 //===----------------------------------------------------------------------===//
36 
37 /// Out of line virtual method to ensure vtables and metadata are emitted to a
38 /// single .o file.
39 void Pass::anchor() {}
40 
41 /// Attempt to initialize the options of this pass from the given string.
42 LogicalResult Pass::initializeOptions(StringRef options) {
43   return passOptions.parseFromString(options);
44 }
45 
46 /// Copy the option values from 'other', which is another instance of this
47 /// pass.
48 void Pass::copyOptionValuesFrom(const Pass *other) {
49   passOptions.copyOptionValuesFrom(other->passOptions);
50 }
51 
52 /// Prints out the pass in the textual representation of pipelines. If this is
53 /// an adaptor pass, print with the op_name(sub_pass,...) format.
54 void Pass::printAsTextualPipeline(raw_ostream &os) {
55   // Special case for adaptors to use the 'op_name(sub_passes)' format.
56   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(this)) {
57     llvm::interleaveComma(adaptor->getPassManagers(), os,
58                           [&](OpPassManager &pm) {
59                             os << pm.getOpName() << "(";
60                             pm.printAsTextualPipeline(os);
61                             os << ")";
62                           });
63     return;
64   }
65   // Otherwise, print the pass argument followed by its options. If the pass
66   // doesn't have an argument, print the name of the pass to give some indicator
67   // of what pass was run.
68   StringRef argument = getArgument();
69   if (!argument.empty())
70     os << argument;
71   else
72     os << "unknown<" << getName() << ">";
73   passOptions.print(os);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // OpPassManagerImpl
78 //===----------------------------------------------------------------------===//
79 
80 namespace mlir {
81 namespace detail {
82 struct OpPassManagerImpl {
83   OpPassManagerImpl(Identifier identifier, OpPassManager::Nesting nesting)
84       : name(identifier.str()), identifier(identifier),
85         initializationGeneration(0), nesting(nesting) {}
86   OpPassManagerImpl(StringRef name, OpPassManager::Nesting nesting)
87       : name(name), initializationGeneration(0), nesting(nesting) {}
88 
89   /// Merge the passes of this pass manager into the one provided.
90   void mergeInto(OpPassManagerImpl &rhs);
91 
92   /// Nest a new operation pass manager for the given operation kind under this
93   /// pass manager.
94   OpPassManager &nest(Identifier nestedName);
95   OpPassManager &nest(StringRef nestedName);
96 
97   /// Add the given pass to this pass manager. If this pass has a concrete
98   /// operation type, it must be the same type as this pass manager.
99   void addPass(std::unique_ptr<Pass> pass);
100 
101   /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
102   /// recursively through the pipeline graph.
103   void coalesceAdjacentAdaptorPasses();
104 
105   /// Split all of AdaptorPasses such that each adaptor only contains one leaf
106   /// pass.
107   void splitAdaptorPasses();
108 
109   /// Return the operation name of this pass manager as an identifier.
110   Identifier getOpName(MLIRContext &context) {
111     if (!identifier)
112       identifier = Identifier::get(name, &context);
113     return *identifier;
114   }
115 
116   /// The name of the operation that passes of this pass manager operate on.
117   std::string name;
118 
119   /// The cached identifier (internalized in the context) for the name of the
120   /// operation that passes of this pass manager operate on.
121   Optional<Identifier> identifier;
122 
123   /// The set of passes to run as part of this pass manager.
124   std::vector<std::unique_ptr<Pass>> passes;
125 
126   /// The current initialization generation of this pass manager. This is used
127   /// to indicate when a pass manager should be reinitialized.
128   unsigned initializationGeneration;
129 
130   /// Control the implicit nesting of passes that mismatch the name set for this
131   /// OpPassManager.
132   OpPassManager::Nesting nesting;
133 };
134 } // end namespace detail
135 } // end namespace mlir
136 
137 void OpPassManagerImpl::mergeInto(OpPassManagerImpl &rhs) {
138   assert(name == rhs.name && "merging unrelated pass managers");
139   for (auto &pass : passes)
140     rhs.passes.push_back(std::move(pass));
141   passes.clear();
142 }
143 
144 OpPassManager &OpPassManagerImpl::nest(Identifier nestedName) {
145   OpPassManager nested(nestedName, nesting);
146   auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
147   addPass(std::unique_ptr<Pass>(adaptor));
148   return adaptor->getPassManagers().front();
149 }
150 
151 OpPassManager &OpPassManagerImpl::nest(StringRef nestedName) {
152   OpPassManager nested(nestedName, nesting);
153   auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
154   addPass(std::unique_ptr<Pass>(adaptor));
155   return adaptor->getPassManagers().front();
156 }
157 
158 void OpPassManagerImpl::addPass(std::unique_ptr<Pass> pass) {
159   // If this pass runs on a different operation than this pass manager, then
160   // implicitly nest a pass manager for this operation if enabled.
161   auto passOpName = pass->getOpName();
162   if (passOpName && passOpName->str() != name) {
163     if (nesting == OpPassManager::Nesting::Implicit)
164       return nest(*passOpName).addPass(std::move(pass));
165     llvm::report_fatal_error(llvm::Twine("Can't add pass '") + pass->getName() +
166                              "' restricted to '" + *passOpName +
167                              "' on a PassManager intended to run on '" + name +
168                              "', did you intend to nest?");
169   }
170 
171   passes.emplace_back(std::move(pass));
172 }
173 
174 void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() {
175   // Bail out early if there are no adaptor passes.
176   if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) {
177         return isa<OpToOpPassAdaptor>(pass.get());
178       }))
179     return;
180 
181   // Walk the pass list and merge adjacent adaptors.
182   OpToOpPassAdaptor *lastAdaptor = nullptr;
183   for (auto it = passes.begin(), e = passes.end(); it != e; ++it) {
184     // Check to see if this pass is an adaptor.
185     if (auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(it->get())) {
186       // If it is the first adaptor in a possible chain, remember it and
187       // continue.
188       if (!lastAdaptor) {
189         lastAdaptor = currentAdaptor;
190         continue;
191       }
192 
193       // Otherwise, merge into the existing adaptor and delete the current one.
194       currentAdaptor->mergeInto(*lastAdaptor);
195       it->reset();
196     } else if (lastAdaptor) {
197       // If this pass is not an adaptor, then coalesce and forget any existing
198       // adaptor.
199       for (auto &pm : lastAdaptor->getPassManagers())
200         pm.getImpl().coalesceAdjacentAdaptorPasses();
201       lastAdaptor = nullptr;
202     }
203   }
204 
205   // If there was an adaptor at the end of the manager, coalesce it as well.
206   if (lastAdaptor) {
207     for (auto &pm : lastAdaptor->getPassManagers())
208       pm.getImpl().coalesceAdjacentAdaptorPasses();
209   }
210 
211   // Now that the adaptors have been merged, erase the empty slot corresponding
212   // to the merged adaptors that were nulled-out in the loop above.
213   llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
214 }
215 
216 void OpPassManagerImpl::splitAdaptorPasses() {
217   std::vector<std::unique_ptr<Pass>> oldPasses;
218   std::swap(passes, oldPasses);
219 
220   for (std::unique_ptr<Pass> &pass : oldPasses) {
221     // If this pass isn't an adaptor, move it directly to the new pass list.
222     auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(pass.get());
223     if (!currentAdaptor) {
224       addPass(std::move(pass));
225       continue;
226     }
227 
228     // Otherwise, split the adaptors of each manager within the adaptor.
229     for (OpPassManager &adaptorPM : currentAdaptor->getPassManagers()) {
230       adaptorPM.getImpl().splitAdaptorPasses();
231       for (std::unique_ptr<Pass> &nestedPass : adaptorPM.getImpl().passes)
232         nest(adaptorPM.getOpName()).addPass(std::move(nestedPass));
233     }
234   }
235 }
236 
237 //===----------------------------------------------------------------------===//
238 // OpPassManager
239 //===----------------------------------------------------------------------===//
240 
241 OpPassManager::OpPassManager(Identifier name, Nesting nesting)
242     : impl(new OpPassManagerImpl(name, nesting)) {}
243 OpPassManager::OpPassManager(StringRef name, Nesting nesting)
244     : impl(new OpPassManagerImpl(name, nesting)) {}
245 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
246 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
247 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
248   impl.reset(new OpPassManagerImpl(rhs.impl->name, rhs.impl->nesting));
249   impl->initializationGeneration = rhs.impl->initializationGeneration;
250   for (auto &pass : rhs.impl->passes)
251     impl->passes.emplace_back(pass->clone());
252   return *this;
253 }
254 
255 OpPassManager::~OpPassManager() {}
256 
257 OpPassManager::pass_iterator OpPassManager::begin() {
258   return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
259 }
260 OpPassManager::pass_iterator OpPassManager::end() {
261   return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
262 }
263 
264 OpPassManager::const_pass_iterator OpPassManager::begin() const {
265   return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
266 }
267 OpPassManager::const_pass_iterator OpPassManager::end() const {
268   return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
269 }
270 
271 /// Nest a new operation pass manager for the given operation kind under this
272 /// pass manager.
273 OpPassManager &OpPassManager::nest(Identifier nestedName) {
274   return impl->nest(nestedName);
275 }
276 OpPassManager &OpPassManager::nest(StringRef nestedName) {
277   return impl->nest(nestedName);
278 }
279 
280 /// Add the given pass to this pass manager. If this pass has a concrete
281 /// operation type, it must be the same type as this pass manager.
282 void OpPassManager::addPass(std::unique_ptr<Pass> pass) {
283   impl->addPass(std::move(pass));
284 }
285 
286 /// Returns the number of passes held by this manager.
287 size_t OpPassManager::size() const { return impl->passes.size(); }
288 
289 /// Returns the internal implementation instance.
290 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
291 
292 /// Return the operation name that this pass manager operates on.
293 StringRef OpPassManager::getOpName() const { return impl->name; }
294 
295 /// Return the operation name that this pass manager operates on.
296 Identifier OpPassManager::getOpName(MLIRContext &context) const {
297   return impl->getOpName(context);
298 }
299 
300 /// Prints out the given passes as the textual representation of a pipeline.
301 static void printAsTextualPipeline(ArrayRef<std::unique_ptr<Pass>> passes,
302                                    raw_ostream &os) {
303   llvm::interleaveComma(passes, os, [&](const std::unique_ptr<Pass> &pass) {
304     pass->printAsTextualPipeline(os);
305   });
306 }
307 
308 /// Prints out the passes of the pass manager as the textual representation
309 /// of pipelines.
310 void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
311   ::printAsTextualPipeline(impl->passes, os);
312 }
313 
314 void OpPassManager::dump() {
315   llvm::errs() << "Pass Manager with " << impl->passes.size() << " passes: ";
316   ::printAsTextualPipeline(impl->passes, llvm::errs());
317   llvm::errs() << "\n";
318 }
319 
320 static void registerDialectsForPipeline(const OpPassManager &pm,
321                                         DialectRegistry &dialects) {
322   for (const Pass &pass : pm.getPasses())
323     pass.getDependentDialects(dialects);
324 }
325 
326 void OpPassManager::getDependentDialects(DialectRegistry &dialects) const {
327   registerDialectsForPipeline(*this, dialects);
328 }
329 
330 void OpPassManager::setNesting(Nesting nesting) { impl->nesting = nesting; }
331 
332 OpPassManager::Nesting OpPassManager::getNesting() { return impl->nesting; }
333 
334 void OpPassManager::initialize(MLIRContext *context,
335                                unsigned newInitGeneration) {
336   if (impl->initializationGeneration == newInitGeneration)
337     return;
338   impl->initializationGeneration = newInitGeneration;
339   for (Pass &pass : getPasses()) {
340     // If this pass isn't an adaptor, directly initialize it.
341     auto *adaptor = dyn_cast<OpToOpPassAdaptor>(&pass);
342     if (!adaptor) {
343       pass.initialize(context);
344       continue;
345     }
346 
347     // Otherwise, initialize each of the adaptors pass managers.
348     for (OpPassManager &adaptorPM : adaptor->getPassManagers())
349       adaptorPM.initialize(context, newInitGeneration);
350   }
351 }
352 
353 //===----------------------------------------------------------------------===//
354 // OpToOpPassAdaptor
355 //===----------------------------------------------------------------------===//
356 
357 LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
358                                      AnalysisManager am, bool verifyPasses,
359                                      unsigned parentInitGeneration) {
360   if (!op->isRegistered())
361     return op->emitOpError()
362            << "trying to schedule a pass on an unregistered operation";
363   if (!op->hasTrait<OpTrait::IsIsolatedFromAbove>())
364     return op->emitOpError() << "trying to schedule a pass on an operation not "
365                                 "marked as 'IsolatedFromAbove'";
366 
367   // Initialize the pass state with a callback for the pass to dynamically
368   // execute a pipeline on the currently visited operation.
369   PassInstrumentor *pi = am.getPassInstrumentor();
370   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
371                                                         pass};
372   auto dynamic_pipeline_callback = [&](OpPassManager &pipeline,
373                                        Operation *root) -> LogicalResult {
374     if (!op->isAncestor(root))
375       return root->emitOpError()
376              << "Trying to schedule a dynamic pipeline on an "
377                 "operation that isn't "
378                 "nested under the current operation the pass is processing";
379     assert(pipeline.getOpName() == root->getName().getStringRef());
380 
381     // Initialize the user provided pipeline and execute the pipeline.
382     pipeline.initialize(root->getContext(), parentInitGeneration);
383     AnalysisManager nestedAm = root == op ? am : am.nest(root);
384     return OpToOpPassAdaptor::runPipeline(pipeline.getPasses(), root, nestedAm,
385                                           verifyPasses, parentInitGeneration,
386                                           pi, &parentInfo);
387   };
388   pass->passState.emplace(op, am, dynamic_pipeline_callback);
389 
390   // Instrument before the pass has run.
391   if (pi)
392     pi->runBeforePass(pass, op);
393 
394   // Invoke the virtual runOnOperation method.
395   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
396     adaptor->runOnOperation(verifyPasses);
397   else
398     pass->runOnOperation();
399   bool passFailed = pass->passState->irAndPassFailed.getInt();
400 
401   // Invalidate any non preserved analyses.
402   am.invalidate(pass->passState->preservedAnalyses);
403 
404   // Run the verifier if this pass didn't fail already.
405   if (!passFailed && verifyPasses)
406     passFailed = failed(verify(op));
407 
408   // Instrument after the pass has run.
409   if (pi) {
410     if (passFailed)
411       pi->runAfterPassFailed(pass, op);
412     else
413       pi->runAfterPass(pass, op);
414   }
415 
416   // Return if the pass signaled a failure.
417   return failure(passFailed);
418 }
419 
420 /// Run the given operation and analysis manager on a provided op pass manager.
421 LogicalResult OpToOpPassAdaptor::runPipeline(
422     iterator_range<OpPassManager::pass_iterator> passes, Operation *op,
423     AnalysisManager am, bool verifyPasses, unsigned parentInitGeneration,
424     PassInstrumentor *instrumentor,
425     const PassInstrumentation::PipelineParentInfo *parentInfo) {
426   assert((!instrumentor || parentInfo) &&
427          "expected parent info if instrumentor is provided");
428   auto scope_exit = llvm::make_scope_exit([&] {
429     // Clear out any computed operation analyses. These analyses won't be used
430     // any more in this pipeline, and this helps reduce the current working set
431     // of memory. If preserving these analyses becomes important in the future
432     // we can re-evaluate this.
433     am.clear();
434   });
435 
436   // Run the pipeline over the provided operation.
437   if (instrumentor)
438     instrumentor->runBeforePipeline(op->getName().getIdentifier(), *parentInfo);
439   for (Pass &pass : passes)
440     if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration)))
441       return failure();
442   if (instrumentor)
443     instrumentor->runAfterPipeline(op->getName().getIdentifier(), *parentInfo);
444   return success();
445 }
446 
447 /// Find an operation pass manager that can operate on an operation of the given
448 /// type, or nullptr if one does not exist.
449 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
450                                          StringRef name) {
451   auto it = llvm::find_if(
452       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
453   return it == mgrs.end() ? nullptr : &*it;
454 }
455 
456 /// Find an operation pass manager that can operate on an operation of the given
457 /// type, or nullptr if one does not exist.
458 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
459                                          Identifier name,
460                                          MLIRContext &context) {
461   auto it = llvm::find_if(
462       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName(context) == name; });
463   return it == mgrs.end() ? nullptr : &*it;
464 }
465 
466 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) {
467   mgrs.emplace_back(std::move(mgr));
468 }
469 
470 void OpToOpPassAdaptor::getDependentDialects(DialectRegistry &dialects) const {
471   for (auto &pm : mgrs)
472     pm.getDependentDialects(dialects);
473 }
474 
475 /// Merge the current pass adaptor into given 'rhs'.
476 void OpToOpPassAdaptor::mergeInto(OpToOpPassAdaptor &rhs) {
477   for (auto &pm : mgrs) {
478     // If an existing pass manager exists, then merge the given pass manager
479     // into it.
480     if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
481       pm.getImpl().mergeInto(existingPM->getImpl());
482     } else {
483       // Otherwise, add the given pass manager to the list.
484       rhs.mgrs.emplace_back(std::move(pm));
485     }
486   }
487   mgrs.clear();
488 
489   // After coalescing, sort the pass managers within rhs by name.
490   llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
491                        [](const OpPassManager *lhs, const OpPassManager *rhs) {
492                          return lhs->getOpName().compare(rhs->getOpName());
493                        });
494 }
495 
496 /// Returns the adaptor pass name.
497 std::string OpToOpPassAdaptor::getAdaptorName() {
498   std::string name = "Pipeline Collection : [";
499   llvm::raw_string_ostream os(name);
500   llvm::interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
501     os << '\'' << pm.getOpName() << '\'';
502   });
503   os << ']';
504   return os.str();
505 }
506 
507 void OpToOpPassAdaptor::runOnOperation() {
508   llvm_unreachable(
509       "Unexpected call to Pass::runOnOperation() on OpToOpPassAdaptor");
510 }
511 
512 /// Run the held pipeline over all nested operations.
513 void OpToOpPassAdaptor::runOnOperation(bool verifyPasses) {
514   if (getContext().isMultithreadingEnabled())
515     runOnOperationAsyncImpl(verifyPasses);
516   else
517     runOnOperationImpl(verifyPasses);
518 }
519 
520 /// Run this pass adaptor synchronously.
521 void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
522   auto am = getAnalysisManager();
523   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
524                                                         this};
525   auto *instrumentor = am.getPassInstrumentor();
526   for (auto &region : getOperation()->getRegions()) {
527     for (auto &block : region) {
528       for (auto &op : block) {
529         auto *mgr = findPassManagerFor(mgrs, op.getName().getIdentifier(),
530                                        *op.getContext());
531         if (!mgr)
532           continue;
533 
534         // Run the held pipeline over the current operation.
535         unsigned initGeneration = mgr->impl->initializationGeneration;
536         if (failed(runPipeline(mgr->getPasses(), &op, am.nest(&op),
537                                verifyPasses, initGeneration, instrumentor,
538                                &parentInfo)))
539           return signalPassFailure();
540       }
541     }
542   }
543 }
544 
545 /// Utility functor that checks if the two ranges of pass managers have a size
546 /// mismatch.
547 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
548                             ArrayRef<OpPassManager> rhs) {
549   return lhs.size() != rhs.size() ||
550          llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
551                       [&](size_t i) { return lhs[i].size() != rhs[i].size(); });
552 }
553 
554 /// Run this pass adaptor synchronously.
555 void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
556   AnalysisManager am = getAnalysisManager();
557 
558   // Create the async executors if they haven't been created, or if the main
559   // pipeline has changed.
560   if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
561     asyncExecutors.assign(llvm::hardware_concurrency().compute_thread_count(),
562                           mgrs);
563 
564   // Run a prepass over the operation to collect the nested operations to
565   // execute over. This ensures that an analysis manager exists for each
566   // operation, as well as providing a queue of operations to execute over.
567   std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
568   for (auto &region : getOperation()->getRegions()) {
569     for (auto &block : region) {
570       for (auto &op : block) {
571         // Add this operation iff the name matches any of the pass managers.
572         if (findPassManagerFor(mgrs, op.getName().getIdentifier(),
573                                getContext()))
574           opAMPairs.emplace_back(&op, am.nest(&op));
575       }
576     }
577   }
578 
579   // A parallel diagnostic handler that provides deterministic diagnostic
580   // ordering.
581   ParallelDiagnosticHandler diagHandler(&getContext());
582 
583   // An index for the current operation/analysis manager pair.
584   std::atomic<unsigned> opIt(0);
585 
586   // Get the current thread for this adaptor.
587   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
588                                                         this};
589   auto *instrumentor = am.getPassInstrumentor();
590 
591   // An atomic failure variable for the async executors.
592   std::atomic<bool> passFailed(false);
593   llvm::parallelForEach(
594       asyncExecutors.begin(),
595       std::next(asyncExecutors.begin(),
596                 std::min(asyncExecutors.size(), opAMPairs.size())),
597       [&](MutableArrayRef<OpPassManager> pms) {
598         for (auto e = opAMPairs.size(); !passFailed && opIt < e;) {
599           // Get the next available operation index.
600           unsigned nextID = opIt++;
601           if (nextID >= e)
602             break;
603 
604           // Set the order id for this thread in the diagnostic handler.
605           diagHandler.setOrderIDForThread(nextID);
606 
607           // Get the pass manager for this operation and execute it.
608           auto &it = opAMPairs[nextID];
609           auto *pm = findPassManagerFor(
610               pms, it.first->getName().getIdentifier(), getContext());
611           assert(pm && "expected valid pass manager for operation");
612 
613           unsigned initGeneration = pm->impl->initializationGeneration;
614           LogicalResult pipelineResult =
615               runPipeline(pm->getPasses(), it.first, it.second, verifyPasses,
616                           initGeneration, instrumentor, &parentInfo);
617 
618           // Drop this thread from being tracked by the diagnostic handler.
619           // After this task has finished, the thread may be used outside of
620           // this pass manager context meaning that we don't want to track
621           // diagnostics from it anymore.
622           diagHandler.eraseOrderIDForThread();
623 
624           // Handle a failed pipeline result.
625           if (failed(pipelineResult)) {
626             passFailed = true;
627             break;
628           }
629         }
630       });
631 
632   // Signal a failure if any of the executors failed.
633   if (passFailed)
634     signalPassFailure();
635 }
636 
637 //===----------------------------------------------------------------------===//
638 // PassCrashReproducer
639 //===----------------------------------------------------------------------===//
640 
641 namespace {
642 /// This class contains all of the context for generating a recovery reproducer.
643 /// Each recovery context is registered globally to allow for generating
644 /// reproducers when a signal is raised, such as a segfault.
645 struct RecoveryReproducerContext {
646   RecoveryReproducerContext(MutableArrayRef<std::unique_ptr<Pass>> passes,
647                             Operation *op,
648                             PassManager::ReproducerStreamFactory &crashStream,
649                             bool disableThreads, bool verifyPasses);
650   ~RecoveryReproducerContext();
651 
652   /// Generate a reproducer with the current context.
653   LogicalResult generate(std::string &error);
654 
655 private:
656   /// This function is invoked in the event of a crash.
657   static void crashHandler(void *);
658 
659   /// Register a signal handler to run in the event of a crash.
660   static void registerSignalHandler();
661 
662   /// The textual description of the currently executing pipeline.
663   std::string pipeline;
664 
665   /// The MLIR operation representing the IR before the crash.
666   Operation *preCrashOperation;
667 
668   /// The factory for the reproducer output stream to use when generating the
669   /// reproducer.
670   PassManager::ReproducerStreamFactory &crashStreamFactory;
671 
672   /// Various pass manager and context flags.
673   bool disableThreads;
674   bool verifyPasses;
675 
676   /// The current set of active reproducer contexts. This is used in the event
677   /// of a crash. This is not thread_local as the pass manager may produce any
678   /// number of child threads. This uses a set to allow for multiple MLIR pass
679   /// managers to be running at the same time.
680   static llvm::ManagedStatic<llvm::sys::SmartMutex<true>> reproducerMutex;
681   static llvm::ManagedStatic<
682       llvm::SmallSetVector<RecoveryReproducerContext *, 1>>
683       reproducerSet;
684 };
685 
686 /// Instance of ReproducerStream backed by file.
687 struct FileReproducerStream : public PassManager::ReproducerStream {
688   FileReproducerStream(std::unique_ptr<llvm::ToolOutputFile> outputFile)
689       : outputFile(std::move(outputFile)) {}
690   ~FileReproducerStream() override;
691 
692   /// Description of the reproducer stream.
693   StringRef description() override;
694 
695   /// Stream on which to output reprooducer.
696   raw_ostream &os() override;
697 
698 private:
699   /// ToolOutputFile corresponding to opened `filename`.
700   std::unique_ptr<llvm::ToolOutputFile> outputFile = nullptr;
701 };
702 
703 } // end anonymous namespace
704 
705 llvm::ManagedStatic<llvm::sys::SmartMutex<true>>
706     RecoveryReproducerContext::reproducerMutex;
707 llvm::ManagedStatic<llvm::SmallSetVector<RecoveryReproducerContext *, 1>>
708     RecoveryReproducerContext::reproducerSet;
709 
710 RecoveryReproducerContext::RecoveryReproducerContext(
711     MutableArrayRef<std::unique_ptr<Pass>> passes, Operation *op,
712     PassManager::ReproducerStreamFactory &crashStreamFactory,
713     bool disableThreads, bool verifyPasses)
714     : preCrashOperation(op->clone()), crashStreamFactory(crashStreamFactory),
715       disableThreads(disableThreads), verifyPasses(verifyPasses) {
716   // Grab the textual pipeline being executed..
717   {
718     llvm::raw_string_ostream pipelineOS(pipeline);
719     ::printAsTextualPipeline(passes, pipelineOS);
720   }
721 
722   // Make sure that the handler is registered, and update the current context.
723   llvm::sys::SmartScopedLock<true> producerLock(*reproducerMutex);
724   if (reproducerSet->empty())
725     llvm::CrashRecoveryContext::Enable();
726   registerSignalHandler();
727   reproducerSet->insert(this);
728 }
729 
730 RecoveryReproducerContext::~RecoveryReproducerContext() {
731   // Erase the cloned preCrash IR that we cached.
732   preCrashOperation->erase();
733 
734   llvm::sys::SmartScopedLock<true> producerLock(*reproducerMutex);
735   reproducerSet->remove(this);
736   if (reproducerSet->empty())
737     llvm::CrashRecoveryContext::Disable();
738 }
739 
740 /// Description of the reproducer stream.
741 StringRef FileReproducerStream::description() {
742   return outputFile->getFilename();
743 }
744 
745 /// Stream on which to output reproducer.
746 raw_ostream &FileReproducerStream::os() { return outputFile->os(); }
747 
748 FileReproducerStream::~FileReproducerStream() { outputFile->keep(); }
749 
750 LogicalResult RecoveryReproducerContext::generate(std::string &error) {
751   std::unique_ptr<PassManager::ReproducerStream> crashStream =
752       crashStreamFactory(error);
753   if (!crashStream)
754     return failure();
755 
756   // Output the current pass manager configuration.
757   auto &os = crashStream->os();
758   os << "// configuration: -pass-pipeline='" << pipeline << "'";
759   if (disableThreads)
760     os << " -mlir-disable-threading";
761   if (verifyPasses)
762     os << " -verify-each";
763   os << '\n';
764 
765   // Output the .mlir module.
766   preCrashOperation->print(os);
767 
768   bool shouldPrintOnOp =
769       preCrashOperation->getContext()->shouldPrintOpOnDiagnostic();
770   preCrashOperation->getContext()->printOpOnDiagnostic(false);
771   preCrashOperation->emitError()
772       << "A failure has been detected while processing the MLIR module, a "
773          "reproducer has been generated in '"
774       << crashStream->description() << "'";
775   preCrashOperation->getContext()->printOpOnDiagnostic(shouldPrintOnOp);
776   return success();
777 }
778 
779 void RecoveryReproducerContext::crashHandler(void *) {
780   // Walk the current stack of contexts and generate a reproducer for each one.
781   // We can't know for certain which one was the cause, so we need to generate
782   // a reproducer for all of them.
783   std::string ignored;
784   for (RecoveryReproducerContext *context : *reproducerSet)
785     (void)context->generate(ignored);
786 }
787 
788 void RecoveryReproducerContext::registerSignalHandler() {
789   // Ensure that the handler is only registered once.
790   static bool registered =
791       (llvm::sys::AddSignalHandler(crashHandler, nullptr), false);
792   (void)registered;
793 }
794 
795 /// Run the pass manager with crash recover enabled.
796 LogicalResult PassManager::runWithCrashRecovery(Operation *op,
797                                                 AnalysisManager am) {
798   // If this isn't a local producer, run all of the passes in recovery mode.
799   if (!localReproducer)
800     return runWithCrashRecovery(impl->passes, op, am);
801 
802   // Split the passes within adaptors to ensure that each pass can be run in
803   // isolation.
804   impl->splitAdaptorPasses();
805 
806   // If this is a local producer, run each of the passes individually.
807   MutableArrayRef<std::unique_ptr<Pass>> passes = impl->passes;
808   for (std::unique_ptr<Pass> &pass : passes)
809     if (failed(runWithCrashRecovery(pass, op, am)))
810       return failure();
811   return success();
812 }
813 
814 /// Run the given passes with crash recover enabled.
815 LogicalResult
816 PassManager::runWithCrashRecovery(MutableArrayRef<std::unique_ptr<Pass>> passes,
817                                   Operation *op, AnalysisManager am) {
818   RecoveryReproducerContext context(passes, op, crashReproducerStreamFactory,
819                                     !getContext()->isMultithreadingEnabled(),
820                                     verifyPasses);
821 
822   // Safely invoke the passes within a recovery context.
823   LogicalResult passManagerResult = failure();
824   llvm::CrashRecoveryContext recoveryContext;
825   recoveryContext.RunSafelyOnThread([&] {
826     for (std::unique_ptr<Pass> &pass : passes)
827       if (failed(OpToOpPassAdaptor::run(pass.get(), op, am, verifyPasses,
828                                         impl->initializationGeneration)))
829         return;
830     passManagerResult = success();
831   });
832   if (succeeded(passManagerResult))
833     return success();
834 
835   std::string error;
836   if (failed(context.generate(error)))
837     return op->emitError("<MLIR-PassManager-Crash-Reproducer>: ") << error;
838   return failure();
839 }
840 
841 //===----------------------------------------------------------------------===//
842 // PassManager
843 //===----------------------------------------------------------------------===//
844 
845 PassManager::PassManager(MLIRContext *ctx, Nesting nesting,
846                          StringRef operationName)
847     : OpPassManager(Identifier::get(operationName, ctx), nesting), context(ctx),
848       initializationKey(DenseMapInfo<llvm::hash_code>::getTombstoneKey()),
849       passTiming(false), localReproducer(false), verifyPasses(true) {}
850 
851 PassManager::~PassManager() {}
852 
853 void PassManager::enableVerifier(bool enabled) { verifyPasses = enabled; }
854 
855 /// Run the passes within this manager on the provided operation.
856 LogicalResult PassManager::run(Operation *op) {
857   MLIRContext *context = getContext();
858   assert(op->getName().getIdentifier() == getOpName(*context) &&
859          "operation has a different name than the PassManager");
860 
861   // Before running, make sure to coalesce any adjacent pass adaptors in the
862   // pipeline.
863   getImpl().coalesceAdjacentAdaptorPasses();
864 
865   // Register all dialects for the current pipeline.
866   DialectRegistry dependentDialects;
867   getDependentDialects(dependentDialects);
868   context->appendDialectRegistry(dependentDialects);
869   for (StringRef name : dependentDialects.getDialectNames())
870     context->getOrLoadDialect(name);
871 
872   // Initialize all of the passes within the pass manager with a new generation.
873   llvm::hash_code newInitKey = context->getRegistryHash();
874   if (newInitKey != initializationKey) {
875     initialize(context, impl->initializationGeneration + 1);
876     initializationKey = newInitKey;
877   }
878 
879   // Construct a top level analysis manager for the pipeline.
880   ModuleAnalysisManager am(op, instrumentor.get());
881 
882   // Notify the context that we start running a pipeline for book keeping.
883   context->enterMultiThreadedExecution();
884 
885   // If reproducer generation is enabled, run the pass manager with crash
886   // handling enabled.
887   LogicalResult result =
888       crashReproducerStreamFactory
889           ? runWithCrashRecovery(op, am)
890           : OpToOpPassAdaptor::runPipeline(getPasses(), op, am, verifyPasses,
891                                            impl->initializationGeneration);
892 
893   // Notify the context that the run is done.
894   context->exitMultiThreadedExecution();
895 
896   // Dump all of the pass statistics if necessary.
897   if (passStatisticsMode)
898     dumpStatistics();
899   return result;
900 }
901 
902 /// Enable support for the pass manager to generate a reproducer on the event
903 /// of a crash or a pass failure. `outputFile` is a .mlir filename used to write
904 /// the generated reproducer. If `genLocalReproducer` is true, the pass manager
905 /// will attempt to generate a local reproducer that contains the smallest
906 /// pipeline.
907 void PassManager::enableCrashReproducerGeneration(StringRef outputFile,
908                                                   bool genLocalReproducer) {
909   // Capture the filename by value in case outputFile is out of scope when
910   // invoked.
911   std::string filename = outputFile.str();
912   enableCrashReproducerGeneration(
913       [filename](std::string &error) -> std::unique_ptr<ReproducerStream> {
914         std::unique_ptr<llvm::ToolOutputFile> outputFile =
915             mlir::openOutputFile(filename, &error);
916         if (!outputFile) {
917           error = "Failed to create reproducer stream: " + error;
918           return nullptr;
919         }
920         return std::make_unique<FileReproducerStream>(std::move(outputFile));
921       },
922       genLocalReproducer);
923 }
924 
925 /// Enable support for the pass manager to generate a reproducer on the event
926 /// of a crash or a pass failure. `factory` is used to construct the streams
927 /// to write the generated reproducer to. If `genLocalReproducer` is true, the
928 /// pass manager will attempt to generate a local reproducer that contains the
929 /// smallest pipeline.
930 void PassManager::enableCrashReproducerGeneration(
931     ReproducerStreamFactory factory, bool genLocalReproducer) {
932   crashReproducerStreamFactory = factory;
933   localReproducer = genLocalReproducer;
934 }
935 
936 /// Add the provided instrumentation to the pass manager.
937 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
938   if (!instrumentor)
939     instrumentor = std::make_unique<PassInstrumentor>();
940 
941   instrumentor->addInstrumentation(std::move(pi));
942 }
943 
944 //===----------------------------------------------------------------------===//
945 // AnalysisManager
946 //===----------------------------------------------------------------------===//
947 
948 /// Get an analysis manager for the given operation, which must be a proper
949 /// descendant of the current operation represented by this analysis manager.
950 AnalysisManager AnalysisManager::nest(Operation *op) {
951   Operation *currentOp = impl->getOperation();
952   assert(currentOp->isProperAncestor(op) &&
953          "expected valid descendant operation");
954 
955   // Check for the base case where the provided operation is immediately nested.
956   if (currentOp == op->getParentOp())
957     return nestImmediate(op);
958 
959   // Otherwise, we need to collect all ancestors up to the current operation.
960   SmallVector<Operation *, 4> opAncestors;
961   do {
962     opAncestors.push_back(op);
963     op = op->getParentOp();
964   } while (op != currentOp);
965 
966   AnalysisManager result = *this;
967   for (Operation *op : llvm::reverse(opAncestors))
968     result = result.nestImmediate(op);
969   return result;
970 }
971 
972 /// Get an analysis manager for the given immediately nested child operation.
973 AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
974   assert(impl->getOperation() == op->getParentOp() &&
975          "expected immediate child operation");
976 
977   auto it = impl->childAnalyses.find(op);
978   if (it == impl->childAnalyses.end())
979     it = impl->childAnalyses
980              .try_emplace(op, std::make_unique<NestedAnalysisMap>(op, impl))
981              .first;
982   return {it->second.get()};
983 }
984 
985 /// Invalidate any non preserved analyses.
986 void detail::NestedAnalysisMap::invalidate(
987     const detail::PreservedAnalyses &pa) {
988   // If all analyses were preserved, then there is nothing to do here.
989   if (pa.isAll())
990     return;
991 
992   // Invalidate the analyses for the current operation directly.
993   analyses.invalidate(pa);
994 
995   // If no analyses were preserved, then just simply clear out the child
996   // analysis results.
997   if (pa.isNone()) {
998     childAnalyses.clear();
999     return;
1000   }
1001 
1002   // Otherwise, invalidate each child analysis map.
1003   SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
1004   while (!mapsToInvalidate.empty()) {
1005     auto *map = mapsToInvalidate.pop_back_val();
1006     for (auto &analysisPair : map->childAnalyses) {
1007       analysisPair.second->invalidate(pa);
1008       if (!analysisPair.second->childAnalyses.empty())
1009         mapsToInvalidate.push_back(analysisPair.second.get());
1010     }
1011   }
1012 }
1013 
1014 //===----------------------------------------------------------------------===//
1015 // PassInstrumentation
1016 //===----------------------------------------------------------------------===//
1017 
1018 PassInstrumentation::~PassInstrumentation() {}
1019 
1020 //===----------------------------------------------------------------------===//
1021 // PassInstrumentor
1022 //===----------------------------------------------------------------------===//
1023 
1024 namespace mlir {
1025 namespace detail {
1026 struct PassInstrumentorImpl {
1027   /// Mutex to keep instrumentation access thread-safe.
1028   llvm::sys::SmartMutex<true> mutex;
1029 
1030   /// Set of registered instrumentations.
1031   std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
1032 };
1033 } // end namespace detail
1034 } // end namespace mlir
1035 
1036 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
1037 PassInstrumentor::~PassInstrumentor() {}
1038 
1039 /// See PassInstrumentation::runBeforePipeline for details.
1040 void PassInstrumentor::runBeforePipeline(
1041     Identifier name,
1042     const PassInstrumentation::PipelineParentInfo &parentInfo) {
1043   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1044   for (auto &instr : impl->instrumentations)
1045     instr->runBeforePipeline(name, parentInfo);
1046 }
1047 
1048 /// See PassInstrumentation::runAfterPipeline for details.
1049 void PassInstrumentor::runAfterPipeline(
1050     Identifier name,
1051     const PassInstrumentation::PipelineParentInfo &parentInfo) {
1052   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1053   for (auto &instr : llvm::reverse(impl->instrumentations))
1054     instr->runAfterPipeline(name, parentInfo);
1055 }
1056 
1057 /// See PassInstrumentation::runBeforePass for details.
1058 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
1059   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1060   for (auto &instr : impl->instrumentations)
1061     instr->runBeforePass(pass, op);
1062 }
1063 
1064 /// See PassInstrumentation::runAfterPass for details.
1065 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
1066   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1067   for (auto &instr : llvm::reverse(impl->instrumentations))
1068     instr->runAfterPass(pass, op);
1069 }
1070 
1071 /// See PassInstrumentation::runAfterPassFailed for details.
1072 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
1073   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1074   for (auto &instr : llvm::reverse(impl->instrumentations))
1075     instr->runAfterPassFailed(pass, op);
1076 }
1077 
1078 /// See PassInstrumentation::runBeforeAnalysis for details.
1079 void PassInstrumentor::runBeforeAnalysis(StringRef name, TypeID id,
1080                                          Operation *op) {
1081   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1082   for (auto &instr : impl->instrumentations)
1083     instr->runBeforeAnalysis(name, id, op);
1084 }
1085 
1086 /// See PassInstrumentation::runAfterAnalysis for details.
1087 void PassInstrumentor::runAfterAnalysis(StringRef name, TypeID id,
1088                                         Operation *op) {
1089   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1090   for (auto &instr : llvm::reverse(impl->instrumentations))
1091     instr->runAfterAnalysis(name, id, op);
1092 }
1093 
1094 /// Add the given instrumentation to the collection.
1095 void PassInstrumentor::addInstrumentation(
1096     std::unique_ptr<PassInstrumentation> pi) {
1097   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
1098   impl->instrumentations.emplace_back(std::move(pi));
1099 }
1100