14 #include "mlir/IR/BuiltinAttributeInterfaces.h"
15 #include "mlir/IR/Location.h"
16 #include "mlir/IR/SymbolTable.h"
17 #include "llvm/ADT/TypeSwitch.h"
18 #include "llvm/Support/Debug.h"
20 #define DEBUG_TYPE "om-evaluator"
30 return cast<ModuleOp>(symbolTable.getOp());
33 SmallVector<evaluator::EvaluatorValuePtr>
35 ArrayRef<Attribute> attributes) {
36 SmallVector<evaluator::EvaluatorValuePtr> values;
37 values.reserve(attributes.size());
38 for (
auto attr : attributes)
39 values.push_back(std::make_shared<evaluator::AttributeValue>(attr));
44 using namespace evaluator;
50 assert(isFullyEvaluated());
51 return llvm::TypeSwitch<EvaluatorValue *, LogicalResult>(
this)
54 [](
auto v) {
return v->finalizeImpl(); });
58 return llvm::TypeSwitch<const EvaluatorValue *, Type>(
this)
59 .Case<
AttributeValue>([](
auto *attr) -> Type {
return attr->getType(); })
60 .Case<ObjectValue>([](
auto *
object) {
return object->getObjectType(); })
61 .Case<ListValue>([](
auto *list) {
return list->getListType(); })
62 .Case<MapValue>([](
auto *map) {
return map->getMapType(); })
63 .Case<ReferenceValue>([](
auto *ref) {
return ref->getValueType(); })
64 .Case<TupleValue>([](
auto *tuple) {
return tuple->getTupleType(); })
75 return TypeSwitch<mlir::Type, FailureOr<evaluator::EvaluatorValuePtr>>(type)
76 .Case([&](circt::om::MapType type) {
78 std::make_shared<evaluator::MapValue>(type, loc);
79 return success(result);
81 .Case([&](circt::om::ListType type) {
83 std::make_shared<evaluator::ListValue>(type, loc);
84 return success(result);
86 .Case([&](mlir::TupleType type) {
88 std::make_shared<evaluator::TupleValue>(type, loc);
89 return success(result);
92 .Case([&](circt::om::ClassType type)
95 symbolTable.lookup<ClassOp>(type.getClassName().getValue());
97 return symbolTable.getOp()->emitError(
"unknown class name ")
98 << type.getClassName();
101 std::make_shared<evaluator::ObjectValue>(cls, loc);
103 return success(result);
105 .Default([&](
auto type) {
return failure(); });
110 auto it = objects.find({value, actualParams});
111 if (it != objects.end()) {
112 auto evalVal = it->second;
113 evalVal->setLocIfUnknown(loc);
118 TypeSwitch<Value, FailureOr<evaluator::EvaluatorValuePtr>>(value)
119 .Case([&](BlockArgument arg) {
120 auto val = (*actualParams)[arg.getArgNumber()];
124 .Case([&](OpResult result) {
125 return TypeSwitch<Operation *,
127 result.getDefiningOp())
128 .Case([&](ConstantOp op) {
129 return evaluateConstant(op, actualParams, loc);
131 .Case([&](IntegerBinaryArithmeticOp op) {
135 std::make_shared<evaluator::AttributeValue>(
136 op.getResult().getType(), loc);
137 return success(result);
139 .Case<ObjectFieldOp>([&](
auto op) {
143 std::make_shared<evaluator::ReferenceValue>(
144 value.getType(), loc);
145 return success(result);
147 .Case<AnyCastOp>([&](AnyCastOp op) {
148 return getOrCreateValue(op.getInput(), actualParams, loc);
150 .Case<FrozenBasePathCreateOp>([&](FrozenBasePathCreateOp op) {
152 std::make_shared<evaluator::BasePathValue>(
153 op.getPathAttr(), loc);
154 return success(result);
156 .Case<FrozenPathCreateOp>([&](FrozenPathCreateOp op) {
158 std::make_shared<evaluator::PathValue>(
159 op.getTargetKindAttr(), op.getPathAttr(),
160 op.getModuleAttr(), op.getRefAttr(),
161 op.getFieldAttr(), loc);
162 return success(result);
164 .Case<FrozenEmptyPathOp>([&](FrozenEmptyPathOp op) {
166 std::make_shared<evaluator::PathValue>(
168 return success(result);
170 .Case<ListCreateOp, TupleCreateOp, MapCreateOp, ObjectFieldOp,
171 ObjectOp>([&](
auto op) {
172 return getPartiallyEvaluatedValue(op.getType(), loc);
174 .Default([&](Operation *op) {
175 auto error = op->emitError(
"unable to evaluate value");
176 error.attachNote() <<
"value: " << value;
183 objects[{value, actualParams}] = result.value();
192 ClassOp cls = symbolTable.lookup<ClassOp>(className);
194 return symbolTable.getOp()->emitError(
"unknown class name ") << className;
196 auto formalParamNames = cls.getFormalParamNames().getAsRange<StringAttr>();
197 auto formalParamTypes = cls.getBodyBlock()->getArgumentTypes();
200 if (actualParams->size() != formalParamTypes.size()) {
201 auto error = cls.emitError(
"actual parameter list length (")
202 << actualParams->size() <<
") does not match formal "
203 <<
"parameter list length (" << formalParamTypes.size() <<
")";
204 auto &diag = error.attachNote() <<
"actual parameters: ";
207 for (
const auto ¶m : *actualParams) {
214 error.attachNote(cls.getLoc()) <<
"formal parameters: " << formalParamTypes;
219 for (
auto [actualParam, formalParamName, formalParamType] :
220 llvm::zip(*actualParams, formalParamNames, formalParamTypes)) {
221 if (!actualParam || !actualParam.get())
222 return cls.emitError(
"actual parameter for ")
223 << formalParamName <<
" is null";
226 if (isa<AnyType>(formalParamType))
229 Type actualParamType = actualParam->getType();
231 assert(actualParamType &&
"actualParamType must be non-null!");
233 if (actualParamType != formalParamType) {
234 auto error = cls.emitError(
"actual parameter for ")
235 << formalParamName <<
" has invalid type";
236 error.attachNote() <<
"actual parameter: " << *actualParam;
237 error.attachNote() <<
"format parameter type: " << formalParamType;
245 auto *context = cls.getContext();
246 for (
auto &op : cls.getOps())
247 for (
auto result : op.getResults()) {
254 worklist.push({result, actualParams});
257 for (
auto field : cls.getOps<ClassFieldOp>()) {
258 StringAttr name = field.getNameAttr();
259 Value value = field.getValue();
261 evaluateValue(value, actualParams, field.getLoc());
265 fields[name] = result.value();
269 if (instanceKey.first) {
271 getOrCreateValue(instanceKey.first, instanceKey.second, loc).value();
272 auto *
object = llvm::cast<evaluator::ObjectValue>(result.get());
273 object->setFields(std::move(fields));
279 std::make_shared<evaluator::ObjectValue>(cls, fields, loc);
286 StringAttr className, ArrayRef<evaluator::EvaluatorValuePtr> actualParams) {
287 ClassOp cls = symbolTable.lookup<ClassOp>(className);
289 return symbolTable.getOp()->emitError(
"unknown class name ") << className;
292 std::make_unique<SmallVector<std::shared_ptr<evaluator::EvaluatorValue>>>(
295 actualParametersBuffers.push_back(std::move(parameters));
297 auto loc = cls.getLoc();
298 auto result = evaluateObjectInstance(
299 className, actualParametersBuffers.back().get(), loc);
306 while (!worklist.empty()) {
307 auto [value, args] = worklist.front();
310 auto result = evaluateValue(value, args, loc);
316 if (!result.value()->isFullyEvaluated())
317 worklist.push({value, args});
320 auto &
object = result.value();
323 if (failed(object->finalize()))
324 return cls.emitError() <<
"failed to finalize evaluation. Probably the "
325 "class contains a dataflow cycle";
332 auto evaluatorValue = getOrCreateValue(value, actualParams, loc).value();
335 if (evaluatorValue->isFullyEvaluated())
336 return evaluatorValue;
338 return llvm::TypeSwitch<Value, FailureOr<evaluator::EvaluatorValuePtr>>(value)
339 .Case([&](BlockArgument arg) {
340 return evaluateParameter(arg, actualParams, loc);
342 .Case([&](OpResult result) {
343 return TypeSwitch<Operation *, FailureOr<evaluator::EvaluatorValuePtr>>(
344 result.getDefiningOp())
345 .Case([&](ConstantOp op) {
346 return evaluateConstant(op, actualParams, loc);
348 .Case([&](IntegerBinaryArithmeticOp op) {
349 return evaluateIntegerBinaryArithmetic(op, actualParams, loc);
351 .Case([&](ObjectOp op) {
352 return evaluateObjectInstance(op, actualParams);
354 .Case([&](ObjectFieldOp op) {
355 return evaluateObjectField(op, actualParams, loc);
357 .Case([&](ListCreateOp op) {
358 return evaluateListCreate(op, actualParams, loc);
360 .Case([&](TupleCreateOp op) {
361 return evaluateTupleCreate(op, actualParams, loc);
363 .Case([&](TupleGetOp op) {
364 return evaluateTupleGet(op, actualParams, loc);
366 .Case([&](AnyCastOp op) {
367 return evaluateValue(op.getInput(), actualParams, loc);
369 .Case([&](MapCreateOp op) {
370 return evaluateMapCreate(op, actualParams, loc);
372 .Case([&](FrozenBasePathCreateOp op) {
373 return evaluateBasePathCreate(op, actualParams, loc);
375 .Case([&](FrozenPathCreateOp op) {
376 return evaluatePathCreate(op, actualParams, loc);
378 .Case([&](FrozenEmptyPathOp op) {
379 return evaluateEmptyPath(op, actualParams, loc);
381 .Default([&](Operation *op) {
382 auto error = op->emitError(
"unable to evaluate value");
383 error.attachNote() <<
"value: " << value;
392 auto val = (*actualParams)[formalParam.getArgNumber()];
402 return success(std::make_shared<circt::om::evaluator::AttributeValue>(
403 op.getValue(), loc));
409 IntegerBinaryArithmeticOp op,
ActualParameters actualParams, Location loc) {
411 auto handle = getOrCreateValue(op.getResult(), actualParams, loc);
414 if (handle.value()->isFullyEvaluated())
419 auto lhsResult = evaluateValue(op.getLhs(), actualParams, loc);
420 if (failed(lhsResult))
422 if (!lhsResult.value()->isFullyEvaluated())
425 auto rhsResult = evaluateValue(op.getRhs(), actualParams, loc);
426 if (failed(rhsResult))
428 if (!rhsResult.value()->isFullyEvaluated())
434 llvm::TypeSwitch<evaluator::EvaluatorValue *, om::IntegerAttr>(value)
436 return val->
getAs<om::IntegerAttr>();
439 return cast<evaluator::AttributeValue>(
440 val->getStrippedValue()->get())
441 ->getAs<om::IntegerAttr>();
445 om::IntegerAttr lhs = extractAttr(lhsResult.value().get());
446 om::IntegerAttr rhs = extractAttr(rhsResult.value().get());
448 "expected om::IntegerAttr for IntegerBinaryArithmeticOp operands");
454 APSInt lhsVal = lhs.getValue().getAPSInt();
455 APSInt rhsVal = rhs.getValue().getAPSInt();
456 if (lhsVal.getBitWidth() > rhsVal.getBitWidth())
457 rhsVal = rhsVal.extend(lhsVal.getBitWidth());
458 else if (rhsVal.getBitWidth() > lhsVal.getBitWidth())
459 lhsVal = lhsVal.extend(rhsVal.getBitWidth());
465 return op->emitError(
"failed to evaluate integer operation");
468 MLIRContext *ctx = op->getContext();
473 auto *handleValue = cast<evaluator::AttributeValue>(handle.value().get());
474 auto resultStatus = handleValue->setAttr(resultAttr);
475 if (failed(resultStatus))
478 auto finalizeStatus = handleValue->finalize();
479 if (failed(finalizeStatus))
480 return finalizeStatus;
490 auto parameters = std::make_unique<
491 SmallVector<std::shared_ptr<evaluator::EvaluatorValue>>>();
494 for (
auto input : range) {
495 auto inputResult = getOrCreateValue(input, actualParams, loc);
496 if (failed(inputResult))
498 parameters->push_back(inputResult.value());
501 actualParametersBuffers.push_back(std::move(parameters));
502 return actualParametersBuffers.back().get();
509 auto loc = op.getLoc();
510 if (isFullyEvaluated({op, actualParams}))
511 return getOrCreateValue(op, actualParams, loc);
514 createParametersFromOperands(op.getOperands(), actualParams, loc);
517 return evaluateObjectInstance(op.getClassNameAttr(), params.value(), loc,
528 evaluateValue(op.getObject(), actualParams, loc);
529 if (failed(currentObjectResult))
530 return currentObjectResult;
532 auto *currentObject =
533 llvm::cast<evaluator::ObjectValue>(currentObjectResult.value().get());
535 auto objectFieldValue = getOrCreateValue(op, actualParams, loc).value();
540 for (
auto field : op.getFieldPath().getAsRange<FlatSymbolRefAttr>()) {
542 if (!currentObject->getFields().contains(field.getAttr()))
543 return objectFieldValue;
545 auto currentField = currentObject->getField(field.getAttr());
546 finalField = currentField.value();
547 if (
auto *nextObject =
548 llvm::dyn_cast<evaluator::ObjectValue>(finalField.get()))
549 currentObject = nextObject;
553 llvm::cast<evaluator::ReferenceValue>(objectFieldValue.get())
554 ->setValue(finalField);
557 return objectFieldValue;
566 SmallVector<evaluator::EvaluatorValuePtr> values;
567 auto list = getOrCreateValue(op, actualParams, loc);
568 for (
auto operand : op.getOperands()) {
569 auto result = evaluateValue(operand, actualParams, loc);
572 if (!result.value()->isFullyEvaluated())
574 values.push_back(result.value());
578 llvm::cast<evaluator::ListValue>(list.value().get())
579 ->setElements(std::move(values));
588 SmallVector<evaluator::EvaluatorValuePtr> values;
589 for (
auto operand : op.getOperands()) {
590 auto result = evaluateValue(operand, actualParams, loc);
593 values.push_back(result.value());
597 auto val = getOrCreateValue(op, actualParams, loc);
598 llvm::cast<evaluator::TupleValue>(val.value().get())
599 ->setElements(std::move(values));
606 auto tuple = evaluateValue(op.getInput(), actualParams, loc);
610 cast<evaluator::TupleValue>(tuple.value().get())
611 ->getElements()[op.getIndex()];
619 DenseMap<Attribute, evaluator::EvaluatorValuePtr> elements;
620 auto valueResult = getOrCreateValue(op, actualParams, loc).value();
621 for (
auto operand : op.getOperands()) {
622 auto result = evaluateValue(operand, actualParams, loc);
626 auto &value = result.value();
627 if (!value->isFullyEvaluated())
629 const auto &element =
630 llvm::cast<evaluator::TupleValue>(value.get())->getElements();
631 assert(element.size() == 2);
633 llvm::cast<evaluator::AttributeValue>(element[0].
get())->getAttr();
634 if (!elements.insert({attr, element[1]}).second)
635 return op.emitError() <<
"map contains duplicated keys";
639 llvm::cast<evaluator::MapValue>(valueResult.get())
640 ->setElements(std::move(elements));
649 auto valueResult = getOrCreateValue(op, actualParams, loc).value();
650 auto *path = llvm::cast<evaluator::BasePathValue>(valueResult.get());
651 auto result = evaluateValue(op.getBasePath(), actualParams, loc);
654 auto &value = result.value();
655 if (!value->isFullyEvaluated())
657 path->setBasepath(*llvm::cast<evaluator::BasePathValue>(value.get()));
666 auto valueResult = getOrCreateValue(op, actualParams, loc).value();
667 auto *path = llvm::cast<evaluator::PathValue>(valueResult.get());
668 auto result = evaluateValue(op.getBasePath(), actualParams, loc);
671 auto &value = result.value();
672 if (!value->isFullyEvaluated())
674 path->setBasepath(*llvm::cast<evaluator::BasePathValue>(value.get()));
680 auto valueResult = getOrCreateValue(op, actualParams, loc).value();
691 auto field = fields.find(name);
692 if (field == fields.end())
693 return cls.emitError(
"field ") << name <<
" does not exist";
694 return success(fields[name]);
700 SmallVector<Attribute> fieldNames;
701 for (
auto &f : fields)
702 fieldNames.push_back(f.first);
704 llvm::sort(fieldNames, [](Attribute a, Attribute b) {
705 return cast<StringAttr>(a).getValue() < cast<StringAttr>(b).getValue();
712 for (
auto &&[e, value] : fields)
725 SmallVector<Attribute> attrs;
726 for (
auto &[key, _] : elements)
727 attrs.push_back(key);
729 std::sort(attrs.begin(), attrs.end(), [](Attribute l, Attribute r) {
730 if (auto lInt = dyn_cast<mlir::IntegerAttr>(l))
731 if (auto rInt = dyn_cast<mlir::IntegerAttr>(r))
732 return lInt.getValue().ult(rInt.getValue());
734 assert(isa<StringAttr>(l) && isa<StringAttr>(r) &&
735 "key type should be integer or string");
736 return cast<StringAttr>(l).getValue() < cast<StringAttr>(r).getValue();
743 for (
auto &&[e, value] : elements)
754 auto result = getStrippedValue();
757 value = std::move(result.value());
766 for (
auto &value : elements) {
779 path(PathAttr::
get(context, {})) {
780 markFullyEvaluated();
784 :
EvaluatorValue(path.getContext(), Kind::BasePath, loc), path(path) {}
787 assert(isFullyEvaluated());
792 assert(!isFullyEvaluated());
793 auto newPath = llvm::to_vector(basepath.
path.getPath());
794 auto oldPath = path.getPath();
795 newPath.append(oldPath.begin(), oldPath.end());
797 markFullyEvaluated();
805 StringAttr module, StringAttr ref,
806 StringAttr field, Location loc)
808 path(path), module(module), ref(ref), field(field) {}
811 PathValue path(
nullptr,
nullptr,
nullptr,
nullptr,
nullptr, loc);
820 SmallString<64> result;
821 switch (targetKind.getValue()) {
822 case TargetKind::DontTouch:
823 result +=
"OMDontTouchedReferenceTarget";
825 case TargetKind::Instance:
826 result +=
"OMInstanceTarget";
828 case TargetKind::MemberInstance:
829 result +=
"OMMemberInstanceTarget";
831 case TargetKind::MemberReference:
832 result +=
"OMMemberReferenceTarget";
834 case TargetKind::Reference:
835 result +=
"OMReferenceTarget";
839 if (!path.getPath().empty())
840 result += path.getPath().front().module;
842 result += module.getValue();
844 for (
const auto &elt : path) {
845 result += elt.module.getValue();
847 result += elt.instance.getValue();
850 if (!module.getValue().empty())
851 result += module.getValue();
852 if (!ref.getValue().empty()) {
854 result += ref.getValue();
856 if (!field.getValue().empty())
857 result += field.getValue();
862 assert(!isFullyEvaluated());
863 auto newPath = llvm::to_vector(basepath.
getPath().getPath());
864 auto oldPath = path.getPath();
865 newPath.append(oldPath.begin(), oldPath.end());
867 markFullyEvaluated();
875 if (cast<TypedAttr>(attr).getType() != this->type)
876 return mlir::emitError(getLoc(),
"cannot set AttributeValue of type ")
877 << this->type <<
" to Attribute " << attr;
878 if (isFullyEvaluated())
879 return mlir::emitError(
881 "cannot set AttributeValue that has already been fully evaluated");
883 markFullyEvaluated();
888 if (!isFullyEvaluated())
889 return mlir::emitError(
890 getLoc(),
"cannot finalize AttributeValue that is not fully evaluated");
assert(baseType &&"element must be base type")
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
static LogicalResult finalizeEvaluatorValue(EvaluatorValuePtr &value)
std::shared_ptr< EvaluatorValue > EvaluatorValuePtr
A value of an object in memory.
SmallVector< EvaluatorValuePtr > getEvaluatorValuesFromAttributes(MLIRContext *context, ArrayRef< Attribute > attributes)
FailureOr< evaluator::EvaluatorValuePtr > evaluateBasePathCreate(FrozenBasePathCreateOp op, ActualParameters actualParams, Location loc)
FailureOr< evaluator::EvaluatorValuePtr > evaluateEmptyPath(FrozenEmptyPathOp op, ActualParameters actualParams, Location loc)
FailureOr< evaluator::EvaluatorValuePtr > getPartiallyEvaluatedValue(Type type, Location loc)
FailureOr< EvaluatorValuePtr > evaluateValue(Value value, ActualParameters actualParams, Location loc)
Evaluate a Value in a Class body according to the small expression grammar described in the rationale...
FailureOr< EvaluatorValuePtr > evaluateConstant(ConstantOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for constants.
FailureOr< EvaluatorValuePtr > evaluateIntegerBinaryArithmetic(IntegerBinaryArithmeticOp op, ActualParameters actualParams, Location loc)
mlir::ModuleOp getModule()
Get the Module this Evaluator is built from.
FailureOr< EvaluatorValuePtr > evaluateObjectField(ObjectFieldOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for Object fields.
Evaluator(ModuleOp mod)
Construct an Evaluator with an IR module.
FailureOr< evaluator::EvaluatorValuePtr > evaluateMapCreate(MapCreateOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for Map creation.
FailureOr< evaluator::EvaluatorValuePtr > instantiate(StringAttr className, ArrayRef< EvaluatorValuePtr > actualParams)
Instantiate an Object with its class name and actual parameters.
FailureOr< EvaluatorValuePtr > getOrCreateValue(Value value, ActualParameters actualParams, Location loc)
SmallVectorImpl< std::shared_ptr< evaluator::EvaluatorValue > > * ActualParameters
FailureOr< EvaluatorValuePtr > evaluateListCreate(ListCreateOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for List creation.
std::pair< Value, ActualParameters > ObjectKey
FailureOr< EvaluatorValuePtr > evaluateParameter(BlockArgument formalParam, ActualParameters actualParams, Location loc)
Evaluator dispatch functions for the small expression grammar.
FailureOr< EvaluatorValuePtr > evaluateObjectInstance(StringAttr className, ActualParameters actualParams, Location loc, ObjectKey instanceKey={})
Instantiate an Object with its class name and actual parameters.
FailureOr< EvaluatorValuePtr > evaluateTupleGet(TupleGetOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for List creation.
FailureOr< EvaluatorValuePtr > evaluateTupleCreate(TupleCreateOp op, ActualParameters actualParams, Location loc)
Evaluator dispatch function for Tuple creation.
FailureOr< evaluator::EvaluatorValuePtr > evaluatePathCreate(FrozenPathCreateOp op, ActualParameters actualParams, Location loc)
FailureOr< ActualParameters > createParametersFromOperands(ValueRange range, ActualParameters actualParams, Location loc)
Evaluator dispatch function for Object instances.
Values which can be directly representable by MLIR attributes.
LogicalResult setAttr(Attribute attr)
LogicalResult finalizeImpl()
BasePathValue(MLIRContext *context)
void setBasepath(const BasePathValue &basepath)
Set the basepath which this path is relative to.
om::PathAttr getPath() const
Base class for evaluator runtime values.
void markFullyEvaluated()
A List which contains variadic length of elements with the same type.
LogicalResult finalizeImpl()
ArrayAttr getKeys()
Return an array of keys in the ascending order.
LogicalResult finalizeImpl()
A composite Object, which has a type and fields.
LogicalResult finalizeImpl()
FailureOr< EvaluatorValuePtr > getField(StringAttr field)
Get a field of the Object by name.
ArrayAttr getFieldNames()
Get all the field names of the Object.
StringAttr getAsString() const
void setBasepath(const BasePathValue &basepath)
PathValue(om::TargetKindAttr targetKind, om::PathAttr path, StringAttr module, StringAttr ref, StringAttr field, Location loc)
Create a path value representing a regular path.
static PathValue getEmptyPath(Location loc)
Values which can be used as pointers to different values.
LogicalResult finalizeImpl()