CIRCT 23.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 = WireOp::create(builder, 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 = PlusArgsValueIntrinsicOp::create(
269 rewriter, 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 CirctLTLPastConverter : public IntrinsicConverter {
379public:
380 using IntrinsicConverter::IntrinsicConverter;
381
382 bool check(GenericIntrinsic gi) override {
383 if (gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
384 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("delay") ||
385 gi.hasNParam(1))
386 return true;
387 if (gi.typedInput<ClockType>(1))
388 return true;
389 return false;
390 }
391
392 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
393 PatternRewriter &rewriter) override {
394 auto delay = rewriter.getI64IntegerAttr(
395 gi.getParamValue<IntegerAttr>("delay").getValue().getZExtValue());
396 auto operands = adaptor.getOperands();
397 Value clock = operands[1];
398 rewriter.replaceOpWithNewOp<LTLPastIntrinsicOp>(
399 gi.op, gi.op.getResultTypes(), operands[0], delay, clock);
400 }
401};
402
403class CirctLTLClockConverter : public IntrinsicConverter {
404public:
405 using IntrinsicConverter::IntrinsicConverter;
406
407 bool check(GenericIntrinsic gi) override {
408 if (gi.hasNInputs(2) || gi.sizedInput<UIntType>(0, 1) ||
409 gi.typedInput<ClockType>(1) || gi.sizedOutput<UIntType>(1) ||
410 gi.hasNParam(0, 1))
411 return true;
412
413 auto params = gi.op.getParameters();
414 if (!params || params.empty())
415 return false;
416
417 auto param = cast<ParamDeclAttr>(*params.begin());
418 if (param.getName().getValue() != "edge") {
419 gi.emitError() << " has unexpected parameter '" << param.getName()
420 << "', expected 'edge'";
421 return true;
422 }
423 if (!isa<StringAttr>(param.getValue())) {
424 gi.emitError() << " has parameter '" << param.getName()
425 << "' which should be a string but is not";
426 return true;
427 }
428 return false;
429 }
430
431 LogicalResult checkAndConvert(GenericIntrinsic gi,
432 GenericIntrinsicOpAdaptor adaptor,
433 PatternRewriter &rewriter) override {
434 if (check(gi))
435 return failure();
436
437 auto edge = EventControl::AtPosEdge;
438 if (auto edgeAttr = gi.getParamValue<StringAttr>("edge")) {
439 auto parsedEdge = symbolizeEventControl(edgeAttr.getValue());
440 if (!parsedEdge)
441 return gi.emitError()
442 << " has invalid edge parameter '" << edgeAttr.getValue()
443 << "', expected one of [posedge, negedge, edge]";
444 edge = *parsedEdge;
445 }
446
447 auto operands = adaptor.getOperands();
448 rewriter.replaceOpWithNewOp<LTLClockIntrinsicOp>(
449 gi.op, gi.op.getResultTypes(), operands[0],
450 EventControlAttr::get(rewriter.getContext(), edge), operands[1]);
451 return success();
452 }
453};
454
455class CirctLTLRepeatConverter : public IntrinsicConverter {
456public:
457 using IntrinsicConverter::IntrinsicConverter;
458
459 bool check(GenericIntrinsic gi) override {
460 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
461 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
462 gi.namedIntParam("more", true) || gi.hasNParam(1, 1);
463 }
464
465 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
466 PatternRewriter &rewriter) override {
467 auto getI64Attr = [&](IntegerAttr val) {
468 if (!val)
469 return IntegerAttr();
470 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
471 };
472 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
473 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
474 rewriter.replaceOpWithNewOp<LTLRepeatIntrinsicOp>(
475 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
476 }
477};
478
479class CirctLTLGoToRepeatConverter : public IntrinsicConverter {
480public:
481 using IntrinsicConverter::IntrinsicConverter;
482
483 bool check(GenericIntrinsic gi) override {
484 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
485 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
486 gi.namedIntParam("more") || gi.hasNParam(1, 1);
487 }
488
489 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
490 PatternRewriter &rewriter) override {
491 auto getI64Attr = [&](IntegerAttr val) {
492 if (!val)
493 return IntegerAttr();
494 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
495 };
496 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
497 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
498 rewriter.replaceOpWithNewOp<LTLGoToRepeatIntrinsicOp>(
499 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
500 }
501};
502
503class CirctLTLNonConsecutiveRepeatConverter : public IntrinsicConverter {
504public:
505 using IntrinsicConverter::IntrinsicConverter;
506
507 bool check(GenericIntrinsic gi) override {
508 return gi.hasNInputs(1) || gi.sizedInput<UIntType>(0, 1) ||
509 gi.sizedOutput<UIntType>(1) || gi.namedIntParam("base") ||
510 gi.namedIntParam("more") || gi.hasNParam(1, 1);
511 }
512
513 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
514 PatternRewriter &rewriter) override {
515 auto getI64Attr = [&](IntegerAttr val) {
516 if (!val)
517 return IntegerAttr();
518 return rewriter.getI64IntegerAttr(val.getValue().getZExtValue());
519 };
520 auto base = getI64Attr(gi.getParamValue<IntegerAttr>("base"));
521 auto more = getI64Attr(gi.getParamValue<IntegerAttr>("more"));
522 rewriter.replaceOpWithNewOp<LTLNonConsecutiveRepeatIntrinsicOp>(
523 gi.op, gi.op.getResultTypes(), adaptor.getOperands()[0], base, more);
524 }
525};
526
527template <class Op>
528class CirctVerifConverter : public IntrinsicConverter {
529public:
530 using IntrinsicConverter::IntrinsicConverter;
531
532 bool check(GenericIntrinsic gi) override {
533 return gi.hasNInputs(1, 2) || gi.sizedInput<UIntType>(0, 1) ||
534 gi.namedParam("label", true) || gi.hasNParam(0, 1) ||
535 gi.hasNoOutput();
536 }
537
538 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
539 PatternRewriter &rewriter) override {
540 auto label = gi.getParamValue<StringAttr>("label");
541 auto operands = adaptor.getOperands();
542
543 // Check if an enable was provided
544 Value enable;
545 if (gi.getNumInputs() == 2)
546 enable = operands[1];
547
548 rewriter.replaceOpWithNewOp<Op>(gi.op, operands[0], enable, label);
549 }
550};
551
552class CirctMux2CellConverter : public IntrinsicConverter {
553 using IntrinsicConverter::IntrinsicConverter;
554
555 bool check(GenericIntrinsic gi) override {
556 return gi.hasNInputs(3) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
557 gi.hasOutput();
558 }
559
560 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
561 PatternRewriter &rewriter) override {
562 auto operands = adaptor.getOperands();
563 rewriter.replaceOpWithNewOp<Mux2CellIntrinsicOp>(gi.op, operands[0],
564 operands[1], operands[2]);
565 }
566};
567
568class CirctMux4CellConverter : public IntrinsicConverter {
569 using IntrinsicConverter::IntrinsicConverter;
570
571 bool check(GenericIntrinsic gi) override {
572 return gi.hasNInputs(5) || gi.typedInput<UIntType>(0) || gi.hasNParam(0) ||
573 gi.hasOutput();
574 }
575
576 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
577 PatternRewriter &rewriter) override {
578 auto operands = adaptor.getOperands();
579 rewriter.replaceOpWithNewOp<Mux4CellIntrinsicOp>(
580 gi.op, operands[0], operands[1], operands[2], operands[3], operands[4]);
581 }
582};
583
584class CirctHasBeenResetConverter
585 : public IntrinsicOpConverter<HasBeenResetIntrinsicOp> {
586public:
587 using IntrinsicOpConverter::IntrinsicOpConverter;
588
589 bool check(GenericIntrinsic gi) override {
590 return gi.hasNInputs(2) || gi.typedInput<ClockType>(0) ||
591 gi.hasResetInput(1) || gi.sizedOutput<UIntType>(1) ||
592 gi.hasNParam(0);
593 }
594};
595
596class CirctProbeConverter : public IntrinsicOpConverter<FPGAProbeIntrinsicOp> {
597public:
598 using IntrinsicOpConverter::IntrinsicOpConverter;
599
600 bool check(GenericIntrinsic gi) override {
601 return gi.hasNInputs(2) || gi.typedInput<ClockType>(1) || gi.hasNParam(0) ||
602 gi.hasNoOutput();
603 }
604};
605
606template <class OpTy, bool ifElseFatal = false>
607class CirctAssertConverter : public IntrinsicConverter {
608public:
609 using IntrinsicConverter::IntrinsicConverter;
610
611 LogicalResult checkAndConvert(GenericIntrinsic gi,
612 GenericIntrinsicOpAdaptor adaptor,
613 PatternRewriter &rewriter) override {
614 // Check structure of the intrinsic.
615 if (gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
616 gi.sizedInput<UIntType>(2, 1) ||
617 gi.namedParam("format", /*optional=*/true) ||
618 gi.namedParam("label", /*optional=*/true) ||
619 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
620 gi.hasNoOutput())
621 return failure();
622
623 auto format = gi.getParamValue<StringAttr>("format");
624 auto label = gi.getParamValue<StringAttr>("label");
625 auto guards = gi.getParamValue<StringAttr>("guards");
626
627 auto clock = adaptor.getOperands()[0];
628 auto predicate = adaptor.getOperands()[1];
629 auto enable = adaptor.getOperands()[2];
630
631 auto substitutions = adaptor.getOperands().drop_front(3);
632 auto name = label ? label.strref() : "";
633
634 // Parse the format string to handle special substitutions like
635 // {{SimulationTime}} and {{HierarchicalModuleName}}
636 StringAttr message;
637 SmallVector<Value> allOperands;
638 if (format) {
639 SmallVector<Value> substitutionVec(substitutions.begin(),
640 substitutions.end());
641 if (failed(parseFormatString(rewriter, gi.op->getLoc(), format.getValue(),
642 substitutionVec, message, allOperands)))
643 return failure();
644 } else {
645 // Message is not optional, so provide empty string if not present.
646 message = rewriter.getStringAttr("");
647 allOperands.append(substitutions.begin(), substitutions.end());
648 }
649
650 auto op = rewriter.template replaceOpWithNewOp<OpTy>(
651 gi.op, clock, predicate, enable, message, allOperands, name,
652 /*isConcurrent=*/true);
653 if (guards) {
654 SmallVector<StringRef> guardStrings;
655 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
656 /*KeepEmpty=*/false);
657 rewriter.startOpModification(op);
658 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
659 rewriter.finalizeOpModification(op);
660 }
661
662 if constexpr (ifElseFatal) {
663 rewriter.startOpModification(op);
664 op->setAttr("format", rewriter.getStringAttr("ifElseFatal"));
665 rewriter.finalizeOpModification(op);
666 }
667
668 return success();
669 }
670};
671
672class CirctCoverConverter : public IntrinsicConverter {
673public:
674 using IntrinsicConverter::IntrinsicConverter;
675
676 bool check(GenericIntrinsic gi) override {
677 return gi.hasNInputs(3) || gi.hasNoOutput() ||
678 gi.typedInput<ClockType>(0) || gi.sizedInput<UIntType>(1, 1) ||
679 gi.sizedInput<UIntType>(2, 1) ||
680 gi.namedParam("label", /*optional=*/true) ||
681 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 2);
682 }
683
684 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
685 PatternRewriter &rewriter) override {
686 auto label = gi.getParamValue<StringAttr>("label");
687 auto guards = gi.getParamValue<StringAttr>("guards");
688
689 auto clock = adaptor.getOperands()[0];
690 auto predicate = adaptor.getOperands()[1];
691 auto enable = adaptor.getOperands()[2];
692
693 auto name = label ? label.strref() : "";
694 // Empty message string for cover, only 'name' / label.
695 auto message = rewriter.getStringAttr("");
696 auto op = rewriter.replaceOpWithNewOp<CoverOp>(
697 gi.op, clock, predicate, enable, message, ValueRange{}, name,
698 /*isConcurrent=*/true);
699 if (guards) {
700 SmallVector<StringRef> guardStrings;
701 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
702 /*KeepEmpty=*/false);
703 rewriter.startOpModification(op);
704 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
705 rewriter.finalizeOpModification(op);
706 }
707 }
708};
709
710class CirctUnclockedAssumeConverter : public IntrinsicConverter {
711public:
712 using IntrinsicConverter::IntrinsicConverter;
713
714 bool check(GenericIntrinsic gi) override {
715 return gi.sizedInput<UIntType>(0, 1) || gi.sizedInput<UIntType>(1, 1) ||
716 gi.namedParam("format", /*optional=*/true) ||
717 gi.namedParam("label", /*optional=*/true) ||
718 gi.namedParam("guards", /*optional=*/true) || gi.hasNParam(0, 3) ||
719 gi.hasNoOutput();
720 }
721
722 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
723 PatternRewriter &rewriter) override {
724 auto format = gi.getParamValue<StringAttr>("format");
725 auto label = gi.getParamValue<StringAttr>("label");
726 auto guards = gi.getParamValue<StringAttr>("guards");
727
728 auto predicate = adaptor.getOperands()[0];
729 auto enable = adaptor.getOperands()[1];
730
731 auto substitutions = adaptor.getOperands().drop_front(2);
732 auto name = label ? label.strref() : "";
733 // Message is not optional, so provide empty string if not present.
734 auto message = format ? format : rewriter.getStringAttr("");
735 auto op = rewriter.template replaceOpWithNewOp<UnclockedAssumeIntrinsicOp>(
736 gi.op, predicate, enable, message, substitutions, name);
737 if (guards) {
738 SmallVector<StringRef> guardStrings;
739 guards.strref().split(guardStrings, ';', /*MaxSplit=*/-1,
740 /*KeepEmpty=*/false);
741 rewriter.startOpModification(op);
742 op->setAttr("guards", rewriter.getStrArrayAttr(guardStrings));
743 rewriter.finalizeOpModification(op);
744 }
745 }
746};
747
748class CirctDPICallConverter : public IntrinsicConverter {
749 static bool getIsClocked(GenericIntrinsic gi) {
750 return !gi.getParamValue<IntegerAttr>("isClocked").getValue().isZero();
751 }
752
753public:
754 using IntrinsicConverter::IntrinsicConverter;
755
756 bool check(GenericIntrinsic gi) override {
757 if (gi.hasNParam(2, 2) || gi.namedIntParam("isClocked") ||
758 gi.namedParam("functionName") ||
759 gi.namedParam("inputNames", /*optional=*/true) ||
760 gi.namedParam("outputName", /*optional=*/true))
761 return true;
762 auto isClocked = getIsClocked(gi);
763 // If clocked, the first operand must be a clock.
764 if (isClocked && gi.typedInput<ClockType>(0))
765 return true;
766 // Enable must be UInt<1>.
767 if (gi.sizedInput<UIntType>(isClocked, 1))
768 return true;
769
770 return false;
771 }
772
773 void convert(GenericIntrinsic gi, GenericIntrinsicOpAdaptor adaptor,
774 PatternRewriter &rewriter) override {
775 auto isClocked = getIsClocked(gi);
776 auto functionName = gi.getParamValue<StringAttr>("functionName");
777 ArrayAttr inputNamesStrArray;
778 StringAttr outputStr = gi.getParamValue<StringAttr>("outputName");
779 if (auto inputNames = gi.getParamValue<StringAttr>("inputNames")) {
780 SmallVector<StringRef> inputNamesTemporary;
781 inputNames.strref().split(inputNamesTemporary, ';', /*MaxSplit=*/-1,
782 /*KeepEmpty=*/false);
783 inputNamesStrArray = rewriter.getStrArrayAttr(inputNamesTemporary);
784 }
785 // Clock and enable are optional.
786 Value clock = isClocked ? adaptor.getOperands()[0] : Value();
787 Value enable = adaptor.getOperands()[static_cast<size_t>(isClocked)];
788
789 auto inputs =
790 adaptor.getOperands().drop_front(static_cast<size_t>(isClocked) + 1);
791
792 rewriter.replaceOpWithNewOp<DPICallIntrinsicOp>(
793 gi.op, gi.op.getResultTypes(), functionName, inputNamesStrArray,
794 outputStr, clock, enable, inputs);
795 }
796};
797
798//===----------------------------------------------------------------------===//
799// View intrinsic converter and helpers
800//===----------------------------------------------------------------------===//
801
802template <typename A>
803A tryGetAs(DictionaryAttr dict, Attribute root, StringRef key, Location loc,
804 Twine path = Twine()) {
805 return tryGetAsBase<A>(dict, root, key, loc, "View 'info'",
806 "'info' attribute", path);
807}
808
809/// Recursively walk a sifive.enterprise.grandcentral.AugmentedType to extract
810/// and slightly restructure information needed for a view.
811std::optional<DictionaryAttr>
812parseAugmentedType(MLIRContext *context, Location loc,
813 DictionaryAttr augmentedType, DictionaryAttr root,
814 StringAttr name, StringAttr defName,
815 std::optional<StringAttr> description, Twine path = {}) {
816 auto classAttr =
817 tryGetAs<StringAttr>(augmentedType, root, "class", loc, path);
818 if (!classAttr)
819 return std::nullopt;
820 StringRef classBase = classAttr.getValue();
821 if (!classBase.consume_front("sifive.enterprise.grandcentral.Augmented")) {
822 mlir::emitError(loc,
823 "the 'class' was expected to start with "
824 "'sifive.enterprise.grandCentral.Augmented*', but was '" +
825 classAttr.getValue() + "' (Did you misspell it?)")
826 .attachNote()
827 << "see attribute: " << augmentedType;
828 return std::nullopt;
829 }
830
831 // An AugmentedBundleType looks like:
832 // "defName": String
833 // "elements": Seq[AugmentedField]
834 if (classBase == "BundleType") {
835 defName = tryGetAs<StringAttr>(augmentedType, root, "defName", loc, path);
836 if (!defName)
837 return std::nullopt;
838
839 // Each element is an AugmentedField with members:
840 // "name": String
841 // "description": Option[String]
842 // "tpe": AugmentedType
843 SmallVector<Attribute> elements;
844 auto elementsAttr =
845 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
846 if (!elementsAttr)
847 return std::nullopt;
848 for (size_t i = 0, e = elementsAttr.size(); i != e; ++i) {
849 auto field = dyn_cast_or_null<DictionaryAttr>(elementsAttr[i]);
850 if (!field) {
851 mlir::emitError(
852 loc,
853 "View 'info' attribute with path '.elements[" + Twine(i) +
854 "]' contained an unexpected type (expected a DictionaryAttr).")
855 .attachNote()
856 << "The received element was: " << elementsAttr[i];
857 return std::nullopt;
858 }
859 auto ePath = (path + ".elements[" + Twine(i) + "]").str();
860 auto name = tryGetAs<StringAttr>(field, root, "name", loc, ePath);
861 if (!name)
862 return std::nullopt;
863 auto tpe = tryGetAs<DictionaryAttr>(field, root, "tpe", loc, ePath);
864 if (!tpe)
865 return std::nullopt;
866 std::optional<StringAttr> description;
867 if (auto maybeDescription = field.get("description"))
868 description = cast<StringAttr>(maybeDescription);
869 auto eltAttr =
870 parseAugmentedType(context, loc, tpe, root, name, defName,
871 description, path + "_" + name.getValue());
872 if (!eltAttr)
873 return std::nullopt;
874
875 // Collect information necessary to build a module with this view later.
876 // This includes the optional description and name.
877 NamedAttrList attrs;
878 if (auto maybeDescription = field.get("description"))
879 attrs.append("description", cast<StringAttr>(maybeDescription));
880 attrs.append("name", name);
881 auto tpeClass = tpe.getAs<StringAttr>("class");
882 if (!tpeClass) {
883 mlir::emitError(loc, "missing 'class' key in") << tpe;
884 return std::nullopt;
885 }
886 attrs.append("tpe", tpeClass);
887 elements.push_back(*eltAttr);
888 }
889 // Add an attribute that stores information necessary to construct the
890 // interface for the view. This needs the name of the interface (defName)
891 // and the names of the components inside it.
892 NamedAttrList attrs;
893 attrs.append("class", classAttr);
894 attrs.append("defName", defName);
895 if (description)
896 attrs.append("description", *description);
897 attrs.append("elements", ArrayAttr::get(context, elements));
898 attrs.append("name", name);
899 return DictionaryAttr::getWithSorted(context, attrs);
900 }
901
902 // An AugmentedGroundType has no contents.
903 if (classBase == "GroundType") {
904 NamedAttrList elementIface;
905
906 // Populate the attribute for the interface element.
907 elementIface.append("class", classAttr);
908 if (description)
909 elementIface.append("description", *description);
910 elementIface.append("name", name);
911
912 return DictionaryAttr::getWithSorted(context, elementIface);
913 }
914
915 // An AugmentedVectorType looks like:
916 // "elements": Seq[AugmentedType]
917 if (classBase == "VectorType") {
918 auto elementsAttr =
919 tryGetAs<ArrayAttr>(augmentedType, root, "elements", loc, path);
920 if (!elementsAttr)
921 return std::nullopt;
922 SmallVector<Attribute> elements;
923 for (auto [i, elt] : llvm::enumerate(elementsAttr)) {
924 auto eltAttr = parseAugmentedType(
925 context, loc, cast<DictionaryAttr>(elt), root, name,
926 StringAttr::get(context, ""), std::nullopt, path + "_" + Twine(i));
927 if (!eltAttr)
928 return std::nullopt;
929 elements.push_back(*eltAttr);
930 }
931 NamedAttrList attrs;
932 attrs.append("class", classAttr);
933 if (description)
934 attrs.append("description", *description);
935 attrs.append("elements", ArrayAttr::get(context, elements));
936 attrs.append("name", name);
937 return DictionaryAttr::getWithSorted(context, attrs);
938 }
939
940 // Anything else is unexpected or a user error if they manually wrote
941 // the JSON/attribute. Print an error and error out.
942 mlir::emitError(loc, "found unknown AugmentedType '" + classAttr.getValue() +
943 "' (Did you misspell it?)")
944 .attachNote()
945 << "see attribute: " << augmentedType;
946 return std::nullopt;
947}
948
949class ViewConverter : public IntrinsicConverter {
950public:
951 LogicalResult checkAndConvert(GenericIntrinsic gi,
952 GenericIntrinsicOpAdaptor adaptor,
953 PatternRewriter &rewriter) override {
954 // Check structure of the intrinsic.
955 if (gi.hasNoOutput() || gi.namedParam("info") || gi.namedParam("name") ||
956 gi.namedParam("yaml", true))
957 return failure();
958
959 // Check operands.
960 for (auto idx : llvm::seq(gi.getNumInputs()))
961 if (gi.checkInputType(idx, "must be ground type", [](auto ty) {
962 auto base = type_dyn_cast<FIRRTLBaseType>(ty);
963 return base && base.isGround();
964 }))
965 return failure();
966
967 // Parse "info" string parameter as JSON.
968 auto view =
969 llvm::json::parse(gi.getParamValue<StringAttr>("info").getValue());
970 if (auto err = view.takeError()) {
971 handleAllErrors(std::move(err), [&](const llvm::json::ParseError &a) {
972 gi.emitError() << ": error parsing view JSON: " << a.message();
973 });
974 return failure();
975 }
976
977 // Convert JSON to MLIR attribute.
978 llvm::json::Path::Root root;
979 auto value = convertJSONToAttribute(gi.op.getContext(), view.get(), root);
980 assert(value && "JSON to attribute failed but should not ever fail");
981
982 // Check attribute is a dictionary, for AugmentedBundleTypeAttr
983 // construction.
984 auto dict = dyn_cast<DictionaryAttr>(value);
985 if (!dict)
986 return gi.emitError() << ": 'info' parameter must be a dictionary";
987
988 auto nameAttr = gi.getParamValue<StringAttr>("name");
989 auto result = parseAugmentedType(
990 gi.op.getContext(), gi.op.getLoc(), dict, dict, nameAttr,
991 /* defName= */ {}, /* description= */ std::nullopt);
992
993 if (!result)
994 return failure();
995
996 // Build AugmentedBundleTypeAttr, unchecked.
997 auto augmentedType =
998 AugmentedBundleTypeAttr::get(gi.op.getContext(), *result);
999 if (augmentedType.getClass() != augmentedBundleTypeAnnoClass)
1000 return gi.emitError() << ": 'info' must be augmented bundle";
1001
1002 // Scan for ground-type (leaves) and count.
1003 SmallVector<DictionaryAttr> worklist;
1004 worklist.push_back(augmentedType.getUnderlying());
1005 size_t numLeaves = 0;
1006 auto augGroundAttr =
1007 StringAttr::get(gi.op.getContext(), augmentedGroundTypeAnnoClass);
1008 [[maybe_unused]] auto augBundleAttr =
1009 StringAttr::get(gi.op.getContext(), augmentedBundleTypeAnnoClass);
1010 [[maybe_unused]] auto augVectorAttr =
1011 StringAttr::get(gi.op.getContext(), augmentedVectorTypeAnnoClass);
1012 while (!worklist.empty()) {
1013 auto dict = worklist.pop_back_val();
1014 auto clazz = dict.getAs<StringAttr>("class");
1015 if (clazz == augGroundAttr) {
1016 ++numLeaves;
1017 continue;
1018 }
1019 assert(clazz == augBundleAttr || clazz == augVectorAttr);
1020 llvm::append_range(
1021 worklist,
1022 dict.getAs<ArrayAttr>("elements").getAsRange<DictionaryAttr>());
1023 }
1024
1025 if (numLeaves != gi.getNumInputs())
1026 return gi.emitError()
1027 << " has " << gi.getNumInputs() << " operands but view 'info' has "
1028 << numLeaves << " leaf elements";
1029
1030 // Check complete, convert!
1031 auto yaml = gi.getParamValue<StringAttr>("yaml");
1032 rewriter.replaceOpWithNewOp<ViewIntrinsicOp>(
1033 gi.op, nameAttr.getValue(), yaml, augmentedType, adaptor.getOperands());
1034 return success();
1035 }
1036};
1037
1038} // namespace
1039
1040//===----------------------------------------------------------------------===//
1041// FIRRTL intrinsic lowering dialect interface
1042//===----------------------------------------------------------------------===//
1043
1044#include "FIRRTLIntrinsics.cpp.inc"
1045
1047 IntrinsicLowerings &lowering) const {
1048 populateLowerings(lowering);
1049}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
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...
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
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
MLIRContext * context
Reference to the MLIR context.
ConversionMapTy conversions
Mapping from intrinsic names to converters.
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...
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.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
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