1 //===- AsmPrinter.cpp - MLIR Assembly Printer 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 the MLIR AsmPrinter class, which is used to implement
10 // the various print() methods on the core IR objects.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/IR/AffineExpr.h"
15 #include "mlir/IR/AffineMap.h"
16 #include "mlir/IR/AsmState.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/BuiltinDialect.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/Dialect.h"
22 #include "mlir/IR/DialectImplementation.h"
23 #include "mlir/IR/IntegerSet.h"
24 #include "mlir/IR/MLIRContext.h"
25 #include "mlir/IR/OpImplementation.h"
26 #include "mlir/IR/Operation.h"
27 #include "mlir/IR/SubElementInterfaces.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/MapVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/ScopeExit.h"
33 #include "llvm/ADT/ScopedHashTable.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSet.h"
38 #include "llvm/ADT/TypeSwitch.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Endian.h"
41 #include "llvm/Support/Regex.h"
42 #include "llvm/Support/SaveAndRestore.h"
43 
44 #include <tuple>
45 
46 using namespace mlir;
47 using namespace mlir::detail;
48 
49 void OperationName::print(raw_ostream &os) const { os << getStringRef(); }
50 
51 void OperationName::dump() const { print(llvm::errs()); }
52 
53 //===--------------------------------------------------------------------===//
54 // AsmParser
55 //===--------------------------------------------------------------------===//
56 
57 AsmParser::~AsmParser() = default;
58 DialectAsmParser::~DialectAsmParser() = default;
59 OpAsmParser::~OpAsmParser() = default;
60 
61 MLIRContext *AsmParser::getContext() const { return getBuilder().getContext(); }
62 
63 //===----------------------------------------------------------------------===//
64 // DialectAsmPrinter
65 //===----------------------------------------------------------------------===//
66 
67 DialectAsmPrinter::~DialectAsmPrinter() = default;
68 
69 //===----------------------------------------------------------------------===//
70 // OpAsmPrinter
71 //===----------------------------------------------------------------------===//
72 
73 OpAsmPrinter::~OpAsmPrinter() = default;
74 
75 void OpAsmPrinter::printFunctionalType(Operation *op) {
76   auto &os = getStream();
77   os << '(';
78   llvm::interleaveComma(op->getOperands(), os, [&](Value operand) {
79     // Print the types of null values as <<NULL TYPE>>.
80     *this << (operand ? operand.getType() : Type());
81   });
82   os << ") -> ";
83 
84   // Print the result list.  We don't parenthesize single result types unless
85   // it is a function (avoiding a grammar ambiguity).
86   bool wrapped = op->getNumResults() != 1;
87   if (!wrapped && op->getResult(0).getType() &&
88       op->getResult(0).getType().isa<FunctionType>())
89     wrapped = true;
90 
91   if (wrapped)
92     os << '(';
93 
94   llvm::interleaveComma(op->getResults(), os, [&](const OpResult &result) {
95     // Print the types of null values as <<NULL TYPE>>.
96     *this << (result ? result.getType() : Type());
97   });
98 
99   if (wrapped)
100     os << ')';
101 }
102 
103 //===----------------------------------------------------------------------===//
104 // Operation OpAsm interface.
105 //===----------------------------------------------------------------------===//
106 
107 /// The OpAsmOpInterface, see OpAsmInterface.td for more details.
108 #include "mlir/IR/OpAsmInterface.cpp.inc"
109 
110 //===----------------------------------------------------------------------===//
111 // OpPrintingFlags
112 //===----------------------------------------------------------------------===//
113 
114 namespace {
115 /// This struct contains command line options that can be used to initialize
116 /// various bits of the AsmPrinter. This uses a struct wrapper to avoid the need
117 /// for global command line options.
118 struct AsmPrinterOptions {
119   llvm::cl::opt<int64_t> printElementsAttrWithHexIfLarger{
120       "mlir-print-elementsattrs-with-hex-if-larger",
121       llvm::cl::desc(
122           "Print DenseElementsAttrs with a hex string that have "
123           "more elements than the given upper limit (use -1 to disable)")};
124 
125   llvm::cl::opt<unsigned> elideElementsAttrIfLarger{
126       "mlir-elide-elementsattrs-if-larger",
127       llvm::cl::desc("Elide ElementsAttrs with \"...\" that have "
128                      "more elements than the given upper limit")};
129 
130   llvm::cl::opt<bool> printDebugInfoOpt{
131       "mlir-print-debuginfo", llvm::cl::init(false),
132       llvm::cl::desc("Print debug info in MLIR output")};
133 
134   llvm::cl::opt<bool> printPrettyDebugInfoOpt{
135       "mlir-pretty-debuginfo", llvm::cl::init(false),
136       llvm::cl::desc("Print pretty debug info in MLIR output")};
137 
138   // Use the generic op output form in the operation printer even if the custom
139   // form is defined.
140   llvm::cl::opt<bool> printGenericOpFormOpt{
141       "mlir-print-op-generic", llvm::cl::init(false),
142       llvm::cl::desc("Print the generic op form"), llvm::cl::Hidden};
143 
144   llvm::cl::opt<bool> printLocalScopeOpt{
145       "mlir-print-local-scope", llvm::cl::init(false),
146       llvm::cl::desc("Print with local scope and inline information (eliding "
147                      "aliases for attributes, types, and locations")};
148 };
149 } // namespace
150 
151 static llvm::ManagedStatic<AsmPrinterOptions> clOptions;
152 
153 /// Register a set of useful command-line options that can be used to configure
154 /// various flags within the AsmPrinter.
155 void mlir::registerAsmPrinterCLOptions() {
156   // Make sure that the options struct has been initialized.
157   *clOptions;
158 }
159 
160 /// Initialize the printing flags with default supplied by the cl::opts above.
161 OpPrintingFlags::OpPrintingFlags()
162     : printDebugInfoFlag(false), printDebugInfoPrettyFormFlag(false),
163       printGenericOpFormFlag(false), printLocalScope(false) {
164   // Initialize based upon command line options, if they are available.
165   if (!clOptions.isConstructed())
166     return;
167   if (clOptions->elideElementsAttrIfLarger.getNumOccurrences())
168     elementsAttrElementLimit = clOptions->elideElementsAttrIfLarger;
169   printDebugInfoFlag = clOptions->printDebugInfoOpt;
170   printDebugInfoPrettyFormFlag = clOptions->printPrettyDebugInfoOpt;
171   printGenericOpFormFlag = clOptions->printGenericOpFormOpt;
172   printLocalScope = clOptions->printLocalScopeOpt;
173 }
174 
175 /// Enable the elision of large elements attributes, by printing a '...'
176 /// instead of the element data, when the number of elements is greater than
177 /// `largeElementLimit`. Note: The IR generated with this option is not
178 /// parsable.
179 OpPrintingFlags &
180 OpPrintingFlags::elideLargeElementsAttrs(int64_t largeElementLimit) {
181   elementsAttrElementLimit = largeElementLimit;
182   return *this;
183 }
184 
185 /// Enable printing of debug information. If 'prettyForm' is set to true,
186 /// debug information is printed in a more readable 'pretty' form.
187 OpPrintingFlags &OpPrintingFlags::enableDebugInfo(bool prettyForm) {
188   printDebugInfoFlag = true;
189   printDebugInfoPrettyFormFlag = prettyForm;
190   return *this;
191 }
192 
193 /// Always print operations in the generic form.
194 OpPrintingFlags &OpPrintingFlags::printGenericOpForm() {
195   printGenericOpFormFlag = true;
196   return *this;
197 }
198 
199 /// Use local scope when printing the operation. This allows for using the
200 /// printer in a more localized and thread-safe setting, but may not necessarily
201 /// be identical of what the IR will look like when dumping the full module.
202 OpPrintingFlags &OpPrintingFlags::useLocalScope() {
203   printLocalScope = true;
204   return *this;
205 }
206 
207 /// Return if the given ElementsAttr should be elided.
208 bool OpPrintingFlags::shouldElideElementsAttr(ElementsAttr attr) const {
209   return elementsAttrElementLimit.hasValue() &&
210          *elementsAttrElementLimit < int64_t(attr.getNumElements()) &&
211          !attr.isa<SplatElementsAttr>();
212 }
213 
214 /// Return the size limit for printing large ElementsAttr.
215 Optional<int64_t> OpPrintingFlags::getLargeElementsAttrLimit() const {
216   return elementsAttrElementLimit;
217 }
218 
219 /// Return if debug information should be printed.
220 bool OpPrintingFlags::shouldPrintDebugInfo() const {
221   return printDebugInfoFlag;
222 }
223 
224 /// Return if debug information should be printed in the pretty form.
225 bool OpPrintingFlags::shouldPrintDebugInfoPrettyForm() const {
226   return printDebugInfoPrettyFormFlag;
227 }
228 
229 /// Return if operations should be printed in the generic form.
230 bool OpPrintingFlags::shouldPrintGenericOpForm() const {
231   return printGenericOpFormFlag;
232 }
233 
234 /// Return if the printer should use local scope when dumping the IR.
235 bool OpPrintingFlags::shouldUseLocalScope() const { return printLocalScope; }
236 
237 /// Returns true if an ElementsAttr with the given number of elements should be
238 /// printed with hex.
239 static bool shouldPrintElementsAttrWithHex(int64_t numElements) {
240   // Check to see if a command line option was provided for the limit.
241   if (clOptions.isConstructed()) {
242     if (clOptions->printElementsAttrWithHexIfLarger.getNumOccurrences()) {
243       // -1 is used to disable hex printing.
244       if (clOptions->printElementsAttrWithHexIfLarger == -1)
245         return false;
246       return numElements > clOptions->printElementsAttrWithHexIfLarger;
247     }
248   }
249 
250   // Otherwise, default to printing with hex if the number of elements is >100.
251   return numElements > 100;
252 }
253 
254 //===----------------------------------------------------------------------===//
255 // NewLineCounter
256 //===----------------------------------------------------------------------===//
257 
258 namespace {
259 /// This class is a simple formatter that emits a new line when inputted into a
260 /// stream, that enables counting the number of newlines emitted. This class
261 /// should be used whenever emitting newlines in the printer.
262 struct NewLineCounter {
263   unsigned curLine = 1;
264 };
265 
266 static raw_ostream &operator<<(raw_ostream &os, NewLineCounter &newLine) {
267   ++newLine.curLine;
268   return os << '\n';
269 }
270 } // namespace
271 
272 //===----------------------------------------------------------------------===//
273 // AliasInitializer
274 //===----------------------------------------------------------------------===//
275 
276 namespace {
277 /// This class represents a specific instance of a symbol Alias.
278 class SymbolAlias {
279 public:
280   SymbolAlias(StringRef name, bool isDeferrable)
281       : name(name), suffixIndex(0), hasSuffixIndex(false),
282         isDeferrable(isDeferrable) {}
283   SymbolAlias(StringRef name, uint32_t suffixIndex, bool isDeferrable)
284       : name(name), suffixIndex(suffixIndex), hasSuffixIndex(true),
285         isDeferrable(isDeferrable) {}
286 
287   /// Print this alias to the given stream.
288   void print(raw_ostream &os) const {
289     os << name;
290     if (hasSuffixIndex)
291       os << suffixIndex;
292   }
293 
294   /// Returns true if this alias supports deferred resolution when parsing.
295   bool canBeDeferred() const { return isDeferrable; }
296 
297 private:
298   /// The main name of the alias.
299   StringRef name;
300   /// The optional suffix index of the alias, if multiple aliases had the same
301   /// name.
302   uint32_t suffixIndex : 30;
303   /// A flag indicating whether this alias has a suffix or not.
304   bool hasSuffixIndex : 1;
305   /// A flag indicating whether this alias may be deferred or not.
306   bool isDeferrable : 1;
307 };
308 
309 /// This class represents a utility that initializes the set of attribute and
310 /// type aliases, without the need to store the extra information within the
311 /// main AliasState class or pass it around via function arguments.
312 class AliasInitializer {
313 public:
314   AliasInitializer(
315       DialectInterfaceCollection<OpAsmDialectInterface> &interfaces,
316       llvm::BumpPtrAllocator &aliasAllocator)
317       : interfaces(interfaces), aliasAllocator(aliasAllocator),
318         aliasOS(aliasBuffer) {}
319 
320   void initialize(Operation *op, const OpPrintingFlags &printerFlags,
321                   llvm::MapVector<Attribute, SymbolAlias> &attrToAlias,
322                   llvm::MapVector<Type, SymbolAlias> &typeToAlias);
323 
324   /// Visit the given attribute to see if it has an alias. `canBeDeferred` is
325   /// set to true if the originator of this attribute can resolve the alias
326   /// after parsing has completed (e.g. in the case of operation locations).
327   void visit(Attribute attr, bool canBeDeferred = false);
328 
329   /// Visit the given type to see if it has an alias.
330   void visit(Type type);
331 
332 private:
333   /// Try to generate an alias for the provided symbol. If an alias is
334   /// generated, the provided alias mapping and reverse mapping are updated.
335   /// Returns success if an alias was generated, failure otherwise.
336   template <typename T>
337   LogicalResult
338   generateAlias(T symbol,
339                 llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol);
340 
341   /// The set of asm interfaces within the context.
342   DialectInterfaceCollection<OpAsmDialectInterface> &interfaces;
343 
344   /// Mapping between an alias and the set of symbols mapped to it.
345   llvm::MapVector<StringRef, std::vector<Attribute>> aliasToAttr;
346   llvm::MapVector<StringRef, std::vector<Type>> aliasToType;
347 
348   /// An allocator used for alias names.
349   llvm::BumpPtrAllocator &aliasAllocator;
350 
351   /// The set of visited attributes.
352   DenseSet<Attribute> visitedAttributes;
353 
354   /// The set of attributes that have aliases *and* can be deferred.
355   DenseSet<Attribute> deferrableAttributes;
356 
357   /// The set of visited types.
358   DenseSet<Type> visitedTypes;
359 
360   /// Storage and stream used when generating an alias.
361   SmallString<32> aliasBuffer;
362   llvm::raw_svector_ostream aliasOS;
363 };
364 
365 /// This class implements a dummy OpAsmPrinter that doesn't print any output,
366 /// and merely collects the attributes and types that *would* be printed in a
367 /// normal print invocation so that we can generate proper aliases. This allows
368 /// for us to generate aliases only for the attributes and types that would be
369 /// in the output, and trims down unnecessary output.
370 class DummyAliasOperationPrinter : private OpAsmPrinter {
371 public:
372   explicit DummyAliasOperationPrinter(const OpPrintingFlags &printerFlags,
373                                       AliasInitializer &initializer)
374       : printerFlags(printerFlags), initializer(initializer) {}
375 
376   /// Print the given operation.
377   void print(Operation *op) {
378     // Visit the operation location.
379     if (printerFlags.shouldPrintDebugInfo())
380       initializer.visit(op->getLoc(), /*canBeDeferred=*/true);
381 
382     // If requested, always print the generic form.
383     if (!printerFlags.shouldPrintGenericOpForm()) {
384       // Check to see if this is a known operation.  If so, use the registered
385       // custom printer hook.
386       if (auto opInfo = op->getRegisteredInfo()) {
387         opInfo->printAssembly(op, *this, /*defaultDialect=*/"");
388         return;
389       }
390     }
391 
392     // Otherwise print with the generic assembly form.
393     printGenericOp(op);
394   }
395 
396 private:
397   /// Print the given operation in the generic form.
398   void printGenericOp(Operation *op, bool printOpName = true) override {
399     // Consider nested operations for aliases.
400     if (op->getNumRegions() != 0) {
401       for (Region &region : op->getRegions())
402         printRegion(region, /*printEntryBlockArgs=*/true,
403                     /*printBlockTerminators=*/true);
404     }
405 
406     // Visit all the types used in the operation.
407     for (Type type : op->getOperandTypes())
408       printType(type);
409     for (Type type : op->getResultTypes())
410       printType(type);
411 
412     // Consider the attributes of the operation for aliases.
413     for (const NamedAttribute &attr : op->getAttrs())
414       printAttribute(attr.getValue());
415   }
416 
417   /// Print the given block. If 'printBlockArgs' is false, the arguments of the
418   /// block are not printed. If 'printBlockTerminator' is false, the terminator
419   /// operation of the block is not printed.
420   void print(Block *block, bool printBlockArgs = true,
421              bool printBlockTerminator = true) {
422     // Consider the types of the block arguments for aliases if 'printBlockArgs'
423     // is set to true.
424     if (printBlockArgs) {
425       for (BlockArgument arg : block->getArguments()) {
426         printType(arg.getType());
427 
428         // Visit the argument location.
429         if (printerFlags.shouldPrintDebugInfo())
430           // TODO: Allow deferring argument locations.
431           initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
432       }
433     }
434 
435     // Consider the operations within this block, ignoring the terminator if
436     // requested.
437     bool hasTerminator =
438         !block->empty() && block->back().hasTrait<OpTrait::IsTerminator>();
439     auto range = llvm::make_range(
440         block->begin(),
441         std::prev(block->end(),
442                   (!hasTerminator || printBlockTerminator) ? 0 : 1));
443     for (Operation &op : range)
444       print(&op);
445   }
446 
447   /// Print the given region.
448   void printRegion(Region &region, bool printEntryBlockArgs,
449                    bool printBlockTerminators,
450                    bool printEmptyBlock = false) override {
451     if (region.empty())
452       return;
453 
454     auto *entryBlock = &region.front();
455     print(entryBlock, printEntryBlockArgs, printBlockTerminators);
456     for (Block &b : llvm::drop_begin(region, 1))
457       print(&b);
458   }
459 
460   void printRegionArgument(BlockArgument arg, ArrayRef<NamedAttribute> argAttrs,
461                            bool omitType) override {
462     printType(arg.getType());
463     // Visit the argument location.
464     if (printerFlags.shouldPrintDebugInfo())
465       // TODO: Allow deferring argument locations.
466       initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
467   }
468 
469   /// Consider the given type to be printed for an alias.
470   void printType(Type type) override { initializer.visit(type); }
471 
472   /// Consider the given attribute to be printed for an alias.
473   void printAttribute(Attribute attr) override { initializer.visit(attr); }
474   void printAttributeWithoutType(Attribute attr) override {
475     printAttribute(attr);
476   }
477   LogicalResult printAlias(Attribute attr) override {
478     initializer.visit(attr);
479     return success();
480   }
481   LogicalResult printAlias(Type type) override {
482     initializer.visit(type);
483     return success();
484   }
485 
486   /// Print the given set of attributes with names not included within
487   /// 'elidedAttrs'.
488   void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
489                              ArrayRef<StringRef> elidedAttrs = {}) override {
490     if (attrs.empty())
491       return;
492     if (elidedAttrs.empty()) {
493       for (const NamedAttribute &attr : attrs)
494         printAttribute(attr.getValue());
495       return;
496     }
497     llvm::SmallDenseSet<StringRef> elidedAttrsSet(elidedAttrs.begin(),
498                                                   elidedAttrs.end());
499     for (const NamedAttribute &attr : attrs)
500       if (!elidedAttrsSet.contains(attr.getName().strref()))
501         printAttribute(attr.getValue());
502   }
503   void printOptionalAttrDictWithKeyword(
504       ArrayRef<NamedAttribute> attrs,
505       ArrayRef<StringRef> elidedAttrs = {}) override {
506     printOptionalAttrDict(attrs, elidedAttrs);
507   }
508 
509   /// Return a null stream as the output stream, this will ignore any data fed
510   /// to it.
511   raw_ostream &getStream() const override { return os; }
512 
513   /// The following are hooks of `OpAsmPrinter` that are not necessary for
514   /// determining potential aliases.
515   void printFloat(const APFloat &value) override {}
516   void printAffineMapOfSSAIds(AffineMapAttr, ValueRange) override {}
517   void printAffineExprOfSSAIds(AffineExpr, ValueRange, ValueRange) override {}
518   void printNewline() override {}
519   void printOperand(Value) override {}
520   void printOperand(Value, raw_ostream &os) override {
521     // Users expect the output string to have at least the prefixed % to signal
522     // a value name. To maintain this invariant, emit a name even if it is
523     // guaranteed to go unused.
524     os << "%";
525   }
526   void printKeywordOrString(StringRef) override {}
527   void printSymbolName(StringRef) override {}
528   void printSuccessor(Block *) override {}
529   void printSuccessorAndUseList(Block *, ValueRange) override {}
530   void shadowRegionArgs(Region &, ValueRange) override {}
531 
532   /// The printer flags to use when determining potential aliases.
533   const OpPrintingFlags &printerFlags;
534 
535   /// The initializer to use when identifying aliases.
536   AliasInitializer &initializer;
537 
538   /// A dummy output stream.
539   mutable llvm::raw_null_ostream os;
540 };
541 } // namespace
542 
543 /// Sanitize the given name such that it can be used as a valid identifier. If
544 /// the string needs to be modified in any way, the provided buffer is used to
545 /// store the new copy,
546 static StringRef sanitizeIdentifier(StringRef name, SmallString<16> &buffer,
547                                     StringRef allowedPunctChars = "$._-",
548                                     bool allowTrailingDigit = true) {
549   assert(!name.empty() && "Shouldn't have an empty name here");
550 
551   auto copyNameToBuffer = [&] {
552     for (char ch : name) {
553       if (llvm::isAlnum(ch) || allowedPunctChars.contains(ch))
554         buffer.push_back(ch);
555       else if (ch == ' ')
556         buffer.push_back('_');
557       else
558         buffer.append(llvm::utohexstr((unsigned char)ch));
559     }
560   };
561 
562   // Check to see if this name is valid. If it starts with a digit, then it
563   // could conflict with the autogenerated numeric ID's, so add an underscore
564   // prefix to avoid problems.
565   if (isdigit(name[0])) {
566     buffer.push_back('_');
567     copyNameToBuffer();
568     return buffer;
569   }
570 
571   // If the name ends with a trailing digit, add a '_' to avoid potential
572   // conflicts with autogenerated ID's.
573   if (!allowTrailingDigit && isdigit(name.back())) {
574     copyNameToBuffer();
575     buffer.push_back('_');
576     return buffer;
577   }
578 
579   // Check to see that the name consists of only valid identifier characters.
580   for (char ch : name) {
581     if (!llvm::isAlnum(ch) && !allowedPunctChars.contains(ch)) {
582       copyNameToBuffer();
583       return buffer;
584     }
585   }
586 
587   // If there are no invalid characters, return the original name.
588   return name;
589 }
590 
591 /// Given a collection of aliases and symbols, initialize a mapping from a
592 /// symbol to a given alias.
593 template <typename T>
594 static void
595 initializeAliases(llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol,
596                   llvm::MapVector<T, SymbolAlias> &symbolToAlias,
597                   DenseSet<T> *deferrableAliases = nullptr) {
598   std::vector<std::pair<StringRef, std::vector<T>>> aliases =
599       aliasToSymbol.takeVector();
600   llvm::array_pod_sort(aliases.begin(), aliases.end(),
601                        [](const auto *lhs, const auto *rhs) {
602                          return lhs->first.compare(rhs->first);
603                        });
604 
605   for (auto &it : aliases) {
606     // If there is only one instance for this alias, use the name directly.
607     if (it.second.size() == 1) {
608       T symbol = it.second.front();
609       bool isDeferrable = deferrableAliases && deferrableAliases->count(symbol);
610       symbolToAlias.insert({symbol, SymbolAlias(it.first, isDeferrable)});
611       continue;
612     }
613     // Otherwise, add the index to the name.
614     for (int i = 0, e = it.second.size(); i < e; ++i) {
615       T symbol = it.second[i];
616       bool isDeferrable = deferrableAliases && deferrableAliases->count(symbol);
617       symbolToAlias.insert({symbol, SymbolAlias(it.first, i, isDeferrable)});
618     }
619   }
620 }
621 
622 void AliasInitializer::initialize(
623     Operation *op, const OpPrintingFlags &printerFlags,
624     llvm::MapVector<Attribute, SymbolAlias> &attrToAlias,
625     llvm::MapVector<Type, SymbolAlias> &typeToAlias) {
626   // Use a dummy printer when walking the IR so that we can collect the
627   // attributes/types that will actually be used during printing when
628   // considering aliases.
629   DummyAliasOperationPrinter aliasPrinter(printerFlags, *this);
630   aliasPrinter.print(op);
631 
632   // Initialize the aliases sorted by name.
633   initializeAliases(aliasToAttr, attrToAlias, &deferrableAttributes);
634   initializeAliases(aliasToType, typeToAlias);
635 }
636 
637 void AliasInitializer::visit(Attribute attr, bool canBeDeferred) {
638   if (!visitedAttributes.insert(attr).second) {
639     // If this attribute already has an alias and this instance can't be
640     // deferred, make sure that the alias isn't deferred.
641     if (!canBeDeferred)
642       deferrableAttributes.erase(attr);
643     return;
644   }
645 
646   // Try to generate an alias for this attribute.
647   if (succeeded(generateAlias(attr, aliasToAttr))) {
648     if (canBeDeferred)
649       deferrableAttributes.insert(attr);
650     return;
651   }
652 
653   // Check for any sub elements.
654   if (auto subElementInterface = attr.dyn_cast<SubElementAttrInterface>()) {
655     subElementInterface.walkSubElements([&](Attribute attr) { visit(attr); },
656                                         [&](Type type) { visit(type); });
657   }
658 }
659 
660 void AliasInitializer::visit(Type type) {
661   if (!visitedTypes.insert(type).second)
662     return;
663 
664   // Try to generate an alias for this type.
665   if (succeeded(generateAlias(type, aliasToType)))
666     return;
667 
668   // Check for any sub elements.
669   if (auto subElementInterface = type.dyn_cast<SubElementTypeInterface>()) {
670     subElementInterface.walkSubElements([&](Attribute attr) { visit(attr); },
671                                         [&](Type type) { visit(type); });
672   }
673 }
674 
675 template <typename T>
676 LogicalResult AliasInitializer::generateAlias(
677     T symbol, llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol) {
678   SmallString<32> nameBuffer;
679   for (const auto &interface : interfaces) {
680     OpAsmDialectInterface::AliasResult result =
681         interface.getAlias(symbol, aliasOS);
682     if (result == OpAsmDialectInterface::AliasResult::NoAlias)
683       continue;
684     nameBuffer = std::move(aliasBuffer);
685     assert(!nameBuffer.empty() && "expected valid alias name");
686     if (result == OpAsmDialectInterface::AliasResult::FinalAlias)
687       break;
688   }
689 
690   if (nameBuffer.empty())
691     return failure();
692 
693   SmallString<16> tempBuffer;
694   StringRef name =
695       sanitizeIdentifier(nameBuffer, tempBuffer, /*allowedPunctChars=*/"$_-",
696                          /*allowTrailingDigit=*/false);
697   name = name.copy(aliasAllocator);
698   aliasToSymbol[name].push_back(symbol);
699   return success();
700 }
701 
702 //===----------------------------------------------------------------------===//
703 // AliasState
704 //===----------------------------------------------------------------------===//
705 
706 namespace {
707 /// This class manages the state for type and attribute aliases.
708 class AliasState {
709 public:
710   // Initialize the internal aliases.
711   void
712   initialize(Operation *op, const OpPrintingFlags &printerFlags,
713              DialectInterfaceCollection<OpAsmDialectInterface> &interfaces);
714 
715   /// Get an alias for the given attribute if it has one and print it in `os`.
716   /// Returns success if an alias was printed, failure otherwise.
717   LogicalResult getAlias(Attribute attr, raw_ostream &os) const;
718 
719   /// Get an alias for the given type if it has one and print it in `os`.
720   /// Returns success if an alias was printed, failure otherwise.
721   LogicalResult getAlias(Type ty, raw_ostream &os) const;
722 
723   /// Print all of the referenced aliases that can not be resolved in a deferred
724   /// manner.
725   void printNonDeferredAliases(raw_ostream &os, NewLineCounter &newLine) const {
726     printAliases(os, newLine, /*isDeferred=*/false);
727   }
728 
729   /// Print all of the referenced aliases that support deferred resolution.
730   void printDeferredAliases(raw_ostream &os, NewLineCounter &newLine) const {
731     printAliases(os, newLine, /*isDeferred=*/true);
732   }
733 
734 private:
735   /// Print all of the referenced aliases that support the provided resolution
736   /// behavior.
737   void printAliases(raw_ostream &os, NewLineCounter &newLine,
738                     bool isDeferred) const;
739 
740   /// Mapping between attribute and alias.
741   llvm::MapVector<Attribute, SymbolAlias> attrToAlias;
742   /// Mapping between type and alias.
743   llvm::MapVector<Type, SymbolAlias> typeToAlias;
744 
745   /// An allocator used for alias names.
746   llvm::BumpPtrAllocator aliasAllocator;
747 };
748 } // namespace
749 
750 void AliasState::initialize(
751     Operation *op, const OpPrintingFlags &printerFlags,
752     DialectInterfaceCollection<OpAsmDialectInterface> &interfaces) {
753   AliasInitializer initializer(interfaces, aliasAllocator);
754   initializer.initialize(op, printerFlags, attrToAlias, typeToAlias);
755 }
756 
757 LogicalResult AliasState::getAlias(Attribute attr, raw_ostream &os) const {
758   auto it = attrToAlias.find(attr);
759   if (it == attrToAlias.end())
760     return failure();
761   it->second.print(os << '#');
762   return success();
763 }
764 
765 LogicalResult AliasState::getAlias(Type ty, raw_ostream &os) const {
766   auto it = typeToAlias.find(ty);
767   if (it == typeToAlias.end())
768     return failure();
769 
770   it->second.print(os << '!');
771   return success();
772 }
773 
774 void AliasState::printAliases(raw_ostream &os, NewLineCounter &newLine,
775                               bool isDeferred) const {
776   auto filterFn = [=](const auto &aliasIt) {
777     return aliasIt.second.canBeDeferred() == isDeferred;
778   };
779   for (const auto &it : llvm::make_filter_range(attrToAlias, filterFn)) {
780     it.second.print(os << '#');
781     os << " = " << it.first << newLine;
782   }
783   for (const auto &it : llvm::make_filter_range(typeToAlias, filterFn)) {
784     it.second.print(os << '!');
785     os << " = type " << it.first << newLine;
786   }
787 }
788 
789 //===----------------------------------------------------------------------===//
790 // SSANameState
791 //===----------------------------------------------------------------------===//
792 
793 namespace {
794 /// This class manages the state of SSA value names.
795 class SSANameState {
796 public:
797   /// A sentinel value used for values with names set.
798   enum : unsigned { NameSentinel = ~0U };
799 
800   SSANameState(Operation *op, const OpPrintingFlags &printerFlags);
801 
802   /// Print the SSA identifier for the given value to 'stream'. If
803   /// 'printResultNo' is true, it also presents the result number ('#' number)
804   /// of this value.
805   void printValueID(Value value, bool printResultNo, raw_ostream &stream) const;
806 
807   /// Return the result indices for each of the result groups registered by this
808   /// operation, or empty if none exist.
809   ArrayRef<int> getOpResultGroups(Operation *op);
810 
811   /// Get the ID for the given block.
812   unsigned getBlockID(Block *block);
813 
814   /// Renumber the arguments for the specified region to the same names as the
815   /// SSA values in namesToUse. See OperationPrinter::shadowRegionArgs for
816   /// details.
817   void shadowRegionArgs(Region &region, ValueRange namesToUse);
818 
819 private:
820   /// Number the SSA values within the given IR unit.
821   void numberValuesInRegion(Region &region);
822   void numberValuesInBlock(Block &block);
823   void numberValuesInOp(Operation &op);
824 
825   /// Given a result of an operation 'result', find the result group head
826   /// 'lookupValue' and the result of 'result' within that group in
827   /// 'lookupResultNo'. 'lookupResultNo' is only filled in if the result group
828   /// has more than 1 result.
829   void getResultIDAndNumber(OpResult result, Value &lookupValue,
830                             Optional<int> &lookupResultNo) const;
831 
832   /// Set a special value name for the given value.
833   void setValueName(Value value, StringRef name);
834 
835   /// Uniques the given value name within the printer. If the given name
836   /// conflicts, it is automatically renamed.
837   StringRef uniqueValueName(StringRef name);
838 
839   /// This is the value ID for each SSA value. If this returns NameSentinel,
840   /// then the valueID has an entry in valueNames.
841   DenseMap<Value, unsigned> valueIDs;
842   DenseMap<Value, StringRef> valueNames;
843 
844   /// This is a map of operations that contain multiple named result groups,
845   /// i.e. there may be multiple names for the results of the operation. The
846   /// value of this map are the result numbers that start a result group.
847   DenseMap<Operation *, SmallVector<int, 1>> opResultGroups;
848 
849   /// This is the block ID for each block in the current.
850   DenseMap<Block *, unsigned> blockIDs;
851 
852   /// This keeps track of all of the non-numeric names that are in flight,
853   /// allowing us to check for duplicates.
854   /// Note: the value of the map is unused.
855   llvm::ScopedHashTable<StringRef, char> usedNames;
856   llvm::BumpPtrAllocator usedNameAllocator;
857 
858   /// This is the next value ID to assign in numbering.
859   unsigned nextValueID = 0;
860   /// This is the next ID to assign to a region entry block argument.
861   unsigned nextArgumentID = 0;
862   /// This is the next ID to assign when a name conflict is detected.
863   unsigned nextConflictID = 0;
864 
865   /// These are the printing flags.  They control, eg., whether to print in
866   /// generic form.
867   OpPrintingFlags printerFlags;
868 };
869 } // namespace
870 
871 SSANameState::SSANameState(
872     Operation *op, const OpPrintingFlags &printerFlags)
873     : printerFlags(printerFlags) {
874   llvm::SaveAndRestore<unsigned> valueIDSaver(nextValueID);
875   llvm::SaveAndRestore<unsigned> argumentIDSaver(nextArgumentID);
876   llvm::SaveAndRestore<unsigned> conflictIDSaver(nextConflictID);
877 
878   // The naming context includes `nextValueID`, `nextArgumentID`,
879   // `nextConflictID` and `usedNames` scoped HashTable. This information is
880   // carried from the parent region.
881   using UsedNamesScopeTy = llvm::ScopedHashTable<StringRef, char>::ScopeTy;
882   using NamingContext =
883       std::tuple<Region *, unsigned, unsigned, unsigned, UsedNamesScopeTy *>;
884 
885   // Allocator for UsedNamesScopeTy
886   llvm::BumpPtrAllocator allocator;
887 
888   // Add a scope for the top level operation.
889   auto *topLevelNamesScope =
890       new (allocator.Allocate<UsedNamesScopeTy>()) UsedNamesScopeTy(usedNames);
891 
892   SmallVector<NamingContext, 8> nameContext;
893   for (Region &region : op->getRegions())
894     nameContext.push_back(std::make_tuple(&region, nextValueID, nextArgumentID,
895                                           nextConflictID, topLevelNamesScope));
896 
897   numberValuesInOp(*op);
898 
899   while (!nameContext.empty()) {
900     Region *region;
901     UsedNamesScopeTy *parentScope;
902     std::tie(region, nextValueID, nextArgumentID, nextConflictID, parentScope) =
903         nameContext.pop_back_val();
904 
905     // When we switch from one subtree to another, pop the scopes(needless)
906     // until the parent scope.
907     while (usedNames.getCurScope() != parentScope) {
908       usedNames.getCurScope()->~UsedNamesScopeTy();
909       assert((usedNames.getCurScope() != nullptr || parentScope == nullptr) &&
910              "top level parentScope must be a nullptr");
911     }
912 
913     // Add a scope for the current region.
914     auto *curNamesScope = new (allocator.Allocate<UsedNamesScopeTy>())
915         UsedNamesScopeTy(usedNames);
916 
917     numberValuesInRegion(*region);
918 
919     for (Operation &op : region->getOps())
920       for (Region &region : op.getRegions())
921         nameContext.push_back(std::make_tuple(&region, nextValueID,
922                                               nextArgumentID, nextConflictID,
923                                               curNamesScope));
924   }
925 
926   // Manually remove all the scopes.
927   while (usedNames.getCurScope() != nullptr)
928     usedNames.getCurScope()->~UsedNamesScopeTy();
929 }
930 
931 void SSANameState::printValueID(Value value, bool printResultNo,
932                                 raw_ostream &stream) const {
933   if (!value) {
934     stream << "<<NULL VALUE>>";
935     return;
936   }
937 
938   Optional<int> resultNo;
939   auto lookupValue = value;
940 
941   // If this is an operation result, collect the head lookup value of the result
942   // group and the result number of 'result' within that group.
943   if (OpResult result = value.dyn_cast<OpResult>())
944     getResultIDAndNumber(result, lookupValue, resultNo);
945 
946   auto it = valueIDs.find(lookupValue);
947   if (it == valueIDs.end()) {
948     stream << "<<UNKNOWN SSA VALUE>>";
949     return;
950   }
951 
952   stream << '%';
953   if (it->second != NameSentinel) {
954     stream << it->second;
955   } else {
956     auto nameIt = valueNames.find(lookupValue);
957     assert(nameIt != valueNames.end() && "Didn't have a name entry?");
958     stream << nameIt->second;
959   }
960 
961   if (resultNo.hasValue() && printResultNo)
962     stream << '#' << resultNo;
963 }
964 
965 ArrayRef<int> SSANameState::getOpResultGroups(Operation *op) {
966   auto it = opResultGroups.find(op);
967   return it == opResultGroups.end() ? ArrayRef<int>() : it->second;
968 }
969 
970 unsigned SSANameState::getBlockID(Block *block) {
971   auto it = blockIDs.find(block);
972   return it != blockIDs.end() ? it->second : NameSentinel;
973 }
974 
975 void SSANameState::shadowRegionArgs(Region &region, ValueRange namesToUse) {
976   assert(!region.empty() && "cannot shadow arguments of an empty region");
977   assert(region.getNumArguments() == namesToUse.size() &&
978          "incorrect number of names passed in");
979   assert(region.getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
980          "only KnownIsolatedFromAbove ops can shadow names");
981 
982   SmallVector<char, 16> nameStr;
983   for (unsigned i = 0, e = namesToUse.size(); i != e; ++i) {
984     auto nameToUse = namesToUse[i];
985     if (nameToUse == nullptr)
986       continue;
987     auto nameToReplace = region.getArgument(i);
988 
989     nameStr.clear();
990     llvm::raw_svector_ostream nameStream(nameStr);
991     printValueID(nameToUse, /*printResultNo=*/true, nameStream);
992 
993     // Entry block arguments should already have a pretty "arg" name.
994     assert(valueIDs[nameToReplace] == NameSentinel);
995 
996     // Use the name without the leading %.
997     auto name = StringRef(nameStream.str()).drop_front();
998 
999     // Overwrite the name.
1000     valueNames[nameToReplace] = name.copy(usedNameAllocator);
1001   }
1002 }
1003 
1004 void SSANameState::numberValuesInRegion(Region &region) {
1005   auto setBlockArgNameFn = [&](Value arg, StringRef name) {
1006     assert(!valueIDs.count(arg) && "arg numbered multiple times");
1007     assert(arg.cast<BlockArgument>().getOwner()->getParent() == &region &&
1008            "arg not defined in current region");
1009     setValueName(arg, name);
1010   };
1011 
1012   if (!printerFlags.shouldPrintGenericOpForm()) {
1013     if (Operation *op = region.getParentOp()) {
1014       if (auto asmInterface = dyn_cast<OpAsmOpInterface>(op))
1015         asmInterface.getAsmBlockArgumentNames(region, setBlockArgNameFn);
1016     }
1017   }
1018 
1019   // Number the values within this region in a breadth-first order.
1020   unsigned nextBlockID = 0;
1021   for (auto &block : region) {
1022     // Each block gets a unique ID, and all of the operations within it get
1023     // numbered as well.
1024     blockIDs[&block] = nextBlockID++;
1025     numberValuesInBlock(block);
1026   }
1027 }
1028 
1029 void SSANameState::numberValuesInBlock(Block &block) {
1030   // Number the block arguments. We give entry block arguments a special name
1031   // 'arg'.
1032   bool isEntryBlock = block.isEntryBlock();
1033   SmallString<32> specialNameBuffer(isEntryBlock ? "arg" : "");
1034   llvm::raw_svector_ostream specialName(specialNameBuffer);
1035   for (auto arg : block.getArguments()) {
1036     if (valueIDs.count(arg))
1037       continue;
1038     if (isEntryBlock) {
1039       specialNameBuffer.resize(strlen("arg"));
1040       specialName << nextArgumentID++;
1041     }
1042     setValueName(arg, specialName.str());
1043   }
1044 
1045   // Number the operations in this block.
1046   for (auto &op : block)
1047     numberValuesInOp(op);
1048 }
1049 
1050 void SSANameState::numberValuesInOp(Operation &op) {
1051   unsigned numResults = op.getNumResults();
1052   if (numResults == 0)
1053     return;
1054   Value resultBegin = op.getResult(0);
1055 
1056   // Function used to set the special result names for the operation.
1057   SmallVector<int, 2> resultGroups(/*Size=*/1, /*Value=*/0);
1058   auto setResultNameFn = [&](Value result, StringRef name) {
1059     assert(!valueIDs.count(result) && "result numbered multiple times");
1060     assert(result.getDefiningOp() == &op && "result not defined by 'op'");
1061     setValueName(result, name);
1062 
1063     // Record the result number for groups not anchored at 0.
1064     if (int resultNo = result.cast<OpResult>().getResultNumber())
1065       resultGroups.push_back(resultNo);
1066   };
1067   if (!printerFlags.shouldPrintGenericOpForm()) {
1068     if (OpAsmOpInterface asmInterface = dyn_cast<OpAsmOpInterface>(&op))
1069       asmInterface.getAsmResultNames(setResultNameFn);
1070   }
1071 
1072   // If the first result wasn't numbered, give it a default number.
1073   if (valueIDs.try_emplace(resultBegin, nextValueID).second)
1074     ++nextValueID;
1075 
1076   // If this operation has multiple result groups, mark it.
1077   if (resultGroups.size() != 1) {
1078     llvm::array_pod_sort(resultGroups.begin(), resultGroups.end());
1079     opResultGroups.try_emplace(&op, std::move(resultGroups));
1080   }
1081 }
1082 
1083 void SSANameState::getResultIDAndNumber(OpResult result, Value &lookupValue,
1084                                         Optional<int> &lookupResultNo) const {
1085   Operation *owner = result.getOwner();
1086   if (owner->getNumResults() == 1)
1087     return;
1088   int resultNo = result.getResultNumber();
1089 
1090   // If this operation has multiple result groups, we will need to find the
1091   // one corresponding to this result.
1092   auto resultGroupIt = opResultGroups.find(owner);
1093   if (resultGroupIt == opResultGroups.end()) {
1094     // If not, just use the first result.
1095     lookupResultNo = resultNo;
1096     lookupValue = owner->getResult(0);
1097     return;
1098   }
1099 
1100   // Find the correct index using a binary search, as the groups are ordered.
1101   ArrayRef<int> resultGroups = resultGroupIt->second;
1102   const auto *it = llvm::upper_bound(resultGroups, resultNo);
1103   int groupResultNo = 0, groupSize = 0;
1104 
1105   // If there are no smaller elements, the last result group is the lookup.
1106   if (it == resultGroups.end()) {
1107     groupResultNo = resultGroups.back();
1108     groupSize = static_cast<int>(owner->getNumResults()) - resultGroups.back();
1109   } else {
1110     // Otherwise, the previous element is the lookup.
1111     groupResultNo = *std::prev(it);
1112     groupSize = *it - groupResultNo;
1113   }
1114 
1115   // We only record the result number for a group of size greater than 1.
1116   if (groupSize != 1)
1117     lookupResultNo = resultNo - groupResultNo;
1118   lookupValue = owner->getResult(groupResultNo);
1119 }
1120 
1121 void SSANameState::setValueName(Value value, StringRef name) {
1122   // If the name is empty, the value uses the default numbering.
1123   if (name.empty()) {
1124     valueIDs[value] = nextValueID++;
1125     return;
1126   }
1127 
1128   valueIDs[value] = NameSentinel;
1129   valueNames[value] = uniqueValueName(name);
1130 }
1131 
1132 StringRef SSANameState::uniqueValueName(StringRef name) {
1133   SmallString<16> tmpBuffer;
1134   name = sanitizeIdentifier(name, tmpBuffer);
1135 
1136   // Check to see if this name is already unique.
1137   if (!usedNames.count(name)) {
1138     name = name.copy(usedNameAllocator);
1139   } else {
1140     // Otherwise, we had a conflict - probe until we find a unique name. This
1141     // is guaranteed to terminate (and usually in a single iteration) because it
1142     // generates new names by incrementing nextConflictID.
1143     SmallString<64> probeName(name);
1144     probeName.push_back('_');
1145     while (true) {
1146       probeName += llvm::utostr(nextConflictID++);
1147       if (!usedNames.count(probeName)) {
1148         name = probeName.str().copy(usedNameAllocator);
1149         break;
1150       }
1151       probeName.resize(name.size() + 1);
1152     }
1153   }
1154 
1155   usedNames.insert(name, char());
1156   return name;
1157 }
1158 
1159 //===----------------------------------------------------------------------===//
1160 // AsmState
1161 //===----------------------------------------------------------------------===//
1162 
1163 namespace mlir {
1164 namespace detail {
1165 class AsmStateImpl {
1166 public:
1167   explicit AsmStateImpl(Operation *op, const OpPrintingFlags &printerFlags,
1168                         AsmState::LocationMap *locationMap)
1169       : interfaces(op->getContext()), nameState(op, printerFlags),
1170         printerFlags(printerFlags), locationMap(locationMap) {}
1171 
1172   /// Initialize the alias state to enable the printing of aliases.
1173   void initializeAliases(Operation *op) {
1174     aliasState.initialize(op, printerFlags, interfaces);
1175   }
1176 
1177   /// Get the state used for aliases.
1178   AliasState &getAliasState() { return aliasState; }
1179 
1180   /// Get the state used for SSA names.
1181   SSANameState &getSSANameState() { return nameState; }
1182 
1183   /// Register the location, line and column, within the buffer that the given
1184   /// operation was printed at.
1185   void registerOperationLocation(Operation *op, unsigned line, unsigned col) {
1186     if (locationMap)
1187       (*locationMap)[op] = std::make_pair(line, col);
1188   }
1189 
1190 private:
1191   /// Collection of OpAsm interfaces implemented in the context.
1192   DialectInterfaceCollection<OpAsmDialectInterface> interfaces;
1193 
1194   /// The state used for attribute and type aliases.
1195   AliasState aliasState;
1196 
1197   /// The state used for SSA value names.
1198   SSANameState nameState;
1199 
1200   /// Flags that control op output.
1201   OpPrintingFlags printerFlags;
1202 
1203   /// An optional location map to be populated.
1204   AsmState::LocationMap *locationMap;
1205 };
1206 } // namespace detail
1207 } // namespace mlir
1208 
1209 AsmState::AsmState(Operation *op, const OpPrintingFlags &printerFlags,
1210                    LocationMap *locationMap)
1211     : impl(std::make_unique<AsmStateImpl>(op, printerFlags, locationMap)) {}
1212 AsmState::~AsmState() = default;
1213 
1214 //===----------------------------------------------------------------------===//
1215 // AsmPrinter::Impl
1216 //===----------------------------------------------------------------------===//
1217 
1218 namespace mlir {
1219 class AsmPrinter::Impl {
1220 public:
1221   Impl(raw_ostream &os, OpPrintingFlags flags = llvm::None,
1222        AsmStateImpl *state = nullptr)
1223       : os(os), printerFlags(flags), state(state) {}
1224   explicit Impl(Impl &other)
1225       : Impl(other.os, other.printerFlags, other.state) {}
1226 
1227   /// Returns the output stream of the printer.
1228   raw_ostream &getStream() { return os; }
1229 
1230   template <typename Container, typename UnaryFunctor>
1231   inline void interleaveComma(const Container &c, UnaryFunctor eachFn) const {
1232     llvm::interleaveComma(c, os, eachFn);
1233   }
1234 
1235   /// This enum describes the different kinds of elision for the type of an
1236   /// attribute when printing it.
1237   enum class AttrTypeElision {
1238     /// The type must not be elided,
1239     Never,
1240     /// The type may be elided when it matches the default used in the parser
1241     /// (for example i64 is the default for integer attributes).
1242     May,
1243     /// The type must be elided.
1244     Must
1245   };
1246 
1247   /// Print the given attribute.
1248   void printAttribute(Attribute attr,
1249                       AttrTypeElision typeElision = AttrTypeElision::Never);
1250 
1251   /// Print the alias for the given attribute, return failure if no alias could
1252   /// be printed.
1253   LogicalResult printAlias(Attribute attr);
1254 
1255   void printType(Type type);
1256 
1257   /// Print the alias for the given type, return failure if no alias could
1258   /// be printed.
1259   LogicalResult printAlias(Type type);
1260 
1261   /// Print the given location to the stream. If `allowAlias` is true, this
1262   /// allows for the internal location to use an attribute alias.
1263   void printLocation(LocationAttr loc, bool allowAlias = false);
1264 
1265   void printAffineMap(AffineMap map);
1266   void
1267   printAffineExpr(AffineExpr expr,
1268                   function_ref<void(unsigned, bool)> printValueName = nullptr);
1269   void printAffineConstraint(AffineExpr expr, bool isEq);
1270   void printIntegerSet(IntegerSet set);
1271 
1272 protected:
1273   void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
1274                              ArrayRef<StringRef> elidedAttrs = {},
1275                              bool withKeyword = false);
1276   void printNamedAttribute(NamedAttribute attr);
1277   void printTrailingLocation(Location loc, bool allowAlias = true);
1278   void printLocationInternal(LocationAttr loc, bool pretty = false);
1279 
1280   /// Print a dense elements attribute. If 'allowHex' is true, a hex string is
1281   /// used instead of individual elements when the elements attr is large.
1282   void printDenseElementsAttr(DenseElementsAttr attr, bool allowHex);
1283 
1284   /// Print a dense string elements attribute.
1285   void printDenseStringElementsAttr(DenseStringElementsAttr attr);
1286 
1287   /// Print a dense elements attribute. If 'allowHex' is true, a hex string is
1288   /// used instead of individual elements when the elements attr is large.
1289   void printDenseIntOrFPElementsAttr(DenseIntOrFPElementsAttr attr,
1290                                      bool allowHex);
1291 
1292   void printDialectAttribute(Attribute attr);
1293   void printDialectType(Type type);
1294 
1295   /// This enum is used to represent the binding strength of the enclosing
1296   /// context that an AffineExprStorage is being printed in, so we can
1297   /// intelligently produce parens.
1298   enum class BindingStrength {
1299     Weak,   // + and -
1300     Strong, // All other binary operators.
1301   };
1302   void printAffineExprInternal(
1303       AffineExpr expr, BindingStrength enclosingTightness,
1304       function_ref<void(unsigned, bool)> printValueName = nullptr);
1305 
1306   /// The output stream for the printer.
1307   raw_ostream &os;
1308 
1309   /// A set of flags to control the printer's behavior.
1310   OpPrintingFlags printerFlags;
1311 
1312   /// An optional printer state for the module.
1313   AsmStateImpl *state;
1314 
1315   /// A tracker for the number of new lines emitted during printing.
1316   NewLineCounter newLine;
1317 };
1318 } // namespace mlir
1319 
1320 void AsmPrinter::Impl::printTrailingLocation(Location loc, bool allowAlias) {
1321   // Check to see if we are printing debug information.
1322   if (!printerFlags.shouldPrintDebugInfo())
1323     return;
1324 
1325   os << " ";
1326   printLocation(loc, /*allowAlias=*/allowAlias);
1327 }
1328 
1329 void AsmPrinter::Impl::printLocationInternal(LocationAttr loc, bool pretty) {
1330   TypeSwitch<LocationAttr>(loc)
1331       .Case<OpaqueLoc>([&](OpaqueLoc loc) {
1332         printLocationInternal(loc.getFallbackLocation(), pretty);
1333       })
1334       .Case<UnknownLoc>([&](UnknownLoc loc) {
1335         if (pretty)
1336           os << "[unknown]";
1337         else
1338           os << "unknown";
1339       })
1340       .Case<FileLineColLoc>([&](FileLineColLoc loc) {
1341         if (pretty) {
1342           os << loc.getFilename().getValue();
1343         } else {
1344           os << "\"";
1345           printEscapedString(loc.getFilename(), os);
1346           os << "\"";
1347         }
1348         os << ':' << loc.getLine() << ':' << loc.getColumn();
1349       })
1350       .Case<NameLoc>([&](NameLoc loc) {
1351         os << '\"';
1352         printEscapedString(loc.getName(), os);
1353         os << '\"';
1354 
1355         // Print the child if it isn't unknown.
1356         auto childLoc = loc.getChildLoc();
1357         if (!childLoc.isa<UnknownLoc>()) {
1358           os << '(';
1359           printLocationInternal(childLoc, pretty);
1360           os << ')';
1361         }
1362       })
1363       .Case<CallSiteLoc>([&](CallSiteLoc loc) {
1364         Location caller = loc.getCaller();
1365         Location callee = loc.getCallee();
1366         if (!pretty)
1367           os << "callsite(";
1368         printLocationInternal(callee, pretty);
1369         if (pretty) {
1370           if (callee.isa<NameLoc>()) {
1371             if (caller.isa<FileLineColLoc>()) {
1372               os << " at ";
1373             } else {
1374               os << newLine << " at ";
1375             }
1376           } else {
1377             os << newLine << " at ";
1378           }
1379         } else {
1380           os << " at ";
1381         }
1382         printLocationInternal(caller, pretty);
1383         if (!pretty)
1384           os << ")";
1385       })
1386       .Case<FusedLoc>([&](FusedLoc loc) {
1387         if (!pretty)
1388           os << "fused";
1389         if (Attribute metadata = loc.getMetadata())
1390           os << '<' << metadata << '>';
1391         os << '[';
1392         interleave(
1393             loc.getLocations(),
1394             [&](Location loc) { printLocationInternal(loc, pretty); },
1395             [&]() { os << ", "; });
1396         os << ']';
1397       });
1398 }
1399 
1400 /// Print a floating point value in a way that the parser will be able to
1401 /// round-trip losslessly.
1402 static void printFloatValue(const APFloat &apValue, raw_ostream &os) {
1403   // We would like to output the FP constant value in exponential notation,
1404   // but we cannot do this if doing so will lose precision.  Check here to
1405   // make sure that we only output it in exponential format if we can parse
1406   // the value back and get the same value.
1407   bool isInf = apValue.isInfinity();
1408   bool isNaN = apValue.isNaN();
1409   if (!isInf && !isNaN) {
1410     SmallString<128> strValue;
1411     apValue.toString(strValue, /*FormatPrecision=*/6, /*FormatMaxPadding=*/0,
1412                      /*TruncateZero=*/false);
1413 
1414     // Check to make sure that the stringized number is not some string like
1415     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1416     // that the string matches the "[-+]?[0-9]" regex.
1417     assert(((strValue[0] >= '0' && strValue[0] <= '9') ||
1418             ((strValue[0] == '-' || strValue[0] == '+') &&
1419              (strValue[1] >= '0' && strValue[1] <= '9'))) &&
1420            "[-+]?[0-9] regex does not match!");
1421 
1422     // Parse back the stringized version and check that the value is equal
1423     // (i.e., there is no precision loss).
1424     if (APFloat(apValue.getSemantics(), strValue).bitwiseIsEqual(apValue)) {
1425       os << strValue;
1426       return;
1427     }
1428 
1429     // If it is not, use the default format of APFloat instead of the
1430     // exponential notation.
1431     strValue.clear();
1432     apValue.toString(strValue);
1433 
1434     // Make sure that we can parse the default form as a float.
1435     if (strValue.str().contains('.')) {
1436       os << strValue;
1437       return;
1438     }
1439   }
1440 
1441   // Print special values in hexadecimal format. The sign bit should be included
1442   // in the literal.
1443   SmallVector<char, 16> str;
1444   APInt apInt = apValue.bitcastToAPInt();
1445   apInt.toString(str, /*Radix=*/16, /*Signed=*/false,
1446                  /*formatAsCLiteral=*/true);
1447   os << str;
1448 }
1449 
1450 void AsmPrinter::Impl::printLocation(LocationAttr loc, bool allowAlias) {
1451   if (printerFlags.shouldPrintDebugInfoPrettyForm())
1452     return printLocationInternal(loc, /*pretty=*/true);
1453 
1454   os << "loc(";
1455   if (!allowAlias || !state || failed(state->getAliasState().getAlias(loc, os)))
1456     printLocationInternal(loc);
1457   os << ')';
1458 }
1459 
1460 /// Returns true if the given dialect symbol data is simple enough to print in
1461 /// the pretty form, i.e. without the enclosing "".
1462 static bool isDialectSymbolSimpleEnoughForPrettyForm(StringRef symName) {
1463   // The name must start with an identifier.
1464   if (symName.empty() || !isalpha(symName.front()))
1465     return false;
1466 
1467   // Ignore all the characters that are valid in an identifier in the symbol
1468   // name.
1469   symName = symName.drop_while(
1470       [](char c) { return llvm::isAlnum(c) || c == '.' || c == '_'; });
1471   if (symName.empty())
1472     return true;
1473 
1474   // If we got to an unexpected character, then it must be a <>.  Check those
1475   // recursively.
1476   if (symName.front() != '<' || symName.back() != '>')
1477     return false;
1478 
1479   SmallVector<char, 8> nestedPunctuation;
1480   do {
1481     // If we ran out of characters, then we had a punctuation mismatch.
1482     if (symName.empty())
1483       return false;
1484 
1485     auto c = symName.front();
1486     symName = symName.drop_front();
1487 
1488     switch (c) {
1489     // We never allow null characters. This is an EOF indicator for the lexer
1490     // which we could handle, but isn't important for any known dialect.
1491     case '\0':
1492       return false;
1493     case '<':
1494     case '[':
1495     case '(':
1496     case '{':
1497       nestedPunctuation.push_back(c);
1498       continue;
1499     case '-':
1500       // Treat `->` as a special token.
1501       if (!symName.empty() && symName.front() == '>') {
1502         symName = symName.drop_front();
1503         continue;
1504       }
1505       break;
1506     // Reject types with mismatched brackets.
1507     case '>':
1508       if (nestedPunctuation.pop_back_val() != '<')
1509         return false;
1510       break;
1511     case ']':
1512       if (nestedPunctuation.pop_back_val() != '[')
1513         return false;
1514       break;
1515     case ')':
1516       if (nestedPunctuation.pop_back_val() != '(')
1517         return false;
1518       break;
1519     case '}':
1520       if (nestedPunctuation.pop_back_val() != '{')
1521         return false;
1522       break;
1523     default:
1524       continue;
1525     }
1526 
1527     // We're done when the punctuation is fully matched.
1528   } while (!nestedPunctuation.empty());
1529 
1530   // If there were extra characters, then we failed.
1531   return symName.empty();
1532 }
1533 
1534 /// Print the given dialect symbol to the stream.
1535 static void printDialectSymbol(raw_ostream &os, StringRef symPrefix,
1536                                StringRef dialectName, StringRef symString) {
1537   os << symPrefix << dialectName;
1538 
1539   // If this symbol name is simple enough, print it directly in pretty form,
1540   // otherwise, we print it as an escaped string.
1541   if (isDialectSymbolSimpleEnoughForPrettyForm(symString)) {
1542     os << '.' << symString;
1543     return;
1544   }
1545 
1546   os << "<\"";
1547   llvm::printEscapedString(symString, os);
1548   os << "\">";
1549 }
1550 
1551 /// Returns true if the given string can be represented as a bare identifier.
1552 static bool isBareIdentifier(StringRef name) {
1553   // By making this unsigned, the value passed in to isalnum will always be
1554   // in the range 0-255. This is important when building with MSVC because
1555   // its implementation will assert. This situation can arise when dealing
1556   // with UTF-8 multibyte characters.
1557   if (name.empty() || (!isalpha(name[0]) && name[0] != '_'))
1558     return false;
1559   return llvm::all_of(name.drop_front(), [](unsigned char c) {
1560     return isalnum(c) || c == '_' || c == '$' || c == '.';
1561   });
1562 }
1563 
1564 /// Print the given string as a keyword, or a quoted and escaped string if it
1565 /// has any special or non-printable characters in it.
1566 static void printKeywordOrString(StringRef keyword, raw_ostream &os) {
1567   // If it can be represented as a bare identifier, write it directly.
1568   if (isBareIdentifier(keyword)) {
1569     os << keyword;
1570     return;
1571   }
1572 
1573   // Otherwise, output the keyword wrapped in quotes with proper escaping.
1574   os << "\"";
1575   printEscapedString(keyword, os);
1576   os << '"';
1577 }
1578 
1579 /// Print the given string as a symbol reference. A symbol reference is
1580 /// represented as a string prefixed with '@'. The reference is surrounded with
1581 /// ""'s and escaped if it has any special or non-printable characters in it.
1582 static void printSymbolReference(StringRef symbolRef, raw_ostream &os) {
1583   assert(!symbolRef.empty() && "expected valid symbol reference");
1584   os << '@';
1585   printKeywordOrString(symbolRef, os);
1586 }
1587 
1588 // Print out a valid ElementsAttr that is succinct and can represent any
1589 // potential shape/type, for use when eliding a large ElementsAttr.
1590 //
1591 // We choose to use an opaque ElementsAttr literal with conspicuous content to
1592 // hopefully alert readers to the fact that this has been elided.
1593 //
1594 // Unfortunately, neither of the strings of an opaque ElementsAttr literal will
1595 // accept the string "elided". The first string must be a registered dialect
1596 // name and the latter must be a hex constant.
1597 static void printElidedElementsAttr(raw_ostream &os) {
1598   os << R"(opaque<"elided_large_const", "0xDEADBEEF">)";
1599 }
1600 
1601 LogicalResult AsmPrinter::Impl::printAlias(Attribute attr) {
1602   return success(state && succeeded(state->getAliasState().getAlias(attr, os)));
1603 }
1604 
1605 LogicalResult AsmPrinter::Impl::printAlias(Type type) {
1606   return success(state && succeeded(state->getAliasState().getAlias(type, os)));
1607 }
1608 
1609 void AsmPrinter::Impl::printAttribute(Attribute attr,
1610                                       AttrTypeElision typeElision) {
1611   if (!attr) {
1612     os << "<<NULL ATTRIBUTE>>";
1613     return;
1614   }
1615 
1616   // Try to print an alias for this attribute.
1617   if (succeeded(printAlias(attr)))
1618     return;
1619 
1620   if (!isa<BuiltinDialect>(attr.getDialect()))
1621     return printDialectAttribute(attr);
1622 
1623   auto attrType = attr.getType();
1624   if (auto opaqueAttr = attr.dyn_cast<OpaqueAttr>()) {
1625     printDialectSymbol(os, "#", opaqueAttr.getDialectNamespace(),
1626                        opaqueAttr.getAttrData());
1627   } else if (attr.isa<UnitAttr>()) {
1628     os << "unit";
1629     return;
1630   } else if (auto dictAttr = attr.dyn_cast<DictionaryAttr>()) {
1631     os << '{';
1632     interleaveComma(dictAttr.getValue(),
1633                     [&](NamedAttribute attr) { printNamedAttribute(attr); });
1634     os << '}';
1635 
1636   } else if (auto intAttr = attr.dyn_cast<IntegerAttr>()) {
1637     if (attrType.isSignlessInteger(1)) {
1638       os << (intAttr.getValue().getBoolValue() ? "true" : "false");
1639 
1640       // Boolean integer attributes always elides the type.
1641       return;
1642     }
1643 
1644     // Only print attributes as unsigned if they are explicitly unsigned or are
1645     // signless 1-bit values.  Indexes, signed values, and multi-bit signless
1646     // values print as signed.
1647     bool isUnsigned =
1648         attrType.isUnsignedInteger() || attrType.isSignlessInteger(1);
1649     intAttr.getValue().print(os, !isUnsigned);
1650 
1651     // IntegerAttr elides the type if I64.
1652     if (typeElision == AttrTypeElision::May && attrType.isSignlessInteger(64))
1653       return;
1654 
1655   } else if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
1656     printFloatValue(floatAttr.getValue(), os);
1657 
1658     // FloatAttr elides the type if F64.
1659     if (typeElision == AttrTypeElision::May && attrType.isF64())
1660       return;
1661 
1662   } else if (auto strAttr = attr.dyn_cast<StringAttr>()) {
1663     os << '"';
1664     printEscapedString(strAttr.getValue(), os);
1665     os << '"';
1666 
1667   } else if (auto arrayAttr = attr.dyn_cast<ArrayAttr>()) {
1668     os << '[';
1669     interleaveComma(arrayAttr.getValue(), [&](Attribute attr) {
1670       printAttribute(attr, AttrTypeElision::May);
1671     });
1672     os << ']';
1673 
1674   } else if (auto affineMapAttr = attr.dyn_cast<AffineMapAttr>()) {
1675     os << "affine_map<";
1676     affineMapAttr.getValue().print(os);
1677     os << '>';
1678 
1679     // AffineMap always elides the type.
1680     return;
1681 
1682   } else if (auto integerSetAttr = attr.dyn_cast<IntegerSetAttr>()) {
1683     os << "affine_set<";
1684     integerSetAttr.getValue().print(os);
1685     os << '>';
1686 
1687     // IntegerSet always elides the type.
1688     return;
1689 
1690   } else if (auto typeAttr = attr.dyn_cast<TypeAttr>()) {
1691     printType(typeAttr.getValue());
1692 
1693   } else if (auto refAttr = attr.dyn_cast<SymbolRefAttr>()) {
1694     printSymbolReference(refAttr.getRootReference().getValue(), os);
1695     for (FlatSymbolRefAttr nestedRef : refAttr.getNestedReferences()) {
1696       os << "::";
1697       printSymbolReference(nestedRef.getValue(), os);
1698     }
1699 
1700   } else if (auto opaqueAttr = attr.dyn_cast<OpaqueElementsAttr>()) {
1701     if (printerFlags.shouldElideElementsAttr(opaqueAttr)) {
1702       printElidedElementsAttr(os);
1703     } else {
1704       os << "opaque<" << opaqueAttr.getDialect() << ", \"0x"
1705          << llvm::toHex(opaqueAttr.getValue()) << "\">";
1706     }
1707 
1708   } else if (auto intOrFpEltAttr = attr.dyn_cast<DenseIntOrFPElementsAttr>()) {
1709     if (printerFlags.shouldElideElementsAttr(intOrFpEltAttr)) {
1710       printElidedElementsAttr(os);
1711     } else {
1712       os << "dense<";
1713       printDenseIntOrFPElementsAttr(intOrFpEltAttr, /*allowHex=*/true);
1714       os << '>';
1715     }
1716 
1717   } else if (auto strEltAttr = attr.dyn_cast<DenseStringElementsAttr>()) {
1718     if (printerFlags.shouldElideElementsAttr(strEltAttr)) {
1719       printElidedElementsAttr(os);
1720     } else {
1721       os << "dense<";
1722       printDenseStringElementsAttr(strEltAttr);
1723       os << '>';
1724     }
1725 
1726   } else if (auto sparseEltAttr = attr.dyn_cast<SparseElementsAttr>()) {
1727     if (printerFlags.shouldElideElementsAttr(sparseEltAttr.getIndices()) ||
1728         printerFlags.shouldElideElementsAttr(sparseEltAttr.getValues())) {
1729       printElidedElementsAttr(os);
1730     } else {
1731       os << "sparse<";
1732       DenseIntElementsAttr indices = sparseEltAttr.getIndices();
1733       if (indices.getNumElements() != 0) {
1734         printDenseIntOrFPElementsAttr(indices, /*allowHex=*/false);
1735         os << ", ";
1736         printDenseElementsAttr(sparseEltAttr.getValues(), /*allowHex=*/true);
1737       }
1738       os << '>';
1739     }
1740 
1741   } else if (auto locAttr = attr.dyn_cast<LocationAttr>()) {
1742     printLocation(locAttr);
1743   }
1744   // Don't print the type if we must elide it, or if it is a None type.
1745   if (typeElision != AttrTypeElision::Must && !attrType.isa<NoneType>()) {
1746     os << " : ";
1747     printType(attrType);
1748   }
1749 }
1750 
1751 /// Print the integer element of a DenseElementsAttr.
1752 static void printDenseIntElement(const APInt &value, raw_ostream &os,
1753                                  bool isSigned) {
1754   if (value.getBitWidth() == 1)
1755     os << (value.getBoolValue() ? "true" : "false");
1756   else
1757     value.print(os, isSigned);
1758 }
1759 
1760 static void
1761 printDenseElementsAttrImpl(bool isSplat, ShapedType type, raw_ostream &os,
1762                            function_ref<void(unsigned)> printEltFn) {
1763   // Special case for 0-d and splat tensors.
1764   if (isSplat)
1765     return printEltFn(0);
1766 
1767   // Special case for degenerate tensors.
1768   auto numElements = type.getNumElements();
1769   if (numElements == 0)
1770     return;
1771 
1772   // We use a mixed-radix counter to iterate through the shape. When we bump a
1773   // non-least-significant digit, we emit a close bracket. When we next emit an
1774   // element we re-open all closed brackets.
1775 
1776   // The mixed-radix counter, with radices in 'shape'.
1777   int64_t rank = type.getRank();
1778   SmallVector<unsigned, 4> counter(rank, 0);
1779   // The number of brackets that have been opened and not closed.
1780   unsigned openBrackets = 0;
1781 
1782   auto shape = type.getShape();
1783   auto bumpCounter = [&] {
1784     // Bump the least significant digit.
1785     ++counter[rank - 1];
1786     // Iterate backwards bubbling back the increment.
1787     for (unsigned i = rank - 1; i > 0; --i)
1788       if (counter[i] >= shape[i]) {
1789         // Index 'i' is rolled over. Bump (i-1) and close a bracket.
1790         counter[i] = 0;
1791         ++counter[i - 1];
1792         --openBrackets;
1793         os << ']';
1794       }
1795   };
1796 
1797   for (unsigned idx = 0, e = numElements; idx != e; ++idx) {
1798     if (idx != 0)
1799       os << ", ";
1800     while (openBrackets++ < rank)
1801       os << '[';
1802     openBrackets = rank;
1803     printEltFn(idx);
1804     bumpCounter();
1805   }
1806   while (openBrackets-- > 0)
1807     os << ']';
1808 }
1809 
1810 void AsmPrinter::Impl::printDenseElementsAttr(DenseElementsAttr attr,
1811                                               bool allowHex) {
1812   if (auto stringAttr = attr.dyn_cast<DenseStringElementsAttr>())
1813     return printDenseStringElementsAttr(stringAttr);
1814 
1815   printDenseIntOrFPElementsAttr(attr.cast<DenseIntOrFPElementsAttr>(),
1816                                 allowHex);
1817 }
1818 
1819 void AsmPrinter::Impl::printDenseIntOrFPElementsAttr(
1820     DenseIntOrFPElementsAttr attr, bool allowHex) {
1821   auto type = attr.getType();
1822   auto elementType = type.getElementType();
1823 
1824   // Check to see if we should format this attribute as a hex string.
1825   auto numElements = type.getNumElements();
1826   if (!attr.isSplat() && allowHex &&
1827       shouldPrintElementsAttrWithHex(numElements)) {
1828     ArrayRef<char> rawData = attr.getRawData();
1829     if (llvm::support::endian::system_endianness() ==
1830         llvm::support::endianness::big) {
1831       // Convert endianess in big-endian(BE) machines. `rawData` is BE in BE
1832       // machines. It is converted here to print in LE format.
1833       SmallVector<char, 64> outDataVec(rawData.size());
1834       MutableArrayRef<char> convRawData(outDataVec);
1835       DenseIntOrFPElementsAttr::convertEndianOfArrayRefForBEmachine(
1836           rawData, convRawData, type);
1837       os << '"' << "0x"
1838          << llvm::toHex(StringRef(convRawData.data(), convRawData.size()))
1839          << "\"";
1840     } else {
1841       os << '"' << "0x"
1842          << llvm::toHex(StringRef(rawData.data(), rawData.size())) << "\"";
1843     }
1844 
1845     return;
1846   }
1847 
1848   if (ComplexType complexTy = elementType.dyn_cast<ComplexType>()) {
1849     Type complexElementType = complexTy.getElementType();
1850     // Note: The if and else below had a common lambda function which invoked
1851     // printDenseElementsAttrImpl. This lambda was hitting a bug in gcc 9.1,9.2
1852     // and hence was replaced.
1853     if (complexElementType.isa<IntegerType>()) {
1854       bool isSigned = !complexElementType.isUnsignedInteger();
1855       auto valueIt = attr.value_begin<std::complex<APInt>>();
1856       printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
1857         auto complexValue = *(valueIt + index);
1858         os << "(";
1859         printDenseIntElement(complexValue.real(), os, isSigned);
1860         os << ",";
1861         printDenseIntElement(complexValue.imag(), os, isSigned);
1862         os << ")";
1863       });
1864     } else {
1865       auto valueIt = attr.value_begin<std::complex<APFloat>>();
1866       printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
1867         auto complexValue = *(valueIt + index);
1868         os << "(";
1869         printFloatValue(complexValue.real(), os);
1870         os << ",";
1871         printFloatValue(complexValue.imag(), os);
1872         os << ")";
1873       });
1874     }
1875   } else if (elementType.isIntOrIndex()) {
1876     bool isSigned = !elementType.isUnsignedInteger();
1877     auto valueIt = attr.value_begin<APInt>();
1878     printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
1879       printDenseIntElement(*(valueIt + index), os, isSigned);
1880     });
1881   } else {
1882     assert(elementType.isa<FloatType>() && "unexpected element type");
1883     auto valueIt = attr.value_begin<APFloat>();
1884     printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
1885       printFloatValue(*(valueIt + index), os);
1886     });
1887   }
1888 }
1889 
1890 void AsmPrinter::Impl::printDenseStringElementsAttr(
1891     DenseStringElementsAttr attr) {
1892   ArrayRef<StringRef> data = attr.getRawStringData();
1893   auto printFn = [&](unsigned index) {
1894     os << "\"";
1895     printEscapedString(data[index], os);
1896     os << "\"";
1897   };
1898   printDenseElementsAttrImpl(attr.isSplat(), attr.getType(), os, printFn);
1899 }
1900 
1901 void AsmPrinter::Impl::printType(Type type) {
1902   if (!type) {
1903     os << "<<NULL TYPE>>";
1904     return;
1905   }
1906 
1907   // Try to print an alias for this type.
1908   if (state && succeeded(state->getAliasState().getAlias(type, os)))
1909     return;
1910 
1911   TypeSwitch<Type>(type)
1912       .Case<OpaqueType>([&](OpaqueType opaqueTy) {
1913         printDialectSymbol(os, "!", opaqueTy.getDialectNamespace(),
1914                            opaqueTy.getTypeData());
1915       })
1916       .Case<IndexType>([&](Type) { os << "index"; })
1917       .Case<BFloat16Type>([&](Type) { os << "bf16"; })
1918       .Case<Float16Type>([&](Type) { os << "f16"; })
1919       .Case<Float32Type>([&](Type) { os << "f32"; })
1920       .Case<Float64Type>([&](Type) { os << "f64"; })
1921       .Case<Float80Type>([&](Type) { os << "f80"; })
1922       .Case<Float128Type>([&](Type) { os << "f128"; })
1923       .Case<IntegerType>([&](IntegerType integerTy) {
1924         if (integerTy.isSigned())
1925           os << 's';
1926         else if (integerTy.isUnsigned())
1927           os << 'u';
1928         os << 'i' << integerTy.getWidth();
1929       })
1930       .Case<FunctionType>([&](FunctionType funcTy) {
1931         os << '(';
1932         interleaveComma(funcTy.getInputs(), [&](Type ty) { printType(ty); });
1933         os << ") -> ";
1934         ArrayRef<Type> results = funcTy.getResults();
1935         if (results.size() == 1 && !results[0].isa<FunctionType>()) {
1936           printType(results[0]);
1937         } else {
1938           os << '(';
1939           interleaveComma(results, [&](Type ty) { printType(ty); });
1940           os << ')';
1941         }
1942       })
1943       .Case<VectorType>([&](VectorType vectorTy) {
1944         os << "vector<";
1945         auto vShape = vectorTy.getShape();
1946         unsigned lastDim = vShape.size();
1947         unsigned lastFixedDim = lastDim - vectorTy.getNumScalableDims();
1948         unsigned dimIdx = 0;
1949         for (dimIdx = 0; dimIdx < lastFixedDim; dimIdx++)
1950           os << vShape[dimIdx] << 'x';
1951         if (vectorTy.isScalable()) {
1952           os << '[';
1953           unsigned secondToLastDim = lastDim - 1;
1954           for (; dimIdx < secondToLastDim; dimIdx++)
1955             os << vShape[dimIdx] << 'x';
1956           os << vShape[dimIdx] << "]x";
1957         }
1958         printType(vectorTy.getElementType());
1959         os << '>';
1960       })
1961       .Case<RankedTensorType>([&](RankedTensorType tensorTy) {
1962         os << "tensor<";
1963         for (int64_t dim : tensorTy.getShape()) {
1964           if (ShapedType::isDynamic(dim))
1965             os << '?';
1966           else
1967             os << dim;
1968           os << 'x';
1969         }
1970         printType(tensorTy.getElementType());
1971         // Only print the encoding attribute value if set.
1972         if (tensorTy.getEncoding()) {
1973           os << ", ";
1974           printAttribute(tensorTy.getEncoding());
1975         }
1976         os << '>';
1977       })
1978       .Case<UnrankedTensorType>([&](UnrankedTensorType tensorTy) {
1979         os << "tensor<*x";
1980         printType(tensorTy.getElementType());
1981         os << '>';
1982       })
1983       .Case<MemRefType>([&](MemRefType memrefTy) {
1984         os << "memref<";
1985         for (int64_t dim : memrefTy.getShape()) {
1986           if (ShapedType::isDynamic(dim))
1987             os << '?';
1988           else
1989             os << dim;
1990           os << 'x';
1991         }
1992         printType(memrefTy.getElementType());
1993         if (!memrefTy.getLayout().isIdentity()) {
1994           os << ", ";
1995           printAttribute(memrefTy.getLayout(), AttrTypeElision::May);
1996         }
1997         // Only print the memory space if it is the non-default one.
1998         if (memrefTy.getMemorySpace()) {
1999           os << ", ";
2000           printAttribute(memrefTy.getMemorySpace(), AttrTypeElision::May);
2001         }
2002         os << '>';
2003       })
2004       .Case<UnrankedMemRefType>([&](UnrankedMemRefType memrefTy) {
2005         os << "memref<*x";
2006         printType(memrefTy.getElementType());
2007         // Only print the memory space if it is the non-default one.
2008         if (memrefTy.getMemorySpace()) {
2009           os << ", ";
2010           printAttribute(memrefTy.getMemorySpace(), AttrTypeElision::May);
2011         }
2012         os << '>';
2013       })
2014       .Case<ComplexType>([&](ComplexType complexTy) {
2015         os << "complex<";
2016         printType(complexTy.getElementType());
2017         os << '>';
2018       })
2019       .Case<TupleType>([&](TupleType tupleTy) {
2020         os << "tuple<";
2021         interleaveComma(tupleTy.getTypes(),
2022                         [&](Type type) { printType(type); });
2023         os << '>';
2024       })
2025       .Case<NoneType>([&](Type) { os << "none"; })
2026       .Default([&](Type type) { return printDialectType(type); });
2027 }
2028 
2029 void AsmPrinter::Impl::printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
2030                                              ArrayRef<StringRef> elidedAttrs,
2031                                              bool withKeyword) {
2032   // If there are no attributes, then there is nothing to be done.
2033   if (attrs.empty())
2034     return;
2035 
2036   // Functor used to print a filtered attribute list.
2037   auto printFilteredAttributesFn = [&](auto filteredAttrs) {
2038     // Print the 'attributes' keyword if necessary.
2039     if (withKeyword)
2040       os << " attributes";
2041 
2042     // Otherwise, print them all out in braces.
2043     os << " {";
2044     interleaveComma(filteredAttrs,
2045                     [&](NamedAttribute attr) { printNamedAttribute(attr); });
2046     os << '}';
2047   };
2048 
2049   // If no attributes are elided, we can directly print with no filtering.
2050   if (elidedAttrs.empty())
2051     return printFilteredAttributesFn(attrs);
2052 
2053   // Otherwise, filter out any attributes that shouldn't be included.
2054   llvm::SmallDenseSet<StringRef> elidedAttrsSet(elidedAttrs.begin(),
2055                                                 elidedAttrs.end());
2056   auto filteredAttrs = llvm::make_filter_range(attrs, [&](NamedAttribute attr) {
2057     return !elidedAttrsSet.contains(attr.getName().strref());
2058   });
2059   if (!filteredAttrs.empty())
2060     printFilteredAttributesFn(filteredAttrs);
2061 }
2062 
2063 void AsmPrinter::Impl::printNamedAttribute(NamedAttribute attr) {
2064   // Print the name without quotes if possible.
2065   ::printKeywordOrString(attr.getName().strref(), os);
2066 
2067   // Pretty printing elides the attribute value for unit attributes.
2068   if (attr.getValue().isa<UnitAttr>())
2069     return;
2070 
2071   os << " = ";
2072   printAttribute(attr.getValue());
2073 }
2074 
2075 void AsmPrinter::Impl::printDialectAttribute(Attribute attr) {
2076   auto &dialect = attr.getDialect();
2077 
2078   // Ask the dialect to serialize the attribute to a string.
2079   std::string attrName;
2080   {
2081     llvm::raw_string_ostream attrNameStr(attrName);
2082     Impl subPrinter(attrNameStr, printerFlags, state);
2083     DialectAsmPrinter printer(subPrinter);
2084     dialect.printAttribute(attr, printer);
2085   }
2086   printDialectSymbol(os, "#", dialect.getNamespace(), attrName);
2087 }
2088 
2089 void AsmPrinter::Impl::printDialectType(Type type) {
2090   auto &dialect = type.getDialect();
2091 
2092   // Ask the dialect to serialize the type to a string.
2093   std::string typeName;
2094   {
2095     llvm::raw_string_ostream typeNameStr(typeName);
2096     Impl subPrinter(typeNameStr, printerFlags, state);
2097     DialectAsmPrinter printer(subPrinter);
2098     dialect.printType(type, printer);
2099   }
2100   printDialectSymbol(os, "!", dialect.getNamespace(), typeName);
2101 }
2102 
2103 //===--------------------------------------------------------------------===//
2104 // AsmPrinter
2105 //===--------------------------------------------------------------------===//
2106 
2107 AsmPrinter::~AsmPrinter() = default;
2108 
2109 raw_ostream &AsmPrinter::getStream() const {
2110   assert(impl && "expected AsmPrinter::getStream to be overriden");
2111   return impl->getStream();
2112 }
2113 
2114 /// Print the given floating point value in a stablized form.
2115 void AsmPrinter::printFloat(const APFloat &value) {
2116   assert(impl && "expected AsmPrinter::printFloat to be overriden");
2117   printFloatValue(value, impl->getStream());
2118 }
2119 
2120 void AsmPrinter::printType(Type type) {
2121   assert(impl && "expected AsmPrinter::printType to be overriden");
2122   impl->printType(type);
2123 }
2124 
2125 void AsmPrinter::printAttribute(Attribute attr) {
2126   assert(impl && "expected AsmPrinter::printAttribute to be overriden");
2127   impl->printAttribute(attr);
2128 }
2129 
2130 LogicalResult AsmPrinter::printAlias(Attribute attr) {
2131   assert(impl && "expected AsmPrinter::printAlias to be overriden");
2132   return impl->printAlias(attr);
2133 }
2134 
2135 LogicalResult AsmPrinter::printAlias(Type type) {
2136   assert(impl && "expected AsmPrinter::printAlias to be overriden");
2137   return impl->printAlias(type);
2138 }
2139 
2140 void AsmPrinter::printAttributeWithoutType(Attribute attr) {
2141   assert(impl &&
2142          "expected AsmPrinter::printAttributeWithoutType to be overriden");
2143   impl->printAttribute(attr, Impl::AttrTypeElision::Must);
2144 }
2145 
2146 void AsmPrinter::printKeywordOrString(StringRef keyword) {
2147   assert(impl && "expected AsmPrinter::printKeywordOrString to be overriden");
2148   ::printKeywordOrString(keyword, impl->getStream());
2149 }
2150 
2151 void AsmPrinter::printSymbolName(StringRef symbolRef) {
2152   assert(impl && "expected AsmPrinter::printSymbolName to be overriden");
2153   ::printSymbolReference(symbolRef, impl->getStream());
2154 }
2155 
2156 //===----------------------------------------------------------------------===//
2157 // Affine expressions and maps
2158 //===----------------------------------------------------------------------===//
2159 
2160 void AsmPrinter::Impl::printAffineExpr(
2161     AffineExpr expr, function_ref<void(unsigned, bool)> printValueName) {
2162   printAffineExprInternal(expr, BindingStrength::Weak, printValueName);
2163 }
2164 
2165 void AsmPrinter::Impl::printAffineExprInternal(
2166     AffineExpr expr, BindingStrength enclosingTightness,
2167     function_ref<void(unsigned, bool)> printValueName) {
2168   const char *binopSpelling = nullptr;
2169   switch (expr.getKind()) {
2170   case AffineExprKind::SymbolId: {
2171     unsigned pos = expr.cast<AffineSymbolExpr>().getPosition();
2172     if (printValueName)
2173       printValueName(pos, /*isSymbol=*/true);
2174     else
2175       os << 's' << pos;
2176     return;
2177   }
2178   case AffineExprKind::DimId: {
2179     unsigned pos = expr.cast<AffineDimExpr>().getPosition();
2180     if (printValueName)
2181       printValueName(pos, /*isSymbol=*/false);
2182     else
2183       os << 'd' << pos;
2184     return;
2185   }
2186   case AffineExprKind::Constant:
2187     os << expr.cast<AffineConstantExpr>().getValue();
2188     return;
2189   case AffineExprKind::Add:
2190     binopSpelling = " + ";
2191     break;
2192   case AffineExprKind::Mul:
2193     binopSpelling = " * ";
2194     break;
2195   case AffineExprKind::FloorDiv:
2196     binopSpelling = " floordiv ";
2197     break;
2198   case AffineExprKind::CeilDiv:
2199     binopSpelling = " ceildiv ";
2200     break;
2201   case AffineExprKind::Mod:
2202     binopSpelling = " mod ";
2203     break;
2204   }
2205 
2206   auto binOp = expr.cast<AffineBinaryOpExpr>();
2207   AffineExpr lhsExpr = binOp.getLHS();
2208   AffineExpr rhsExpr = binOp.getRHS();
2209 
2210   // Handle tightly binding binary operators.
2211   if (binOp.getKind() != AffineExprKind::Add) {
2212     if (enclosingTightness == BindingStrength::Strong)
2213       os << '(';
2214 
2215     // Pretty print multiplication with -1.
2216     auto rhsConst = rhsExpr.dyn_cast<AffineConstantExpr>();
2217     if (rhsConst && binOp.getKind() == AffineExprKind::Mul &&
2218         rhsConst.getValue() == -1) {
2219       os << "-";
2220       printAffineExprInternal(lhsExpr, BindingStrength::Strong, printValueName);
2221       if (enclosingTightness == BindingStrength::Strong)
2222         os << ')';
2223       return;
2224     }
2225 
2226     printAffineExprInternal(lhsExpr, BindingStrength::Strong, printValueName);
2227 
2228     os << binopSpelling;
2229     printAffineExprInternal(rhsExpr, BindingStrength::Strong, printValueName);
2230 
2231     if (enclosingTightness == BindingStrength::Strong)
2232       os << ')';
2233     return;
2234   }
2235 
2236   // Print out special "pretty" forms for add.
2237   if (enclosingTightness == BindingStrength::Strong)
2238     os << '(';
2239 
2240   // Pretty print addition to a product that has a negative operand as a
2241   // subtraction.
2242   if (auto rhs = rhsExpr.dyn_cast<AffineBinaryOpExpr>()) {
2243     if (rhs.getKind() == AffineExprKind::Mul) {
2244       AffineExpr rrhsExpr = rhs.getRHS();
2245       if (auto rrhs = rrhsExpr.dyn_cast<AffineConstantExpr>()) {
2246         if (rrhs.getValue() == -1) {
2247           printAffineExprInternal(lhsExpr, BindingStrength::Weak,
2248                                   printValueName);
2249           os << " - ";
2250           if (rhs.getLHS().getKind() == AffineExprKind::Add) {
2251             printAffineExprInternal(rhs.getLHS(), BindingStrength::Strong,
2252                                     printValueName);
2253           } else {
2254             printAffineExprInternal(rhs.getLHS(), BindingStrength::Weak,
2255                                     printValueName);
2256           }
2257 
2258           if (enclosingTightness == BindingStrength::Strong)
2259             os << ')';
2260           return;
2261         }
2262 
2263         if (rrhs.getValue() < -1) {
2264           printAffineExprInternal(lhsExpr, BindingStrength::Weak,
2265                                   printValueName);
2266           os << " - ";
2267           printAffineExprInternal(rhs.getLHS(), BindingStrength::Strong,
2268                                   printValueName);
2269           os << " * " << -rrhs.getValue();
2270           if (enclosingTightness == BindingStrength::Strong)
2271             os << ')';
2272           return;
2273         }
2274       }
2275     }
2276   }
2277 
2278   // Pretty print addition to a negative number as a subtraction.
2279   if (auto rhsConst = rhsExpr.dyn_cast<AffineConstantExpr>()) {
2280     if (rhsConst.getValue() < 0) {
2281       printAffineExprInternal(lhsExpr, BindingStrength::Weak, printValueName);
2282       os << " - " << -rhsConst.getValue();
2283       if (enclosingTightness == BindingStrength::Strong)
2284         os << ')';
2285       return;
2286     }
2287   }
2288 
2289   printAffineExprInternal(lhsExpr, BindingStrength::Weak, printValueName);
2290 
2291   os << " + ";
2292   printAffineExprInternal(rhsExpr, BindingStrength::Weak, printValueName);
2293 
2294   if (enclosingTightness == BindingStrength::Strong)
2295     os << ')';
2296 }
2297 
2298 void AsmPrinter::Impl::printAffineConstraint(AffineExpr expr, bool isEq) {
2299   printAffineExprInternal(expr, BindingStrength::Weak);
2300   isEq ? os << " == 0" : os << " >= 0";
2301 }
2302 
2303 void AsmPrinter::Impl::printAffineMap(AffineMap map) {
2304   // Dimension identifiers.
2305   os << '(';
2306   for (int i = 0; i < (int)map.getNumDims() - 1; ++i)
2307     os << 'd' << i << ", ";
2308   if (map.getNumDims() >= 1)
2309     os << 'd' << map.getNumDims() - 1;
2310   os << ')';
2311 
2312   // Symbolic identifiers.
2313   if (map.getNumSymbols() != 0) {
2314     os << '[';
2315     for (unsigned i = 0; i < map.getNumSymbols() - 1; ++i)
2316       os << 's' << i << ", ";
2317     if (map.getNumSymbols() >= 1)
2318       os << 's' << map.getNumSymbols() - 1;
2319     os << ']';
2320   }
2321 
2322   // Result affine expressions.
2323   os << " -> (";
2324   interleaveComma(map.getResults(),
2325                   [&](AffineExpr expr) { printAffineExpr(expr); });
2326   os << ')';
2327 }
2328 
2329 void AsmPrinter::Impl::printIntegerSet(IntegerSet set) {
2330   // Dimension identifiers.
2331   os << '(';
2332   for (unsigned i = 1; i < set.getNumDims(); ++i)
2333     os << 'd' << i - 1 << ", ";
2334   if (set.getNumDims() >= 1)
2335     os << 'd' << set.getNumDims() - 1;
2336   os << ')';
2337 
2338   // Symbolic identifiers.
2339   if (set.getNumSymbols() != 0) {
2340     os << '[';
2341     for (unsigned i = 0; i < set.getNumSymbols() - 1; ++i)
2342       os << 's' << i << ", ";
2343     if (set.getNumSymbols() >= 1)
2344       os << 's' << set.getNumSymbols() - 1;
2345     os << ']';
2346   }
2347 
2348   // Print constraints.
2349   os << " : (";
2350   int numConstraints = set.getNumConstraints();
2351   for (int i = 1; i < numConstraints; ++i) {
2352     printAffineConstraint(set.getConstraint(i - 1), set.isEq(i - 1));
2353     os << ", ";
2354   }
2355   if (numConstraints >= 1)
2356     printAffineConstraint(set.getConstraint(numConstraints - 1),
2357                           set.isEq(numConstraints - 1));
2358   os << ')';
2359 }
2360 
2361 //===----------------------------------------------------------------------===//
2362 // OperationPrinter
2363 //===----------------------------------------------------------------------===//
2364 
2365 namespace {
2366 /// This class contains the logic for printing operations, regions, and blocks.
2367 class OperationPrinter : public AsmPrinter::Impl, private OpAsmPrinter {
2368 public:
2369   using Impl = AsmPrinter::Impl;
2370   using Impl::printType;
2371 
2372   explicit OperationPrinter(raw_ostream &os, OpPrintingFlags flags,
2373                             AsmStateImpl &state)
2374       : Impl(os, flags, &state), OpAsmPrinter(static_cast<Impl &>(*this)) {}
2375 
2376   /// Print the given top-level operation.
2377   void printTopLevelOperation(Operation *op);
2378 
2379   /// Print the given operation with its indent and location.
2380   void print(Operation *op);
2381   /// Print the bare location, not including indentation/location/etc.
2382   void printOperation(Operation *op);
2383   /// Print the given operation in the generic form.
2384   void printGenericOp(Operation *op, bool printOpName) override;
2385 
2386   /// Print the name of the given block.
2387   void printBlockName(Block *block);
2388 
2389   /// Print the given block. If 'printBlockArgs' is false, the arguments of the
2390   /// block are not printed. If 'printBlockTerminator' is false, the terminator
2391   /// operation of the block is not printed.
2392   void print(Block *block, bool printBlockArgs = true,
2393              bool printBlockTerminator = true);
2394 
2395   /// Print the ID of the given value, optionally with its result number.
2396   void printValueID(Value value, bool printResultNo = true,
2397                     raw_ostream *streamOverride = nullptr) const;
2398 
2399   //===--------------------------------------------------------------------===//
2400   // OpAsmPrinter methods
2401   //===--------------------------------------------------------------------===//
2402 
2403   /// Print a newline and indent the printer to the start of the current
2404   /// operation.
2405   void printNewline() override {
2406     os << newLine;
2407     os.indent(currentIndent);
2408   }
2409 
2410   /// Print a block argument in the usual format of:
2411   ///   %ssaName : type {attr1=42} loc("here")
2412   /// where location printing is controlled by the standard internal option.
2413   /// You may pass omitType=true to not print a type, and pass an empty
2414   /// attribute list if you don't care for attributes.
2415   void printRegionArgument(BlockArgument arg,
2416                            ArrayRef<NamedAttribute> argAttrs = {},
2417                            bool omitType = false) override;
2418 
2419   /// Print the ID for the given value.
2420   void printOperand(Value value) override { printValueID(value); }
2421   void printOperand(Value value, raw_ostream &os) override {
2422     printValueID(value, /*printResultNo=*/true, &os);
2423   }
2424 
2425   /// Print an optional attribute dictionary with a given set of elided values.
2426   void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
2427                              ArrayRef<StringRef> elidedAttrs = {}) override {
2428     Impl::printOptionalAttrDict(attrs, elidedAttrs);
2429   }
2430   void printOptionalAttrDictWithKeyword(
2431       ArrayRef<NamedAttribute> attrs,
2432       ArrayRef<StringRef> elidedAttrs = {}) override {
2433     Impl::printOptionalAttrDict(attrs, elidedAttrs,
2434                                 /*withKeyword=*/true);
2435   }
2436 
2437   /// Print the given successor.
2438   void printSuccessor(Block *successor) override;
2439 
2440   /// Print an operation successor with the operands used for the block
2441   /// arguments.
2442   void printSuccessorAndUseList(Block *successor,
2443                                 ValueRange succOperands) override;
2444 
2445   /// Print the given region.
2446   void printRegion(Region &region, bool printEntryBlockArgs,
2447                    bool printBlockTerminators, bool printEmptyBlock) override;
2448 
2449   /// Renumber the arguments for the specified region to the same names as the
2450   /// SSA values in namesToUse. This may only be used for IsolatedFromAbove
2451   /// operations. If any entry in namesToUse is null, the corresponding
2452   /// argument name is left alone.
2453   void shadowRegionArgs(Region &region, ValueRange namesToUse) override {
2454     state->getSSANameState().shadowRegionArgs(region, namesToUse);
2455   }
2456 
2457   /// Print the given affine map with the symbol and dimension operands printed
2458   /// inline with the map.
2459   void printAffineMapOfSSAIds(AffineMapAttr mapAttr,
2460                               ValueRange operands) override;
2461 
2462   /// Print the given affine expression with the symbol and dimension operands
2463   /// printed inline with the expression.
2464   void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands,
2465                                ValueRange symOperands) override;
2466 
2467 private:
2468   // Contains the stack of default dialects to use when printing regions.
2469   // A new dialect is pushed to the stack before parsing regions nested under an
2470   // operation implementing `OpAsmOpInterface`, and popped when done. At the
2471   // top-level we start with "builtin" as the default, so that the top-level
2472   // `module` operation prints as-is.
2473   SmallVector<StringRef> defaultDialectStack{"builtin"};
2474 
2475   /// The number of spaces used for indenting nested operations.
2476   const static unsigned indentWidth = 2;
2477 
2478   // This is the current indentation level for nested structures.
2479   unsigned currentIndent = 0;
2480 };
2481 } // namespace
2482 
2483 void OperationPrinter::printTopLevelOperation(Operation *op) {
2484   // Output the aliases at the top level that can't be deferred.
2485   state->getAliasState().printNonDeferredAliases(os, newLine);
2486 
2487   // Print the module.
2488   print(op);
2489   os << newLine;
2490 
2491   // Output the aliases at the top level that can be deferred.
2492   state->getAliasState().printDeferredAliases(os, newLine);
2493 }
2494 
2495 /// Print a block argument in the usual format of:
2496 ///   %ssaName : type {attr1=42} loc("here")
2497 /// where location printing is controlled by the standard internal option.
2498 /// You may pass omitType=true to not print a type, and pass an empty
2499 /// attribute list if you don't care for attributes.
2500 void OperationPrinter::printRegionArgument(BlockArgument arg,
2501                                            ArrayRef<NamedAttribute> argAttrs,
2502                                            bool omitType) {
2503   printOperand(arg);
2504   if (!omitType) {
2505     os << ": ";
2506     printType(arg.getType());
2507   }
2508   printOptionalAttrDict(argAttrs);
2509   // TODO: We should allow location aliases on block arguments.
2510   printTrailingLocation(arg.getLoc(), /*allowAlias*/ false);
2511 }
2512 
2513 void OperationPrinter::print(Operation *op) {
2514   // Track the location of this operation.
2515   state->registerOperationLocation(op, newLine.curLine, currentIndent);
2516 
2517   os.indent(currentIndent);
2518   printOperation(op);
2519   printTrailingLocation(op->getLoc());
2520 }
2521 
2522 void OperationPrinter::printOperation(Operation *op) {
2523   if (size_t numResults = op->getNumResults()) {
2524     auto printResultGroup = [&](size_t resultNo, size_t resultCount) {
2525       printValueID(op->getResult(resultNo), /*printResultNo=*/false);
2526       if (resultCount > 1)
2527         os << ':' << resultCount;
2528     };
2529 
2530     // Check to see if this operation has multiple result groups.
2531     ArrayRef<int> resultGroups = state->getSSANameState().getOpResultGroups(op);
2532     if (!resultGroups.empty()) {
2533       // Interleave the groups excluding the last one, this one will be handled
2534       // separately.
2535       interleaveComma(llvm::seq<int>(0, resultGroups.size() - 1), [&](int i) {
2536         printResultGroup(resultGroups[i],
2537                          resultGroups[i + 1] - resultGroups[i]);
2538       });
2539       os << ", ";
2540       printResultGroup(resultGroups.back(), numResults - resultGroups.back());
2541 
2542     } else {
2543       printResultGroup(/*resultNo=*/0, /*resultCount=*/numResults);
2544     }
2545 
2546     os << " = ";
2547   }
2548 
2549   // If requested, always print the generic form.
2550   if (!printerFlags.shouldPrintGenericOpForm()) {
2551     // Check to see if this is a known operation. If so, use the registered
2552     // custom printer hook.
2553     if (auto opInfo = op->getRegisteredInfo()) {
2554       opInfo->printAssembly(op, *this, defaultDialectStack.back());
2555       return;
2556     }
2557     // Otherwise try to dispatch to the dialect, if available.
2558     if (Dialect *dialect = op->getDialect()) {
2559       if (auto opPrinter = dialect->getOperationPrinter(op)) {
2560         // Print the op name first.
2561         StringRef name = op->getName().getStringRef();
2562         name.consume_front((defaultDialectStack.back() + ".").str());
2563         printEscapedString(name, os);
2564         // Print the rest of the op now.
2565         opPrinter(op, *this);
2566         return;
2567       }
2568     }
2569   }
2570 
2571   // Otherwise print with the generic assembly form.
2572   printGenericOp(op, /*printOpName=*/true);
2573 }
2574 
2575 void OperationPrinter::printGenericOp(Operation *op, bool printOpName) {
2576   if (printOpName) {
2577     os << '"';
2578     printEscapedString(op->getName().getStringRef(), os);
2579     os << '"';
2580   }
2581   os << '(';
2582   interleaveComma(op->getOperands(), [&](Value value) { printValueID(value); });
2583   os << ')';
2584 
2585   // For terminators, print the list of successors and their operands.
2586   if (op->getNumSuccessors() != 0) {
2587     os << '[';
2588     interleaveComma(op->getSuccessors(),
2589                     [&](Block *successor) { printBlockName(successor); });
2590     os << ']';
2591   }
2592 
2593   // Print regions.
2594   if (op->getNumRegions() != 0) {
2595     os << " (";
2596     interleaveComma(op->getRegions(), [&](Region &region) {
2597       printRegion(region, /*printEntryBlockArgs=*/true,
2598                   /*printBlockTerminators=*/true, /*printEmptyBlock=*/true);
2599     });
2600     os << ')';
2601   }
2602 
2603   auto attrs = op->getAttrs();
2604   printOptionalAttrDict(attrs);
2605 
2606   // Print the type signature of the operation.
2607   os << " : ";
2608   printFunctionalType(op);
2609 }
2610 
2611 void OperationPrinter::printBlockName(Block *block) {
2612   auto id = state->getSSANameState().getBlockID(block);
2613   if (id != SSANameState::NameSentinel)
2614     os << "^bb" << id;
2615   else
2616     os << "^INVALIDBLOCK";
2617 }
2618 
2619 void OperationPrinter::print(Block *block, bool printBlockArgs,
2620                              bool printBlockTerminator) {
2621   // Print the block label and argument list if requested.
2622   if (printBlockArgs) {
2623     os.indent(currentIndent);
2624     printBlockName(block);
2625 
2626     // Print the argument list if non-empty.
2627     if (!block->args_empty()) {
2628       os << '(';
2629       interleaveComma(block->getArguments(), [&](BlockArgument arg) {
2630         printValueID(arg);
2631         os << ": ";
2632         printType(arg.getType());
2633         // TODO: We should allow location aliases on block arguments.
2634         printTrailingLocation(arg.getLoc(), /*allowAlias*/ false);
2635       });
2636       os << ')';
2637     }
2638     os << ':';
2639 
2640     // Print out some context information about the predecessors of this block.
2641     if (!block->getParent()) {
2642       os << "  // block is not in a region!";
2643     } else if (block->hasNoPredecessors()) {
2644       if (!block->isEntryBlock())
2645         os << "  // no predecessors";
2646     } else if (auto *pred = block->getSinglePredecessor()) {
2647       os << "  // pred: ";
2648       printBlockName(pred);
2649     } else {
2650       // We want to print the predecessors in increasing numeric order, not in
2651       // whatever order the use-list is in, so gather and sort them.
2652       SmallVector<std::pair<unsigned, Block *>, 4> predIDs;
2653       for (auto *pred : block->getPredecessors())
2654         predIDs.push_back({state->getSSANameState().getBlockID(pred), pred});
2655       llvm::array_pod_sort(predIDs.begin(), predIDs.end());
2656 
2657       os << "  // " << predIDs.size() << " preds: ";
2658 
2659       interleaveComma(predIDs, [&](std::pair<unsigned, Block *> pred) {
2660         printBlockName(pred.second);
2661       });
2662     }
2663     os << newLine;
2664   }
2665 
2666   currentIndent += indentWidth;
2667   bool hasTerminator =
2668       !block->empty() && block->back().hasTrait<OpTrait::IsTerminator>();
2669   auto range = llvm::make_range(
2670       block->begin(),
2671       std::prev(block->end(),
2672                 (!hasTerminator || printBlockTerminator) ? 0 : 1));
2673   for (auto &op : range) {
2674     print(&op);
2675     os << newLine;
2676   }
2677   currentIndent -= indentWidth;
2678 }
2679 
2680 void OperationPrinter::printValueID(Value value, bool printResultNo,
2681                                     raw_ostream *streamOverride) const {
2682   state->getSSANameState().printValueID(value, printResultNo,
2683                                         streamOverride ? *streamOverride : os);
2684 }
2685 
2686 void OperationPrinter::printSuccessor(Block *successor) {
2687   printBlockName(successor);
2688 }
2689 
2690 void OperationPrinter::printSuccessorAndUseList(Block *successor,
2691                                                 ValueRange succOperands) {
2692   printBlockName(successor);
2693   if (succOperands.empty())
2694     return;
2695 
2696   os << '(';
2697   interleaveComma(succOperands,
2698                   [this](Value operand) { printValueID(operand); });
2699   os << " : ";
2700   interleaveComma(succOperands,
2701                   [this](Value operand) { printType(operand.getType()); });
2702   os << ')';
2703 }
2704 
2705 void OperationPrinter::printRegion(Region &region, bool printEntryBlockArgs,
2706                                    bool printBlockTerminators,
2707                                    bool printEmptyBlock) {
2708   os << "{" << newLine;
2709   if (!region.empty()) {
2710     auto restoreDefaultDialect =
2711         llvm::make_scope_exit([&]() { defaultDialectStack.pop_back(); });
2712     if (auto iface = dyn_cast<OpAsmOpInterface>(region.getParentOp()))
2713       defaultDialectStack.push_back(iface.getDefaultDialect());
2714     else
2715       defaultDialectStack.push_back("");
2716 
2717     auto *entryBlock = &region.front();
2718     // Force printing the block header if printEmptyBlock is set and the block
2719     // is empty or if printEntryBlockArgs is set and there are arguments to
2720     // print.
2721     bool shouldAlwaysPrintBlockHeader =
2722         (printEmptyBlock && entryBlock->empty()) ||
2723         (printEntryBlockArgs && entryBlock->getNumArguments() != 0);
2724     print(entryBlock, shouldAlwaysPrintBlockHeader, printBlockTerminators);
2725     for (auto &b : llvm::drop_begin(region.getBlocks(), 1))
2726       print(&b);
2727   }
2728   os.indent(currentIndent) << "}";
2729 }
2730 
2731 void OperationPrinter::printAffineMapOfSSAIds(AffineMapAttr mapAttr,
2732                                               ValueRange operands) {
2733   AffineMap map = mapAttr.getValue();
2734   unsigned numDims = map.getNumDims();
2735   auto printValueName = [&](unsigned pos, bool isSymbol) {
2736     unsigned index = isSymbol ? numDims + pos : pos;
2737     assert(index < operands.size());
2738     if (isSymbol)
2739       os << "symbol(";
2740     printValueID(operands[index]);
2741     if (isSymbol)
2742       os << ')';
2743   };
2744 
2745   interleaveComma(map.getResults(), [&](AffineExpr expr) {
2746     printAffineExpr(expr, printValueName);
2747   });
2748 }
2749 
2750 void OperationPrinter::printAffineExprOfSSAIds(AffineExpr expr,
2751                                                ValueRange dimOperands,
2752                                                ValueRange symOperands) {
2753   auto printValueName = [&](unsigned pos, bool isSymbol) {
2754     if (!isSymbol)
2755       return printValueID(dimOperands[pos]);
2756     os << "symbol(";
2757     printValueID(symOperands[pos]);
2758     os << ')';
2759   };
2760   printAffineExpr(expr, printValueName);
2761 }
2762 
2763 //===----------------------------------------------------------------------===//
2764 // print and dump methods
2765 //===----------------------------------------------------------------------===//
2766 
2767 void Attribute::print(raw_ostream &os) const {
2768   AsmPrinter::Impl(os).printAttribute(*this);
2769 }
2770 
2771 void Attribute::dump() const {
2772   print(llvm::errs());
2773   llvm::errs() << "\n";
2774 }
2775 
2776 void Type::print(raw_ostream &os) const {
2777   AsmPrinter::Impl(os).printType(*this);
2778 }
2779 
2780 void Type::dump() const { print(llvm::errs()); }
2781 
2782 void AffineMap::dump() const {
2783   print(llvm::errs());
2784   llvm::errs() << "\n";
2785 }
2786 
2787 void IntegerSet::dump() const {
2788   print(llvm::errs());
2789   llvm::errs() << "\n";
2790 }
2791 
2792 void AffineExpr::print(raw_ostream &os) const {
2793   if (!expr) {
2794     os << "<<NULL AFFINE EXPR>>";
2795     return;
2796   }
2797   AsmPrinter::Impl(os).printAffineExpr(*this);
2798 }
2799 
2800 void AffineExpr::dump() const {
2801   print(llvm::errs());
2802   llvm::errs() << "\n";
2803 }
2804 
2805 void AffineMap::print(raw_ostream &os) const {
2806   if (!map) {
2807     os << "<<NULL AFFINE MAP>>";
2808     return;
2809   }
2810   AsmPrinter::Impl(os).printAffineMap(*this);
2811 }
2812 
2813 void IntegerSet::print(raw_ostream &os) const {
2814   AsmPrinter::Impl(os).printIntegerSet(*this);
2815 }
2816 
2817 void Value::print(raw_ostream &os) {
2818   if (!impl) {
2819     os << "<<NULL VALUE>>";
2820     return;
2821   }
2822 
2823   if (auto *op = getDefiningOp())
2824     return op->print(os);
2825   // TODO: Improve BlockArgument print'ing.
2826   BlockArgument arg = this->cast<BlockArgument>();
2827   os << "<block argument> of type '" << arg.getType()
2828      << "' at index: " << arg.getArgNumber();
2829 }
2830 void Value::print(raw_ostream &os, AsmState &state) {
2831   if (!impl) {
2832     os << "<<NULL VALUE>>";
2833     return;
2834   }
2835 
2836   if (auto *op = getDefiningOp())
2837     return op->print(os, state);
2838 
2839   // TODO: Improve BlockArgument print'ing.
2840   BlockArgument arg = this->cast<BlockArgument>();
2841   os << "<block argument> of type '" << arg.getType()
2842      << "' at index: " << arg.getArgNumber();
2843 }
2844 
2845 void Value::dump() {
2846   print(llvm::errs());
2847   llvm::errs() << "\n";
2848 }
2849 
2850 void Value::printAsOperand(raw_ostream &os, AsmState &state) {
2851   // TODO: This doesn't necessarily capture all potential cases.
2852   // Currently, region arguments can be shadowed when printing the main
2853   // operation. If the IR hasn't been printed, this will produce the old SSA
2854   // name and not the shadowed name.
2855   state.getImpl().getSSANameState().printValueID(*this, /*printResultNo=*/true,
2856                                                  os);
2857 }
2858 
2859 void Operation::print(raw_ostream &os, const OpPrintingFlags &printerFlags) {
2860   // If this is a top level operation, we also print aliases.
2861   if (!getParent() && !printerFlags.shouldUseLocalScope()) {
2862     AsmState state(this, printerFlags);
2863     state.getImpl().initializeAliases(this);
2864     print(os, state, printerFlags);
2865     return;
2866   }
2867 
2868   // Find the operation to number from based upon the provided flags.
2869   Operation *op = this;
2870   bool shouldUseLocalScope = printerFlags.shouldUseLocalScope();
2871   do {
2872     // If we are printing local scope, stop at the first operation that is
2873     // isolated from above.
2874     if (shouldUseLocalScope && op->hasTrait<OpTrait::IsIsolatedFromAbove>())
2875       break;
2876 
2877     // Otherwise, traverse up to the next parent.
2878     Operation *parentOp = op->getParentOp();
2879     if (!parentOp)
2880       break;
2881     op = parentOp;
2882   } while (true);
2883 
2884   AsmState state(op, printerFlags);
2885   print(os, state, printerFlags);
2886 }
2887 void Operation::print(raw_ostream &os, AsmState &state,
2888                       const OpPrintingFlags &flags) {
2889   OperationPrinter printer(os, flags, state.getImpl());
2890   if (!getParent() && !flags.shouldUseLocalScope())
2891     printer.printTopLevelOperation(this);
2892   else
2893     printer.print(this);
2894 }
2895 
2896 void Operation::dump() {
2897   print(llvm::errs(), OpPrintingFlags().useLocalScope());
2898   llvm::errs() << "\n";
2899 }
2900 
2901 void Block::print(raw_ostream &os) {
2902   Operation *parentOp = getParentOp();
2903   if (!parentOp) {
2904     os << "<<UNLINKED BLOCK>>\n";
2905     return;
2906   }
2907   // Get the top-level op.
2908   while (auto *nextOp = parentOp->getParentOp())
2909     parentOp = nextOp;
2910 
2911   AsmState state(parentOp);
2912   print(os, state);
2913 }
2914 void Block::print(raw_ostream &os, AsmState &state) {
2915   OperationPrinter(os, /*flags=*/llvm::None, state.getImpl()).print(this);
2916 }
2917 
2918 void Block::dump() { print(llvm::errs()); }
2919 
2920 /// Print out the name of the block without printing its body.
2921 void Block::printAsOperand(raw_ostream &os, bool printType) {
2922   Operation *parentOp = getParentOp();
2923   if (!parentOp) {
2924     os << "<<UNLINKED BLOCK>>\n";
2925     return;
2926   }
2927   AsmState state(parentOp);
2928   printAsOperand(os, state);
2929 }
2930 void Block::printAsOperand(raw_ostream &os, AsmState &state) {
2931   OperationPrinter printer(os, /*flags=*/llvm::None, state.getImpl());
2932   printer.printBlockName(this);
2933 }
2934