CIRCT  19.0.0git
HWAttributes.cpp
Go to the documentation of this file.
1 //===- HWAttributes.cpp - Implement HW attributes -------------------------===//
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 
11 #include "circt/Dialect/HW/HWOps.h"
13 #include "circt/Support/LLVM.h"
14 #include "mlir/IR/Diagnostics.h"
15 #include "mlir/IR/DialectImplementation.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/TypeSwitch.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 
22 using namespace circt;
23 using namespace circt::hw;
24 using mlir::TypedAttr;
25 
26 // Internal method used for .mlir file parsing, defined below.
27 static Attribute parseParamExprWithOpcode(StringRef opcode, DialectAsmParser &p,
28  Type type);
29 
30 //===----------------------------------------------------------------------===//
31 // ODS Boilerplate
32 //===----------------------------------------------------------------------===//
33 
34 #define GET_ATTRDEF_CLASSES
35 #include "circt/Dialect/HW/HWAttributes.cpp.inc"
36 
37 void HWDialect::registerAttributes() {
38  addAttributes<
39 #define GET_ATTRDEF_LIST
40 #include "circt/Dialect/HW/HWAttributes.cpp.inc"
41  >();
42 }
43 
44 Attribute HWDialect::parseAttribute(DialectAsmParser &p, Type type) const {
45  StringRef attrName;
46  Attribute attr;
47  auto parseResult = generatedAttributeParser(p, &attrName, type, attr);
48  if (parseResult.has_value())
49  return attr;
50 
51  // Parse "#hw.param.expr.add" as ParamExprAttr.
52  if (attrName.starts_with(ParamExprAttr::getMnemonic())) {
53  auto string = attrName.drop_front(ParamExprAttr::getMnemonic().size());
54  if (string.front() == '.')
55  return parseParamExprWithOpcode(string.drop_front(), p, type);
56  }
57 
58  p.emitError(p.getNameLoc(), "Unexpected hw attribute '" + attrName + "'");
59  return {};
60 }
61 
62 void HWDialect::printAttribute(Attribute attr, DialectAsmPrinter &p) const {
63  if (succeeded(generatedAttributePrinter(attr, p)))
64  return;
65  llvm_unreachable("Unexpected attribute");
66 }
67 
68 //===----------------------------------------------------------------------===//
69 // OutputFileAttr
70 //===----------------------------------------------------------------------===//
71 
72 static std::string canonicalizeFilename(const Twine &directory,
73  const Twine &filename) {
74 
75  // Convert the filename to a native style path.
76  SmallString<128> nativeFilename;
77  llvm::sys::path::native(filename, nativeFilename);
78 
79  // If the filename is an absolute path, ignore the directory.
80  // e.g. `directory/` + `/etc/filename` -> `/etc/filename`.
81  if (llvm::sys::path::is_absolute(nativeFilename))
82  return std::string(nativeFilename);
83 
84  // Convert the directory to a native style path.
85  SmallString<128> nativeDirectory;
86  llvm::sys::path::native(directory, nativeDirectory);
87 
88  // If the filename component is empty, then ensure that the path ends in a
89  // separator and return it.
90  // e.g. `directory` + `` -> `directory/`.
91  auto separator = llvm::sys::path::get_separator();
92  if (nativeFilename.empty() && !nativeDirectory.ends_with(separator)) {
93  nativeDirectory += separator;
94  return std::string(nativeDirectory);
95  }
96 
97  // Append the directory and filename together.
98  // e.g. `/tmp/` + `out/filename` -> `/tmp/out/filename`.
99  SmallString<128> fullPath;
100  llvm::sys::path::append(fullPath, nativeDirectory, nativeFilename);
101  return std::string(fullPath);
102 }
103 
104 OutputFileAttr OutputFileAttr::getFromFilename(MLIRContext *context,
105  const Twine &filename,
106  bool excludeFromFileList,
107  bool includeReplicatedOps) {
108  return OutputFileAttr::getFromDirectoryAndFilename(
109  context, "", filename, excludeFromFileList, includeReplicatedOps);
110 }
111 
112 OutputFileAttr OutputFileAttr::getFromDirectoryAndFilename(
113  MLIRContext *context, const Twine &directory, const Twine &filename,
114  bool excludeFromFileList, bool includeReplicatedOps) {
115  auto canonicalized = canonicalizeFilename(directory, filename);
116  return OutputFileAttr::get(StringAttr::get(context, canonicalized),
117  BoolAttr::get(context, excludeFromFileList),
118  BoolAttr::get(context, includeReplicatedOps));
119 }
120 
121 OutputFileAttr OutputFileAttr::getAsDirectory(MLIRContext *context,
122  const Twine &directory,
123  bool excludeFromFileList,
124  bool includeReplicatedOps) {
125  return getFromDirectoryAndFilename(context, directory, "",
126  excludeFromFileList, includeReplicatedOps);
127 }
128 
129 bool OutputFileAttr::isDirectory() {
130  return getFilename().getValue().ends_with(llvm::sys::path::get_separator());
131 }
132 
133 /// Option ::= 'excludeFromFileList' | 'includeReplicatedOp'
134 /// OutputFileAttr ::= 'output_file<' directory ',' name (',' Option)* '>'
135 Attribute OutputFileAttr::parse(AsmParser &p, Type type) {
136  StringAttr filename;
137  if (p.parseLess() || p.parseAttribute<StringAttr>(filename))
138  return Attribute();
139 
140  // Parse the additional keyword attributes. Its easier to let people specify
141  // these more than once than to detect the problem and do something about it.
142  bool excludeFromFileList = false;
143  bool includeReplicatedOps = false;
144  while (true) {
145  if (p.parseOptionalComma())
146  break;
147  if (!p.parseOptionalKeyword("excludeFromFileList"))
148  excludeFromFileList = true;
149  else if (!p.parseKeyword("includeReplicatedOps",
150  "or 'excludeFromFileList'"))
151  includeReplicatedOps = true;
152  else
153  return Attribute();
154  }
155 
156  if (p.parseGreater())
157  return Attribute();
158 
159  return OutputFileAttr::getFromFilename(p.getContext(), filename.getValue(),
160  excludeFromFileList,
161  includeReplicatedOps);
162 }
163 
164 void OutputFileAttr::print(AsmPrinter &p) const {
165  p << "<" << getFilename();
166  if (getExcludeFromFilelist().getValue())
167  p << ", excludeFromFileList";
168  if (getIncludeReplicatedOps().getValue())
169  p << ", includeReplicatedOps";
170  p << ">";
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // EnumFieldAttr
175 //===----------------------------------------------------------------------===//
176 
177 Attribute EnumFieldAttr::parse(AsmParser &p, Type) {
178  StringRef field;
179  Type type;
180  if (p.parseLess() || p.parseKeyword(&field) || p.parseComma() ||
181  p.parseType(type) || p.parseGreater())
182  return Attribute();
183  return EnumFieldAttr::get(p.getEncodedSourceLoc(p.getCurrentLocation()),
184  StringAttr::get(p.getContext(), field), type);
185 }
186 
187 void EnumFieldAttr::print(AsmPrinter &p) const {
188  p << "<" << getField().getValue() << ", ";
189  p.printType(getType().getValue());
190  p << ">";
191 }
192 
193 EnumFieldAttr EnumFieldAttr::get(Location loc, StringAttr value,
194  mlir::Type type) {
195  if (!hw::isHWEnumType(type))
196  emitError(loc) << "expected enum type";
197 
198  // Check whether the provided value is a member of the enum type.
199  EnumType enumType = llvm::cast<EnumType>(getCanonicalType(type));
200  if (!enumType.contains(value.getValue())) {
201  emitError(loc) << "enum value '" << value.getValue()
202  << "' is not a member of enum type " << enumType;
203  return nullptr;
204  }
205 
206  return Base::get(value.getContext(), value, TypeAttr::get(type));
207 }
208 
209 //===----------------------------------------------------------------------===//
210 // InnerRefAttr
211 //===----------------------------------------------------------------------===//
212 
213 Attribute InnerRefAttr::parse(AsmParser &p, Type type) {
214  SymbolRefAttr attr;
215  if (p.parseLess() || p.parseAttribute<SymbolRefAttr>(attr) ||
216  p.parseGreater())
217  return Attribute();
218  if (attr.getNestedReferences().size() != 1)
219  return Attribute();
220  return InnerRefAttr::get(attr.getRootReference(), attr.getLeafReference());
221 }
222 
223 static void printSymbolName(AsmPrinter &p, StringAttr sym) {
224  if (sym)
225  p.printSymbolName(sym.getValue());
226  else
227  p.printSymbolName({});
228 }
229 
230 void InnerRefAttr::print(AsmPrinter &p) const {
231  p << "<";
232  printSymbolName(p, getModule());
233  p << "::";
234  printSymbolName(p, getName());
235  p << ">";
236 }
237 
238 //===----------------------------------------------------------------------===//
239 // InnerSymAttr and InnerSymPropertiesAttr
240 //===----------------------------------------------------------------------===//
241 
242 Attribute InnerSymPropertiesAttr::parse(AsmParser &parser, Type type) {
243  StringAttr name;
244  NamedAttrList dummyList;
245  int64_t fieldId = 0;
246  if (parser.parseLess() || parser.parseSymbolName(name, "name", dummyList) ||
247  parser.parseComma() || parser.parseInteger(fieldId) ||
248  parser.parseComma())
249  return Attribute();
250 
251  StringRef visibility;
252  auto loc = parser.getCurrentLocation();
253  if (parser.parseOptionalKeyword(&visibility,
254  {"public", "private", "nested"})) {
255  parser.emitError(loc, "expected 'public', 'private', or 'nested'");
256  return Attribute();
257  }
258  auto visibilityAttr = parser.getBuilder().getStringAttr(visibility);
259 
260  if (parser.parseGreater())
261  return Attribute();
262 
263  return parser.getChecked<InnerSymPropertiesAttr>(parser.getContext(), name,
264  fieldId, visibilityAttr);
265 }
266 
267 void InnerSymPropertiesAttr::print(AsmPrinter &odsPrinter) const {
268  odsPrinter << "<@" << getName().getValue() << "," << getFieldID() << ","
269  << getSymVisibility().getValue() << ">";
270 }
271 
272 LogicalResult InnerSymPropertiesAttr::verify(
273  ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
274  ::mlir::StringAttr name, uint64_t fieldID,
275  ::mlir::StringAttr symVisibility) {
276  if (!name || name.getValue().empty())
277  return emitError() << "inner symbol cannot have empty name";
278  return success();
279 }
280 
281 StringAttr InnerSymAttr::getSymIfExists(uint64_t fieldId) const {
282  const auto *it =
283  llvm::find_if(getImpl()->props, [&](const InnerSymPropertiesAttr &p) {
284  return p.getFieldID() == fieldId;
285  });
286  if (it != getProps().end())
287  return it->getName();
288  return {};
289 }
290 
291 InnerSymAttr InnerSymAttr::erase(uint64_t fieldID) const {
292  SmallVector<InnerSymPropertiesAttr> syms(getProps());
293  const auto *it = llvm::find_if(syms, [fieldID](InnerSymPropertiesAttr p) {
294  return p.getFieldID() == fieldID;
295  });
296  assert(it != syms.end());
297  syms.erase(it);
298  return InnerSymAttr::get(getContext(), syms);
299 }
300 
301 LogicalResult InnerSymAttr::walkSymbols(
302  llvm::function_ref<LogicalResult(StringAttr)> callback) const {
303  for (auto p : getImpl()->props)
304  if (callback(p.getName()).failed())
305  return failure();
306  return success();
307 }
308 
309 Attribute InnerSymAttr::parse(AsmParser &parser, Type type) {
310  StringAttr sym;
311  NamedAttrList dummyList;
312  SmallVector<InnerSymPropertiesAttr, 4> names;
313  if (!parser.parseOptionalSymbolName(sym, "dummy", dummyList)) {
314  auto prop = parser.getChecked<InnerSymPropertiesAttr>(
315  parser.getContext(), sym, 0,
316  StringAttr::get(parser.getContext(), "public"));
317  if (!prop)
318  return {};
319  names.push_back(prop);
320  } else if (parser.parseCommaSeparatedList(
321  OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
322  InnerSymPropertiesAttr prop;
323  if (parser.parseCustomAttributeWithFallback(
324  prop, mlir::Type{}, "dummy", dummyList))
325  return failure();
326 
327  names.push_back(prop);
328 
329  return success();
330  }))
331  return Attribute();
332 
333  std::sort(names.begin(), names.end(),
334  [&](InnerSymPropertiesAttr a, InnerSymPropertiesAttr b) {
335  return a.getFieldID() < b.getFieldID();
336  });
337 
338  return InnerSymAttr::get(parser.getContext(), names);
339 }
340 
341 void InnerSymAttr::print(AsmPrinter &odsPrinter) const {
342 
343  auto props = getProps();
344  if (props.size() == 1 &&
345  props[0].getSymVisibility().getValue().equals("public") &&
346  props[0].getFieldID() == 0) {
347  odsPrinter << "@" << props[0].getName().getValue();
348  return;
349  }
350  auto names = props.vec();
351 
352  std::sort(names.begin(), names.end(),
353  [&](InnerSymPropertiesAttr a, InnerSymPropertiesAttr b) {
354  return a.getFieldID() < b.getFieldID();
355  });
356  odsPrinter << "[";
357  llvm::interleaveComma(names, odsPrinter, [&](InnerSymPropertiesAttr attr) {
358  attr.print(odsPrinter);
359  });
360  odsPrinter << "]";
361 }
362 
363 //===----------------------------------------------------------------------===//
364 // ParamDeclAttr
365 //===----------------------------------------------------------------------===//
366 
367 Attribute ParamDeclAttr::parse(AsmParser &p, Type trailing) {
368  std::string name;
369  Type type;
370  Attribute value;
371  // < "FOO" : i32 > : i32
372  // < "FOO" : i32 = 0 > : i32
373  // < "FOO" : none >
374  if (p.parseLess() || p.parseString(&name) || p.parseColonType(type))
375  return Attribute();
376 
377  if (succeeded(p.parseOptionalEqual())) {
378  if (p.parseAttribute(value, type))
379  return Attribute();
380  }
381 
382  if (p.parseGreater())
383  return Attribute();
384 
385  if (value)
386  return ParamDeclAttr::get(p.getContext(),
387  p.getBuilder().getStringAttr(name), type, value);
388  return ParamDeclAttr::get(name, type);
389 }
390 
391 void ParamDeclAttr::print(AsmPrinter &p) const {
392  p << "<" << getName() << ": " << getType();
393  if (getValue()) {
394  p << " = ";
395  p.printAttributeWithoutType(getValue());
396  }
397  p << ">";
398 }
399 
400 //===----------------------------------------------------------------------===//
401 // ParamDeclRefAttr
402 //===----------------------------------------------------------------------===//
403 
404 Attribute ParamDeclRefAttr::parse(AsmParser &p, Type type) {
405  StringAttr name;
406  if (p.parseLess() || p.parseAttribute(name) || p.parseGreater() ||
407  (!type && (p.parseColon() || p.parseType(type))))
408  return Attribute();
409 
410  return ParamDeclRefAttr::get(name, type);
411 }
412 
413 void ParamDeclRefAttr::print(AsmPrinter &p) const {
414  p << "<" << getName() << ">";
415 }
416 
417 //===----------------------------------------------------------------------===//
418 // ParamVerbatimAttr
419 //===----------------------------------------------------------------------===//
420 
421 Attribute ParamVerbatimAttr::parse(AsmParser &p, Type type) {
422  StringAttr text;
423  if (p.parseLess() || p.parseAttribute(text) || p.parseGreater() ||
424  (!type && (p.parseColon() || p.parseType(type))))
425  return Attribute();
426 
427  return ParamVerbatimAttr::get(p.getContext(), text, type);
428 }
429 
430 void ParamVerbatimAttr::print(AsmPrinter &p) const {
431  p << "<" << getValue() << ">";
432 }
433 
434 //===----------------------------------------------------------------------===//
435 // ParamExprAttr
436 //===----------------------------------------------------------------------===//
437 
438 /// Given a binary function, if the two operands are known constant integers,
439 /// use the specified fold function to compute the result.
440 static TypedAttr foldBinaryOp(
441  ArrayRef<TypedAttr> operands,
442  llvm::function_ref<APInt(const APInt &, const APInt &)> calculate) {
443  assert(operands.size() == 2 && "binary operator always has two operands");
444  if (auto lhs = dyn_cast<IntegerAttr>(operands[0]))
445  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
446  return IntegerAttr::get(lhs.getType(),
447  calculate(lhs.getValue(), rhs.getValue()));
448  return {};
449 }
450 
451 /// Given a unary function, if the operand is a known constant integer,
452 /// use the specified fold function to compute the result.
453 static TypedAttr
454 foldUnaryOp(ArrayRef<TypedAttr> operands,
455  llvm::function_ref<APInt(const APInt &)> calculate) {
456  assert(operands.size() == 1 && "unary operator always has one operand");
457  if (auto intAttr = dyn_cast<IntegerAttr>(operands[0]))
458  return IntegerAttr::get(intAttr.getType(), calculate(intAttr.getValue()));
459  return {};
460 }
461 
462 /// If the specified attribute is a ParamExprAttr with the specified opcode,
463 /// return it. Otherwise return null.
464 static ParamExprAttr dyn_castPE(PEO opcode, Attribute value) {
465  if (auto expr = dyn_cast<ParamExprAttr>(value))
466  if (expr.getOpcode() == opcode)
467  return expr;
468  return {};
469 }
470 
471 /// This implements a < comparison for two operands to an associative operation
472 /// imposing an ordering upon them.
473 ///
474 /// The ordering provided puts more complex things to the start of the list,
475 /// from left to right:
476 /// expressions :: verbatims :: decl.refs :: constant
477 ///
478 static bool paramExprOperandSortPredicate(Attribute lhs, Attribute rhs) {
479  // Simplify the code below - we never have to care about exactly equal values.
480  if (lhs == rhs)
481  return false;
482 
483  // All expressions are "less than" a constant, since they appear on the right.
484  if (isa<IntegerAttr>(rhs)) {
485  // We don't bother to order constants w.r.t. each other since they will be
486  // folded - they can all compare equal.
487  return !isa<IntegerAttr>(lhs);
488  }
489  if (isa<IntegerAttr>(lhs))
490  return false;
491 
492  // Next up are named parameters.
493  if (auto rhsParam = dyn_cast<ParamDeclRefAttr>(rhs)) {
494  // Parameters are sorted lexically w.r.t. each other.
495  if (auto lhsParam = dyn_cast<ParamDeclRefAttr>(lhs))
496  return lhsParam.getName().getValue() < rhsParam.getName().getValue();
497  // They otherwise appear on the right of other things.
498  return true;
499  }
500  if (isa<ParamDeclRefAttr>(lhs))
501  return false;
502 
503  // Next up are verbatim parameters.
504  if (auto rhsParam = dyn_cast<ParamVerbatimAttr>(rhs)) {
505  // Verbatims are sorted lexically w.r.t. each other.
506  if (auto lhsParam = dyn_cast<ParamVerbatimAttr>(lhs))
507  return lhsParam.getValue().getValue() < rhsParam.getValue().getValue();
508  // They otherwise appear on the right of other things.
509  return true;
510  }
511  if (isa<ParamVerbatimAttr>(lhs))
512  return false;
513 
514  // The only thing left are nested expressions.
515  auto lhsExpr = cast<ParamExprAttr>(lhs), rhsExpr = cast<ParamExprAttr>(rhs);
516  // Sort by the string form of the opcode, e.g. add, .. mul,... then xor.
517  if (lhsExpr.getOpcode() != rhsExpr.getOpcode())
518  return stringifyPEO(lhsExpr.getOpcode()) <
519  stringifyPEO(rhsExpr.getOpcode());
520 
521  // If they are the same opcode, then sort by arity: more complex to the left.
522  ArrayRef<TypedAttr> lhsOperands = lhsExpr.getOperands(),
523  rhsOperands = rhsExpr.getOperands();
524  if (lhsOperands.size() != rhsOperands.size())
525  return lhsOperands.size() > rhsOperands.size();
526 
527  // We know the two subexpressions are different (they'd otherwise be pointer
528  // equivalent) so just go compare all of the elements.
529  for (size_t i = 0, e = lhsOperands.size(); i != e; ++i) {
530  if (paramExprOperandSortPredicate(lhsOperands[i], rhsOperands[i]))
531  return true;
532  if (paramExprOperandSortPredicate(rhsOperands[i], lhsOperands[i]))
533  return false;
534  }
535 
536  llvm_unreachable("expressions should never be equivalent");
537  return false;
538 }
539 
540 /// Given a fully associative variadic integer operation, constant fold any
541 /// constant operands and move them to the right. If the whole expression is
542 /// constant, then return that, otherwise update the operands list.
543 static TypedAttr simplifyAssocOp(
544  PEO opcode, SmallVector<TypedAttr, 4> &operands,
545  llvm::function_ref<APInt(const APInt &, const APInt &)> calculateFn,
546  llvm::function_ref<bool(const APInt &)> identityConstantFn,
547  llvm::function_ref<bool(const APInt &)> destructiveConstantFn = {}) {
548  auto type = operands[0].getType();
549  assert(isHWIntegerType(type));
550  if (operands.size() == 1)
551  return operands[0];
552 
553  // Flatten any of the same operation into the operand list:
554  // `(add x, (add y, z))` => `(add x, y, z)`.
555  for (size_t i = 0, e = operands.size(); i != e; ++i) {
556  if (auto subexpr = dyn_castPE(opcode, operands[i])) {
557  std::swap(operands[i], operands.back());
558  operands.pop_back();
559  --e;
560  --i;
561  operands.append(subexpr.getOperands().begin(),
562  subexpr.getOperands().end());
563  }
564  }
565 
566  // Impose an ordering on the operands, pushing subexpressions to the left and
567  // constants to the right, with verbatims and parameters in the middle - but
568  // predictably ordered w.r.t. each other.
569  llvm::stable_sort(operands, paramExprOperandSortPredicate);
570 
571  // Merge any constants, they will appear at the back of the operand list now.
572  if (isa<IntegerAttr>(operands.back())) {
573  while (operands.size() >= 2 &&
574  isa<IntegerAttr>(operands[operands.size() - 2])) {
575  APInt c1 = cast<IntegerAttr>(operands.pop_back_val()).getValue();
576  APInt c2 = cast<IntegerAttr>(operands.pop_back_val()).getValue();
577  auto resultConstant = IntegerAttr::get(type, calculateFn(c1, c2));
578  operands.push_back(resultConstant);
579  }
580 
581  auto resultCst = cast<IntegerAttr>(operands.back());
582 
583  // If the resulting constant is the destructive constant (e.g. `x*0`), then
584  // return it.
585  if (destructiveConstantFn && destructiveConstantFn(resultCst.getValue()))
586  return resultCst;
587 
588  // Remove the constant back to our operand list if it is the identity
589  // constant for this operator (e.g. `x*1`) and there are other operands.
590  if (identityConstantFn(resultCst.getValue()) && operands.size() != 1)
591  operands.pop_back();
592  }
593 
594  return operands.size() == 1 ? operands[0] : TypedAttr();
595 }
596 
597 /// Analyze an operand to an add. If it is a multiplication by a constant (e.g.
598 /// `(a*b*42)` then split it into the non-constant and the constant portions
599 /// (e.g. `a*b` and `42`). Otherwise return the operand as the first value and
600 /// null as the second (standin for "multiplication by 1").
601 static std::pair<TypedAttr, TypedAttr> decomposeAddend(TypedAttr operand) {
602  if (auto mul = dyn_castPE(PEO::Mul, operand))
603  if (auto cst = dyn_cast<IntegerAttr>(mul.getOperands().back())) {
604  auto nonCst = ParamExprAttr::get(PEO::Mul, mul.getOperands().drop_back());
605  return {nonCst, cst};
606  }
607  return {operand, TypedAttr()};
608 }
609 
610 static TypedAttr getOneOfType(Type type) {
611  return IntegerAttr::get(type, APInt(type.getIntOrFloatBitWidth(), 1));
612 }
613 
614 static TypedAttr simplifyAdd(SmallVector<TypedAttr, 4> &operands) {
615  if (auto result = simplifyAssocOp(
616  PEO::Add, operands, [](auto a, auto b) { return a + b; },
617  /*identityCst*/ [](auto cst) { return cst.isZero(); }))
618  return result;
619 
620  // Canonicalize the add by splitting all addends into their variable and
621  // constant factors.
622  SmallVector<std::pair<TypedAttr, TypedAttr>> decomposedOperands;
623  llvm::SmallDenseSet<TypedAttr> nonConstantParts;
624  for (auto &op : operands) {
625  decomposedOperands.push_back(decomposeAddend(op));
626 
627  // Keep track of non-constant parts we've already seen. If we see multiple
628  // uses of the same value, then we can fold them together with a multiply.
629  // This handles things like `(a+b+a)` => `(a*2 + b)` and `(a*2 + b + a)` =>
630  // `(a*3 + b)`.
631  if (!nonConstantParts.insert(decomposedOperands.back().first).second) {
632  // The thing we multiply will be the common expression.
633  TypedAttr mulOperand = decomposedOperands.back().first;
634 
635  // Find the index of the first occurrence.
636  size_t i = 0;
637  while (decomposedOperands[i].first != mulOperand)
638  ++i;
639  // Remove both occurrences from the operand list.
640  operands.erase(operands.begin() + (&op - &operands[0]));
641  operands.erase(operands.begin() + i);
642 
643  auto type = mulOperand.getType();
644  auto c1 = decomposedOperands[i].second,
645  c2 = decomposedOperands.back().second;
646  // Fill in missing constant multiplicands with 1.
647  if (!c1)
648  c1 = getOneOfType(type);
649  if (!c2)
650  c2 = getOneOfType(type);
651  // Re-add the "a"*(c1+c2) expression to the operand list and
652  // re-canonicalize.
653  auto constant = ParamExprAttr::get(PEO::Add, c1, c2);
654  auto mulCst = ParamExprAttr::get(PEO::Mul, mulOperand, constant);
655  operands.push_back(mulCst);
656  return ParamExprAttr::get(PEO::Add, operands);
657  }
658  }
659 
660  return {};
661 }
662 
663 static TypedAttr simplifyMul(SmallVector<TypedAttr, 4> &operands) {
664  if (auto result = simplifyAssocOp(
665  PEO::Mul, operands, [](auto a, auto b) { return a * b; },
666  /*identityCst*/ [](auto cst) { return cst.isOne(); },
667  /*destructiveCst*/ [](auto cst) { return cst.isZero(); }))
668  return result;
669 
670  // We always build a sum-of-products representation, so if we see an addition
671  // as a subexpr, we need to pull it out: (a+b)*c*d ==> (a*c*d + b*c*d).
672  for (size_t i = 0, e = operands.size(); i != e; ++i) {
673  if (auto subexpr = dyn_castPE(PEO::Add, operands[i])) {
674  // Pull the `c*d` operands out - it is whatever operands remain after
675  // removing the `(a+b)` term.
676  SmallVector<TypedAttr> mulOperands(operands.begin(), operands.end());
677  mulOperands.erase(mulOperands.begin() + i);
678 
679  // Build each add operand.
680  SmallVector<TypedAttr> addOperands;
681  for (auto addOperand : subexpr.getOperands()) {
682  mulOperands.push_back(addOperand);
683  addOperands.push_back(ParamExprAttr::get(PEO::Mul, mulOperands));
684  mulOperands.pop_back();
685  }
686  // Canonicalize and form the add expression.
687  return ParamExprAttr::get(PEO::Add, addOperands);
688  }
689  }
690 
691  return {};
692 }
693 static TypedAttr simplifyAnd(SmallVector<TypedAttr, 4> &operands) {
694  return simplifyAssocOp(
695  PEO::And, operands, [](auto a, auto b) { return a & b; },
696  /*identityCst*/ [](auto cst) { return cst.isAllOnes(); },
697  /*destructiveCst*/ [](auto cst) { return cst.isZero(); });
698 }
699 
700 static TypedAttr simplifyOr(SmallVector<TypedAttr, 4> &operands) {
701  return simplifyAssocOp(
702  PEO::Or, operands, [](auto a, auto b) { return a | b; },
703  /*identityCst*/ [](auto cst) { return cst.isZero(); },
704  /*destructiveCst*/ [](auto cst) { return cst.isAllOnes(); });
705 }
706 
707 static TypedAttr simplifyXor(SmallVector<TypedAttr, 4> &operands) {
708  return simplifyAssocOp(
709  PEO::Xor, operands, [](auto a, auto b) { return a ^ b; },
710  /*identityCst*/ [](auto cst) { return cst.isZero(); });
711 }
712 
713 static TypedAttr simplifyShl(SmallVector<TypedAttr, 4> &operands) {
714  assert(isHWIntegerType(operands[0].getType()));
715 
716  if (auto rhs = dyn_cast<IntegerAttr>(operands[1])) {
717  // Constant fold simple integers.
718  if (auto lhs = dyn_cast<IntegerAttr>(operands[0]))
719  return IntegerAttr::get(lhs.getType(),
720  lhs.getValue().shl(rhs.getValue()));
721 
722  // Canonicalize `x << cst` => `x * (1<<cst)` to compose correctly with
723  // add/mul canonicalization.
724  auto rhsCst = APInt::getOneBitSet(rhs.getValue().getBitWidth(),
725  rhs.getValue().getZExtValue());
726  return ParamExprAttr::get(PEO::Mul, operands[0],
727  IntegerAttr::get(rhs.getType(), rhsCst));
728  }
729  return {};
730 }
731 
732 static TypedAttr simplifyShrU(SmallVector<TypedAttr, 4> &operands) {
733  assert(isHWIntegerType(operands[0].getType()));
734  // Implement support for identities like `x >> 0`.
735  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
736  if (rhs.getValue().isZero())
737  return operands[0];
738 
739  return foldBinaryOp(operands, [](auto a, auto b) { return a.lshr(b); });
740 }
741 
742 static TypedAttr simplifyShrS(SmallVector<TypedAttr, 4> &operands) {
743  assert(isHWIntegerType(operands[0].getType()));
744  // Implement support for identities like `x >> 0`.
745  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
746  if (rhs.getValue().isZero())
747  return operands[0];
748 
749  return foldBinaryOp(operands, [](auto a, auto b) { return a.ashr(b); });
750 }
751 
752 static TypedAttr simplifyDivU(SmallVector<TypedAttr, 4> &operands) {
753  assert(isHWIntegerType(operands[0].getType()));
754  // Implement support for identities like `x/1`.
755  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
756  if (rhs.getValue().isOne())
757  return operands[0];
758 
759  return foldBinaryOp(operands, [](auto a, auto b) { return a.udiv(b); });
760 }
761 
762 static TypedAttr simplifyDivS(SmallVector<TypedAttr, 4> &operands) {
763  assert(isHWIntegerType(operands[0].getType()));
764  // Implement support for identities like `x/1`.
765  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
766  if (rhs.getValue().isOne())
767  return operands[0];
768 
769  return foldBinaryOp(operands, [](auto a, auto b) { return a.sdiv(b); });
770 }
771 
772 static TypedAttr simplifyModU(SmallVector<TypedAttr, 4> &operands) {
773  assert(isHWIntegerType(operands[0].getType()));
774  // Implement support for identities like `x%1`.
775  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
776  if (rhs.getValue().isOne())
777  return IntegerAttr::get(rhs.getType(), 0);
778 
779  return foldBinaryOp(operands, [](auto a, auto b) { return a.urem(b); });
780 }
781 
782 static TypedAttr simplifyModS(SmallVector<TypedAttr, 4> &operands) {
783  assert(isHWIntegerType(operands[0].getType()));
784  // Implement support for identities like `x%1`.
785  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
786  if (rhs.getValue().isOne())
787  return IntegerAttr::get(rhs.getType(), 0);
788 
789  return foldBinaryOp(operands, [](auto a, auto b) { return a.srem(b); });
790 }
791 
792 static TypedAttr simplifyCLog2(SmallVector<TypedAttr, 4> &operands) {
793  assert(isHWIntegerType(operands[0].getType()));
794  return foldUnaryOp(operands, [](auto a) {
795  // Following the Verilog spec, clog2(0) is 0
796  return APInt(a.getBitWidth(), a == 0 ? 0 : a.ceilLogBase2());
797  });
798 }
799 
800 static TypedAttr simplifyStrConcat(SmallVector<TypedAttr, 4> &operands) {
801  // Combine all adjacent strings.
802  SmallVector<TypedAttr> newOperands;
803  SmallVector<StringAttr> stringsToCombine;
804  auto combineAndPush = [&]() {
805  if (stringsToCombine.empty())
806  return;
807  // Concatenate buffered strings, push to ops.
808  SmallString<32> newString;
809  for (auto part : stringsToCombine)
810  newString.append(part.getValue());
811  newOperands.push_back(
812  StringAttr::get(stringsToCombine[0].getContext(), newString));
813  stringsToCombine.clear();
814  };
815 
816  for (TypedAttr op : operands) {
817  if (auto strOp = dyn_cast<StringAttr>(op)) {
818  // Queue up adjacent strings.
819  stringsToCombine.push_back(strOp);
820  } else {
821  combineAndPush();
822  newOperands.push_back(op);
823  }
824  }
825  combineAndPush();
826 
827  assert(!newOperands.empty());
828  if (newOperands.size() == 1)
829  return newOperands[0];
830  if (newOperands.size() < operands.size())
831  return ParamExprAttr::get(PEO::StrConcat, newOperands);
832  return {};
833 }
834 
835 /// Build a parameter expression. This automatically canonicalizes and
836 /// folds, so it may not necessarily return a ParamExprAttr.
837 TypedAttr ParamExprAttr::get(PEO opcode, ArrayRef<TypedAttr> operandsIn) {
838  assert(!operandsIn.empty() && "Cannot have expr with no operands");
839  // All operands must have the same type, which is the type of the result.
840  auto type = operandsIn.front().getType();
841  assert(llvm::all_of(operandsIn.drop_front(),
842  [&](auto op) { return op.getType() == type; }));
843 
844  SmallVector<TypedAttr, 4> operands(operandsIn.begin(), operandsIn.end());
845 
846  // Verify and canonicalize parameter expressions.
847  TypedAttr result;
848  switch (opcode) {
849  case PEO::Add:
850  result = simplifyAdd(operands);
851  break;
852  case PEO::Mul:
853  result = simplifyMul(operands);
854  break;
855  case PEO::And:
856  result = simplifyAnd(operands);
857  break;
858  case PEO::Or:
859  result = simplifyOr(operands);
860  break;
861  case PEO::Xor:
862  result = simplifyXor(operands);
863  break;
864  case PEO::Shl:
865  result = simplifyShl(operands);
866  break;
867  case PEO::ShrU:
868  result = simplifyShrU(operands);
869  break;
870  case PEO::ShrS:
871  result = simplifyShrS(operands);
872  break;
873  case PEO::DivU:
874  result = simplifyDivU(operands);
875  break;
876  case PEO::DivS:
877  result = simplifyDivS(operands);
878  break;
879  case PEO::ModU:
880  result = simplifyModU(operands);
881  break;
882  case PEO::ModS:
883  result = simplifyModS(operands);
884  break;
885  case PEO::CLog2:
886  result = simplifyCLog2(operands);
887  break;
888  case PEO::StrConcat:
889  result = simplifyStrConcat(operands);
890  break;
891  }
892 
893  // If we folded to an operand, return it.
894  if (result)
895  return result;
896 
897  return Base::get(operands[0].getContext(), opcode, operands, type);
898 }
899 
900 Attribute ParamExprAttr::parse(AsmParser &p, Type type) {
901  // We require an opcode suffix like `#hw.param.expr.add`, we don't allow
902  // parsing a plain `#hw.param.expr` on its own.
903  p.emitError(p.getNameLoc(), "#hw.param.expr should have opcode suffix");
904  return {};
905 }
906 
907 /// Internal method used for .mlir file parsing when parsing the
908 /// "#hw.param.expr.mul" form of the attribute.
909 static Attribute parseParamExprWithOpcode(StringRef opcodeStr,
910  DialectAsmParser &p, Type type) {
911  SmallVector<TypedAttr> operands;
912  if (p.parseCommaSeparatedList(
913  mlir::AsmParser::Delimiter::LessGreater, [&]() -> ParseResult {
914  operands.push_back({});
915  return p.parseAttribute(operands.back(), type);
916  }))
917  return {};
918 
919  std::optional<PEO> opcode = symbolizePEO(opcodeStr);
920  if (!opcode.has_value()) {
921  p.emitError(p.getNameLoc(), "unknown parameter expr operator name");
922  return {};
923  }
924 
925  return ParamExprAttr::get(*opcode, operands);
926 }
927 
928 void ParamExprAttr::print(AsmPrinter &p) const {
929  p << "." << stringifyPEO(getOpcode()) << '<';
930  llvm::interleaveComma(getOperands(), p.getStream(),
931  [&](Attribute op) { p.printAttributeWithoutType(op); });
932  p << '>';
933 }
934 
935 // Replaces any ParamDeclRefAttr within a parametric expression with its
936 // corresponding value from the map of provided parameters.
937 static FailureOr<Attribute>
938 replaceDeclRefInExpr(Location loc,
939  const std::map<std::string, Attribute> &parameters,
940  Attribute paramAttr, bool emitErrors) {
941  if (dyn_cast<IntegerAttr>(paramAttr)) {
942  // Nothing to do, constant value.
943  return paramAttr;
944  }
945  if (auto paramRefAttr = dyn_cast<hw::ParamDeclRefAttr>(paramAttr)) {
946  // Get the value from the provided parameters.
947  auto it = parameters.find(paramRefAttr.getName().str());
948  if (it == parameters.end()) {
949  if (emitErrors)
950  return emitError(loc)
951  << "Could not find parameter " << paramRefAttr.getName().str()
952  << " in the provided parameters for the expression!";
953  return failure();
954  }
955  return it->second;
956  }
957  if (auto paramExprAttr = dyn_cast<hw::ParamExprAttr>(paramAttr)) {
958  // Recurse into all operands of the expression.
959  llvm::SmallVector<TypedAttr, 4> replacedOperands;
960  for (auto operand : paramExprAttr.getOperands()) {
961  auto res = replaceDeclRefInExpr(loc, parameters, operand, emitErrors);
962  if (failed(res))
963  return {failure()};
964  replacedOperands.push_back(res->cast<TypedAttr>());
965  }
966  return {
967  hw::ParamExprAttr::get(paramExprAttr.getOpcode(), replacedOperands)};
968  }
969  llvm_unreachable("Unhandled parametric attribute");
970  return {};
971 }
972 
973 FailureOr<TypedAttr> hw::evaluateParametricAttr(Location loc,
974  ArrayAttr parameters,
975  Attribute paramAttr,
976  bool emitErrors) {
977  // Create a map of the provided parameters for faster lookup.
978  std::map<std::string, Attribute> parameterMap;
979  for (auto param : parameters) {
980  auto paramDecl = cast<ParamDeclAttr>(param);
981  parameterMap[paramDecl.getName().str()] = paramDecl.getValue();
982  }
983 
984  // First, replace any ParamDeclRefAttr in the expression with its
985  // corresponding value in 'parameters'.
986  auto paramAttrRes =
987  replaceDeclRefInExpr(loc, parameterMap, paramAttr, emitErrors);
988  if (failed(paramAttrRes))
989  return {failure()};
990  paramAttr = *paramAttrRes;
991 
992  // Then, evaluate the parametric attribute.
993  if (isa<IntegerAttr, hw::ParamDeclRefAttr>(paramAttr))
994  return cast<TypedAttr>(paramAttr);
995  if (auto paramExprAttr = dyn_cast<hw::ParamExprAttr>(paramAttr)) {
996  // Since any ParamDeclRefAttr was replaced within the expression,
997  // we re-evaluate the expression through the existing ParamExprAttr
998  // canonicalizer.
999  return ParamExprAttr::get(paramExprAttr.getOpcode(),
1000  paramExprAttr.getOperands());
1001  }
1002 
1003  llvm_unreachable("Unhandled parametric attribute");
1004  return TypedAttr();
1005 }
1006 
1007 template <typename TArray>
1008 FailureOr<Type> evaluateParametricArrayType(Location loc, ArrayAttr parameters,
1009  TArray arrayType, bool emitErrors) {
1010  auto size = evaluateParametricAttr(loc, parameters, arrayType.getSizeAttr(),
1011  emitErrors);
1012  if (failed(size))
1013  return failure();
1014  auto elementType = evaluateParametricType(
1015  loc, parameters, arrayType.getElementType(), emitErrors);
1016  if (failed(elementType))
1017  return failure();
1018 
1019  // If the size was evaluated to a constant, use a 64-bit integer
1020  // attribute version of it
1021  if (auto intAttr = dyn_cast<IntegerAttr>(*size))
1022  return TArray::get(
1023  arrayType.getContext(), *elementType,
1024  IntegerAttr::get(IntegerType::get(arrayType.getContext(), 64),
1025  intAttr.getValue().getSExtValue()));
1026 
1027  // Otherwise parameter references are still involved
1028  return TArray::get(arrayType.getContext(), *elementType, *size);
1029 }
1030 
1031 FailureOr<Type> hw::evaluateParametricType(Location loc, ArrayAttr parameters,
1032  Type type, bool emitErrors) {
1033  return llvm::TypeSwitch<Type, FailureOr<Type>>(type)
1034  .Case<hw::IntType>([&](hw::IntType t) -> FailureOr<Type> {
1035  auto evaluatedWidth =
1036  evaluateParametricAttr(loc, parameters, t.getWidth(), emitErrors);
1037  if (failed(evaluatedWidth))
1038  return {failure()};
1039 
1040  // If the width was evaluated to a constant, return an `IntegerType`
1041  if (auto intAttr = evaluatedWidth->dyn_cast<IntegerAttr>())
1042  return {IntegerType::get(type.getContext(),
1043  intAttr.getValue().getSExtValue())};
1044 
1045  // Otherwise parameter references are still involved
1046  return hw::IntType::get(evaluatedWidth->cast<TypedAttr>());
1047  })
1048  .Case<hw::ArrayType, hw::UnpackedArrayType>(
1049  [&](auto arrayType) -> FailureOr<Type> {
1050  return evaluateParametricArrayType(loc, parameters, arrayType,
1051  emitErrors);
1052  })
1053  .Default([&](auto) { return type; });
1054 }
1055 
1056 // Returns true if any part of this parametric attribute contains a reference
1057 // to a parameter declaration.
1058 static bool isParamAttrWithParamRef(Attribute expr) {
1059  return llvm::TypeSwitch<Attribute, bool>(expr)
1060  .Case([](ParamExprAttr attr) {
1061  return llvm::any_of(attr.getOperands(), isParamAttrWithParamRef);
1062  })
1063  .Case([](ParamDeclRefAttr) { return true; })
1064  .Default([](auto) { return false; });
1065 }
1066 
1067 bool hw::isParametricType(mlir::Type t) {
1068  return llvm::TypeSwitch<Type, bool>(t)
1069  .Case<hw::IntType>(
1070  [&](hw::IntType t) { return isParamAttrWithParamRef(t.getWidth()); })
1071  .Case<hw::ArrayType, hw::UnpackedArrayType>([&](auto arrayType) {
1072  return isParametricType(arrayType.getElementType()) ||
1073  isParamAttrWithParamRef(arrayType.getSizeAttr());
1074  })
1075  .Default([](auto) { return false; });
1076 }
assert(baseType &&"element must be base type")
static TypedAttr foldBinaryOp(ArrayRef< TypedAttr > operands, llvm::function_ref< APInt(const APInt &, const APInt &)> calculate)
Given a binary function, if the two operands are known constant integers, use the specified fold func...
static TypedAttr simplifyDivS(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyAssocOp(PEO opcode, SmallVector< TypedAttr, 4 > &operands, llvm::function_ref< APInt(const APInt &, const APInt &)> calculateFn, llvm::function_ref< bool(const APInt &)> identityConstantFn, llvm::function_ref< bool(const APInt &)> destructiveConstantFn={})
Given a fully associative variadic integer operation, constant fold any constant operands and move th...
static TypedAttr simplifyDivU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyCLog2(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyModU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyOr(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyShl(SmallVector< TypedAttr, 4 > &operands)
static void printSymbolName(AsmPrinter &p, StringAttr sym)
static TypedAttr simplifyShrS(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr foldUnaryOp(ArrayRef< TypedAttr > operands, llvm::function_ref< APInt(const APInt &)> calculate)
Given a unary function, if the operand is a known constant integer, use the specified fold function t...
static TypedAttr simplifyMul(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr getOneOfType(Type type)
static TypedAttr simplifyAnd(SmallVector< TypedAttr, 4 > &operands)
static std::pair< TypedAttr, TypedAttr > decomposeAddend(TypedAttr operand)
Analyze an operand to an add.
static TypedAttr simplifyModS(SmallVector< TypedAttr, 4 > &operands)
static Attribute parseParamExprWithOpcode(StringRef opcode, DialectAsmParser &p, Type type)
Internal method used for .mlir file parsing when parsing the "#hw.param.expr.mul" form of the attribu...
static bool paramExprOperandSortPredicate(Attribute lhs, Attribute rhs)
This implements a < comparison for two operands to an associative operation imposing an ordering upon...
static std::string canonicalizeFilename(const Twine &directory, const Twine &filename)
static TypedAttr simplifyShrU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyAdd(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyStrConcat(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyXor(SmallVector< TypedAttr, 4 > &operands)
static ParamExprAttr dyn_castPE(PEO opcode, Attribute value)
If the specified attribute is a ParamExprAttr with the specified opcode, return it.
static StringAttr append(StringAttr base, const Twine &suffix)
Return a attribute with the specified suffix appended.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:54
uint64_t getFieldID(Type type, uint64_t index)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
bool isHWIntegerType(mlir::Type type)
Return true if the specified type is a value HW Integer type.
Definition: HWTypes.cpp:52
bool isHWEnumType(mlir::Type type)
Return true if the specified type is a HW Enum type.
Definition: HWTypes.cpp:65
mlir::Type getCanonicalType(mlir::Type type)
Definition: HWTypes.cpp:41
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21