1 //===- PassRegistry.cpp - Pass Registration Utilities ---------------------===//
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 #include "mlir/Pass/PassRegistry.h"
10 #include "mlir/Pass/Pass.h"
11 #include "mlir/Pass/PassManager.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/Support/Format.h"
14 #include "llvm/Support/ManagedStatic.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "llvm/Support/SourceMgr.h"
17 
18 using namespace mlir;
19 using namespace detail;
20 
21 /// Static mapping of all of the registered passes.
22 static llvm::ManagedStatic<llvm::StringMap<PassInfo>> passRegistry;
23 
24 /// A mapping of the above pass registry entries to the corresponding TypeID
25 /// of the pass that they generate.
26 static llvm::ManagedStatic<llvm::StringMap<TypeID>> passRegistryTypeIDs;
27 
28 /// Static mapping of all of the registered pass pipelines.
29 static llvm::ManagedStatic<llvm::StringMap<PassPipelineInfo>>
30     passPipelineRegistry;
31 
32 /// Utility to create a default registry function from a pass instance.
33 static PassRegistryFunction
34 buildDefaultRegistryFn(const PassAllocatorFunction &allocator) {
35   return [=](OpPassManager &pm, StringRef options,
36              function_ref<LogicalResult(const Twine &)> errorHandler) {
37     std::unique_ptr<Pass> pass = allocator();
38     LogicalResult result = pass->initializeOptions(options);
39     if ((pm.getNesting() == OpPassManager::Nesting::Explicit) &&
40         pass->getOpName() && *pass->getOpName() != pm.getOpName())
41       return errorHandler(llvm::Twine("Can't add pass '") + pass->getName() +
42                           "' restricted to '" + *pass->getOpName() +
43                           "' on a PassManager intended to run on '" +
44                           pm.getOpName() + "', did you intend to nest?");
45     pm.addPass(std::move(pass));
46     return result;
47   };
48 }
49 
50 /// Utility to print the help string for a specific option.
51 static void printOptionHelp(StringRef arg, StringRef desc, size_t indent,
52                             size_t descIndent, bool isTopLevel) {
53   size_t numSpaces = descIndent - indent - 4;
54   llvm::outs().indent(indent)
55       << "--" << llvm::left_justify(arg, numSpaces) << "-   " << desc << '\n';
56 }
57 
58 //===----------------------------------------------------------------------===//
59 // PassRegistry
60 //===----------------------------------------------------------------------===//
61 
62 /// Print the help information for this pass. This includes the argument,
63 /// description, and any pass options. `descIndent` is the indent that the
64 /// descriptions should be aligned.
65 void PassRegistryEntry::printHelpStr(size_t indent, size_t descIndent) const {
66   printOptionHelp(getPassArgument(), getPassDescription(), indent, descIndent,
67                   /*isTopLevel=*/true);
68   // If this entry has options, print the help for those as well.
69   optHandler([=](const PassOptions &options) {
70     options.printHelp(indent, descIndent);
71   });
72 }
73 
74 /// Return the maximum width required when printing the options of this
75 /// entry.
76 size_t PassRegistryEntry::getOptionWidth() const {
77   size_t maxLen = 0;
78   optHandler([&](const PassOptions &options) mutable {
79     maxLen = options.getOptionWidth() + 2;
80   });
81   return maxLen;
82 }
83 
84 //===----------------------------------------------------------------------===//
85 // PassPipelineInfo
86 //===----------------------------------------------------------------------===//
87 
88 void mlir::registerPassPipeline(
89     StringRef arg, StringRef description, const PassRegistryFunction &function,
90     std::function<void(function_ref<void(const PassOptions &)>)> optHandler) {
91   PassPipelineInfo pipelineInfo(arg, description, function, optHandler);
92   bool inserted = passPipelineRegistry->try_emplace(arg, pipelineInfo).second;
93   assert(inserted && "Pass pipeline registered multiple times");
94   (void)inserted;
95 }
96 
97 //===----------------------------------------------------------------------===//
98 // PassInfo
99 //===----------------------------------------------------------------------===//
100 
101 PassInfo::PassInfo(StringRef arg, StringRef description,
102                    const PassAllocatorFunction &allocator)
103     : PassRegistryEntry(
104           arg, description, buildDefaultRegistryFn(allocator),
105           // Use a temporary pass to provide an options instance.
106           [=](function_ref<void(const PassOptions &)> optHandler) {
107             optHandler(allocator()->passOptions);
108           }) {}
109 
110 void mlir::registerPass(StringRef arg, StringRef description,
111                         const PassAllocatorFunction &function) {
112   PassInfo passInfo(arg, description, function);
113   passRegistry->try_emplace(arg, passInfo);
114 
115   // Verify that the registered pass has the same ID as any registered to this
116   // arg before it.
117   TypeID entryTypeID = function()->getTypeID();
118   auto it = passRegistryTypeIDs->try_emplace(arg, entryTypeID).first;
119   if (it->second != entryTypeID) {
120     llvm_unreachable("pass allocator creates a different pass than previously "
121                      "registered");
122   }
123 }
124 
125 /// Returns the pass info for the specified pass argument or null if unknown.
126 const PassInfo *mlir::Pass::lookupPassInfo(StringRef passArg) {
127   auto it = passRegistry->find(passArg);
128   return it == passRegistry->end() ? nullptr : &it->second;
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // PassOptions
133 //===----------------------------------------------------------------------===//
134 
135 /// Out of line virtual function to provide home for the class.
136 void detail::PassOptions::OptionBase::anchor() {}
137 
138 /// Copy the option values from 'other'.
139 void detail::PassOptions::copyOptionValuesFrom(const PassOptions &other) {
140   assert(options.size() == other.options.size());
141   if (options.empty())
142     return;
143   for (auto optionsIt : llvm::zip(options, other.options))
144     std::get<0>(optionsIt)->copyValueFrom(*std::get<1>(optionsIt));
145 }
146 
147 LogicalResult detail::PassOptions::parseFromString(StringRef options) {
148   // TODO: Handle escaping strings.
149   // NOTE: `options` is modified in place to always refer to the unprocessed
150   // part of the string.
151   while (!options.empty()) {
152     size_t spacePos = options.find(' ');
153     StringRef arg = options;
154     if (spacePos != StringRef::npos) {
155       arg = options.substr(0, spacePos);
156       options = options.substr(spacePos + 1);
157     } else {
158       options = StringRef();
159     }
160     if (arg.empty())
161       continue;
162 
163     // At this point, arg refers to everything that is non-space in options
164     // upto the next space, and options refers to the rest of the string after
165     // that point.
166 
167     // Split the individual option on '=' to form key and value. If there is no
168     // '=', then value is `StringRef()`.
169     size_t equalPos = arg.find('=');
170     StringRef key = arg;
171     StringRef value;
172     if (equalPos != StringRef::npos) {
173       key = arg.substr(0, equalPos);
174       value = arg.substr(equalPos + 1);
175     }
176     auto it = OptionsMap.find(key);
177     if (it == OptionsMap.end()) {
178       llvm::errs() << "<Pass-Options-Parser>: no such option " << key << "\n";
179       return failure();
180     }
181     if (llvm::cl::ProvidePositionalOption(it->second, value, 0))
182       return failure();
183   }
184 
185   return success();
186 }
187 
188 /// Print the options held by this struct in a form that can be parsed via
189 /// 'parseFromString'.
190 void detail::PassOptions::print(raw_ostream &os) {
191   // If there are no options, there is nothing left to do.
192   if (OptionsMap.empty())
193     return;
194 
195   // Sort the options to make the ordering deterministic.
196   SmallVector<OptionBase *, 4> orderedOps(options.begin(), options.end());
197   auto compareOptionArgs = [](OptionBase *const *lhs, OptionBase *const *rhs) {
198     return (*lhs)->getArgStr().compare((*rhs)->getArgStr());
199   };
200   llvm::array_pod_sort(orderedOps.begin(), orderedOps.end(), compareOptionArgs);
201 
202   // Interleave the options with ' '.
203   os << '{';
204   llvm::interleave(
205       orderedOps, os, [&](OptionBase *option) { option->print(os); }, " ");
206   os << '}';
207 }
208 
209 /// Print the help string for the options held by this struct. `descIndent` is
210 /// the indent within the stream that the descriptions should be aligned.
211 void detail::PassOptions::printHelp(size_t indent, size_t descIndent) const {
212   // Sort the options to make the ordering deterministic.
213   SmallVector<OptionBase *, 4> orderedOps(options.begin(), options.end());
214   auto compareOptionArgs = [](OptionBase *const *lhs, OptionBase *const *rhs) {
215     return (*lhs)->getArgStr().compare((*rhs)->getArgStr());
216   };
217   llvm::array_pod_sort(orderedOps.begin(), orderedOps.end(), compareOptionArgs);
218   for (OptionBase *option : orderedOps) {
219     // TODO: printOptionInfo assumes a specific indent and will
220     // print options with values with incorrect indentation. We should add
221     // support to llvm::cl::Option for passing in a base indent to use when
222     // printing.
223     llvm::outs().indent(indent);
224     option->getOption()->printOptionInfo(descIndent - indent);
225   }
226 }
227 
228 /// Return the maximum width required when printing the help string.
229 size_t detail::PassOptions::getOptionWidth() const {
230   size_t max = 0;
231   for (auto *option : options)
232     max = std::max(max, option->getOption()->getOptionWidth());
233   return max;
234 }
235 
236 //===----------------------------------------------------------------------===//
237 // TextualPassPipeline Parser
238 //===----------------------------------------------------------------------===//
239 
240 namespace {
241 /// This class represents a textual description of a pass pipeline.
242 class TextualPipeline {
243 public:
244   /// Try to initialize this pipeline with the given pipeline text.
245   /// `errorStream` is the output stream to emit errors to.
246   LogicalResult initialize(StringRef text, raw_ostream &errorStream);
247 
248   /// Add the internal pipeline elements to the provided pass manager.
249   LogicalResult
250   addToPipeline(OpPassManager &pm,
251                 function_ref<LogicalResult(const Twine &)> errorHandler) const;
252 
253 private:
254   /// A functor used to emit errors found during pipeline handling. The first
255   /// parameter corresponds to the raw location within the pipeline string. This
256   /// should always return failure.
257   using ErrorHandlerT = function_ref<LogicalResult(const char *, Twine)>;
258 
259   /// A struct to capture parsed pass pipeline names.
260   ///
261   /// A pipeline is defined as a series of names, each of which may in itself
262   /// recursively contain a nested pipeline. A name is either the name of a pass
263   /// (e.g. "cse") or the name of an operation type (e.g. "func"). If the name
264   /// is the name of a pass, the InnerPipeline is empty, since passes cannot
265   /// contain inner pipelines.
266   struct PipelineElement {
267     PipelineElement(StringRef name) : name(name), registryEntry(nullptr) {}
268 
269     StringRef name;
270     StringRef options;
271     const PassRegistryEntry *registryEntry;
272     std::vector<PipelineElement> innerPipeline;
273   };
274 
275   /// Parse the given pipeline text into the internal pipeline vector. This
276   /// function only parses the structure of the pipeline, and does not resolve
277   /// its elements.
278   LogicalResult parsePipelineText(StringRef text, ErrorHandlerT errorHandler);
279 
280   /// Resolve the elements of the pipeline, i.e. connect passes and pipelines to
281   /// the corresponding registry entry.
282   LogicalResult
283   resolvePipelineElements(MutableArrayRef<PipelineElement> elements,
284                           ErrorHandlerT errorHandler);
285 
286   /// Resolve a single element of the pipeline.
287   LogicalResult resolvePipelineElement(PipelineElement &element,
288                                        ErrorHandlerT errorHandler);
289 
290   /// Add the given pipeline elements to the provided pass manager.
291   LogicalResult
292   addToPipeline(ArrayRef<PipelineElement> elements, OpPassManager &pm,
293                 function_ref<LogicalResult(const Twine &)> errorHandler) const;
294 
295   std::vector<PipelineElement> pipeline;
296 };
297 
298 } // end anonymous namespace
299 
300 /// Try to initialize this pipeline with the given pipeline text. An option is
301 /// given to enable accurate error reporting.
302 LogicalResult TextualPipeline::initialize(StringRef text,
303                                           raw_ostream &errorStream) {
304   if (text.empty())
305     return success();
306 
307   // Build a source manager to use for error reporting.
308   llvm::SourceMgr pipelineMgr;
309   pipelineMgr.AddNewSourceBuffer(
310       llvm::MemoryBuffer::getMemBuffer(text, "MLIR Textual PassPipeline Parser",
311                                        /*RequiresNullTerminator=*/false),
312       llvm::SMLoc());
313   auto errorHandler = [&](const char *rawLoc, Twine msg) {
314     pipelineMgr.PrintMessage(errorStream, llvm::SMLoc::getFromPointer(rawLoc),
315                              llvm::SourceMgr::DK_Error, msg);
316     return failure();
317   };
318 
319   // Parse the provided pipeline string.
320   if (failed(parsePipelineText(text, errorHandler)))
321     return failure();
322   return resolvePipelineElements(pipeline, errorHandler);
323 }
324 
325 /// Add the internal pipeline elements to the provided pass manager.
326 LogicalResult TextualPipeline::addToPipeline(
327     OpPassManager &pm,
328     function_ref<LogicalResult(const Twine &)> errorHandler) const {
329   return addToPipeline(pipeline, pm, errorHandler);
330 }
331 
332 /// Parse the given pipeline text into the internal pipeline vector. This
333 /// function only parses the structure of the pipeline, and does not resolve
334 /// its elements.
335 LogicalResult TextualPipeline::parsePipelineText(StringRef text,
336                                                  ErrorHandlerT errorHandler) {
337   SmallVector<std::vector<PipelineElement> *, 4> pipelineStack = {&pipeline};
338   for (;;) {
339     std::vector<PipelineElement> &pipeline = *pipelineStack.back();
340     size_t pos = text.find_first_of(",(){");
341     pipeline.emplace_back(/*name=*/text.substr(0, pos).trim());
342 
343     // If we have a single terminating name, we're done.
344     if (pos == StringRef::npos)
345       break;
346 
347     text = text.substr(pos);
348     char sep = text[0];
349 
350     // Handle pulling ... from 'pass{...}' out as PipelineElement.options.
351     if (sep == '{') {
352       text = text.substr(1);
353 
354       // Skip over everything until the closing '}' and store as options.
355       size_t close = StringRef::npos;
356       for (unsigned i = 0, e = text.size(), braceCount = 1; i < e; ++i) {
357         if (text[i] == '{') {
358           ++braceCount;
359           continue;
360         }
361         if (text[i] == '}' && --braceCount == 0) {
362           close = i;
363           break;
364         }
365       }
366 
367       // Check to see if a closing options brace was found.
368       if (close == StringRef::npos) {
369         return errorHandler(
370             /*rawLoc=*/text.data() - 1,
371             "missing closing '}' while processing pass options");
372       }
373       pipeline.back().options = text.substr(0, close);
374       text = text.substr(close + 1);
375 
376       // Skip checking for '(' because nested pipelines cannot have options.
377     } else if (sep == '(') {
378       text = text.substr(1);
379 
380       // Push the inner pipeline onto the stack to continue processing.
381       pipelineStack.push_back(&pipeline.back().innerPipeline);
382       continue;
383     }
384 
385     // When handling the close parenthesis, we greedily consume them to avoid
386     // empty strings in the pipeline.
387     while (text.consume_front(")")) {
388       // If we try to pop the outer pipeline we have unbalanced parentheses.
389       if (pipelineStack.size() == 1)
390         return errorHandler(/*rawLoc=*/text.data() - 1,
391                             "encountered extra closing ')' creating unbalanced "
392                             "parentheses while parsing pipeline");
393 
394       pipelineStack.pop_back();
395     }
396 
397     // Check if we've finished parsing.
398     if (text.empty())
399       break;
400 
401     // Otherwise, the end of an inner pipeline always has to be followed by
402     // a comma, and then we can continue.
403     if (!text.consume_front(","))
404       return errorHandler(text.data(), "expected ',' after parsing pipeline");
405   }
406 
407   // Check for unbalanced parentheses.
408   if (pipelineStack.size() > 1)
409     return errorHandler(
410         text.data(),
411         "encountered unbalanced parentheses while parsing pipeline");
412 
413   assert(pipelineStack.back() == &pipeline &&
414          "wrong pipeline at the bottom of the stack");
415   return success();
416 }
417 
418 /// Resolve the elements of the pipeline, i.e. connect passes and pipelines to
419 /// the corresponding registry entry.
420 LogicalResult TextualPipeline::resolvePipelineElements(
421     MutableArrayRef<PipelineElement> elements, ErrorHandlerT errorHandler) {
422   for (auto &elt : elements)
423     if (failed(resolvePipelineElement(elt, errorHandler)))
424       return failure();
425   return success();
426 }
427 
428 /// Resolve a single element of the pipeline.
429 LogicalResult
430 TextualPipeline::resolvePipelineElement(PipelineElement &element,
431                                         ErrorHandlerT errorHandler) {
432   // If the inner pipeline of this element is not empty, this is an operation
433   // pipeline.
434   if (!element.innerPipeline.empty())
435     return resolvePipelineElements(element.innerPipeline, errorHandler);
436   // Otherwise, this must be a pass or pass pipeline.
437   // Check to see if a pipeline was registered with this name.
438   auto pipelineRegistryIt = passPipelineRegistry->find(element.name);
439   if (pipelineRegistryIt != passPipelineRegistry->end()) {
440     element.registryEntry = &pipelineRegistryIt->second;
441     return success();
442   }
443 
444   // If not, then this must be a specific pass name.
445   if ((element.registryEntry = Pass::lookupPassInfo(element.name)))
446     return success();
447 
448   // Emit an error for the unknown pass.
449   auto *rawLoc = element.name.data();
450   return errorHandler(rawLoc, "'" + element.name +
451                                   "' does not refer to a "
452                                   "registered pass or pass pipeline");
453 }
454 
455 /// Add the given pipeline elements to the provided pass manager.
456 LogicalResult TextualPipeline::addToPipeline(
457     ArrayRef<PipelineElement> elements, OpPassManager &pm,
458     function_ref<LogicalResult(const Twine &)> errorHandler) const {
459   for (auto &elt : elements) {
460     if (elt.registryEntry) {
461       if (failed(elt.registryEntry->addToPipeline(pm, elt.options,
462                                                   errorHandler))) {
463         return errorHandler("failed to add `" + elt.name + "` with options `" +
464                             elt.options + "`");
465       }
466     } else if (failed(addToPipeline(elt.innerPipeline, pm.nest(elt.name),
467                                     errorHandler))) {
468       return errorHandler("failed to add `" + elt.name + "` with options `" +
469                           elt.options + "` to inner pipeline");
470     }
471   }
472   return success();
473 }
474 
475 /// This function parses the textual representation of a pass pipeline, and adds
476 /// the result to 'pm' on success. This function returns failure if the given
477 /// pipeline was invalid. 'errorStream' is an optional parameter that, if
478 /// non-null, will be used to emit errors found during parsing.
479 LogicalResult mlir::parsePassPipeline(StringRef pipeline, OpPassManager &pm,
480                                       raw_ostream &errorStream) {
481   TextualPipeline pipelineParser;
482   if (failed(pipelineParser.initialize(pipeline, errorStream)))
483     return failure();
484   auto errorHandler = [&](Twine msg) {
485     errorStream << msg << "\n";
486     return failure();
487   };
488   if (failed(pipelineParser.addToPipeline(pm, errorHandler)))
489     return failure();
490   return success();
491 }
492 
493 //===----------------------------------------------------------------------===//
494 // PassNameParser
495 //===----------------------------------------------------------------------===//
496 
497 namespace {
498 /// This struct represents the possible data entries in a parsed pass pipeline
499 /// list.
500 struct PassArgData {
501   PassArgData() : registryEntry(nullptr) {}
502   PassArgData(const PassRegistryEntry *registryEntry)
503       : registryEntry(registryEntry) {}
504 
505   /// This field is used when the parsed option corresponds to a registered pass
506   /// or pass pipeline.
507   const PassRegistryEntry *registryEntry;
508 
509   /// This field is set when instance specific pass options have been provided
510   /// on the command line.
511   StringRef options;
512 
513   /// This field is used when the parsed option corresponds to an explicit
514   /// pipeline.
515   TextualPipeline pipeline;
516 };
517 } // end anonymous namespace
518 
519 namespace llvm {
520 namespace cl {
521 /// Define a valid OptionValue for the command line pass argument.
522 template <>
523 struct OptionValue<PassArgData> final
524     : OptionValueBase<PassArgData, /*isClass=*/true> {
525   OptionValue(const PassArgData &value) { this->setValue(value); }
526   OptionValue() = default;
527   void anchor() override {}
528 
529   bool hasValue() const { return true; }
530   const PassArgData &getValue() const { return value; }
531   void setValue(const PassArgData &value) { this->value = value; }
532 
533   PassArgData value;
534 };
535 } // end namespace cl
536 } // end namespace llvm
537 
538 namespace {
539 
540 /// The name for the command line option used for parsing the textual pass
541 /// pipeline.
542 static constexpr StringLiteral passPipelineArg = "pass-pipeline";
543 
544 /// Adds command line option for each registered pass or pass pipeline, as well
545 /// as textual pass pipelines.
546 struct PassNameParser : public llvm::cl::parser<PassArgData> {
547   PassNameParser(llvm::cl::Option &opt) : llvm::cl::parser<PassArgData>(opt) {}
548 
549   void initialize();
550   void printOptionInfo(const llvm::cl::Option &opt,
551                        size_t globalWidth) const override;
552   size_t getOptionWidth(const llvm::cl::Option &opt) const override;
553   bool parse(llvm::cl::Option &opt, StringRef argName, StringRef arg,
554              PassArgData &value);
555 
556   /// If true, this parser only parses entries that correspond to a concrete
557   /// pass registry entry, and does not add a `pass-pipeline` argument, does not
558   /// include the options for pass entries, and does not include pass pipelines
559   /// entries.
560   bool passNamesOnly = false;
561 };
562 } // namespace
563 
564 void PassNameParser::initialize() {
565   llvm::cl::parser<PassArgData>::initialize();
566 
567   /// Add an entry for the textual pass pipeline option.
568   if (!passNamesOnly) {
569     addLiteralOption(passPipelineArg, PassArgData(),
570                      "A textual description of a pass pipeline to run");
571   }
572 
573   /// Add the pass entries.
574   for (const auto &kv : *passRegistry) {
575     addLiteralOption(kv.second.getPassArgument(), &kv.second,
576                      kv.second.getPassDescription());
577   }
578   /// Add the pass pipeline entries.
579   if (!passNamesOnly) {
580     for (const auto &kv : *passPipelineRegistry) {
581       addLiteralOption(kv.second.getPassArgument(), &kv.second,
582                        kv.second.getPassDescription());
583     }
584   }
585 }
586 
587 void PassNameParser::printOptionInfo(const llvm::cl::Option &opt,
588                                      size_t globalWidth) const {
589   // If this parser is just parsing pass names, print a simplified option
590   // string.
591   if (passNamesOnly) {
592     llvm::outs() << "  --" << opt.ArgStr << "=<pass-arg>";
593     opt.printHelpStr(opt.HelpStr, globalWidth, opt.ArgStr.size() + 18);
594     return;
595   }
596 
597   // Print the information for the top-level option.
598   if (opt.hasArgStr()) {
599     llvm::outs() << "  --" << opt.ArgStr;
600     opt.printHelpStr(opt.HelpStr, globalWidth, opt.ArgStr.size() + 7);
601   } else {
602     llvm::outs() << "  " << opt.HelpStr << '\n';
603   }
604 
605   // Print the top-level pipeline argument.
606   printOptionHelp(passPipelineArg,
607                   "A textual description of a pass pipeline to run",
608                   /*indent=*/4, globalWidth, /*isTopLevel=*/!opt.hasArgStr());
609 
610   // Functor used to print the ordered entries of a registration map.
611   auto printOrderedEntries = [&](StringRef header, auto &map) {
612     llvm::SmallVector<PassRegistryEntry *, 32> orderedEntries;
613     for (auto &kv : map)
614       orderedEntries.push_back(&kv.second);
615     llvm::array_pod_sort(
616         orderedEntries.begin(), orderedEntries.end(),
617         [](PassRegistryEntry *const *lhs, PassRegistryEntry *const *rhs) {
618           return (*lhs)->getPassArgument().compare((*rhs)->getPassArgument());
619         });
620 
621     llvm::outs().indent(4) << header << ":\n";
622     for (PassRegistryEntry *entry : orderedEntries)
623       entry->printHelpStr(/*indent=*/6, globalWidth);
624   };
625 
626   // Print the available passes.
627   printOrderedEntries("Passes", *passRegistry);
628 
629   // Print the available pass pipelines.
630   if (!passPipelineRegistry->empty())
631     printOrderedEntries("Pass Pipelines", *passPipelineRegistry);
632 }
633 
634 size_t PassNameParser::getOptionWidth(const llvm::cl::Option &opt) const {
635   size_t maxWidth = llvm::cl::parser<PassArgData>::getOptionWidth(opt) + 2;
636 
637   // Check for any wider pass or pipeline options.
638   for (auto &entry : *passRegistry)
639     maxWidth = std::max(maxWidth, entry.second.getOptionWidth() + 4);
640   for (auto &entry : *passPipelineRegistry)
641     maxWidth = std::max(maxWidth, entry.second.getOptionWidth() + 4);
642   return maxWidth;
643 }
644 
645 bool PassNameParser::parse(llvm::cl::Option &opt, StringRef argName,
646                            StringRef arg, PassArgData &value) {
647   // Handle the pipeline option explicitly.
648   if (argName == passPipelineArg)
649     return failed(value.pipeline.initialize(arg, llvm::errs()));
650 
651   // Otherwise, default to the base for handling.
652   if (llvm::cl::parser<PassArgData>::parse(opt, argName, arg, value))
653     return true;
654   value.options = arg;
655   return false;
656 }
657 
658 //===----------------------------------------------------------------------===//
659 // PassPipelineCLParser
660 //===----------------------------------------------------------------------===//
661 
662 namespace mlir {
663 namespace detail {
664 struct PassPipelineCLParserImpl {
665   PassPipelineCLParserImpl(StringRef arg, StringRef description,
666                            bool passNamesOnly)
667       : passList(arg, llvm::cl::desc(description)) {
668     passList.getParser().passNamesOnly = passNamesOnly;
669     passList.setValueExpectedFlag(llvm::cl::ValueExpected::ValueOptional);
670   }
671 
672   /// Returns true if the given pass registry entry was registered at the
673   /// top-level of the parser, i.e. not within an explicit textual pipeline.
674   bool contains(const PassRegistryEntry *entry) const {
675     return llvm::any_of(passList, [&](const PassArgData &data) {
676       return data.registryEntry == entry;
677     });
678   }
679 
680   /// The set of passes and pass pipelines to run.
681   llvm::cl::list<PassArgData, bool, PassNameParser> passList;
682 };
683 } // end namespace detail
684 } // end namespace mlir
685 
686 /// Construct a pass pipeline parser with the given command line description.
687 PassPipelineCLParser::PassPipelineCLParser(StringRef arg, StringRef description)
688     : impl(std::make_unique<detail::PassPipelineCLParserImpl>(
689           arg, description, /*passNamesOnly=*/false)) {}
690 PassPipelineCLParser::~PassPipelineCLParser() {}
691 
692 /// Returns true if this parser contains any valid options to add.
693 bool PassPipelineCLParser::hasAnyOccurrences() const {
694   return impl->passList.getNumOccurrences() != 0;
695 }
696 
697 /// Returns true if the given pass registry entry was registered at the
698 /// top-level of the parser, i.e. not within an explicit textual pipeline.
699 bool PassPipelineCLParser::contains(const PassRegistryEntry *entry) const {
700   return impl->contains(entry);
701 }
702 
703 /// Adds the passes defined by this parser entry to the given pass manager.
704 LogicalResult PassPipelineCLParser::addToPipeline(
705     OpPassManager &pm,
706     function_ref<LogicalResult(const Twine &)> errorHandler) const {
707   for (auto &passIt : impl->passList) {
708     if (passIt.registryEntry) {
709       if (failed(passIt.registryEntry->addToPipeline(pm, passIt.options,
710                                                      errorHandler)))
711         return failure();
712     } else {
713       OpPassManager::Nesting nesting = pm.getNesting();
714       pm.setNesting(OpPassManager::Nesting::Explicit);
715       LogicalResult status = passIt.pipeline.addToPipeline(pm, errorHandler);
716       pm.setNesting(nesting);
717       if (failed(status))
718         return failure();
719     }
720   }
721   return success();
722 }
723 
724 //===----------------------------------------------------------------------===//
725 // PassNameCLParser
726 
727 /// Construct a pass pipeline parser with the given command line description.
728 PassNameCLParser::PassNameCLParser(StringRef arg, StringRef description)
729     : impl(std::make_unique<detail::PassPipelineCLParserImpl>(
730           arg, description, /*passNamesOnly=*/true)) {
731   impl->passList.setMiscFlag(llvm::cl::CommaSeparated);
732 }
733 PassNameCLParser::~PassNameCLParser() {}
734 
735 /// Returns true if this parser contains any valid options to add.
736 bool PassNameCLParser::hasAnyOccurrences() const {
737   return impl->passList.getNumOccurrences() != 0;
738 }
739 
740 /// Returns true if the given pass registry entry was registered at the
741 /// top-level of the parser, i.e. not within an explicit textual pipeline.
742 bool PassNameCLParser::contains(const PassRegistryEntry *entry) const {
743   return impl->contains(entry);
744 }
745