Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Direct cast is possible between equivalent types #3935

Merged
merged 3 commits into from
Mar 22, 2023

Conversation

MichalKekely
Copy link
Contributor

The issue was that the following code ended with a CompilerBug:

bit_var0 = (bit<1>) (bool) (bool) bit_var1;

The problem is with the double cast to bool (more specifically casting bool into bool). The problem was that the source and destination types were two different objects of the same class:

[9144] Type_Boolean
[9142] Type_Boolean

Therefore the original check for canCastBetween did not match those as the same type (since the pointers are not equal):

bool TypeInference::canCastBetween(const IR::Type *dest, const IR::Type *src) const {
if (src->is<IR::Type_Action>()) return false;
if (src == dest) return true;

Which lead to a new cast being introduced (so essentially there were 3 casts to bool instead of 2), while one of the original ones was not added into the type map:
if (!canCastBetween(castType, sourceType)) {
// This cast is not legal directly, but let's try to see whether
// performing a substitution can help. This will allow the use
// of constants on the RHS.
const IR::Type *destType = castType;
while (destType->is<IR::Type_Newtype>())
destType = getTypeType(destType->to<IR::Type_Newtype>()->type);
auto tvs = unify(expression, destType, sourceType, "Cannot cast from '%1%' to '%2%'",
{sourceType, castType});
if (tvs == nullptr) return expression;
const IR::Expression *rhs = expression;
if (!tvs->isIdentity()) {
ConstantTypeSubstitution cts(tvs, refMap, typeMap, this);
rhs = cts.convert(expression->expr); // sets type
}
if (rhs != expression->expr) {
// if we are here we have performed a substitution on the rhs
expression = new IR::Cast(expression->srcInfo, expression->destType, rhs);

Copy link
Contributor

@davidbolvansky davidbolvansky left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any test?

frontends/p4/typeChecking/typeChecker.cpp Show resolved Hide resolved
@MichalKekely
Copy link
Contributor Author

any test?

Added testcase: 4743bf4

@mihaibudiu mihaibudiu merged commit 846f672 into main Mar 22, 2023
@mihaibudiu mihaibudiu deleted the mkekely/bool_bool_cast branch March 22, 2023 17:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants