46#include <mlir/IR/BuiltinOps.h>
47#include <mlir/IR/PatternMatch.h>
49#include <llvm/ADT/DenseMap.h>
50#include <llvm/ADT/DenseSet.h>
51#include <llvm/ADT/SmallVector.h>
52#include <llvm/ADT/StringMap.h>
53#include <llvm/Support/raw_ostream.h>
60#define GEN_PASS_DEF_TYPEVARINFERENCEPASS
66#define DEBUG_TYPE "llzk-infer-tvar"
97using SpecializedCallableCloneCache = DenseMap<Operation *, llvm::StringMap<SymbolRefAttr>>;
98using SpecializedTemplateCloneCache = DenseMap<Operation *, llvm::StringMap<StringAttr>>;
105static SmallVector<StringAttr> getStringPieces(SymbolRefAttr ref) {
106 return llvm::to_vector(llvm::map_range(
getPieces(ref), [](FlatSymbolRefAttr piece) {
107 return piece.getAttr();
112static StringAttr getFlatSymbolName(Attribute attr) {
113 auto symRef = llvm::dyn_cast_if_present<SymbolRefAttr>(attr);
114 if (!symRef || !symRef.getNestedReferences().empty()) {
117 return symRef.getRootReference();
128 std::optional<Type> declaredTy = op.
getTypeOpt();
132 auto tvarTy = llvm::dyn_cast<TypeVarType>(*declaredTy);
133 return tvarTy && tvarTy.getRefName() == op.getName();
142static bool isCurrentTemplateTypeVarParamSymbol(StringAttr symbolName, Operation *op) {
148 return paramOp && isTypeVarParam(paramOp);
152template <
typename ConverterT>
154convertTypeRange(TypeRange oldTypes, SmallVectorImpl<Type> &newTypes, ConverterT &converter) {
155 bool changed =
false;
156 newTypes.reserve(oldTypes.size());
157 for (Type oldTy : oldTypes) {
158 Type newTy = converter.convertType(oldTy);
159 newTypes.push_back(newTy);
160 changed |= newTy != oldTy;
166template <
typename ConverterT>
167static Type convertPodType(
PodType podTy, MLIRContext *ctx, ConverterT &converter) {
168 SmallVector<RecordAttr> newRecords;
169 bool changed =
false;
170 for (RecordAttr record : podTy.
getRecords()) {
171 Type newRecordTy = converter.convertType(record.getType());
172 newRecords.push_back(RecordAttr::get(ctx, record.getName(), newRecordTy));
173 changed |= newRecordTy != record.getType();
179template <
typename ConvertElementFn>
180static Type convertArrayElementType(
ArrayType arrTy, ConvertElementFn convertElement) {
189template <
typename ConverterT>
190static Type convertFunctionType(FunctionType funcTy, ConverterT &converter) {
191 SmallVector<Type> newInputs;
192 SmallVector<Type> newResults;
193 bool changed = convertTypeRange(funcTy.getInputs(), newInputs, converter);
194 changed |= convertTypeRange(funcTy.getResults(), newResults, converter);
195 return changed ? FunctionType::get(funcTy.getContext(), newInputs, newResults) : funcTy;
199template <
typename ConvertTypeFn,
typename ConvertNestedAttrFn>
200static Attribute convertTypeOrArrayAttr(
201 Attribute attr, MLIRContext *ctx, ConvertTypeFn convertType,
202 ConvertNestedAttrFn convertNestedAttr
207 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
208 Type newTy = convertType(tyAttr.getValue());
209 return newTy == tyAttr.getValue() ? attr : TypeAttr::get(newTy);
211 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
212 SmallVector<Attribute> newAttrs;
213 bool changed =
false;
214 for (Attribute nested : arrAttr.getValue()) {
215 Attribute newNested = convertNestedAttr(nested);
216 newAttrs.push_back(newNested);
217 changed |= newNested != nested;
219 return changed ? ArrayAttr::get(ctx, newAttrs) : attr;
226static bool templateArgUnifiesWithType(Attribute attr, Type expectedTy) {
227 Attribute expectedAttr = TypeAttr::get(expectedTy);
228 return typeParamsUnify(ArrayRef<Attribute> {attr}, ArrayRef<Attribute> {expectedAttr});
238class TypeVarReplacementConverter {
242 SmallVector<StringAttr> templatePath_;
244 SmallVector<StringAttr> oldParamOrder_;
246 DenseSet<StringAttr> removedParams_;
248 DenseMap<StringAttr, Type> replacements_;
250 bool trimResolvedParams_;
258 TypeVarReplacementConverter(
259 MLIRContext *c, ArrayRef<StringAttr> templatePath, ArrayRef<StringAttr> oldParamOrder,
260 const DenseMap<StringAttr, Type> &replacements,
bool trimResolvedParams =
true
262 : ctx_(c), templatePath_(templatePath), oldParamOrder_(oldParamOrder),
263 replacements_(replacements), trimResolvedParams_(trimResolvedParams) {
264 for (
const auto &entry : replacements_) {
265 removedParams_.insert(entry.first);
273 Type convertType(Type ty)
const {
274 DenseSet<StringAttr> resolvingParams;
275 return convertType(ty, resolvingParams);
280 Type convertType(Type ty, DenseSet<StringAttr> &resolvingParams)
const {
284 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
285 StringAttr paramName = tvarTy.getNameRef().getAttr();
286 auto it = replacements_.find(paramName);
287 if (it == replacements_.end()) {
290 if (!resolvingParams.insert(paramName).second) {
293 Type replacement = convertType(it->second, resolvingParams);
294 resolvingParams.erase(paramName);
297 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
298 return convertArrayElementType(arrTy, [
this, &resolvingParams](Type elemTy) {
299 return convertType(elemTy, resolvingParams);
302 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
303 return convertStructType(structTy, resolvingParams);
305 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
306 return convertPodType(podTy, ctx_, *
this);
308 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
309 return convertFunctionType(funcTy, *
this);
320 Attribute convertAttr(Attribute attr)
const {
321 DenseSet<StringAttr> resolvingParams;
322 return convertAttr(attr, resolvingParams);
327 LogicalResult validateOperation(Operation *op)
const {
328 if (
auto createOp = llvm::dyn_cast<CreateArrayOp>(op)) {
329 if (failed(validateCreateArrayOp(createOp))) {
333 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
334 if (failed(validateType(func.getFunctionType(), op))) {
338 for (Region ®ion : op->getRegions()) {
339 for (Block &block : region.getBlocks()) {
340 for (Type argTy : block.getArgumentTypes()) {
341 if (failed(validateType(argTy, op))) {
347 for (Type resultTy : op->getResultTypes()) {
348 if (failed(validateType(resultTy, op))) {
352 for (NamedAttribute attr : op->getAttrs()) {
353 if (failed(validateAttr(attr.getValue(), op))) {
369 LogicalResult validateCreateArrayOp(
CreateArrayOp createOp)
const {
374 ArrayType oldResultTy = createOp.getType();
375 auto newResultTy = llvm::dyn_cast<ArrayType>(convertType(oldResultTy));
376 auto newElemTy = llvm::dyn_cast<ArrayType>(convertType(oldResultTy.
getElementType()));
377 if (!newResultTy || !newElemTy || newResultTy == oldResultTy || oldResultTy.hasStaticShape()) {
381 return createOp.emitError()
382 <<
"cannot rewrite initialized array.new with non-static initializer shape "
387 LogicalResult validateType(Type ty, Operation *diagnosticOp)
const {
391 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
394 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
395 return validateStructType(structTy, diagnosticOp);
397 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
398 for (RecordAttr record : podTy.
getRecords()) {
399 if (failed(validateType(record.getType(), diagnosticOp))) {
405 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
406 for (Type inputTy : funcTy.getInputs()) {
407 if (failed(validateType(inputTy, diagnosticOp))) {
411 for (Type resultTy : funcTy.getResults()) {
412 if (failed(validateType(resultTy, diagnosticOp))) {
421 LogicalResult validateAttr(Attribute attr, Operation *diagnosticOp)
const {
425 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
426 return validateType(tyAttr.getValue(), diagnosticOp);
428 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
429 for (Attribute nested : arrAttr.getValue()) {
430 if (failed(validateAttr(nested, diagnosticOp))) {
439 Attribute convertAttr(Attribute attr, DenseSet<StringAttr> &resolvingParams)
const {
440 return convertTypeOrArrayAttr(attr, ctx_, [
this, &resolvingParams](Type ty) {
441 return convertType(ty, resolvingParams);
442 }, [
this, &resolvingParams](Attribute nested) {
443 return convertTemplateArgAttr(nested, resolvingParams);
455 FailureOr<ArrayAttr> convertTemplateParams(
456 ArrayAttr params, Operation *diagnosticOp,
bool resolveTemplateSymbolArgs =
true,
457 bool allowCurrentTemplateTypeVarSymbols =
false
462 if (params.size() != oldParamOrder_.size()) {
465 SmallVector<Attribute> kept;
466 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder_, params.getValue())) {
467 if (removedParams_.contains(paramName)) {
468 if (failed(checkRemovedTemplateParam(
469 paramName, attr, diagnosticOp, resolveTemplateSymbolArgs,
470 allowCurrentTemplateTypeVarSymbols
476 kept.push_back(resolveTemplateSymbolArgs ? convertTemplateArgAttr(attr) : attr);
478 return kept.empty() ? ArrayAttr() : ArrayAttr::get(ctx_, kept);
483 bool hasWildcardForRemovedParam(ArrayAttr params)
const {
484 if (!params || params.size() != oldParamOrder_.size()) {
487 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder_, params.getValue())) {
488 if (!removedParams_.contains(paramName)) {
491 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr); intAttr &&
isDynamic(intAttr)) {
500 Attribute convertTemplateArgAttr(Attribute attr)
const {
501 DenseSet<StringAttr> resolvingParams;
502 return convertTemplateArgAttr(attr, resolvingParams);
511 Attribute convertTemplateArgAttr(Attribute attr, DenseSet<StringAttr> &resolvingParams)
const {
512 if (StringAttr symbolName = getFlatSymbolName(attr)) {
513 auto it = replacements_.find(symbolName);
514 if (it != replacements_.end()) {
515 if (!resolvingParams.insert(symbolName).second) {
518 Type replacement = convertType(it->second, resolvingParams);
519 resolvingParams.erase(symbolName);
520 return TypeAttr::get(replacement);
523 return convertAttr(attr, resolvingParams);
527 LogicalResult checkRemovedTemplateParam(
528 StringAttr paramName, Attribute attr, Operation *diagnosticOp,
bool resolveTemplateSymbolArgs,
529 bool allowCurrentTemplateTypeVarSymbols =
false
531 auto replacementIt = replacements_.find(paramName);
532 assert(replacementIt != replacements_.end() &&
"removed parameter must have a replacement");
533 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr); intAttr &&
isDynamic(intAttr)) {
536 Attribute convertedAttr = resolveTemplateSymbolArgs ? convertTemplateArgAttr(attr) : attr;
537 if (StringAttr symbolName = getFlatSymbolName(convertedAttr)) {
538 if (allowCurrentTemplateTypeVarSymbols &&
539 isCurrentTemplateTypeVarParamSymbol(symbolName, diagnosticOp)) {
542 return emitRemovedTemplateParamMismatch(paramName, attr, replacementIt->second, diagnosticOp);
544 if (templateArgUnifiesWithType(convertedAttr, convertType(replacementIt->second))) {
548 return emitRemovedTemplateParamMismatch(paramName, attr, replacementIt->second, diagnosticOp);
552 LogicalResult emitRemovedTemplateParamMismatch(
553 StringAttr paramName, Attribute attr, Type replacementTy, Operation *diagnosticOp
555 InFlightDiagnostic diag = diagnosticOp->emitError()
556 <<
"explicit template argument for inferred parameter @"
557 << paramName.getValue() <<
" must match inferred type "
558 << replacementTy <<
", but found ";
559 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
560 diag << typeAttr.getValue();
573 bool isOwnedStructType(StructType structTy)
const {
574 SmallVector<StringAttr> structPath = getStringPieces(structTy.
getNameRef());
575 return structPath.size() > templatePath_.size() &&
576 std::equal(templatePath_.begin(), templatePath_.end(), structPath.begin());
584 StructType convertStructType(StructType structTy, DenseSet<StringAttr> &resolvingParams)
const {
590 SmallVector<Attribute> newParams;
591 bool changed =
false;
592 bool removeOwnedParams = isOwnedStructType(structTy) && params.size() == oldParamOrder_.size();
593 for (
auto [index, attr] : llvm::enumerate(params.getValue())) {
594 if (trimResolvedParams_ && removeOwnedParams &&
595 removedParams_.contains(oldParamOrder_[index])) {
599 Attribute newAttr = convertTemplateArgAttr(attr, resolvingParams);
600 newParams.push_back(newAttr);
601 changed |= newAttr != attr;
607 LogicalResult validateStructType(StructType structTy, Operation *diagnosticOp)
const {
612 bool removeOwnedParams = isOwnedStructType(structTy) && params.size() == oldParamOrder_.size();
613 for (
auto indexedAttr : llvm::enumerate(params.getValue())) {
614 unsigned index = indexedAttr.index();
615 Attribute attr = indexedAttr.value();
616 if (trimResolvedParams_ && removeOwnedParams &&
617 removedParams_.contains(oldParamOrder_[index])) {
618 if (failed(checkRemovedTemplateParam(
619 oldParamOrder_[index], attr, diagnosticOp,
true,
626 if (failed(validateAttr(attr, diagnosticOp))) {
635template <
typename ConverterT,
typename SetSignatureFn>
636static void updateCallableSignature(
637 FunctionType oldFuncTy, Region &body, ConverterT &converter, SetSignatureFn setSignature
639 Type converted = converter.convertType(oldFuncTy);
640 auto newFuncTy = llvm::cast<FunctionType>(converted);
641 if (oldFuncTy == newFuncTy) {
645 setSignature(newFuncTy);
650 Block &entryBlock = body.front();
651 assert(entryBlock.getNumArguments() == newFuncTy.getNumInputs());
652 for (
auto [arg, newTy] : llvm::zip_equal(entryBlock.getArguments(), newFuncTy.getInputs())) {
662template <
typename ConverterT>
663static void updateFuncSignature(
FuncDefOp func, ConverterT &converter) {
664 updateCallableSignature(
666 [func](FunctionType newFuncTy)
mutable { func.setType(newFuncTy); }
671template <
typename ConverterT>
672static void updateContractSignature(
verif::ContractOp contract, ConverterT &converter) {
673 updateCallableSignature(
675 [contract](FunctionType newFuncTy)
mutable { contract.setFunctionType(newFuncTy); }
681template <
typename ConverterT>
static bool convertCallCallee(
CallOp callOp, ConverterT &converter) {
682 if constexpr (
requires { converter.convertCallCallee(callOp); }) {
684 SymbolRefAttr newCallee = converter.convertCallCallee(callOp);
685 if (newCallee != oldCallee) {
695template <
typename ConverterT>
696static bool convertContractTarget(
verif::ContractOp contract, ConverterT &converter) {
697 if constexpr (
requires { converter.convertContractTarget(contract); }) {
699 SymbolRefAttr newTarget = converter.convertContractTarget(contract);
700 if (newTarget != oldTarget) {
709template <
typename ConverterT>
static bool converterFailed(ConverterT &converter) {
710 if constexpr (
requires { converter.hadFailure(); }) {
711 return converter.hadFailure();
717template <
typename ConverterT>
718static void startConverterOperation(ConverterT &converter, Operation *op) {
719 if constexpr (
requires { converter.startOperation(op); }) {
720 converter.startOperation(op);
729template <
typename ConverterT>
730static FailureOr<bool> convertOperationTypes(Operation *op, ConverterT &converter) {
731 if (
auto createOp = llvm::dyn_cast<CreateArrayOp>(op)) {
732 ArrayType oldResultTy = createOp.getType();
733 auto newResultTy = llvm::dyn_cast<ArrayType>(converter.convertType(oldResultTy));
734 auto newElemTy = llvm::dyn_cast<ArrayType>(converter.convertType(oldResultTy.
getElementType()));
735 if (converterFailed(converter)) {
738 if (newResultTy && newElemTy && newResultTy != oldResultTy && !createOp.
getElements().empty() &&
739 oldResultTy.hasStaticShape()) {
742 SmallVector<Type> newElementValueTypes;
743 newElementValueTypes.reserve(createOp.
getElements().size());
744 for (
auto [index, element] : llvm::enumerate(createOp.
getElements())) {
745 Type newElementValueTy = converter.convertType(element.getType());
746 if (converterFailed(converter)) {
749 if (newElementValueTy != newElemTy) {
750 return createOp.emitError()
751 <<
"cannot rewrite initialized array.new: initializer " << index <<
" converts to "
752 << newElementValueTy <<
", but expected " << newElemTy;
754 newElementValueTypes.push_back(newElementValueTy);
757 OpBuilder builder(createOp);
758 Location loc = createOp.getLoc();
761 for (
auto [index, element] : llvm::enumerate(createOp.
getElements())) {
762 Type newElementValueTy = newElementValueTypes[index];
763 if (element.getType() != newElementValueTy) {
764 element.setType(newElementValueTy);
766 std::optional<SmallVector<Value>> indices =
768 assert(indices &&
"static array initializer index should delinearize");
777 if (
auto readOp = llvm::dyn_cast<ReadArrayOp>(op)) {
778 Type newResultTy = converter.convertType(readOp.getResult().getType());
779 if (converterFailed(converter)) {
782 if (
auto newArrayTy = llvm::dyn_cast<ArrayType>(newResultTy)) {
783 OpBuilder builder(readOp);
785 builder, readOp.getLoc(), newArrayTy, readOp.getArrRef(), readOp.getIndices()
787 readOp.getResult().replaceAllUsesWith(extractOp.getResult());
793 if (
auto writeOp = llvm::dyn_cast<WriteArrayOp>(op)) {
794 Type newRvalueTy = converter.convertType(writeOp.getRvalue().getType());
795 if (converterFailed(converter)) {
798 if (llvm::isa<ArrayType>(newRvalueTy)) {
799 OpBuilder builder(writeOp);
801 builder, writeOp.getLoc(), writeOp.getArrRef(), writeOp.getIndices(), writeOp.getRvalue()
808 bool changed =
false;
810 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
811 FunctionType oldFuncTy = func.getFunctionType();
812 updateFuncSignature(func, converter);
813 if (converterFailed(converter)) {
816 changed |= oldFuncTy != func.getFunctionType();
818 if (
auto contract = llvm::dyn_cast<verif::ContractOp>(op)) {
820 updateContractSignature(contract, converter);
821 if (converterFailed(converter)) {
825 changed |= convertContractTarget(contract, converter);
826 if (converterFailed(converter)) {
831 for (Region ®ion : op->getRegions()) {
832 for (Block &block : region.getBlocks()) {
833 for (BlockArgument arg : block.getArguments()) {
834 Type newTy = converter.convertType(arg.getType());
835 if (converterFailed(converter)) {
838 if (newTy != arg.getType()) {
846 for (Value result : op->getResults()) {
847 Type newTy = converter.convertType(result.getType());
848 if (converterFailed(converter)) {
851 if (newTy != result.getType()) {
852 result.setType(newTy);
857 if (
auto callOp = llvm::dyn_cast<CallOp>(op)) {
858 changed |= convertCallCallee(callOp, converter);
859 if (converterFailed(converter)) {
864 SmallVector<NamedAttribute> newAttrs;
865 bool attrsChanged =
false;
866 newAttrs.reserve(op->getAttrs().size());
867 for (NamedAttribute attr : op->getAttrs()) {
868 Attribute newAttr = converter.convertAttr(attr.getValue());
869 if (converterFailed(converter)) {
872 newAttrs.emplace_back(attr.getName(), newAttr);
873 attrsChanged |= newAttr != attr.getValue();
876 op->setAttrs(DictionaryAttr::get(op->getContext(), newAttrs));
884template <
typename ConverterT>
885static FailureOr<bool> convertOperationTypesInAndTrack(Operation *root, ConverterT &converter) {
886 bool changed =
false;
887 WalkResult res = root->walk([&converter, &changed](Operation *op) {
888 startConverterOperation(converter, op);
889 FailureOr<bool> opChanged = convertOperationTypes(op, converter);
890 if (failed(opChanged)) {
891 return WalkResult::interrupt();
893 changed |= *opChanged;
894 return WalkResult::advance();
896 if (res.wasInterrupted()) {
903template <
typename ConverterT>
904static LogicalResult convertOperationTypesIn(Operation *root, ConverterT &converter) {
905 return failure(failed(convertOperationTypesInAndTrack(root, converter)));
914static void removeIdentityCasts(Operation *root) {
916 if (castOp.getInput().getType() != castOp.getResult().getType()) {
919 castOp.getResult().replaceAllUsesWith(castOp.getInput());
925template <
typename ConverterT>
926static LogicalResult convertTemplateExprTypesIn(
TemplateOp templateOp, ConverterT &converter) {
928 if (failed(convertOperationTypesIn(expr.getOperation(), converter))) {
931 removeIdentityCasts(expr.getOperation());
941static std::string buildSpecializedTemplateCloneCacheKey(
942 StringRef templateName, ArrayRef<StringAttr> oldParamOrder,
943 const DenseMap<Attribute, Attribute> ¶mNameToConcrete
946 llvm::raw_string_ostream os(key);
947 os << templateName.size() <<
':' << templateName;
948 for (StringAttr paramName : oldParamOrder) {
950 os << paramName.getValue().size() <<
':' << paramName.getValue() <<
'=';
951 auto concreteIt = paramNameToConcrete.find(FlatSymbolRefAttr::get(paramName));
952 if (concreteIt == paramNameToConcrete.end()) {
957 std::string attrText;
958 llvm::raw_string_ostream attrOs(attrText);
959 concreteIt->second.print(attrOs);
960 os << attrText.size() <<
':' << attrText;
966static bool canCopyTemplateExprToSpecialization(
973 return WalkResult::interrupt();
975 return WalkResult::advance();
984static void copyPreservedTemplateExprs(
985 TemplateOp parentTemplate, Block &newTemplateBody, ArrayRef<Attribute> remainingNames
987 DenseSet<StringAttr> availableNames;
988 for (Attribute name : remainingNames) {
989 FlatSymbolRefAttr nameSym = llvm::cast<FlatSymbolRefAttr>(name);
990 availableNames.insert(nameSym.getAttr());
994 if (canCopyTemplateExprToSpecialization(expr, availableNames)) {
995 newTemplateBody.push_back(expr->clone());
1001static FailureOr<TemplateOp> getOrCreateSpecializedTemplateClone(
1002 TemplateOp parentTemplate, ArrayRef<StringAttr> oldParamOrder,
1003 const DenseMap<Attribute, Attribute> ¶mNameToConcrete, ArrayAttr callParams,
1004 SymbolTableCollection &tables, llvm::StringMap<StringAttr> &templateClones,
1007 FailureOr<InstantiationLayout> layoutResult =
1009 if (failed(layoutResult)) {
1012 layout = std::move(*layoutResult);
1013 std::string cacheKey = buildSpecializedTemplateCloneCacheKey(
1014 parentTemplate.
getSymName(), oldParamOrder, paramNameToConcrete
1018 if (!parentModule) {
1021 SymbolTable &moduleSymbols = tables.getSymbolTable(parentModule);
1023 auto cachedName = templateClones.find(cacheKey);
1024 if (cachedName != templateClones.end()) {
1025 Operation *existing = moduleSymbols.lookup(cachedName->second);
1026 if (
auto existingTemplate = llvm::dyn_cast_or_null<TemplateOp>(existing)) {
1027 return existingTemplate;
1032 TemplateOp newTemplate = parentTemplate.cloneWithoutRegions();
1037 assert(newTemplate->getNumRegions() > 0 &&
"region exists");
1039 Block &newTemplateBody = newTemplate.
getBodyRegion().front();
1040 SymbolTable &parentTemplateSymbols = tables.getSymbolTable(parentTemplate);
1042 FlatSymbolRefAttr nameSym = llvm::cast<FlatSymbolRefAttr>(name);
1043 Operation *paramOp = parentTemplateSymbols.lookup(nameSym.getAttr());
1044 assert(paramOp &&
"symbol must exist");
1045 newTemplateBody.push_back(paramOp->clone());
1047 copyPreservedTemplateExprs(parentTemplate, newTemplateBody, layout.
remainingNames);
1049 moduleSymbols.insert(newTemplate, Block::iterator(parentTemplate));
1050 templateClones.try_emplace(cacheKey, newTemplate.
getSymNameAttr());
1060class ConcreteStructInstantiationConverter {
1062 struct StructInstantiationTypes {
1064 StructType localType;
1066 StructType remoteType;
1074 SymbolTableCollection &tables_;
1076 DenseMap<StructType, StructInstantiationTypes> instantiations_;
1078 SpecializedTemplateCloneCache templateClones_;
1080 DenseSet<SymbolRefAttr> instantiatedCloneNames_;
1082 DenseMap<StructType, StructType> activeLocalStructReplacements_;
1084 DenseMap<StringAttr, Type> activeTypeReplacements_;
1086 bool hasFailure =
false;
1090 ConcreteStructInstantiationConverter(MLIRContext *c, ModuleOp m, SymbolTableCollection &t)
1091 : ctx_(c), module_(m), tables_(t) {}
1094 bool hadFailure()
const {
return hasFailure; }
1097 Type convertType(Type ty) {
1098 if (!ty || hasFailure) {
1101 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1102 auto it = activeTypeReplacements_.find(tvarTy.getNameRef().getAttr());
1103 return it == activeTypeReplacements_.end() ? ty : it->second;
1105 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1106 return convertArrayElementType(arrTy, [
this](Type elemTy) {
return convertType(elemTy); });
1108 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1109 return convertPodType(podTy, ctx_, *
this);
1111 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1112 return convertFunctionType(funcTy, *
this);
1114 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1115 return convertStructType(structTy);
1121 Attribute convertAttr(Attribute attr) {
1125 return convertTypeOrArrayAttr(attr, ctx_, [
this](Type ty) {
1126 return convertType(ty);
1127 }, [
this](Attribute nested) {
return convertTemplateArgAttr(nested); });
1131 SymbolRefAttr convertCallCallee(CallOp callOp) {
1133 if (!callee || callee.getNestedReferences().empty()) {
1137 StructType targetStructTy = getStructFunctionTargetType(callOp);
1138 if (!targetStructTy) {
1141 auto convertedStructTy = llvm::dyn_cast<StructType>(convertType(targetStructTy));
1142 if (!convertedStructTy) {
1146 SymbolRefAttr convertedStructName = convertedStructTy.getNameRef();
1150 SmallVector<FlatSymbolRefAttr> pieces =
getPieces(convertedStructName);
1151 pieces.push_back(FlatSymbolRefAttr::get(callee.getLeafReference()));
1156 SymbolRefAttr convertContractTarget(verif::ContractOp contract) {
1163 if (contractTy.getNumInputs() == 0) {
1166 auto selfTy = llvm::dyn_cast<StructType>(contractTy.getInput(0));
1167 if (!selfTy || selfTy.getNameRef() == target) {
1170 return instantiatedCloneNames_.contains(selfTy.getNameRef()) ? selfTy.getNameRef() : target;
1175 static StructType getStructFunctionTargetType(CallOp callOp) {
1176 StringAttr calleeLeaf = callOp.
getCallee().getLeafReference();
1187 Attribute convertTemplateArgAttr(Attribute attr) {
1188 if (StringAttr symbolName = getFlatSymbolName(attr)) {
1189 auto it = activeTypeReplacements_.find(symbolName);
1190 if (it != activeTypeReplacements_.end()) {
1191 return TypeAttr::get(it->second);
1194 return convertAttr(attr);
1198 StructType convertStructType(StructType structTy) {
1199 ArrayAttr params = structTy.
getParams();
1204 SmallVector<Attribute> newParams;
1205 bool changed =
false;
1206 for (Attribute attr : params.getValue()) {
1207 Attribute newAttr = convertTemplateArgAttr(attr);
1208 newParams.push_back(newAttr);
1209 changed |= newAttr != attr;
1211 StructType convertedTy =
1215 if (
auto it = activeLocalStructReplacements_.find(convertedTy);
1216 it != activeLocalStructReplacements_.end()) {
1219 if (instantiatedCloneNames_.contains(convertedTy.
getNameRef())) {
1223 if (llvm::any_of(newParams, [](Attribute attr) {
1229 FailureOr<StructType> cloneTy = getOrCreateStructClone(convertedTy, newParams);
1230 if (failed(cloneTy)) {
1238 FailureOr<StructType>
1239 getOrCreateStructClone(StructType concreteStructTy, ArrayRef<Attribute> concreteParams) {
1240 if (
auto it = instantiations_.find(concreteStructTy); it != instantiations_.end()) {
1241 return it->second.remoteType;
1244 FailureOr<SymbolLookupResult<StructDefOp>> lookup =
1246 if (failed(lookup)) {
1250 StructDefOp origStruct = lookup->get();
1252 if (!parentTemplate) {
1255 StructType typeAtDef = origStruct.
getType();
1256 ArrayAttr paramNames = typeAtDef.
getParams();
1257 if (!paramNames || paramNames.size() != concreteParams.size()) {
1261 DenseMap<StringAttr, Type> typeReplacements;
1262 DenseMap<Attribute, Attribute> paramNameToConcrete;
1263 SmallVector<StringAttr> oldParamOrder;
1264 oldParamOrder.reserve(paramNames.size());
1265 SmallVector<Attribute> convertedSourceParams;
1266 convertedSourceParams.reserve(concreteParams.size());
1267 for (
auto [paramName, concreteAttr] : llvm::zip_equal(paramNames.getValue(), concreteParams)) {
1268 auto paramSym = llvm::dyn_cast<FlatSymbolRefAttr>(paramName);
1272 oldParamOrder.push_back(paramSym.getAttr());
1273 auto concreteType = llvm::dyn_cast<TypeAttr>(concreteAttr);
1275 paramNameToConcrete.try_emplace(FlatSymbolRefAttr::get(paramSym.getAttr()), concreteAttr);
1276 typeReplacements.try_emplace(paramSym.getAttr(), concreteType.getValue());
1277 convertedSourceParams.push_back(concreteType);
1279 convertedSourceParams.push_back(paramName);
1282 if (paramNameToConcrete.empty()) {
1283 return concreteStructTy;
1286 InstantiationLayout layout;
1287 ArrayAttr concreteParamArray = ArrayAttr::get(ctx_, concreteParams);
1288 FailureOr<TemplateOp> newTemplate = getOrCreateSpecializedTemplateClone(
1289 parentTemplate, oldParamOrder, paramNameToConcrete, concreteParamArray, tables_,
1290 templateClones_[parentTemplate.getOperation()], layout
1292 if (failed(newTemplate)) {
1296 SymbolTable &templateSymbols = tables_.getSymbolTable(*newTemplate);
1297 StructDefOp clone = origStruct.clone();
1298 templateSymbols.insert(clone);
1299 StructType localTy =
1301 StructType remoteTy =
1303 instantiations_.try_emplace(concreteStructTy, StructInstantiationTypes {localTy, remoteTy});
1306 DenseMap<StringAttr, Type> previousReplacements = std::move(activeTypeReplacements_);
1307 DenseMap<StructType, StructType> previousLocalStructReplacements =
1308 std::move(activeLocalStructReplacements_);
1309 activeTypeReplacements_ = std::move(typeReplacements);
1310 activeLocalStructReplacements_.clear();
1311 activeLocalStructReplacements_.try_emplace(concreteStructTy, localTy);
1312 activeLocalStructReplacements_.try_emplace(
1316 activeLocalStructReplacements_.try_emplace(
1319 activeLocalStructReplacements_.try_emplace(
1323 if (failed(convertTemplateExprTypesIn(*newTemplate, *
this))) {
1324 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1325 activeTypeReplacements_ = std::move(previousReplacements);
1326 instantiations_.erase(concreteStructTy);
1327 instantiatedCloneNames_.erase(cloneNameRef);
1331 if (failed(convertOperationTypesIn(clone.getOperation(), *
this))) {
1332 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1333 activeTypeReplacements_ = std::move(previousReplacements);
1334 instantiations_.erase(concreteStructTy);
1335 instantiatedCloneNames_.erase(cloneNameRef);
1339 removeIdentityCasts(clone.getOperation());
1340 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1341 activeTypeReplacements_ = std::move(previousReplacements);
1347struct TemplateInferenceInfo {
1349 TemplateOp templateOp;
1351 SmallVector<StringAttr> templatePath;
1353 SmallVector<StringAttr> oldParamOrder;
1355 DenseMap<StringAttr, TemplateParamOp> typeVarParams;
1357 DenseMap<StringAttr, InferredType> replacements;
1359 DenseMap<StringAttr, InferredType> templateScopeReplacements;
1361 DenseMap<Operation *, DenseMap<StringAttr, InferredType>> functionReplacements;
1365static DenseMap<Attribute, Attribute>
1366buildParamNameToCallArg(ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder) {
1367 DenseMap<Attribute, Attribute> paramNameToCallArg;
1368 if (!callParams || callParams.size() != oldParamOrder.size()) {
1369 return paramNameToCallArg;
1371 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder, callParams.getValue())) {
1372 paramNameToCallArg.try_emplace(FlatSymbolRefAttr::get(paramName), attr);
1374 return paramNameToCallArg;
1384substituteExplicitCallTypeArgs(Type ty, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder) {
1385 if (!callParams || callParams.size() != oldParamOrder.size()) {
1389 DenseMap<StringAttr, Type> callTypeArgs;
1390 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder, callParams.getValue())) {
1391 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1392 callTypeArgs.try_emplace(paramName, tyAttr.getValue());
1395 TypeVarReplacementConverter converter(
1396 ty.getContext(), ArrayRef<StringAttr> {}, oldParamOrder, callTypeArgs,
1399 return converter.convertType(ty);
1403class ExplicitCallTemplateParamSubstituter {
1405 const DenseMap<Attribute, Attribute> ¶mNameToCallArg_;
1407 DenseSet<Attribute> resolvingParams_;
1410 explicit ExplicitCallTemplateParamSubstituter(
1411 const DenseMap<Attribute, Attribute> ¶mNameToCallArg
1413 : paramNameToCallArg_(paramNameToCallArg) {}
1415 Type substituteType(Type ty);
1416 Attribute substituteAttr(Attribute attr);
1420Attribute ExplicitCallTemplateParamSubstituter::substituteAttr(Attribute attr) {
1424 auto it = paramNameToCallArg_.find(attr);
1425 if (it != paramNameToCallArg_.end()) {
1428 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1429 Type newTy = substituteType(tyAttr.getValue());
1430 return newTy == tyAttr.getValue() ? attr : TypeAttr::get(newTy);
1432 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1433 SmallVector<Attribute> newAttrs;
1434 bool changed =
false;
1435 for (Attribute nested : arrAttr.getValue()) {
1436 Attribute newNested = substituteAttr(nested);
1437 newAttrs.push_back(newNested);
1438 changed |= newNested != nested;
1440 return changed ? ArrayAttr::get(attr.getContext(), newAttrs) : attr;
1452Type ExplicitCallTemplateParamSubstituter::substituteType(Type ty) {
1456 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1457 Attribute paramRef = tvarTy.getNameRef();
1458 auto it = paramNameToCallArg_.find(paramRef);
1459 if (it == paramNameToCallArg_.end()) {
1462 auto tyAttr = llvm::dyn_cast<TypeAttr>(it->second);
1463 if (!tyAttr || tyAttr.getValue() == ty) {
1466 if (!resolvingParams_.insert(paramRef).second) {
1469 Type replacement = substituteType(tyAttr.getValue());
1470 resolvingParams_.erase(paramRef);
1473 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1474 SmallVector<Attribute> newDims;
1475 bool changed =
false;
1477 Attribute newDim = substituteAttr(dim);
1478 newDims.push_back(newDim);
1479 changed |= newDim != dim;
1489 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1490 ArrayAttr params = structTy.
getParams();
1494 SmallVector<Attribute> newParams;
1495 bool changed =
false;
1496 for (Attribute param : params.getValue()) {
1497 Attribute newParam = substituteAttr(param);
1498 newParams.push_back(newParam);
1499 changed |= newParam != param;
1504 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1505 SmallVector<RecordAttr> newRecords;
1506 bool changed =
false;
1507 for (RecordAttr record : podTy.
getRecords()) {
1508 Type newRecordTy = substituteType(record.getType());
1509 newRecords.push_back(RecordAttr::get(ty.getContext(), record.getName(), newRecordTy));
1510 changed |= newRecordTy != record.getType();
1512 return changed ?
PodType::get(ty.getContext(), newRecords) : podTy;
1514 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1515 SmallVector<Type> newInputs;
1516 SmallVector<Type> newResults;
1517 bool changed =
false;
1518 newInputs.reserve(funcTy.getNumInputs());
1519 newResults.reserve(funcTy.getNumResults());
1520 for (Type inputTy : funcTy.getInputs()) {
1521 Type newInputTy = substituteType(inputTy);
1522 newInputs.push_back(newInputTy);
1523 changed |= newInputTy != inputTy;
1525 for (Type resultTy : funcTy.getResults()) {
1526 Type newResultTy = substituteType(resultTy);
1527 newResults.push_back(newResultTy);
1528 changed |= newResultTy != resultTy;
1530 return changed ? FunctionType::get(ty.getContext(), newInputs, newResults) : funcTy;
1536static Type substituteExplicitCallTemplateParams(
1537 Type ty, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder
1539 auto paramNameToCallArg = buildParamNameToCallArg(callParams, oldParamOrder);
1540 ExplicitCallTemplateParamSubstituter substituter(paramNameToCallArg);
1541 return substituter.substituteType(ty);
1545static bool symbolMatchesParam(SymbolRefAttr symRef, StringAttr paramName) {
1546 return symRef && symRef.getNestedReferences().empty() && symRef.getRootReference() == paramName;
1550class ParamMentionChecker {
1551 StringAttr paramName_;
1554 explicit ParamMentionChecker(StringAttr paramName) : paramName_(paramName) {}
1557 bool typeMentions(Type ty)
const {
1561 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1562 return tvarTy.getNameRef().getAttr() == paramName_;
1564 if (
auto arrayTy = llvm::dyn_cast<ArrayType>(ty)) {
1565 return typeMentions(arrayTy.getElementType()) ||
1566 llvm::any_of(arrayTy.getDimensionSizes(), [
this](Attribute dim) {
1567 return attrMentions(dim, true);
1570 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1571 ArrayAttr params = structTy.
getParams();
1572 return params && attrMentions(params,
true);
1574 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1575 return llvm::any_of(podTy.
getRecords(), [
this](RecordAttr record) {
1576 return typeMentions(record.getType());
1579 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1580 return llvm::any_of(funcTy.getInputs(), [
this](Type input) {
1581 return typeMentions(input);
1582 }) || llvm::any_of(funcTy.getResults(), [
this](Type result) { return typeMentions(result); });
1592 bool attrMentions(Attribute attr,
bool allowSymbolRefs)
const {
1596 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1597 return typeMentions(typeAttr.getValue());
1599 if (
auto arrayAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1600 return llvm::any_of(arrayAttr, [
this](Attribute nested) {
1601 return attrMentions(nested,
true);
1604 return allowSymbolRefs && symbolMatchesParam(llvm::dyn_cast<SymbolRefAttr>(attr), paramName_);
1609static bool operationMentionsParam(Operation *op, StringAttr paramName) {
1610 ParamMentionChecker mentions(paramName);
1611 if (llvm::any_of(op->getResultTypes(), [&mentions](Type ty) {
1612 return mentions.typeMentions(ty);
1616 for (Region ®ion : op->getRegions()) {
1617 for (Block &block : region.getBlocks()) {
1618 if (llvm::any_of(block.getArgumentTypes(), [&mentions](Type ty) {
1619 return mentions.typeMentions(ty);
1625 return llvm::any_of(op->getAttrs(), [&mentions](NamedAttribute attr) {
1626 return mentions.attrMentions(attr.getValue(), false);
1631static SmallVector<StringAttr> getMentionedTypeVarParams(
1632 Attribute attr,
const DenseMap<StringAttr, TemplateParamOp> &typeVarParams
1634 SmallVector<StringAttr> mentionedParams;
1635 for (
const auto &entry : typeVarParams) {
1636 if (ParamMentionChecker(entry.first).attrMentions(attr,
true)) {
1637 mentionedParams.push_back(entry.first);
1640 return mentionedParams;
1644static inline bool attrMentionsAnyTypeVarParam(
1645 Attribute attr,
const DenseMap<StringAttr, TemplateParamOp> &typeVarParams
1647 return !getMentionedTypeVarParams(attr, typeVarParams).empty();
1651static bool funcMentionsParam(FuncDefOp func, StringAttr paramName) {
1652 if (operationMentionsParam(func.getOperation(), paramName)) {
1655 return walkContains<Operation *>(func, [paramName](Operation *op) {
1656 return operationMentionsParam(op, paramName);
1661static bool contractMentionsParam(verif::ContractOp contract, StringAttr paramName) {
1662 if (operationMentionsParam(contract.getOperation(), paramName)) {
1665 return walkContains<Operation *>(contract, [paramName](Operation *op) {
1666 return operationMentionsParam(op, paramName);
1671static inline bool targetMentionsParam(FuncDefOp func, StringAttr paramName) {
1672 return funcMentionsParam(func, paramName);
1676static inline bool targetMentionsParam(verif::ContractOp contract, StringAttr paramName) {
1677 return contractMentionsParam(contract, paramName);
1681static inline bool exprMentionsParam(TemplateExprOp expr, StringAttr paramName) {
1682 return walkContains<Operation *>(expr, [paramName](Operation *op) {
1683 return operationMentionsParam(op, paramName);
1689static bool structUseCoveredByFunctionProof(
1690 StructDefOp structOp, StringAttr paramName, Type replacementType,
1691 const DenseMap<Operation *, DenseMap<StringAttr, InferredType>> &functionReplacements
1693 bool sawMention =
false;
1694 bool missingProof =
false;
1695 structOp.walk([&](FuncDefOp func) {
1696 if (func->getParentOfType<StructDefOp>() != structOp || !funcMentionsParam(func, paramName)) {
1700 auto funcIt = functionReplacements.find(func.getOperation());
1701 if (funcIt == functionReplacements.end()) {
1702 missingProof =
true;
1705 auto replacementIt = funcIt->second.find(paramName);
1706 if (replacementIt == funcIt->second.end() || replacementIt->second.type != replacementType) {
1707 missingProof =
true;
1710 return sawMention && !missingProof;
1720static bool hasUncoveredNonFunctionMention(
1721 TemplateOp templateOp, StringAttr paramName, Type replacementType,
1722 const DenseMap<Operation *, DenseMap<StringAttr, InferredType>> &functionReplacements
1725 templateOp.walk([paramName, replacementType, &functionReplacements](Operation *op) {
1726 if (llvm::isa<FuncDefOp, TemplateExprOp, TemplateParamOp, verif::ContractOp>(op) ||
1727 op->getParentOfType<FuncDefOp, TemplateExprOp, verif::ContractOp>()) {
1728 return WalkResult::advance();
1730 if (!operationMentionsParam(op, paramName)) {
1731 return WalkResult::advance();
1733 if (StructDefOp structOp = op->getParentOfType<StructDefOp>()) {
1734 if (structUseCoveredByFunctionProof(
1735 structOp, paramName, replacementType, functionReplacements
1737 return WalkResult::advance();
1740 return WalkResult::interrupt();
1742 return result.wasInterrupted();
1751class TypeVarInferenceCollector {
1753 TemplateInferenceInfo &inferenceInfo;
1755 DenseMap<StringAttr, InferredType> &replacements;
1757 DenseMap<Value, InferredType> byValue;
1759 DenseMap<StringAttr, DenseSet<StringAttr>> paramRelations;
1761 bool changedInIteration =
false;
1765 TypeVarInferenceCollector(
1766 TemplateInferenceInfo &info, DenseMap<StringAttr, InferredType> &scopeReplacements
1768 : inferenceInfo(info), replacements(scopeReplacements) {}
1771 LogicalResult collect(Operation *root) {
1773 changedInIteration =
false;
1774 auto result = root->walk([
this](UnifiableCastOp castOp) -> WalkResult {
1775 return collectTypePairInferences(
1780 if (result.wasInterrupted()) {
1783 }
while (changedInIteration);
1788 LogicalResult collectTypeInferences(Type lhs, Type rhs, Location loc) {
1790 changedInIteration =
false;
1791 if (failed(collectTypePairInferences(lhs, rhs, Value(), Value(), loc))) {
1794 }
while (changedInIteration);
1806 LogicalResult collectStructTemplateParamInferences(
1807 Operation *root, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1808 SymbolTableCollection &tables
1810 auto result = root->walk([&](Operation *op) -> WalkResult {
1811 return collectOperationStructTemplateParamInferences(op, module, infos, tables);
1813 return failure(result.wasInterrupted());
1817 LogicalResult collectOperationStructTemplateParamInferences(
1818 Operation *op, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1819 SymbolTableCollection &tables
1821 Location loc = op->getLoc();
1823 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
1824 if (failed(collectStructTemplateParamInferences(
1831 for (Region ®ion : op->getRegions()) {
1832 for (Block &block : region.getBlocks()) {
1833 for (Type argTy : block.getArgumentTypes()) {
1834 if (failed(collectStructTemplateParamInferences(argTy, loc, module, infos, tables))) {
1841 for (Type resultTy : op->getResultTypes()) {
1842 if (failed(collectStructTemplateParamInferences(resultTy, loc, module, infos, tables))) {
1847 if (
auto callOp = llvm::dyn_cast<CallOp>(op)) {
1848 if (failed(collectCallableTemplateParamInferences(callOp, infos, tables))) {
1852 if (
auto includeOp = llvm::dyn_cast<verif::IncludeOp>(op)) {
1853 if (failed(collectIncludeTemplateParamInferences(includeOp, infos, tables))) {
1858 for (NamedAttribute attr : op->getAttrs()) {
1860 collectStructTemplateParamInferences(attr.getValue(), loc, module, infos, tables)
1874 LogicalResult collectStructTemplateParamInferences(
1875 Attribute attr, Location loc, ModuleOp module,
1876 DenseMap<Operation *, TemplateInferenceInfo *> &infos, SymbolTableCollection &tables
1881 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1882 return collectStructTemplateParamInferences(tyAttr.getValue(), loc, module, infos, tables);
1884 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1885 for (Attribute nested : arrAttr.getValue()) {
1886 if (failed(collectStructTemplateParamInferences(nested, loc, module, infos, tables))) {
1902 LogicalResult collectStructTemplateParamInferences(
1903 Type ty, Location loc, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1904 SymbolTableCollection &tables
1909 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1910 return collectStructTemplateParamInferences(
1914 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1915 for (RecordAttr record : podTy.
getRecords()) {
1917 collectStructTemplateParamInferences(record.getType(), loc, module, infos, tables)
1924 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1925 for (Type inputTy : funcTy.getInputs()) {
1926 if (failed(collectStructTemplateParamInferences(inputTy, loc, module, infos, tables))) {
1930 for (Type resultTy : funcTy.getResults()) {
1931 if (failed(collectStructTemplateParamInferences(resultTy, loc, module, infos, tables))) {
1937 auto structTy = llvm::dyn_cast<StructType>(ty);
1942 ArrayAttr params = structTy.
getParams();
1946 for (Attribute attr : params.getValue()) {
1947 if (failed(collectStructTemplateParamInferences(attr, loc, module, infos, tables))) {
1952 FailureOr<SymbolLookupResult<StructDefOp>> lookup =
1954 if (failed(lookup)) {
1958 if (!parentTemplate) {
1961 TemplateInferenceInfo *targetInfo = infos.lookup(parentTemplate.getOperation());
1962 if (!targetInfo || targetInfo->replacements.empty() ||
1963 params.size() != targetInfo->oldParamOrder.size()) {
1967 for (
auto [paramName, attr] : llvm::zip_equal(targetInfo->oldParamOrder, params.getValue())) {
1968 auto replacementIt = targetInfo->replacements.find(paramName);
1969 if (replacementIt == targetInfo->replacements.end()) {
1972 Type expectedTy = substituteExplicitCallTemplateParams(
1973 replacementIt->second.type, params, targetInfo->oldParamOrder
1975 Attribute expectedAttr = TypeAttr::get(expectedTy);
1976 if (failed(collectTemplateArgInferences(attr, expectedAttr, loc))) {
1989 SmallVector<Attribute>
1990 getInferredOmittedTemplateArgs(
const UnificationMap &unifyResult, StringAttr targetParamName) {
1991 SmallVector<Attribute> inferredAttrs;
1992 auto targetRef = FlatSymbolRefAttr::get(targetParamName);
1993 auto inferredIt = unifyResult.find({targetRef, Side::RHS});
1994 if (inferredIt != unifyResult.end()) {
1995 inferredAttrs.push_back(inferredIt->second);
1997 for (
const auto &entry : unifyResult) {
1998 if (entry.first.second == Side::LHS && entry.second == targetRef) {
1999 inferredAttrs.push_back(entry.first.first);
2002 return inferredAttrs;
2006 template <
typename TargetOp>
2007 TemplateInferenceInfo *
2008 getTargetTemplateInfo(TargetOp targetOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos) {
2010 if (!parentTemplate) {
2013 TemplateInferenceInfo *targetInfo = infos.lookup(parentTemplate.getOperation());
2014 if (!targetInfo || targetInfo->replacements.empty()) {
2027 template <
typename CallableOp>
2028 LogicalResult collectCallableUseTemplateParamInferences(
2029 CallableOp callableOp, FunctionType targetSignature, TemplateInferenceInfo &targetInfo
2031 ArrayAttr params = callableOp.getTemplateParamsAttr();
2033 if (params.size() != targetInfo.oldParamOrder.size()) {
2036 struct DeferredExplicitArgInference {
2038 Attribute expectedAttr;
2039 SmallVector<StringAttr> mentionedParams;
2041 SmallVector<DeferredExplicitArgInference> deferredExplicitArgInferences;
2042 bool deferredToSignature =
false;
2043 for (
auto [paramName, attr] : llvm::zip_equal(targetInfo.oldParamOrder, params)) {
2044 auto replacementIt = targetInfo.replacements.find(paramName);
2045 if (replacementIt == targetInfo.replacements.end()) {
2048 Type expectedTy = substituteExplicitCallTemplateParams(
2049 replacementIt->second.type, params, targetInfo.oldParamOrder
2051 Attribute expectedAttr = TypeAttr::get(expectedTy);
2052 if (attrMentionsAnyTypeVarParam(attr, inferenceInfo.typeVarParams)) {
2053 deferredToSignature =
true;
2054 SmallVector<StringAttr> mentionedParams =
2055 getMentionedTypeVarParams(attr, inferenceInfo.typeVarParams);
2056 if (!ParamMentionChecker(paramName).typeMentions(targetSignature)) {
2057 if (failed(collectTemplateArgInferences(attr, expectedAttr, callableOp.getLoc()))) {
2061 deferredExplicitArgInferences.push_back(
2062 {attr, expectedAttr, std::move(mentionedParams)}
2067 if (failed(collectTemplateArgInferences(attr, expectedAttr, callableOp.getLoc()))) {
2071 if (deferredToSignature) {
2072 DenseMap<StringAttr, Type> targetReplacements;
2073 for (
const auto &entry : targetInfo.replacements) {
2074 targetReplacements.try_emplace(entry.first, entry.second.type);
2076 TypeVarReplacementConverter converter(
2077 callableOp.getContext(), targetInfo.templatePath, targetInfo.oldParamOrder,
2078 targetReplacements,
false
2080 Type rewrittenTy = substituteExplicitCallTemplateParams(
2081 converter.convertType(targetSignature), params, targetInfo.oldParamOrder
2083 if (failed(collectTypeInferences(
2084 callableOp.getTypeSignature(), llvm::cast<FunctionType>(rewrittenTy),
2090 for (
const DeferredExplicitArgInference &deferred : deferredExplicitArgInferences) {
2091 bool signatureCanInferAllParams =
2092 llvm::all_of(deferred.mentionedParams, [&](StringAttr mentionedParam) {
2093 return ParamMentionChecker(mentionedParam).typeMentions(callableOp.getTypeSignature());
2095 bool signatureHasInferredAllParams =
2096 llvm::all_of(deferred.mentionedParams, [&](StringAttr mentionedParam) {
2097 return replacements.contains(mentionedParam);
2099 if (signatureCanInferAllParams && signatureHasInferredAllParams) {
2102 if (failed(collectTemplateArgInferences(
2103 deferred.attr, deferred.expectedAttr, callableOp.getLoc()
2112 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetSignature);
2113 if (failed(unifyResult)) {
2117 for (StringAttr paramName : targetInfo.oldParamOrder) {
2118 auto replacementIt = targetInfo.replacements.find(paramName);
2119 if (replacementIt == targetInfo.replacements.end()) {
2122 SmallVector<Attribute> inferredAttrs =
2123 getInferredOmittedTemplateArgs(*unifyResult, paramName);
2124 if (inferredAttrs.empty()) {
2128 Attribute expectedAttr = TypeAttr::get(replacementIt->second.type);
2129 for (Attribute inferredAttr : inferredAttrs) {
2130 if (!inferredAttr || !
typeParamsUnify({inferredAttr}, {expectedAttr})) {
2131 InFlightDiagnostic diag = callableOp.emitError()
2132 <<
"implicit template argument for inferred parameter @"
2133 << paramName.getValue() <<
" must match inferred type "
2134 << replacementIt->second.type <<
", but found ";
2135 if (
auto typeAttr = llvm::dyn_cast_if_present<TypeAttr>(inferredAttr)) {
2136 diag << typeAttr.getValue();
2138 diag << inferredAttr;
2142 if (failed(collectTemplateArgInferences(inferredAttr, expectedAttr, callableOp.getLoc()))) {
2159 LogicalResult collectCallableTemplateParamInferences(
2160 CallOp callOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
2161 SymbolTableCollection &tables
2163 FailureOr<SymbolLookupResult<FuncDefOp>> target = callOp.
getCalleeTarget(tables);
2164 if (failed(target)) {
2167 FuncDefOp targetFunc = target->get();
2168 TemplateInferenceInfo *targetInfo = getTargetTemplateInfo(targetFunc, infos);
2172 return collectCallableUseTemplateParamInferences(
2183 LogicalResult collectIncludeTemplateParamInferences(
2184 verif::IncludeOp includeOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
2185 SymbolTableCollection &tables
2187 FailureOr<SymbolLookupResult<verif::ContractOp>> target = includeOp.
getCalleeTarget(tables);
2188 if (failed(target)) {
2191 verif::ContractOp targetContract = target->get();
2192 TemplateInferenceInfo *targetInfo = getTargetTemplateInfo(targetContract, infos);
2196 return collectCallableUseTemplateParamInferences(
2214 LogicalResult recordInference(StringAttr paramName, Type inferredTy, Value value, Location loc) {
2215 if (!inferenceInfo.typeVarParams.contains(paramName)) {
2218 if (
auto inferredTvar = llvm::dyn_cast<TypeVarType>(inferredTy)) {
2219 return recordParamRelation(paramName, inferredTvar.getNameRef().getAttr(), loc);
2225 auto reportConflict = [&](StringRef kind, Location originalLoc, Type originalTy) {
2226 InFlightDiagnostic diag = emitError(loc) <<
"conflicting inferred type for " << kind <<
" @"
2227 << paramName.getValue() <<
": " << originalTy
2228 <<
" vs " << inferredTy;
2229 diag.attachNote(originalLoc) <<
"previous inference here";
2233 auto byParamIt = replacements.find(paramName);
2234 bool learnedParamInference =
false;
2235 if (byParamIt == replacements.end()) {
2236 replacements.try_emplace(paramName, InferredType {inferredTy, loc});
2237 changedInIteration =
true;
2238 learnedParamInference =
true;
2239 }
else if (byParamIt->second.type != inferredTy) {
2240 return reportConflict(
"template parameter", byParamIt->second.loc, byParamIt->second.type);
2244 auto byValueIt = byValue.find(value);
2245 if (byValueIt == byValue.end()) {
2246 byValue.try_emplace(value, InferredType {inferredTy, loc});
2247 changedInIteration =
true;
2248 }
else if (byValueIt->second.type != inferredTy) {
2249 return reportConflict(
"SSA value using", byValueIt->second.loc, byValueIt->second.type);
2253 if (learnedParamInference) {
2254 auto relatedIt = paramRelations.find(paramName);
2255 if (relatedIt != paramRelations.end()) {
2256 for (StringAttr relatedParam : relatedIt->second) {
2257 if (failed(recordInference(relatedParam, inferredTy, Value(), loc))) {
2267 LogicalResult recordParamRelation(StringAttr lhsParam, StringAttr rhsParam, Location loc) {
2268 if (lhsParam == rhsParam || !inferenceInfo.typeVarParams.contains(rhsParam)) {
2272 bool inserted = paramRelations[lhsParam].insert(rhsParam).second;
2273 inserted |= paramRelations[rhsParam].insert(lhsParam).second;
2278 changedInIteration =
true;
2280 auto lhsIt = replacements.find(lhsParam);
2281 if (lhsIt != replacements.end() &&
2282 failed(recordInference(rhsParam, lhsIt->second.type, Value(), loc))) {
2285 auto rhsIt = replacements.find(rhsParam);
2286 if (rhsIt != replacements.end() &&
2287 failed(recordInference(lhsParam, rhsIt->second.type, Value(), loc))) {
2301 collectTypePairInferences(Type lhs, Type rhs, Value lhsValue, Value rhsValue, Location loc) {
2302 if (
auto lhsTvar = llvm::dyn_cast<TypeVarType>(lhs)) {
2303 if (failed(recordInference(lhsTvar.getNameRef().getAttr(), rhs, lhsValue, loc))) {
2307 auto rhsValueIt = byValue.find(rhsValue);
2308 if (rhsValueIt != byValue.end() &&
2309 failed(recordInference(
2310 lhsTvar.getNameRef().getAttr(), rhsValueIt->second.type, lhsValue, loc
2316 if (
auto rhsTvar = llvm::dyn_cast<TypeVarType>(rhs)) {
2317 if (failed(recordInference(rhsTvar.getNameRef().getAttr(), lhs, rhsValue, loc))) {
2321 auto lhsValueIt = byValue.find(lhsValue);
2322 if (lhsValueIt != byValue.end() &&
2323 failed(recordInference(
2324 rhsTvar.getNameRef().getAttr(), lhsValueIt->second.type, rhsValue, loc
2331 if (
auto lhsArr = llvm::dyn_cast<ArrayType>(lhs)) {
2332 if (
auto rhsArr = llvm::dyn_cast<ArrayType>(rhs)) {
2333 return collectTypePairInferences(
2334 lhsArr.getElementType(), rhsArr.getElementType(), Value(), Value(), loc
2339 if (
auto lhsStruct = llvm::dyn_cast<StructType>(lhs)) {
2340 if (
auto rhsStruct = llvm::dyn_cast<StructType>(rhs)) {
2341 ArrayRef<Attribute> lhsParams =
2342 lhsStruct.getParams() ? lhsStruct.getParams().getValue() : ArrayRef<Attribute> {};
2343 ArrayRef<Attribute> rhsParams =
2344 rhsStruct.getParams() ? rhsStruct.getParams().getValue() : ArrayRef<Attribute> {};
2345 if (lhsParams.size() != rhsParams.size()) {
2348 for (
auto [lhsAttr, rhsAttr] : llvm::zip_equal(lhsParams, rhsParams)) {
2349 if (failed(collectTemplateArgInferences(lhsAttr, rhsAttr, loc))) {
2356 if (
auto lhsPod = llvm::dyn_cast<PodType>(lhs)) {
2357 if (
auto rhsPod = llvm::dyn_cast<PodType>(rhs)) {
2358 ArrayRef<RecordAttr> lhsRecords = lhsPod.getRecords();
2359 ArrayRef<RecordAttr> rhsRecords = rhsPod.getRecords();
2360 if (lhsRecords.size() != rhsRecords.size()) {
2363 for (
auto [lhsRecord, rhsRecord] : llvm::zip_equal(lhsRecords, rhsRecords)) {
2364 if (lhsRecord.getName() != rhsRecord.getName()) {
2367 if (failed(collectTypePairInferences(
2368 lhsRecord.getType(), rhsRecord.getType(), Value(), Value(), loc
2376 if (
auto lhsFunc = llvm::dyn_cast<FunctionType>(lhs)) {
2377 if (
auto rhsFunc = llvm::dyn_cast<FunctionType>(rhs)) {
2378 if (lhsFunc.getNumInputs() != rhsFunc.getNumInputs() ||
2379 lhsFunc.getNumResults() != rhsFunc.getNumResults()) {
2382 for (
auto [lhsInput, rhsInput] :
2383 llvm::zip_equal(lhsFunc.getInputs(), rhsFunc.getInputs())) {
2384 if (failed(collectTypePairInferences(lhsInput, rhsInput, Value(), Value(), loc))) {
2388 for (
auto [lhsResult, rhsResult] :
2389 llvm::zip_equal(lhsFunc.getResults(), rhsFunc.getResults())) {
2390 if (failed(collectTypePairInferences(lhsResult, rhsResult, Value(), Value(), loc))) {
2407 LogicalResult collectTemplateArgInferences(Attribute lhsAttr, Attribute rhsAttr, Location loc) {
2408 auto lhsTyAttr = llvm::dyn_cast<TypeAttr>(lhsAttr);
2409 auto rhsTyAttr = llvm::dyn_cast<TypeAttr>(rhsAttr);
2410 if (lhsTyAttr && rhsTyAttr) {
2411 return collectTypePairInferences(
2412 lhsTyAttr.getValue(), rhsTyAttr.getValue(), Value(), Value(), loc
2416 if (StringAttr lhsSymbolName = getFlatSymbolName(lhsAttr)) {
2417 if (StringAttr rhsSymbolName = getFlatSymbolName(rhsAttr)) {
2418 return recordParamRelation(lhsSymbolName, rhsSymbolName, loc);
2420 if (rhsTyAttr && failed(recordInference(lhsSymbolName, rhsTyAttr.getValue(), Value(), loc))) {
2424 if (StringAttr rhsSymbolName = getFlatSymbolName(rhsAttr)) {
2425 if (lhsTyAttr && failed(recordInference(rhsSymbolName, lhsTyAttr.getValue(), Value(), loc))) {
2434static DenseMap<StringAttr, Type>
2435getFunctionProofReplacements(
const TemplateInferenceInfo &info, FuncDefOp func) {
2436 DenseMap<StringAttr, Type> replacements;
2437 auto funcIt = info.functionReplacements.find(func.getOperation());
2438 if (funcIt == info.functionReplacements.end()) {
2439 return replacements;
2441 for (
const auto &entry : funcIt->second) {
2442 replacements.try_emplace(entry.first, entry.second.type);
2444 return replacements;
2448static std::optional<unsigned>
2449getParamIndex(ArrayRef<StringAttr> paramOrder, StringAttr paramName) {
2450 for (
auto indexedParam : llvm::enumerate(paramOrder)) {
2451 if (indexedParam.value() == paramName) {
2452 return indexedParam.index();
2455 return std::nullopt;
2460static DenseMap<Attribute, Attribute>
2461buildParamNameToConcrete(
const DenseMap<StringAttr, Type> &replacements) {
2462 DenseMap<Attribute, Attribute> paramNameToConcrete;
2463 for (
const auto &entry : replacements) {
2464 paramNameToConcrete.try_emplace(
2465 FlatSymbolRefAttr::get(entry.first), TypeAttr::get(entry.second)
2468 return paramNameToConcrete;
2474static bool callParamsMatchReplacements(
2475 ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder,
2476 const DenseMap<StringAttr, Type> &replacements,
2477 const DenseMap<StringAttr, InferredType> *wildcardAllowedReplacements =
nullptr
2479 if (!callParams || callParams.size() != oldParamOrder.size()) {
2482 for (
const auto &entry : replacements) {
2483 std::optional<unsigned> index = getParamIndex(oldParamOrder, entry.first);
2487 Type expectedTy = substituteExplicitCallTypeArgs(entry.second, callParams, oldParamOrder);
2488 Attribute attr = callParams[*index];
2489 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr);
2490 intAttr &&
isDynamic(intAttr) && wildcardAllowedReplacements &&
2491 wildcardAllowedReplacements->contains(entry.first)) {
2494 if (!templateArgUnifiesWithType(attr, expectedTy)) {
2507static LogicalResult diagnoseCallParamsMismatch(
2508 Operation *callableOp, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder,
2509 const DenseMap<StringAttr, Type> &replacements,
2510 const DenseMap<StringAttr, InferredType> *wildcardAllowedReplacements,
bool explicitCallParams
2512 if (callParamsMatchReplacements(
2513 callParams, oldParamOrder, replacements, wildcardAllowedReplacements
2517 for (
const auto &entry : replacements) {
2518 std::optional<unsigned> index = getParamIndex(oldParamOrder, entry.first);
2519 if (!index || !callParams || *index >= callParams.size()) {
2522 Attribute attr = callParams[*index];
2523 Type expectedTy = substituteExplicitCallTypeArgs(entry.second, callParams, oldParamOrder);
2524 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr);
2525 intAttr &&
isDynamic(intAttr) && wildcardAllowedReplacements &&
2526 wildcardAllowedReplacements->contains(entry.first)) {
2529 if (templateArgUnifiesWithType(attr, expectedTy)) {
2533 InFlightDiagnostic diag = callableOp->emitError()
2534 << (explicitCallParams ?
"explicit" :
"implicit")
2535 <<
" template argument for inferred parameter @"
2536 << entry.first.getValue() <<
" must match inferred type "
2537 << expectedTy <<
", but found ";
2538 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
2539 diag << typeAttr.getValue();
2545 return callableOp->emitError() << (explicitCallParams ?
"explicit" :
"implicit")
2546 <<
" template arguments do not match inferred callee types";
2552static ArrayAttr expandCurrentTemplateParamsToOriginalOrder(
2553 ArrayAttr callParams,
const TemplateInferenceInfo &info
2555 if (!callParams || callParams.size() == info.oldParamOrder.size()) {
2559 unsigned currentParamCount = llvm::count_if(info.oldParamOrder, [&info](StringAttr paramName) {
2560 return !info.replacements.contains(paramName);
2562 if (callParams.size() != currentParamCount) {
2566 SmallVector<Attribute> expandedParams;
2567 expandedParams.reserve(info.oldParamOrder.size());
2568 unsigned currentIndex = 0;
2569 for (StringAttr paramName : info.oldParamOrder) {
2570 auto replacementIt = info.replacements.find(paramName);
2571 if (replacementIt != info.replacements.end()) {
2572 expandedParams.push_back(TypeAttr::get(replacementIt->second.type));
2575 expandedParams.push_back(callParams[currentIndex++]);
2577 return ArrayAttr::get(callParams.getContext(), expandedParams);
2586template <
typename TargetOp>
2587static DenseMap<StringAttr, Type> getConcreteCallSiteReplacements(
2588 ArrayAttr callParams,
const TemplateInferenceInfo &info, TargetOp targetOp
2590 DenseMap<StringAttr, Type> replacements;
2591 if (!callParams || callParams.size() != info.oldParamOrder.size()) {
2592 return replacements;
2595 bool sawResidualReplacement =
false;
2596 for (
const auto &entry : info.typeVarParams) {
2597 StringAttr paramName = entry.first;
2598 if (info.replacements.contains(paramName)) {
2601 if (!targetMentionsParam(targetOp, paramName)) {
2604 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2605 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2606 Attribute attr = callParams[*index];
2607 auto tyAttr = llvm::dyn_cast<TypeAttr>(attr);
2609 return DenseMap<StringAttr, Type>();
2611 replacements.try_emplace(paramName, tyAttr.getValue());
2612 sawResidualReplacement =
true;
2614 if (!sawResidualReplacement) {
2615 return DenseMap<StringAttr, Type>();
2618 for (
const auto &entry : info.replacements) {
2619 replacements.try_emplace(entry.first, entry.second.type);
2622 TypeVarReplacementConverter converter(
2623 info.templatePath.front().getContext(), info.templatePath, info.oldParamOrder, replacements,
2626 for (
const auto &entry : replacements) {
2628 return DenseMap<StringAttr, Type>();
2631 return replacements;
2635static bool isWildcardTemplateArg(Attribute attr) {
2636 auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr);
2641static void appendUniqueType(SmallVectorImpl<Type> &types, Type ty) {
2642 if (!llvm::any_of(types, [ty](Type existing) {
return existing == ty; })) {
2643 types.push_back(ty);
2648static void collectRhsTypeVarCandidates(
2649 Type lhsTy, Type rhsTy, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2653static void collectRhsTypeVarCandidates(
2654 ArrayRef<Attribute> lhsAttrs, ArrayRef<Attribute> rhsAttrs, SymbolRefAttr targetRef,
2655 SmallVectorImpl<Type> &candidates
2657 if (lhsAttrs.size() != rhsAttrs.size()) {
2660 for (
auto [lhsAttr, rhsAttr] : llvm::zip_equal(lhsAttrs, rhsAttrs)) {
2661 collectRhsTypeVarCandidates(lhsAttr, rhsAttr, targetRef, candidates);
2666static void collectRhsTypeVarCandidates(
2667 Attribute lhsAttr, Attribute rhsAttr, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2669 if (
auto rhsTypeAttr = llvm::dyn_cast_if_present<TypeAttr>(rhsAttr)) {
2670 if (
auto lhsTypeAttr = llvm::dyn_cast_if_present<TypeAttr>(lhsAttr)) {
2671 collectRhsTypeVarCandidates(
2672 lhsTypeAttr.getValue(), rhsTypeAttr.getValue(), targetRef, candidates
2678 auto lhsArray = llvm::dyn_cast_if_present<ArrayAttr>(lhsAttr);
2679 auto rhsArray = llvm::dyn_cast_if_present<ArrayAttr>(rhsAttr);
2680 if (!lhsArray || !rhsArray || lhsArray.size() != rhsArray.size()) {
2683 collectRhsTypeVarCandidates(lhsArray.getValue(), rhsArray.getValue(), targetRef, candidates);
2691static void collectRhsTypeVarCandidates(
2692 Type lhsTy, Type rhsTy, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2694 if (
auto rhsTvar = llvm::dyn_cast<TypeVarType>(rhsTy);
2695 rhsTvar && rhsTvar.getNameRef() == targetRef) {
2696 appendUniqueType(candidates, lhsTy);
2700 if (
auto lhsArray = llvm::dyn_cast<ArrayType>(lhsTy)) {
2701 if (
auto rhsArray = llvm::dyn_cast<ArrayType>(rhsTy)) {
2702 collectRhsTypeVarCandidates(
2703 lhsArray.getElementType(), rhsArray.getElementType(), targetRef, candidates
2705 collectRhsTypeVarCandidates(
2706 lhsArray.getDimensionSizes(), rhsArray.getDimensionSizes(), targetRef, candidates
2712 if (
auto lhsStruct = llvm::dyn_cast<StructType>(lhsTy)) {
2713 if (
auto rhsStruct = llvm::dyn_cast<StructType>(rhsTy)) {
2714 collectRhsTypeVarCandidates(
2715 lhsStruct.getParams(), rhsStruct.getParams(), targetRef, candidates
2721 if (
auto lhsPod = llvm::dyn_cast<PodType>(lhsTy)) {
2722 if (
auto rhsPod = llvm::dyn_cast<PodType>(rhsTy);
2723 rhsPod && lhsPod.getRecords().size() == rhsPod.getRecords().size()) {
2724 for (
auto [lhsRecord, rhsRecord] :
2725 llvm::zip_equal(lhsPod.getRecords(), rhsPod.getRecords())) {
2726 collectRhsTypeVarCandidates(
2727 lhsRecord.getType(), rhsRecord.getType(), targetRef, candidates
2734 if (
auto lhsFunc = llvm::dyn_cast<FunctionType>(lhsTy)) {
2735 if (
auto rhsFunc = llvm::dyn_cast<FunctionType>(rhsTy)) {
2736 for (
auto [lhsInput, rhsInput] : llvm::zip_equal(lhsFunc.getInputs(), rhsFunc.getInputs())) {
2737 collectRhsTypeVarCandidates(lhsInput, rhsInput, targetRef, candidates);
2739 for (
auto [lhsResult, rhsResult] :
2740 llvm::zip_equal(lhsFunc.getResults(), rhsFunc.getResults())) {
2741 collectRhsTypeVarCandidates(lhsResult, rhsResult, targetRef, candidates);
2748static SmallVector<Type>
2749getConflictingRhsTypeVarCandidates(FunctionType lhs, FunctionType rhs, SymbolRefAttr targetRef) {
2750 SmallVector<Type> candidates;
2751 if (lhs.getNumInputs() != rhs.getNumInputs() || lhs.getNumResults() != rhs.getNumResults()) {
2754 for (
auto [lhsInput, rhsInput] : llvm::zip_equal(lhs.getInputs(), rhs.getInputs())) {
2755 collectRhsTypeVarCandidates(lhsInput, rhsInput, targetRef, candidates);
2757 for (
auto [lhsResult, rhsResult] : llvm::zip_equal(lhs.getResults(), rhs.getResults())) {
2758 collectRhsTypeVarCandidates(lhsResult, rhsResult, targetRef, candidates);
2764template <
typename CallableOp,
typename TargetOp>
2766emitConflictingInferredTypes(CallableOp callableOp, TargetOp targetOp, StringAttr paramName) {
2767 InFlightDiagnostic diag = callableOp.emitError()
2768 <<
"conflicting inferred types for @" << paramName.getValue();
2769 SmallVector<Type> candidates = getConflictingRhsTypeVarCandidates(
2770 callableOp.getTypeSignature(), targetOp.getFunctionType(), FlatSymbolRefAttr::get(paramName)
2772 if (candidates.size() >= 2) {
2773 diag <<
": " << candidates.front();
2774 for (Type candidate : llvm::drop_begin(candidates)) {
2775 diag <<
" vs " << candidate;
2782template <
typename CallableOp,
typename TargetOp>
2783static FailureOr<Attribute> getInferredRhsTemplateArg(
2784 CallableOp callableOp, TargetOp targetOp,
const UnificationMap &unifyResult,
2785 StringAttr paramName, StringRef argKind
2787 auto inferredIt = unifyResult.find({FlatSymbolRefAttr::get(paramName), Side::RHS});
2788 if (inferredIt == unifyResult.end()) {
2789 return callableOp.emitError() <<
"could not infer " << argKind
2790 <<
" template argument for parameter @" << paramName.getValue()
2791 <<
" from callee signature";
2793 if (!inferredIt->second) {
2794 return emitConflictingInferredTypes(callableOp, targetOp, paramName);
2796 return inferredIt->second;
2800template <
typename CallableOp,
typename TargetOp>
2801static FailureOr<ArrayAttr> getCallSignatureTemplateParams(
2802 CallableOp callableOp,
const TemplateInferenceInfo &info, TargetOp targetOp
2804 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetOp.getFunctionType());
2805 if (failed(unifyResult)) {
2806 return callableOp.emitError()
2807 <<
"could not infer omitted template arguments from callee signature";
2810 SmallVector<Attribute> params;
2811 params.reserve(info.oldParamOrder.size());
2812 for (StringAttr paramName : info.oldParamOrder) {
2813 auto replacementIt = info.replacements.find(paramName);
2814 if (replacementIt != info.replacements.end()) {
2815 params.push_back(TypeAttr::get(replacementIt->second.type));
2818 FailureOr<Attribute> inferredAttr =
2819 getInferredRhsTemplateArg(callableOp, targetOp, *unifyResult, paramName,
"omitted");
2820 if (failed(inferredAttr)) {
2823 params.push_back(*inferredAttr);
2825 return ArrayAttr::get(callableOp.getContext(), params);
2830template <
typename TargetOp>
2831static bool hasResidualFunctionTvarWildcard(
2832 ArrayAttr callParams,
const TemplateInferenceInfo &info, TargetOp targetOp
2834 if (!callParams || callParams.size() != info.oldParamOrder.size()) {
2837 for (
const auto &entry : info.typeVarParams) {
2838 StringAttr paramName = entry.first;
2839 if (info.replacements.contains(paramName)) {
2842 if (!targetMentionsParam(targetOp, paramName)) {
2845 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2846 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2847 if (isWildcardTemplateArg(callParams[*index])) {
2856template <
typename CallableOp,
typename TargetOp>
2857static FailureOr<ArrayAttr> materializeResidualFunctionTvarWildcards(
2858 CallableOp callableOp, ArrayAttr callParams,
const TemplateInferenceInfo &info,
2861 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetOp.getFunctionType());
2862 if (failed(unifyResult)) {
2863 return callableOp.emitError()
2864 <<
"could not infer wildcard template arguments from callee signature";
2867 SmallVector<Attribute> params(callParams.begin(), callParams.end());
2868 for (
const auto &entry : info.typeVarParams) {
2869 StringAttr paramName = entry.first;
2870 if (info.replacements.contains(paramName)) {
2873 if (!targetMentionsParam(targetOp, paramName)) {
2876 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2877 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2878 if (!isWildcardTemplateArg(params[*index])) {
2882 auto inferredIt = unifyResult->find({FlatSymbolRefAttr::get(paramName), Side::RHS});
2883 if (inferredIt == unifyResult->end()) {
2884 auto proofIt = info.functionReplacements.find(targetOp.getOperation());
2885 if (proofIt == info.functionReplacements.end()) {
2888 auto replacementIt = proofIt->second.find(paramName);
2889 if (replacementIt == proofIt->second.end()) {
2892 params[*index] = TypeAttr::get(replacementIt->second.type);
2895 if (!inferredIt->second) {
2896 return emitConflictingInferredTypes(callableOp, targetOp, paramName);
2898 params[*index] = inferredIt->second;
2900 return ArrayAttr::get(callableOp.getContext(), params);
2908template <
typename TargetOp>
2909static bool hasResidualFunctionTvar(
const TemplateInferenceInfo &info, TargetOp targetOp) {
2910 return llvm::any_of(info.typeVarParams, [&](
const auto &entry) {
2911 return !info.replacements.contains(entry.first) && targetMentionsParam(targetOp, entry.first);
2916struct CallableSpecializationInputs {
2918 bool explicitParams =
false;
2919 bool paramsChanged =
false;
2920 DenseMap<StringAttr, Type> replacements;
2924template <
typename CallableOp,
typename TargetOp>
2925static LogicalResult prepareCallableSpecialization(
2926 CallableOp callableOp,
const TemplateInferenceInfo &info, TargetOp targetOp,
2927 CallableSpecializationInputs &inputs,
bool &shouldSpecialize
2929 shouldSpecialize =
false;
2931 inputs.explicitParams =
false;
2932 inputs.paramsChanged =
false;
2933 inputs.replacements.clear();
2934 inputs.params = callableOp.getTemplateParamsAttr();
2937 FailureOr<ArrayAttr> inferredParams =
2938 getCallSignatureTemplateParams(callableOp, info, targetOp);
2939 if (failed(inferredParams)) {
2942 inputs.params = *inferredParams;
2943 inputs.paramsChanged =
true;
2945 inputs.params = expandCurrentTemplateParamsToOriginalOrder(inputs.params, info);
2946 if (hasResidualFunctionTvarWildcard(inputs.params, info, targetOp)) {
2947 FailureOr<ArrayAttr> materializedParams =
2948 materializeResidualFunctionTvarWildcards(callableOp, inputs.params, info, targetOp);
2949 if (failed(materializedParams)) {
2952 inputs.params = *materializedParams;
2953 inputs.paramsChanged =
true;
2957 inputs.replacements = getConcreteCallSiteReplacements(inputs.params, info, targetOp);
2958 shouldSpecialize = !inputs.replacements.empty();
2968static std::string buildTemplateLocalFunctionCloneCacheKey(
2969 StringRef functionName, ArrayRef<StringAttr> oldParamOrder,
2970 const DenseMap<StringAttr, Type> &replacements
2973 llvm::raw_string_ostream os(key);
2974 os << functionName.size() <<
':' << functionName;
2975 for (StringAttr paramName : oldParamOrder) {
2977 os << paramName.getValue().size() <<
':' << paramName.getValue() <<
'=';
2978 auto replacementIt = replacements.find(paramName);
2979 if (replacementIt == replacements.end()) {
2984 std::string typeText;
2985 llvm::raw_string_ostream typeOs(typeText);
2986 replacementIt->second.print(typeOs);
2987 os << typeText.size() <<
':' << typeText;
2993static SymbolRefAttr getSpecializedFunctionCloneCallee(
2994 SymbolRefAttr originalCallee, StringAttr templateName, StringAttr cloneName
2996 SmallVector<FlatSymbolRefAttr> pieces =
getPieces(originalCallee);
2997 assert(pieces.size() >= 2 &&
"callee must include at least template and function names");
3000 pieces.push_back(FlatSymbolRefAttr::get(templateName));
3001 pieces.push_back(FlatSymbolRefAttr::get(cloneName));
3006template <
typename CallableOp,
typename ConfigureCloneFn>
3007static FailureOr<SymbolRefAttr> getOrCreateSpecializedCallableClone(
3008 TemplateOp templateOp, CallableOp callable, SymbolRefAttr originalCallee,
3009 const TemplateInferenceInfo &info,
const DenseMap<StringAttr, Type> &replacements,
3010 SymbolTableCollection &tables, llvm::StringMap<SymbolRefAttr> &cloneCallees,
3011 llvm::StringMap<StringAttr> &templateClones, InstantiationLayout &layout, ArrayAttr callParams,
3012 ConfigureCloneFn configureClone
3014 DenseMap<Attribute, Attribute> paramNameToConcrete = buildParamNameToConcrete(replacements);
3015 FailureOr<TemplateOp> newTemplate = getOrCreateSpecializedTemplateClone(
3016 templateOp, info.oldParamOrder, paramNameToConcrete, callParams, tables, templateClones,
3019 if (failed(newTemplate)) {
3023 std::string cacheKey = buildTemplateLocalFunctionCloneCacheKey(
3024 callable.getSymName(), info.oldParamOrder, replacements
3026 auto cachedCallee = cloneCallees.find(cacheKey);
3027 if (cachedCallee != cloneCallees.end()) {
3028 return cachedCallee->second;
3031 SymbolTable &templateSymbols = tables.getSymbolTable(*newTemplate);
3033 auto clone = llvm::cast<CallableOp>(callable.getOperation()->clone());
3034 configureClone(clone);
3035 templateSymbols.insert(clone);
3037 TypeVarReplacementConverter converter(
3038 templateOp.getContext(), info.templatePath, info.oldParamOrder, replacements,
3041 if (failed(convertTemplateExprTypesIn(*newTemplate, converter))) {
3045 if (failed(convertOperationTypesIn(clone.getOperation(), converter))) {
3049 removeIdentityCasts(clone.getOperation());
3050 SymbolRefAttr cloneCallee = getSpecializedFunctionCloneCallee(
3051 originalCallee, newTemplate->getSymNameAttr(), clone.
getSymNameAttr()
3053 cloneCallees.try_emplace(cacheKey, cloneCallee);
3058static FailureOr<SymbolRefAttr> getOrCreateSpecializedFunctionClone(
3059 TemplateOp templateOp, FuncDefOp func, SymbolRefAttr originalCallee,
3060 const TemplateInferenceInfo &info,
const DenseMap<StringAttr, Type> &replacements,
3061 SymbolTableCollection &tables, llvm::StringMap<SymbolRefAttr> &cloneCallees,
3062 llvm::StringMap<StringAttr> &templateClones, InstantiationLayout &layout, ArrayAttr callParams
3064 return getOrCreateSpecializedCallableClone(
3065 templateOp, func, originalCallee, info, replacements, tables, cloneCallees, templateClones,
3066 layout, callParams, [](FuncDefOp) {}
3071static FailureOr<SymbolRefAttr> getOrCreateSpecializedContractClone(
3072 TemplateOp templateOp, verif::ContractOp contract, SymbolRefAttr originalCallee,
3073 SymbolRefAttr specializedTarget,
const TemplateInferenceInfo &info,
3074 const DenseMap<StringAttr, Type> &replacements, SymbolTableCollection &tables,
3075 llvm::StringMap<SymbolRefAttr> &cloneCallees, llvm::StringMap<StringAttr> &templateClones,
3076 InstantiationLayout &layout, ArrayAttr callParams
3078 return getOrCreateSpecializedCallableClone(
3079 templateOp, contract, originalCallee, info, replacements, tables, cloneCallees,
3080 templateClones, layout, callParams,
3081 [specializedTarget](verif::ContractOp clone) { clone.
setTargetAttr(specializedTarget); }
3090static LogicalResult removeResolvedParams(TemplateInferenceInfo &info) {
3091 if (info.replacements.empty()) {
3095 DenseMap<StringAttr, Type> replacements;
3096 for (
const auto &entry : info.replacements) {
3097 replacements.try_emplace(entry.first, entry.second.type);
3099 DenseMap<Attribute, Attribute> paramNameToConcrete = buildParamNameToConcrete(replacements);
3100 FailureOr<InstantiationLayout> layout =
3102 if (failed(layout)) {
3107 for (
auto paramOp : llvm::make_early_inc_range(info.templateOp.
getConstOps<TemplateParamOp>())) {
3108 auto name = paramOp.getSymNameAttr();
3109 if (info.replacements.contains(name)) {
3114 info.templateOp, layout->remainingNames.empty() ? ArrayAttr() : layout->namePattern
3120template <
typename CallableOp>
3122validateWildcardCallableSignature(CallableOp callableOp, FunctionType targetTy) {
3123 if (succeeded(callableOp.unifyTypeSignature(targetTy))) {
3126 return callableOp.emitError() <<
"call signature " << callableOp.getTypeSignature()
3127 <<
" does not match inferred callee signature " << targetTy;
3131static void updateCallableResultTypesIfNeeded(
3132 CallOp callOp,
const TypeVarReplacementConverter &converter,
bool &modified
3134 for (Value result : callOp.getResults()) {
3135 Type newTy = converter.convertType(result.getType());
3136 if (newTy != result.getType()) {
3137 result.setType(newTy);
3145updateCallableResultTypesIfNeeded(verif::IncludeOp,
const TypeVarReplacementConverter &,
bool &) {}
3148template <
typename CallableOp>
3149static FailureOr<bool> updateCallableTemplateParamsFor(
3150 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters,
3151 SymbolTableCollection &tables
3153 bool modified =
false;
3154 bool failedConversion =
false;
3155 module.walk([&](CallableOp callableOp) {
3156 if (failedConversion) {
3159 auto target = callableOp.getCalleeTarget(tables);
3160 if (failed(target)) {
3163 auto targetOp = target->get();
3165 if (!parentTemplate) {
3168 const TypeVarReplacementConverter *converter = converters.lookup(parentTemplate.getOperation());
3174 bool resolveTemplateSymbolArgs =
3175 callableTemplate && callableTemplate.getOperation() == parentTemplate.getOperation();
3176 ArrayAttr oldParams = callableOp.getTemplateParamsAttr();
3177 FailureOr<ArrayAttr> newParams = converter->convertTemplateParams(
3178 oldParams, callableOp, resolveTemplateSymbolArgs,
3181 if (failed(newParams)) {
3182 failedConversion =
true;
3185 if (converter->hasWildcardForRemovedParam(oldParams)) {
3186 auto inferredTargetTy =
3187 llvm::cast<FunctionType>(converter->convertType(targetOp.getFunctionType()));
3188 if (failed(validateWildcardCallableSignature(callableOp, inferredTargetTy))) {
3189 failedConversion =
true;
3193 if (oldParams != *newParams) {
3194 callableOp.setTemplateParamsAttr(*newParams);
3198 updateCallableResultTypesIfNeeded(callableOp, *converter, modified);
3200 if (failedConversion) {
3213static FailureOr<bool> updateCallableTemplateParams(
3214 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3216 SymbolTableCollection tables;
3217 FailureOr<bool> callsModified =
3218 updateCallableTemplateParamsFor<CallOp>(module, converters, tables);
3219 if (failed(callsModified)) {
3222 FailureOr<bool> includesModified =
3223 updateCallableTemplateParamsFor<verif::IncludeOp>(module, converters, tables);
3224 if (failed(includesModified)) {
3227 return *callsModified || *includesModified;
3236class ReferencedStructTemplateParamConverter {
3242 SymbolTableCollection &tables_;
3244 DenseMap<Operation *, const TypeVarReplacementConverter *> &converters_;
3246 Operation *diagnosticOp_ =
nullptr;
3248 bool hasFailure =
false;
3251 ReferencedStructTemplateParamConverter(
3252 MLIRContext *ctx, ModuleOp module, SymbolTableCollection &tables,
3253 DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3255 : ctx_(ctx), module_(module), tables_(tables), converters_(converters) {}
3258 void startOperation(Operation *op) {
3264 bool hadFailure()
const {
return hasFailure; }
3267 Type convertType(Type ty) {
3268 if (!ty || hasFailure) {
3271 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
3272 return convertArrayElementType(arrTy, [
this](Type elemTy) {
return convertType(elemTy); });
3274 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
3275 return convertStructType(structTy);
3277 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
3278 return convertPodType(podTy, ctx_, *
this);
3280 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
3281 return convertFunctionType(funcTy, *
this);
3287 Attribute convertAttr(Attribute attr) {
3291 return convertTypeOrArrayAttr(attr, ctx_, [
this](Type ty) {
3292 return convertType(ty);
3293 }, [
this](Attribute nested) {
return convertAttr(nested); });
3298 StructType convertStructType(StructType structTy) {
3299 ArrayAttr params = structTy.
getParams();
3304 SmallVector<Attribute> newParams;
3305 bool changed =
false;
3306 for (Attribute attr : params.getValue()) {
3307 Attribute newAttr = convertAttr(attr);
3308 newParams.push_back(newAttr);
3309 changed |= newAttr != attr;
3314 StructType convertedTy =
3318 tables_, convertedTy.
getNameRef(), module_,
false
3320 if (failed(lookup)) {
3324 if (!parentTemplate) {
3327 const TypeVarReplacementConverter *converter =
3328 converters_.lookup(parentTemplate.getOperation());
3334 bool resolveTemplateSymbolArgs =
3335 useTemplate && useTemplate.getOperation() == parentTemplate.getOperation();
3336 FailureOr<ArrayAttr> trimmedParams = converter->convertTemplateParams(
3337 convertedTy.
getParams(), diagnosticOp_, resolveTemplateSymbolArgs,
3340 if (failed(trimmedParams)) {
3344 if (convertedTy.
getParams() == *trimmedParams) {
3352static FailureOr<bool> updateStructTemplateParams(
3353 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3355 SymbolTableCollection tables;
3356 ReferencedStructTemplateParamConverter converter(module.getContext(), module, tables, converters);
3357 return convertOperationTypesInAndTrack(module.getOperation(), converter);
3361static LogicalResult instantiateConcreteStructUses(ModuleOp module) {
3362 SymbolTableCollection tables;
3363 ConcreteStructInstantiationConverter converter(module.getContext(), module, tables);
3364 return convertOperationTypesIn(module.getOperation(), converter);
3369getContractTargetTemplate(verif::ContractOp contract, SymbolTableCollection &tables) {
3370 if (FailureOr<SymbolLookupResult<FuncDefOp>> funcTarget = contract.
getFuncTarget(tables);
3371 succeeded(funcTarget)) {
3374 if (FailureOr<SymbolLookupResult<StructDefOp>> structTarget = contract.
getStructTarget(tables);
3375 succeeded(structTarget)) {
3387static LogicalResult updateExternalContractTemplateParams(
3388 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3390 bool failedConversion =
false;
3391 SymbolTableCollection tables;
3392 module.walk([&](verif::ContractOp contract) {
3393 if (failedConversion) {
3396 TemplateOp targetTemplate = getContractTargetTemplate(contract, tables);
3397 if (!targetTemplate) {
3403 const TypeVarReplacementConverter *converter = converters.lookup(targetTemplate.getOperation());
3408 auto validationResult = contract.walk([converter](Operation *op) -> WalkResult {
3409 return converter->validateOperation(op);
3411 if (validationResult.wasInterrupted() ||
3412 failed(convertOperationTypesIn(contract.getOperation(), *converter))) {
3413 failedConversion =
true;
3416 removeIdentityCasts(contract.getOperation());
3418 return failure(failedConversion);
3429static LogicalResult specializeFunctionLocalCallables(
3430 ModuleOp module, DenseMap<Operation *, const TemplateInferenceInfo *> &infoByTemplate,
3431 SpecializedCallableCloneCache &functionCloneCache,
3432 SpecializedCallableCloneCache &contractCloneCache,
3433 SpecializedTemplateCloneCache &templateCloneCache
3435 bool failedClone =
false;
3436 SymbolTableCollection tables;
3437 module.walk([&](CallOp callOp) {
3441 FailureOr<SymbolLookupResult<FuncDefOp>> target = callOp.
getCalleeTarget(tables);
3442 if (failed(target)) {
3445 FuncDefOp targetFunc = target->get();
3446 auto parentTemplate = llvm::dyn_cast_or_null<TemplateOp>(targetFunc->getParentOp());
3447 if (!parentTemplate) {
3450 const TemplateInferenceInfo *info = infoByTemplate.lookup(parentTemplate.getOperation());
3454 if (!hasResidualFunctionTvar(*info, targetFunc)) {
3458 CallableSpecializationInputs inputs;
3459 bool shouldSpecialize =
false;
3461 prepareCallableSpecialization(callOp, *info, targetFunc, inputs, shouldSpecialize)
3466 if (!shouldSpecialize) {
3469 DenseMap<StringAttr, Type> inferredReplacements =
3470 getFunctionProofReplacements(*info, targetFunc);
3471 if (failed(diagnoseCallParamsMismatch(
3472 callOp.getOperation(), inputs.params, info->oldParamOrder, inferredReplacements,
3473 &info->replacements, inputs.explicitParams
3479 InstantiationLayout layout;
3480 FailureOr<SymbolRefAttr> cloneCallee = getOrCreateSpecializedFunctionClone(
3481 parentTemplate, targetFunc, callOp.
getCalleeAttr(), *info, inputs.replacements, tables,
3482 functionCloneCache[parentTemplate.getOperation()],
3483 templateCloneCache[parentTemplate.getOperation()], layout, inputs.params
3485 if (failed(cloneCallee)) {
3493 module.walk([&](verif::IncludeOp includeOp) {
3497 FailureOr<SymbolLookupResult<verif::ContractOp>> target = includeOp.
getCalleeTarget(tables);
3498 if (failed(target)) {
3501 verif::ContractOp targetContract = target->get();
3502 auto parentTemplate = llvm::dyn_cast_or_null<TemplateOp>(targetContract->getParentOp());
3503 if (!parentTemplate) {
3506 const TemplateInferenceInfo *info = infoByTemplate.lookup(parentTemplate.getOperation());
3510 if (!hasResidualFunctionTvar(*info, targetContract)) {
3514 FailureOr<SymbolLookupResult<FuncDefOp>> targetFuncResult =
3516 if (failed(targetFuncResult)) {
3519 FuncDefOp targetFunc = targetFuncResult->get();
3524 CallableSpecializationInputs inputs;
3525 bool shouldSpecialize =
false;
3526 if (failed(prepareCallableSpecialization(
3527 includeOp, *info, targetContract, inputs, shouldSpecialize
3532 if (!shouldSpecialize) {
3535 DenseMap<StringAttr, Type> inferredReplacements =
3536 getFunctionProofReplacements(*info, targetFunc);
3537 if (failed(diagnoseCallParamsMismatch(
3538 includeOp.getOperation(), inputs.params, info->oldParamOrder, inferredReplacements,
3539 &info->replacements, inputs.explicitParams
3545 InstantiationLayout targetLayout;
3546 FailureOr<SymbolRefAttr> specializedTarget = getOrCreateSpecializedFunctionClone(
3547 parentTemplate, targetFunc, targetContract.
getTargetAttr(), *info, inputs.replacements,
3548 tables, functionCloneCache[parentTemplate.getOperation()],
3549 templateCloneCache[parentTemplate.getOperation()], targetLayout, inputs.params
3551 if (failed(specializedTarget)) {
3555 InstantiationLayout contractLayout;
3556 FailureOr<SymbolRefAttr> cloneCallee = getOrCreateSpecializedContractClone(
3557 parentTemplate, targetContract, includeOp.
getCalleeAttr(), *specializedTarget, *info,
3558 inputs.replacements, tables, contractCloneCache[parentTemplate.getOperation()],
3559 templateCloneCache[parentTemplate.getOperation()], contractLayout, inputs.params
3561 if (failed(cloneCallee)) {
3569 return failure(failedClone);
3573static bool sameReplacementTypes(
3574 const DenseMap<StringAttr, InferredType> &lhs,
const DenseMap<StringAttr, InferredType> &rhs
3576 if (lhs.size() != rhs.size()) {
3579 for (
const auto &entry : lhs) {
3580 auto rhsIt = rhs.find(entry.first);
3581 if (rhsIt == rhs.end() || rhsIt->second.type != entry.second.type) {
3594static LogicalResult collectContractTargetFunctionInferences(
3595 TemplateInferenceInfo &info, verif::ContractOp contract, ModuleOp module,
3596 DenseMap<Operation *, TemplateInferenceInfo *> *infoByTemplate, SymbolTableCollection &tables,
3599 FailureOr<SymbolLookupResult<FuncDefOp>> target = contract.
getFuncTarget(tables);
3600 if (failed(target)) {
3603 FuncDefOp targetFunc = target->get();
3608 DenseMap<StringAttr, InferredType> funcReplacements;
3609 auto funcIt = info.functionReplacements.find(targetFunc.getOperation());
3610 if (funcIt != info.functionReplacements.end()) {
3611 funcReplacements = funcIt->second;
3613 DenseMap<StringAttr, InferredType> oldFuncReplacements = funcReplacements;
3615 TypeVarInferenceCollector collector(info, funcReplacements);
3616 if (failed(collector.collect(contract.getOperation()))) {
3619 if (infoByTemplate && failed(collector.collectStructTemplateParamInferences(
3620 contract.getOperation(), module, *infoByTemplate, tables
3625 if (!sameReplacementTypes(oldFuncReplacements, funcReplacements)) {
3628 if (funcReplacements.empty()) {
3629 info.functionReplacements.erase(targetFunc.getOperation());
3631 info.functionReplacements[targetFunc.getOperation()] = std::move(funcReplacements);
3642static LogicalResult collectContractTargetStructInferences(
3643 TemplateInferenceInfo &info, verif::ContractOp contract, ModuleOp module,
3644 DenseMap<Operation *, TemplateInferenceInfo *> *infoByTemplate, SymbolTableCollection &tables,
3647 FailureOr<SymbolLookupResult<StructDefOp>> target = contract.
getStructTarget(tables);
3648 if (failed(target)) {
3651 StructDefOp targetStruct = target->get();
3656 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements = info.templateScopeReplacements;
3658 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3660 if (contractTy.getNumInputs() > 0) {
3661 StructType targetSelfTy = targetStruct.
getType();
3662 if (
auto contractSelfTy = llvm::dyn_cast<StructType>(contractTy.getInput(0));
3663 contractSelfTy && contractSelfTy.getNameRef() == targetSelfTy.
getNameRef() &&
3664 failed(collector.collectTypeInferences(contractSelfTy, targetSelfTy, contract.getLoc()))) {
3668 if (failed(collector.collect(contract.getOperation()))) {
3671 if (infoByTemplate && failed(collector.collectStructTemplateParamInferences(
3672 contract.getOperation(), module, *infoByTemplate, tables
3677 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3692static LogicalResult recomputeTemplateWideReplacements(TemplateInferenceInfo &info) {
3693 DenseMap<StringAttr, unsigned> mentionCounts;
3694 DenseMap<StringAttr, unsigned> proofCounts;
3695 DenseMap<StringAttr, InferredType> commonReplacements;
3696 DenseSet<StringAttr> incompatibleReplacements;
3698 for (FuncDefOp func : walkCollect<FuncDefOp>(info.templateOp)) {
3699 for (
const auto &entry : info.typeVarParams) {
3700 if (funcMentionsParam(func, entry.first)) {
3701 ++mentionCounts[entry.first];
3705 auto funcIt = info.functionReplacements.find(func.getOperation());
3706 if (funcIt == info.functionReplacements.end()) {
3709 for (
const auto &entry : funcIt->second) {
3710 ++proofCounts[entry.first];
3711 auto commonIt = commonReplacements.find(entry.first);
3712 if (commonIt == commonReplacements.end()) {
3713 commonReplacements.try_emplace(entry.first, entry.second);
3714 }
else if (commonIt->second.type != entry.second.type) {
3715 incompatibleReplacements.insert(entry.first);
3720 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(info.templateOp)) {
3721 for (
const auto &entry : info.typeVarParams) {
3722 if (exprMentionsParam(expr, entry.first)) {
3723 ++mentionCounts[entry.first];
3728 info.replacements = info.templateScopeReplacements;
3729 for (
const auto &entry : info.templateScopeReplacements) {
3730 auto commonIt = commonReplacements.find(entry.first);
3731 if (commonIt != commonReplacements.end() && commonIt->second.type != entry.second.type) {
3732 InFlightDiagnostic diag = emitError(entry.second.loc)
3733 <<
"conflicting inferred type for template parameter @"
3734 << entry.first.getValue() <<
": " << commonIt->second.type <<
" vs "
3735 << entry.second.type;
3736 diag.attachNote(commonIt->second.loc) <<
"previous function-local inference here";
3741 for (
const auto &entry : commonReplacements) {
3742 StringAttr paramName = entry.first;
3743 if (info.replacements.contains(paramName)) {
3746 if (!hasUncoveredNonFunctionMention(
3747 info.templateOp, paramName, entry.second.type, info.functionReplacements
3749 !incompatibleReplacements.contains(paramName) &&
3750 proofCounts.lookup(paramName) == mentionCounts.lookup(paramName)) {
3751 info.replacements.try_emplace(paramName, entry.second);
3759static LogicalResult inferStructTemplateParamUses(
3760 ModuleOp module, MutableArrayRef<TemplateInferenceInfo> templateInfos,
3761 DenseMap<Operation *, TemplateInferenceInfo *> &infoByTemplate
3763 bool changed =
false;
3766 SymbolTableCollection tables;
3767 for (TemplateInferenceInfo &info : templateInfos) {
3768 for (FuncDefOp func : walkCollect<FuncDefOp>(info.templateOp)) {
3769 DenseMap<StringAttr, InferredType> funcReplacements;
3770 auto funcIt = info.functionReplacements.find(func.getOperation());
3771 if (funcIt != info.functionReplacements.end()) {
3772 funcReplacements = funcIt->second;
3774 DenseMap<StringAttr, InferredType> oldFuncReplacements = funcReplacements;
3776 TypeVarInferenceCollector collector(info, funcReplacements);
3777 if (failed(collector.collect(func.getOperation())) ||
3778 failed(collector.collectStructTemplateParamInferences(
3779 func.getOperation(), module, infoByTemplate, tables
3784 if (!sameReplacementTypes(oldFuncReplacements, funcReplacements)) {
3787 if (funcReplacements.empty()) {
3788 info.functionReplacements.erase(func.getOperation());
3790 info.functionReplacements[func.getOperation()] = std::move(funcReplacements);
3794 for (verif::ContractOp contract : walkCollect<verif::ContractOp>(info.templateOp)) {
3795 if (failed(collectContractTargetFunctionInferences(
3796 info, contract, module, &infoByTemplate, tables, changed
3798 failed(collectContractTargetStructInferences(
3799 info, contract, module, &infoByTemplate, tables, changed
3805 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(info.templateOp)) {
3806 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements =
3807 info.templateScopeReplacements;
3809 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3810 if (failed(collector.collect(expr.getOperation())) ||
3811 failed(collector.collectStructTemplateParamInferences(
3812 expr.getOperation(), module, infoByTemplate, tables
3817 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3822 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements =
3823 info.templateScopeReplacements;
3824 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3825 auto nonFunctionResult = info.templateOp.walk([&](Operation *op) -> WalkResult {
3826 if (llvm::isa<FuncDefOp, TemplateExprOp, verif::ContractOp>(op) ||
3827 op->getParentOfType<FuncDefOp, TemplateExprOp, verif::ContractOp>()) {
3828 return WalkResult::advance();
3830 return collector.collectOperationStructTemplateParamInferences(
3831 op, module, infoByTemplate, tables
3834 if (nonFunctionResult.wasInterrupted()) {
3837 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3841 DenseMap<StringAttr, InferredType> oldReplacements = info.replacements;
3842 if (failed(recomputeTemplateWideReplacements(info))) {
3845 if (!sameReplacementTypes(oldReplacements, info.replacements)) {
3855static LogicalResult collectExternalContractTargetInferences(
3856 ModuleOp module, MutableArrayRef<TemplateInferenceInfo> templateInfos,
3857 DenseMap<Operation *, TemplateInferenceInfo *> &infoByTemplate
3859 bool changed =
false;
3862 bool failedCollection =
false;
3863 SymbolTableCollection tables;
3864 module.walk([&](verif::ContractOp contract) {
3865 TemplateOp targetTemplate = getContractTargetTemplate(contract, tables);
3866 if (!targetTemplate) {
3872 TemplateInferenceInfo *info = infoByTemplate.lookup(targetTemplate.getOperation());
3876 if (failed(collectContractTargetFunctionInferences(
3877 *info, contract, module, &infoByTemplate, tables, changed
3879 failed(collectContractTargetStructInferences(
3880 *info, contract, module, &infoByTemplate, tables, changed
3882 failedCollection =
true;
3885 if (failedCollection) {
3889 for (TemplateInferenceInfo &info : templateInfos) {
3890 DenseMap<StringAttr, InferredType> oldReplacements = info.replacements;
3891 if (failed(recomputeTemplateWideReplacements(info))) {
3894 if (!sameReplacementTypes(oldReplacements, info.replacements)) {
3909static FailureOr<TemplateInferenceInfo> buildInfo(TemplateOp templateOp) {
3910 TemplateInferenceInfo info;
3911 info.templateOp = templateOp;
3912 FailureOr<SymbolRefAttr> templatePath =
3913 getPathFromRoot(llvm::cast<SymbolOpInterface>(templateOp.getOperation()));
3914 if (failed(templatePath)) {
3917 info.templatePath = getStringPieces(*templatePath);
3918 for (TemplateParamOp paramOp : templateOp.
getConstOps<TemplateParamOp>()) {
3919 auto name = paramOp.getSymNameAttr();
3920 info.oldParamOrder.push_back(name);
3921 if (isTypeVarParam(paramOp)) {
3922 info.typeVarParams.try_emplace(name, paramOp);
3926 for (FuncDefOp func : walkCollect<FuncDefOp>(templateOp)) {
3927 DenseMap<StringAttr, InferredType> funcReplacements;
3928 if (failed(TypeVarInferenceCollector(info, funcReplacements).collect(func.getOperation()))) {
3931 if (!funcReplacements.empty()) {
3932 info.functionReplacements.try_emplace(func.getOperation(), funcReplacements);
3936 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(templateOp)) {
3937 if (failed(TypeVarInferenceCollector(info, info.templateScopeReplacements)
3938 .collect(expr.getOperation()))) {
3943 bool changed =
false;
3944 SymbolTableCollection tables;
3945 ModuleOp module = templateOp->getParentOfType<ModuleOp>();
3946 for (verif::ContractOp contract : walkCollect<verif::ContractOp>(templateOp)) {
3947 if (failed(collectContractTargetFunctionInferences(
3948 info, contract, module,
nullptr, tables, changed
3950 failed(collectContractTargetStructInferences(
3951 info, contract, module,
nullptr, tables, changed
3957 if (failed(recomputeTemplateWideReplacements(info))) {
3970class PassImpl :
public llzk::polymorphic::impl::TypeVarInferencePassBase<PassImpl> {
3972 using Base = TypeVarInferencePassBase<PassImpl>;
3976 void runOnOperation()
override {
3977 ModuleOp module = getOperation();
3982 std::vector<TemplateInferenceInfo> templateInfos;
3983 WalkResult collectResult =
module.walk([&templateInfos](TemplateOp templateOp) {
3984 if (templateOp.getConstOps<TemplateParamOp>().empty()) {
3985 return WalkResult::advance();
3987 FailureOr<TemplateInferenceInfo> info = buildInfo(templateOp);
3989 return WalkResult::interrupt();
3991 templateInfos.push_back(std::move(*info));
3992 return WalkResult::advance();
3994 if (collectResult.wasInterrupted()) {
3995 signalPassFailure();
3998 if (templateInfos.empty()) {
4002 DenseMap<Operation *, TemplateInferenceInfo *> mutableInfoByTemplate;
4003 for (TemplateInferenceInfo &info : templateInfos) {
4004 mutableInfoByTemplate.try_emplace(info.templateOp.getOperation(), &info);
4007 collectExternalContractTargetInferences(module, templateInfos, mutableInfoByTemplate)
4009 signalPassFailure();
4012 if (failed(inferStructTemplateParamUses(module, templateInfos, mutableInfoByTemplate))) {
4013 signalPassFailure();
4017 SmallVector<TemplateInferenceInfo *> rewrites;
4018 DenseMap<Operation *, const TemplateInferenceInfo *> infoByTemplate;
4019 for (TemplateInferenceInfo &info : templateInfos) {
4020 infoByTemplate.try_emplace(info.templateOp.getOperation(), &info);
4021 if (!info.replacements.empty() || !info.functionReplacements.empty()) {
4022 rewrites.push_back(&info);
4028 SmallVector<std::unique_ptr<TypeVarReplacementConverter>> converterStorage;
4029 DenseMap<Operation *, const TypeVarReplacementConverter *> convertersByTemplate;
4030 for (TemplateInferenceInfo *info : rewrites) {
4031 DenseMap<StringAttr, Type> replacements;
4032 for (
const auto &entry : info->replacements) {
4033 replacements.try_emplace(entry.first, entry.second.type);
4035 auto converter = std::make_unique<TypeVarReplacementConverter>(
4036 module.getContext(), info->templatePath, info->oldParamOrder, replacements
4038 convertersByTemplate.try_emplace(info->templateOp.getOperation(), converter.get());
4039 converterStorage.push_back(std::move(converter));
4044 SpecializedCallableCloneCache functionCloneCache;
4045 SpecializedCallableCloneCache contractCloneCache;
4046 SpecializedTemplateCloneCache templateCloneCache;
4047 if (failed(specializeFunctionLocalCallables(
4048 module, infoByTemplate, functionCloneCache, contractCloneCache, templateCloneCache
4050 signalPassFailure();
4057 if (failed(updateCallableTemplateParams(module, convertersByTemplate))) {
4058 signalPassFailure();
4062 for (TemplateInferenceInfo *info : rewrites) {
4063 const TypeVarReplacementConverter *converter =
4064 convertersByTemplate.lookup(info->templateOp.getOperation());
4065 assert(converter &&
"rewritten template must have a converter");
4066 auto validationResult = info->templateOp.walk([converter](Operation *op) -> WalkResult {
4067 return converter->validateOperation(op);
4069 if (validationResult.wasInterrupted()) {
4070 signalPassFailure();
4073 if (failed(convertOperationTypesIn(info->templateOp.getOperation(), *converter))) {
4074 signalPassFailure();
4077 removeIdentityCasts(info->templateOp.getOperation());
4080 if (failed(updateExternalContractTemplateParams(module, convertersByTemplate))) {
4081 signalPassFailure();
4087 if (failed(updateCallableTemplateParams(module, convertersByTemplate))) {
4088 signalPassFailure();
4093 if (failed(specializeFunctionLocalCallables(
4094 module, infoByTemplate, functionCloneCache, contractCloneCache, templateCloneCache
4096 signalPassFailure();
4099 if (failed(updateStructTemplateParams(module, convertersByTemplate))) {
4100 signalPassFailure();
4107 for (TemplateInferenceInfo *info : rewrites) {
4108 if (failed(removeResolvedParams(*info))) {
4109 signalPassFailure();
4114 if (failed(instantiateConcreteStructUses(module))) {
4115 signalPassFailure();
Common private implementation for poly dialect passes.
This file defines methods symbol lookup across LLZK operations and included files.
Helper for converting between linear and multi-dimensional indexing with checks to ensure indices are...
static ArrayIndexGen from(ArrayType)
Construct new ArrayIndexGen. Will assert if hasStaticShape() is false.
std::optional< llvm::SmallVector< mlir::Value > > delinearize(int64_t, mlir::Location, mlir::OpBuilder &) const
ArrayType cloneWith(std::optional<::llvm::ArrayRef< int64_t > > shape, ::mlir::Type elementType) const
Clone this type with the given shape and element type.
::mlir::Type getElementType() const
::llvm::ArrayRef<::mlir::Attribute > getDimensionSizes() const
static CreateArrayOp create(::mlir::OpBuilder &builder, ::mlir::Location location, ::llzk::array::ArrayType result, ::mlir::ValueRange elements={})
::mlir::TypedValue<::llzk::array::ArrayType > getResult()
::mlir::Operation::operand_range getElements()
static InsertArrayOp create(::mlir::OpBuilder &builder, ::mlir::Location location, ::mlir::Value arr_ref, ::mlir::ValueRange indices, ::mlir::Value rvalue)
StructType getType(::std::optional<::mlir::ArrayAttr > constParams={})
Gets the StructType representing this struct.
::mlir::SymbolRefAttr getFullyQualifiedName()
Return the full name for this struct from the root module, including any surrounding module scopes.
::mlir::StringAttr getSymNameAttr()
::mlir::SymbolRefAttr getNameRef() const
static StructType get(::mlir::SymbolRefAttr structName)
::mlir::FailureOr< SymbolLookupResult< StructDefOp > > getDefinition(::mlir::SymbolTableCollection &symbolTable, ::mlir::Operation *op, bool reportMissing=true) const
Gets the struct op that defines this struct.
::mlir::ArrayAttr getParams() const
::mlir::SymbolRefAttr getCalleeAttr()
::mlir::SymbolRefAttr getCallee()
void setTemplateParamsAttr(::mlir::ArrayAttr attr)
::mlir::Value getSelfValueFromConstrain()
Return the "self" value (i.e.
::llzk::component::StructType getSingleResultTypeOfWitnessGen()
Assuming the callee contains witness generation code, return the single StructType result.
void setCalleeAttr(::mlir::SymbolRefAttr attr)
::mlir::FailureOr<::llzk::SymbolLookupResult<::llzk::function::FuncDefOp > > getCalleeTarget(::mlir::SymbolTableCollection &tables)
Resolve and return the target FuncDefOp for this CallOp.
::mlir::FunctionType getFunctionType()
static PodType get(::mlir::MLIRContext *context, ::llvm::ArrayRef<::llzk::pod::RecordAttr > records)
::llvm::ArrayRef<::llzk::pod::RecordAttr > getRecords() const
::mlir::FlatSymbolRefAttr getConstNameAttr()
::mlir::Region & getBodyRegion()
OpT getConstNamed(::mlir::StringRef find)
Return the op of type OpT with the given name within the body region if it exists,...
::mlir::StringAttr getSymNameAttr()
void setSymName(::llvm::StringRef attrValue)
::llvm::StringRef getSymName()
inline ::llvm::iterator_range<::mlir::Region::op_iterator< OpT > > getConstOps()
Return ops of type OpT within the body region.
::std::optional<::mlir::Type > getTypeOpt()
::mlir::TypedValue<::mlir::Type > getInput()
::mlir::TypedValue<::mlir::Type > getResult()
::mlir::FailureOr< SymbolLookupResult< function::FuncDefOp > > getFuncTarget(::mlir::SymbolTableCollection &tables)
Return the FuncDefOp that this contract targets, or failure if it does not target a function or the f...
void setTargetAttr(::mlir::SymbolRefAttr attr)
::mlir::FunctionType getFunctionType()
::mlir::Region & getBody()
::mlir::FailureOr< SymbolLookupResult< component::StructDefOp > > getStructTarget(::mlir::SymbolTableCollection &tables)
Return the StructDefOp that this contract targets, or failure if it does not target a struct or the s...
::mlir::SymbolRefAttr getTargetAttr()
::mlir::SymbolRefAttr getCalleeAttr()
void setCalleeAttr(::mlir::SymbolRefAttr attr)
::mlir::FailureOr<::llzk::SymbolLookupResult<::llzk::verif::ContractOp > > getCalleeTarget(::mlir::SymbolTableCollection &tables)
Resolve and return the target Contract for this CallOp.
void setTemplateParamsAttr(::mlir::ArrayAttr attr)
Common interface for constant parameter-like symbol operations that can be defined within a TemplateO...
component::StructType getStructTypeWithParams(mlir::SymbolRefAttr nameRef, mlir::ArrayAttr params)
Build a struct type while representing an empty parameter list as absent.
FailureOr< InstantiationLayout > buildInstantiationLayout(TemplateOp parentTemplate, ArrayAttr callParams, const DenseMap< Attribute, Attribute > ¶mNameToConcrete)
array::ArrayType flattenInstantiatedArrayType(array::ArrayType inputTy, mlir::Type convertedElemTy)
Merge nested array dimensions produced by replacing an array element type.
void setInstantiationNamePattern(TemplateOp templateOp, ArrayAttr namePattern)
constexpr char FUNC_NAME_COMPUTE[]
Symbol name for the witness generation (and resp.
mlir::SymbolRefAttr getPrefixAsSymbolRefAttr(mlir::SymbolRefAttr symbol)
Return SymbolRefAttr like the one given but with the leaf/final element removed.
mlir::FailureOr< SymbolLookupResultUntyped > lookupTopLevelSymbol(mlir::SymbolTableCollection &tables, mlir::SymbolRefAttr symbol, mlir::Operation *origin, bool reportMissing=true)
constexpr char FUNC_NAME_CONSTRAIN[]
mlir::DenseMap< std::pair< mlir::SymbolRefAttr, Side >, mlir::Attribute > UnificationMap
Optional result from type unifications.
bool isNullOrEmpty(mlir::ArrayAttr a)
OpClass getParentOfType(mlir::Operation *op)
Return the closest surrounding parent/ancestor operation that is of type 'OpClass'.
constexpr char FUNC_NAME_PRODUCT[]
constexpr T checkedCast(U u) noexcept
bool isDynamic(IntegerAttr intAttr)
mlir::SymbolRefAttr asSymbolRefAttr(mlir::StringAttr root, mlir::SymbolRefAttr tail)
Build a SymbolRefAttr that prepends tail with root, i.e., root::tail.
bool isTypeVarFreeType(Type type)
bool typeParamsUnify(const ArrayRef< Attribute > &lhsParams, const ArrayRef< Attribute > &rhsParams, UnificationMap *unifications)
bool isConcreteStructParamAttr(mlir::Attribute attr, bool allowStructParams=true)
Return true if attr is a concrete argument for a parameterized struct type.
llvm::SmallVector< FlatSymbolRefAttr > getPieces(SymbolRefAttr ref)
FailureOr< SymbolRefAttr > getPathFromRoot(SymbolOpInterface to, ModuleOp *foundRoot)
Groups the information needed after concrete parameters have been chosen to decide how to name a new ...
mlir::ArrayAttr namePattern
The refined literal chunks; fully concrete generated templates clear this state.
std::string templateNameWithAttrs
mlir::ArrayAttr rewrittenCallParams
mlir::SmallVector< mlir::Attribute > remainingNames