CIRCT  20.0.0git
SeqToSV.cpp
Go to the documentation of this file.
1 //===- LowerSeqToSV.cpp - Seq to SV lowering ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transform translate Seq ops to SV.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "FirMemLowering.h"
15 #include "FirRegLowering.h"
20 #include "circt/Dialect/HW/HWOps.h"
23 #include "circt/Dialect/SV/SVOps.h"
25 #include "circt/Support/Naming.h"
26 #include "mlir/Analysis/TopologicalSortUtils.h"
27 #include "mlir/IR/Builders.h"
28 #include "mlir/IR/DialectImplementation.h"
29 #include "mlir/IR/ImplicitLocOpBuilder.h"
30 #include "mlir/IR/Threading.h"
31 #include "mlir/Pass/Pass.h"
32 #include "mlir/Transforms/DialectConversion.h"
33 #include "llvm/ADT/IntervalMap.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/Support/Mutex.h"
36 
37 #define DEBUG_TYPE "lower-seq-to-sv"
38 
39 using namespace circt;
40 using namespace seq;
41 using hw::HWModuleOp;
42 using llvm::MapVector;
43 
44 namespace circt {
45 #define GEN_PASS_DEF_LOWERSEQTOSV
46 #include "circt/Conversion/Passes.h.inc"
47 
48 struct SeqToSVPass : public impl::LowerSeqToSVBase<SeqToSVPass> {
49 
50  void runOnOperation() override;
51 
52  using LowerSeqToSVBase<SeqToSVPass>::lowerToAlwaysFF;
53  using LowerSeqToSVBase<SeqToSVPass>::disableRegRandomization;
54  using LowerSeqToSVBase<SeqToSVPass>::emitSeparateAlwaysBlocks;
55  using LowerSeqToSVBase<SeqToSVPass>::LowerSeqToSVBase;
56  using LowerSeqToSVBase<SeqToSVPass>::numSubaccessRestored;
57 };
58 } // namespace circt
59 
60 namespace {
61 struct ModuleLoweringState {
62  ModuleLoweringState(HWModuleOp module)
63  : immutableValueLowering(module), module(module) {}
64 
65  struct ImmutableValueLowering {
66  ImmutableValueLowering(hw::HWModuleOp module) : module(module) {}
67 
68  // Lower initial ops.
69  LogicalResult lower();
70  LogicalResult lower(seq::InitialOp initialOp);
71 
72  Value
73  lookupImmutableValue(mlir::TypedValue<seq::ImmutableType> immut) const {
74  return mapping.lookup(immut);
75  }
76 
77  sv::InitialOp getSVInitial() const { return svInitialOp; }
78 
79  private:
80  sv::InitialOp svInitialOp = {};
81  // A mapping from a dummy immutable value to the actual initial value
82  // defined in SV initial op.
83  MapVector<mlir::TypedValue<seq::ImmutableType>, Value> mapping;
84 
85  hw::HWModuleOp module;
86  } immutableValueLowering;
87 
88  struct FragmentInfo {
89  bool needsRegFragment = false;
90  bool needsMemFragment = false;
91  } fragment;
92 
93  HWModuleOp module;
94 };
95 
96 LogicalResult ModuleLoweringState::ImmutableValueLowering::lower() {
97  auto result = mergeInitialOps(module.getBodyBlock());
98  if (failed(result))
99  return failure();
100 
101  auto initialOp = *result;
102  if (!initialOp)
103  return success();
104 
105  return lower(initialOp);
106 }
107 
108 LogicalResult
109 ModuleLoweringState::ImmutableValueLowering::lower(seq::InitialOp initialOp) {
110  OpBuilder builder = OpBuilder::atBlockBegin(module.getBodyBlock());
111  if (!svInitialOp)
112  svInitialOp = builder.create<sv::InitialOp>(initialOp->getLoc());
113  // Initial ops are merged to single one and must not have operands.
114  assert(initialOp.getNumOperands() == 0 &&
115  "initial op should have no operands");
116 
117  auto loc = initialOp.getLoc();
118  llvm::SmallVector<Value> results;
119 
120  auto yieldOp = cast<seq::YieldOp>(initialOp.getBodyBlock()->getTerminator());
121 
122  for (auto [result, operand] :
123  llvm::zip(initialOp.getResults(), yieldOp->getOperands())) {
124  auto placeholder =
125  builder
126  .create<mlir::UnrealizedConversionCastOp>(
127  loc, ArrayRef<Type>{result.getType()}, ArrayRef<Value>{})
128  ->getResult(0);
129  result.replaceAllUsesWith(placeholder);
130  mapping.insert(
131  {cast<mlir::TypedValue<seq ::ImmutableType>>(placeholder), operand});
132  }
133 
134  svInitialOp.getBodyBlock()->getOperations().splice(
135  svInitialOp.end(), initialOp.getBodyBlock()->getOperations());
136 
137  assert(initialOp->use_empty());
138  initialOp.erase();
139  yieldOp->erase();
140  return success();
141 }
142 
143 /// Lower CompRegOp to `sv.reg` and `sv.alwaysff`. Use a posedge clock and
144 /// synchronous reset.
145 template <typename OpTy>
146 class CompRegLower : public OpConversionPattern<OpTy> {
147 public:
148  CompRegLower(
149  TypeConverter &typeConverter, MLIRContext *context, bool lowerToAlwaysFF,
150  const MapVector<StringAttr, ModuleLoweringState> &moduleLoweringStates)
151  : OpConversionPattern<OpTy>(typeConverter, context),
152  lowerToAlwaysFF(lowerToAlwaysFF),
153  moduleLoweringStates(moduleLoweringStates) {}
154 
155  using OpAdaptor = typename OpConversionPattern<OpTy>::OpAdaptor;
156 
157  LogicalResult
158  matchAndRewrite(OpTy reg, OpAdaptor adaptor,
159  ConversionPatternRewriter &rewriter) const final {
160  Location loc = reg.getLoc();
161 
162  auto regTy =
163  ConversionPattern::getTypeConverter()->convertType(reg.getType());
164  auto svReg = rewriter.create<sv::RegOp>(loc, regTy, reg.getNameAttr(),
165  reg.getInnerSymAttr());
166 
167  svReg->setDialectAttrs(reg->getDialectAttrs());
168 
170 
171  auto regVal = rewriter.create<sv::ReadInOutOp>(loc, svReg);
172 
173  auto assignValue = [&] {
174  createAssign(rewriter, reg.getLoc(), svReg, reg);
175  };
176  auto assignReset = [&] {
177  rewriter.create<sv::PAssignOp>(loc, svReg, adaptor.getResetValue());
178  };
179 
180  if (adaptor.getReset() && adaptor.getResetValue()) {
181  if (lowerToAlwaysFF) {
182  rewriter.create<sv::AlwaysFFOp>(
183  loc, sv::EventControl::AtPosEdge, adaptor.getClk(),
184  sv::ResetType::SyncReset, sv::EventControl::AtPosEdge,
185  adaptor.getReset(), assignValue, assignReset);
186  } else {
187  rewriter.create<sv::AlwaysOp>(
188  loc, sv::EventControl::AtPosEdge, adaptor.getClk(), [&] {
189  rewriter.create<sv::IfOp>(loc, adaptor.getReset(), assignReset,
190  assignValue);
191  });
192  }
193  } else {
194  if (lowerToAlwaysFF) {
195  rewriter.create<sv::AlwaysFFOp>(loc, sv::EventControl::AtPosEdge,
196  adaptor.getClk(), assignValue);
197  } else {
198  rewriter.create<sv::AlwaysOp>(loc, sv::EventControl::AtPosEdge,
199  adaptor.getClk(), assignValue);
200  }
201  }
202 
203  // Lower initial values.
204  if (auto init = reg.getInitialValue()) {
205  auto module = reg->template getParentOfType<hw::HWModuleOp>();
206  const auto &initial =
207  moduleLoweringStates.find(module.getModuleNameAttr())
208  ->second.immutableValueLowering;
209 
210  Value initialValue = initial.lookupImmutableValue(init);
211 
212  if (auto op = initialValue.getDefiningOp();
213  op && op->hasTrait<mlir::OpTrait::ConstantLike>()) {
214  auto clonedConstant = rewriter.clone(*op);
215  rewriter.moveOpBefore(clonedConstant, svReg);
216  svReg.getInitMutable().assign(clonedConstant->getResult(0));
217  } else {
218  OpBuilder::InsertionGuard guard(rewriter);
219  auto in = initial.getSVInitial();
220  rewriter.setInsertionPointToEnd(in.getBodyBlock());
221  rewriter.create<sv::BPAssignOp>(reg->getLoc(), svReg, initialValue);
222  }
223  }
224 
225  rewriter.replaceOp(reg, regVal);
226  return success();
227  }
228 
229  // Helper to create an assignment based on the register type.
230  void createAssign(ConversionPatternRewriter &rewriter, Location loc,
231  sv::RegOp svReg, OpAdaptor reg) const;
232 
233 private:
234  bool lowerToAlwaysFF;
235  const MapVector<StringAttr, ModuleLoweringState> &moduleLoweringStates;
236 };
237 
238 /// Create the assign.
239 template <>
240 void CompRegLower<CompRegOp>::createAssign(ConversionPatternRewriter &rewriter,
241  Location loc, sv::RegOp svReg,
242  OpAdaptor reg) const {
243  rewriter.create<sv::PAssignOp>(loc, svReg, reg.getInput());
244 }
245 /// Create the assign inside of an if block.
246 template <>
247 void CompRegLower<CompRegClockEnabledOp>::createAssign(
248  ConversionPatternRewriter &rewriter, Location loc, sv::RegOp svReg,
249  OpAdaptor reg) const {
250  rewriter.create<sv::IfOp>(loc, reg.getClockEnable(), [&]() {
251  rewriter.create<sv::PAssignOp>(loc, svReg, reg.getInput());
252  });
253 }
254 
255 /// Lower FromImmutable to `sv.reg` and `sv.initial`.
256 class FromImmutableLowering : public OpConversionPattern<FromImmutableOp> {
257 public:
258  FromImmutableLowering(
259  TypeConverter &typeConverter, MLIRContext *context,
260  const MapVector<StringAttr, ModuleLoweringState> &moduleLoweringStates)
261  : OpConversionPattern<FromImmutableOp>(typeConverter, context),
262  moduleLoweringStates(moduleLoweringStates) {}
263 
264  using OpAdaptor = typename OpConversionPattern<FromImmutableOp>::OpAdaptor;
265 
266  LogicalResult
267  matchAndRewrite(FromImmutableOp fromImmutableOp, OpAdaptor adaptor,
268  ConversionPatternRewriter &rewriter) const final {
269  Location loc = fromImmutableOp.getLoc();
270 
271  auto regTy = ConversionPattern::getTypeConverter()->convertType(
272  fromImmutableOp.getType());
273  auto svReg = rewriter.create<sv::RegOp>(loc, regTy);
274 
275  auto regVal = rewriter.create<sv::ReadInOutOp>(loc, svReg);
276 
277  // Lower initial values.
278  auto module = fromImmutableOp->template getParentOfType<hw::HWModuleOp>();
279  const auto &initial = moduleLoweringStates.find(module.getModuleNameAttr())
280  ->second.immutableValueLowering;
281 
282  Value initialValue =
283  initial.lookupImmutableValue(fromImmutableOp.getInput());
284 
285  OpBuilder::InsertionGuard guard(rewriter);
286  auto in = initial.getSVInitial();
287  rewriter.setInsertionPointToEnd(in.getBodyBlock());
288  rewriter.create<sv::BPAssignOp>(fromImmutableOp->getLoc(), svReg,
289  initialValue);
290 
291  rewriter.replaceOp(fromImmutableOp, regVal);
292  return success();
293  }
294 
295 private:
296  const MapVector<StringAttr, ModuleLoweringState> &moduleLoweringStates;
297 };
298 // Lower seq.clock_gate to a fairly standard clock gate implementation.
299 //
300 class ClockGateLowering : public OpConversionPattern<ClockGateOp> {
301 public:
303  using OpAdaptor = typename OpConversionPattern<ClockGateOp>::OpAdaptor;
304  LogicalResult
305  matchAndRewrite(ClockGateOp clockGate, OpAdaptor adaptor,
306  ConversionPatternRewriter &rewriter) const final {
307  auto loc = clockGate.getLoc();
308  Value clk = adaptor.getInput();
309 
310  // enable in
311  Value enable = adaptor.getEnable();
312  if (auto te = adaptor.getTestEnable())
313  enable = rewriter.create<comb::OrOp>(loc, enable, te);
314 
315  // Enable latch.
316  Value enableLatch = rewriter.create<sv::RegOp>(
317  loc, rewriter.getI1Type(), rewriter.getStringAttr("cg_en_latch"));
318 
319  // Latch the enable signal using an always @* block.
320  rewriter.create<sv::AlwaysOp>(
321  loc, llvm::SmallVector<sv::EventControl>{}, llvm::SmallVector<Value>{},
322  [&]() {
323  rewriter.create<sv::IfOp>(
324  loc, comb::createOrFoldNot(loc, clk, rewriter), [&]() {
325  rewriter.create<sv::PAssignOp>(loc, enableLatch, enable);
326  });
327  });
328 
329  // Create the gated clock signal.
330  rewriter.replaceOpWithNewOp<comb::AndOp>(
331  clockGate, clk, rewriter.create<sv::ReadInOutOp>(loc, enableLatch));
332  return success();
333  }
334 };
335 
336 // Lower seq.clock_inv to a regular inverter.
337 //
338 class ClockInverterLowering : public OpConversionPattern<ClockInverterOp> {
339 public:
341 
342  LogicalResult
343  matchAndRewrite(ClockInverterOp op, OpAdaptor adaptor,
344  ConversionPatternRewriter &rewriter) const final {
345  auto loc = op.getLoc();
346  Value clk = adaptor.getInput();
347 
348  StringAttr name = op->getAttrOfType<StringAttr>("sv.namehint");
349  Value one = rewriter.create<hw::ConstantOp>(loc, APInt(1, 1));
350  auto newOp = rewriter.replaceOpWithNewOp<comb::XorOp>(op, clk, one);
351  if (name)
352  rewriter.modifyOpInPlace(newOp,
353  [&] { newOp->setAttr("sv.namehint", name); });
354  return success();
355  }
356 };
357 
358 // Lower seq.clock_mux to a `comb.mux` op
359 //
360 class ClockMuxLowering : public OpConversionPattern<ClockMuxOp> {
361 public:
364 
365  LogicalResult
366  matchAndRewrite(ClockMuxOp clockMux, OpAdaptor adaptor,
367  ConversionPatternRewriter &rewriter) const final {
368  rewriter.replaceOpWithNewOp<comb::MuxOp>(clockMux, adaptor.getCond(),
369  adaptor.getTrueClock(),
370  adaptor.getFalseClock(), true);
371  return success();
372  }
373 };
374 
375 /// Map `seq.clock` to `i1`.
376 struct SeqToSVTypeConverter : public TypeConverter {
377  SeqToSVTypeConverter() {
378  addConversion([&](Type type) { return type; });
379  addConversion([&](seq::ImmutableType type) { return type.getInnerType(); });
380  addConversion([&](seq::ClockType type) {
381  return IntegerType::get(type.getContext(), 1);
382  });
383  addConversion([&](hw::StructType structTy) {
384  bool changed = false;
385 
386  SmallVector<hw::StructType::FieldInfo> newFields;
387  for (auto field : structTy.getElements()) {
388  auto &newField = newFields.emplace_back();
389  newField.name = field.name;
390  newField.type = convertType(field.type);
391  if (field.type != newField.type)
392  changed = true;
393  }
394 
395  if (!changed)
396  return structTy;
397 
398  return hw::StructType::get(structTy.getContext(), newFields);
399  });
400  addConversion([&](hw::ArrayType arrayTy) {
401  auto elementTy = arrayTy.getElementType();
402  auto newElementTy = convertType(elementTy);
403  if (elementTy != newElementTy)
404  return hw::ArrayType::get(newElementTy, arrayTy.getNumElements());
405  return arrayTy;
406  });
407 
408  addTargetMaterialization(
409  [&](mlir::OpBuilder &builder, mlir::Type resultType,
410  mlir::ValueRange inputs,
411  mlir::Location loc) -> std::optional<mlir::Value> {
412  if (inputs.size() != 1)
413  return std::nullopt;
414  return builder
415  .create<mlir::UnrealizedConversionCastOp>(loc, resultType,
416  inputs[0])
417  ->getResult(0);
418  });
419 
420  addSourceMaterialization(
421  [&](mlir::OpBuilder &builder, mlir::Type resultType,
422  mlir::ValueRange inputs,
423  mlir::Location loc) -> std::optional<mlir::Value> {
424  if (inputs.size() != 1)
425  return std::nullopt;
426  return builder
427  .create<mlir::UnrealizedConversionCastOp>(loc, resultType,
428  inputs[0])
429  ->getResult(0);
430  });
431  }
432 };
433 
434 /// Eliminate no-op clock casts.
435 template <typename T>
436 class ClockCastLowering : public OpConversionPattern<T> {
437 public:
439 
440  LogicalResult
441  matchAndRewrite(T op, typename T::Adaptor adaptor,
442  ConversionPatternRewriter &rewriter) const final {
443  // If the cast had a better name than its input, propagate it.
444  if (Operation *inputOp = adaptor.getInput().getDefiningOp())
445  if (!isa<mlir::UnrealizedConversionCastOp>(inputOp))
446  if (auto name = chooseName(op, inputOp))
447  rewriter.modifyOpInPlace(
448  inputOp, [&] { inputOp->setAttr("sv.namehint", name); });
449 
450  rewriter.replaceOp(op, adaptor.getInput());
451  return success();
452  }
453 };
454 
455 // Lower seq.const_clock to `hw.constant`
456 //
457 class ClockConstLowering : public OpConversionPattern<ConstClockOp> {
458 public:
461 
462  LogicalResult
463  matchAndRewrite(ConstClockOp clockConst, OpAdaptor adaptor,
464  ConversionPatternRewriter &rewriter) const final {
465  rewriter.replaceOpWithNewOp<hw::ConstantOp>(
466  clockConst, APInt(1, clockConst.getValue() == ClockConst::High));
467  return success();
468  }
469 };
470 
471 class AggregateConstantPattern
472  : public OpConversionPattern<hw::AggregateConstantOp> {
473 public:
476 
477  LogicalResult
478  matchAndRewrite(hw::AggregateConstantOp aggregateConstant, OpAdaptor adaptor,
479  ConversionPatternRewriter &rewriter) const final {
480  auto newType = typeConverter->convertType(aggregateConstant.getType());
481  auto newAttr = aggregateConstant.getFieldsAttr().replace(
482  [](seq::ClockConstAttr clockConst) {
483  return mlir::IntegerAttr::get(
484  mlir::IntegerType::get(clockConst.getContext(), 1),
485  APInt(1, clockConst.getValue() == ClockConst::High));
486  });
487  rewriter.replaceOpWithNewOp<hw::AggregateConstantOp>(
488  aggregateConstant, newType, cast<ArrayAttr>(newAttr));
489  return success();
490  }
491 };
492 
493 /// Lower `seq.clock_div` to a behavioural clock divider
494 ///
495 class ClockDividerLowering : public OpConversionPattern<ClockDividerOp> {
496 public:
499 
500  LogicalResult
501  matchAndRewrite(ClockDividerOp clockDiv, OpAdaptor adaptor,
502  ConversionPatternRewriter &rewriter) const final {
503  Location loc = clockDiv.getLoc();
504 
505  Value one;
506  if (clockDiv.getPow2()) {
507  one = rewriter.create<hw::ConstantOp>(loc, APInt(1, 1));
508  }
509 
510  Value output = clockDiv.getInput();
511 
512  SmallVector<Value> regs;
513  for (unsigned i = 0; i < clockDiv.getPow2(); ++i) {
514  Value reg = rewriter.create<sv::RegOp>(
515  loc, rewriter.getI1Type(),
516  rewriter.getStringAttr("clock_out_" + std::to_string(i)));
517  regs.push_back(reg);
518 
519  rewriter.create<sv::AlwaysOp>(
520  loc, sv::EventControl::AtPosEdge, output, [&] {
521  Value outputVal = rewriter.create<sv::ReadInOutOp>(loc, reg);
522  Value inverted = rewriter.create<comb::XorOp>(loc, outputVal, one);
523  rewriter.create<sv::BPAssignOp>(loc, reg, inverted);
524  });
525 
526  output = rewriter.create<sv::ReadInOutOp>(loc, reg);
527  }
528 
529  if (!regs.empty()) {
530  Value zero = rewriter.create<hw::ConstantOp>(loc, APInt(1, 0));
531  rewriter.create<sv::InitialOp>(loc, [&] {
532  for (Value reg : regs) {
533  rewriter.create<sv::BPAssignOp>(loc, reg, zero);
534  }
535  });
536  }
537 
538  rewriter.replaceOp(clockDiv, output);
539  return success();
540  }
541 };
542 
543 } // namespace
544 
545 // NOLINTBEGIN(misc-no-recursion)
546 static bool isLegalType(Type ty) {
547  if (hw::type_isa<ClockType>(ty))
548  return false;
549 
550  if (auto arrayTy = hw::type_dyn_cast<hw::ArrayType>(ty))
551  return isLegalType(arrayTy.getElementType());
552 
553  if (auto structTy = hw::type_dyn_cast<hw::StructType>(ty)) {
554  for (auto field : structTy.getElements())
555  if (!isLegalType(field.type))
556  return false;
557  return true;
558  }
559 
560  return true;
561 }
562 // NOLINTEND(misc-no-recursion)
563 
564 static bool isLegalOp(Operation *op) {
565  if (auto module = dyn_cast<hw::HWModuleLike>(op)) {
566  for (auto port : module.getHWModuleType().getPorts())
567  if (!isLegalType(port.type))
568  return false;
569  return true;
570  }
571 
572  if (auto hwAggregateConstantOp = dyn_cast<hw::AggregateConstantOp>(op)) {
573  bool foundClockAttr = false;
574  hwAggregateConstantOp.getFieldsAttr().walk(
575  [&](seq::ClockConstAttr attr) { foundClockAttr = true; });
576  if (foundClockAttr)
577  return false;
578  }
579 
580  bool allOperandsLowered = llvm::all_of(
581  op->getOperands(), [](auto op) { return isLegalType(op.getType()); });
582  bool allResultsLowered = llvm::all_of(op->getResults(), [](auto result) {
583  return isLegalType(result.getType());
584  });
585  return allOperandsLowered && allResultsLowered;
586 }
587 
589  auto circuit = getOperation();
590  MLIRContext *context = &getContext();
591 
592  auto modules = llvm::to_vector(circuit.getOps<HWModuleOp>());
593 
594  FirMemLowering memLowering(circuit);
595 
596  // Identify memories and group them by module.
597  auto uniqueMems = memLowering.collectMemories(modules);
598  MapVector<HWModuleOp, SmallVector<FirMemLowering::MemoryConfig>> memsByModule;
599  for (auto &[config, memOps] : uniqueMems) {
600  // Create the `HWModuleGeneratedOp`s for each unique configuration.
601  auto genOp = memLowering.createMemoryModule(config, memOps);
602 
603  // Group memories by their parent module for parallelism.
604  for (auto memOp : memOps) {
605  auto parent = memOp->getParentOfType<HWModuleOp>();
606  memsByModule[parent].emplace_back(&config, genOp, memOp);
607  }
608  }
609 
610  // Lower memories and registers in modules in parallel.
611  std::atomic<bool> needsRegRandomization = false;
612  std::atomic<bool> needsMemRandomization = false;
613 
614  MapVector<StringAttr, ModuleLoweringState> moduleLoweringStates;
615  for (auto module : circuit.getOps<HWModuleOp>())
616  moduleLoweringStates.try_emplace(module.getModuleNameAttr(),
617  ModuleLoweringState(module));
618 
619  auto result = mlir::failableParallelForEach(
620  &getContext(), moduleLoweringStates, [&](auto &moduleAndState) {
621  auto &state = moduleAndState.second;
622  auto module = state.module;
623  SeqToSVTypeConverter typeConverter;
624  FirRegLowering regLowering(typeConverter, module,
625  disableRegRandomization,
626  emitSeparateAlwaysBlocks);
627  regLowering.lower();
628  if (regLowering.needsRegRandomization()) {
629  if (!disableRegRandomization) {
630  state.fragment.needsRegFragment = true;
631  }
632  needsRegRandomization = true;
633  }
634  numSubaccessRestored += regLowering.numSubaccessRestored;
635 
636  if (auto *it = memsByModule.find(module); it != memsByModule.end()) {
637  memLowering.lowerMemoriesInModule(module, it->second);
638  if (!disableMemRandomization) {
639  state.fragment.needsMemFragment = true;
640  }
641  needsMemRandomization = true;
642  }
643  return state.immutableValueLowering.lower();
644  });
645 
646  if (failed(result))
647  return signalPassFailure();
648 
649  auto randomInitFragmentName =
650  FlatSymbolRefAttr::get(context, "RANDOM_INIT_FRAGMENT");
651  auto randomInitRegFragmentName =
652  FlatSymbolRefAttr::get(context, "RANDOM_INIT_REG_FRAGMENT");
653  auto randomInitMemFragmentName =
654  FlatSymbolRefAttr::get(context, "RANDOM_INIT_MEM_FRAGMENT");
655 
656  for (auto &[_, state] : moduleLoweringStates) {
657  const auto &info = state.fragment;
658  if (!info.needsRegFragment && !info.needsMemFragment) {
659  // If neither is emitted, just skip it.
660  continue;
661  }
662 
663  SmallVector<Attribute> fragmentAttrs;
664  auto module = state.module;
665  if (auto others =
666  module->getAttrOfType<ArrayAttr>(emit::getFragmentsAttrName()))
667  fragmentAttrs = llvm::to_vector(others);
668 
669  if (info.needsRegFragment)
670  fragmentAttrs.push_back(randomInitRegFragmentName);
671  if (info.needsMemFragment)
672  fragmentAttrs.push_back(randomInitMemFragmentName);
673  fragmentAttrs.push_back(randomInitFragmentName);
674 
675  module->setAttr(emit::getFragmentsAttrName(),
676  ArrayAttr::get(context, fragmentAttrs));
677  }
678 
679  // Mark all ops which can have clock types as illegal.
680  SeqToSVTypeConverter typeConverter;
681  ConversionTarget target(*context);
682  target.addIllegalDialect<SeqDialect>();
683  target.markUnknownOpDynamicallyLegal(isLegalOp);
684 
685  RewritePatternSet patterns(context);
686  patterns.add<CompRegLower<CompRegOp>>(typeConverter, context, lowerToAlwaysFF,
687  moduleLoweringStates);
688  patterns.add<CompRegLower<CompRegClockEnabledOp>>(
689  typeConverter, context, lowerToAlwaysFF, moduleLoweringStates);
690  patterns.add<FromImmutableLowering>(typeConverter, context,
691  moduleLoweringStates);
692  patterns.add<ClockCastLowering<seq::FromClockOp>>(typeConverter, context);
693  patterns.add<ClockCastLowering<seq::ToClockOp>>(typeConverter, context);
694  patterns.add<ClockGateLowering>(typeConverter, context);
695  patterns.add<ClockInverterLowering>(typeConverter, context);
696  patterns.add<ClockMuxLowering>(typeConverter, context);
697  patterns.add<ClockDividerLowering>(typeConverter, context);
698  patterns.add<ClockConstLowering>(typeConverter, context);
699  patterns.add<TypeConversionPattern>(typeConverter, context);
700  patterns.add<AggregateConstantPattern>(typeConverter, context);
701 
702  if (failed(applyPartialConversion(circuit, target, std::move(patterns))))
703  signalPassFailure();
704 
705  auto loc = UnknownLoc::get(context);
706  auto b = ImplicitLocOpBuilder::atBlockBegin(loc, circuit.getBody());
707  if (needsRegRandomization || needsMemRandomization) {
708  b.create<sv::MacroDeclOp>("ENABLE_INITIAL_REG_");
709  b.create<sv::MacroDeclOp>("ENABLE_INITIAL_MEM_");
710  if (needsRegRandomization) {
711  b.create<sv::MacroDeclOp>("FIRRTL_BEFORE_INITIAL");
712  b.create<sv::MacroDeclOp>("FIRRTL_AFTER_INITIAL");
713  }
714  if (needsMemRandomization)
715  b.create<sv::MacroDeclOp>("RANDOMIZE_MEM_INIT");
716  b.create<sv::MacroDeclOp>("RANDOMIZE_REG_INIT");
717  b.create<sv::MacroDeclOp>("RANDOMIZE");
718  b.create<sv::MacroDeclOp>("RANDOMIZE_DELAY");
719  b.create<sv::MacroDeclOp>("RANDOM");
720  b.create<sv::MacroDeclOp>("INIT_RANDOM");
721  b.create<sv::MacroDeclOp>("INIT_RANDOM_PROLOG_");
722  }
723 
724  bool hasRegRandomization = needsRegRandomization && !disableRegRandomization;
725  bool hasMemRandomization = needsMemRandomization && !disableMemRandomization;
726  if (!hasRegRandomization && !hasMemRandomization)
727  return;
728 
729  // Build macros for FIRRTL-style register and memory initialization.
730  // Insert them at the start of the module, after any other verbatims.
731  for (Operation &op : *circuit.getBody()) {
732  if (!isa<sv::VerbatimOp, sv::IfDefOp>(&op)) {
733  b.setInsertionPoint(&op);
734  break;
735  }
736  }
737 
738  // Create SYNTHESIS/VERILATOR macros if other passes have not done so already.
739  {
740  StringSet<> symbols;
741  for (auto sym : circuit.getOps<sv::MacroDeclOp>())
742  symbols.insert(sym.getName());
743  if (!symbols.count("SYNTHESIS"))
744  b.create<sv::MacroDeclOp>("SYNTHESIS");
745  if (!symbols.count("VERILATOR"))
746  b.create<sv::MacroDeclOp>("VERILATOR");
747  }
748 
749  // TODO: We could have an operation for macros and uses of them, and
750  // even turn them into symbols so we can DCE unused macro definitions.
751  auto emitGuardedDefine = [&](StringRef guard, StringRef defName,
752  StringRef defineTrue = "",
753  StringRef defineFalse = StringRef()) {
754  if (!defineFalse.data()) {
755  assert(defineTrue.data() && "didn't define anything");
756  b.create<sv::IfDefOp>(
757  guard, [&]() { b.create<sv::MacroDefOp>(defName, defineTrue); });
758  } else {
759  b.create<sv::IfDefOp>(
760  guard,
761  [&]() {
762  if (defineTrue.data())
763  b.create<sv::MacroDefOp>(defName, defineTrue);
764  },
765  [&]() { b.create<sv::MacroDefOp>(defName, defineFalse); });
766  }
767  };
768 
769  // Helper function to emit #ifndef guard.
770  auto emitGuard = [&](const char *guard, llvm::function_ref<void(void)> body) {
771  b.create<sv::IfDefOp>(
772  guard, []() {}, body);
773  };
774 
775  b.create<emit::FragmentOp>(randomInitFragmentName.getAttr(), [&] {
776  b.create<sv::VerbatimOp>(
777  "// Standard header to adapt well known macros for "
778  "register randomization.");
779 
780  b.create<sv::VerbatimOp>(
781  "\n// RANDOM may be set to an expression that produces a 32-bit "
782  "random unsigned value.");
783  emitGuardedDefine("RANDOM", "RANDOM", StringRef(), "$random");
784 
785  b.create<sv::VerbatimOp>(
786  "\n// Users can define INIT_RANDOM as general code that gets "
787  "injected "
788  "into the\n// initializer block for modules with registers.");
789  emitGuardedDefine("INIT_RANDOM", "INIT_RANDOM", StringRef(), "");
790 
791  b.create<sv::VerbatimOp>(
792  "\n// If using random initialization, you can also define "
793  "RANDOMIZE_DELAY to\n// customize the delay used, otherwise 0.002 "
794  "is used.");
795  emitGuardedDefine("RANDOMIZE_DELAY", "RANDOMIZE_DELAY", StringRef(),
796  "0.002");
797 
798  b.create<sv::VerbatimOp>(
799  "\n// Define INIT_RANDOM_PROLOG_ for use in our modules below.");
800  emitGuard("INIT_RANDOM_PROLOG_", [&]() {
801  b.create<sv::IfDefOp>(
802  "RANDOMIZE",
803  [&]() {
804  emitGuardedDefine("VERILATOR", "INIT_RANDOM_PROLOG_",
805  "`INIT_RANDOM",
806  "`INIT_RANDOM #`RANDOMIZE_DELAY begin end");
807  },
808  [&]() { b.create<sv::MacroDefOp>("INIT_RANDOM_PROLOG_", ""); });
809  });
810  });
811 
812  if (hasMemRandomization) {
813  b.create<emit::FragmentOp>(randomInitMemFragmentName.getAttr(), [&] {
814  b.create<sv::VerbatimOp>("\n// Include rmemory initializers in init "
815  "blocks unless synthesis is set");
816  emitGuard("RANDOMIZE", [&]() {
817  emitGuardedDefine("RANDOMIZE_MEM_INIT", "RANDOMIZE");
818  });
819  emitGuard("SYNTHESIS", [&] {
820  emitGuardedDefine("ENABLE_INITIAL_MEM_", "ENABLE_INITIAL_MEM_",
821  StringRef(), "");
822  });
823  b.create<sv::VerbatimOp>("");
824  });
825  }
826 
827  if (hasRegRandomization) {
828  b.create<emit::FragmentOp>(randomInitRegFragmentName.getAttr(), [&] {
829  b.create<sv::VerbatimOp>("\n// Include register initializers in init "
830  "blocks unless synthesis is set");
831  emitGuard("RANDOMIZE", [&]() {
832  emitGuardedDefine("RANDOMIZE_REG_INIT", "RANDOMIZE");
833  });
834  emitGuard("SYNTHESIS", [&] {
835  emitGuardedDefine("ENABLE_INITIAL_REG_", "ENABLE_INITIAL_REG_",
836  StringRef(), "");
837  });
838  b.create<sv::VerbatimOp>("");
839  });
840  }
841 }
842 
843 std::unique_ptr<Pass>
844 circt::createLowerSeqToSVPass(const LowerSeqToSVOptions &options) {
845  return std::make_unique<SeqToSVPass>(options);
846 }
assert(baseType &&"element must be base type")
static FIRRTLBaseType convertType(FIRRTLBaseType type)
Returns null type if no conversion is needed.
Definition: DropConst.cpp:32
static bool isLegalType(Type ty)
Definition: SeqToSV.cpp:546
static bool isLegalOp(Operation *op)
Definition: SeqToSV.cpp:564
FIR memory lowering helper.
UniqueConfigs collectMemories(ArrayRef< hw::HWModuleOp > modules)
Groups memories by their kind from the whole design.
void lowerMemoriesInModule(hw::HWModuleOp module, ArrayRef< MemoryConfig > mems)
Lowers a group of memories from the same module.
hw::HWModuleGeneratedOp createMemoryModule(FirMemConfig &mem, ArrayRef< seq::FirMemOp > memOps)
Creates the generated module for a given configuration.
Lower FirRegOp to sv.reg and sv.always.
bool needsRegRandomization() const
def create(data_type, value)
Definition: hw.py:393
Definition: sv.py:15
def create(value)
Definition: sv.py:106
Definition: sv.py:68
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:55
Value createOrFoldNot(Location loc, Value value, OpBuilder &builder, bool twoState=false)
Create a `‘Not’' gate on a value.
Definition: CombOps.cpp:48
StringRef getFragmentsAttrName()
Return the name of the fragments array attribute.
Definition: EmitOps.h:32
FailureOr< seq::InitialOp > mergeInitialOps(Block *block)
Definition: SeqOps.cpp:1093
mlir::ArrayAttr getSVAttributes(mlir::Operation *op)
Return all the SV attributes of an operation, or null if there are none.
void setSVAttributes(mlir::Operation *op, mlir::ArrayAttr attrs)
Set the SV attributes of an operation.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21
std::unique_ptr< mlir::Pass > createLowerSeqToSVPass(const LowerSeqToSVOptions &options={})
Definition: SeqToSV.cpp:844
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
Definition: Naming.cpp:47
Definition: seq.py:1
def reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)
Definition: seq.py:21
void runOnOperation() override
Definition: SeqToSV.cpp:588
Generic pattern which replaces an operation by one of the same operation name, but with converted att...