CIRCT 21.0.0git
Loading...
Searching...
No Matches
FIRRTLIntrinsics.cpp
Go to the documentation of this file.
1//===- FIRRTLIntrinsics.cpp - Lower Intrinsics ------------------*- C++ -*-===//
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
14#include "circt/Support/JSON.h"
15#include "mlir/Transforms/DialectConversion.h"
16#include "llvm/Support/JSON.h"
17
18using namespace circt;
19using namespace firrtl;
20
21// vtable anchor
23
24//===----------------------------------------------------------------------===//
25// GenericIntrinsic
26//===----------------------------------------------------------------------===//
27
28// Checks for a number of operands between n and n+c (allows for c optional
29// inputs)
30ParseResult GenericIntrinsic::hasNInputs(unsigned n, unsigned c) {
31 auto numOps = op.getNumOperands();
32 unsigned m = n + c;
33 if (numOps < n || numOps > m) {
34 auto err = emitError() << " has " << numOps << " inputs instead of ";
35 if (c == 0)
36 err << n;
37 else
38 err << " between " << n << " and " << m;
39 return failure();
40 }
41 return success();
42}
43
44// Accessor method for the number of inputs
45unsigned GenericIntrinsic::getNumInputs() { return op.getNumOperands(); }
46
47ParseResult GenericIntrinsic::hasNOutputElements(unsigned n) {
48 auto b = getOutputBundle();
49 if (!b)
50 return emitError() << " missing output bundle";
51 if (b.getType().getNumElements() != n)
52 return emitError() << " has " << b.getType().getNumElements()
53 << " output elements instead of " << n;
54 return success();
55}
56
57ParseResult GenericIntrinsic::hasNParam(unsigned n, unsigned c) {
58 unsigned num = 0;
59 if (op.getParameters())
60 num = op.getParameters().size();
61 if (num < n || num > n + c) {
62 auto d = emitError() << " has " << num << " parameters instead of ";
63 if (c == 0)
64 d << n;
65 else
66 d << " between " << n << " and " << (n + c);
67 return failure();
68 }
69 return success();
70}
71
72ParseResult GenericIntrinsic::namedParam(StringRef paramName, bool optional) {
73 for (auto a : op.getParameters()) {
74 auto param = cast<ParamDeclAttr>(a);
75 if (param.getName().getValue() == paramName) {
76 if (isa<StringAttr>(param.getValue()))
77 return success();
78
79 return emitError() << " has parameter '" << param.getName()
80 << "' which should be a string but is not";
81 }
82 }
83 if (optional)
84 return success();
85 return emitError() << " is missing parameter " << paramName;
86}
87
88ParseResult GenericIntrinsic::namedIntParam(StringRef paramName,
89 bool optional) {
90 for (auto a : op.getParameters()) {
91 auto param = cast<ParamDeclAttr>(a);
92 if (param.getName().getValue() == paramName) {
93 if (isa<IntegerAttr>(param.getValue()))
94 return success();
95
96 return emitError() << " has parameter '" << param.getName()
97 << "' which should be an integer but is not";
98 }
99 }
100 if (optional)
101 return success();
102 return emitError() << " is missing parameter " << paramName;
103}
104
105//===----------------------------------------------------------------------===//
106// IntrinsicOpConversion
107//===----------------------------------------------------------------------===//
108
109/// Conversion pattern adaptor dispatching via generic intrinsic name.
110namespace {
111class IntrinsicOpConversion final
112 : public OpConversionPattern<GenericIntrinsicOp> {
113public:
114 using ConversionMapTy = IntrinsicLowerings::ConversionMapTy;
115
116 IntrinsicOpConversion(TypeConverter &typeConverter, MLIRContext *context,
117 const ConversionMapTy &conversions,
118 size_t &numConversions,
119 bool allowUnknownIntrinsics = false)
120 : OpConversionPattern(typeConverter, context), conversions(conversions),
121 numConversions(numConversions),
122 allowUnknownIntrinsics(allowUnknownIntrinsics) {}
123
124 LogicalResult
125 matchAndRewrite(GenericIntrinsicOp op, OpAdaptor adaptor,
126 ConversionPatternRewriter &rewriter) const override {
127
128 auto it = conversions.find(op.getIntrinsicAttr());
129 if (it == conversions.end()) {
130 if (!allowUnknownIntrinsics)
131 return op.emitError("unknown intrinsic ") << op.getIntrinsicAttr();
132 return failure();
133 }
134
135 auto &conv = *it->second;
136 auto result = conv.checkAndConvert(GenericIntrinsic(op), adaptor, rewriter);
137 if (succeeded(result))
138 ++numConversions;
139 return result;
140 }
141
142private:
143 const ConversionMapTy &conversions;
144 size_t &numConversions;
145 const bool allowUnknownIntrinsics;
146};
147} // namespace
148
149//===----------------------------------------------------------------------===//
150// IntrinsicLowerings
151//===----------------------------------------------------------------------===//
152
153FailureOr<size_t> IntrinsicLowerings::lower(FModuleOp mod,
154 bool allowUnknownIntrinsics) {
155
156 ConversionTarget target(*context);
157
158 target.markUnknownOpDynamicallyLegal([](Operation *op) { return true; });
159 if (allowUnknownIntrinsics)
160 target.addDynamicallyLegalOp<GenericIntrinsicOp>(
161 [this](GenericIntrinsicOp op) {
162 return !conversions.contains(op.getIntrinsicAttr());
163 });
164 else
165 target.addIllegalOp<GenericIntrinsicOp>();
166
167 // Automatically insert wires + connect for compatible FIRRTL base types.
168 // For now, this is not customizable/extendable.
169 TypeConverter typeConverter;
170 typeConverter.addConversion([](Type type) { return type; });
171 auto firrtlBaseTypeMaterialization =
172 [](OpBuilder &builder, FIRRTLBaseType resultType, ValueRange inputs,
173 Location loc) -> Value {
174 if (inputs.size() != 1)
175 return {};
176 auto inputType = type_dyn_cast<FIRRTLBaseType>(inputs.front().getType());
177 if (!inputType)
178 return {};
179
180 if (!areTypesEquivalent(resultType, inputType) ||
181 !isTypeLarger(resultType, inputType))
182 return {};
183
184 auto w = builder.create<WireOp>(loc, resultType).getResult();
185 emitConnect(builder, loc, w, inputs.front());
186 return w;
187 };
188 // New result doesn't match? Add wire + connect.
189 typeConverter.addSourceMaterialization(firrtlBaseTypeMaterialization);
190 // New operand doesn't match? Add wire + connect.
191 typeConverter.addTargetMaterialization(firrtlBaseTypeMaterialization);
192
193 RewritePatternSet patterns(context);
194 size_t count = 0;
195 patterns.add<IntrinsicOpConversion>(typeConverter, context, conversions,
196 count, allowUnknownIntrinsics);
197
198 if (failed(mlir::applyPartialConversion(mod, target, std::move(patterns))))
199 return failure();
200
201 return count;
202}
203
204//===----------------------------------------------------------------------===//
205// IntrinsicLoweringInterfaceCollection
206//===----------------------------------------------------------------------===//
207
209 IntrinsicLowerings &lowering) const {
210 for (const IntrinsicLoweringDialectInterface &interface : *this)
211 interface.populateIntrinsicLowerings(lowering);
212}
213
214//===----------------------------------------------------------------------===//
215// FIRRTL intrinsic lowering converters
216//===----------------------------------------------------------------------===//
217
218namespace {
219
220class CirctSizeofConverter : public IntrinsicOpConverter<SizeOfIntrinsicOp> {
221public:
222 using IntrinsicOpConverter::IntrinsicOpConverter;
223
224 bool check(GenericIntrinsic gi) override {
225 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(32) || gi.hasNParam(0);
226 }
227};
228
229class CirctIsXConverter : public IntrinsicOpConverter<IsXIntrinsicOp> {
230public:
231 using IntrinsicOpConverter::IntrinsicOpConverter;
232
233 bool check(GenericIntrinsic gi) override {
234 return gi.hasNInputs(1) || gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
235 }
236};
237
238class CirctPlusArgTestConverter : public IntrinsicConverter {
239public:
240 using IntrinsicConverter::IntrinsicConverter;
241
242 bool check(GenericIntrinsic gi) override {
243 return gi.hasNInputs(0) || gi.sizedOutput<UIntType>(1) ||
244 gi.namedParam("FORMAT") || gi.hasNParam(1);
245 }
246
247 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
248 PatternRewriter &rewriter) override {
249 rewriter.replaceOpWithNewOp<PlusArgsTestIntrinsicOp>(
250 gi.op, gi.getParamValue<StringAttr>("FORMAT"));
251 }
252};
253
254class CirctPlusArgValueConverter : public IntrinsicConverter {
255public:
256 using IntrinsicConverter::IntrinsicConverter;
257
258 bool check(GenericIntrinsic gi) override {
259 return gi.hasNOutputElements(2) ||
260 gi.sizedOutputElement<UIntType>(0, "found", 1) ||
261 gi.hasOutputElement(1, "result") || gi.namedParam("FORMAT") ||
262 gi.hasNParam(1);
263 }
264
265 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
266 PatternRewriter &rewriter) override {
267 auto bty = gi.getOutputBundle().getType();
268 auto newop = rewriter.create<PlusArgsValueIntrinsicOp>(
269 gi.op.getLoc(), bty.getElementTypePreservingConst(0),
270 bty.getElementTypePreservingConst(1),
271 gi.getParamValue<StringAttr>("FORMAT"));
272 rewriter.replaceOpWithNewOp<BundleCreateOp>(
273 gi.op, bty, ValueRange({newop.getFound(), newop.getResult()}));
274 }
275};
276
277class CirctClockGateConverter
278 : public IntrinsicOpConverter<ClockGateIntrinsicOp> {
279public:
280 using IntrinsicOpConverter::IntrinsicOpConverter;
281
282 bool check(GenericIntrinsic gi) override {
283 if (gi.op.getNumOperands() == 3) {
284 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
285 gi.sizedInput<UIntType>(2, 1) || gi.typedOutput<ClockType>() ||
286 gi.hasNParam(0);
287 }
288 if (gi.op.getNumOperands() == 2) {
289 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
290 gi.typedOutput<ClockType>() || gi.hasNParam(0);
291 }
292 gi.emitError() << " has " << gi.op.getNumOperands()
293 << " ports instead of 3 or 4";
294 return true;
295 }
296};
297
298class CirctClockInverterConverter
299 : public IntrinsicOpConverter<ClockInverterIntrinsicOp> {
300public:
301 using IntrinsicOpConverter::IntrinsicOpConverter;
302
303 bool check(GenericIntrinsic gi) override {
304 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
305 gi.typedOutput<ClockType>() || gi.hasNParam(0);
306 }
307};
308
309class CirctClockDividerConverter : public IntrinsicConverter {
310public:
311 using IntrinsicConverter::IntrinsicConverter;
312
313 bool check(GenericIntrinsic gi) override {
314 return gi.hasNInputs(1) || gi.typedInput<ClockType>(0) ||
315 gi.typedOutput<ClockType>() || gi.namedIntParam("POW_2") ||
316 gi.hasNParam(1);
317 }
318
319 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
320 PatternRewriter &rewriter) override {
321 auto pow2 =
322 gi.getParamValue<IntegerAttr>("POW_2").getValue().getZExtValue();
323
324 auto pow2Attr = rewriter.getI64IntegerAttr(pow2);
325
326 rewriter.replaceOpWithNewOp<ClockDividerIntrinsicOp>(
327 gi.op, adaptor.getOperands()[0], pow2Attr);
328 }
329};
330
331template <typename OpTy>
332class CirctLTLBinaryConverter : public IntrinsicOpConverter<OpTy> {
333public:
335
336 bool check(GenericIntrinsic gi) override {
337 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
338 gi.sizedInput<UIntType>(1, 1) || gi.sizedOutput<UIntType>(1) ||
339 gi.hasNParam(0);
340 }
341};
342
343template <typename OpTy>
344class CirctLTLUnaryConverter : public IntrinsicOpConverter<OpTy> {
345public:
347
348 bool check(GenericIntrinsic gi) override {
349 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
350 gi.sizedOutput<UIntType>(1) || gi.hasNParam(0);
351 }
352};
353
354class CirctLTLDelayConverter : public IntrinsicConverter {
355public:
356 using IntrinsicConverter::IntrinsicConverter;
357
358 bool check(GenericIntrinsic gi) override {
359 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
360 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
361 gi.namedIntParam("length", true) || gi.hasNParam(1, 1);
362 }
363
364 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
365 PatternRewriter &rewriter) override {
366 auto getI64Attr = [&](IntegerAttr val) {
367 if (!val)
368 return IntegerAttr();
369 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
370 };
371 auto delay = getI64Attr(gi.getParamValue<IntegerAttr>("delay"));
372 auto length = getI64Attr(gi.getParamValue<IntegerAttr>("length"));
373 rewriter.replaceOpWithNewOp<LTLDelayIntrinsicOp>(
374 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], delay, length);
375 }
376};
377
378class CirctLTLClockConverter
379 : public IntrinsicOpConverter<LTLClockIntrinsicOp> {
380public:
381 using IntrinsicOpConverter::IntrinsicOpConverter;
382
383 bool check(GenericIntrinsic gi) override {
384 return gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
385 gi.typedInput<ClockType>(1) || gi.sizedOutput<UIntType>(1) ||
386 gi.hasNParam(0);
387 }
388};
389
390class CirctLTLRepeatConverter : public IntrinsicConverter {
391public:
392 using IntrinsicConverter::IntrinsicConverter;
393
394 bool check(GenericIntrinsic gi) override {
395 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
396 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
397 gi.namedIntParam("more", true) || gi.hasNParam(1, 1);
398 }
399
400 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
401 PatternRewriter &rewriter) override {
402 auto getI64Attr = [&](IntegerAttr val) {
403 if (!val)
404 return IntegerAttr();
405 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
406 };
407 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
408 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
409 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
410 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
411 }
412};
413
414class CirctLTLGoToRepeatConverter : public IntrinsicConverter {
415public:
416 using IntrinsicConverter::IntrinsicConverter;
417
418 bool check(GenericIntrinsic gi) override {
419 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
420 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
421 gi.namedIntParam("more") || gi.hasNParam(1, 1);
422 }
423
424 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
425 PatternRewriter &rewriter) override {
426 auto getI64Attr = [&](IntegerAttr val) {
427 if (!val)
428 return IntegerAttr();
429 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
430 };
431 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
432 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
433 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
434 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
435 }
436};
437
438class CirctLTLNonConsecutiveRepeatConverter : public IntrinsicConverter {
439public:
440 using IntrinsicConverter::IntrinsicConverter;
441
442 bool check(GenericIntrinsic gi) override {
443 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
444 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
445 gi.namedIntParam("more") || gi.hasNParam(1, 1);
446 }
447
448 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
449 PatternRewriter &rewriter) override {
450 auto getI64Attr = [&](IntegerAttr val) {
451 if (!val)
452 return IntegerAttr();
453 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
454 };
455 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
456 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
457 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
458 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
459 }
460};
461
462template <class Op>
463class CirctVerifConverter : public IntrinsicConverter {
464public:
465 using IntrinsicConverter::IntrinsicConverter;
466
467 bool check(GenericIntrinsic gi) override {
468 return gi.hasNInputs(1, 2) || gi.sizedInput<UIntType>(0, 1) ||
469 gi.namedParam("label", true) || gi.hasNParam(0, 1) ||
470 gi.hasNoOutput();
471 }
472
473 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
474 PatternRewriter &rewriter) override {
475 auto label = gi.getParamValue<StringAttr>("label");
476 auto operands = adaptor.getOperands();
477
478 // Check if an enable was provided
479 Value enable;
480 if (gi.getNumInputs() == 2)
481 enable = operands[1];
482
483 rewriter.replaceOpWithNewOp<Op>(gi.op, operands[0], enable, label);
484 }
485};
486
487class CirctMux2CellConverter : public IntrinsicConverter {
488 using IntrinsicConverter::IntrinsicConverter;
489
490 bool check(GenericIntrinsic gi) override {
491 return gi.hasNInputs(3) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
492 gi.hasOutput();
493 }
494
495 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
496 PatternRewriter &rewriter) override {
497 auto operands = adaptor.getOperands();
498 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.op, operands[0],
499 operands[1], operands[2]);
500 }
501};
502
503class CirctMux4CellConverter : public IntrinsicConverter {
504 using IntrinsicConverter::IntrinsicConverter;
505
506 bool check(GenericIntrinsic gi) override {
507 return gi.hasNInputs(5) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
508 gi.hasOutput();
509 }
510
511 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
512 PatternRewriter &rewriter) override {
513 auto operands = adaptor.getOperands();
514 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
515 gi.op, operands[0], operands[1], operands[2], operands[3], operands[4]);
516 }
517};
518
519class CirctHasBeenResetConverter
520 : public IntrinsicOpConverter<HasBeenResetIntrinsicOp> {
521public:
522 using IntrinsicOpConverter::IntrinsicOpConverter;
523
524 bool check(GenericIntrinsic gi) override {
525 return gi.hasNInputs(2) || gi.typedInput<ClockType>(0) ||
526 gi.hasResetInput(1) || gi.sizedOutput<UIntType>(1) ||
527 gi.hasNParam(0);
528 }
529};
530
531class CirctProbeConverter : public IntrinsicOpConverter<FPGAProbeIntrinsicOp> {
532public:
533 using IntrinsicOpConverter::IntrinsicOpConverter;
534
535 bool check(GenericIntrinsic gi) override {
536 return gi.hasNInputs(2) || gi.typedInput<ClockType>(1) || gi.hasNParam(0) ||
537 gi.hasNoOutput();
538 }
539};
540
541template <class OpTy, bool ifElseFatal = false>
542class CirctAssertConverter : public IntrinsicConverter {
543public:
544 using IntrinsicConverter::IntrinsicConverter;
545
546 bool check(GenericIntrinsic gi) override {
547 return gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
548 gi.sizedInput<UIntType>(2, 1) ||
549 gi.namedParam("format", /*optional=*/true) ||
550 gi.namedParam("label", /*optional=*/true) ||
551 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
552 gi.hasNoOutput();
553 }
554
555 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
556 PatternRewriter &rewriter) override {
557 auto format = gi.getParamValue<StringAttr>("format");
558 auto label = gi.getParamValue<StringAttr>("label");
559 auto guards = gi.getParamValue<StringAttr>("guards");
560
561 auto clock = adaptor.getOperands()[0];
562 auto predicate = adaptor.getOperands()[1];
563 auto enable = adaptor.getOperands()[2];
564
565 auto substitutions = adaptor.getOperands().drop_front(3);
566 auto name = label ? label.strref() : "";
567 // Message is not optional, so provide empty string if not present.
568 auto message = format ? format : rewriter.getStringAttr("");
569 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
570 gi.op, clock, predicate, enable, message, substitutions, name,
571 /*isConcurrent=*/true);
572 if (guards) {
573 SmallVector<StringRef> guardStrings;
574 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
575 /*KeepEmpty=*/false);
576 rewriter.startOpModification(op);
577 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
578 rewriter.finalizeOpModification(op);
579 }
580
581 if constexpr (ifElseFatal) {
582 rewriter.startOpModification(op);
583 op->setAttr("format", rewriter.getStringAttr("ifElseFatal"));
584 rewriter.finalizeOpModification(op);
585 }
586 }
587};
588
589class CirctCoverConverter : public IntrinsicConverter {
590public:
591 using IntrinsicConverter::IntrinsicConverter;
592
593 bool check(GenericIntrinsic gi) override {
594 return gi.hasNInputs(3) || gi.hasNoOutput() ||
595 gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
596 gi.sizedInput<UIntType>(2, 1) ||
597 gi.namedParam("label", /*optional=*/true) ||
598 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 2);
599 }
600
601 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
602 PatternRewriter &rewriter) override {
603 auto label = gi.getParamValue<StringAttr>("label");
604 auto guards = gi.getParamValue<StringAttr>("guards");
605
606 auto clock = adaptor.getOperands()[0];
607 auto predicate = adaptor.getOperands()[1];
608 auto enable = adaptor.getOperands()[2];
609
610 auto name = label ? label.strref() : "";
611 // Empty message string for cover, only 'name' / label.
612 auto message = rewriter.getStringAttr("");
613 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
614 gi.op, clock, predicate, enable, message, ValueRange{}, name,
615 /*isConcurrent=*/true);
616 if (guards) {
617 SmallVector<StringRef> guardStrings;
618 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
619 /*KeepEmpty=*/false);
620 rewriter.startOpModification(op);
621 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
622 rewriter.finalizeOpModification(op);
623 }
624 }
625};
626
627class CirctUnclockedAssumeConverter : public IntrinsicConverter {
628public:
629 using IntrinsicConverter::IntrinsicConverter;
630
631 bool check(GenericIntrinsic gi) override {
632 return gi.sizedInput<UIntType>(0, 1) || gi.sizedInput<UIntType>(1, 1) ||
633 gi.namedParam("format", /*optional=*/true) ||
634 gi.namedParam("label", /*optional=*/true) ||
635 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
636 gi.hasNoOutput();
637 }
638
639 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
640 PatternRewriter &rewriter) override {
641 auto format = gi.getParamValue<StringAttr>("format");
642 auto label = gi.getParamValue<StringAttr>("label");
643 auto guards = gi.getParamValue<StringAttr>("guards");
644
645 auto predicate = adaptor.getOperands()[0];
646 auto enable = adaptor.getOperands()[1];
647
648 auto substitutions = adaptor.getOperands().drop_front(2);
649 auto name = label ? label.strref() : "";
650 // Message is not optional, so provide empty string if not present.
651 auto message = format ? format : rewriter.getStringAttr("");
652 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
653 gi.op, predicate, enable, message, substitutions, name);
654 if (guards) {
655 SmallVector<StringRef> guardStrings;
656 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
657 /*KeepEmpty=*/false);
658 rewriter.startOpModification(op);
659 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
660 rewriter.finalizeOpModification(op);
661 }
662 }
663};
664
665class CirctDPICallConverter : public IntrinsicConverter {
666 static bool getIsClocked(GenericIntrinsic gi) {
667 return !gi.getParamValue<IntegerAttr>("isClocked").getValue().isZero();
668 }
669
670public:
671 using IntrinsicConverter::IntrinsicConverter;
672
673 bool check(GenericIntrinsic gi) override {
674 if (gi.hasNParam(2, 2) || gi.namedIntParam("isClocked") ||
675 gi.namedParam("functionName") ||
676 gi.namedParam("inputNames", /*optional=*/true) ||
677 gi.namedParam("outputName", /*optional=*/true))
678 return true;
679 auto isClocked = getIsClocked(gi);
680 // If clocked, the first operand must be a clock.
681 if (isClocked && gi.typedInput<ClockType>(0))
682 return true;
683 // Enable must be UInt<1>.
684 if (gi.sizedInput<UIntType>(isClocked, 1))
685 return true;
686
687 return false;
688 }
689
690 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
691 PatternRewriter &rewriter) override {
692 auto isClocked = getIsClocked(gi);
693 auto functionName = gi.getParamValue<StringAttr>("functionName");
694 ArrayAttr inputNamesStrArray;
695 StringAttr outputStr = gi.getParamValue<StringAttr>("outputName");
696 if (auto inputNames = gi.getParamValue<StringAttr>("inputNames")) {
697 SmallVector<StringRef> inputNamesTemporary;
698 inputNames.strref().split(inputNamesTemporary, ';', /*MaxSplit=*/-1,
699 /*KeepEmpty=*/false);
700 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
701 }
702 // Clock and enable are optional.
703 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
704 Value enable = adaptor.getOperands()[static_cast<size_t>(isClocked)];
705
706 auto inputs =
707 adaptor.getOperands().drop_front(static_cast<size_t>(isClocked) + 1);
708
709 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
710 gi.op, gi.op.getResultTypes(), functionName, inputNamesStrArray,
711 outputStr, clock, enable, inputs);
712 }
713};
714
715//===----------------------------------------------------------------------===//
716// View intrinsic converter and helpers
717//===----------------------------------------------------------------------===//
718
719template <typename A>
720A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
721 Twine path = Twine()) {
722 return tryGetAsBase<A>(dict, root, key, loc, "View 'info'",
723 "'info' attribute", path);
724}
725
726/// Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract
727/// and slightly restructure information needed for a view.
728std::optional<DictionaryAttr>
729parseAugmentedType(MLIRContext *context, Location loc,
730 DictionaryAttr augmentedType, DictionaryAttr root,
731 StringAttr name, StringAttr defName,
732 std::optional<StringAttr> description, Twine path = {}) {
733 auto classAttr =
734 tryGetAs<StringAttr>(augmentedType, root, "class", loc, path);
735 if (!classAttr)
736 return std::nullopt;
737 StringRef classBase = classAttr.getValue();
738 if (!classBase.consume_front("sifive.enterprise.grandcentral.Augmented")) {
739 mlir::emitError(loc,
740 "the 'class' was expected to start with "
741 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
742 classAttr.getValue() + "' (Did you misspell it?)")
743 .attachNote()
744 << "see attribute: " << augmentedType;
745 return std::nullopt;
746 }
747
748 // An AugmentedBundleType looks like:
749 // "defName": String
750 // "elements": Seq[AugmentedField]
751 if (classBase == "BundleType") {
752 defName = tryGetAs<StringAttr>(augmentedType, root, "defName", loc, path);
753 if (!defName)
754 return std::nullopt;
755
756 // Each element is an AugmentedField with members:
757 // "name": String
758 // "description": Option[String]
759 // "tpe": AugmentedType
760 SmallVector<Attribute> elements;
761 auto elementsAttr =
762 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
763 if (!elementsAttr)
764 return std::nullopt;
765 for (size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
766 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
767 if (!field) {
768 mlir::emitError(
769 loc,
770 "View 'info' attribute with path '.elements[" + Twine(i) +
771 "]' contained an unexpected type (expected a DictionaryAttr).")
772 .attachNote()
773 << "The received element was: " << elementsAttr[i];
774 return std::nullopt;
775 }
776 auto ePath = (path + ".elements[" + Twine(i) + "]").str();
777 auto name = tryGetAs<StringAttr>(field, root, "name", loc, ePath);
778 if (!name)
779 return std::nullopt;
780 auto tpe = tryGetAs<DictionaryAttr>(field, root, "tpe", loc, ePath);
781 if (!tpe)
782 return std::nullopt;
783 std::optional<StringAttr> description;
784 if (auto maybeDescription = field.get("description"))
785 description = cast<StringAttr>(maybeDescription);
786 auto eltAttr =
787 parseAugmentedType(context, loc, tpe, root, name, defName,
788 description, path + "_" + name.getValue());
789 if (!eltAttr)
790 return std::nullopt;
791
792 // Collect information necessary to build a module with this view later.
793 // This includes the optional description and name.
794 NamedAttrList attrs;
795 if (auto maybeDescription = field.get("description"))
796 attrs.append("description", cast<StringAttr>(maybeDescription));
797 attrs.append("name", name);
798 auto tpeClass = tpe.getAs<StringAttr>("class");
799 if (!tpeClass) {
800 mlir::emitError(loc, "missing 'class' key in") << tpe;
801 return std::nullopt;
802 }
803 attrs.append("tpe", tpeClass);
804 elements.push_back(*eltAttr);
805 }
806 // Add an attribute that stores information necessary to construct the
807 // interface for the view. This needs the name of the interface (defName)
808 // and the names of the components inside it.
809 NamedAttrList attrs;
810 attrs.append("class", classAttr);
811 attrs.append("defName", defName);
812 if (description)
813 attrs.append("description", *description);
814 attrs.append("elements", ArrayAttr::get(context, elements));
815 attrs.append("name", name);
816 return DictionaryAttr::getWithSorted(context, attrs);
817 }
818
819 // An AugmentedGroundType has no contents.
820 if (classBase == "GroundType") {
821 NamedAttrList elementIface;
822
823 // Populate the attribute for the interface element.
824 elementIface.append("class", classAttr);
825 if (description)
826 elementIface.append("description", *description);
827 elementIface.append("name", name);
828
829 return DictionaryAttr::getWithSorted(context, elementIface);
830 }
831
832 // An AugmentedVectorType looks like:
833 // "elements": Seq[AugmentedType]
834 if (classBase == "VectorType") {
835 auto elementsAttr =
836 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
837 if (!elementsAttr)
838 return std::nullopt;
839 SmallVector<Attribute> elements;
840 for (auto [i, elt] : llvm::enumerate(elementsAttr)) {
841 auto eltAttr = parseAugmentedType(
842 context, loc, cast<DictionaryAttr>(elt), root, name,
843 StringAttr::get(context, ""), std::nullopt, path + "_" + Twine(i));
844 if (!eltAttr)
845 return std::nullopt;
846 elements.push_back(*eltAttr);
847 }
848 NamedAttrList attrs;
849 attrs.append("class", classAttr);
850 if (description)
851 attrs.append("description", *description);
852 attrs.append("elements", ArrayAttr::get(context, elements));
853 attrs.append("name", name);
854 return DictionaryAttr::getWithSorted(context, attrs);
855 }
856
857 // Anything else is unexpected or a user error if they manually wrote
858 // the JSON/attribute. Print an error and error out.
859 mlir::emitError(loc, "found unknown AugmentedType '" + classAttr.getValue() +
860 "' (Did you misspell it?)")
861 .attachNote()
862 << "see attribute: " << augmentedType;
863 return std::nullopt;
864}
865
866class ViewConverter : public IntrinsicConverter {
867public:
868 LogicalResult checkAndConvert(GenericIntrinsic gi,
869 GenericIntrinsicOpAdaptor adaptor,
870 PatternRewriter &rewriter) override {
871 // Check structure of the intrinsic.
872 if (gi.hasNoOutput() || gi.namedParam("info") || gi.namedParam("name") ||
873 gi.namedParam("yaml", true))
874 return failure();
875
876 // Check operands.
877 for (auto idx : llvm::seq(gi.getNumInputs()))
878 if (gi.checkInputType(idx, "must be ground type", [](auto ty) {
879 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
880 return base && base.isGround();
881 }))
882 return failure();
883
884 // Parse "info" string parameter as JSON.
885 auto view =
886 llvm::json::parse(gi.getParamValue<StringAttr>("info").getValue());
887 if (auto err = view.takeError()) {
888 handleAllErrors(std::move(err), [&](const llvm::json::ParseError &a) {
889 gi.emitError() << ": error parsing view JSON: " << a.message();
890 });
891 return failure();
892 }
893
894 // Convert JSON to MLIR attribute.
895 llvm::json::Path::Root root;
896 auto value = convertJSONToAttribute(gi.op.getContext(), view.get(), root);
897 assert(value && "JSON to attribute failed but should not ever fail");
898
899 // Check attribute is a dictionary, for AugmentedBundleTypeAttr
900 // construction.
901 auto dict = dyn_cast<DictionaryAttr>(value);
902 if (!dict)
903 return gi.emitError() << ": 'info' parameter must be a dictionary";
904
905 auto nameAttr = gi.getParamValue<StringAttr>("name");
906 auto result = parseAugmentedType(
907 gi.op.getContext(), gi.op.getLoc(), dict, dict, nameAttr,
908 /* defName= */ {}, /* description= */ std::nullopt);
909
910 if (!result)
911 return failure();
912
913 // Build AugmentedBundleTypeAttr, unchecked.
914 auto augmentedType =
915 AugmentedBundleTypeAttr::get(gi.op.getContext(), *result);
916 if (augmentedType.getClass() != augmentedBundleTypeClass)
917 return gi.emitError() << ": 'info' must be augmented bundle";
918
919 // Scan for ground-type (leaves) and count.
920 SmallVector<DictionaryAttr> worklist;
921 worklist.push_back(augmentedType.getUnderlying());
922 size_t numLeaves = 0;
923 auto augGroundAttr =
924 StringAttr::get(gi.op.getContext(), augmentedGroundTypeClass);
925 auto augBundleAttr =
926 StringAttr::get(gi.op.getContext(), augmentedBundleTypeClass);
927 auto augVectorAttr =
928 StringAttr::get(gi.op.getContext(), augmentedVectorTypeClass);
929 while (!worklist.empty()) {
930 auto dict = worklist.pop_back_val();
931 auto clazz = dict.getAs<StringAttr>("class");
932 if (clazz == augGroundAttr) {
933 ++numLeaves;
934 continue;
935 }
936 assert(clazz == augBundleAttr || clazz == augVectorAttr);
937 llvm::append_range(
938 worklist,
939 dict.getAs<ArrayAttr>("elements").getAsRange<DictionaryAttr>());
940 }
941
942 if (numLeaves != gi.getNumInputs())
943 return gi.emitError()
944 << " has " << gi.getNumInputs() << " operands but view 'info' has "
945 << numLeaves << " leaf elements";
946
947 // Check complete, convert!
948 auto yaml = gi.getParamValue<StringAttr>("yaml");
949 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
950 gi.op, nameAttr.getValue(), yaml, augmentedType, adaptor.getOperands());
951 return success();
952 }
953};
954
955} // namespace
956
957//===----------------------------------------------------------------------===//
958// FIRRTL intrinsic lowering dialect interface
959//===----------------------------------------------------------------------===//
960
962 IntrinsicLowerings &lowering) const {
963 lowering.add<CirctSizeofConverter>("circt.sizeof", "circt_sizeof");
964 lowering.add<CirctIsXConverter>("circt.isX", "circt_isX");
965 lowering.add<CirctPlusArgTestConverter>("circt.plusargs.test",
966 "circt_plusargs_test");
967 lowering.add<CirctPlusArgValueConverter>("circt.plusargs.value",
968 "circt_plusargs_value");
969 lowering.add<CirctClockGateConverter>("circt.clock_gate", "circt_clock_gate");
970 lowering.add<CirctClockInverterConverter>("circt.clock_inv",
971 "circt_clock_inv");
972 lowering.add<CirctClockDividerConverter>("circt.clock_div",
973 "circt_clock_div");
974 lowering.add<CirctLTLBinaryConverter<LTLAndIntrinsicOp>>("circt.ltl.and",
975 "circt_ltl_and");
976 lowering.add<CirctLTLBinaryConverter<LTLOrIntrinsicOp>>("circt.ltl.or",
977 "circt_ltl_or");
978 lowering.add<CirctLTLBinaryConverter<LTLIntersectIntrinsicOp>>(
979 "circt.ltl.intersect", "circt_ltl_intersect");
980 lowering.add<CirctLTLBinaryConverter<LTLConcatIntrinsicOp>>(
981 "circt.ltl.concat", "circt_ltl_concat");
982 lowering.add<CirctLTLBinaryConverter<LTLImplicationIntrinsicOp>>(
983 "circt.ltl.implication", "circt_ltl_implication");
984 lowering.add<CirctLTLBinaryConverter<LTLUntilIntrinsicOp>>("circt.ltl.until",
985 "circt_ltl_until");
986 lowering.add<CirctLTLUnaryConverter<LTLNotIntrinsicOp>>("circt.ltl.not",
987 "circt_ltl_not");
988 lowering.add<CirctLTLUnaryConverter<LTLEventuallyIntrinsicOp>>(
989 "circt.ltl.eventually", "circt_ltl_eventually");
990
991 lowering.add<CirctLTLDelayConverter>("circt.ltl.delay", "circt_ltl_delay");
992 lowering.add<CirctLTLRepeatConverter>("circt.ltl.repeat", "circt_ltl_repeat");
993 lowering.add<CirctLTLGoToRepeatConverter>("circt.ltl.goto_repeat",
994 "circt_ltl_goto_repeat");
995 lowering.add<CirctLTLNonConsecutiveRepeatConverter>(
996 "circt.ltl.non_consecutive_repeat", "circt_ltl_non_consecutive_repeat");
997 lowering.add<CirctLTLClockConverter>("circt.ltl.clock", "circt_ltl_clock");
998
999 lowering.add<CirctVerifConverter<VerifAssertIntrinsicOp>>(
1000 "circt.verif.assert", "circt_verif_assert");
1001 lowering.add<CirctVerifConverter<VerifAssumeIntrinsicOp>>(
1002 "circt.verif.assume", "circt_verif_assume");
1003 lowering.add<CirctVerifConverter<VerifCoverIntrinsicOp>>("circt.verif.cover",
1004 "circt_verif_cover");
1005 lowering.add<CirctVerifConverter<VerifRequireIntrinsicOp>>(
1006 "circt.verif.require", "circt_verif_require");
1007 lowering.add<CirctVerifConverter<VerifEnsureIntrinsicOp>>(
1008 "circt.verif.ensure", "circt_verif_ensure");
1009 lowering.add<CirctMux2CellConverter>("circt.mux2cell", "circt_mux2cell");
1010 lowering.add<CirctMux4CellConverter>("circt.mux4cell", "circt_mux4cell");
1011 lowering.add<CirctHasBeenResetConverter>("circt.has_been_reset",
1012 "circt_has_been_reset");
1013 lowering.add<CirctProbeConverter>("circt.fpga_probe", "circt_fpga_probe");
1014 lowering.add<CirctAssertConverter<AssertOp>>("circt.chisel_assert",
1015 "circt_chisel_assert");
1016 lowering.add<CirctAssertConverter<AssertOp, /*ifElseFatal=*/true>>(
1017 "circt.chisel_ifelsefatal", "circt_chisel_ifelsefatal");
1018 lowering.add<CirctAssertConverter<AssumeOp>>("circt.chisel_assume",
1019 "circt_chisel_assume");
1020 lowering.add<CirctCoverConverter>("circt.chisel_cover", "circt_chisel_cover");
1021 lowering.add<CirctUnclockedAssumeConverter>("circt.unclocked_assume",
1022 "circt_unclocked_assume");
1023 lowering.add<CirctDPICallConverter>("circt.dpi_call", "circt_dpi_call");
1024
1025 lowering.add<ViewConverter>("circt.view", "circt_view");
1026}
assert(baseType &&"element must be base type")
static std::optional< DictionaryAttr > parseAugmentedType(ApplyState &state, DictionaryAttr augmentedType, DictionaryAttr root, StringAttr name, StringAttr defName, std::optional< IntegerAttr > id, std::optional< StringAttr > description, Twine clazz, StringAttr companionAttr, Twine path={})
Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract any annotations it may con...
Base class for Intrinsic Converters.
Lowering helper which collects all intrinsic converters.
FailureOr< size_t > lower(FModuleOp mod, bool allowUnknownIntrinsics=false)
Lowers all intrinsics in a module. Returns number converted or failure.
llvm::DenseMap< StringAttr, std::unique_ptr< IntrinsicConverter > > ConversionMapTy
void add(Args... args)
Registers a converter to one or more intrinsic names.
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
constexpr const char * augmentedVectorTypeClass
constexpr const char * augmentedBundleTypeClass
A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc, Twine clazz, Twine path=Twine())
Implements the same behavior as DictionaryAttr::getAs<A> to return the value of a specific type assoc...
constexpr const char * augmentedGroundTypeClass
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
bool isTypeLarger(FIRRTLBaseType dstType, FIRRTLBaseType srcType)
Returns true if the destination is at least as wide as a source.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Attribute convertJSONToAttribute(MLIRContext *context, llvm::json::Value &value, llvm::json::Path p)
Convert arbitrary JSON to an MLIR Attribute.
Definition seq.py:1
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const override
Helper class for checking and extracting information from the generic instrinsic op.
ParseResult sizedInput(unsigned n, int32_t size)
mlir::TypedValue< BundleType > getOutputBundle()
T getParamValue(StringRef name)
Get parameter value by name, if present, as requested type.
ParseResult hasResetInput(unsigned n)
ParseResult typedInput(unsigned n)
ParseResult hasNOutputElements(unsigned n)
ParseResult namedIntParam(StringRef paramName, bool optional=false)
ParseResult namedParam(StringRef paramName, bool optional=false)
ParseResult sizedOutput(int32_t size)
ParseResult sizedOutputElement(unsigned n, StringRef name, int32_t size)
ParseResult hasNParam(unsigned n, unsigned c=0)
ParseResult hasOutputElement(unsigned n, StringRef name)
ParseResult hasNInputs(unsigned n, unsigned c=0)
A dialect interface to provide lowering conversions.
void populateIntrinsicLowerings(IntrinsicLowerings &lowerings) const