P4C
The P4 Compiler
Loading...
Searching...
No Matches
constantTypeSubstitution.h
1/*
2 * SPDX-FileCopyrightText: 2013 Barefoot Networks, Inc.
3 * Copyright 2013-present Barefoot Networks, Inc.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef FRONTENDS_P4_TYPECHECKING_CONSTANTTYPESUBSTITUTION_H_
9#define FRONTENDS_P4_TYPECHECKING_CONSTANTTYPESUBSTITUTION_H_
10
11#include "frontends/common/resolveReferences/resolveReferences.h"
12#include "ir/visitor.h"
13#include "typeChecker.h"
14#include "typeSubstitution.h"
15
16namespace P4 {
17
18// Used to set the type of Constants after type inference
19class ConstantTypeSubstitution : public Transform, ResolutionContext {
21 TypeMap *typeMap;
23
24 public:
25 ConstantTypeSubstitution(TypeVariableSubstitution *subst, TypeMap *typeMap,
27 : subst(subst), typeMap(typeMap), tc(tc) {
28 CHECK_NULL(subst);
29 CHECK_NULL(typeMap);
30 CHECK_NULL(tc);
31 LOG3("ConstantTypeSubstitution " << subst);
32 }
33
34 const IR::Node *postorder(IR::Constant *cst) override {
35 auto cstType = typeMap->getType(getOriginal(), true);
36 if (!cstType || !cstType->is<IR::ITypeVar>()) return cst;
37 auto repl = cstType;
38 while (repl->is<IR::ITypeVar>()) {
39 auto next = subst->get(repl->to<IR::ITypeVar>());
40 BUG_CHECK(next != repl, "Cycle in substitutions: %1%", next);
41 if (!next) break;
42 repl = next;
43 }
44 if (repl != cstType) {
45 // We may replace a type variable with another one
46 LOG2("Inferred type " << repl << " for " << cst);
47 cst = new IR::Constant(cst->srcInfo, repl, cst->value, cst->base);
48 } else {
49 LOG2("No type inferred for " << cst << " repl is " << repl);
50 }
51 return cst;
52 }
53
54 const IR::Expression *convert(const IR::Expression *expr, const Visitor::Context *ctxt) {
55 auto result = expr->apply(*this, ctxt)->to<IR::Expression>();
56 if (result != expr && (::P4::errorCount() == 0)) tc->learn(result, this, ctxt);
57 return result;
58 }
60 const Visitor::Context *ctxt) {
61 auto result = vec->apply(*this, ctxt)->to<IR::Vector<IR::Expression>>();
62 if (result != vec) tc->learn(result, this, ctxt);
63 return result;
64 }
65 const IR::Vector<IR::Argument> *convert(const IR::Vector<IR::Argument> *vec,
66 const Visitor::Context *ctxt) {
67 auto result = vec->apply(*this, ctxt)->to<IR::Vector<IR::Argument>>();
68 if (result != vec) tc->learn(result, this, ctxt);
69 return result;
70 }
71};
72
73} // namespace P4
74
75#endif // FRONTENDS_P4_TYPECHECKING_CONSTANTTYPESUBSTITUTION_H_
Definition node.h:53
Definition ir/vector.h:59
Definition visitor.h:442
Definition typeChecker.h:80
Definition typeMap.h:32
Definition typeSubstitution.h:64
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:13
unsigned errorCount()
Definition lib/error.h:34
T * to() noexcept
Definition rtti.h:226