CIRCT 24.0.0git
Loading...
Searching...
No Matches
InjectDUTHierarchy.cpp
Go to the documentation of this file.
1//===- InjectDUTHierarchy.cpp - Add hierarchy above the DUT ---------------===//
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// Implementation of the SiFive transform InjectDUTHierarchy. This moves all
10// the logic inside the DUT into a new module named using an annotation.
11//
12// As the terminology in this pass is a constant source of confusion, FIGURE 1
13// below, and the accompanying description of terms is provided to clarify what
14// is going on.
15//
16// BEFORE AFTER
17// +-------------+ +-------------+
18// | DUT | | DUT |
19// | | | +---------+ |
20// | | | | WRAPPER | |
21// | | ====> | | | |
22// | LOGIC | | | LOGIC | |
23// | | | +---------+ |
24// +-------------+ +-------------+
25//
26// FIGURE 1: A graphical view of this pass
27//
28// In FIGURE 1, the DUT (design under test which roughly is the unit of
29// compilation excluding all testharness, testbenches, or tests) is the module
30// in the circuit which is annotated with a `MarkDUTAnnotation`. Inside the
31// DUT, there exists some LOGIC. This is the complete contents of all
32// operations inside the DUT module. Logically, this pass takes the LOGIC and
33// puts it into a new MODULE, called the WRAPPER.
34//
35// This pass operates in two modes, moderated by a `moveDut` boolean parameter
36// on the controlling annotation. When `moveDut=false`, the DUT in FIGURE 1 is
37// treated as the design under test. When `moveDut=true`, the WRAPPER in FIGURE
38// 1 is treated as the design under test. Mechanically, this means that
39// annotations on the DUT will be moved to the wrapper.
40//
41// The names of the WRAPPER and DUT change based on the mode. If
42// `moveDut=false`, then the WRAPPER is named using the `name` field of the
43// controlling annotation and the DUT gets the name of the original DUT. If
44// `moveDut=true`, then the DUT is named using the `name` field and the WRAPPER
45// gets the name of the original DUT.
46//
47// This pass is closely coupled to `ExtractInstances`. This pass is intended to
48// be used to create a "space" where modules can be extracted or groups of
49// modules can be extracted to. Commonly, the LOGIC will be extracted to the
50// WRAPPER, memories will be extracted to a MEMORIES module, and other things
51// (clock gates and blackboxes) will be extracted to other modules.
52//
53//===----------------------------------------------------------------------===//
54
66#include "circt/Support/Debug.h"
67#include "mlir/Pass/Pass.h"
68#include "llvm/Support/Debug.h"
69
70#define DEBUG_TYPE "firrtl-inject-dut-hier"
71
72namespace circt {
73namespace firrtl {
74#define GEN_PASS_DEF_INJECTDUTHIERARCHY
75#include "circt/Dialect/FIRRTL/Passes.h.inc"
76} // namespace firrtl
77} // namespace circt
78
79using namespace circt;
80using namespace firrtl;
81
82namespace {
83struct InjectDUTHierarchy
84 : public circt::firrtl::impl::InjectDUTHierarchyBase<InjectDUTHierarchy> {
85 void runOnOperation() override;
86};
87} // namespace
88
89/// Add an extra level of hierarchy to a hierarchical path that places the
90/// wrapper instance after the DUT. This appends to the existing path
91/// immediately after the `dut`.
92///
93/// E.g., this is converting:
94///
95/// firrtl.hierpath [@Top::@dut, @DUT]
96///
97/// Into:
98///
99/// firrtl.hierpath [@Top::@dut, @DUT::@wrapper, @Wrapper]
100///
101/// The `oldDutNameAttr` parameter controls the insertion point. I.e., this is
102/// the location of a module wehre an insertion will happen. By separating this
103/// from the `dut` paramter, this allows this function to work for both the
104/// `moveDut=false` and `moveDut=true` cases. In the `moveDut=false` case the
105/// `dut` and `oldDutNameAttr` refer to the same module.
106static void addHierarchy(hw::HierPathOp path, FModuleOp dut,
107 InstanceOp wrapperInst, StringAttr oldDutNameAttr) {
108
109 auto namepath = path.getNamepath().getValue();
110
111 size_t nlaIdx = 0;
112 SmallVector<Attribute> newNamepath;
113 newNamepath.reserve(namepath.size() + 1);
114 while (path.modPart(nlaIdx) != oldDutNameAttr)
115 newNamepath.push_back(namepath[nlaIdx++]);
116 newNamepath.push_back(hw::InnerRefAttr::get(dut.getModuleNameAttr(),
117 getInnerSymName(wrapperInst)));
118
119 // Add the extra level of hierarchy.
120 if (auto dutRef = dyn_cast<hw::InnerRefAttr>(namepath[nlaIdx]))
121 newNamepath.push_back(hw::InnerRefAttr::get(
122 wrapperInst.getModuleNameAttr().getAttr(), dutRef.getName()));
123 else
124 newNamepath.push_back(
125 FlatSymbolRefAttr::get(wrapperInst.getModuleNameAttr().getAttr()));
126
127 // Add anything left over.
128 auto back = namepath.drop_front(nlaIdx + 1);
129 newNamepath.append(back.begin(), back.end());
130 path.setNamepathAttr(ArrayAttr::get(dut.getContext(), newNamepath));
131}
132
133void InjectDUTHierarchy::runOnOperation() {
135
136 CircuitOp circuit = getOperation();
137
138 /// The wrapper module that is created inside the DUT to house all its logic.
139 FModuleOp wrapper;
140
141 /// The name of the new module to create under the DUT.
142 StringAttr wrapperName;
143
144 /// Optional name of the instance of the new module.
145 StringRef wrapperInstanceName;
146
147 /// If true, then move the MarkDUTAnnotation to the newly created module.
148 bool moveDut = false;
149
150 /// Mutable indicator that an error occurred for some reason. If this is ever
151 /// true, then the pass can just signalPassFailure.
152 bool error = false;
153
154 // Do not remove the injection annotation as this is necessary to additionally
155 // influence ExtractInstances.
156 for (Annotation anno : AnnotationSet(circuit)) {
157 if (!anno.isClass(injectDUTHierarchyAnnoClass))
158 continue;
159
160 auto name = anno.getMember<StringAttr>("name");
161 if (!name) {
162 emitError(circuit->getLoc())
163 << "contained a malformed "
164 "'sifive.enterprise.firrtl.InjectDUTHierarchyAnnotation' "
165 "annotation that did not contain a 'name' field";
166 error = true;
167 continue;
168 }
169
170 if (wrapperName) {
171 emitError(circuit->getLoc())
172 << "contained multiple "
173 "'sifive.enterprise.firrtl.InjectDUTHierarchyAnnotation' "
174 "annotations when at most one is allowed";
175 error = true;
176 continue;
177 }
178
179 wrapperName = name;
180 if (auto instanceName = anno.getMember<StringAttr>("instanceName"))
181 wrapperInstanceName = instanceName.getValue();
182 if (auto moveDutAnnoAttr = anno.getMember<BoolAttr>("moveDut"))
183 moveDut = moveDutAnnoAttr.getValue();
184 }
185
186 if (error)
187 return signalPassFailure();
188
189 // The prerequisites for the pass to run were not met. Indicate that no work
190 // was done and exit.
191 if (!wrapperName)
192 return markAllAnalysesPreserved();
193
194 // A DUT must exist in order to continue. The pass could silently ignore this
195 // case and do nothing, but it is better to provide an error.
196 InstanceInfo &instanceInfo = getAnalysis<InstanceInfo>();
197 if (!instanceInfo.getDut()) {
198 emitError(circuit->getLoc())
199 << "contained a '" << injectDUTHierarchyAnnoClass << "', but no '"
200 << markDUTAnnoClass << "' was provided";
201 return signalPassFailure();
202 }
203
204 /// The design-under-test (DUT). This is kept up-to-date by the pass as the
205 /// DUT changes due to internal logic.
206 FModuleOp dut = cast<FModuleOp>(instanceInfo.getDut());
207
208 // Create a module that will become the new DUT. The original DUT is renamed
209 // to become the wrapper. This is done to save copying into the wrapper.
210 // While the logical movement is "copy the body of the DUT into a wrapper", it
211 // is mechanically more straigthforward to make the DUT the wrappper. After
212 // this block finishes, the "dut" and "wrapper" variables are set correctly.
213 // This logic is intentionally put into a block to avoid confusion while the
214 // dut and wrapper do not match the logical definition.
215 OpBuilder b(circuit.getContext());
216 CircuitNamespace circuitNS(circuit);
217 b.setInsertionPointAfter(dut);
218
219 // After this, he original DUT module is now the "wrapper". The new module we
220 // just created becomes the "DUT".
221 auto oldDutNameAttr = dut.getNameAttr();
222 wrapper = dut;
223 dut = FModuleOp::create(b, dut.getLoc(), oldDutNameAttr,
224 dut.getConventionAttr(), dut.getPorts());
225
226 // Finish setting up the DUT and the Wrapper. This depends on if we are in
227 // `moveDut` mode or not. If `moveDut=false` (the normal, legacy behavior),
228 // then the wrapper is a wrapper of logic inside the original DUT. The newly
229 // created module to instantiate the wrapper becomes the DUT. In this mode,
230 // we need to move all annotations over to the new DUT. If `moveDut=true`,
231 // then we need to move all the annotations/information from the wrapper onto
232 // the DUT.
233 //
234 // This pass shouldn't create new public modules. It should only preserve the
235 // existing public modules. In "moveDut" mode, then the wrapper is the new
236 // DUT and we should move the publicness from the old DUT to the wrapper.
237 // When not in "moveDut" mode, then the wrapper should be made private.
238 //
239 // Note: `movedDut=true` violates the FIRRTL ABI unless the user it doing
240 // something clever with module prefixing. Because this annotation is already
241 // outside the specification, this workflow is allowed even though it violates
242 // the FIRRTL ABI. The mid-term plan is to remove this pass to avoid the tech
243 // debt that it creates.
244 auto emptyArray = b.getArrayAttr({});
245 auto name = circuitNS.newName(wrapperName.getValue());
246 if (moveDut) {
247 dut.setPortAnnotationsAttr(emptyArray);
248 dut.setName(b.getStringAttr(name));
249 // If the wrapper is the circuit's main module, then we need to rename the
250 // circuit. This mandates that the wrapper is now public.
251 if (circuit.getNameAttr() == wrapper.getNameAttr()) {
252 circuit.setNameAttr(dut.getNameAttr());
253 dut.setPublic();
254 } else {
255 dut.setPrivate();
256 }
257 // The DUT name has changed. Rewrite instances to use the new DUT name.
258 InstanceGraph &instanceGraph = getAnalysis<InstanceGraph>();
259 for (auto *use : instanceGraph.lookup(wrapper.getNameAttr())->uses()) {
260 auto instanceOp = use->getInstance<InstanceOp>();
261 if (!instanceOp) {
262 use->getInstance().emitOpError()
263 << "instantiates the design-under-test, but "
264 "is not a 'firrtl.instance'";
265 return signalPassFailure();
266 }
267 instanceOp.setModuleNameAttr(FlatSymbolRefAttr::get(dut.getNameAttr()));
268 }
269 } else {
270 dut.setVisibility(wrapper.getVisibility());
271 dut.setAnnotationsAttr(wrapper.getAnnotationsAttr());
272 dut.setPortAnnotationsAttr(wrapper.getPortAnnotationsAttr());
273 wrapper.setPrivate();
274 wrapper.setAnnotationsAttr(emptyArray);
275 wrapper.setPortAnnotationsAttr(emptyArray);
276 wrapper.setName(name);
277 }
278
279 // Instantiate the wrapper inside the DUT and wire it up.
280 b.setInsertionPointToStart(dut.getBodyBlock());
281 hw::InnerSymbolNamespace dutNS(dut);
282 auto instanceName = wrapperInstanceName.empty() ? wrapper.getModuleName()
283 : wrapperInstanceName;
284 auto wrapperInst = InstanceOp::create(
285 b, b.getUnknownLoc(), wrapper, instanceName, NameKindEnum::DroppableName,
286 ArrayRef<Attribute>{}, ArrayRef<Attribute>{}, false, false,
287 hw::InnerSymAttr::get(b.getStringAttr(dutNS.newName(instanceName))));
288 for (const auto &pair : llvm::enumerate(wrapperInst.getResults())) {
289 Value lhs = dut.getArgument(pair.index());
290 Value rhs = pair.value();
291 if (dut.getPortDirection(pair.index()) == Direction::In)
292 std::swap(lhs, rhs);
293 emitConnect(b, b.getUnknownLoc(), lhs, rhs);
294 }
295
296 // Compute a set of paths that are used _inside_ the wrapper.
297 DenseSet<StringAttr> dutPaths, dutPortSyms;
298 for (auto anno : AnnotationSet(dut)) {
299 auto sym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
300 if (sym)
301 dutPaths.insert(sym.getAttr());
302 }
303 for (size_t i = 0, e = dut.getNumPorts(); i != e; ++i) {
304 auto portSym = dut.getPortSymbolAttr(i);
305 if (portSym)
306 dutPortSyms.insert(portSym.getSymName());
307 for (auto anno : AnnotationSet::forPort(dut, i)) {
308 auto sym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
309 if (sym)
310 dutPaths.insert(sym.getAttr());
311 }
312 }
313
314 LLVM_DEBUG({
315 llvm::dbgs() << "DUT Symbol Users:\n";
316 for (auto path : dutPaths)
317 llvm::dbgs() << " - " << FlatSymbolRefAttr::get(path) << "\n";
318 llvm::dbgs() << "Port Symbols:\n";
319 for (auto sym : dutPortSyms)
320 llvm::dbgs() << " - " << FlatSymbolRefAttr::get(sym) << "\n";
321 });
322
323 // Update NLAs involving the DUT.
324 //
325 // In the `moveDut=true` case, the WRAPPER will have the `MarkDUTAnnotation`
326 // moved onto it and this will be the "design-under-test" from the perspective
327 // of later passes. In the `moveDut=false` case, the DUT will be the
328 // "design-under-test.
329 //
330 // There are three cases to consider:
331 // 1. The DUT or a DUT port is a leaf ref. Do nothing.
332 // 2. The DUT is the root. Update the root module to be the wrapper.
333 // 3. The NLA passes through the DUT. Remove the original InnerRef and
334 // replace it with two InnerRefs: (1) on the DUT and (2) one the wrapper.
335 LLVM_DEBUG(llvm::dbgs() << "Processing hierarchical paths:\n");
336 auto &nlaTable = getAnalysis<NLATable>();
337 DenseMap<StringAttr, hw::HierPathOp> dutRenames;
338 for (auto nla : llvm::make_early_inc_range(nlaTable.lookup(oldDutNameAttr))) {
339 LLVM_DEBUG(llvm::dbgs() << " - " << nla << "\n");
340 auto namepath = nla.getNamepath().getValue();
341
342 // The DUT is the root module. Just update the root module to point at the
343 // wrapper.
344 //
345 // TODO: It _may_ be desirable to only do this in the `moveDut=true` case.
346 // In the `moveDut=false` case, this will change the semantic of the
347 // annotation if the annotation user is assuming that the annotation root is
348 // locked to the DUT. However, annotations are not supposed to have
349 // semantics like this.
350 if (nla.root() == oldDutNameAttr) {
351 assert(namepath.size() > 1 && "namepath size must be greater than one");
352 SmallVector<Attribute> newNamepath{hw::InnerRefAttr::get(
353 wrapper.getNameAttr(),
354 cast<hw::InnerRefAttr>(namepath.front()).getName())};
355 auto tail = namepath.drop_front();
356 newNamepath.append(tail.begin(), tail.end());
357 nla->setAttr("namepath", b.getArrayAttr(newNamepath));
358 continue;
359 }
360
361 // The path ends at the DUT. This may be a reference path (ends in
362 // hw::InnerRefAttr) or a module path (ends in FlatSymbolRefAttr). There
363 // are a number of patterns to disambiguate:
364 //
365 // NOTE: the _DUT_ is the new DUT and all the original DUT contents are put
366 // inside the DUT in the _wrapper_.
367 //
368 // 1. Reference path on DUT port. Do nothing.
369 // 2. Reference path on component. Add hierarchy
370 // 3. Module path on DUT/DUT port. Clone path, add hier to original path.
371 // 4. Module path on component. Add hierarchy.
372 //
373 if (nla.leafMod() == oldDutNameAttr) {
374 // Case (1): ref path targeting a DUT port. Do nothing. When
375 // `moveDut=true`, this is always false.
376 if (nla.isComponent() && dutPortSyms.count(nla.ref()))
377 continue;
378
379 // Case (3): the module path is used by the DUT module or a port. Create a
380 // clone of the path and update dutRenames so that this path symbol will
381 // get updated for annotations on the DUT or on its ports.
382 if (nla.isModule() && dutPaths.contains(nla.getSymNameAttr())) {
383 OpBuilder::InsertionGuard guard(b);
384 b.setInsertionPoint(nla);
385 auto clone = cast<hw::HierPathOp>(b.clone(*nla));
386 clone.setSymNameAttr(b.getStringAttr(
387 circuitNS.newName(clone.getSymNameAttr().getValue())));
388 dutRenames.insert({nla.getSymNameAttr(), clone});
389 }
390
391 // Cases (2), (3), and (4): fallthrough to add hierarchy to original path.
392 }
393
394 addHierarchy(nla, dut, wrapperInst, oldDutNameAttr);
395 }
396
397 SmallVector<Annotation> newAnnotations;
398 auto removeAndUpdateNLAs = [&](Annotation anno) -> bool {
399 auto sym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
400 if (!sym)
401 return false;
402 if (!dutRenames.count(sym.getAttr()))
403 return false;
404 anno.setMember(
405 "circt.nonlocal",
406 FlatSymbolRefAttr::get(dutRenames[sym.getAttr()].getSymNameAttr()));
407 newAnnotations.push_back(anno);
408 return true;
409 };
410
411 // Replace any annotations on the DUT or DUT ports to use the cloned path.
412 AnnotationSet annotations(dut);
413 annotations.removeAnnotations(removeAndUpdateNLAs);
414 annotations.addAnnotations(newAnnotations);
415 annotations.applyToOperation(dut);
416 for (size_t i = 0, e = dut.getNumPorts(); i != e; ++i) {
417 newAnnotations.clear();
418 auto annotations = AnnotationSet::forPort(dut, i);
419 annotations.removeAnnotations(removeAndUpdateNLAs);
420 annotations.addAnnotations(newAnnotations);
421 annotations.applyToPort(dut, i);
422 }
423
424 // Update rwprobe operations' local innerrefs within the module.
425 wrapper.walk([&](RWProbeOp rwp) {
426 rwp.setTargetAttr(hw::InnerRefAttr::get(wrapper.getModuleNameAttr(),
427 rwp.getTarget().getName()));
428 });
429}
assert(baseType &&"element must be base type")
static void addHierarchy(hw::HierPathOp path, FModuleOp dut, InstanceOp wrapperInst, StringAttr oldDutNameAttr)
Add an extra level of hierarchy to a hierarchical path that places the wrapper instance after the DUT...
#define CIRCT_DEBUG_SCOPED_PASS_LOGGER(PASS)
Definition Debug.h:70
static AnnotationSet forPort(FModuleLike op, size_t portNo)
Get an annotation set for the specified port.
igraph::ModuleOpInterface getDut()
Return the design-under-test if one is defined for the circuit, otherwise return null.
llvm::iterator_range< UseIterator > uses()
InstanceGraphNode * lookup(ModuleOpInterface op)
Look up an InstanceGraphNode for a module.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs, bool warnOnTruncation=false)
Emit a connect between two values.
StringAttr getInnerSymName(Operation *op)
Return the StringAttr for the inner_sym name, if it exists.
Definition FIRRTLOps.h:108
std::map< std::string, std::set< std::string > > InstanceGraph
Iterates over the handshake::FuncOp's in the program to build an instance graph.
void error(Twine message)
Definition LSPUtils.cpp:16
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.