-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
AsmPrinter.cpp
3709 lines (3194 loc) · 129 KB
/
AsmPrinter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- AsmPrinter.cpp - MLIR Assembly Printer Implementation --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the MLIR AsmPrinter class, which is used to implement
// the various print() methods on the core IR objects.
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinDialect.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/DialectResourceBlobManager.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/SubElementInterfaces.h"
#include "mlir/IR/Verifier.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/Threading.h"
#include <tuple>
using namespace mlir;
using namespace mlir::detail;
#define DEBUG_TYPE "mlir-asm-printer"
void OperationName::print(raw_ostream &os) const { os << getStringRef(); }
void OperationName::dump() const { print(llvm::errs()); }
//===--------------------------------------------------------------------===//
// AsmParser
//===--------------------------------------------------------------------===//
AsmParser::~AsmParser() = default;
DialectAsmParser::~DialectAsmParser() = default;
OpAsmParser::~OpAsmParser() = default;
MLIRContext *AsmParser::getContext() const { return getBuilder().getContext(); }
//===----------------------------------------------------------------------===//
// DialectAsmPrinter
//===----------------------------------------------------------------------===//
DialectAsmPrinter::~DialectAsmPrinter() = default;
//===----------------------------------------------------------------------===//
// OpAsmPrinter
//===----------------------------------------------------------------------===//
OpAsmPrinter::~OpAsmPrinter() = default;
void OpAsmPrinter::printFunctionalType(Operation *op) {
auto &os = getStream();
os << '(';
llvm::interleaveComma(op->getOperands(), os, [&](Value operand) {
// Print the types of null values as <<NULL TYPE>>.
*this << (operand ? operand.getType() : Type());
});
os << ") -> ";
// Print the result list. We don't parenthesize single result types unless
// it is a function (avoiding a grammar ambiguity).
bool wrapped = op->getNumResults() != 1;
if (!wrapped && op->getResult(0).getType() &&
op->getResult(0).getType().isa<FunctionType>())
wrapped = true;
if (wrapped)
os << '(';
llvm::interleaveComma(op->getResults(), os, [&](const OpResult &result) {
// Print the types of null values as <<NULL TYPE>>.
*this << (result ? result.getType() : Type());
});
if (wrapped)
os << ')';
}
//===----------------------------------------------------------------------===//
// Operation OpAsm interface.
//===----------------------------------------------------------------------===//
/// The OpAsmOpInterface, see OpAsmInterface.td for more details.
#include "mlir/IR/OpAsmInterface.cpp.inc"
LogicalResult
OpAsmDialectInterface::parseResource(AsmParsedResourceEntry &entry) const {
return entry.emitError() << "unknown 'resource' key '" << entry.getKey()
<< "' for dialect '" << getDialect()->getNamespace()
<< "'";
}
//===----------------------------------------------------------------------===//
// OpPrintingFlags
//===----------------------------------------------------------------------===//
namespace {
/// This struct contains command line options that can be used to initialize
/// various bits of the AsmPrinter. This uses a struct wrapper to avoid the need
/// for global command line options.
struct AsmPrinterOptions {
llvm::cl::opt<int64_t> printElementsAttrWithHexIfLarger{
"mlir-print-elementsattrs-with-hex-if-larger",
llvm::cl::desc(
"Print DenseElementsAttrs with a hex string that have "
"more elements than the given upper limit (use -1 to disable)")};
llvm::cl::opt<unsigned> elideElementsAttrIfLarger{
"mlir-elide-elementsattrs-if-larger",
llvm::cl::desc("Elide ElementsAttrs with \"...\" that have "
"more elements than the given upper limit")};
llvm::cl::opt<bool> printDebugInfoOpt{
"mlir-print-debuginfo", llvm::cl::init(false),
llvm::cl::desc("Print debug info in MLIR output")};
llvm::cl::opt<bool> printPrettyDebugInfoOpt{
"mlir-pretty-debuginfo", llvm::cl::init(false),
llvm::cl::desc("Print pretty debug info in MLIR output")};
// Use the generic op output form in the operation printer even if the custom
// form is defined.
llvm::cl::opt<bool> printGenericOpFormOpt{
"mlir-print-op-generic", llvm::cl::init(false),
llvm::cl::desc("Print the generic op form"), llvm::cl::Hidden};
llvm::cl::opt<bool> assumeVerifiedOpt{
"mlir-print-assume-verified", llvm::cl::init(false),
llvm::cl::desc("Skip op verification when using custom printers"),
llvm::cl::Hidden};
llvm::cl::opt<bool> printLocalScopeOpt{
"mlir-print-local-scope", llvm::cl::init(false),
llvm::cl::desc("Print with local scope and inline information (eliding "
"aliases for attributes, types, and locations")};
llvm::cl::opt<bool> printValueUsers{
"mlir-print-value-users", llvm::cl::init(false),
llvm::cl::desc(
"Print users of operation results and block arguments as a comment")};
};
} // namespace
static llvm::ManagedStatic<AsmPrinterOptions> clOptions;
/// Register a set of useful command-line options that can be used to configure
/// various flags within the AsmPrinter.
void mlir::registerAsmPrinterCLOptions() {
// Make sure that the options struct has been initialized.
*clOptions;
}
/// Initialize the printing flags with default supplied by the cl::opts above.
OpPrintingFlags::OpPrintingFlags()
: printDebugInfoFlag(false), printDebugInfoPrettyFormFlag(false),
printGenericOpFormFlag(false), assumeVerifiedFlag(false),
printLocalScope(false), printValueUsersFlag(false) {
// Initialize based upon command line options, if they are available.
if (!clOptions.isConstructed())
return;
if (clOptions->elideElementsAttrIfLarger.getNumOccurrences())
elementsAttrElementLimit = clOptions->elideElementsAttrIfLarger;
printDebugInfoFlag = clOptions->printDebugInfoOpt;
printDebugInfoPrettyFormFlag = clOptions->printPrettyDebugInfoOpt;
printGenericOpFormFlag = clOptions->printGenericOpFormOpt;
assumeVerifiedFlag = clOptions->assumeVerifiedOpt;
printLocalScope = clOptions->printLocalScopeOpt;
printValueUsersFlag = clOptions->printValueUsers;
}
/// Enable the elision of large elements attributes, by printing a '...'
/// instead of the element data, when the number of elements is greater than
/// `largeElementLimit`. Note: The IR generated with this option is not
/// parsable.
OpPrintingFlags &
OpPrintingFlags::elideLargeElementsAttrs(int64_t largeElementLimit) {
elementsAttrElementLimit = largeElementLimit;
return *this;
}
/// Enable printing of debug information. If 'prettyForm' is set to true,
/// debug information is printed in a more readable 'pretty' form.
OpPrintingFlags &OpPrintingFlags::enableDebugInfo(bool enable,
bool prettyForm) {
printDebugInfoFlag = enable;
printDebugInfoPrettyFormFlag = prettyForm;
return *this;
}
/// Always print operations in the generic form.
OpPrintingFlags &OpPrintingFlags::printGenericOpForm() {
printGenericOpFormFlag = true;
return *this;
}
/// Do not verify the operation when using custom operation printers.
OpPrintingFlags &OpPrintingFlags::assumeVerified() {
assumeVerifiedFlag = true;
return *this;
}
/// Use local scope when printing the operation. This allows for using the
/// printer in a more localized and thread-safe setting, but may not necessarily
/// be identical of what the IR will look like when dumping the full module.
OpPrintingFlags &OpPrintingFlags::useLocalScope() {
printLocalScope = true;
return *this;
}
/// Print users of values as comments.
OpPrintingFlags &OpPrintingFlags::printValueUsers() {
printValueUsersFlag = true;
return *this;
}
/// Return if the given ElementsAttr should be elided.
bool OpPrintingFlags::shouldElideElementsAttr(ElementsAttr attr) const {
return elementsAttrElementLimit &&
*elementsAttrElementLimit < int64_t(attr.getNumElements()) &&
!attr.isa<SplatElementsAttr>();
}
/// Return the size limit for printing large ElementsAttr.
Optional<int64_t> OpPrintingFlags::getLargeElementsAttrLimit() const {
return elementsAttrElementLimit;
}
/// Return if debug information should be printed.
bool OpPrintingFlags::shouldPrintDebugInfo() const {
return printDebugInfoFlag;
}
/// Return if debug information should be printed in the pretty form.
bool OpPrintingFlags::shouldPrintDebugInfoPrettyForm() const {
return printDebugInfoPrettyFormFlag;
}
/// Return if operations should be printed in the generic form.
bool OpPrintingFlags::shouldPrintGenericOpForm() const {
return printGenericOpFormFlag;
}
/// Return if operation verification should be skipped.
bool OpPrintingFlags::shouldAssumeVerified() const {
return assumeVerifiedFlag;
}
/// Return if the printer should use local scope when dumping the IR.
bool OpPrintingFlags::shouldUseLocalScope() const { return printLocalScope; }
/// Return if the printer should print users of values.
bool OpPrintingFlags::shouldPrintValueUsers() const {
return printValueUsersFlag;
}
/// Returns true if an ElementsAttr with the given number of elements should be
/// printed with hex.
static bool shouldPrintElementsAttrWithHex(int64_t numElements) {
// Check to see if a command line option was provided for the limit.
if (clOptions.isConstructed()) {
if (clOptions->printElementsAttrWithHexIfLarger.getNumOccurrences()) {
// -1 is used to disable hex printing.
if (clOptions->printElementsAttrWithHexIfLarger == -1)
return false;
return numElements > clOptions->printElementsAttrWithHexIfLarger;
}
}
// Otherwise, default to printing with hex if the number of elements is >100.
return numElements > 100;
}
//===----------------------------------------------------------------------===//
// NewLineCounter
//===----------------------------------------------------------------------===//
namespace {
/// This class is a simple formatter that emits a new line when inputted into a
/// stream, that enables counting the number of newlines emitted. This class
/// should be used whenever emitting newlines in the printer.
struct NewLineCounter {
unsigned curLine = 1;
};
static raw_ostream &operator<<(raw_ostream &os, NewLineCounter &newLine) {
++newLine.curLine;
return os << '\n';
}
} // namespace
//===----------------------------------------------------------------------===//
// AsmPrinter::Impl
//===----------------------------------------------------------------------===//
namespace mlir {
class AsmPrinter::Impl {
public:
Impl(raw_ostream &os, AsmStateImpl &state);
explicit Impl(Impl &other) : Impl(other.os, other.state) {}
/// Returns the output stream of the printer.
raw_ostream &getStream() { return os; }
template <typename Container, typename UnaryFunctor>
inline void interleaveComma(const Container &c, UnaryFunctor eachFn) const {
llvm::interleaveComma(c, os, eachFn);
}
/// This enum describes the different kinds of elision for the type of an
/// attribute when printing it.
enum class AttrTypeElision {
/// The type must not be elided,
Never,
/// The type may be elided when it matches the default used in the parser
/// (for example i64 is the default for integer attributes).
May,
/// The type must be elided.
Must
};
/// Print the given attribute or an alias.
void printAttribute(Attribute attr,
AttrTypeElision typeElision = AttrTypeElision::Never);
/// Print the given attribute without considering an alias.
void printAttributeImpl(Attribute attr,
AttrTypeElision typeElision = AttrTypeElision::Never);
/// Print the alias for the given attribute, return failure if no alias could
/// be printed.
LogicalResult printAlias(Attribute attr);
/// Print the given type or an alias.
void printType(Type type);
/// Print the given type.
void printTypeImpl(Type type);
/// Print the alias for the given type, return failure if no alias could
/// be printed.
LogicalResult printAlias(Type type);
/// Print the given location to the stream. If `allowAlias` is true, this
/// allows for the internal location to use an attribute alias.
void printLocation(LocationAttr loc, bool allowAlias = false);
/// Print a reference to the given resource that is owned by the given
/// dialect.
void printResourceHandle(const AsmDialectResourceHandle &resource);
void printAffineMap(AffineMap map);
void
printAffineExpr(AffineExpr expr,
function_ref<void(unsigned, bool)> printValueName = nullptr);
void printAffineConstraint(AffineExpr expr, bool isEq);
void printIntegerSet(IntegerSet set);
protected:
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
ArrayRef<StringRef> elidedAttrs = {},
bool withKeyword = false);
void printNamedAttribute(NamedAttribute attr);
void printTrailingLocation(Location loc, bool allowAlias = true);
void printLocationInternal(LocationAttr loc, bool pretty = false,
bool isTopLevel = false);
/// Print a dense elements attribute. If 'allowHex' is true, a hex string is
/// used instead of individual elements when the elements attr is large.
void printDenseElementsAttr(DenseElementsAttr attr, bool allowHex);
/// Print a dense string elements attribute.
void printDenseStringElementsAttr(DenseStringElementsAttr attr);
/// Print a dense elements attribute. If 'allowHex' is true, a hex string is
/// used instead of individual elements when the elements attr is large.
void printDenseIntOrFPElementsAttr(DenseIntOrFPElementsAttr attr,
bool allowHex);
/// Print a dense array attribute.
void printDenseArrayAttr(DenseArrayAttr attr);
void printDialectAttribute(Attribute attr);
void printDialectType(Type type);
/// Print an escaped string, wrapped with "".
void printEscapedString(StringRef str);
/// Print a hex string, wrapped with "".
void printHexString(StringRef str);
void printHexString(ArrayRef<char> data);
/// This enum is used to represent the binding strength of the enclosing
/// context that an AffineExprStorage is being printed in, so we can
/// intelligently produce parens.
enum class BindingStrength {
Weak, // + and -
Strong, // All other binary operators.
};
void printAffineExprInternal(
AffineExpr expr, BindingStrength enclosingTightness,
function_ref<void(unsigned, bool)> printValueName = nullptr);
/// The output stream for the printer.
raw_ostream &os;
/// An underlying assembly printer state.
AsmStateImpl &state;
/// A set of flags to control the printer's behavior.
OpPrintingFlags printerFlags;
/// A tracker for the number of new lines emitted during printing.
NewLineCounter newLine;
};
} // namespace mlir
//===----------------------------------------------------------------------===//
// AliasInitializer
//===----------------------------------------------------------------------===//
namespace {
/// This class represents a specific instance of a symbol Alias.
class SymbolAlias {
public:
SymbolAlias(StringRef name, uint32_t suffixIndex, bool isType,
bool isDeferrable)
: name(name), suffixIndex(suffixIndex), isType(isType),
isDeferrable(isDeferrable) {}
/// Print this alias to the given stream.
void print(raw_ostream &os) const {
os << (isType ? "!" : "#") << name;
if (suffixIndex)
os << suffixIndex;
}
/// Returns true if this is a type alias.
bool isTypeAlias() const { return isType; }
/// Returns true if this alias supports deferred resolution when parsing.
bool canBeDeferred() const { return isDeferrable; }
private:
/// The main name of the alias.
StringRef name;
/// The suffix index of the alias.
uint32_t suffixIndex : 30;
/// A flag indicating whether this alias is for a type.
bool isType : 1;
/// A flag indicating whether this alias may be deferred or not.
bool isDeferrable : 1;
};
/// This class represents a utility that initializes the set of attribute and
/// type aliases, without the need to store the extra information within the
/// main AliasState class or pass it around via function arguments.
class AliasInitializer {
public:
AliasInitializer(
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces,
llvm::BumpPtrAllocator &aliasAllocator)
: interfaces(interfaces), aliasAllocator(aliasAllocator),
aliasOS(aliasBuffer) {}
void initialize(Operation *op, const OpPrintingFlags &printerFlags,
llvm::MapVector<const void *, SymbolAlias> &attrTypeToAlias);
/// Visit the given attribute to see if it has an alias. `canBeDeferred` is
/// set to true if the originator of this attribute can resolve the alias
/// after parsing has completed (e.g. in the case of operation locations).
/// `elideType` indicates if the type of the attribute should be skipped when
/// looking for nested aliases. Returns the maximum alias depth of the
/// attribute, and the alias index of this attribute.
std::pair<size_t, size_t> visit(Attribute attr, bool canBeDeferred = false,
bool elideType = false) {
return visitImpl(attr, aliases, canBeDeferred, elideType);
}
/// Visit the given type to see if it has an alias. `canBeDeferred` is
/// set to true if the originator of this attribute can resolve the alias
/// after parsing has completed. Returns the maximum alias depth of the type,
/// and the alias index of this type.
std::pair<size_t, size_t> visit(Type type, bool canBeDeferred = false) {
return visitImpl(type, aliases, canBeDeferred);
}
private:
struct InProgressAliasInfo {
InProgressAliasInfo()
: aliasDepth(0), isType(false), canBeDeferred(false) {}
InProgressAliasInfo(StringRef alias, bool isType, bool canBeDeferred)
: alias(alias), aliasDepth(1), isType(isType),
canBeDeferred(canBeDeferred) {}
bool operator<(const InProgressAliasInfo &rhs) const {
// Order first by depth, then by attr/type kind, and then by name.
if (aliasDepth != rhs.aliasDepth)
return aliasDepth < rhs.aliasDepth;
if (isType != rhs.isType)
return isType;
return alias < rhs.alias;
}
/// The alias for the attribute or type, or std::nullopt if the value has no
/// alias.
Optional<StringRef> alias;
/// The alias depth of this attribute or type, i.e. an indication of the
/// relative ordering of when to print this alias.
unsigned aliasDepth : 30;
/// If this alias represents a type or an attribute.
bool isType : 1;
/// If this alias can be deferred or not.
bool canBeDeferred : 1;
/// Indices for child aliases.
SmallVector<size_t> childIndices;
};
/// Visit the given attribute or type to see if it has an alias.
/// `canBeDeferred` is set to true if the originator of this value can resolve
/// the alias after parsing has completed (e.g. in the case of operation
/// locations). Returns the maximum alias depth of the value, and its alias
/// index.
template <typename T, typename... PrintArgs>
std::pair<size_t, size_t>
visitImpl(T value,
llvm::MapVector<const void *, InProgressAliasInfo> &aliases,
bool canBeDeferred, PrintArgs &&...printArgs);
/// Mark the given alias as non-deferrable.
void markAliasNonDeferrable(size_t aliasIndex);
/// Try to generate an alias for the provided symbol. If an alias is
/// generated, the provided alias mapping and reverse mapping are updated.
template <typename T>
void generateAlias(T symbol, InProgressAliasInfo &alias, bool canBeDeferred);
/// Given a collection of aliases and symbols, initialize a mapping from a
/// symbol to a given alias.
static void initializeAliases(
llvm::MapVector<const void *, InProgressAliasInfo> &visitedSymbols,
llvm::MapVector<const void *, SymbolAlias> &symbolToAlias);
/// The set of asm interfaces within the context.
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces;
/// An allocator used for alias names.
llvm::BumpPtrAllocator &aliasAllocator;
/// The set of built aliases.
llvm::MapVector<const void *, InProgressAliasInfo> aliases;
/// Storage and stream used when generating an alias.
SmallString<32> aliasBuffer;
llvm::raw_svector_ostream aliasOS;
};
/// This class implements a dummy OpAsmPrinter that doesn't print any output,
/// and merely collects the attributes and types that *would* be printed in a
/// normal print invocation so that we can generate proper aliases. This allows
/// for us to generate aliases only for the attributes and types that would be
/// in the output, and trims down unnecessary output.
class DummyAliasOperationPrinter : private OpAsmPrinter {
public:
explicit DummyAliasOperationPrinter(const OpPrintingFlags &printerFlags,
AliasInitializer &initializer)
: printerFlags(printerFlags), initializer(initializer) {}
/// Prints the entire operation with the custom assembly form, if available,
/// or the generic assembly form, otherwise.
void printCustomOrGenericOp(Operation *op) override {
// Visit the operation location.
if (printerFlags.shouldPrintDebugInfo())
initializer.visit(op->getLoc(), /*canBeDeferred=*/true);
// If requested, always print the generic form.
if (!printerFlags.shouldPrintGenericOpForm()) {
// Check to see if this is a known operation. If so, use the registered
// custom printer hook.
if (auto opInfo = op->getRegisteredInfo()) {
opInfo->printAssembly(op, *this, /*defaultDialect=*/"");
return;
}
}
// Otherwise print with the generic assembly form.
printGenericOp(op);
}
private:
/// Print the given operation in the generic form.
void printGenericOp(Operation *op, bool printOpName = true) override {
// Consider nested operations for aliases.
for (Region ®ion : op->getRegions())
printRegion(region, /*printEntryBlockArgs=*/true,
/*printBlockTerminators=*/true);
// Visit all the types used in the operation.
for (Type type : op->getOperandTypes())
printType(type);
for (Type type : op->getResultTypes())
printType(type);
// Consider the attributes of the operation for aliases.
for (const NamedAttribute &attr : op->getAttrs())
printAttribute(attr.getValue());
}
/// Print the given block. If 'printBlockArgs' is false, the arguments of the
/// block are not printed. If 'printBlockTerminator' is false, the terminator
/// operation of the block is not printed.
void print(Block *block, bool printBlockArgs = true,
bool printBlockTerminator = true) {
// Consider the types of the block arguments for aliases if 'printBlockArgs'
// is set to true.
if (printBlockArgs) {
for (BlockArgument arg : block->getArguments()) {
printType(arg.getType());
// Visit the argument location.
if (printerFlags.shouldPrintDebugInfo())
// TODO: Allow deferring argument locations.
initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
}
}
// Consider the operations within this block, ignoring the terminator if
// requested.
bool hasTerminator =
!block->empty() && block->back().hasTrait<OpTrait::IsTerminator>();
auto range = llvm::make_range(
block->begin(),
std::prev(block->end(),
(!hasTerminator || printBlockTerminator) ? 0 : 1));
for (Operation &op : range)
printCustomOrGenericOp(&op);
}
/// Print the given region.
void printRegion(Region ®ion, bool printEntryBlockArgs,
bool printBlockTerminators,
bool printEmptyBlock = false) override {
if (region.empty())
return;
auto *entryBlock = ®ion.front();
print(entryBlock, printEntryBlockArgs, printBlockTerminators);
for (Block &b : llvm::drop_begin(region, 1))
print(&b);
}
void printRegionArgument(BlockArgument arg, ArrayRef<NamedAttribute> argAttrs,
bool omitType) override {
printType(arg.getType());
// Visit the argument location.
if (printerFlags.shouldPrintDebugInfo())
// TODO: Allow deferring argument locations.
initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
}
/// Consider the given type to be printed for an alias.
void printType(Type type) override { initializer.visit(type); }
/// Consider the given attribute to be printed for an alias.
void printAttribute(Attribute attr) override { initializer.visit(attr); }
void printAttributeWithoutType(Attribute attr) override {
printAttribute(attr);
}
LogicalResult printAlias(Attribute attr) override {
initializer.visit(attr);
return success();
}
LogicalResult printAlias(Type type) override {
initializer.visit(type);
return success();
}
/// Consider the given location to be printed for an alias.
void printOptionalLocationSpecifier(Location loc) override {
printAttribute(loc);
}
/// Print the given set of attributes with names not included within
/// 'elidedAttrs'.
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
ArrayRef<StringRef> elidedAttrs = {}) override {
if (attrs.empty())
return;
if (elidedAttrs.empty()) {
for (const NamedAttribute &attr : attrs)
printAttribute(attr.getValue());
return;
}
llvm::SmallDenseSet<StringRef> elidedAttrsSet(elidedAttrs.begin(),
elidedAttrs.end());
for (const NamedAttribute &attr : attrs)
if (!elidedAttrsSet.contains(attr.getName().strref()))
printAttribute(attr.getValue());
}
void printOptionalAttrDictWithKeyword(
ArrayRef<NamedAttribute> attrs,
ArrayRef<StringRef> elidedAttrs = {}) override {
printOptionalAttrDict(attrs, elidedAttrs);
}
/// Return a null stream as the output stream, this will ignore any data fed
/// to it.
raw_ostream &getStream() const override { return os; }
/// The following are hooks of `OpAsmPrinter` that are not necessary for
/// determining potential aliases.
void printFloat(const APFloat &) override {}
void printAffineMapOfSSAIds(AffineMapAttr, ValueRange) override {}
void printAffineExprOfSSAIds(AffineExpr, ValueRange, ValueRange) override {}
void printNewline() override {}
void increaseIndent() override {}
void decreaseIndent() override {}
void printOperand(Value) override {}
void printOperand(Value, raw_ostream &os) override {
// Users expect the output string to have at least the prefixed % to signal
// a value name. To maintain this invariant, emit a name even if it is
// guaranteed to go unused.
os << "%";
}
void printKeywordOrString(StringRef) override {}
void printResourceHandle(const AsmDialectResourceHandle &) override {}
void printSymbolName(StringRef) override {}
void printSuccessor(Block *) override {}
void printSuccessorAndUseList(Block *, ValueRange) override {}
void shadowRegionArgs(Region &, ValueRange) override {}
/// The printer flags to use when determining potential aliases.
const OpPrintingFlags &printerFlags;
/// The initializer to use when identifying aliases.
AliasInitializer &initializer;
/// A dummy output stream.
mutable llvm::raw_null_ostream os;
};
class DummyAliasDialectAsmPrinter : public DialectAsmPrinter {
public:
explicit DummyAliasDialectAsmPrinter(AliasInitializer &initializer,
bool canBeDeferred,
SmallVectorImpl<size_t> &childIndices)
: initializer(initializer), canBeDeferred(canBeDeferred),
childIndices(childIndices) {}
/// Print the given attribute/type, visiting any nested aliases that would be
/// generated as part of printing. Returns the maximum alias depth found while
/// printing the given value.
template <typename T, typename... PrintArgs>
size_t printAndVisitNestedAliases(T value, PrintArgs &&...printArgs) {
printAndVisitNestedAliasesImpl(value, printArgs...);
return maxAliasDepth;
}
private:
/// Print the given attribute/type, visiting any nested aliases that would be
/// generated as part of printing.
void printAndVisitNestedAliasesImpl(Attribute attr, bool elideType) {
if (!isa<BuiltinDialect>(attr.getDialect())) {
attr.getDialect().printAttribute(attr, *this);
// Process the builtin attributes.
} else if (attr.isa<AffineMapAttr, DenseArrayAttr, FloatAttr, IntegerAttr,
IntegerSetAttr, UnitAttr>()) {
return;
} else if (auto dictAttr = dyn_cast<DictionaryAttr>(attr)) {
for (const NamedAttribute &nestedAttr : dictAttr.getValue()) {
printAttribute(nestedAttr.getName());
printAttribute(nestedAttr.getValue());
}
} else if (auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
for (Attribute nestedAttr : arrayAttr.getValue())
printAttribute(nestedAttr);
} else if (auto typeAttr = dyn_cast<TypeAttr>(attr)) {
printType(typeAttr.getValue());
} else if (auto locAttr = dyn_cast<OpaqueLoc>(attr)) {
printAttribute(locAttr.getFallbackLocation());
} else if (auto locAttr = dyn_cast<NameLoc>(attr)) {
if (!isa<UnknownLoc>(locAttr.getChildLoc()))
printAttribute(locAttr.getChildLoc());
} else if (auto locAttr = dyn_cast<CallSiteLoc>(attr)) {
printAttribute(locAttr.getCallee());
printAttribute(locAttr.getCaller());
} else if (auto locAttr = dyn_cast<FusedLoc>(attr)) {
if (Attribute metadata = locAttr.getMetadata())
printAttribute(metadata);
for (Location nestedLoc : locAttr.getLocations())
printAttribute(nestedLoc);
}
// Don't print the type if we must elide it, or if it is a None type.
if (!elideType) {
if (auto typedAttr = attr.dyn_cast<TypedAttr>()) {
Type attrType = typedAttr.getType();
if (!attrType.isa<NoneType>())
printType(attrType);
}
}
}
void printAndVisitNestedAliasesImpl(Type type) {
if (!isa<BuiltinDialect>(type.getDialect()))
return type.getDialect().printType(type, *this);
// Only visit the layout of memref if it isn't the identity.
if (auto memrefTy = type.dyn_cast<MemRefType>()) {
printType(memrefTy.getElementType());
MemRefLayoutAttrInterface layout = memrefTy.getLayout();
if (!layout.isa<AffineMapAttr>() || !layout.isIdentity())
printAttribute(memrefTy.getLayout());
if (memrefTy.getMemorySpace())
printAttribute(memrefTy.getMemorySpace());
return;
}
// For most builtin types, we can simply walk the sub elements.
if (auto subElementInterface = dyn_cast<SubElementTypeInterface>(type)) {
auto visitFn = [&](auto element) {
if (element)
(void)printAlias(element);
};
subElementInterface.walkImmediateSubElements(visitFn, visitFn);
}
}
/// Consider the given type to be printed for an alias.
void printType(Type type) override {
recordAliasResult(initializer.visit(type, canBeDeferred));
}
/// Consider the given attribute to be printed for an alias.
void printAttribute(Attribute attr) override {
recordAliasResult(initializer.visit(attr, canBeDeferred));
}
void printAttributeWithoutType(Attribute attr) override {
recordAliasResult(
initializer.visit(attr, canBeDeferred, /*elideType=*/true));
}
LogicalResult printAlias(Attribute attr) override {
printAttribute(attr);
return success();
}
LogicalResult printAlias(Type type) override {
printType(type);
return success();
}
/// Record the alias result of a child element.
void recordAliasResult(std::pair<size_t, size_t> aliasDepthAndIndex) {
childIndices.push_back(aliasDepthAndIndex.second);
if (aliasDepthAndIndex.first > maxAliasDepth)
maxAliasDepth = aliasDepthAndIndex.first;
}
/// Return a null stream as the output stream, this will ignore any data fed
/// to it.
raw_ostream &getStream() const override { return os; }
/// The following are hooks of `DialectAsmPrinter` that are not necessary for
/// determining potential aliases.
void printFloat(const APFloat &) override {}
void printKeywordOrString(StringRef) override {}
void printSymbolName(StringRef) override {}
void printResourceHandle(const AsmDialectResourceHandle &) override {}
/// The initializer to use when identifying aliases.
AliasInitializer &initializer;
/// If the aliases visited by this printer can be deferred.
bool canBeDeferred;
/// The indices of child aliases.
SmallVectorImpl<size_t> &childIndices;
/// The maximum alias depth found by the printer.
size_t maxAliasDepth = 0;
/// A dummy output stream.
mutable llvm::raw_null_ostream os;
};
} // namespace
/// Sanitize the given name such that it can be used as a valid identifier. If
/// the string needs to be modified in any way, the provided buffer is used to
/// store the new copy,
static StringRef sanitizeIdentifier(StringRef name, SmallString<16> &buffer,
StringRef allowedPunctChars = "$._-",
bool allowTrailingDigit = true) {
assert(!name.empty() && "Shouldn't have an empty name here");
auto copyNameToBuffer = [&] {
for (char ch : name) {
if (llvm::isAlnum(ch) || allowedPunctChars.contains(ch))
buffer.push_back(ch);
else if (ch == ' ')
buffer.push_back('_');
else
buffer.append(llvm::utohexstr((unsigned char)ch));
}
};
// Check to see if this name is valid. If it starts with a digit, then it
// could conflict with the autogenerated numeric ID's, so add an underscore
// prefix to avoid problems.
if (isdigit(name[0])) {
buffer.push_back('_');
copyNameToBuffer();
return buffer;
}
// If the name ends with a trailing digit, add a '_' to avoid potential
// conflicts with autogenerated ID's.
if (!allowTrailingDigit && isdigit(name.back())) {
copyNameToBuffer();
buffer.push_back('_');
return buffer;
}
// Check to see that the name consists of only valid identifier characters.
for (char ch : name) {
if (!llvm::isAlnum(ch) && !allowedPunctChars.contains(ch)) {
copyNameToBuffer();
return buffer;
}
}
// If there are no invalid characters, return the original name.
return name;
}
/// Given a collection of aliases and symbols, initialize a mapping from a
/// symbol to a given alias.
void AliasInitializer::initializeAliases(
llvm::MapVector<const void *, InProgressAliasInfo> &visitedSymbols,
llvm::MapVector<const void *, SymbolAlias> &symbolToAlias) {
std::vector<std::pair<const void *, InProgressAliasInfo>> unprocessedAliases =
visitedSymbols.takeVector();
llvm::stable_sort(unprocessedAliases, [](const auto &lhs, const auto &rhs) {
return lhs.second < rhs.second;
});
llvm::StringMap<unsigned> nameCounts;
for (auto &[symbol, aliasInfo] : unprocessedAliases) {
if (!aliasInfo.alias)
continue;
StringRef alias = *aliasInfo.alias;
unsigned nameIndex = nameCounts[alias]++;
symbolToAlias.insert(
{symbol, SymbolAlias(alias, nameIndex, aliasInfo.isType,
aliasInfo.canBeDeferred)});
}
}
void AliasInitializer::initialize(
Operation *op, const OpPrintingFlags &printerFlags,
llvm::MapVector<const void *, SymbolAlias> &attrTypeToAlias) {
// Use a dummy printer when walking the IR so that we can collect the
// attributes/types that will actually be used during printing when
// considering aliases.
DummyAliasOperationPrinter aliasPrinter(printerFlags, *this);
aliasPrinter.printCustomOrGenericOp(op);
// Initialize the aliases.
initializeAliases(aliases, attrTypeToAlias);
}
template <typename T, typename... PrintArgs>
std::pair<size_t, size_t> AliasInitializer::visitImpl(
T value, llvm::MapVector<const void *, InProgressAliasInfo> &aliases,
bool canBeDeferred, PrintArgs &&...printArgs) {