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