Skip to content

Commit

Permalink
Move IRUtils Literal get functions to the respective IR members. Add …
Browse files Browse the repository at this point in the history
…stringliteral get function. (#4623)

* Add a getStringLiteral utility function.

* Introduce ::get functions.

* Remove IRUtils getters and replace them with IR::get().

* Do not use emit for declarations.

* Use flat abseil map with util hasher. Add big_int hasher.

* Small edits to configuration.h
  • Loading branch information
fruffy authored May 6, 2024
1 parent c170f45 commit 1583086
Show file tree
Hide file tree
Showing 50 changed files with 365 additions and 335 deletions.
3 changes: 1 addition & 2 deletions backends/p4tools/common/compiler/configuration.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#define BACKENDS_P4TOOLS_COMMON_COMPILER_CONFIGURATION_H_

#include <climits>
#include <limits>

#include "ir/configuration.h"

Expand All @@ -12,7 +11,7 @@ namespace P4Tools {
/// integer.
class CompilerConfiguration : public DefaultP4CConfiguration {
public:
int maximumWidthSupported() const override { return INT_MAX; }
[[nodiscard]] int maximumWidthSupported() const override { return INT_MAX; }

/// @return the singleton instance.
static const CompilerConfiguration &get() {
Expand Down
2 changes: 1 addition & 1 deletion backends/p4tools/common/compiler/convert_hs_index.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const IR::Node *HSIndexToMember::postorder(IR::ArrayIndex *curArrayIndex) {
const IR::ArrayIndex *HSIndexToMember::produceStackIndex(const IR::Type *type,
const IR::Expression *expression,
size_t arrayIndex) {
return new IR::ArrayIndex(type, expression, IR::getConstant(IR::getBitType(32), arrayIndex));
return new IR::ArrayIndex(type, expression, IR::Constant::get(IR::getBitType(32), arrayIndex));
}

} // namespace P4Tools
2 changes: 1 addition & 1 deletion backends/p4tools/common/compiler/convert_struct_expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const IR::Node *ConvertStructExpr::postorder(IR::StructExpression *structExpr) {
}
if (structType->is<IR::Type_Header>()) {
return new IR::HeaderExpression(structExpr->srcInfo, structType, structExpr->type,
structExpr->components, IR::getBoolLiteral(true));
structExpr->components, IR::BoolLiteral::get(true));
}
if (resolved) {
return new IR::StructExpression(structExpr->srcInfo, structType, structExpr->type,
Expand Down
2 changes: 1 addition & 1 deletion backends/p4tools/common/core/abstract_execution_state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ void AbstractExecutionState::initializeStructLike(const Target &target,
std::vector<IR::StateVariable> flatTargetValids;
auto flatTargetFields = getFlatFields(targetVar, &flatTargetValids);
for (const auto &fieldTargetValid : flatTargetValids) {
set(fieldTargetValid, IR::getBoolLiteral(false));
set(fieldTargetValid, IR::BoolLiteral::get(false));
}
for (const auto &flatTargetRef : flatTargetFields) {
set(flatTargetRef, target.createTargetUninitialized(flatTargetRef->type, forceTaint));
Expand Down
6 changes: 3 additions & 3 deletions backends/p4tools/common/core/z3_solver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ const IR::Literal *Z3Solver::toLiteral(const z3::expr &e, const IR::Type *type)
// Handle booleans.
if (type->is<IR::Type::Boolean>()) {
BUG_CHECK(e.is_bool(), "Expected a boolean value: %1%", e);
return IR::getBoolLiteral(e.is_true());
return IR::BoolLiteral::get(e.is_true());
}

// Handle bit vectors.
Expand All @@ -306,7 +306,7 @@ const IR::Literal *Z3Solver::toLiteral(const z3::expr &e, const IR::Type *type)
strNum.erase(remove(strNum.begin(), strNum.end(), ' '), strNum.end());
}
big_int bigint(strNum.c_str());
return IR::getConstant(type, bigint);
return IR::Constant::get(type, bigint);
}

void Z3Solver::toJSON(JSONGenerator &json) const {
Expand Down Expand Up @@ -491,7 +491,7 @@ const ShiftType *Z3Translator::rewriteShift(const ShiftType *shift) const {
// vector.
const auto *shiftAmount = right->to<IR::Constant>();
BUG_CHECK(shiftAmount, "Shift amount is not a compile-time known constant: %1%", right);
const auto *newShiftAmount = IR::getConstant(left->type, shiftAmount->value);
const auto *newShiftAmount = IR::Constant::get(left->type, shiftAmount->value);

return new ShiftType(shift->type, left, newShiftAmount);
}
Expand Down
2 changes: 1 addition & 1 deletion backends/p4tools/common/lib/gen_eq.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const IR::Expression *equate(const IR::Expression *left, const IR::Expression *r

// A single default expression can be matched with a list expression.
if (left->is<IR::DefaultExpression>() || right->is<IR::DefaultExpression>()) {
return IR::getBoolLiteral(true);
return IR::BoolLiteral::get(true);
}

// If we still have lists after unrolling, compare them.
Expand Down
4 changes: 2 additions & 2 deletions backends/p4tools/common/lib/table_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@ const IR::Expression *computeEntryMatch(const IR::P4Table &table, const IR::Entr
auto numKeys = key.keyElements.size();
// If there are no entries or keys, there is nothing we can match against.
if (numKeys == 0) {
return IR::getBoolLiteral(false);
return IR::BoolLiteral::get(false);
}
BUG_CHECK(key.keyElements.size() == entry.keys->size(),
"The entry key list and key match list must be equal in size.");
const IR::Expression *entryMatchCondition = IR::getBoolLiteral(true);
const IR::Expression *entryMatchCondition = IR::BoolLiteral::get(true);
for (size_t idx = 0; idx < numKeys; ++idx) {
const auto *keyElement = key.keyElements.at(idx);
const auto *keyExpr = keyElement->expression;
Expand Down
4 changes: 2 additions & 2 deletions backends/p4tools/common/lib/taint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ class TaintPropagator : public Transform {
}
// Otherwise we convert the expression to a constant of the sliced type.
// Ultimately, the value here does not matter.
return IR::getConstant(sliceTb, 0);
return IR::Constant::get(sliceTb, 0);
}

public:
Expand All @@ -231,7 +231,7 @@ class MaskBuilder : public Transform {

const IR::Node *preorder(IR::PathExpression *path) override {
// Non-tainted members just return the max value, which corresponds to a mask of all zeroes.
return IR::getConstant(path->type, IR::getMaxBvVal(path->type));
return IR::Constant::get(path->type, IR::getMaxBvVal(path->type));
}

const IR::Node *preorder(IR::TaintExpression *taintExpr) override {
Expand Down
4 changes: 2 additions & 2 deletions backends/p4tools/common/lib/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ const IR::Constant *Utils::getRandConstantForWidth(int bitWidth) {
auto maxVal = IR::getMaxBvVal(bitWidth);
auto randInt = Utils::getRandBigInt(maxVal);
const auto *constType = IR::getBitType(bitWidth);
return IR::getConstant(constType, randInt);
return IR::Constant::get(constType, randInt);
}

const IR::Constant *Utils::getRandConstantForType(const IR::Type_Bits *type) {
auto maxVal = IR::getMaxBvVal(type->width_bits());
auto randInt = Utils::getRandBigInt(maxVal);
return IR::getConstant(type, randInt);
return IR::Constant::get(type, randInt);
}

/* =========================================================================================
Expand Down
5 changes: 2 additions & 3 deletions backends/p4tools/modules/testgen/core/program_info.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,11 @@ void ProgramInfo::produceCopyInOutCall(const IR::Parameter *param, size_t paramI
}
const auto *archPath = new IR::PathExpression(paramType, new IR::Path(archRef));
const auto *paramRef = new IR::PathExpression(paramType, new IR::Path(param->name));
const auto *paramDir =
new IR::StringLiteral(IR::Type_String::get(), directionToString(param->direction));
const auto *paramDir = IR::StringLiteral::get(directionToString(param->direction));
if (copyIns != nullptr) {
// This mimicks the copy-in from the architecture environment.
const auto *copyInCall = new IR::MethodCallStatement(Utils::generateInternalMethodCall(
"copy_in", {archPath, paramRef, paramDir, IR::getBoolLiteral(false)}));
"copy_in", {archPath, paramRef, paramDir, IR::BoolLiteral::get(false)}));
copyIns->emplace_back(copyInCall);
}
if (copyOuts != nullptr) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,12 @@ bool AbstractStepper::stepGetHeaderValidity(const IR::StateVariable &headerRef)
const auto *res = value->to<IR::BoolLiteral>();
BUG_CHECK(res, "%1%: expected a boolean", value);
if (res->value) {
state.replaceTopBody(Continuation::Return(IR::getBoolLiteral(true)));
state.replaceTopBody(Continuation::Return(IR::BoolLiteral::get(true)));
result->emplace_back(state);
return false;
}
}
state.replaceTopBody(Continuation::Return(IR::getBoolLiteral(false)));
state.replaceTopBody(Continuation::Return(IR::BoolLiteral::get(false)));
result->emplace_back(state);
return false;
}
Expand All @@ -212,7 +212,7 @@ bool AbstractStepper::stepGetHeaderValidity(const IR::StateVariable &headerRef)
void AbstractStepper::setHeaderValidity(const IR::StateVariable &headerRef, bool validity,
ExecutionState &nextState) {
const auto &headerRefValidity = ToolsVariables::getHeaderValidity(headerRef);
nextState.set(headerRefValidity, IR::getBoolLiteral(validity));
nextState.set(headerRefValidity, IR::BoolLiteral::get(validity));

// In some cases, the header may be `part of a union.
if (validity) {
Expand Down Expand Up @@ -351,7 +351,7 @@ void AbstractStepper::setTargetUninitialized(ExecutionState &nextState,
auto fields = nextState.getFlatFields(ref, &validFields);
// We also need to initialize the validity bits of the headers. These are false.
for (const auto &validField : validFields) {
nextState.set(validField, IR::getBoolLiteral(false));
nextState.set(validField, IR::BoolLiteral::get(false));
}
// For each field in the undefined struct, we create a new symbolic variable.
// If the variable does not have an initializer we need to create a new variable for it.
Expand All @@ -373,7 +373,7 @@ void AbstractStepper::declareStructLike(ExecutionState &nextState,
auto fields = nextState.getFlatFields(parentExpr, &validFields);
// We also need to initialize the validity bits of the headers. These are false.
for (const auto &validField : validFields) {
nextState.set(validField, IR::getBoolLiteral(false));
nextState.set(validField, IR::BoolLiteral::get(false));
}
// For each field in the undefined struct, we create a new symbolic variable.
// If the variable does not have an initializer we need to create a new variable for it.
Expand Down
14 changes: 7 additions & 7 deletions backends/p4tools/modules/testgen/core/small_step/cmd_stepper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,8 @@ bool CmdStepper::preorder(const IR::P4Program * /*program*/) {
std::optional<const Constraint *> portRangeCond = std::nullopt;
const auto &inputPortVar = programInfo.getTargetInputPortVar();
for (auto portRange : options.permittedPortRanges) {
const auto *loVarIn = IR::getConstant(inputPortVar->type, portRange.first);
const auto *hiVarIn = IR::getConstant(inputPortVar->type, portRange.second);
const auto *loVarIn = IR::Constant::get(inputPortVar->type, portRange.first);
const auto *hiVarIn = IR::Constant::get(inputPortVar->type, portRange.second);
if (portRangeCond.has_value()) {
portRangeCond = new IR::LOr(portRangeCond.value(),
new IR::LAnd(new IR::Leq(loVarIn, inputPortVar),
Expand All @@ -308,7 +308,7 @@ bool CmdStepper::preorder(const IR::P4Program * /*program*/) {
if (pktSize != 0) {
const auto *fixedSizeEqu =
new IR::Geq(ExecutionState::getInputPacketSizeVar(),
IR::getConstant(&PacketVars::PACKET_SIZE_VAR_TYPE, pktSize));
IR::Constant::get(&PacketVars::PACKET_SIZE_VAR_TYPE, pktSize));
if (cond == std::nullopt) {
cond = fixedSizeEqu;
} else {
Expand Down Expand Up @@ -446,7 +446,7 @@ const Constraint *CmdStepper::startParser(const IR::P4Parser *parser, ExecutionS
const auto *boolType = IR::Type::Boolean::get();
const Constraint *result =
new IR::Leq(boolType, ExecutionState::getInputPacketSizeVar(),
IR::getConstant(parserCursorVarType, ExecutionState::getMaxPacketLength()));
IR::Constant::get(parserCursorVarType, ExecutionState::getMaxPacketLength()));

// Constrain the input packet size to be a multiple of 8 bits. Do this by constraining the
// lowest three bits of the packet size to 0.
Expand All @@ -455,9 +455,9 @@ const Constraint *CmdStepper::startParser(const IR::P4Parser *parser, ExecutionS
boolType, result,
new IR::Equ(boolType,
new IR::Slice(threeBitType, ExecutionState::getInputPacketSizeVar(),
IR::getConstant(parserCursorVarType, 2),
IR::getConstant(parserCursorVarType, 0)),
IR::getConstant(threeBitType, 0)));
IR::Constant::get(parserCursorVarType, 2),
IR::Constant::get(parserCursorVarType, 0)),
IR::Constant::get(threeBitType, 0)));

// Call the implementation for the specific target.
// If we get a constraint back, add it to the result.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ bool ExprStepper::preorder(const IR::PathExpression *pathExpression) {
// If the path expression is a Type_MatchKind, convert it to a StringLiteral.
if (pathExpression->type->is<IR::Type_MatchKind>()) {
state.replaceTopBody(Continuation::Return(
new IR::StringLiteral(IR::Type_MatchKind::get(), pathExpression->path->name)));
IR::StringLiteral::get(pathExpression->path->name, IR::Type_MatchKind::get())));
result->emplace_back(state);
return false;
}
Expand Down Expand Up @@ -423,7 +423,7 @@ bool ExprStepper::preorder(const IR::SelectExpression *selectExpression) {
}
}

const IR::Expression *missCondition = IR::getBoolLiteral(true);
const IR::Expression *missCondition = IR::BoolLiteral::get(true);
bool hasDefault = false;
for (const auto *selectCase : selectCases) {
auto &nextState = state.clone();
Expand Down
28 changes: 14 additions & 14 deletions backends/p4tools/modules/testgen/core/small_step/extern_stepper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ ExprStepper::PacketCursorAdvanceInfo ExprStepper::calculateSuccessfulParserAdvan
auto minSize =
std::max(0, state.getInputPacketCursor() + advanceSize - state.getPacketBufferSize());
auto *cond = new IR::Geq(IR::Type::Boolean::get(), ExecutionState::getInputPacketSizeVar(),
IR::getConstant(&PacketVars::PACKET_SIZE_VAR_TYPE, minSize));
IR::Constant::get(&PacketVars::PACKET_SIZE_VAR_TYPE, minSize));
return {advanceSize, cond, advanceSize, new IR::LNot(cond)};
}

Expand All @@ -101,8 +101,8 @@ ExprStepper::PacketCursorAdvanceInfo ExprStepper::calculateAdvanceExpression(
const IR::Expression *restrictions) const {
const auto *packetSizeVarType = &PacketVars::PACKET_SIZE_VAR_TYPE;

const auto *cursorConst = IR::getConstant(packetSizeVarType, state.getInputPacketCursor());
const auto *bufferSizeConst = IR::getConstant(packetSizeVarType, state.getPacketBufferSize());
const auto *cursorConst = IR::Constant::get(packetSizeVarType, state.getInputPacketCursor());
const auto *bufferSizeConst = IR::Constant::get(packetSizeVarType, state.getPacketBufferSize());
const auto *advanceSum = new IR::Add(packetSizeVarType, cursorConst, advanceExpr);
auto *minSize = new IR::Sub(packetSizeVarType, advanceSum, bufferSizeConst);
// The packet size must be larger than the current parser cursor minus what is already
Expand Down Expand Up @@ -441,11 +441,11 @@ void ExprStepper::evalExternMethodCall(const IR::MethodCallExpression *call,
// size.
auto *sizeRestriction = new IR::Leq(
advanceExpr,
IR::getConstant(advanceExpr->type, ExecutionState::getMaxPacketLength()));
IR::Constant::get(advanceExpr->type, ExecutionState::getMaxPacketLength()));
// The advance expression should ideally have a size that is a multiple of 8 bits.
auto *bytesRestriction =
new IR::Equ(new IR::Mod(advanceExpr, IR::getConstant(advanceExpr->type, 8)),
IR::getConstant(advanceExpr->type, 0));
new IR::Equ(new IR::Mod(advanceExpr, IR::Constant::get(advanceExpr->type, 8)),
IR::Constant::get(advanceExpr->type, 0));
auto *restrictions = new IR::LAnd(sizeRestriction, bytesRestriction);
condInfo = calculateAdvanceExpression(state, advanceExpr, restrictions);
}
Expand Down Expand Up @@ -606,17 +606,17 @@ void ExprStepper::evalExternMethodCall(const IR::MethodCallExpression *call,
// size.
auto maxVarbit = std::min(ExecutionState::getMaxPacketLength(), varbit->size);
auto *sizeRestriction = new IR::Leq(
varbitExtractExpr, IR::getConstant(varbitExtractExpr->type, maxVarbit));
varbitExtractExpr, IR::Constant::get(varbitExtractExpr->type, maxVarbit));
// The advance expression should ideally fit into a multiple of 8 bits.
auto *bytesRestriction = new IR::Equ(
new IR::Mod(varbitExtractExpr, IR::getConstant(varbitExtractExpr->type, 8)),
IR::getConstant(varbitExtractExpr->type, 0));
new IR::Mod(varbitExtractExpr, IR::Constant::get(varbitExtractExpr->type, 8)),
IR::Constant::get(varbitExtractExpr->type, 0));
// The advance expression should not be larger than the varbit maximum width.
auto *restrictions = new IR::LAnd(sizeRestriction, bytesRestriction);
// In the second case, where the advance amount is a runtime expression, we need to
// invoke the solver.
varbitExtractExpr = new IR::Add(
varbitExtractExpr, IR::getConstant(varbitExtractExpr->type, extractSize));
varbitExtractExpr, IR::Constant::get(varbitExtractExpr->type, extractSize));
condInfo = calculateAdvanceExpression(state, varbitExtractExpr, restrictions);
varBitFieldSize = std::max(0, condInfo.advanceSize - extractSize);
}
Expand All @@ -626,8 +626,8 @@ void ExprStepper::evalExternMethodCall(const IR::MethodCallExpression *call,
if (varbit->size < varBitFieldSize) {
auto &nextState = state.clone();
nextState.set(state.getCurrentParserErrorLabel(),
IR::getConstant(programInfo.getParserErrorType(),
P4Constants::PARSER_ERROR_HEADER_TOO_SHORT));
IR::Constant::get(programInfo.getParserErrorType(),
P4Constants::PARSER_ERROR_HEADER_TOO_SHORT));
nextState.replaceTopBody(Continuation::Exception::Reject);
result->emplace_back(condInfo.advanceCond, state, nextState);
return;
Expand Down Expand Up @@ -683,7 +683,7 @@ void ExprStepper::evalExternMethodCall(const IR::MethodCallExpression *call,
const auto &lengthVar = ExecutionState::getInputPacketSizeVar();
const auto *divVar =
new IR::Div(lengthVar->type, ExecutionState::getInputPacketSizeVar(),
IR::getConstant(lengthVar->type, 8));
IR::Constant::get(lengthVar->type, 8));
nextState.add(*new TraceEvents::Expression(divVar, "Return packet length"));
nextState.replaceTopBody(Continuation::Return(divVar));
result->emplace_back(std::nullopt, state, nextState);
Expand Down Expand Up @@ -817,7 +817,7 @@ void ExprStepper::evalExternMethodCall(const IR::MethodCallExpression *call,
auto &falseState = state.clone();
const auto &errVar = state.getCurrentParserErrorLabel();
falseState.set(errVar,
IR::getConstant(programInfo.getParserErrorType(), error->value));
IR::Constant::get(programInfo.getParserErrorType(), error->value));
falseState.replaceTopBody(Continuation::Exception::Reject);
result->emplace_back(new IR::LNot(IR::Type::Boolean::get(), cond), state, falseState);
}},
Expand Down
Loading

0 comments on commit 1583086

Please sign in to comment.