-
Notifications
You must be signed in to change notification settings - Fork 303
/
EmitOMIR.cpp
1315 lines (1199 loc) · 49.6 KB
/
EmitOMIR.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
//===- EmitOMIR.cpp ---------------------------------------------*- C++ -*-===//
//
// 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 defines the EmitOMIR pass.
//
//===----------------------------------------------------------------------===//
#include "circt/Dialect/Emit/EmitOps.h"
#include "circt/Dialect/FIRRTL/AnnotationDetails.h"
#include "circt/Dialect/FIRRTL/FIRParser.h"
#include "circt/Dialect/FIRRTL/FIRRTLAnnotationHelper.h"
#include "circt/Dialect/FIRRTL/FIRRTLInstanceGraph.h"
#include "circt/Dialect/FIRRTL/FIRRTLOps.h"
#include "circt/Dialect/FIRRTL/FIRRTLUtils.h"
#include "circt/Dialect/FIRRTL/NLATable.h"
#include "circt/Dialect/FIRRTL/Namespace.h"
#include "circt/Dialect/FIRRTL/Passes.h"
#include "circt/Dialect/HW/HWAttributes.h"
#include "circt/Dialect/HW/InnerSymbolNamespace.h"
#include "circt/Dialect/SV/SVDialect.h"
#include "circt/Dialect/SV/SVOps.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/Pass/Pass.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/JSON.h"
#include <functional>
#define DEBUG_TYPE "omir"
namespace circt {
namespace firrtl {
#define GEN_PASS_DEF_EMITOMIR
#include "circt/Dialect/FIRRTL/Passes.h.inc"
} // namespace firrtl
} // namespace circt
using namespace circt;
using namespace firrtl;
using mlir::LocationAttr;
using mlir::UnitAttr;
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
namespace {
/// Information concerning a tracker in the IR.
struct Tracker {
/// The unique ID of this tracker.
IntegerAttr id;
/// The operation onto which this tracker was annotated.
Operation *op;
/// If this tracker is non-local, this is the corresponding anchor.
hw::HierPathOp nla;
/// If this is a port, then set the portIdx, else initialized to -1.
int portNo = -1;
/// If this is a field, the ID will be greater than 0, else it will be 0.
unsigned fieldID;
// Returns true if the tracker has a non-zero field ID.
bool hasFieldID() { return fieldID > 0; }
};
class EmitOMIRPass : public circt::firrtl::impl::EmitOMIRBase<EmitOMIRPass> {
public:
using EmitOMIRBase::outputFilename;
private:
void runOnOperation() override;
void makeTrackerAbsolute(Tracker &tracker);
void emitSourceInfo(Location input, SmallString<64> &into);
void emitOMNode(Attribute node, llvm::json::OStream &jsonStream);
void emitOMField(StringAttr fieldName, DictionaryAttr field,
llvm::json::OStream &jsonStream);
void emitOptionalRTLPorts(DictionaryAttr node,
llvm::json::OStream &jsonStream);
void emitValue(Attribute node, llvm::json::OStream &jsonStream,
bool dutInstance);
void emitTrackedTarget(DictionaryAttr node, llvm::json::OStream &jsonStream,
bool dutInstance);
SmallString<8> addSymbolImpl(Attribute symbol) {
unsigned id;
auto it = symbolIndices.find(symbol);
if (it != symbolIndices.end()) {
id = it->second;
} else {
id = symbols.size();
symbols.push_back(symbol);
symbolIndices.insert({symbol, id});
}
SmallString<8> str;
("{{" + Twine(id) + "}}").toVector(str);
return str;
}
SmallString<8> addSymbol(hw::InnerRefAttr symbol) {
return addSymbolImpl(symbol);
}
SmallString<8> addSymbol(FlatSymbolRefAttr symbol) {
return addSymbolImpl(symbol);
}
SmallString<8> addSymbol(StringAttr symbolName) {
return addSymbol(FlatSymbolRefAttr::get(symbolName));
}
SmallString<8> addSymbol(Operation *op) {
return addSymbol(SymbolTable::getSymbolName(op));
}
/// Obtain an inner reference to an operation, possibly adding an `inner_sym`
/// to that operation.
hw::InnerRefAttr getInnerRefTo(Operation *op);
/// Obtain an inner reference to a module port, possibly adding an `inner_sym`
/// to that port.
hw::InnerRefAttr getInnerRefTo(FModuleLike module, size_t portIdx);
// Obtain the result type of an Operation.
FIRRTLType getTypeOf(Operation *op);
// Obtain the type of a module port.
FIRRTLType getTypeOf(FModuleLike mod, size_t portIdx);
// Constructs a reference to a field from a FIRRTLType with a fieldID.
void addFieldID(FIRRTLType type, unsigned fieldID,
SmallVectorImpl<char> &result);
/// Get the cached namespace for a module.
hw::InnerSymbolNamespace &getModuleNamespace(FModuleLike module) {
return moduleNamespaces.try_emplace(module, module).first->second;
}
/// Whether any errors have occurred in the current `runOnOperation`.
bool anyFailures;
CircuitNamespace *circuitNamespace;
InstanceGraph *instanceGraph;
InstancePathCache *instancePaths;
/// OMIR target trackers gathered in the current operation, by tracker ID.
DenseMap<Attribute, Tracker> trackers;
/// The list of symbols to be interpolated in the verbatim JSON. This gets
/// populated as the JSON is constructed and module and instance names are
/// collected.
SmallVector<Attribute> symbols;
SmallDenseMap<Attribute, unsigned> symbolIndices;
/// Temporary `firrtl.hierpath` operations to be deleted at the end of the
/// pass. Vector elements are unique.
SmallVector<hw::HierPathOp> removeTempNLAs;
DenseMap<Operation *, hw::InnerSymbolNamespace> moduleNamespaces;
/// Lookup table of instances by name and parent module.
DenseMap<hw::InnerRefAttr, InstanceOp> instancesByName;
/// Record to remove any temporary symbols added to instances.
DenseSet<Operation *> tempSymInstances;
/// The Design Under Test module.
StringAttr dutModuleName;
/// Cached NLA table analysis.
NLATable *nlaTable;
};
} // namespace
/// Check if an `OMNode` is an `OMSRAM` and requires special treatment of its
/// instance path field. This returns the ID of the tracker stored in the
/// `instancePath` or `finalPath` field if the node has an array field `omType`
/// that contains a `OMString:OMSRAM` entry.
static IntegerAttr isOMSRAM(Attribute &node) {
auto dict = dyn_cast<DictionaryAttr>(node);
if (!dict)
return {};
auto idAttr = dict.getAs<StringAttr>("id");
if (!idAttr)
return {};
IntegerAttr id;
if (auto infoAttr = dict.getAs<DictionaryAttr>("fields")) {
auto finalPath = infoAttr.getAs<DictionaryAttr>("finalPath");
// The following is used prior to an upstream bump in Chisel.
if (!finalPath)
finalPath = infoAttr.getAs<DictionaryAttr>("instancePath");
if (finalPath)
if (auto v = finalPath.getAs<DictionaryAttr>("value"))
if (v.getAs<UnitAttr>("omir.tracker"))
id = v.getAs<IntegerAttr>("id");
if (auto omTy = infoAttr.getAs<DictionaryAttr>("omType"))
if (auto valueArr = omTy.getAs<ArrayAttr>("value"))
for (auto attr : valueArr)
if (auto str = dyn_cast<StringAttr>(attr))
if (str.getValue() == "OMString:OMSRAM")
return id;
}
return {};
}
//===----------------------------------------------------------------------===//
// Code related to handling OMIR annotations
//===----------------------------------------------------------------------===//
/// Recursively walk Object Model IR and convert FIRRTL targets to identifiers
/// while scattering trackers into the newAnnotations argument.
///
/// Object Model IR consists of a type hierarchy built around recursive arrays
/// and dictionaries whose leaves are "string-encoded types". This is an Object
/// Model-specific construct that puts type information alongside a value.
/// Concretely, these look like:
///
/// 'OM' type ':' value
///
/// This function is only concerned with unpacking types whose values are FIRRTL
/// targets. This is because these need to be kept up-to-date with
/// modifications made to the circuit whereas other types are just passing
/// through CIRCT.
///
/// At a later time this understanding may be expanded or Object Model IR may
/// become its own Dialect. At this time, this function is trying to do as
/// minimal work as possible to just validate that the OMIR looks okay without
/// doing lots of unnecessary unpacking/repacking of string-encoded types.
static std::optional<Attribute> scatterOMIR(Attribute original,
ApplyState &state) {
auto *ctx = original.getContext();
// Convert a string-encoded type to a dictionary that includes the type
// information and an identifier derived from the current annotationID. Then
// increment the annotationID. Return the constructed dictionary.
auto addID = [&](StringRef tpe, StringRef path,
IntegerAttr id) -> DictionaryAttr {
NamedAttrList fields;
fields.append("id", id);
fields.append("omir.tracker", UnitAttr::get(ctx));
fields.append("path", StringAttr::get(ctx, path));
fields.append("type", StringAttr::get(ctx, tpe));
return DictionaryAttr::getWithSorted(ctx, fields);
};
return TypeSwitch<Attribute, std::optional<Attribute>>(original)
// Most strings in the Object Model are actually string-encoded types.
// These are types which look like: "<type>:<value>". This code will
// examine all strings, parse them into type and value, and then either
// store them in their unpacked state (and possibly scatter trackers into
// the circuit), store them in their packed state (because CIRCT is not
// expected to care about them right now), or error if we see them
// (because they should not exist and are expected to serialize to a
// different format).
.Case<StringAttr>([&](StringAttr str) -> std::optional<Attribute> {
// Unpack the string into type and value.
StringRef tpe, value;
std::tie(tpe, value) = str.getValue().split(":");
// These are string-encoded types that are targets in the circuit.
// These require annotations to be scattered for them. Replace their
// target with an ID and scatter a tracker.
if (tpe == "OMReferenceTarget" || tpe == "OMMemberReferenceTarget" ||
tpe == "OMMemberInstanceTarget" || tpe == "OMInstanceTarget" ||
tpe == "OMDontTouchedReferenceTarget") {
auto idAttr = state.newID();
NamedAttrList tracker;
tracker.append("class", StringAttr::get(ctx, omirTrackerAnnoClass));
tracker.append("id", idAttr);
tracker.append("target", StringAttr::get(ctx, value));
tracker.append("type", StringAttr::get(ctx, tpe));
state.addToWorklistFn(DictionaryAttr::get(ctx, tracker));
return addID(tpe, value, idAttr);
}
// The following are types that may exist, but we do not unbox them. At
// a later time, we may want to change this behavior and unbox these if
// we wind up building out an Object Model dialect:
if (isOMIRStringEncodedPassthrough(tpe))
return str;
// The following types are not expected to exist because they have
// serializations to JSON types or are removed during serialization.
// Hence, any of the following types are NOT expected to exist and we
// error if we see them. These are explicitly specified as opposed to
// being handled in the "unknown" catch-all case below because we want
// to provide a good error message that a user may be doing something
// very weird.
if (tpe == "OMMap" || tpe == "OMArray" || tpe == "OMBoolean" ||
tpe == "OMInt" || tpe == "OMDouble" || tpe == "OMFrozenTarget") {
auto diag =
mlir::emitError(state.circuit.getLoc())
<< "found known string-encoded OMIR type \"" << tpe
<< "\", but this type should not be seen as it has a defined "
"serialization format that does NOT use a string-encoded type";
diag.attachNote()
<< "the problematic OMIR is reproduced here: " << original;
return std::nullopt;
}
// This is a catch-all for any unknown types.
auto diag = mlir::emitError(state.circuit.getLoc())
<< "found unknown string-encoded OMIR type \"" << tpe
<< "\" (Did you misspell it? Is CIRCT missing an Object "
"Model OMIR type?)";
diag.attachNote() << "the problematic OMIR is reproduced here: "
<< original;
return std::nullopt;
})
// For an array, just recurse into each element and rewrite the array with
// the results.
.Case<ArrayAttr>([&](ArrayAttr arr) -> std::optional<Attribute> {
SmallVector<Attribute> newArr;
for (auto element : arr) {
auto newElement = scatterOMIR(element, state);
if (!newElement)
return std::nullopt;
newArr.push_back(*newElement);
}
return ArrayAttr::get(ctx, newArr);
})
// For a dictionary, recurse into each value and rewrite the key/value
// pairs.
.Case<DictionaryAttr>(
[&](DictionaryAttr dict) -> std::optional<Attribute> {
NamedAttrList newAttrs;
for (auto pairs : dict) {
auto maybeValue = scatterOMIR(pairs.getValue(), state);
if (!maybeValue)
return std::nullopt;
newAttrs.append(pairs.getName(), *maybeValue);
}
return DictionaryAttr::get(ctx, newAttrs);
})
// These attributes are all expected. They are OMIR types, but do not
// have string-encodings (hence why these should error if we see them as
// strings).
.Case</* OMBoolean */ BoolAttr, /* OMDouble */ FloatAttr,
/* OMInt */ IntegerAttr>(
[](auto passThrough) { return passThrough; })
// Error if we see anything else.
.Default([&](auto) -> std::optional<Attribute> {
auto diag = mlir::emitError(state.circuit.getLoc())
<< "found unexpected MLIR attribute \"" << original
<< "\" while trying to scatter OMIR";
return std::nullopt;
});
}
/// Convert an Object Model Field into an optional pair of a string key and a
/// dictionary attribute. Expand internal source locator strings to location
/// attributes. Scatter any FIRRTL targets into the circuit. If this is an
/// illegal Object Model Field return None.
///
/// Each Object Model Field consists of three mandatory members with
/// the following names and types:
///
/// - "info": Source Locator String
/// - "name": String
/// - "value": Object Model IR
///
/// The key is the "name" and the dictionary consists of the "info" and "value"
/// members. Each value is recursively traversed to scatter any FIRRTL targets
/// that may be used inside it.
///
/// This conversion from an object (dictionary) to key--value pair is safe
/// because each Object Model Field in an Object Model Node must have a unique
/// "name". Anything else is illegal Object Model.
static std::optional<std::pair<StringRef, DictionaryAttr>>
scatterOMField(Attribute original, const Attribute root, unsigned index,
ApplyState &state) {
// The input attribute must be a dictionary.
DictionaryAttr dict = dyn_cast<DictionaryAttr>(original);
if (!dict) {
llvm::errs() << "OMField is not a dictionary, but should be: " << original
<< "\n";
return std::nullopt;
}
auto loc = state.circuit.getLoc();
auto *ctx = state.circuit.getContext();
// Generate an arbitrary identifier to use for caching when using
// `maybeStringToLocation`.
StringAttr locatorFilenameCache = StringAttr::get(ctx, ".");
FileLineColLoc fileLineColLocCache;
// Convert location from a string to a location attribute.
auto infoAttr = tryGetAs<StringAttr>(dict, root, "info", loc, omirAnnoClass);
if (!infoAttr)
return std::nullopt;
auto maybeLoc =
maybeStringToLocation(infoAttr.getValue(), false, locatorFilenameCache,
fileLineColLocCache, ctx);
mlir::LocationAttr infoLoc;
if (maybeLoc.first)
infoLoc = *maybeLoc.second;
else
infoLoc = UnknownLoc::get(ctx);
// Extract the name attribute.
auto nameAttr = tryGetAs<StringAttr>(dict, root, "name", loc, omirAnnoClass);
if (!nameAttr)
return std::nullopt;
// The value attribute is unstructured and just copied over.
auto valueAttr = tryGetAs<Attribute>(dict, root, "value", loc, omirAnnoClass);
if (!valueAttr)
return std::nullopt;
auto newValue = scatterOMIR(valueAttr, state);
if (!newValue)
return std::nullopt;
NamedAttrList values;
// We add the index if one was provided. This can be used later to
// reconstruct the order of the original array.
values.append("index", IntegerAttr::get(IntegerType::get(ctx, 64), index));
values.append("info", infoLoc);
values.append("value", *newValue);
return {{nameAttr.getValue(), DictionaryAttr::getWithSorted(ctx, values)}};
}
/// Convert an Object Model Node to an optional dictionary, convert source
/// locator strings to location attributes, and scatter FIRRTL targets into the
/// circuit. If this is an illegal Object Model Node, then return None.
///
/// An Object Model Node is expected to look like:
///
/// - "info": Source Locator String
/// - "id": String-encoded integer ('OMID' ':' Integer)
/// - "fields": Array<Object>
///
/// The "fields" member may be absent. If so, then construct an empty array.
static std::optional<DictionaryAttr>
scatterOMNode(Attribute original, const Attribute root, ApplyState &state) {
auto loc = state.circuit.getLoc();
/// The input attribute must be a dictionary.
DictionaryAttr dict = dyn_cast<DictionaryAttr>(original);
if (!dict) {
llvm::errs() << "OMNode is not a dictionary, but should be: " << original
<< "\n";
return std::nullopt;
}
NamedAttrList omnode;
auto *ctx = state.circuit.getContext();
// Generate an arbitrary identifier to use for caching when using
// `maybeStringToLocation`.
StringAttr locatorFilenameCache = StringAttr::get(ctx, ".");
FileLineColLoc fileLineColLocCache;
// Convert the location from a string to a location attribute.
auto infoAttr = tryGetAs<StringAttr>(dict, root, "info", loc, omirAnnoClass);
if (!infoAttr)
return std::nullopt;
auto maybeLoc =
maybeStringToLocation(infoAttr.getValue(), false, locatorFilenameCache,
fileLineColLocCache, ctx);
mlir::LocationAttr infoLoc;
if (maybeLoc.first)
infoLoc = *maybeLoc.second;
else
infoLoc = UnknownLoc::get(ctx);
// Extract the OMID. Don't parse this, just leave it as a string.
auto idAttr = tryGetAs<StringAttr>(dict, root, "id", loc, omirAnnoClass);
if (!idAttr)
return std::nullopt;
// Convert the fields from an ArrayAttr to a DictionaryAttr keyed by their
// "name". If no fields member exists, then just create an empty dictionary.
// Note that this is safe to construct because all fields must have unique
// "name" members relative to each other.
auto maybeFields = dict.getAs<ArrayAttr>("fields");
DictionaryAttr fields;
if (!maybeFields)
fields = DictionaryAttr::get(ctx);
else {
auto fieldAttr = maybeFields.getValue();
NamedAttrList fieldAttrs;
for (size_t i = 0, e = fieldAttr.size(); i != e; ++i) {
auto field = fieldAttr[i];
if (auto newField = scatterOMField(field, root, i, state)) {
fieldAttrs.append(newField->first, newField->second);
continue;
}
return std::nullopt;
}
fields = DictionaryAttr::get(ctx, fieldAttrs);
}
omnode.append("fields", fields);
omnode.append("id", idAttr);
omnode.append("info", infoLoc);
return DictionaryAttr::getWithSorted(ctx, omnode);
}
/// Main entry point to handle scattering of an OMIRAnnotation. Return the
/// modified optional attribute on success and None on failure. Any scattered
/// annotations will be added to the reference argument `newAnnotations`.
LogicalResult circt::firrtl::applyOMIR(const AnnoPathValue &target,
DictionaryAttr anno, ApplyState &state) {
auto loc = state.circuit.getLoc();
auto nodes = tryGetAs<ArrayAttr>(anno, anno, "nodes", loc, omirAnnoClass);
if (!nodes)
return failure();
SmallVector<Attribute> newNodes;
for (auto node : nodes) {
auto newNode = scatterOMNode(node, anno, state);
if (!newNode)
return failure();
newNodes.push_back(*newNode);
}
auto *ctx = state.circuit.getContext();
NamedAttrList newAnnotation;
newAnnotation.append("class", StringAttr::get(ctx, omirAnnoClass));
newAnnotation.append("nodes", ArrayAttr::get(ctx, newNodes));
AnnotationSet annotations(state.circuit);
annotations.addAnnotations(DictionaryAttr::get(ctx, newAnnotation));
annotations.applyToOperation(state.circuit);
return success();
}
//===----------------------------------------------------------------------===//
// Pass Implementation
//===----------------------------------------------------------------------===//
void EmitOMIRPass::runOnOperation() {
anyFailures = false;
circuitNamespace = nullptr;
instanceGraph = nullptr;
instancePaths = nullptr;
trackers.clear();
symbols.clear();
symbolIndices.clear();
removeTempNLAs.clear();
moduleNamespaces.clear();
instancesByName.clear();
CircuitOp circuitOp = getOperation();
// Gather the relevant annotations from the circuit. On the one hand these are
// all the actual `OMIRAnnotation`s that need processing and emission, as well
// as an optional `OMIRFileAnnotation` that overrides the default OMIR output
// file. Also while we're at it, keep track of all OMIR nodes that qualify as
// an SRAM and that require their trackers to be turned into NLAs starting at
// the root of the hierarchy.
SmallVector<ArrayRef<Attribute>> annoNodes;
DenseSet<Attribute> sramIDs;
std::optional<StringRef> outputFilename;
AnnotationSet::removeAnnotations(circuitOp, [&](Annotation anno) {
if (anno.isClass(omirFileAnnoClass)) {
auto pathAttr = anno.getMember<StringAttr>("filename");
if (!pathAttr) {
circuitOp.emitError(omirFileAnnoClass)
<< " annotation missing `filename` string attribute";
anyFailures = true;
return true;
}
LLVM_DEBUG(llvm::dbgs() << "- OMIR path: " << pathAttr << "\n");
outputFilename = pathAttr.getValue();
return true;
}
if (anno.isClass(omirAnnoClass)) {
auto nodesAttr = anno.getMember<ArrayAttr>("nodes");
if (!nodesAttr) {
circuitOp.emitError(omirAnnoClass)
<< " annotation missing `nodes` array attribute";
anyFailures = true;
return true;
}
LLVM_DEBUG(llvm::dbgs() << "- OMIR: " << nodesAttr << "\n");
annoNodes.push_back(nodesAttr.getValue());
for (auto node : nodesAttr) {
if (auto id = isOMSRAM(node)) {
LLVM_DEBUG(llvm::dbgs() << " - is SRAM with tracker " << id << "\n");
sramIDs.insert(id);
}
}
return true;
}
return false;
});
if (anyFailures)
return signalPassFailure();
// If an OMIR output filename has been specified as a pass parameter, override
// whatever the annotations have configured. If neither are specified we just
// bail.
if (!this->outputFilename.empty())
outputFilename = this->outputFilename;
if (!outputFilename) {
LLVM_DEBUG(llvm::dbgs() << "Not emitting OMIR because no annotation or "
"pass parameter specified an output file\n");
markAllAnalysesPreserved();
return;
}
// Establish some of the analyses we need throughout the pass.
CircuitNamespace currentCircuitNamespace(circuitOp);
InstanceGraph ¤tInstanceGraph = getAnalysis<InstanceGraph>();
nlaTable = &getAnalysis<NLATable>();
InstancePathCache currentInstancePaths(currentInstanceGraph);
circuitNamespace = ¤tCircuitNamespace;
instanceGraph = ¤tInstanceGraph;
instancePaths = ¤tInstancePaths;
dutModuleName = {};
// Traverse the IR and collect all tracker annotations that were previously
// scattered into the circuit.
circuitOp.walk([&](Operation *op) {
if (auto instOp = dyn_cast<InstanceOp>(op)) {
// This instance does not have a symbol, but we are adding one. Remove it
// after the pass.
if (!op->getAttr(hw::InnerSymbolTable::getInnerSymbolAttrName()))
tempSymInstances.insert(instOp);
instancesByName.insert({getInnerRefTo(op), instOp});
}
auto setTracker = [&](int portNo, Annotation anno) {
if (!anno.isClass(omirTrackerAnnoClass))
return false;
Tracker tracker;
tracker.op = op;
tracker.id = anno.getMember<IntegerAttr>("id");
tracker.portNo = portNo;
tracker.fieldID = anno.getFieldID();
if (!tracker.id) {
op->emitError(omirTrackerAnnoClass)
<< " annotation missing `id` integer attribute";
anyFailures = true;
return true;
}
if (auto nlaSym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal")) {
auto tmp = nlaTable->getNLA(nlaSym.getAttr());
if (!tmp) {
op->emitError("missing annotation ") << nlaSym.getValue();
anyFailures = true;
return true;
}
tracker.nla = cast<hw::HierPathOp>(tmp);
}
if (sramIDs.erase(tracker.id))
makeTrackerAbsolute(tracker);
if (auto [it, inserted] = trackers.try_emplace(tracker.id, tracker);
!inserted) {
auto diag = op->emitError(omirTrackerAnnoClass)
<< " annotation with same ID already found, must resolve "
"to single target";
diag.attachNote(it->second.op->getLoc())
<< "tracker with same ID already found here";
anyFailures = true;
return true;
}
return true;
};
AnnotationSet::removePortAnnotations(op, setTracker);
AnnotationSet::removeAnnotations(
op, std::bind(setTracker, -1, std::placeholders::_1));
if (auto modOp = dyn_cast<FModuleOp>(op)) {
if (!AnnotationSet::hasAnnotation(modOp, dutAnnoClass))
return;
dutModuleName = modOp.getNameAttr();
}
});
// Build the output JSON.
std::string jsonBuffer;
llvm::raw_string_ostream jsonOs(jsonBuffer);
llvm::json::OStream json(jsonOs, 2);
json.array([&] {
for (auto nodes : annoNodes) {
for (auto node : nodes) {
emitOMNode(node, json);
if (anyFailures)
return;
}
}
});
if (anyFailures)
return signalPassFailure();
// Drop temporary (and sometimes invalid) NLA's created during the pass:
for (auto nla : removeTempNLAs) {
LLVM_DEBUG(llvm::dbgs() << "Removing '" << nla << "'\n");
nlaTable->erase(nla);
nla.erase();
}
removeTempNLAs.clear();
// Remove the temp symbol from instances.
for (auto *op : tempSymInstances)
cast<InstanceOp>(op).setInnerSymbolAttr({});
tempSymInstances.clear();
// Emit the OMIR JSON as a verbatim op.
auto builder = circuitOp.getBodyBuilder();
auto loc = builder.getUnknownLoc();
builder.create<emit::FileOp>(loc, *outputFilename, [&] {
builder.create<sv::VerbatimOp>(builder.getUnknownLoc(), jsonBuffer,
ValueRange{}, builder.getArrayAttr(symbols));
});
markAnalysesPreserved<NLATable>();
}
/// Make a tracker absolute by adding an NLA to it which starts at the root
/// module of the circuit. Generates an error if any module along the path is
/// instantiated multiple times.
void EmitOMIRPass::makeTrackerAbsolute(Tracker &tracker) {
auto builder = OpBuilder::atBlockBegin(getOperation().getBodyBlock());
// Pick a name for the NLA that doesn't collide with anything.
StringAttr opName;
if (auto module = dyn_cast<FModuleLike>(tracker.op))
opName = module.getModuleNameAttr();
else
opName = tracker.op->getAttrOfType<StringAttr>("name");
auto nlaName = circuitNamespace->newName("omir_nla_" + opName.getValue());
// Get all the paths instantiating this module. If there is an NLA already
// attached to this tracker, we use it as a base to disambiguate the path to
// the memory.
igraph::ModuleOpInterface mod;
if (tracker.nla)
mod = instanceGraph->lookup(tracker.nla.root())
->getModule<igraph::ModuleOpInterface>();
else
mod = tracker.op->getParentOfType<FModuleOp>();
// Get all the paths instantiating this module.
auto paths = instancePaths->getAbsolutePaths(mod);
if (paths.empty()) {
tracker.op->emitError("OMIR node targets uninstantiated component `")
<< opName.getValue() << "`";
anyFailures = true;
return;
}
if (paths.size() > 1) {
auto diag = tracker.op->emitError("OMIR node targets ambiguous component `")
<< opName.getValue() << "`";
diag.attachNote(tracker.op->getLoc())
<< "may refer to the following paths:";
for (auto path : paths) {
std::string pathStr;
llvm::raw_string_ostream os(pathStr);
os << "- " << path;
diag.attachNote(tracker.op->getLoc()) << pathStr;
}
anyFailures = true;
return;
}
// Assemble the module and name path for the NLA. Also attach an NLA reference
// annotation to each instance participating in the path.
SmallVector<Attribute> namepath;
auto addToPath = [&](Operation *op) {
namepath.push_back(getInnerRefTo(op));
};
// Add the path up to where the NLA starts.
for (auto inst : paths[0])
addToPath(inst);
// Add the path from the NLA to the op.
if (tracker.nla) {
auto path = tracker.nla.getNamepath().getValue();
for (auto attr : path.drop_back()) {
auto ref = cast<hw::InnerRefAttr>(attr);
// Find the instance referenced by the NLA.
auto *node = instanceGraph->lookup(ref.getModule());
auto it = llvm::find_if(*node, [&](igraph::InstanceRecord *record) {
return getInnerSymName(record->getInstance<InstanceOp>()) ==
ref.getName();
});
assert(it != node->end() &&
"Instance referenced by NLA does not exist in module");
addToPath((*it)->getInstance());
}
}
// TODO: Don't create NLA if namepath is empty
// (care needed to ensure this will be handled correctly elsewhere)
// Add the op itself.
if (auto module = dyn_cast<FModuleLike>(tracker.op))
namepath.push_back(FlatSymbolRefAttr::get(module.getModuleNameAttr()));
else
namepath.push_back(getInnerRefTo(tracker.op));
// Add the NLA to the tracker and mark it to be deleted later.
tracker.nla = builder.create<hw::HierPathOp>(builder.getUnknownLoc(),
builder.getStringAttr(nlaName),
builder.getArrayAttr(namepath));
nlaTable->addNLA(tracker.nla);
removeTempNLAs.push_back(tracker.nla);
}
/// Emit a source locator into a string, for inclusion in the `info` field of
/// `OMNode` and `OMField`.
void EmitOMIRPass::emitSourceInfo(Location input, SmallString<64> &into) {
into.clear();
input->walk([&](Location loc) {
if (FileLineColLoc fileLoc = dyn_cast<FileLineColLoc>(loc)) {
into.append(into.empty() ? "@[" : " ");
(Twine(fileLoc.getFilename()) + " " + Twine(fileLoc.getLine()) + ":" +
Twine(fileLoc.getColumn()))
.toVector(into);
}
return WalkResult::advance();
});
if (!into.empty())
into.append("]");
else
into.append("UnlocatableSourceInfo");
}
/// Emit an entire `OMNode` as JSON.
void EmitOMIRPass::emitOMNode(Attribute node, llvm::json::OStream &jsonStream) {
auto dict = dyn_cast<DictionaryAttr>(node);
if (!dict) {
getOperation()
.emitError("OMNode must be a dictionary")
.attachNote(getOperation().getLoc())
<< node;
anyFailures = true;
return;
}
// Extract the `info` field and serialize the location.
SmallString<64> info;
if (auto infoAttr = dict.getAs<LocationAttr>("info"))
emitSourceInfo(infoAttr, info);
if (anyFailures)
return;
// Extract the `id` field.
auto idAttr = dict.getAs<StringAttr>("id");
if (!idAttr) {
getOperation()
.emitError("OMNode missing `id` string field")
.attachNote(getOperation().getLoc())
<< dict;
anyFailures = true;
return;
}
// Extract and order the fields of this node.
SmallVector<std::tuple<unsigned, StringAttr, DictionaryAttr>> orderedFields;
auto fieldsDict = dict.getAs<DictionaryAttr>("fields");
if (fieldsDict) {
for (auto nameAndField : fieldsDict.getValue()) {
auto fieldDict = dyn_cast<DictionaryAttr>(nameAndField.getValue());
if (!fieldDict) {
getOperation()
.emitError("OMField must be a dictionary")
.attachNote(getOperation().getLoc())
<< nameAndField.getValue();
anyFailures = true;
return;
}
unsigned index = 0;
if (auto indexAttr = fieldDict.getAs<IntegerAttr>("index"))
index = indexAttr.getValue().getLimitedValue();
orderedFields.push_back({index, nameAndField.getName(), fieldDict});
}
llvm::sort(orderedFields,
[](auto a, auto b) { return std::get<0>(a) < std::get<0>(b); });
}
jsonStream.object([&] {
jsonStream.attribute("info", info);
jsonStream.attribute("id", idAttr.getValue());
jsonStream.attributeArray("fields", [&] {
for (auto &orderedField : orderedFields) {
emitOMField(std::get<1>(orderedField), std::get<2>(orderedField),
jsonStream);
if (anyFailures)
return;
}
if (auto node = fieldsDict.getAs<DictionaryAttr>("containingModule"))
if (auto value = node.getAs<DictionaryAttr>("value"))
emitOptionalRTLPorts(value, jsonStream);
});
});
}
/// Emit a single `OMField` as JSON. This expects the field's name to be
/// provided from the outside, for example as the field name that this attribute
/// has in the surrounding dictionary.
void EmitOMIRPass::emitOMField(StringAttr fieldName, DictionaryAttr field,
llvm::json::OStream &jsonStream) {
// Extract the `info` field and serialize the location.
auto infoAttr = field.getAs<LocationAttr>("info");
SmallString<64> info;
if (infoAttr)
emitSourceInfo(infoAttr, info);
if (anyFailures)
return;
jsonStream.object([&] {
jsonStream.attribute("info", info);
jsonStream.attribute("name", fieldName.strref());
jsonStream.attributeBegin("value");
emitValue(field.get("value"), jsonStream,
fieldName.strref() == "dutInstance");
jsonStream.attributeEnd();
});
}
// If the given `node` refers to a valid tracker in the IR, gather the
// additional port metadata of the module it refers to. Then emit this port
// metadata as a `ports` array field for the surrounding `OMNode`.
void EmitOMIRPass::emitOptionalRTLPorts(DictionaryAttr node,
llvm::json::OStream &jsonStream) {
// First make sure we actually have a valid tracker. If not, just silently
// abort and don't emit any port metadata.
auto idAttr = node.getAs<IntegerAttr>("id");
auto trackerIt = trackers.find(idAttr);
if (!idAttr || !node.getAs<UnitAttr>("omir.tracker") ||
trackerIt == trackers.end())
return;
auto tracker = trackerIt->second;
// Lookup the module the tracker refers to. If it points at something *within*
// a module, go dig up the surrounding module. This is roughly what
// `Target.referringModule(...)` does on the Scala side.
auto module = dyn_cast<FModuleLike>(tracker.op);
if (!module)
module = tracker.op->getParentOfType<FModuleLike>();
if (!module) {
LLVM_DEBUG(llvm::dbgs() << "Not emitting RTL ports since tracked operation "
"does not have a FModuleLike parent: "
<< *tracker.op << "\n");
return;
}
LLVM_DEBUG(llvm::dbgs() << "Emitting RTL ports for module `"
<< module.getModuleName() << "`\n");
// Emit the JSON.
SmallString<64> buf;
jsonStream.object([&] {
buf.clear();
emitSourceInfo(module.getLoc(), buf);
jsonStream.attribute("info", buf);
jsonStream.attribute("name", "ports");
jsonStream.attributeArray("value", [&] {
for (const auto &port : llvm::enumerate(module.getPorts())) {
auto portType = type_dyn_cast<FIRRTLBaseType>(port.value().type);
if (!portType || portType.getBitWidthOrSentinel() == 0)
continue;
jsonStream.object([&] {
// Emit the `ref` field.
buf.assign("OMDontTouchedReferenceTarget:~");
if (module.getModuleNameAttr() == dutModuleName) {
// If module is DUT, then root the target relative to the DUT.
buf.append(module.getModuleName());
} else {
buf.append(getOperation().getName());
}
buf.push_back('|');
buf.append(addSymbol(module));
buf.push_back('>');
buf.append(addSymbol(getInnerRefTo(module, port.index())));
jsonStream.attribute("ref", buf);
// Emit the `direction` field.
buf.assign("OMString:");
buf.append(port.value().isOutput() ? "Output" : "Input");
jsonStream.attribute("direction", buf);
// Emit the `width` field.
buf.assign("OMBigInt:");
Twine::utohexstr(portType.getBitWidthOrSentinel()).toVector(buf);
jsonStream.attribute("width", buf);
});
}
});
});
}
void EmitOMIRPass::emitValue(Attribute node, llvm::json::OStream &jsonStream,
bool dutInstance) {
// Handle the null case.
if (!node || isa<UnitAttr>(node))
return jsonStream.value(nullptr);
// Handle the trivial cases where the OMIR serialization simply uses the
// builtin JSON types.
if (auto attr = dyn_cast<BoolAttr>(node))
return jsonStream.value(attr.getValue()); // OMBoolean
if (auto attr = dyn_cast<IntegerAttr>(node)) {
// CAVEAT: We expect these integers to come from an OMIR file that is
// initially read in from JSON, where they are i32 or i64, so this should
// yield a valid value. However, a user could cook up an arbitrary precision
// integer attr in MLIR input and then subtly break the JSON spec.