CIRCT  20.0.0git
ResolvePaths.cpp
Go to the documentation of this file.
1 //===- ResolvePaths.cpp - Resolve path operations ---------------*- 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 //
9 // This file contains the ResolvePathsPass.
10 //
11 //===----------------------------------------------------------------------===//
12 
17 #include "mlir/IR/ImplicitLocOpBuilder.h"
18 #include "mlir/Pass/Pass.h"
19 
20 namespace circt {
21 namespace firrtl {
22 #define GEN_PASS_DEF_RESOLVEPATHS
23 #include "circt/Dialect/FIRRTL/Passes.h.inc"
24 } // namespace firrtl
25 } // namespace circt
26 
27 using namespace circt;
28 using namespace firrtl;
29 
30 namespace {
31 struct PathResolver {
32  PathResolver(CircuitOp circuit, InstanceGraph &instanceGraph)
33  : circuit(circuit), symbolTable(circuit), instanceGraph(instanceGraph),
34  instancePathCache(instanceGraph), hierPathCache(circuit, symbolTable),
35  builder(OpBuilder::atBlockBegin(circuit->getBlock())) {}
36 
37  /// This function will find the operation targeted and create a hierarchical
38  /// path operation if needed. If the target is resolved, the op will either
39  /// be a reference to the HierPathOp, or null if no HierPathOp was needed.
40  LogicalResult resolveHierPath(Location loc, FModuleOp owningModule,
41  const AnnoPathValue &target,
42  FlatSymbolRefAttr &result) {
43 
44  // We want to root this path at the top level module, or in the case of an
45  // unreachable module, we settle for as high as we can get.
46  auto module = target.ref.getModule();
47  if (!target.instances.empty())
48  module = target.instances.front()->getParentOfType<FModuleLike>();
49  auto *node = instanceGraph[module];
50  while (true) {
51  // If the path is rooted at the owning module, we're done.
52  if (node->getModule() == owningModule)
53  break;
54  // If there are no more parents, then the path op lives in a different
55  // hierarchy than the HW object it references, which is an error.
56  if (node->noUses())
57  return emitError(loc)
58  << "unable to resolve path relative to owning module "
59  << owningModule.getModuleNameAttr();
60  // If there is more than one instance of this module, then the path
61  // operation is ambiguous, which is an error.
62  if (!node->hasOneUse()) {
63  auto diag = emitError(loc) << "unable to uniquely resolve target due "
64  "to multiple instantiation";
65  for (auto *use : node->uses())
66  diag.attachNote(use->getInstance().getLoc()) << "instance here";
67  return diag;
68  }
69  node = (*node->usesBegin())->getParent();
70  }
71 
72  // If the path is empty then this is a local reference and we should not
73  // construct a HierPathOp.
74  if (target.instances.empty()) {
75  return success();
76  }
77 
78  // Transform the instances into a list of FlatSymbolRefs.
79  SmallVector<Attribute> insts;
80  insts.reserve(target.instances.size());
81  std::transform(target.instances.begin(), target.instances.end(),
82  std::back_inserter(insts), [&](InstanceOp instance) {
83  return OpAnnoTarget(instance).getNLAReference(
84  namespaces[instance->getParentOfType<FModuleLike>()]);
85  });
86 
87  // Push a reference to the current module.
88  insts.push_back(
89  FlatSymbolRefAttr::get(target.ref.getModule().getModuleNameAttr()));
90 
91  // Return the hierchical path.
92  auto instAttr = ArrayAttr::get(circuit.getContext(), insts);
93 
94  result = hierPathCache.getRefFor(instAttr);
95 
96  return success();
97  }
98 
99  LogicalResult resolve(OwningModuleCache &cache, UnresolvedPathOp unresolved) {
100  auto loc = unresolved.getLoc();
101  ImplicitLocOpBuilder b(loc, unresolved);
102  auto *context = b.getContext();
103 
104  /// Spelling takes the form
105  /// "OMReferenceTarget:~Circuit|Foo/bar:Bar>member".
106  auto target = unresolved.getTarget();
107 
108  // OMDeleted nodes do not have a target, so it is impossible to resolve
109  // them to a real path. We create a special constant for these path
110  // values.
111  if (target.consume_front("OMDeleted:")) {
112  if (!target.empty())
113  return emitError(loc, "OMDeleted references can not have targets");
114  // Deleted targets are turned into OMReference targets with a dangling
115  // id
116  // - i.e. the id is not attached to any target.
117  auto targetKind = TargetKindAttr::get(context, TargetKind::Reference);
118  auto id = DistinctAttr::create(UnitAttr::get(context));
119  auto resolved = b.create<PathOp>(targetKind, id);
120  unresolved->replaceAllUsesWith(resolved);
121  unresolved.erase();
122  return success();
123  }
124 
125  // Parse the OM target kind.
126  TargetKind targetKind;
127  if (target.consume_front("OMDontTouchedReferenceTarget")) {
128  targetKind = TargetKind::DontTouch;
129  } else if (target.consume_front("OMInstanceTarget")) {
130  targetKind = TargetKind::Instance;
131  } else if (target.consume_front("OMMemberInstanceTarget")) {
132  targetKind = TargetKind::MemberInstance;
133  } else if (target.consume_front("OMMemberReferenceTarget")) {
134  targetKind = TargetKind::MemberReference;
135  } else if (target.consume_front("OMReferenceTarget")) {
136  targetKind = TargetKind::Reference;
137  } else {
138  return emitError(loc)
139  << "unknown or missing OM reference type in target string: \""
140  << target << "\"";
141  }
142  auto targetKindAttr = TargetKindAttr::get(context, targetKind);
143 
144  // Parse the target.
145  if (!target.consume_front(":"))
146  return emitError(loc, "expected ':' in target string");
147 
148  auto token = tokenizePath(target);
149  if (!token)
150  return emitError(loc)
151  << "cannot tokenize annotation path \"" << target << "\"";
152 
153  // Resolve the target to a target.
154  auto path = resolveEntities(*token, circuit, symbolTable, targetCache);
155  if (!path)
156  return failure();
157 
158  // Make sure that we are targeting a leaf of the operation. That way lower
159  // types can't split a single reference into many, and cause ambiguity. If
160  // we are targeting a module, the type will be null.
161  if (Type targetType = path->ref.getType()) {
162  auto fieldId = path->fieldIdx;
163  auto baseType = type_dyn_cast<FIRRTLBaseType>(targetType);
164  if (!baseType)
165  return emitError(loc, "unable to target non-hardware type ")
166  << targetType;
167  targetType = hw::FieldIdImpl::getFinalTypeByFieldID(baseType, fieldId);
168  if (type_isa<BundleType, FVectorType>(targetType))
169  return emitError(loc, "unable to target aggregate type ") << targetType;
170  }
171 
172  auto owningModule = cache.lookup(unresolved);
173  StringRef moduleName = "nullptr";
174  if (owningModule)
175  moduleName = owningModule.getModuleName();
176  if (!owningModule)
177  return unresolved->emitError("path does not have a single owning module");
178 
179  // Resolve a path to the operation in question.
180  FlatSymbolRefAttr hierPathName;
181  if (failed(resolveHierPath(loc, owningModule, *path, hierPathName)))
182  return failure();
183 
184  auto createAnnotation = [&](FlatSymbolRefAttr hierPathName) {
185  // Create a unique ID.
186  auto id = DistinctAttr::create(UnitAttr::get(context));
187 
188  // Create the annotation.
189  NamedAttrList fields;
190  fields.append("id", id);
191  fields.append("class", StringAttr::get(context, "circt.tracker"));
192  if (hierPathName)
193  fields.append("circt.nonlocal", hierPathName);
194  if (path->fieldIdx != 0)
195  fields.append("circt.fieldID", b.getI64IntegerAttr(path->fieldIdx));
196 
197  return DictionaryAttr::get(context, fields);
198  };
199 
200  // Create the annotation(s).
201  Attribute annotation = createAnnotation(hierPathName);
202 
203  // Attach the annotation(s) to the target.
204  auto annoTarget = path->ref;
205  auto targetAnnotations = annoTarget.getAnnotations();
206  targetAnnotations.addAnnotations({annotation});
207  if (targetKindAttr.getValue() == TargetKind::DontTouch)
208  targetAnnotations.addDontTouch();
209  annoTarget.setAnnotations(targetAnnotations);
210 
211  // Create a PathOp using the id in the annotation we added to the target.
212  auto dictAttr = cast<DictionaryAttr>(annotation);
213  auto id = cast<DistinctAttr>(dictAttr.get("id"));
214  auto resolved = b.create<PathOp>(targetKindAttr, id);
215 
216  // Replace the unresolved path with the PathOp.
217  unresolved->replaceAllUsesWith(resolved);
218  unresolved.erase();
219 
220  return success();
221  }
222 
223  CircuitOp circuit;
224  SymbolTable symbolTable;
225  CircuitTargetCache targetCache;
226  InstanceGraph &instanceGraph;
227  InstancePathCache instancePathCache;
228  hw::InnerSymbolNamespaceCollection namespaces;
229  HierPathCache hierPathCache;
230  OpBuilder builder;
231 };
232 } // end anonymous namespace
233 
234 //===----------------------------------------------------------------------===//
235 // Pass Infrastructure
236 //===----------------------------------------------------------------------===//
237 
238 namespace {
239 struct ResolvePathsPass
240  : public circt::firrtl::impl::ResolvePathsBase<ResolvePathsPass> {
241  void runOnOperation() override;
242 };
243 } // end anonymous namespace
244 
245 void ResolvePathsPass::runOnOperation() {
246  auto circuit = getOperation();
247  auto &instanceGraph = getAnalysis<InstanceGraph>();
248  PathResolver resolver(circuit, instanceGraph);
249  OwningModuleCache cache(instanceGraph);
250  auto result = circuit.walk([&](UnresolvedPathOp unresolved) {
251  if (failed(resolver.resolve(cache, unresolved))) {
252  signalPassFailure();
253  return WalkResult::interrupt();
254  }
255  return WalkResult::advance();
256  });
257  if (result.wasInterrupted())
258  signalPassFailure();
259  markAnalysesPreserved<InstanceGraph>();
260 }
261 
262 std::unique_ptr<mlir::Pass> circt::firrtl::createResolvePathsPass() {
263  return std::make_unique<ResolvePathsPass>();
264 }
This graph tracks modules and where they are instantiated.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:55
std::unique_ptr< mlir::Pass > createResolvePathsPass()
std::optional< AnnoPathValue > resolveEntities(TokenAnnoTarget path, CircuitOp circuit, SymbolTable &symTbl, CircuitTargetCache &cache)
Convert a parsed target string to a resolved target structure.
std::optional< TokenAnnoTarget > tokenizePath(StringRef origTarget)
Parse a FIRRTL annotation path into its constituent parts.
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21
SmallVector< InstanceOp > instances
FModuleLike getModule() const
Get the parent module of the target.
Cache AnnoTargets for a circuit's modules, walked as needed.
A cache of existing HierPathOps, mostly used to facilitate HierPathOp reuse.
This implements an analysis to determine which module owns a given path operation.
FModuleOp lookup(ClassOp classOp)
Return this operation's owning module.
A data structure that caches and provides absolute paths to module instances in the IR.