From ba1e77b475d4357ff0df5a9e4ddb5c97e8a7d945 Mon Sep 17 00:00:00 2001 From: Anton Korobeynikov Date: Mon, 21 Oct 2024 12:50:04 -0700 Subject: [PATCH] Add abseil formatters for: - cstring - IR::Node - IR::ID This improves the code itself as we no longer need to do explicit .toString() / .string_view() calls. Also, this prints directly to sink, providing some performance improvements. Signed-off-by: Anton Korobeynikov --- .../control-plane/bfruntime_arch_handler.h | 18 +- backends/ebpf/codeGen.cpp | 6 +- backends/ebpf/ebpfControl.cpp | 14 +- backends/ebpf/ebpfDeparser.cpp | 16 +- backends/ebpf/ebpfParser.cpp | 56 +++-- backends/ebpf/ebpfTable.cpp | 84 ++++--- backends/ebpf/ebpfType.cpp | 2 +- backends/ebpf/psa/ebpfPipeline.cpp | 206 +++++++++--------- backends/ebpf/psa/ebpfPsaControl.cpp | 2 +- backends/ebpf/psa/ebpfPsaDeparser.cpp | 37 ++-- backends/ebpf/psa/ebpfPsaGen.cpp | 4 +- backends/ebpf/psa/ebpfPsaTable.cpp | 45 ++-- backends/ebpf/psa/externs/ebpfPsaCounter.cpp | 2 +- backends/ebpf/psa/externs/ebpfPsaDigest.cpp | 8 +- backends/ebpf/psa/externs/ebpfPsaMeter.cpp | 15 +- backends/ebpf/psa/externs/ebpfPsaRegister.cpp | 4 +- .../externs/ebpfPsaTableImplementation.cpp | 2 +- backends/ebpf/psa/xdpHelpProgram.h | 2 +- backends/ebpf/target.cpp | 46 ++-- backends/ebpf/target.h | 3 +- .../targets/bmv2/p4_asserts_parser.cpp | 2 +- backends/tc/ebpfCodeGen.cpp | 147 ++++++------- backends/tc/ebpfCodeGen.h | 2 +- backends/tc/tcExterns.cpp | 24 +- backends/ubpf/target.cpp | 8 +- backends/ubpf/ubpfControl.cpp | 10 +- backends/ubpf/ubpfDeparser.cpp | 4 +- backends/ubpf/ubpfParser.cpp | 8 +- backends/ubpf/ubpfProgram.cpp | 14 +- backends/ubpf/ubpfTable.cpp | 8 +- backends/ubpf/ubpfType.cpp | 4 +- control-plane/p4RuntimeArchHandler.cpp | 6 +- control-plane/p4RuntimeArchHandler.h | 8 +- control-plane/p4RuntimeArchStandard.h | 9 +- control-plane/p4RuntimeSerializer.cpp | 22 +- control-plane/typeSpecConverter.cpp | 29 +-- frontends/p4/def_use.cpp | 6 +- frontends/p4/localizeActions.cpp | 4 +- frontends/p4/typeChecking/typeCheckDecl.cpp | 8 +- frontends/p4/uniqueNames.h | 4 +- ir/base.def | 10 +- ir/expression.def | 29 +-- ir/id.h | 8 +- ir/ir.def | 6 +- ir/node.h | 5 + ir/type.def | 24 +- lib/bug_helper.h | 2 +- lib/cstring.h | 24 +- lib/json.cpp | 2 +- lib/options.cpp | 6 +- lib/source_file.cpp | 13 +- lib/source_file.h | 8 +- lib/stringify.h | 2 +- midend/flattenInterfaceStructs.cpp | 2 +- midend/nestedStructs.cpp | 2 +- tools/ir-generator/ir-generator.ypp | 4 +- tools/ir-generator/methods.cpp | 20 +- tools/ir-generator/type.h | 3 +- 58 files changed, 531 insertions(+), 538 deletions(-) diff --git a/backends/dpdk/control-plane/bfruntime_arch_handler.h b/backends/dpdk/control-plane/bfruntime_arch_handler.h index a5d8190680b..3a90595bc8b 100644 --- a/backends/dpdk/control-plane/bfruntime_arch_handler.h +++ b/backends/dpdk/control-plane/bfruntime_arch_handler.h @@ -147,7 +147,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { } auto *externType = p4info->add_externs(); externType->set_extern_type_id(static_cast(typeId)); - externType->set_extern_type_name(typeName); + externType->set_extern_type_name(typeName.string_view()); return externType; } @@ -161,8 +161,8 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { auto *externInstance = externType->add_instances(); auto *pre = externInstance->mutable_preamble(); pre->set_id(symbols.getId(typeId, name)); - pre->set_name(prefix(pipeName, name)); - pre->set_alias(symbols.getAlias(name)); + pre->set_name(prefix(pipeName, name).string_view()); + pre->set_alias(symbols.getAlias(name).string_view()); Helpers::addAnnotations(pre, annotations); Helpers::addDocumentation(pre, annotations); externInstance->mutable_info()->PackFrom(message); @@ -237,7 +237,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { auto pipeName = getBlockNamePrefix(tableBlock); auto *pre = table->mutable_preamble(); if (pre->name() == tableDeclaration->controlPlaneName()) - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); } void addExternInstance(const P4RuntimeSymbolTableIface &symbols, p4configv1::P4Info *p4info, @@ -261,7 +261,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { for (auto &extType : *p4info->mutable_action_profiles()) { auto *pre = extType.mutable_preamble(); if (pre->name() == decl->controlPlaneName()) { - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); break; } } @@ -269,7 +269,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { for (auto &extType : *p4info->mutable_action_profiles()) { auto *pre = extType.mutable_preamble(); if (pre->name() == decl->controlPlaneName()) { - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); break; } } @@ -277,7 +277,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { for (auto &extType : *p4info->mutable_meters()) { auto *pre = extType.mutable_preamble(); if (pre->name() == decl->controlPlaneName()) { - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); break; } } @@ -285,7 +285,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { for (auto &extType : *p4info->mutable_counters()) { auto *pre = extType.mutable_preamble(); if (pre->name() == decl->controlPlaneName()) { - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); break; } } @@ -293,7 +293,7 @@ class BFRuntimeArchHandler : public P4RuntimeArchHandlerCommon { for (auto &extType : *p4info->mutable_registers()) { auto *pre = extType.mutable_preamble(); if (pre->name() == decl->controlPlaneName()) { - pre->set_name(prefix(pipeName, pre->name())); + pre->set_name(prefix(pipeName, pre->name()).string_view()); break; } } diff --git a/backends/ebpf/codeGen.cpp b/backends/ebpf/codeGen.cpp index 83b9459f2ba..db05340e817 100644 --- a/backends/ebpf/codeGen.cpp +++ b/backends/ebpf/codeGen.cpp @@ -39,14 +39,14 @@ bool CodeGenInspector::preorder(const IR::Constant *expression) { cstring str = EBPFInitializerUtils::genHexStr(expression->value, width, expression); builder->append("{ "); for (size_t i = 0; i < str.size() / 2; ++i) - builder->appendFormat("0x%s, ", str.substr(2 * i, 2)); + builder->appendFormat("0x%v, ", str.substr(2 * i, 2)); builder->append("}"); return false; } bool CodeGenInspector::preorder(const IR::StringLiteral *expression) { - builder->appendFormat("\"%s\"", expression->toString()); + builder->appendFormat("\"%v\"", expression->toString()); return true; } @@ -491,7 +491,7 @@ void CodeGenInspector::emitAndConvertByteOrder(const IR::Expression *expr, cstri loadSize = 64; } unsigned shift = loadSize - widthToEmit; - builder->appendFormat("%s(", emit); + builder->appendFormat("%v(", emit); visit(expr); if (shift != 0 && byte_order == "HOST") builder->appendFormat(" << %d", shift); builder->append(")"); diff --git a/backends/ebpf/ebpfControl.cpp b/backends/ebpf/ebpfControl.cpp index 968ec5da44b..8f78d8e7154 100644 --- a/backends/ebpf/ebpfControl.cpp +++ b/backends/ebpf/ebpfControl.cpp @@ -142,8 +142,7 @@ bool ControlBodyTranslator::preorder(const IR::MethodCallExpression *expression) // Action arguments have been eliminated by the mid-end. BUG_CHECK(expression->arguments->size() == 0, "%1%: unexpected arguments for action call", expression); - cstring msg = - absl::StrFormat("Control: explicit calling action %s()", ac->action->name.name); + cstring msg = absl::StrFormat("Control: explicit calling action %v()", ac->action->name); builder->target->emitTraceMessage(builder, msg.c_str()); visit(ac->action->body); return false; @@ -165,9 +164,9 @@ void ControlBodyTranslator::compileEmitField(const IR::Expression *expr, cstring if (!swap.isNullOrEmpty()) { builder->emitIndent(); visit(expr); - builder->appendFormat(".%s = %s(", field.c_str(), swap); + builder->appendFormat(".%v = %v(", field, swap); visit(expr); - builder->appendFormat(".%s)", field.c_str()); + builder->appendFormat(".%v)", field); builder->endOfStatement(true); } @@ -304,7 +303,7 @@ void ControlBodyTranslator::processApply(const P4::ApplyMethod *method) { auto table = control->getTable(method->object->getName().name); BUG_CHECK(table != nullptr, "No table for %1%", method->expr); - msgStr = absl::StrFormat("Control: applying %s", method->object->getName().name); + msgStr = absl::StrFormat("Control: applying %v", method->object->getName()); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->emitIndent(); @@ -393,7 +392,7 @@ void ControlBodyTranslator::processApply(const P4::ApplyMethod *method) { builder->blockEnd(true); builder->blockEnd(true); - msgStr = absl::StrFormat("Control: %s applied", method->object->getName().name); + msgStr = absl::StrFormat("Control: %v applied", method->object->getName()); builder->target->emitTraceMessage(builder, msgStr.c_str()); } @@ -595,8 +594,7 @@ void EBPFControl::emitDeclaration(CodeBuilder *builder, const IR::Declaration *d // Therefore, this piece of code zero-initialize structures // that might be used as keys. builder->emitIndent(); - builder->appendFormat("__builtin_memset((void *) &%s, 0, sizeof(", - vd->name.name); + builder->appendFormat("__builtin_memset((void *) &%v, 0, sizeof(", vd->name); etype->declare(builder, cstring::empty, false); builder->append("))"); builder->endOfStatement(true); diff --git a/backends/ebpf/ebpfDeparser.cpp b/backends/ebpf/ebpfDeparser.cpp index 8569955732e..deff72a4a23 100644 --- a/backends/ebpf/ebpfDeparser.cpp +++ b/backends/ebpf/ebpfDeparser.cpp @@ -201,13 +201,13 @@ void DeparserHdrEmitTranslator::emitField(CodeBuilder *builder, cstring field, visit(hdrExpr); builder->appendFormat(".%s", field.c_str()); builder->endOfStatement(true); - msgStr = absl::StrFormat("Deparser: emitting field %s=0x%%llx (%u bits)", field, + msgStr = absl::StrFormat("Deparser: emitting field %v=0x%%llx (%u bits)", field, widthToEmit); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, "tmp"); builder->blockEnd(true); } } else { - msgStr = absl::StrFormat("Deparser: emitting field %s (%u bits)", field, widthToEmit); + msgStr = absl::StrFormat("Deparser: emitting field %v (%u bits)", field, widthToEmit); builder->target->emitTraceMessage(builder, msgStr.c_str()); } @@ -229,9 +229,9 @@ void DeparserHdrEmitTranslator::emitField(CodeBuilder *builder, cstring field, if (!swap.isNullOrEmpty()) { builder->emitIndent(); visit(hdrExpr); - builder->appendFormat(".%s = %s(", field, swap); + builder->appendFormat(".%v = %v(", field, swap); visit(hdrExpr); - builder->appendFormat(".%s", field); + builder->appendFormat(".%v", field); if (shift != 0) builder->appendFormat(" << %d", shift); builder->append(")"); builder->endOfStatement(true); @@ -244,7 +244,7 @@ void DeparserHdrEmitTranslator::emitField(CodeBuilder *builder, cstring field, builder->emitIndent(); builder->appendFormat("%s = ((char*)(&", program->byteVar.c_str()); visit(hdrExpr); - builder->appendFormat(".%s))[%d]", field, i); + builder->appendFormat(".%v))[%d]", field, i); builder->endOfStatement(true); unsigned freeBits = alignment != 0 ? (8 - alignment) : 8; bitsInCurrentByte = left >= 8 ? 8 : left; @@ -371,14 +371,14 @@ void EBPFDeparser::emit(CodeBuilder *builder) { emitBufferAdjusts(builder); builder->emitIndent(); - builder->appendFormat("%s = %s;", program->packetStartVar, + builder->appendFormat("%v = %v;", program->packetStartVar, builder->target->dataOffset(program->model.CPacketName.toString())); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s = %s;", program->headerStartVar, program->packetStartVar); + builder->appendFormat("%v = %v;", program->headerStartVar, program->packetStartVar); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s = %s;", program->packetEndVar, + builder->appendFormat("%v = %v;", program->packetEndVar, builder->target->dataEnd(program->model.CPacketName.toString())); builder->newline(); diff --git a/backends/ebpf/ebpfParser.cpp b/backends/ebpf/ebpfParser.cpp index d72be768365..85eaaa1fbc0 100644 --- a/backends/ebpf/ebpfParser.cpp +++ b/backends/ebpf/ebpfParser.cpp @@ -24,21 +24,20 @@ limitations under the License. namespace P4::EBPF { void StateTranslationVisitor::compileLookahead(const IR::Expression *destination) { - cstring msgStr = absl::StrFormat("Parser: lookahead for %s %s", - state->parser->typeMap->getType(destination)->toString(), - destination->toString()); + cstring msgStr = absl::StrFormat("Parser: lookahead for %v %v", + state->parser->typeMap->getType(destination), destination); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->emitIndent(); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("u8* %s_save = %s", state->parser->program->headerStartVar.c_str(), - state->parser->program->headerStartVar.c_str()); + builder->appendFormat("u8* %v_save = %v", state->parser->program->headerStartVar, + state->parser->program->headerStartVar); builder->endOfStatement(true); compileExtract(destination); builder->emitIndent(); - builder->appendFormat("%s = %s_save", state->parser->program->headerStartVar.c_str(), - state->parser->program->headerStartVar.c_str()); + builder->appendFormat("%v = %v_save", state->parser->program->headerStartVar, + state->parser->program->headerStartVar); builder->endOfStatement(true); builder->blockEnd(true); } @@ -49,7 +48,7 @@ void StateTranslationVisitor::compileAdvance(const P4::ExternMethod *extMethod) if (cnst) { cstring argStr = cstring::to_cstring(cnst->asUnsigned()); cstring offsetStr = - absl::StrFormat("%s - (u8*)%s + BYTES(%s)", state->parser->program->headerStartVar, + absl::StrFormat("%v - (u8*)%v + BYTES(%v)", state->parser->program->headerStartVar, state->parser->program->packetStartVar, argStr); builder->target->emitTraceMessage(builder, "Parser (advance): check pkt_len=%%d < " @@ -70,14 +69,14 @@ void StateTranslationVisitor::compileAdvance(const P4::ExternMethod *extMethod) } builder->emitIndent(); - builder->appendFormat("%s += BYTES(", state->parser->program->headerStartVar.c_str()); + builder->appendFormat("%v += BYTES(", state->parser->program->headerStartVar); visit(argExpr); builder->append(")"); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("if ((u8*)%s < %s) ", state->parser->program->packetEndVar.c_str(), - state->parser->program->headerStartVar.c_str()); + builder->appendFormat("if ((u8*)%v < %v) ", state->parser->program->packetEndVar, + state->parser->program->headerStartVar); builder->blockStart(); builder->target->emitTraceMessage(builder, "Parser: invalid packet (packet too short)"); @@ -111,12 +110,11 @@ void StateTranslationVisitor::compileVerify(const IR::MethodCallExpression *expr builder->blockStart(); builder->emitIndent(); - builder->appendFormat("%s = %s", state->parser->program->errorVar.c_str(), - errorMember->member.name); + builder->appendFormat("%v = %v", state->parser->program->errorVar, errorMember->member); builder->endOfStatement(true); - cstring msg = absl::StrFormat("Verify: condition failed, parser_error=%%u (%s)", - errorMember->member.name); + cstring msg = + absl::StrFormat("Verify: condition failed, parser_error=%%u (%v)", errorMember->member); builder->target->emitTraceMessage(builder, msg.c_str(), 1, state->parser->program->errorVar.c_str()); @@ -156,8 +154,8 @@ bool StateTranslationVisitor::preorder(const IR::ParserState *parserState) { builder->spc(); builder->blockStart(); - cstring msgStr = absl::StrFormat("Parser: state %s (curr_offset=%%d)", parserState->name.name); - cstring offsetStr = absl::StrFormat("%s - (u8*)%s", state->parser->program->headerStartVar, + cstring msgStr = absl::StrFormat("Parser: state %v (curr_offset=%%d)", parserState->name); + cstring offsetStr = absl::StrFormat("%v - (u8*)%v", state->parser->program->headerStartVar, state->parser->program->packetStartVar); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, offsetStr.c_str()); @@ -235,7 +233,7 @@ bool StateTranslationVisitor::preorder(const IR::SelectCase *selectCase) { builder->append(" != NULL)"); } else if (auto mask = selectCase->keyset->to()) { if (scalar) { - builder->appendFormat("if ((%s", selectValue); + builder->appendFormat("if ((%v", selectValue); builder->append(" & "); visit(mask->right); builder->append(") == ("); @@ -255,15 +253,15 @@ bool StateTranslationVisitor::preorder(const IR::SelectCase *selectCase) { if (!first) { builder->append(" && "); } - builder->appendFormat("((%s[%u] & 0x%s)", selectValue, i, hex.substr(2 * i, 2)); + builder->appendFormat("((%v[%u] & 0x%v)", selectValue, i, hex.substr(2 * i, 2)); builder->append(" == "); - builder->appendFormat("(%s & %s))", value.substr(2 * i, 2), hex.substr(2 * i, 2)); + builder->appendFormat("(%v & %v))", value.substr(2 * i, 2), hex.substr(2 * i, 2)); first = false; } builder->append(") "); } } else { - builder->appendFormat("if (%s", selectValue); + builder->appendFormat("if (%v", selectValue); builder->append(" == "); visit(selectCase->keyset); builder->append(")"); @@ -283,7 +281,7 @@ void StateTranslationVisitor::compileExtractField(const IR::Expression *expr, cstring msgStr; cstring fieldName = field->name.name; - msgStr = absl::StrFormat("Parser: extracting field %s", fieldName); + msgStr = absl::StrFormat("Parser: extracting field %v", fieldName); builder->target->emitTraceMessage(builder, msgStr.c_str()); if (widthToExtract <= 64) { @@ -391,13 +389,13 @@ void StateTranslationVisitor::compileExtractField(const IR::Expression *expr, expr->to()->expr->to()->path->name.name)) { exprStr = exprStr.replace(".", "->"); } - cstring tmp = absl::StrFormat("(unsigned long long) %s.%s", exprStr, fieldName); + auto tmp = absl::StrFormat("(unsigned long long) %v.%v", exprStr, fieldName); msgStr = - absl::StrFormat("Parser: extracted %s=0x%%llx (%u bits)", fieldName, widthToExtract); + absl::StrFormat("Parser: extracted %v=0x%%llx (%u bits)", fieldName, widthToExtract); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, tmp.c_str()); } else { - msgStr = absl::StrFormat("Parser: extracted %s (%u bits)", fieldName, widthToExtract); + msgStr = absl::StrFormat("Parser: extracted %v (%u bits)", fieldName, widthToExtract); builder->target->emitTraceMessage(builder, msgStr.c_str()); } } @@ -422,8 +420,8 @@ void StateTranslationVisitor::compileExtract(const IR::Expression *destination) auto program = state->parser->program; - cstring offsetStr = absl::StrFormat("(%s - (u8*)%s) + BYTES(%s)", program->headerStartVar, - program->packetStartVar, cstring::to_cstring(width)); + auto offsetStr = absl::StrFormat("(%v - (u8*)%v) + BYTES(%d)", program->headerStartVar, + program->packetStartVar, width); builder->target->emitTraceMessage(builder, "Parser: check pkt_len=%d >= last_read_byte=%d", 2, program->lengthVar.c_str(), offsetStr.c_str()); @@ -466,7 +464,7 @@ void StateTranslationVisitor::compileExtract(const IR::Expression *destination) builder->newline(); builder->blockEnd(true); - msgStr = absl::StrFormat("Parser: extracting header %s", destination->toString()); + msgStr = absl::StrFormat("Parser: extracting header %v", destination); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->newline(); @@ -496,7 +494,7 @@ void StateTranslationVisitor::compileExtract(const IR::Expression *destination) builder->appendFormat("%s += BYTES(%u);", program->headerStartVar.c_str(), width); builder->newline(); - msgStr = absl::StrFormat("Parser: extracted %s", destination->toString()); + msgStr = absl::StrFormat("Parser: extracted %v", destination); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->newline(); diff --git a/backends/ebpf/ebpfTable.cpp b/backends/ebpf/ebpfTable.cpp index 3fe9dd0fefb..706a4250262 100644 --- a/backends/ebpf/ebpfTable.cpp +++ b/backends/ebpf/ebpfTable.cpp @@ -44,7 +44,7 @@ bool ActionTranslationVisitor::isActionParameter(const IR::PathExpression *expre cstring ActionTranslationVisitor::getParamInstanceName(const IR::Expression *expression) const { cstring actionName = EBPFObject::externalName(action); - return absl::StrFormat("%s->u.%s.%s", valueName, actionName, expression->toString()); + return absl::StrFormat("%v->u.%v.%v", valueName, actionName, expression); } bool ActionTranslationVisitor::preorder(const IR::P4Action *act) { @@ -219,16 +219,16 @@ void EBPFTable::emitKeyType(CodeBuilder *builder) { if (isTernaryTable()) { // generate mask key builder->emitIndent(); - builder->appendFormat("#define MAX_%s_MASKS %u", keyTypeName.toUpper(), + builder->appendFormat("#define MAX_%v_MASKS %u", keyTypeName.toUpper(), program->options.maxTernaryMasks); builder->newline(); builder->emitIndent(); - builder->appendFormat("struct %s_mask ", keyTypeName.c_str()); + builder->appendFormat("struct %v_mask ", keyTypeName); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("__u8 mask[sizeof(struct %s)];", keyTypeName.c_str()); + builder->appendFormat("__u8 mask[sizeof(struct %v)];", keyTypeName); builder->newline(); builder->blockEnd(false); @@ -261,7 +261,7 @@ void EBPFTable::emitValueType(CodeBuilder *builder) { // a type-safe union: a struct with a tag and an union builder->emitIndent(); - builder->appendFormat("struct %s ", valueTypeName.c_str()); + builder->appendFormat("struct %v ", valueTypeName); builder->blockStart(); emitValueStructStructure(builder); @@ -273,13 +273,13 @@ void EBPFTable::emitValueType(CodeBuilder *builder) { if (isTernaryTable()) { // emit ternary mask value builder->emitIndent(); - builder->appendFormat("struct %s_mask ", valueTypeName.c_str()); + builder->appendFormat("struct %v_mask ", valueTypeName); builder->blockStart(); builder->emitIndent(); builder->appendLine("__u32 tuple_id;"); builder->emitIndent(); - builder->appendFormat("struct %s_mask next_tuple_mask;", keyTypeName.c_str()); + builder->appendFormat("struct %v_mask next_tuple_mask;", keyTypeName); builder->newline(); builder->emitIndent(); builder->appendLine("__u8 has_next;"); @@ -301,7 +301,7 @@ void EBPFTable::emitValueActionIDNames(CodeBuilder *builder) { continue; } builder->emitIndent(); - builder->appendFormat("#define %s %d", p4ActionToActionIDName(action), action_idx); + builder->appendFormat("#define %v %d", p4ActionToActionIDName(action), action_idx); builder->newline(); action_idx++; } @@ -453,8 +453,8 @@ void EBPFTable::emitKey(CodeBuilder *builder, cstring keyName) { if (isLPMTable()) { builder->emitIndent(); - builder->appendFormat("%s.%s = sizeof(%s)*8 - %d", keyName.c_str(), prefixFieldName, - keyName, prefixLenFieldWidth); + builder->appendFormat("%v.%v = sizeof(%v)*8 - %d", keyName, prefixFieldName, keyName, + prefixLenFieldWidth); builder->endOfStatement(true); } @@ -498,13 +498,12 @@ void EBPFTable::emitKey(CodeBuilder *builder, cstring keyName) { builder->emitIndent(); if (memcpy) { - builder->appendFormat("__builtin_memcpy(&(%s.%s[0]), &(", keyName.c_str(), - fieldName.c_str()); + builder->appendFormat("__builtin_memcpy(&(%v.%v[0]), &(", keyName, fieldName); codeGen->visit(c->expression); builder->appendFormat("[0]), %d)", scalar->bytesRequired()); } else { - builder->appendFormat("%s.%s = ", keyName.c_str(), fieldName.c_str()); - if (isLPMKeyBigEndian) builder->appendFormat("%s(", swap.c_str()); + builder->appendFormat("%v.%v = ", keyName, fieldName); + if (isLPMKeyBigEndian) builder->appendFormat("%v(", swap); codeGen->visit(c->expression); if (isLPMKeyBigEndian) builder->append(")"); } @@ -512,10 +511,10 @@ void EBPFTable::emitKey(CodeBuilder *builder, cstring keyName) { cstring msgStr, varStr; if (memcpy) { - msgStr = absl::StrFormat("Control: key %s", c->expression->toString()); + msgStr = absl::StrFormat("Control: key %v", c->expression); builder->target->emitTraceMessage(builder, msgStr.c_str()); } else { - msgStr = absl::StrFormat("Control: key %s=0x%%llx", c->expression->toString()); + msgStr = absl::StrFormat("Control: key %v=0x%%llx", c->expression); varStr = absl::StrFormat("(unsigned long long) %s.%s", keyName.c_str(), fieldName.c_str()); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, varStr.c_str()); @@ -534,24 +533,23 @@ void EBPFTable::emitAction(CodeBuilder *builder, cstring valueName, cstring acti cstring name = EBPFObject::externalName(action), msgStr, convStr; builder->emitIndent(); cstring actionName = p4ActionToActionIDName(action); - builder->appendFormat("case %s: ", actionName); + builder->appendFormat("case %v: ", actionName); builder->newline(); builder->increaseIndent(); - msgStr = absl::StrFormat("Control: executing action %s", name); + msgStr = absl::StrFormat("Control: executing action %v", name); builder->target->emitTraceMessage(builder, msgStr.c_str()); for (auto param : *(action->parameters)) { auto etype = EBPFTypeFactory::instance->create(param->type); unsigned width = etype->as().widthInBits(); if (width <= 64) { - convStr = absl::StrFormat("(unsigned long long) (%s->u.%s.%s)", valueName, name, - param->toString()); - msgStr = absl::StrFormat("Control: param %s=0x%%llx (%d bits)", param->toString(), - width); + convStr = + absl::StrFormat("(unsigned long long) (%v->u.%v.%v)", valueName, name, param); + msgStr = absl::StrFormat("Control: param %v=0x%%llx (%d bits)", param, width); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, convStr.c_str()); } else { - msgStr = absl::StrFormat("Control: param %s (%d bits)", param->toString(), width); + msgStr = absl::StrFormat("Control: param %v (%d bits)", param, width); builder->target->emitTraceMessage(builder, msgStr.c_str()); } } @@ -623,7 +621,7 @@ void EBPFTable::emitInitializer(CodeBuilder *builder) { builder->blockStart(); builder->emitIndent(); cstring actionName = p4ActionToActionIDName(action); - builder->appendFormat(".action = %s,", actionName); + builder->appendFormat(".action = %v,", actionName); builder->newline(); CodeGenInspector cg(program->refMap, program->typeMap); @@ -695,7 +693,7 @@ void EBPFTable::emitInitializer(CodeBuilder *builder) { builder->blockStart(); builder->emitIndent(); cstring actionName = p4ActionToActionIDName(action); - builder->appendFormat(".action = %s,", actionName); + builder->appendFormat(".action = %v,", actionName); builder->newline(); CodeGenInspector cg(program->refMap, program->typeMap); @@ -739,25 +737,25 @@ void EBPFTable::emitLookup(CodeBuilder *builder, cstring key, cstring value) { } // for ternary tables - builder->appendFormat("struct %s_mask head = {0};", keyTypeName); + builder->appendFormat("struct %v_mask head = {0};", keyTypeName); builder->newline(); builder->emitIndent(); - builder->appendFormat("struct %s_mask *", valueTypeName); + builder->appendFormat("struct %v_mask *", valueTypeName); builder->target->emitTableLookup(builder, instanceName + "_prefixes", "head"_cs, "val"_cs); builder->endOfStatement(true); builder->emitIndent(); builder->append("if (val && val->has_next != 0) "); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("struct %s_mask next = val->next_tuple_mask;", keyTypeName); + builder->appendFormat("struct %v_mask next = val->next_tuple_mask;", keyTypeName); builder->newline(); builder->emitIndent(); builder->appendLine("#pragma clang loop unroll(disable)"); builder->emitIndent(); - builder->appendFormat("for (int i = 0; i < MAX_%s_MASKS; i++) ", keyTypeName.toUpper()); + builder->appendFormat("for (int i = 0; i < MAX_%v_MASKS; i++) ", keyTypeName.toUpper()); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("struct %s_mask *", valueTypeName); + builder->appendFormat("struct %v_mask *", valueTypeName); builder->target->emitTableLookup(builder, instanceName + "_prefixes", "next"_cs, "v"_cs); builder->endOfStatement(true); builder->emitIndent(); @@ -769,25 +767,25 @@ void EBPFTable::emitLookup(CodeBuilder *builder, cstring key, cstring value) { builder->blockEnd(true); builder->emitIndent(); cstring new_key = "k"_cs; - builder->appendFormat("struct %s %s = {};", keyTypeName, new_key); + builder->appendFormat("struct %v %v = {};", keyTypeName, new_key); builder->newline(); builder->emitIndent(); - builder->appendFormat("__u32 *chunk = ((__u32 *) &%s);", new_key); + builder->appendFormat("__u32 *chunk = ((__u32 *) &%v);", new_key); builder->newline(); builder->emitIndent(); builder->appendLine("__u32 *mask = ((__u32 *) &next);"); builder->emitIndent(); builder->appendLine("#pragma clang loop unroll(disable)"); builder->emitIndent(); - builder->appendFormat("for (int i = 0; i < sizeof(struct %s_mask) / 4; i++) ", keyTypeName); + builder->appendFormat("for (int i = 0; i < sizeof(struct %v_mask) / 4; i++) ", keyTypeName); builder->blockStart(); - cstring str = absl::StrFormat("*(((__u32 *) &%s) + i)", key); + cstring str = absl::StrFormat("*(((__u32 *) &%v) + i)", key); builder->target->emitTraceMessage( builder, "Control: [Ternary] Masking next 4 bytes of %llx with mask %llx", 2, str, "mask[i]"); builder->emitIndent(); - builder->appendFormat("chunk[i] = ((__u32 *) &%s)[i] & mask[i];", key); + builder->appendFormat("chunk[i] = ((__u32 *) &%v)[i] & mask[i];", key); builder->newline(); builder->blockEnd(true); @@ -805,7 +803,7 @@ void EBPFTable::emitLookup(CodeBuilder *builder, cstring key, cstring value) { builder->append("if (!tuple) "); builder->blockStart(); builder->target->emitTraceMessage( - builder, absl::StrFormat("Control: Tuples map %s not found during ternary lookup. Bug?", + builder, absl::StrFormat("Control: Tuples map %v not found during ternary lookup. Bug?", instanceName) .c_str()); builder->emitIndent(); @@ -815,8 +813,8 @@ void EBPFTable::emitLookup(CodeBuilder *builder, cstring key, cstring value) { builder->emitIndent(); builder->appendFormat( - "struct %s *tuple_entry = " - "bpf_map_lookup_elem(%s, &%s)", + "struct %v *tuple_entry = " + "bpf_map_lookup_elem(%s, &%v)", valueTypeName, "tuple", new_key); builder->endOfStatement(true); builder->emitIndent(); @@ -836,10 +834,10 @@ void EBPFTable::emitLookup(CodeBuilder *builder, cstring key, cstring value) { "tuple_entry->priority"); builder->emitIndent(); - builder->appendFormat("if (%s == NULL || tuple_entry->priority > %s->priority) ", value, value); + builder->appendFormat("if (%v == NULL || tuple_entry->priority > %v->priority) ", value, value); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("%s = tuple_entry;", value); + builder->appendFormat("%v = tuple_entry;", value); builder->newline(); builder->blockEnd(true); @@ -861,7 +859,7 @@ cstring EBPFTable::p4ActionToActionIDName(const IR::P4Action *action) const { cstring actionName = EBPFObject::externalName(action); cstring tableInstance = dataMapName; - return absl::StrFormat("%s_ACT_%s", tableInstance.toUpper(), actionName.toUpper()); + return absl::StrFormat("%v_ACT_%v", tableInstance.toUpper(), actionName.toUpper()); } /// As ternary has precedence over lpm, this function checks if any @@ -1121,7 +1119,7 @@ void EBPFValueSet::emitTypes(CodeBuilder *builder) { if (auto tsl = elemType->to()) { for (auto field : tsl->fields) { - fieldNames.emplace_back(std::make_pair(field->name.name, field->type)); + fieldNames.emplace_back(field->name.name, field->type); } // Do not re-declare this type return; @@ -1147,7 +1145,7 @@ void EBPFValueSet::emitTypes(CodeBuilder *builder) { for (auto field : tuple->components) { cstring name = absl::StrFormat("field%d", i++); fieldEmitter(field, name); - fieldNames.emplace_back(std::make_pair(name, field)); + fieldNames.emplace_back(name, field); } } else { BUG("Type for value_set not implemented %1%", pvs->elementType); diff --git a/backends/ebpf/ebpfType.cpp b/backends/ebpf/ebpfType.cpp index c3a18d1ac81..10f4f7a26aa 100644 --- a/backends/ebpf/ebpfType.cpp +++ b/backends/ebpf/ebpfType.cpp @@ -209,7 +209,7 @@ void EBPFStructType::emitInitializer(CodeBuilder *builder) { if (type->is() || type->is()) { for (auto f : fields) { builder->emitIndent(); - builder->appendFormat(".%s = ", f->field->name.name); + builder->appendFormat(".%v = ", f->field->name); f->type->emitInitializer(builder); builder->append(","); builder->newline(); diff --git a/backends/ebpf/psa/ebpfPipeline.cpp b/backends/ebpf/psa/ebpfPipeline.cpp index 2a3784194c4..35ed3e0f336 100644 --- a/backends/ebpf/psa/ebpfPipeline.cpp +++ b/backends/ebpf/psa/ebpfPipeline.cpp @@ -104,8 +104,8 @@ void EBPFPipeline::emitUserMetadataInstance(CodeBuilder *builder) { void EBPFPipeline::emitLocalHeaderInstancesAsPointers(CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("struct %s *%s;", parser->headerType->to()->name, - parser->headers->name.name); + builder->appendFormat("struct %v *%v;", parser->headerType->to()->name, + parser->headers->name); builder->newline(); } @@ -134,7 +134,7 @@ void EBPFPipeline::emitCPUMAPInitializers(CodeBuilder *builder) { builder->newline(); builder->emitIndent(); builder->emitIndent(); - builder->appendFormat("return %s;", dropReturnCode()); + builder->appendFormat("return %v;", dropReturnCode()); builder->newline(); builder->emitIndent(); builder->appendLine("__builtin_memset(hdrMd, 0, sizeof(struct hdr_md));"); @@ -142,18 +142,18 @@ void EBPFPipeline::emitCPUMAPInitializers(CodeBuilder *builder) { void EBPFPipeline::emitHeadersFromCPUMAP(CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("%s = &(hdrMd->cpumap_hdr);", parser->headers->name.name); + builder->appendFormat("%v = &(hdrMd->cpumap_hdr);", parser->headers->name); } void EBPFPipeline::emitMetadataFromCPUMAP(CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("%s = &(hdrMd->cpumap_usermeta);", control->user_metadata->name.name); + builder->appendFormat("%v = &(hdrMd->cpumap_usermeta);", control->user_metadata->name); } void EBPFPipeline::emitGlobalMetadataInitializer(CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct psa_global_metadata *%s = (struct psa_global_metadata *) skb->cb;", + "struct psa_global_metadata *%v = (struct psa_global_metadata *) skb->cb;", compilerGlobalMetadata); builder->newline(); } @@ -192,18 +192,17 @@ void EBPFIngressPipeline::emitSharedMetadataInitializer(CodeBuilder *builder) { void EBPFIngressPipeline::emitPSAControlInputMetadata(CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct psa_ingress_input_metadata_t %s = {\n" - " .ingress_port = %s,\n" - " .packet_path = %s,\n" - " .parser_error = %s,\n" + "struct psa_ingress_input_metadata_t %v = {\n" + " .ingress_port = %v,\n" + " .packet_path = %v,\n" + " .parser_error = %v,\n" " };", - control->inputStandardMetadata->name.name, inputPortVar.c_str(), packetPathVar.c_str(), - errorVar.c_str()); + control->inputStandardMetadata->name, inputPortVar, packetPathVar, errorVar); builder->newline(); if (shouldEmitTimestamp()) { builder->emitIndent(); - builder->appendFormat("%s.ingress_timestamp = %s", - control->inputStandardMetadata->name.name, timestampVar.c_str()); + builder->appendFormat("%v.ingress_timestamp = %v", control->inputStandardMetadata->name, + timestampVar); builder->endOfStatement(true); } } @@ -212,10 +211,10 @@ void EBPFIngressPipeline::emitPSAControlOutputMetadata(CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct psa_ingress_output_metadata_t %s = {\n" + "struct psa_ingress_output_metadata_t %v = {\n" " .drop = true,\n" " };", - control->outputStandardMetadata->name.name); + control->outputStandardMetadata->name); builder->newline(); builder->newline(); } @@ -228,12 +227,12 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { builder->spc(); // FIXME: use Target to generate metadata type builder->appendFormat( - "int process(%s *%s, %s %s *%s, struct psa_ingress_output_metadata_t *%s, " - "struct psa_global_metadata *%s, ", + "int process(%v *%s, %v %v *%v, struct psa_ingress_output_metadata_t *%v, " + "struct psa_global_metadata *%v, ", builder->target->packetDescriptorType(), model.CPacketName.str(), parser->headerType->to()->kind, - parser->headerType->to()->name, parser->headers->name.name, - control->outputStandardMetadata->name.name, compilerGlobalMetadata); + parser->headerType->to()->name, parser->headers->name, + control->outputStandardMetadata->name, compilerGlobalMetadata); auto type = EBPFTypeFactory::instance->create(deparser->resubmit_meta->type); type->declare(builder, deparser->resubmit_meta->name.name, true); @@ -256,10 +255,10 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { builder->newline(); msgStr = absl::StrFormat( - "%s parser: parsing new packet, input_port=%%d, path=%%d, " + "%v parser: parsing new packet, input_port=%%d, path=%%d, " "pkt_len=%%d", sectionName); - varStr = absl::StrFormat("%s->packet_path", compilerGlobalMetadata); + varStr = absl::StrFormat("%v->packet_path", compilerGlobalMetadata); builder->target->emitTraceMessage(builder, msgStr.c_str(), 3, inputPortVar.c_str(), varStr, lengthVar.c_str()); @@ -274,20 +273,20 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { builder->spc(); builder->blockStart(); emitPSAControlInputMetadata(builder); - msgStr = absl::StrFormat("%s control: packet processing started", sectionName); + msgStr = absl::StrFormat("%v control: packet processing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); control->emit(builder); builder->blockEnd(true); - msgStr = absl::StrFormat("%s control: packet processing finished", sectionName); + msgStr = absl::StrFormat("%v control: packet processing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); // DEPARSER builder->emitIndent(); builder->blockStart(); - msgStr = absl::StrFormat("%s deparser: packet deparsing started", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); deparser->emit(builder); - msgStr = absl::StrFormat("%s deparser: packet deparsing finished", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->blockEnd(true); @@ -297,7 +296,7 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { builder->blockEnd(true); builder->target->emitCodeSection(builder, sectionName); builder->emitIndent(); - builder->appendFormat("int %s(%s *%s)", functionName, builder->target->packetDescriptorType(), + builder->appendFormat("int %v(%v *%s)", functionName, builder->target->packetDescriptorType(), model.CPacketName.str()); builder->spc(); @@ -323,23 +322,23 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { builder->appendFormat("for (int i = 0; i < %d; i++) ", maxResubmitDepth); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("%s.resubmit = 0;", control->outputStandardMetadata->name.name); + builder->appendFormat("%v.resubmit = 0;", control->outputStandardMetadata->name); builder->newline(); builder->emitIndent(); builder->append("ret = process(skb, "); - builder->appendFormat("(%s %s *) %s, &%s, %s, &%s);", + builder->appendFormat("(%v %v *) %v, &%v, %v, &%v);", parser->headerType->to()->kind, - parser->headerType->to()->name, - parser->headers->name.name, control->outputStandardMetadata->name.name, - compilerGlobalMetadata, deparser->resubmit_meta->name.name); + parser->headerType->to()->name, parser->headers->name, + control->outputStandardMetadata->name, compilerGlobalMetadata, + deparser->resubmit_meta->name); builder->newline(); builder->appendFormat( - " if (%s.drop == 1 || %s.resubmit == 0) {\n" + " if (%v.drop == 1 || %v.resubmit == 0) {\n" " break;\n" " }\n", - control->outputStandardMetadata->name.name, control->outputStandardMetadata->name.name); + control->outputStandardMetadata->name, control->outputStandardMetadata->name); builder->blockEnd(true); builder->emitIndent(); @@ -359,28 +358,28 @@ void EBPFIngressPipeline::emit(CodeBuilder *builder) { void EBPFEgressPipeline::emitPSAControlInputMetadata(CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct psa_egress_input_metadata_t %s = {\n" - " .class_of_service = %s,\n" - " .egress_port = %s,\n" - " .packet_path = %s,\n" - " .instance = %s,\n" - " .parser_error = %s,\n" + "struct psa_egress_input_metadata_t %v = {\n" + " .class_of_service = %v,\n" + " .egress_port = %v,\n" + " .packet_path = %v,\n" + " .instance = %v,\n" + " .parser_error = %v,\n" " };", - control->inputStandardMetadata->name.name, priorityVar.c_str(), inputPortVar.c_str(), - packetPathVar.c_str(), pktInstanceVar.c_str(), errorVar.c_str()); + control->inputStandardMetadata->name, priorityVar, inputPortVar, packetPathVar, + pktInstanceVar, errorVar); builder->newline(); if (shouldEmitTimestamp()) { builder->emitIndent(); - builder->appendFormat("%s.egress_timestamp = %s", control->inputStandardMetadata->name.name, - timestampVar.c_str()); + builder->appendFormat("%v.egress_timestamp = %v", control->inputStandardMetadata->name, + timestampVar); builder->endOfStatement(true); } } void EBPFEgressPipeline::emitPSAControlOutputMetadata(CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("struct psa_egress_output_metadata_t %s = {\n", - control->outputStandardMetadata->name.name); + builder->appendFormat("struct psa_egress_output_metadata_t %v = {\n", + control->outputStandardMetadata->name); builder->appendLine( " .clone = false,\n" " .drop = false,\n" @@ -426,10 +425,10 @@ void EBPFEgressPipeline::emit(CodeBuilder *builder) { emitPSAControlInputMetadata(builder); msgStr = absl::StrFormat( - "%s parser: parsing new packet, input_port=%%d, path=%%d, " + "%v parser: parsing new packet, input_port=%%d, path=%%d, " "pkt_len=%%d", sectionName); - varStr = absl::StrFormat("%s->packet_path", compilerGlobalMetadata); + varStr = absl::StrFormat("%v->packet_path", compilerGlobalMetadata); builder->target->emitTraceMessage(builder, msgStr.c_str(), 3, inputPortVar.c_str(), varStr, lengthVar.c_str()); @@ -442,27 +441,26 @@ void EBPFEgressPipeline::emit(CodeBuilder *builder) { builder->append(":"); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s.parser_error = %s", control->inputStandardMetadata->name.name, - errorVar.c_str()); + builder->appendFormat("%v.parser_error = %v", control->inputStandardMetadata->name, errorVar); builder->endOfStatement(true); builder->newline(); builder->emitIndent(); builder->blockStart(); builder->newline(); - msgStr = absl::StrFormat("%s control: packet processing started", sectionName); + msgStr = absl::StrFormat("%v control: packet processing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); control->emit(builder); builder->blockEnd(true); - msgStr = absl::StrFormat("%s control: packet processing finished", sectionName); + msgStr = absl::StrFormat("%v control: packet processing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); // DEPARSER builder->emitIndent(); builder->blockStart(); - msgStr = absl::StrFormat("%s deparser: packet deparsing started", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); deparser->emit(builder); - msgStr = absl::StrFormat("%s deparser: packet deparsing finished", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->blockEnd(true); @@ -482,7 +480,7 @@ void TCIngressPipeline::emitGlobalMetadataInitializer(CodeBuilder *builder) { // workaround to make TC protocol-independent, DO NOT REMOVE builder->emitIndent(); // replace ether_type only if a packet comes from XDP - builder->appendFormat("if (%s->packet_path == NORMAL) ", compilerGlobalMetadata); + builder->appendFormat("if (%v->packet_path == NORMAL) ", compilerGlobalMetadata); builder->blockStart(); builder->emitIndent(); builder->appendFormat("compiler_meta__->mark = %u", packetMark); @@ -556,10 +554,9 @@ void TCIngressPipeline::emitTCWorkaroundUsingCPUMAP(CodeBuilder *builder) { /// - Multicast handling /// - send to port void TCIngressPipeline::emitTrafficManager(CodeBuilder *builder) { - cstring mcast_grp = - absl::StrFormat("%s.multicast_group", control->outputStandardMetadata->name.name); + auto mcast_grp = absl::StrFormat("%v.multicast_group", control->outputStandardMetadata->name); builder->emitIndent(); - builder->appendFormat("if (%s != 0) ", mcast_grp.c_str()); + builder->appendFormat("if (%s != 0) ", mcast_grp); builder->blockStart(); builder->target->emitTraceMessage( builder, "IngressTM: Performing multicast, multicast_group=%u", 1, mcast_grp.c_str()); @@ -570,19 +567,19 @@ void TCIngressPipeline::emitTrafficManager(CodeBuilder *builder) { // In multicast mode, unicast packet is not send builder->target->emitTraceMessage(builder, "IngressTM: Multicast done, dropping source packet"); builder->emitIndent(); - builder->appendFormat("return %s", dropReturnCode()); + builder->appendFormat("return %v", dropReturnCode()); builder->endOfStatement(true); builder->blockEnd(true); builder->emitIndent(); - builder->appendFormat("skb->priority = %s.class_of_service;", - control->outputStandardMetadata->name.name); + builder->appendFormat("skb->priority = %v.class_of_service;", + control->outputStandardMetadata->name); builder->newline(); builder->emitIndent(); - builder->appendFormat("if (!%s.drop && %s.egress_port == 0) ", - control->outputStandardMetadata->name.name, - control->outputStandardMetadata->name.name); + builder->appendFormat("if (!%v.drop && %v.egress_port == 0) ", + control->outputStandardMetadata->name, + control->outputStandardMetadata->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "IngressTM: Sending packet up to the kernel stack"); @@ -600,14 +597,13 @@ void TCIngressPipeline::emitTrafficManager(CodeBuilder *builder) { builder->endOfStatement(true); builder->blockEnd(true); - cstring eg_port = absl::StrFormat("%s.egress_port", control->outputStandardMetadata->name.name); - cstring cos = - absl::StrFormat("%s.class_of_service", control->outputStandardMetadata->name.name); + cstring eg_port = absl::StrFormat("%v.egress_port", control->outputStandardMetadata->name); + cstring cos = absl::StrFormat("%v.class_of_service", control->outputStandardMetadata->name); builder->target->emitTraceMessage( builder, "IngressTM: Sending packet out of port %d with priority %d", 2, eg_port, cos); builder->emitIndent(); - builder->appendFormat("return bpf_redirect(%s.egress_port, 0)", - control->outputStandardMetadata->name.name); + builder->appendFormat("return bpf_redirect(%v.egress_port, 0)", + control->outputStandardMetadata->name); builder->endOfStatement(true); } @@ -616,14 +612,14 @@ void TCEgressPipeline::emitTrafficManager(CodeBuilder *builder) { cstring varStr; // clone support builder->emitIndent(); - builder->appendFormat("if (%s.clone) ", control->outputStandardMetadata->name.name); + builder->appendFormat("if (%v.clone) ", control->outputStandardMetadata->name); builder->blockStart(); builder->emitIndent(); builder->appendFormat( - "do_packet_clones(%s, &clone_session_tbl, %s.clone_session_id, " + "do_packet_clones(%v, &clone_session_tbl, %v.clone_session_id, " "CLONE_E2E, 3)", - contextVar.c_str(), control->outputStandardMetadata->name.name); + contextVar, control->outputStandardMetadata->name); builder->endOfStatement(true); builder->blockEnd(true); @@ -631,11 +627,11 @@ void TCEgressPipeline::emitTrafficManager(CodeBuilder *builder) { // drop support builder->emitIndent(); - builder->appendFormat("if (%s.drop) ", control->outputStandardMetadata->name.name); + builder->appendFormat("if (%v.drop) ", control->outputStandardMetadata->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "EgressTM: Packet dropped due to metadata"); builder->emitIndent(); - builder->appendFormat("return %s;", dropReturnCode()); + builder->appendFormat("return %v;", dropReturnCode()); builder->endOfStatement(true); builder->blockEnd(true); @@ -646,12 +642,12 @@ void TCEgressPipeline::emitTrafficManager(CodeBuilder *builder) { // TODO: there is parameter type `psa_egress_deparser_input_metadata_t` to the deparser, // maybe it should be used instead of `istd`? builder->emitIndent(); - builder->appendFormat("if (%s.egress_port == P4C_PSA_PORT_RECIRCULATE) ", - control->inputStandardMetadata->name.name); + builder->appendFormat("if (%v.egress_port == P4C_PSA_PORT_RECIRCULATE) ", + control->inputStandardMetadata->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "EgressTM: recirculating packet"); builder->emitIndent(); - builder->appendFormat("%s->packet_path = RECIRCULATE", compilerGlobalMetadata); + builder->appendFormat("%v->packet_path = RECIRCULATE", compilerGlobalMetadata); builder->endOfStatement(true); builder->emitIndent(); builder->appendFormat("return bpf_redirect(PSA_PORT_RECIRCULATE, BPF_F_INGRESS)"); @@ -661,14 +657,14 @@ void TCEgressPipeline::emitTrafficManager(CodeBuilder *builder) { builder->newline(); // normal packet to port - varStr = absl::StrFormat("%s->ifindex", contextVar); + varStr = absl::StrFormat("%v->ifindex", contextVar); builder->target->emitTraceMessage(builder, "EgressTM: output packet to port %d", 1, varStr.c_str()); builder->emitIndent(); builder->newline(); builder->emitIndent(); - builder->appendFormat("return %s", forwardReturnCode()); + builder->appendFormat("return %v", forwardReturnCode()); builder->endOfStatement(true); } @@ -677,7 +673,7 @@ void TCEgressPipeline::emitCheckPacketMarkMetadata(CodeBuilder *builder) { builder->appendFormat("if (compiler_meta__->mark != %u) ", packetMark); builder->blockStart(); builder->emitIndent(); - builder->appendFormat("return %s", forwardReturnCode()); + builder->appendFormat("return %v", forwardReturnCode()); builder->endOfStatement(true); builder->blockEnd(true); } @@ -688,21 +684,21 @@ void XDPIngressPipeline::emitGlobalMetadataInitializer(CodeBuilder *builder) { builder->append("struct psa_global_metadata instance = {}"); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("struct psa_global_metadata *%s = &instance;", compilerGlobalMetadata); + builder->appendFormat("struct psa_global_metadata *%v = &instance;", compilerGlobalMetadata); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s->packet_path = NORMAL", compilerGlobalMetadata); + builder->appendFormat("%v->packet_path = NORMAL", compilerGlobalMetadata); builder->endOfStatement(true); } void XDPIngressPipeline::emitTrafficManager(CodeBuilder *builder) { // do not handle multicast; it has been handled earlier by PreDeparser. - cstring portVar = absl::StrFormat("%s.egress_port", control->outputStandardMetadata->name.name); + cstring portVar = absl::StrFormat("%v.egress_port", control->outputStandardMetadata->name); builder->target->emitTraceMessage(builder, "IngressTM: Sending packet out of port %u", 1, portVar); builder->emitIndent(); - builder->appendFormat("return bpf_redirect_map(&tx_port, %s.egress_port%s, 0);", - control->outputStandardMetadata->name.name, "%DEVMAP_SIZE"); + builder->appendFormat("return bpf_redirect_map(&tx_port, %v.egress_port%s, 0);", + control->outputStandardMetadata->name, "%DEVMAP_SIZE"); builder->newline(); } @@ -712,10 +708,10 @@ void XDPEgressPipeline::emitGlobalMetadataInitializer(CodeBuilder *builder) { builder->append("struct psa_global_metadata instance = {}"); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("struct psa_global_metadata *%s = &instance;", compilerGlobalMetadata); + builder->appendFormat("struct psa_global_metadata *%v = &instance;", compilerGlobalMetadata); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s->packet_path = NORMAL_UNICAST", compilerGlobalMetadata); + builder->appendFormat("%v->packet_path = NORMAL_UNICAST", compilerGlobalMetadata); builder->endOfStatement(true); } @@ -724,22 +720,22 @@ void XDPEgressPipeline::emitTrafficManager(CodeBuilder *builder) { builder->newline(); builder->emitIndent(); - builder->appendFormat("if (%s.clone || %s.drop) ", control->outputStandardMetadata->name.name, - control->outputStandardMetadata->name.name); + builder->appendFormat("if (%v.clone || %v.drop) ", control->outputStandardMetadata->name, + control->outputStandardMetadata->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "EgressTM: Packet dropped due to metadata"); builder->emitIndent(); - builder->appendFormat("return %s", dropReturnCode()); + builder->appendFormat("return %v", dropReturnCode()); builder->endOfStatement(true); builder->blockEnd(true); builder->newline(); // normal packet to port - varStr = absl::StrFormat("%s.egress_port", control->inputStandardMetadata->name.name); + varStr = absl::StrFormat("%v.egress_port", control->inputStandardMetadata->name); builder->target->emitTraceMessage(builder, "EgressTM: output packet to port %d", 1, varStr); builder->emitIndent(); - builder->appendFormat("return %s;", this->forwardReturnCode()); + builder->appendFormat("return %v;", this->forwardReturnCode()); builder->newline(); } @@ -756,13 +752,13 @@ void TCTrafficManagerForXDP::emitGlobalMetadataInitializer(CodeBuilder *builder) // if Traffic Manager decided to pass packet to the kernel stack earlier, send it up immediately builder->emitIndent(); - builder->appendFormat("if (%s->pass_to_kernel) return %s;", compilerGlobalMetadata, + builder->appendFormat("if (%v->pass_to_kernel) return %v;", compilerGlobalMetadata, progTarget->forwardReturnCode()); builder->newline(); // Mark packet for egress processing builder->emitIndent(); - builder->appendFormat("%s->mark = %u", compilerGlobalMetadata, packetMark); + builder->appendFormat("%v->mark = %u", compilerGlobalMetadata, packetMark); builder->endOfStatement(true); } @@ -782,11 +778,11 @@ void TCTrafficManagerForXDP::emit(CodeBuilder *builder) { emitReadXDP2TCMetadataFromHead(builder); } - msgStr = absl::StrFormat("%s deparser: packet deparsing started", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->emitIndent(); deparser->emit(builder); - msgStr = absl::StrFormat("%s deparser: packet deparsing finished", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); this->emitTrafficManager(builder); @@ -819,15 +815,15 @@ void TCTrafficManagerForXDP::emitReadXDP2TCMetadataFromHead(CodeBuilder *builder " }\n" " *ether_type = xdp2tc_md.pkt_ether_type;\n"); builder->emitIndent(); - builder->appendFormat("struct psa_ingress_output_metadata_t %s = xdp2tc_md.ostd;", - control->outputStandardMetadata->name.name); + builder->appendFormat("struct psa_ingress_output_metadata_t %v = xdp2tc_md.ostd;", + control->outputStandardMetadata->name); builder->newline(); builder->emitIndent(); emitLocalHeaderInstancesAsPointers(builder); builder->emitIndent(); - builder->appendFormat("%s = &(xdp2tc_md.headers);", parser->headers->name.name); + builder->appendFormat("%v = &(xdp2tc_md.headers);", parser->headers->name); builder->newline(); builder->emitIndent(); @@ -858,7 +854,7 @@ void TCTrafficManagerForXDP::emitReadXDP2TCMetadataFromCPUMAP(CodeBuilder *build builder->emitIndent(); builder->append("if (!md) "); builder->blockStart(); - builder->appendFormat("return %s;", dropReturnCode()); + builder->appendFormat("return %v;", dropReturnCode()); builder->newline(); builder->blockEnd(true); builder->emitIndent(); @@ -866,16 +862,16 @@ void TCTrafficManagerForXDP::emitReadXDP2TCMetadataFromCPUMAP(CodeBuilder *build builder->emitIndent(); emitLocalHeaderInstancesAsPointers(builder); builder->emitIndent(); - builder->appendFormat("%s = &(md->headers);", parser->headers->name.name); + builder->appendFormat("%v = &(md->headers);", parser->headers->name); builder->newline(); builder->emitIndent(); - builder->appendFormat("struct psa_ingress_output_metadata_t %s = md->ostd;", - this->control->outputStandardMetadata->name.name); + builder->appendFormat("struct psa_ingress_output_metadata_t %v = md->ostd;", + this->control->outputStandardMetadata->name); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s = (u8*)%s + BYTES(md->packetOffsetInBits);", headerStartVar.c_str(), - packetStartVar.c_str()); + builder->appendFormat("%v = (u8*)%v + BYTES(md->packetOffsetInBits);", headerStartVar, + packetStartVar); builder->emitIndent(); builder->append( diff --git a/backends/ebpf/psa/ebpfPsaControl.cpp b/backends/ebpf/psa/ebpfPsaControl.cpp index 50954748056..bc0d3f10955 100644 --- a/backends/ebpf/psa/ebpfPsaControl.cpp +++ b/backends/ebpf/psa/ebpfPsaControl.cpp @@ -48,7 +48,7 @@ bool ControlBodyTranslatorPSA::preorder(const IR::AssignmentStatement *a) { ext->originalExternType->name.name == "DirectMeter") { // It is just for trace message before meter execution cstring name = EBPFObject::externalName(ext->object); - auto msgStr = absl::StrFormat("Executing meter: %s", name); + auto msgStr = absl::StrFormat("Executing meter: %v", name); builder->target->emitTraceMessage(builder, msgStr.c_str()); } } diff --git a/backends/ebpf/psa/ebpfPsaDeparser.cpp b/backends/ebpf/psa/ebpfPsaDeparser.cpp index 42a235d3e63..f0ca5b995c9 100644 --- a/backends/ebpf/psa/ebpfPsaDeparser.cpp +++ b/backends/ebpf/psa/ebpfPsaDeparser.cpp @@ -30,8 +30,7 @@ void DeparserBodyTranslatorPSA::processFunction(const P4::ExternFunction *functi auto dprs = deparser->to(); CHECK_NULL(dprs); if (function->method->name.name == "psa_resubmit") { - builder->appendFormat("(!%s->drop && %s->resubmit)", dprs->istd->name.name, - dprs->istd->name.name); + builder->appendFormat("(!%v->drop && %v->resubmit)", dprs->istd->name, dprs->istd->name); } } @@ -141,19 +140,19 @@ void TCIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { builder->emitIndent(); // clone support - builder->appendFormat("if (%s->clone) ", istd->name.name); + builder->appendFormat("if (%v->clone) ", istd->name); builder->blockStart(); builder->emitIndent(); builder->appendFormat( - "do_packet_clones(%s, &clone_session_tbl, %s->clone_session_id," + "do_packet_clones(%s, &clone_session_tbl, %v->clone_session_id," " CLONE_I2E, 1);", - program->model.CPacketName.str(), istd->name.name); + program->model.CPacketName.str(), istd->name); builder->newline(); builder->blockEnd(true); // early drop builder->emitIndent(); - builder->appendFormat("if (%s->drop) ", istd->name.name); + builder->appendFormat("if (%v->drop) ", istd->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: dropping packet.."); builder->emitIndent(); @@ -162,7 +161,7 @@ void TCIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { // if packet should be resubmitted, we skip deparser builder->emitIndent(); - builder->appendFormat("if (%s->resubmit) ", istd->name.name); + builder->appendFormat("if (%v->resubmit) ", istd->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: resubmitting packet, " @@ -170,7 +169,7 @@ void TCIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { builder->emitIndent(); CHECK_NULL(program); auto pipeline = program->checkedTo(); - builder->appendFormat("%s->packet_path = RESUBMIT;", pipeline->compilerGlobalMetadata); + builder->appendFormat("%v->packet_path = RESUBMIT;", pipeline->compilerGlobalMetadata); builder->newline(); builder->emitIndent(); builder->appendLine("return TC_ACT_UNSPEC;"); @@ -181,13 +180,13 @@ void TCIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { void TCIngressDeparserForTrafficManagerPSA::emitPreDeparser(CodeBuilder *builder) { // clone support builder->emitIndent(); - builder->appendFormat("if (%s.clone) ", this->istd->name.name); + builder->appendFormat("if (%v.clone) ", this->istd->name); builder->blockStart(); builder->emitIndent(); builder->appendFormat( - "do_packet_clones(%s, &clone_session_tbl, %s.clone_session_id," + "do_packet_clones(%s, &clone_session_tbl, %v.clone_session_id," " CLONE_I2E, 1);", - program->model.CPacketName.str(), this->istd->name.name); + program->model.CPacketName.str(), this->istd->name); builder->newline(); builder->blockEnd(true); } @@ -208,14 +207,14 @@ void XDPIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { builder->emitIndent(); builder->appendLine("struct xdp2tc_metadata xdp2tc_md = {};"); builder->emitIndent(); - builder->appendFormat("xdp2tc_md.headers = *%s", this->parserHeaders->name.name); + builder->appendFormat("xdp2tc_md.headers = *%v", this->parserHeaders->name); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("xdp2tc_md.ostd = *%s", this->istd->name.name); + builder->appendFormat("xdp2tc_md.ostd = *%v", this->istd->name); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("xdp2tc_md.packetOffsetInBits = 8 * PTR_DIFF_BYTES(%s, %s)", + builder->appendFormat("xdp2tc_md.packetOffsetInBits = 8 * PTR_DIFF_BYTES(%v, %v)", this->program->headerStartVar, this->program->packetStartVar); builder->endOfStatement(true); builder->append( @@ -260,11 +259,11 @@ void XDPIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { } builder->target->emitTraceMessage(builder, "Sending packet up to TC for cloning or to kernel"); builder->emitIndent(); - builder->appendFormat("return %s", builder->target->forwardReturnCode()); + builder->appendFormat("return %v", builder->target->forwardReturnCode()); builder->endOfStatement(true); builder->blockEnd(true); builder->emitIndent(); - builder->appendFormat("if (%s->drop) ", istd->name.name); + builder->appendFormat("if (%v->drop) ", istd->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: dropping packet.."); builder->emitIndent(); @@ -273,13 +272,13 @@ void XDPIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { // if packet should be resubmitted, we skip deparser builder->emitIndent(); - builder->appendFormat("if (%s->resubmit) ", istd->name.name); + builder->appendFormat("if (%v->resubmit) ", istd->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: resubmitting packet, " "skipping deparser.."); builder->emitIndent(); - builder->appendFormat("%s->packet_path = RESUBMIT;", + builder->appendFormat("%v->packet_path = RESUBMIT;", program->to()->compilerGlobalMetadata); builder->newline(); builder->emitIndent(); @@ -290,7 +289,7 @@ void XDPIngressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { // =====================XDPEgressDeparserPSA============================= void XDPEgressDeparserPSA::emitPreDeparser(CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("if (%s.drop) ", istd->name.name); + builder->appendFormat("if (%v.drop) ", istd->name); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: dropping packet.."); builder->emitIndent(); diff --git a/backends/ebpf/psa/ebpfPsaGen.cpp b/backends/ebpf/psa/ebpfPsaGen.cpp index f6ba5a7371a..56e6b990f40 100644 --- a/backends/ebpf/psa/ebpfPsaGen.cpp +++ b/backends/ebpf/psa/ebpfPsaGen.cpp @@ -46,7 +46,7 @@ class PSAErrorCodesGen : public Inspector { } builder->emitIndent(); - builder->appendFormat("static const ParserError_t %s = %d", decl->name.name, id); + builder->appendFormat("static const ParserError_t %v = %d", decl->name, id); builder->endOfStatement(true); // Type ParserError_t is u8, which can have values from 0 to 255. @@ -567,7 +567,7 @@ void PSAArchXDP::emitInitializerSection(CodeBuilder *builder) const { void PSAArchXDP::emitXDP2TCInternalStructures(CodeBuilder *builder) const { builder->appendFormat( "struct xdp2tc_metadata {\n" - " struct %s headers;\n" + " struct %v headers;\n" " struct psa_ingress_output_metadata_t ostd;\n" " __u32 packetOffsetInBits;\n" " __u16 pkt_ether_type;\n" diff --git a/backends/ebpf/psa/ebpfPsaTable.cpp b/backends/ebpf/psa/ebpfPsaTable.cpp index 517fbf2720b..d65d01b61e2 100644 --- a/backends/ebpf/psa/ebpfPsaTable.cpp +++ b/backends/ebpf/psa/ebpfPsaTable.cpp @@ -158,7 +158,7 @@ class EBPFTablePSAInitializerCodeGen : public CodeGenInspector { cstring mask = EBPFInitializerUtils::genHexStr(rc->value, width, expr->right); builder->append("{ "); for (size_t i = 0; i < value.size() / 2; ++i) - builder->appendFormat("(0x%s & 0x%s), ", value.substr(2 * i, 2), + builder->appendFormat("(0x%v & 0x%v), ", value.substr(2 * i, 2), mask.substr(2 * i, 2)); builder->append("}"); } @@ -239,11 +239,11 @@ class EBPFTablePSAInitializerCodeGen : public CodeGenInspector { builder->blockStart(); builder->emitIndent(); - builder->appendFormat(".action = %s,", fullActionName); + builder->appendFormat(".action = %v,", fullActionName); builder->newline(); builder->emitIndent(); - builder->appendFormat(".u = {.%s = {", actionName.c_str()); + builder->appendFormat(".u = {.%v = {", actionName); for (auto p : *mi->substitution.getParametersInArgumentOrder()) { visit(mi->substitution.lookup(p)); builder->append(", "); @@ -614,14 +614,14 @@ void EBPFTablePSA::emitMapUpdateTraceMsg(CodeBuilder *builder, cstring mapName, builder->appendFormat("if (%s) ", returnCode.c_str()); builder->blockStart(); cstring msgStr = - absl::StrFormat("Map initializer: Error while map (%s) update, code: %s", mapName, "%d"); + absl::StrFormat("Map initializer: Error while map (%v) update, code: %s", mapName, "%d"); builder->target->emitTraceMessage(builder, msgStr, 1, returnCode.c_str()); builder->blockEnd(false); builder->append(" else "); builder->blockStart(); - msgStr = absl::StrFormat("Map initializer: Map (%s) update succeed", mapName); + msgStr = absl::StrFormat("Map initializer: Map (%v) update succeed", mapName); builder->target->emitTraceMessage(builder, msgStr); builder->blockEnd(true); } @@ -679,7 +679,7 @@ void EBPFTablePSA::emitTernaryConstEntriesInitializer(CodeBuilder *builder) { // emit key head mask cstring headName = program->refMap->newName("key_mask"); builder->emitIndent(); - builder->appendFormat("struct %s_mask %s = {0}", keyTypeName, headName); + builder->appendFormat("struct %v_mask %v = {0}", keyTypeName, headName); builder->endOfStatement(true); // emit key masks @@ -695,7 +695,7 @@ void EBPFTablePSA::emitTernaryConstEntriesInitializer(CodeBuilder *builder) { builder->newline(); builder->emitIndent(); - builder->appendFormat("%s(0, 0, &%s, &%s, &%s, &%s, NULL, NULL)", addPrefixFunctionName, + builder->appendFormat("%v(0, 0, &%v, &%v, &%v, &%v, NULL, NULL)", addPrefixFunctionName, tuplesMapName, prefixesMapName, headName, valueMask); builder->endOfStatement(true); builder->newline(); @@ -722,23 +722,22 @@ void EBPFTablePSA::emitTernaryConstEntriesInitializer(CodeBuilder *builder) { // construct keys array builder->newline(); builder->emitIndent(); - builder->appendFormat("void *%s[] = {", keysArray); - for (auto keyName : keyNames) builder->appendFormat("&%s,", keyName); + builder->appendFormat("void *%v[] = {", keysArray); + for (auto keyName : keyNames) builder->appendFormat("&%v,", keyName); builder->append("}"); builder->endOfStatement(true); // construct values array builder->emitIndent(); - builder->appendFormat("void *%s[] = {", valuesArray); - for (auto valueName : valueNames) builder->appendFormat("&%s,", valueName); + builder->appendFormat("void *%v[] = {", valuesArray); + for (auto valueName : valueNames) builder->appendFormat("&%v,", valueName); builder->append("}"); builder->endOfStatement(true); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s(%s, %s, &%s, &%s, &%s, &%s, %s, %s)", addPrefixFunctionName, - cstring::to_cstring(sameMaskEntries.size()), - cstring::to_cstring(tuple_id), tuplesMapName, prefixesMapName, + builder->appendFormat("%v(%d, %d, &%v, &%v, &%v, &%v, %v, %v)", addPrefixFunctionName, + sameMaskEntries.size(), tuple_id, tuplesMapName, prefixesMapName, keyMaskVarName, valueMask, keysArray, valuesArray); builder->endOfStatement(true); @@ -784,12 +783,12 @@ void EBPFTablePSA::emitKeyMasks(CodeBuilder *builder, EntriesGroupedByMask_t &en keyMasksNames.push_back(keyFieldName); builder->emitIndent(); - builder->appendFormat("struct %s_mask %s = {0}", keyTypeName, keyFieldName); + builder->appendFormat("struct %v_mask %v = {0}", keyTypeName, keyFieldName); builder->endOfStatement(true); builder->emitIndent(); cstring keyFieldNamePtr = program->refMap->newName(keyFieldName + "_ptr"); - builder->appendFormat("char *%s = &%s.mask", keyFieldNamePtr, keyFieldName); + builder->appendFormat("char *%v = &%v.mask", keyFieldNamePtr, keyFieldName); builder->endOfStatement(true); for (size_t i = 0; i < keyGenerator->keyElements.size(); i++) { @@ -803,11 +802,11 @@ void EBPFTablePSA::emitKeyMasks(CodeBuilder *builder, EntriesGroupedByMask_t &en expr->apply(cg); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("__builtin_memcpy(%s, &%s, sizeof(%s))", keyFieldNamePtr, + builder->appendFormat("__builtin_memcpy(%v, &%v, sizeof(%v))", keyFieldNamePtr, fieldName, fieldName); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("%s = %s + sizeof(%s)", keyFieldNamePtr, keyFieldNamePtr, + builder->appendFormat("%v = %v + sizeof(%v)", keyFieldNamePtr, keyFieldNamePtr, fieldName); builder->endOfStatement(true); } @@ -817,21 +816,21 @@ void EBPFTablePSA::emitKeyMasks(CodeBuilder *builder, EntriesGroupedByMask_t &en void EBPFTablePSA::emitValueMask(CodeBuilder *builder, const cstring valueMask, const cstring nextMask, int tupleId) const { builder->emitIndent(); - builder->appendFormat("struct %s_mask %s = {0}", valueTypeName, valueMask); + builder->appendFormat("struct %v_mask %v = {0}", valueTypeName, valueMask); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("%s.tuple_id = %s", valueMask, cstring::to_cstring(tupleId)); + builder->appendFormat("%v.tuple_id = %d", valueMask, tupleId); builder->endOfStatement(true); builder->emitIndent(); if (nextMask.isNullOrEmpty()) { - builder->appendFormat("%s.has_next = 0", valueMask); + builder->appendFormat("%v.has_next = 0", valueMask); builder->endOfStatement(true); } else { - builder->appendFormat("%s.next_tuple_mask = %s", valueMask, nextMask); + builder->appendFormat("%v.next_tuple_mask = %v", valueMask, nextMask); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("%s.has_next = 1", valueMask); + builder->appendFormat("%v.has_next = 1", valueMask); builder->endOfStatement(true); } } diff --git a/backends/ebpf/psa/externs/ebpfPsaCounter.cpp b/backends/ebpf/psa/externs/ebpfPsaCounter.cpp index de06a581f3f..4511cb09eee 100644 --- a/backends/ebpf/psa/externs/ebpfPsaCounter.cpp +++ b/backends/ebpf/psa/externs/ebpfPsaCounter.cpp @@ -260,7 +260,7 @@ void EBPFCounterPSA::emitCounterUpdate(CodeBuilder *builder, const cstring targe if (type == CounterType::BYTES || type == CounterType::PACKETS_AND_BYTES) { builder->emitIndent(); - builder->appendFormat("__sync_fetch_and_add(&(%sbytes), %s)", targetWAccess.c_str(), + builder->appendFormat("__sync_fetch_and_add(&(%vbytes), %v)", targetWAccess, program->lengthVar); builder->endOfStatement(true); diff --git a/backends/ebpf/psa/externs/ebpfPsaDigest.cpp b/backends/ebpf/psa/externs/ebpfPsaDigest.cpp index 03ef4d8ef34..4b8f38c15ee 100644 --- a/backends/ebpf/psa/externs/ebpfPsaDigest.cpp +++ b/backends/ebpf/psa/externs/ebpfPsaDigest.cpp @@ -82,7 +82,7 @@ class EBPFDigestPSAValueVisitor : public CodeGenInspector { for (const auto *f : se->components) { auto type = typeMap->getType(f->expression); - cstring path = absl::StrFormat("%s.%s", tmpVar, f->name.name); + cstring path = absl::StrFormat("%v.%v", tmpVar, f->name); codegen->emitAssignStatement(type, nullptr, path, f->expression); builder->newline(); } @@ -123,7 +123,7 @@ void EBPFDigestPSA::emitTypes(CodeBuilder *builder) { } void EBPFDigestPSA::emitInstance(CodeBuilder *builder) const { - builder->appendFormat("REGISTER_TABLE_NO_KEY_TYPE(%s, BPF_MAP_TYPE_QUEUE, 0, ", instanceName); + builder->appendFormat("REGISTER_TABLE_NO_KEY_TYPE(%v, BPF_MAP_TYPE_QUEUE, 0, ", instanceName); if (valueTypeName.isNullOrEmpty()) { valueType->declare(builder, cstring::empty, false); @@ -151,7 +151,7 @@ void EBPFDigestPSA::processMethod(CodeBuilder *builder, cstring method, void EBPFDigestPSA::emitPushElement(CodeBuilder *builder, const IR::Expression *elem, Inspector *codegen) const { builder->emitIndent(); - builder->appendFormat("bpf_map_push_elem(&%s, &", instanceName); + builder->appendFormat("bpf_map_push_elem(&%v, &", instanceName); codegen->visit(elem); builder->append(", BPF_EXIST)"); builder->endOfStatement(true); @@ -159,7 +159,7 @@ void EBPFDigestPSA::emitPushElement(CodeBuilder *builder, const IR::Expression * void EBPFDigestPSA::emitPushElement(CodeBuilder *builder, cstring elem) const { builder->emitIndent(); - builder->appendFormat("bpf_map_push_elem(&%s, &%s, BPF_EXIST)", instanceName, elem); + builder->appendFormat("bpf_map_push_elem(&%v, &%v, BPF_EXIST)", instanceName, elem); builder->endOfStatement(true); } diff --git a/backends/ebpf/psa/externs/ebpfPsaMeter.cpp b/backends/ebpf/psa/externs/ebpfPsaMeter.cpp index c04296f1d4b..72da775c444 100644 --- a/backends/ebpf/psa/externs/ebpfPsaMeter.cpp +++ b/backends/ebpf/psa/externs/ebpfPsaMeter.cpp @@ -169,12 +169,12 @@ void EBPFMeterPSA::emitExecute(CodeBuilder *builder, const P4::ExternMethod *met } if (type == BYTES) { - builder->appendFormat("meter_execute_bytes%s(&%s, &%s, ", functionNameSuffix, instanceName, - pipeline->lengthVar.c_str()); + builder->appendFormat("meter_execute_bytes%v(&%v, &%v, ", functionNameSuffix, instanceName, + pipeline->lengthVar); this->emitIndex(builder, method, translator); builder->appendFormat(", &%s", pipeline->timestampVar.c_str()); } else { - builder->appendFormat("meter_execute_packets%s(&%s, ", functionNameSuffix, instanceName); + builder->appendFormat("meter_execute_packets%v(&%v, ", functionNameSuffix, instanceName); this->emitIndex(builder, method, translator); builder->appendFormat(", &%s", pipeline->timestampVar.c_str()); } @@ -215,12 +215,11 @@ void EBPFMeterPSA::emitDirectExecute(CodeBuilder *builder, const P4::ExternMetho cstring lockVar = valuePtr + "->" + spinlockField; cstring valueMeter = valuePtr + "->" + instanceName; if (type == BYTES) { - builder->appendFormat("meter_execute_bytes_value%s(&%s, &%s, &%s, &%s", functionNameSuffix, - valueMeter, lockVar, pipeline->lengthVar.c_str(), - pipeline->timestampVar.c_str()); + builder->appendFormat("meter_execute_bytes_value%v(&%v, &%v, &%v, &%v", functionNameSuffix, + valueMeter, lockVar, pipeline->lengthVar, pipeline->timestampVar); } else { - builder->appendFormat("meter_execute_packets_value%s(&%s, &%s, &%s", functionNameSuffix, - valueMeter, lockVar, pipeline->timestampVar.c_str()); + builder->appendFormat("meter_execute_packets_value%v(&%v, &%v, &%v", functionNameSuffix, + valueMeter, lockVar, pipeline->timestampVar); } if (method->expr->arguments->size() == 1) { diff --git a/backends/ebpf/psa/externs/ebpfPsaRegister.cpp b/backends/ebpf/psa/externs/ebpfPsaRegister.cpp index 5e36e9953a4..54ccf47cf20 100644 --- a/backends/ebpf/psa/externs/ebpfPsaRegister.cpp +++ b/backends/ebpf/psa/externs/ebpfPsaRegister.cpp @@ -136,7 +136,7 @@ void EBPFRegisterPSA::emitInitializer(CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat("if (%s) ", ret.c_str()); builder->blockStart(); - cstring msgStr = absl::StrFormat("Map initializer: Error while map (%s) update, code: %s", + cstring msgStr = absl::StrFormat("Map initializer: Error while map (%v) update, code: %s", instanceName, "%d"); builder->target->emitTraceMessage(builder, msgStr, 1, ret.c_str()); @@ -231,7 +231,7 @@ void EBPFRegisterPSA::emitRegisterWrite(CodeBuilder *builder, const P4::ExternMe builder->emitIndent(); builder->appendFormat("if (%s) ", ret.c_str()); builder->blockStart(); - msgStr = absl::StrFormat("Register: Error while map (%s) update, code: %s", instanceName, "%d"); + msgStr = absl::StrFormat("Register: Error while map (%v) update, code: %s", instanceName, "%d"); builder->target->emitTraceMessage(builder, msgStr, 1, ret.c_str()); builder->blockEnd(true); diff --git a/backends/ebpf/psa/externs/ebpfPsaTableImplementation.cpp b/backends/ebpf/psa/externs/ebpfPsaTableImplementation.cpp index 483907a5654..86205b225b1 100644 --- a/backends/ebpf/psa/externs/ebpfPsaTableImplementation.cpp +++ b/backends/ebpf/psa/externs/ebpfPsaTableImplementation.cpp @@ -279,7 +279,7 @@ void EBPFActionSelectorPSA::emitInitializer(CodeBuilder *builder) { if (action->name.originalName == P4::P4CoreLibrary::instance().noAction.name) { builder->append(".action = 0,"); } else { - builder->appendFormat(".action = %s,", p4ActionToActionIDName(action)); + builder->appendFormat(".action = %v,", p4ActionToActionIDName(action)); } builder->newline(); builder->blockEnd(false); diff --git a/backends/ebpf/psa/xdpHelpProgram.h b/backends/ebpf/psa/xdpHelpProgram.h index a1311fa8b0e..defea583400 100644 --- a/backends/ebpf/psa/xdpHelpProgram.h +++ b/backends/ebpf/psa/xdpHelpProgram.h @@ -104,7 +104,7 @@ class XDPHelpProgram : public EBPFProgram { void emit(CodeBuilder *builder) { builder->target->emitCodeSection(builder, sectionName); builder->emitIndent(); - builder->appendFormat("int %s(struct xdp_md *%s)", functionName, model.CPacketName.str()); + builder->appendFormat("int %v(struct xdp_md *%s)", functionName, model.CPacketName.str()); builder->spc(); builder->blockStart(); builder->emitIndent(); diff --git a/backends/ebpf/target.cpp b/backends/ebpf/target.cpp index f8eec4ad258..c58926bc33c 100644 --- a/backends/ebpf/target.cpp +++ b/backends/ebpf/target.cpp @@ -42,33 +42,32 @@ void KernelSamplesTarget::emitIncludes(Util::SourceCodeBuilder *builder) const { void KernelSamplesTarget::emitResizeBuffer(Util::SourceCodeBuilder *builder, cstring buffer, cstring offsetVar) const { - builder->appendFormat("bpf_skb_adjust_room(%s, %s, 1, 0)", buffer, offsetVar); + builder->appendFormat("bpf_skb_adjust_room(%v, %v, 1, 0)", buffer, offsetVar); } void KernelSamplesTarget::emitTableLookup(Util::SourceCodeBuilder *builder, cstring tblName, cstring key, cstring value) const { if (!value.isNullOrEmpty()) builder->appendFormat("%s = ", value.c_str()); - builder->appendFormat("BPF_MAP_LOOKUP_ELEM(%s, &%s)", tblName.c_str(), key.c_str()); + builder->appendFormat("BPF_MAP_LOOKUP_ELEM(%v, &%v)", tblName, key); } void KernelSamplesTarget::emitTableUpdate(Util::SourceCodeBuilder *builder, cstring tblName, cstring key, cstring value) const { - builder->appendFormat("BPF_MAP_UPDATE_ELEM(%s, &%s, &%s, BPF_ANY);", tblName.c_str(), - key.c_str(), value.c_str()); + builder->appendFormat("BPF_MAP_UPDATE_ELEM(%v, &%v, &%v, BPF_ANY);", tblName, key, value); } void KernelSamplesTarget::emitUserTableUpdate(Util::SourceCodeBuilder *builder, cstring tblName, cstring key, cstring value) const { - builder->appendFormat("BPF_USER_MAP_UPDATE_ELEM(%s, &%s, &%s, BPF_ANY);", tblName.c_str(), - key.c_str(), value.c_str()); + builder->appendFormat("BPF_USER_MAP_UPDATE_ELEM(%v, &%v, &%v, BPF_ANY);", tblName, key, value); } void KernelSamplesTarget::emitTableDecl(Util::SourceCodeBuilder *builder, cstring tblName, TableKind tableKind, cstring keyType, cstring valueType, unsigned size) const { cstring kind, flags; - static constexpr char registerTable[] = "REGISTER_TABLE(%s, %s, %s, %s, %d)"; - static constexpr char registerTableWithFlags[] = "REGISTER_TABLE_FLAGS(%s, %s, %s, %s, %d, %s)"; + static constexpr std::string_view registerTable = "REGISTER_TABLE(%v, %v, %v, %v, %d)"; + static constexpr std::string_view registerTableWithFlags = + "REGISTER_TABLE_FLAGS(%v, %v, %v, %v, %d, %v)"; kind = getBPFMapType(tableKind); @@ -93,11 +92,10 @@ void KernelSamplesTarget::emitTableDecl(Util::SourceCodeBuilder *builder, cstrin } if (flags.isNullOrEmpty()) { - builder->appendFormat(registerTable, tblName.c_str(), kind.c_str(), keyType.c_str(), - valueType.c_str(), size); + builder->appendFormat(registerTable, tblName, kind, keyType, valueType, size); } else { - builder->appendFormat(registerTableWithFlags, tblName.c_str(), kind.c_str(), - keyType.c_str(), valueType.c_str(), size, flags); + builder->appendFormat(registerTableWithFlags, tblName, kind, keyType, valueType, size, + flags); } builder->newline(); annotateTableWithBTF(builder, tblName, keyType, valueType); @@ -122,9 +120,10 @@ void KernelSamplesTarget::emitMapInMapDecl(Util::SourceCodeBuilder *builder, cst BUG("Unsupported type of outer map for map-in-map"); } - static constexpr char registerOuterTable[] = - "REGISTER_TABLE_OUTER(%s, %s_OF_MAPS, %s, %s, %d, %d, %s)"; - static constexpr char registerInnerTable[] = "REGISTER_TABLE_INNER(%s, %s, %s, %s, %d, %d, %d)"; + static constexpr std::string_view registerOuterTable = + "REGISTER_TABLE_OUTER(%v, %v_OF_MAPS, %v, %s, %d, %d, %v)"; + static constexpr std::string_view registerInnerTable = + "REGISTER_TABLE_INNER(%v, %v, %v, %v, %d, %d, %d)"; innerMapIndex++; @@ -144,18 +143,18 @@ void KernelSamplesTarget::emitMapInMapDecl(Util::SourceCodeBuilder *builder, cst void KernelSamplesTarget::emitLicense(Util::SourceCodeBuilder *builder, cstring license) const { builder->emitIndent(); - builder->appendFormat("char _license[] SEC(\"license\") = \"%s\";", license.c_str()); + builder->appendFormat(R"(char _license[] SEC("license") = "%v";)", license); builder->newline(); } void KernelSamplesTarget::emitCodeSection(Util::SourceCodeBuilder *builder, cstring sectionName) const { - builder->appendFormat("SEC(\"%s\")\n", sectionName.c_str()); + builder->appendFormat("SEC(\"%v\")\n", sectionName); } void KernelSamplesTarget::emitMain(Util::SourceCodeBuilder *builder, cstring functionName, cstring argName) const { - builder->appendFormat("int %s(SK_BUFF *%s)", functionName.c_str(), argName.c_str()); + builder->appendFormat("int %v(SK_BUFF *%v)", functionName, argName); } void KernelSamplesTarget::emitPreamble(Util::SourceCodeBuilder *builder) const { @@ -199,21 +198,20 @@ void KernelSamplesTarget::emitTraceMessage(Util::SourceCodeBuilder *builder, con va_end(ap); builder->emitIndent(); - builder->appendFormat("bpf_trace_message(%s);", msg); + builder->appendFormat("bpf_trace_message(%v);", msg); builder->newline(); } void KernelSamplesTarget::annotateTableWithBTF(Util::SourceCodeBuilder *builder, cstring name, cstring keyType, cstring valueType) const { - builder->appendFormat("BPF_ANNOTATE_KV_PAIR(%s, %s, %s)", name.c_str(), keyType.c_str(), - valueType.c_str()); + builder->appendFormat("BPF_ANNOTATE_KV_PAIR(%v, %v, %v)", name, keyType, valueType); builder->newline(); } ////////////////////////////////////////////////////////////// void XdpTarget::emitResizeBuffer(Util::SourceCodeBuilder *builder, cstring buffer, cstring offsetVar) const { - builder->appendFormat("bpf_xdp_adjust_head(%s, -%s)", buffer, offsetVar); + builder->appendFormat("bpf_xdp_adjust_head(%v, -%v)", buffer, offsetVar); } ////////////////////////////////////////////////////////////// @@ -225,8 +223,8 @@ void TestTarget::emitIncludes(Util::SourceCodeBuilder *builder) const { void TestTarget::emitTableDecl(Util::SourceCodeBuilder *builder, cstring tblName, TableKind, cstring keyType, cstring valueType, unsigned size) const { - builder->appendFormat("REGISTER_TABLE(%s, 0 /* unused */,", tblName.c_str()); - builder->appendFormat("sizeof(%s), sizeof(%s), %d)", keyType.c_str(), valueType.c_str(), size); + builder->appendFormat("REGISTER_TABLE(%v, 0 /* unused */,", tblName); + builder->appendFormat("sizeof(%v), sizeof(%v), %d)", keyType, valueType, size); builder->newline(); } diff --git a/backends/ebpf/target.h b/backends/ebpf/target.h index 3bc414514c5..5cab0095029 100644 --- a/backends/ebpf/target.h +++ b/backends/ebpf/target.h @@ -258,8 +258,7 @@ class XdpTarget : public KernelSamplesTarget { cstring offsetVar) const override; void emitMain(Util::SourceCodeBuilder *builder, cstring functionName, cstring argName) const override { - builder->appendFormat("int %s(%s *%s)", functionName.c_str(), packetDescriptorType(), - argName.c_str()); + builder->appendFormat("int %v(%v *%v)", functionName, packetDescriptorType(), argName); } }; diff --git a/backends/p4tools/modules/testgen/targets/bmv2/p4_asserts_parser.cpp b/backends/p4tools/modules/testgen/targets/bmv2/p4_asserts_parser.cpp index 18ef6041215..4867a655191 100644 --- a/backends/p4tools/modules/testgen/targets/bmv2/p4_asserts_parser.cpp +++ b/backends/p4tools/modules/testgen/targets/bmv2/p4_asserts_parser.cpp @@ -130,7 +130,7 @@ const IR::Expression *makeConstant(Token input, const IdenitifierTypeMap &typeMa for (const auto &[identifier, keyType] : typeMap) { auto annoSize = identifier.size(); auto tokenLength = inputStr.length(); - if (inputStr.compare(tokenLength - annoSize, annoSize, identifier) != 0) { + if (inputStr.compare(tokenLength - annoSize, annoSize, identifier.string_view()) != 0) { continue; } if (const auto *bit = keyType->to()) { diff --git a/backends/tc/ebpfCodeGen.cpp b/backends/tc/ebpfCodeGen.cpp index de0e4b596ca..052cc6f2db0 100644 --- a/backends/tc/ebpfCodeGen.cpp +++ b/backends/tc/ebpfCodeGen.cpp @@ -136,7 +136,7 @@ void PNAEbpfGenerator::emitP4TCActionParam(EBPF::CodeBuilder *builder) const { cstring placeholder = tblName + "_" + defaultActionName + "_" + paramName; cstring typeName = param->paramDetail->getParamType(); builder->emitIndent(); - builder->appendFormat("%s %s", typeName, placeholder); + builder->appendFormat("%v %v", typeName, placeholder); builder->endOfStatement(true); } } @@ -151,7 +151,7 @@ void PNAEbpfGenerator::emitP4TCActionParam(EBPF::CodeBuilder *builder) const { cstring placeholder = tblName + "_" + defaultActionName + "_" + paramName; cstring typeName = param->paramDetail->getParamType(); builder->emitIndent(); - builder->appendFormat("%s %s", typeName, placeholder); + builder->appendFormat("%v %v", typeName, placeholder); builder->endOfStatement(true); } } @@ -183,7 +183,7 @@ void PNAArchTC::emit(EBPF::CodeBuilder *builder) const { * 2. Include header file. */ cstring headerFile = getProgramName() + "_parser.h"; - builder->appendFormat("#include \"%s\"", headerFile); + builder->appendFormat("#include \"%v\"", headerFile); builder->newline(); /* * 3. Headers, structs @@ -222,7 +222,7 @@ void PNAArchTC::emitParser(EBPF::CodeBuilder *builder) const { */ xdp->emitGeneratedComment(builder); cstring headerFile = getProgramName() + "_parser.h"; - builder->appendFormat("#include \"%s\"", headerFile); + builder->appendFormat("#include \"%v\"", headerFile); builder->newline(); builder->newline(); builder->appendLine("struct p4tc_filter_fields p4tc_filter_fields;"); @@ -260,11 +260,11 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { // FIXME: use Target to generate metadata type cstring func_name = (name == "tc-parse") ? "run_parser"_cs : "process"_cs; builder->appendFormat( - "int %s(%s *%s, %s %s *%s, " - "struct pna_global_metadata *%s", + "int %v(%v *%s, %v %v *%v, " + "struct pna_global_metadata *%v", func_name, builder->target->packetDescriptorType(), model.CPacketName.str(), parser->headerType->as().kind, - parser->headerType->as().name, parser->headers->name.name, + parser->headerType->as().name, parser->headers->name, compilerGlobalMetadata); builder->append(")"); @@ -290,7 +290,7 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { builder->newline(); builder->emitIndent(); builder->emitIndent(); - builder->appendFormat("return %s;", dropReturnCode()); + builder->appendFormat("return %v;", dropReturnCode()); builder->newline(); builder->emitIndent(); builder->appendFormat("unsigned %s = hdrMd->%s;", offsetVar.c_str(), offsetVar.c_str()); @@ -307,10 +307,10 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { if (name == "tc-parse") { msgStr = absl::StrFormat( - "%s parser: parsing new packet, input_port=%%d, path=%%d, " + "%v parser: parsing new packet, input_port=%%d, path=%%d, " "pkt_len=%%d", sectionName); - varStr = absl::StrFormat("%s->packet_path", compilerGlobalMetadata); + varStr = absl::StrFormat("%v->packet_path", compilerGlobalMetadata); builder->target->emitTraceMessage(builder, msgStr.c_str(), 3, inputPortVar.c_str(), varStr, lengthVar.c_str()); @@ -327,21 +327,21 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { if (name == "tc-ingress") { // CONTROL builder->blockStart(); - msgStr = absl::StrFormat("%s control: packet processing started", sectionName); + msgStr = absl::StrFormat("%v control: packet processing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); ((EBPFControlPNA *)control)->emitExternDefinition(builder); control->emit(builder); builder->blockEnd(true); - msgStr = absl::StrFormat("%s control: packet processing finished", sectionName); + msgStr = absl::StrFormat("%v control: packet processing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); // DEPARSER builder->emitIndent(); builder->blockStart(); - msgStr = absl::StrFormat("%s deparser: packet deparsing started", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing started", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); deparser->emit(builder); - msgStr = absl::StrFormat("%s deparser: packet deparsing finished", sectionName); + msgStr = absl::StrFormat("%v deparser: packet deparsing finished", sectionName); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->blockEnd(true); } @@ -359,7 +359,7 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { if (name == "tc-ingress") { builder->target->emitCodeSection(builder, sectionName); builder->emitIndent(); - builder->appendFormat("int %s(%s *%s)", functionName, + builder->appendFormat("int %v(%v *%s)", functionName, builder->target->packetDescriptorType(), model.CPacketName.str()); builder->spc(); @@ -374,12 +374,12 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { builder->appendFormat("int ret = %d;", actUnspecCode); builder->newline(); builder->emitIndent(); - builder->appendFormat("ret = %s(skb, ", func_name); + builder->appendFormat("ret = %v(skb, ", func_name); - builder->appendFormat("(%s %s *) %s, %s);", + builder->appendFormat("(%v %v *) %v, %v);", parser->headerType->as().kind, parser->headerType->as().name, - parser->headers->name.name, compilerGlobalMetadata); + parser->headers->name, compilerGlobalMetadata); builder->newline(); builder->emitIndent(); @@ -397,7 +397,7 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { builder->newline(); builder->target->emitCodeSection(builder, sectionName); builder->emitIndent(); - builder->appendFormat("int %s(%s *%s)", functionName, + builder->appendFormat("int %v(%v *%s)", functionName, builder->target->packetDescriptorType(), model.CPacketName.str()); builder->spc(); @@ -405,7 +405,7 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct pna_global_metadata *%s = (struct pna_global_metadata *) skb->cb;", + "struct pna_global_metadata *%v = (struct pna_global_metadata *) skb->cb;", compilerGlobalMetadata); builder->newline(); @@ -416,12 +416,12 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { builder->appendFormat("int ret = %d;", actUnspecCode); builder->newline(); builder->emitIndent(); - builder->appendFormat("ret = %s(skb, ", func_name); + builder->appendFormat("ret = %v(skb, ", func_name); - builder->appendFormat("(%s %s *) %s, %s);", + builder->appendFormat("(%v %v *) %v, %v);", parser->headerType->as().kind, parser->headerType->as().name, - parser->headers->name.name, compilerGlobalMetadata); + parser->headers->name, compilerGlobalMetadata); builder->newline(); builder->emitIndent(); @@ -442,7 +442,7 @@ void TCIngressPipelinePNA::emit(EBPF::CodeBuilder *builder) { void TCIngressPipelinePNA::emitGlobalMetadataInitializer(EBPF::CodeBuilder *builder) { builder->emitIndent(); builder->appendFormat( - "struct pna_global_metadata *%s = (struct pna_global_metadata *) skb->cb;", + "struct pna_global_metadata *%v = (struct pna_global_metadata *) skb->cb;", compilerGlobalMetadata); builder->newline(); @@ -459,7 +459,7 @@ void TCIngressPipelinePNA::emitGlobalMetadataInitializer(EBPF::CodeBuilder *buil // workaround to make TC protocol-independent, DO NOT REMOVE builder->emitIndent(); // replace ether_type only if a packet comes from XDP - builder->appendFormat("if (!%s->recirculated) ", compilerGlobalMetadata); + builder->appendFormat("if (!%v->recirculated) ", compilerGlobalMetadata); builder->blockStart(); builder->emitIndent(); builder->appendFormat("compiler_meta__->mark = %u", packetMark); @@ -482,7 +482,7 @@ void TCIngressPipelinePNA::emitGlobalMetadataInitializer(EBPF::CodeBuilder *buil void TCIngressPipelinePNA::emitTrafficManager(EBPF::CodeBuilder *builder) { builder->emitIndent(); - builder->appendFormat("if (!%s->drop && %s->egress_port == 0) ", compilerGlobalMetadata, + builder->appendFormat("if (!%v->drop && %v->egress_port == 0) ", compilerGlobalMetadata, compilerGlobalMetadata); builder->blockStart(); builder->target->emitTraceMessage(builder, "IngressTM: Sending packet up to the kernel stack"); @@ -501,13 +501,13 @@ void TCIngressPipelinePNA::emitTrafficManager(EBPF::CodeBuilder *builder) { builder->endOfStatement(true); builder->blockEnd(true); - cstring eg_port = absl::StrFormat("%s->egress_port", compilerGlobalMetadata); + cstring eg_port = absl::StrFormat("%v->egress_port", compilerGlobalMetadata); cstring cos = - absl::StrFormat("%s.class_of_service", control->outputStandardMetadata->name.name); + absl::StrFormat("%v.class_of_service", control->outputStandardMetadata->name.name); builder->target->emitTraceMessage( builder, "IngressTM: Sending packet out of port %d with priority %d", 2, eg_port, cos); builder->emitIndent(); - builder->appendFormat("return bpf_redirect(%s->egress_port, 0)", compilerGlobalMetadata); + builder->appendFormat("return bpf_redirect(%v->egress_port, 0)", compilerGlobalMetadata); builder->endOfStatement(true); } @@ -636,7 +636,7 @@ void PnaStateTranslationVisitor::compileExtractField(const IR::Expression *expr, } } - msgStr = absl::StrFormat("Parser: extracting field %s", fieldName); + msgStr = absl::StrFormat("Parser: extracting field %v", fieldName); builder->target->emitTraceMessage(builder, msgStr.c_str()); if (widthToExtract <= 64) { @@ -666,15 +666,14 @@ void PnaStateTranslationVisitor::compileExtractField(const IR::Expression *expr, if (noEndiannessConversion) { builder->appendFormat("__builtin_memcpy(&"); visit(expr); - builder->appendFormat(".%s, %s + BYTES(%s), %d)", fieldName, - program->packetStartVar.c_str(), program->offsetVar.c_str(), - widthToExtract / 8); + builder->appendFormat(".%v, %v + BYTES(%v), %d)", fieldName, program->packetStartVar, + program->offsetVar, widthToExtract / 8); } else { visit(expr); - builder->appendFormat(".%s = (", fieldName); + builder->appendFormat(".%v = (", fieldName); type->emit(builder); - builder->appendFormat(")((%s(%s, BYTES(%s))", helper, program->packetStartVar.c_str(), - program->offsetVar.c_str()); + builder->appendFormat(")((%s(%v, BYTES(%v))", helper, program->packetStartVar, + program->offsetVar); if (shift != 0) builder->appendFormat(" >> %d", shift); builder->append(")"); if (widthToExtract != loadSize) { @@ -753,13 +752,13 @@ void PnaStateTranslationVisitor::compileExtractField(const IR::Expression *expr, } } } - cstring tmp = absl::StrFormat("(unsigned long long) %s.%s", exprStr, fieldName); + cstring tmp = absl::StrFormat("(unsigned long long) %v.%v", exprStr, fieldName); msgStr = - absl::StrFormat("Parser: extracted %s=0x%%llx (%u bits)", fieldName, widthToExtract); + absl::StrFormat("Parser: extracted %v=0x%%llx (%u bits)", fieldName, widthToExtract); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, tmp.c_str()); } else { - msgStr = absl::StrFormat("Parser: extracted %s (%u bits)", fieldName, widthToExtract); + msgStr = absl::StrFormat("Parser: extracted %v (%u bits)", fieldName, widthToExtract); builder->target->emitTraceMessage(builder, msgStr.c_str()); } @@ -785,9 +784,8 @@ bool PnaStateTranslationVisitor::preorder(const IR::Member *m) { } void PnaStateTranslationVisitor::compileLookahead(const IR::Expression *destination) { - cstring msgStr = absl::StrFormat("Parser: lookahead for %s %s", - state->parser->typeMap->getType(destination)->toString(), - destination->toString()); + cstring msgStr = absl::StrFormat("Parser: lookahead for %v %v", + state->parser->typeMap->getType(destination), destination); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->emitIndent(); @@ -863,7 +861,7 @@ void EBPFTablePNA::emitKeyType(EBPF::CodeBuilder *builder) { if (isTernaryTable()) { // generate mask key builder->emitIndent(); - builder->appendFormat("#define MAX_%s_MASKS %u", keyTypeName.toUpper(), + builder->appendFormat("#define MAX_%v_MASKS %u", keyTypeName.toUpper(), program->options.maxTernaryMasks); builder->newline(); @@ -939,7 +937,7 @@ void EBPFTablePNA::emitValueStructStructure(EBPF::CodeBuilder *builder) { cstring EBPFTablePNA::p4ActionToActionIDName(const IR::P4Action *action) const { cstring actionName = EBPFObject::externalName(action); cstring tableInstance = dataMapName; - return absl::StrFormat("%s_ACT_%s", tableInstance.toUpper(), actionName.toUpper()); + return absl::StrFormat("%v_ACT_%v", tableInstance.toUpper(), actionName.toUpper()); } void EBPFTablePNA::emitActionArguments(EBPF::CodeBuilder *builder, const IR::P4Action *action, @@ -982,24 +980,23 @@ void EBPFTablePNA::emitAction(EBPF::CodeBuilder *builder, cstring valueName, cstring name = EBPF::EBPFObject::externalName(action), msgStr, convStr; builder->emitIndent(); cstring actionName = p4ActionToActionIDName(action); - builder->appendFormat("case %s: ", actionName); + builder->appendFormat("case %v: ", actionName); builder->newline(); builder->increaseIndent(); - msgStr = absl::StrFormat("Control: executing action %s", name); + msgStr = absl::StrFormat("Control: executing action %v", name); builder->target->emitTraceMessage(builder, msgStr.c_str()); for (auto param : *(action->parameters)) { auto etype = EBPF::EBPFTypeFactory::instance->create(param->type); unsigned width = etype->as().widthInBits(); if (width <= 64) { - convStr = absl::StrFormat("(unsigned long long) (%s->u.%s.%s)", valueName, name, - param->toString()); - msgStr = absl::StrFormat("Control: param %s=0x%%llx (%d bits)", param->toString(), - width); + convStr = + absl::StrFormat("(unsigned long long) (%v->u.%v.%v)", valueName, name, param); + msgStr = absl::StrFormat("Control: param %v=0x%%llx (%d bits)", param, width); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, convStr.c_str()); } else { - msgStr = absl::StrFormat("Control: param %s (%d bits)", param->toString(), width); + msgStr = absl::StrFormat("Control: param %v (%d bits)", param, width); builder->target->emitTraceMessage(builder, msgStr.c_str()); } } @@ -1080,9 +1077,9 @@ void EBPFTablePNA::emitAction(EBPF::CodeBuilder *builder, cstring valueName, cstring noActionName = P4::P4CoreLibrary::instance().noAction.name; cstring tableInstance = dataMapName; cstring actionName = - absl::StrFormat("%s_ACT_%s", tableInstance.toUpper(), noActionName.toUpper()); + absl::StrFormat("%v_ACT_%v", tableInstance.toUpper(), noActionName.toUpper()); builder->emitIndent(); - builder->appendFormat("case %s: ", actionName); + builder->appendFormat("case %v: ", actionName); builder->newline(); builder->increaseIndent(); builder->emitIndent(); @@ -1138,17 +1135,17 @@ void EBPFTablePNA::emitValueActionIDNames(EBPF::CodeBuilder *builder) { noActionGenerated = true; unsigned int action_idx = tcIR->getActionId(tcIR->externalName(action)); builder->emitIndent(); - builder->appendFormat("#define %s %d", p4ActionToActionIDName(action), action_idx); + builder->appendFormat("#define %v %d", p4ActionToActionIDName(action), action_idx); builder->newline(); } if (!noActionGenerated) { cstring noActionName = P4::P4CoreLibrary::instance().noAction.name; cstring tableInstance = dataMapName; cstring actionName = - absl::StrFormat("%s_ACT_%s", tableInstance.toUpper(), noActionName.toUpper()); + absl::StrFormat("%v_ACT_%v", tableInstance.toUpper(), noActionName.toUpper()); unsigned int action_idx = tcIR->getActionId(noActionName); builder->emitIndent(); - builder->appendFormat("#define %s %d", actionName, action_idx); + builder->appendFormat("#define %v %d", actionName, action_idx); builder->newline(); } builder->emitIndent(); @@ -1191,7 +1188,7 @@ void IngressDeparserPNA::emitPreDeparser(EBPF::CodeBuilder *builder) { builder->emitIndent(); CHECK_NULL(program); auto pipeline = program->checkedTo(); - builder->appendFormat("if (%s->drop) ", pipeline->compilerGlobalMetadata); + builder->appendFormat("if (%v->drop) ", pipeline->compilerGlobalMetadata); builder->blockStart(); builder->target->emitTraceMessage(builder, "PreDeparser: dropping packet.."); builder->emitIndent(); @@ -1231,11 +1228,11 @@ void IngressDeparserPNA::emit(EBPF::CodeBuilder *builder) { emitBufferAdjusts(builder); builder->emitIndent(); - builder->appendFormat("%s = %s;", program->packetStartVar, + builder->appendFormat("%v = %v;", program->packetStartVar, builder->target->dataOffset(program->model.CPacketName.toString())); builder->newline(); builder->emitIndent(); - builder->appendFormat("%s = %s;", program->packetEndVar, + builder->appendFormat("%v = %v;", program->packetEndVar, builder->target->dataEnd(program->model.CPacketName.toString())); builder->newline(); @@ -1749,19 +1746,19 @@ void ControlBodyTranslatorPNA::processFunction(const P4::ExternFunction *functio actionName); } builder->emitIndent(); - builder->appendFormat("update_act_bpf_val->u.%s.%s = ", actionExtName, - param->toString()); + builder->appendFormat("update_act_bpf_val->u.%v.%v = ", actionExtName, + param); visit(components.at(index)->expression); builder->endOfStatement(); builder->newline(); } builder->emitIndent(); - builder->appendFormat("update_act_bpf_val->action = %s;", + builder->appendFormat("update_act_bpf_val->action = %v;", table->p4ActionToActionIDName(action)); builder->newline(); } else { builder->emitIndent(); - builder->appendFormat("update_act_bpf.act_id = %s;", + builder->appendFormat("update_act_bpf.act_id = %v;", table->p4ActionToActionIDName(action)); builder->newline(); } @@ -1818,7 +1815,7 @@ void ControlBodyTranslatorPNA::processApply(const P4::ApplyMethod *method) { auto table = control->getTable(method->object->getName().name); BUG_CHECK(table != nullptr, "No table for %1%", method->expr); - msgStr = absl::StrFormat("Control: applying %s", method->object->getName().name); + msgStr = absl::StrFormat("Control: applying %v", method->object->getName()); builder->target->emitTraceMessage(builder, msgStr.c_str()); builder->emitIndent(); @@ -1918,10 +1915,10 @@ void ControlBodyTranslatorPNA::processApply(const P4::ApplyMethod *method) { cstring msgStr, varStr; if (memcpy) { - msgStr = absl::StrFormat("Control: key %s", c->expression->toString()); + msgStr = absl::StrFormat("Control: key %v", c->expression); builder->target->emitTraceMessage(builder, msgStr.c_str()); } else { - msgStr = absl::StrFormat("Control: key %s=0x%%llx", c->expression->toString()); + msgStr = absl::StrFormat("Control: key %v=0x%%llx", c->expression); varStr = absl::StrFormat("(unsigned long long) %s.%s", keyname.c_str(), fieldName.c_str()); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, varStr.c_str()); @@ -1981,7 +1978,7 @@ void ControlBodyTranslatorPNA::processApply(const P4::ApplyMethod *method) { toDereference.clear(); builder->blockEnd(true); - msgStr = absl::StrFormat("Control: %s applied", method->object->getName().name); + msgStr = absl::StrFormat("Control: %v applied", method->object->getName()); builder->target->emitTraceMessage(builder, msgStr.c_str()); } @@ -2109,9 +2106,9 @@ cstring ActionTranslationVisitorPNA::getParamInstanceName(const IR::Expression * if (isDefaultAction) { cstring actionName = action->name.originalName; - auto paramStr = absl::StrFormat("p4tc_filter_fields.%s_%s_%s", - table->table->container->name.originalName, actionName, - expression->toString()); + auto paramStr = + absl::StrFormat("p4tc_filter_fields.%v_%v_%v", + table->table->container->name.originalName, actionName, expression); return paramStr; } else { return EBPF::ActionTranslationVisitor::getParamInstanceName(expression); @@ -2289,13 +2286,13 @@ void DeparserHdrEmitTranslatorPNA::emitField(EBPF::CodeBuilder *builder, cstring visit(hdrExpr); builder->appendFormat(".%s", field.c_str()); builder->endOfStatement(true); - msgStr = absl::StrFormat("Deparser: emitting field %s=0x%%llx (%u bits)", field, + msgStr = absl::StrFormat("Deparser: emitting field %v=0x%%llx (%u bits)", field, widthToEmit); builder->target->emitTraceMessage(builder, msgStr.c_str(), 1, "tmp"); builder->blockEnd(true); } } else { - msgStr = absl::StrFormat("Deparser: emitting field %s (%u bits)", field, widthToEmit); + msgStr = absl::StrFormat("Deparser: emitting field %v (%u bits)", field, widthToEmit); builder->target->emitTraceMessage(builder, msgStr.c_str()); } @@ -2317,9 +2314,9 @@ void DeparserHdrEmitTranslatorPNA::emitField(EBPF::CodeBuilder *builder, cstring if (!swap.isNullOrEmpty() && !noEndiannessConversion) { builder->emitIndent(); visit(hdrExpr); - builder->appendFormat(".%s = %s(", field, swap); + builder->appendFormat(".%v = %v(", field, swap); visit(hdrExpr); - builder->appendFormat(".%s", field); + builder->appendFormat(".%v", field); if (shift != 0) builder->appendFormat(" << %d", shift); builder->append(")"); builder->endOfStatement(true); @@ -2332,7 +2329,7 @@ void DeparserHdrEmitTranslatorPNA::emitField(EBPF::CodeBuilder *builder, cstring builder->emitIndent(); builder->appendFormat("%s = ((char*)(&", program->byteVar.c_str()); visit(hdrExpr); - builder->appendFormat(".%s))[%d]", field, i); + builder->appendFormat(".%v))[%d]", field, i); builder->endOfStatement(true); unsigned freeBits = alignment != 0 ? (8 - alignment) : 8; bitsInCurrentByte = left >= 8 ? 8 : left; diff --git a/backends/tc/ebpfCodeGen.h b/backends/tc/ebpfCodeGen.h index 12cfabe8ecd..44b94629202 100644 --- a/backends/tc/ebpfCodeGen.h +++ b/backends/tc/ebpfCodeGen.h @@ -76,7 +76,7 @@ class PNAErrorCodesGen : public Inspector { } builder->emitIndent(); - builder->appendFormat("static const ParserError_t %s = %d", decl->name.name, id); + builder->appendFormat("static const ParserError_t %v = %d", decl->name, id); builder->endOfStatement(true); // type ParserError_t is u8, which can have values from 0 to 255 diff --git a/backends/tc/tcExterns.cpp b/backends/tc/tcExterns.cpp index ea9b4ec974c..d1b0519b864 100644 --- a/backends/tc/tcExterns.cpp +++ b/backends/tc/tcExterns.cpp @@ -29,7 +29,7 @@ void EBPFRegisterPNA::emitInitializer(EBPF::CodeBuilder *builder, const P4::Exte builder->emitIndent(); auto extId = translator->tcIR->getExternId(externName); BUG_CHECK(!extId.isNullOrEmpty(), "Extern ID not found"); - builder->appendFormat("ext_params.ext_id = %s;", extId); + builder->appendFormat("ext_params.ext_id = %v;", extId); builder->newline(); builder->emitIndent(); auto instId = translator->tcIR->getExternInstanceId(externName, this->instanceName); @@ -151,7 +151,7 @@ void EBPFCounterPNA::emitCount(EBPF::CodeBuilder *builder, const P4::ExternMetho builder->emitIndent(); auto extId = translator->tcIR->getExternId(externName); BUG_CHECK(!extId.isNullOrEmpty(), "Extern ID not found"); - builder->appendFormat("ext_params.ext_id = %s;", extId); + builder->appendFormat("ext_params.ext_id = %v;", extId); builder->newline(); builder->emitIndent(); auto instId = translator->tcIR->getExternInstanceId(externName, instanceName); @@ -350,7 +350,7 @@ void InternetChecksumAlgorithmPNA::updateChecksum(EBPF::CodeBuilder *builder, auto etype = EBPF::EBPFTypeFactory::instance->create(field->type); builder->emitIndent(); etype->declare(builder, field_temp, false); - builder->appendFormat(" = %s(", getConvertByteOrderFunction(width, "HOST"_cs)); + builder->appendFormat(" = %v(", getConvertByteOrderFunction(width, "HOST"_cs)); visitor->visit(field); builder->appendLine(");"); } @@ -366,7 +366,7 @@ void InternetChecksumAlgorithmPNA::updateChecksum(EBPF::CodeBuilder *builder, remainingBits -= bitsToRead; builder->append("("); if (fieldByteOrder == "NETWORK"_cs) { - builder->appendFormat("%s", field_temp); + builder->appendFormat("%v", field_temp); } else { visitor->visit(field); } @@ -375,7 +375,7 @@ void InternetChecksumAlgorithmPNA::updateChecksum(EBPF::CodeBuilder *builder, } else if (bitsToRead == remainingBits) { remainingBits = 0; if (fieldByteOrder == "NETWORK"_cs) { - builder->appendFormat("%s", field_temp); + builder->appendFormat("%v", field_temp); } else { visitor->visit(field); } @@ -385,7 +385,7 @@ void InternetChecksumAlgorithmPNA::updateChecksum(EBPF::CodeBuilder *builder, remainingBits = 0; builder->append("("); if (fieldByteOrder == "NETWORK"_cs) { - builder->appendFormat("%s", field_temp); + builder->appendFormat("%v", field_temp); } else { visitor->visit(field); } @@ -444,7 +444,7 @@ void EBPFDigestPNA::emitInitializer(EBPF::CodeBuilder *builder) const { builder->emitIndent(); auto extId = tcIR->getExternId(externName); BUG_CHECK(!extId.isNullOrEmpty(), "Extern ID not found"); - builder->appendFormat("ext_params.ext_id = %s;", extId); + builder->appendFormat("ext_params.ext_id = %v;", extId); builder->newline(); builder->emitIndent(); auto instId = tcIR->getExternInstanceId(externName, instanceName); @@ -542,7 +542,7 @@ void EBPFDigestPNA::emitPushElement(EBPF::CodeBuilder *builder, cstring elem) co emitInitializer(builder); builder->newline(); builder->emitIndent(); - builder->appendFormat("__builtin_memcpy(ext_params.in_params, &%s, sizeof(", elem); + builder->appendFormat("__builtin_memcpy(ext_params.in_params, &%v, sizeof(", elem); this->valueType->declare(builder, cstring::empty, false); builder->append("));"); builder->newline(); @@ -559,11 +559,11 @@ void EBPFMeterPNA::emitInitializer(EBPF::CodeBuilder *builder, const ConvertToBa builder->emitIndent(); auto extId = tcIR->getExternId(externName); BUG_CHECK(!extId.isNullOrEmpty(), "Extern ID not found"); - builder->appendFormat("ext_params.ext_id = %s;", extId); + builder->appendFormat("ext_params.ext_id = %v;", extId); builder->newline(); cstring ext_flags = isDirect ? "P4TC_EXT_METER_DIRECT"_cs : "P4TC_EXT_METER_INDIRECT"_cs; builder->emitIndent(); - builder->appendFormat("ext_params.flags = %s;", ext_flags); + builder->appendFormat("ext_params.flags = %v;", ext_flags); } void EBPFMeterPNA::emitExecute(EBPF::CodeBuilder *builder, const P4::ExternMethod *method, @@ -597,7 +597,7 @@ void EBPFMeterPNA::emitExecute(EBPF::CodeBuilder *builder, const P4::ExternMetho etype->declare(builder, color_aware, true); builder->appendLine(" = (u32 *)ext_params.in_params;"); builder->emitIndent(); - builder->appendFormat("*%s = ", color_aware); + builder->appendFormat("*%v = ", color_aware); translator->visit(value); builder->endOfStatement(); } @@ -655,7 +655,7 @@ void EBPFMeterPNA::emitDirectMeterExecute(EBPF::CodeBuilder *builder, etype->declare(builder, color_aware, true); builder->appendLine(" = (u32 *)ext_params.in_params;"); builder->emitIndent(); - builder->appendFormat("*%s = ", color_aware); + builder->appendFormat("*%v = ", color_aware); translator->visit(value); builder->endOfStatement(); } diff --git a/backends/ubpf/target.cpp b/backends/ubpf/target.cpp index 87601a550d0..d858f893bd2 100644 --- a/backends/ubpf/target.cpp +++ b/backends/ubpf/target.cpp @@ -53,7 +53,7 @@ void UbpfTarget::emitTableDecl(Util::SourceCodeBuilder *builder, cstring tblName EBPF::TableKind tableKind, cstring keyType, cstring valueType, unsigned size) const { builder->append("struct "); - builder->appendFormat("ubpf_map_def %s = ", tblName); + builder->appendFormat("ubpf_map_def %v = ", tblName); builder->spc(); builder->blockStart(); @@ -69,15 +69,15 @@ void UbpfTarget::emitTableDecl(Util::SourceCodeBuilder *builder, cstring tblName } builder->emitIndent(); - builder->appendFormat(".type = %s,", type); + builder->appendFormat(".type = %v,", type); builder->newline(); builder->emitIndent(); - builder->appendFormat(".key_size = sizeof(%s),", keyType); + builder->appendFormat(".key_size = sizeof(%v),", keyType); builder->newline(); builder->emitIndent(); - builder->appendFormat(".value_size = sizeof(%s),", valueType); + builder->appendFormat(".value_size = sizeof(%v),", valueType); builder->newline(); diff --git a/backends/ubpf/ubpfControl.cpp b/backends/ubpf/ubpfControl.cpp index 79f9922cea9..72a53a42653 100644 --- a/backends/ubpf/ubpfControl.cpp +++ b/backends/ubpf/ubpfControl.cpp @@ -35,10 +35,10 @@ UBPFControlBodyTranslator::UBPFControlBodyTranslator(const UBPFControl *control) void UBPFControlBodyTranslator::processFunction(const P4::ExternFunction *function) { if (function->method->name.name == control->program->model.drop.name) { - builder->appendFormat("%s = false", control->passVariable); + builder->appendFormat("%v = false", control->passVariable); return; } else if (function->method->name.name == control->program->model.pass.name) { - builder->appendFormat("%s = true", control->passVariable); + builder->appendFormat("%v = true", control->passVariable); return; } else if (function->method->name.name == control->program->model.ubpf_time_get_ns.name) { builder->append(control->program->model.ubpf_time_get_ns.name + "()"); @@ -56,7 +56,7 @@ void UBPFControlBodyTranslator::processFunction(const P4::ExternFunction *functi auto algorithmType = algorithmTypeArgument->member.name; if (algorithmType == control->program->model.hashAlgorithm.lookup3.name) { - builder->appendFormat(" = ubpf_hash(&%s, sizeof(%s))", hashKeyInstanceName, + builder->appendFormat(" = ubpf_hash(&%v, sizeof(%v))", hashKeyInstanceName, hashKeyInstanceName); } else { ::P4::error(ErrorType::ERR_UNSUPPORTED, "%1%: Not supported hash algorithm type", @@ -129,7 +129,7 @@ cstring UBPFControlBodyTranslator::createHashKeyInstance(const P4::ExternFunctio if (!f->type) // If nullptr it's a padding. continue; builder->emitIndent(); - builder->appendFormat("%s.%s = ", hashKeyInstance, f->name); + builder->appendFormat("%v.%v = ", hashKeyInstance, f->name); auto c = dataArgument->components.at(idx); visit(c); builder->endOfStatement(true); @@ -358,7 +358,7 @@ bool UBPFControlBodyTranslator::emitRegisterRead(const IR::AssignmentStatement * builder->newline(); builder->emitIndent(); - builder->appendFormat("if (%s != NULL) ", tmp); + builder->appendFormat("if (%v != NULL) ", tmp); builder->blockStart(); builder->emitIndent(); diff --git a/backends/ubpf/ubpfDeparser.cpp b/backends/ubpf/ubpfDeparser.cpp index 9a92681a2da..72216f1fdbb 100644 --- a/backends/ubpf/ubpfDeparser.cpp +++ b/backends/ubpf/ubpfDeparser.cpp @@ -141,9 +141,9 @@ void UBPFDeparserTranslationVisitor::compileEmitField(const IR::Expression *expr if (!swap.isNullOrEmpty()) { builder->emitIndent(); visit(expr); - builder->appendFormat(".%s = %s(", field.c_str(), swap); + builder->appendFormat(".%v = %v(", field, swap); visit(expr); - builder->appendFormat(".%s", field.c_str()); + builder->appendFormat(".%v", field); if (shift != 0) builder->appendFormat(" << %d", shift); builder->append(")"); builder->endOfStatement(true); diff --git a/backends/ubpf/ubpfParser.cpp b/backends/ubpf/ubpfParser.cpp index 6f5fe0cc20d..cdd09c300bb 100644 --- a/backends/ubpf/ubpfParser.cpp +++ b/backends/ubpf/ubpfParser.cpp @@ -128,7 +128,7 @@ bool UBPFStateTranslationVisitor::preorder(const IR::ParserState *parserState) { bool UBPFStateTranslationVisitor::preorder(const IR::SelectCase *selectCase) { builder->emitIndent(); if (auto mask = selectCase->keyset->to()) { - builder->appendFormat("if ((%s", selectValue); + builder->appendFormat("if ((%v", selectValue); builder->append(" & "); visit(mask->right); builder->append(") == ("); @@ -137,7 +137,7 @@ bool UBPFStateTranslationVisitor::preorder(const IR::SelectCase *selectCase) { visit(mask->right); builder->append("))"); } else { - builder->appendFormat("if (%s", selectValue); + builder->appendFormat("if (%v", selectValue); builder->append(" == "); visit(selectCase->keyset); builder->append(")"); @@ -162,13 +162,13 @@ bool UBPFStateTranslationVisitor::preorder(const IR::SelectExpression *expressio etype->declare(builder, selectValue, false); builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("%s = ", selectValue); + builder->appendFormat("%v = ", selectValue); visit(expression->select); builder->endOfStatement(true); for (auto e : expression->selectCases) visit(e); builder->emitIndent(); - builder->appendFormat("else goto %s;", IR::ParserState::reject.c_str()); + builder->appendFormat("else goto %v;", IR::ParserState::reject); builder->newline(); return false; } diff --git a/backends/ubpf/ubpfProgram.cpp b/backends/ubpf/ubpfProgram.cpp index 214d6fbd4f0..96d06582a89 100644 --- a/backends/ubpf/ubpfProgram.cpp +++ b/backends/ubpf/ubpfProgram.cpp @@ -97,7 +97,7 @@ void UBPFProgram::emitC(UbpfCodeBuilder *builder, const std::filesystem::path &h emitLocalVariables(builder); builder->newline(); builder->emitIndent(); - builder->appendFormat("goto %s;", IR::ParserState::start.c_str()); + builder->appendFormat("goto %v;", IR::ParserState::start); builder->newline(); parser->emit(builder); @@ -105,23 +105,23 @@ void UBPFProgram::emitC(UbpfCodeBuilder *builder, const std::filesystem::path &h emitPipeline(builder); builder->emitIndent(); - builder->appendFormat("%s:\n", endLabel.c_str()); + builder->appendFormat("%v:\n", endLabel); builder->emitIndent(); builder->blockStart(); deparser->emit(builder); builder->blockEnd(true); builder->emitIndent(); - builder->appendFormat("if (%s)\n", control->passVariable); + builder->appendFormat("if (%v)\n", control->passVariable); builder->increaseIndent(); builder->emitIndent(); - builder->appendFormat("return %s;\n", builder->target->forwardReturnCode().c_str()); + builder->appendFormat("return %v;\n", builder->target->forwardReturnCode()); builder->decreaseIndent(); builder->emitIndent(); builder->appendLine("else"); builder->increaseIndent(); builder->emitIndent(); - builder->appendFormat("return %s;\n", builder->target->dropReturnCode().c_str()); + builder->appendFormat("return %v;\n", builder->target->dropReturnCode()); builder->decreaseIndent(); builder->blockEnd(true); } @@ -267,11 +267,11 @@ void UBPFProgram::emitLocalVariables(EBPF::CodeBuilder *builder) { builder->newline(); builder->emitIndent(); - builder->appendFormat("uint8_t %s = 1;", control->passVariable); + builder->appendFormat("uint8_t %v = 1;", control->passVariable); builder->newline(); builder->emitIndent(); - builder->appendFormat("uint8_t %s = 0;", control->hitVariable); + builder->appendFormat("uint8_t %v = 0;", control->hitVariable); builder->newline(); builder->emitIndent(); diff --git a/backends/ubpf/ubpfTable.cpp b/backends/ubpf/ubpfTable.cpp index e35c237cbd5..ab5fdb1c311 100644 --- a/backends/ubpf/ubpfTable.cpp +++ b/backends/ubpf/ubpfTable.cpp @@ -86,10 +86,10 @@ class UbpfActionTranslationVisitor : public EBPF::CodeGenInspector { auto ef = mi->to(); if (ef != nullptr) { if (ef->method->name.name == program->model.drop.name) { - builder->appendFormat("%s = false", program->control->passVariable); + builder->appendFormat("%v = false", program->control->passVariable); return false; } else if (ef->method->name.name == program->model.pass.name) { - builder->appendFormat("%s = true", program->control->passVariable); + builder->appendFormat("%v = true", program->control->passVariable); return false; } else if (ef->method->name.name == program->model.ubpf_time_get_ns.name) { builder->emitIndent(); @@ -484,8 +484,8 @@ void UBPFTable::emitInitializer(EBPF::CodeBuilder *builder) { builder->endOfStatement(true); builder->emitIndent(); - builder->appendFormat("INIT_UBPF_TABLE(\"%s\", sizeof(%s), sizeof(%s));", defaultTable, - program->zeroKey.c_str(), value); + builder->appendFormat("INIT_UBPF_TABLE(\"%v\", sizeof(%v), sizeof(%v));", defaultTable, + program->zeroKey, value); builder->newline(); builder->emitIndent(); diff --git a/backends/ubpf/ubpfType.cpp b/backends/ubpf/ubpfType.cpp index ad34902b209..53c20d0f215 100644 --- a/backends/ubpf/ubpfType.cpp +++ b/backends/ubpf/ubpfType.cpp @@ -252,14 +252,14 @@ void UBPFListType::emitInitializer(EBPF::CodeBuilder *builder) { for (auto f : elements) { if (!f->is()) continue; builder->emitIndent(); - builder->appendFormat(".%s = {0},", f->to()->name); + builder->appendFormat(".%v = {0},", f->to()->name); builder->newline(); } builder->blockEnd(false); } void UBPFListType::emitPadding(EBPF::CodeBuilder *builder, UBPF::UBPFListType::Padding *pad) { - builder->appendFormat("uint8_t %s[%u]", pad->name, pad->widthInBytes); + builder->appendFormat("uint8_t %v[%u]", pad->name, pad->widthInBytes); } /*** diff --git a/control-plane/p4RuntimeArchHandler.cpp b/control-plane/p4RuntimeArchHandler.cpp index bf2bc5a7faa..8ea8b966976 100644 --- a/control-plane/p4RuntimeArchHandler.cpp +++ b/control-plane/p4RuntimeArchHandler.cpp @@ -142,7 +142,7 @@ void serializeStructuredExpression(const IR::Expression *expr, p4configv1::Expre } else if (expr->is()) { sExpr->set_bool_value(expr->to()->value); } else if (expr->is()) { - sExpr->set_string_value(expr->to()->value); + sExpr->set_string_value(expr->to()->value.string_view()); } else { // guaranteed by the type checker. BUG("%1%: structured annotation expression must be a compile-time value", expr); @@ -150,13 +150,13 @@ void serializeStructuredExpression(const IR::Expression *expr, p4configv1::Expre } void serializeStructuredKVPair(const IR::NamedExpression *kv, p4configv1::KeyValuePair *sKV) { - sKV->set_key(kv->name.name); + sKV->set_key(kv->name.string_view()); serializeStructuredExpression(kv->expression, sKV->mutable_value()); } void serializeOneStructuredAnnotation(const IR::Annotation *annotation, p4configv1::StructuredAnnotation *structuredAnnotation) { - structuredAnnotation->set_name(annotation->name.name); + structuredAnnotation->set_name(annotation->name.string_view()); switch (annotation->annotationKind()) { case IR::Annotation::Kind::StructuredEmpty: // nothing to do, body oneof should be empty. diff --git a/control-plane/p4RuntimeArchHandler.h b/control-plane/p4RuntimeArchHandler.h index d3dba572651..1e1f021ab64 100644 --- a/control-plane/p4RuntimeArchHandler.h +++ b/control-plane/p4RuntimeArchHandler.h @@ -321,7 +321,7 @@ void addDocumentation(Message *message, const IR::IAnnotated *annotated) { auto brief = annotation->expr[0]->to(); // guaranteed by ParseAnnotations pass CHECK_NULL(brief); - doc.set_brief(brief->value); + doc.set_brief(brief->value.string_view()); hasDoc = true; continue; } @@ -329,7 +329,7 @@ void addDocumentation(Message *message, const IR::IAnnotated *annotated) { auto description = annotation->expr[0]->to(); // guaranteed by ParseAnnotations pass CHECK_NULL(description); - doc.set_description(description->value); + doc.set_description(description->value.string_view()); hasDoc = true; continue; } @@ -346,8 +346,8 @@ void setPreamble(::p4::config::v1::Preamble *preamble, p4rt_id_t id, cstring nam const IR::IAnnotated *annotated, UnaryPredicate p) { CHECK_NULL(preamble); preamble->set_id(id); - preamble->set_name(name); - preamble->set_alias(alias); + preamble->set_name(name.string_view()); + preamble->set_alias(alias.string_view()); addAnnotations(preamble, annotated, p); addDocumentation(preamble, annotated); } diff --git a/control-plane/p4RuntimeArchStandard.h b/control-plane/p4RuntimeArchStandard.h index 4678af8e8e6..c6b71341c40 100644 --- a/control-plane/p4RuntimeArchStandard.h +++ b/control-plane/p4RuntimeArchStandard.h @@ -874,7 +874,8 @@ class P4RuntimeArchHandlerCommon : public P4RuntimeArchHandlerIface { setCounterCommon(symbols, counter, id, counterInstance); counter->set_size(counterInstance.size); if (counterInstance.index_type_name) { - counter->mutable_index_type_name()->set_name(counterInstance.index_type_name); + counter->mutable_index_type_name()->set_name( + counterInstance.index_type_name.string_view()); } } } @@ -903,7 +904,8 @@ class P4RuntimeArchHandlerCommon : public P4RuntimeArchHandlerIface { setMeterCommon(symbols, meter, id, meterInstance); meter->set_size(meterInstance.size); if (meterInstance.index_type_name) { - meter->mutable_index_type_name()->set_name(meterInstance.index_type_name); + meter->mutable_index_type_name()->set_name( + meterInstance.index_type_name.string_view()); } } } @@ -917,7 +919,8 @@ class P4RuntimeArchHandlerCommon : public P4RuntimeArchHandlerIface { register_->set_size(registerInstance.size); register_->mutable_type_spec()->CopyFrom(*registerInstance.typeSpec); if (registerInstance.index_type_name) { - register_->mutable_index_type_name()->set_name(registerInstance.index_type_name); + register_->mutable_index_type_name()->set_name( + registerInstance.index_type_name.string_view()); } } diff --git a/control-plane/p4RuntimeSerializer.cpp b/control-plane/p4RuntimeSerializer.cpp index e6120d824ca..8509b6c2d9f 100644 --- a/control-plane/p4RuntimeSerializer.cpp +++ b/control-plane/p4RuntimeSerializer.cpp @@ -562,7 +562,7 @@ class P4RuntimeAnalyzer { auto paramName = actionParam->controlPlaneName(); auto id = idAllocator.getId(actionParam); param->set_id(id); - param->set_name(paramName); + param->set_name(paramName.string_view()); addAnnotations(param, actionParam->to()); addDocumentation(param, actionParam->to()); @@ -586,7 +586,7 @@ class P4RuntimeAnalyzer { auto type_name = getTypeName(paramType, typeMap); if (type_name) { auto namedType = param->mutable_type_name(); - namedType->set_name(type_name); + namedType->set_name(type_name.string_view()); } else if (auto e = paramType->to()) { param->mutable_type_name()->set_name(std::string(e->controlPlaneName())); } @@ -626,7 +626,7 @@ class P4RuntimeAnalyzer { auto fieldName = headerField->controlPlaneName(); auto id = idAllocator.getId(headerField); metadata->set_id(id); - metadata->set_name(fieldName); + metadata->set_name(fieldName.string_view()); addAnnotations(metadata, headerField->to()); auto fieldType = typeMap->getType(headerField, true); @@ -643,7 +643,7 @@ class P4RuntimeAnalyzer { auto type_name = getTypeName(fieldType, typeMap); if (type_name) { auto namedType = metadata->mutable_type_name(); - namedType->set_name(type_name); + namedType->set_name(type_name.string_view()); } } } @@ -729,17 +729,17 @@ class P4RuntimeAnalyzer { for (const auto &field : matchFields) { auto match_field = table->add_match_fields(); match_field->set_id(field.id); - match_field->set_name(field.name); + match_field->set_name(field.name.string_view()); addAnnotations(match_field, field.annotations); addDocumentation(match_field, field.annotations); match_field->set_bitwidth(field.bitwidth); if (field.type != MatchField::MatchTypes::UNSPECIFIED) match_field->set_match_type(field.type); else - match_field->set_other_match_type(field.other_match_type); + match_field->set_other_match_type(field.other_match_type.string_view()); if (field.type_name) { auto namedType = match_field->mutable_type_name(); - namedType->set_name(field.type_name); + namedType->set_name(field.type_name.string_view()); } } @@ -840,7 +840,7 @@ class P4RuntimeAnalyzer { if (matchType != MatchField::MatchTypes::UNSPECIFIED) match->set_match_type(*matchType); else - match->set_other_match_type(matchTypeName); + match->set_other_match_type(matchTypeName.string_view()); }; // TODO(antonin): handle new types @@ -872,7 +872,7 @@ class P4RuntimeAnalyzer { auto *match = vs->add_match(); auto fieldId = idAllocator.getId(f); match->set_id(fieldId); - match->set_name(f->controlPlaneName()); + match->set_name(f->controlPlaneName().string_view()); match->set_bitwidth(fType->width_bits()); setMatchType(f, match); // add annotations save for the @match one @@ -896,7 +896,7 @@ class P4RuntimeAnalyzer { for (auto f : fields) { auto *match = vs->add_match(); match->set_id(index++); - match->set_name(f->controlPlaneName()); + match->set_name(f->controlPlaneName().string_view()); match->set_bitwidth(fType->width_bits()); match->set_match_type(MatchField::MatchTypes::EXACT); } @@ -933,7 +933,7 @@ class P4RuntimeAnalyzer { CHECK_NULL(decl); auto *pkginfo = p4Info->mutable_pkg_info(); - pkginfo->set_arch(arch); + pkginfo->set_arch(arch.string_view()); std::set keysVisited; diff --git a/control-plane/typeSpecConverter.cpp b/control-plane/typeSpecConverter.cpp index 57ae67d0761..f8304941ed5 100644 --- a/control-plane/typeSpecConverter.cpp +++ b/control-plane/typeSpecConverter.cpp @@ -131,15 +131,15 @@ bool TypeSpecConverter::preorder(const IR::Type_Name *type) { auto decl = refMap->getDeclaration(type->path, true); auto name = decl->controlPlaneName(); if (decl->is()) { - typeSpec->mutable_struct_()->set_name(name); + typeSpec->mutable_struct_()->set_name(name.string_view()); } else if (decl->is()) { - typeSpec->mutable_header()->set_name(name); + typeSpec->mutable_header()->set_name(name.string_view()); } else if (decl->is()) { - typeSpec->mutable_header_union()->set_name(name); + typeSpec->mutable_header_union()->set_name(name.string_view()); } else if (decl->is()) { - typeSpec->mutable_enum_()->set_name(name); + typeSpec->mutable_enum_()->set_name(name.string_view()); } else if (decl->is()) { - typeSpec->mutable_serializable_enum()->set_name(name); + typeSpec->mutable_serializable_enum()->set_name(name.string_view()); } else if (decl->is()) { // enable "error" field in P4DataTypeSpec's type_spec oneof (void)typeSpec->mutable_error(); @@ -154,7 +154,7 @@ bool TypeSpecConverter::preorder(const IR::Type_Name *type) { map.emplace(type, typeSpec); return false; } else if (decl->is()) { - typeSpec->mutable_new_type()->set_name(name); + typeSpec->mutable_new_type()->set_name(name.string_view()); } else { BUG("Unexpected named type %1%", type); } @@ -244,11 +244,11 @@ bool TypeSpecConverter::preorder(const IR::Type_Stack *type) { if (decl->is()) { auto headerStackTypeSpec = typeSpec->mutable_header_stack(); - headerStackTypeSpec->mutable_header()->set_name(name); + headerStackTypeSpec->mutable_header()->set_name(name.string_view()); headerStackTypeSpec->set_size(size); } else if (decl->is()) { auto headerUnionStackTypeSpec = typeSpec->mutable_header_union_stack(); - headerUnionStackTypeSpec->mutable_header_union()->set_name(name); + headerUnionStackTypeSpec->mutable_header_union()->set_name(name.string_view()); headerUnionStackTypeSpec->set_size(size); } else { BUG("Unexpected declaration %1%", decl); @@ -270,7 +270,7 @@ bool TypeSpecConverter::preorder(const IR::Type_Struct *type) { auto fTypeSpec = map.at(fType); CHECK_NULL(fTypeSpec); auto member = structTypeSpec->add_members(); - member->set_name(f->controlPlaneName()); + member->set_name(f->controlPlaneName().string_view()); member->mutable_type_spec()->CopyFrom(*fTypeSpec); } (*structs)[name] = *structTypeSpec; @@ -296,7 +296,7 @@ bool TypeSpecConverter::preorder(const IR::Type_Header *type) { "Only bitstring fields expected in flattened header type %1%", flattenedHeaderType); auto member = headerTypeSpec->add_members(); - member->set_name(f->controlPlaneName()); + member->set_name(f->controlPlaneName().string_view()); member->mutable_type_spec()->CopyFrom(fTypeSpec->bitstring()); } (*headers)[name] = *headerTypeSpec; @@ -320,7 +320,7 @@ bool TypeSpecConverter::preorder(const IR::Type_HeaderUnion *type) { BUG_CHECK(fTypeSpec->has_header(), "Only header fields expected in header union declaration %1%", type); auto member = headerUnionTypeSpec->add_members(); - member->set_name(f->controlPlaneName()); + member->set_name(f->controlPlaneName().string_view()); member->mutable_header()->CopyFrom(fTypeSpec->header()); } (*headerUnions)[name] = *headerUnionTypeSpec; @@ -338,7 +338,7 @@ bool TypeSpecConverter::preorder(const IR::Type_Enum *type) { auto enumTypeSpec = new p4configv1::P4EnumTypeSpec(); for (auto m : type->members) { auto member = enumTypeSpec->add_members(); - member->set_name(m->controlPlaneName()); + member->set_name(m->controlPlaneName().string_view()); } (*enums)[name] = *enumTypeSpec; } @@ -358,7 +358,7 @@ bool TypeSpecConverter::preorder(const IR::Type_SerEnum *type) { bitTypeSpec->set_bitwidth(width); for (auto m : type->members) { auto member = enumTypeSpec->add_members(); - member->set_name(m->controlPlaneName()); + member->set_name(m->controlPlaneName().string_view()); if (!m->value->is()) { ::P4::error(ErrorType::ERR_UNSUPPORTED, "%1% unsupported SerEnum member value", m->value); @@ -378,7 +378,8 @@ bool TypeSpecConverter::preorder(const IR::Type_SerEnum *type) { bool TypeSpecConverter::preorder(const IR::Type_Error *type) { if (p4RtTypeInfo && !p4RtTypeInfo->has_error()) { auto errorTypeSpec = p4RtTypeInfo->mutable_error(); - for (auto m : type->members) errorTypeSpec->add_members(m->controlPlaneName()); + for (auto m : type->members) + errorTypeSpec->add_members(m->controlPlaneName().string_view()); } map.emplace(type, nullptr); return false; diff --git a/frontends/p4/def_use.cpp b/frontends/p4/def_use.cpp index e4830b1df3a..45a8e2d2f33 100644 --- a/frontends/p4/def_use.cpp +++ b/frontends/p4/def_use.cpp @@ -65,7 +65,7 @@ StorageLocation *StorageFactory::create(const IR::Type *type, cstring name) cons auto *result = construct(type, name); size_t index = 0; for (const auto *t : bl->components) { - cstring fieldName = absl::StrCat(name.string_view(), "[", index, "]"); + cstring fieldName = absl::StrCat(name, "[", index, "]"); auto *sl = create(t, fieldName); result->createElement(index, sl); index++; @@ -103,11 +103,11 @@ StorageLocation *StorageFactory::create(const IR::Type *type, cstring name) cons } else if (auto st = type->to()) { auto *result = construct(st, name); for (unsigned i = 0; i < st->getSize(); i++) { - auto *sl = create(st->elementType, absl::StrCat(name.string_view(), "[", i, "]")); + auto *sl = create(st->elementType, absl::StrCat(name, "[", i, "]")); result->createElement(i, sl); } result->setLastIndexField( - create(IR::Type_Bits::get(32), absl::StrCat(name.string_view(), ".", indexFieldName))); + create(IR::Type_Bits::get(32), absl::StrCat(name, ".", indexFieldName))); return result; } diff --git a/frontends/p4/localizeActions.cpp b/frontends/p4/localizeActions.cpp index 3ae11913a68..f0b338a6138 100644 --- a/frontends/p4/localizeActions.cpp +++ b/frontends/p4/localizeActions.cpp @@ -73,7 +73,7 @@ bool FindGlobalActionUses::preorder(const IR::PathExpression *path) { auto control = findContext(); if (control != nullptr) { if (repl->getReplacement(action, control) != nullptr) return false; - auto newName = nameGen.newName(action->name.name.string_view()); + auto newName = nameGen.newName(action->name.string_view()); ParamCloner cloner; auto replBody = cloner.clone(action->body); auto params = cloner.clone(action->parameters); @@ -163,7 +163,7 @@ bool FindRepeatedActionUses::preorder(const IR::PathExpression *expression) { LOG1(dbp(expression) << " used by " << dbp(actionUser)); auto replacement = repl->getActionUser(action, actionUser); if (replacement == nullptr) { - auto newName = nameGen.newName(action->name.name.string_view()); + auto newName = nameGen.newName(action->name.string_view()); ParamCloner cloner; auto replBody = cloner.clone(action->body); auto annos = action->annotations; diff --git a/frontends/p4/typeChecking/typeCheckDecl.cpp b/frontends/p4/typeChecking/typeCheckDecl.cpp index c179b797fd7..5cf30ccb2fd 100644 --- a/frontends/p4/typeChecking/typeCheckDecl.cpp +++ b/frontends/p4/typeChecking/typeCheckDecl.cpp @@ -379,15 +379,13 @@ static bool checkEnumValueInitializer(const IR::Type_Bits *type, const IR::Expre if (!type->isSigned && constant->value < low) { extraMsg = absl::Substitute( "the value $0 is negative, but the underlying type $1 is unsigned", - P4::Util::toString(constant->value, 0, type->isSigned).string_view(), - type->toString().string_view()); + P4::Util::toString(constant->value, 0, type->isSigned), type->toString()); } else { extraMsg = absl::Substitute( "the value $0 requires $1 bits but the underlying " "$2 type $3 only contains $4 bits", - P4::Util::toString(constant->value, 0, type->isSigned).string_view(), required, - (type->isSigned ? "signed" : "unsigned"), type->toString().string_view(), - type->size); + P4::Util::toString(constant->value, 0, type->isSigned), required, + (type->isSigned ? "signed" : "unsigned"), type->toString(), type->size); } P4::error(ErrorType::ERR_TYPE_ERROR, "%1%: Serialized enum constant value %2% is out of bounds of the underlying " diff --git a/frontends/p4/uniqueNames.h b/frontends/p4/uniqueNames.h index fd00b0a1652..3c78aefae19 100644 --- a/frontends/p4/uniqueNames.h +++ b/frontends/p4/uniqueNames.h @@ -97,7 +97,7 @@ class FindSymbols : public Inspector { } void doDecl(const IR::Declaration *decl) { - cstring newName = nameGen.newName(decl->getName().name.string_view()); + cstring newName = nameGen.newName(decl->getName().string_view()); renameMap->setNewName(decl, newName); } void postorder(const IR::Declaration_Variable *decl) override { doDecl(decl); } @@ -170,7 +170,7 @@ class FindParameters : public Inspector { void doParameters(const IR::ParameterList *pl) { for (auto p : pl->parameters) { - cstring newName = nameGen.newName(p->name.name.string_view()); + cstring newName = nameGen.newName(p->name.string_view()); renameMap->setNewName(p, newName); } } diff --git a/ir/base.def b/ir/base.def index e1f4be4cb2d..4b9ceea30e0 100644 --- a/ir/base.def +++ b/ir/base.def @@ -193,11 +193,11 @@ class Path { bool isDontCare() const { return name.isDontCare(); } toString{ // This is the ORIGINAL name the user used - return absl::StrCat(absolute ? "." : "", name.toString().string_view()); + return absl::StrCat(absolute ? "." : "", name.toString()); } cstring asString() const { // The CURRENT internal name - return absl::StrCat(absolute ? "." : "", name.string_view()); + return absl::StrCat(absolute ? "." : "", name); } dbprint { out << name; } validate { BUG_CHECK(!name.name.isNullOrEmpty(), "Empty path"); } @@ -288,7 +288,7 @@ class Annotation { static const cstring matchAnnotation; /// Match annotation (for value sets). static const cstring fieldListAnnotation; /// Used for recirculate, etc. static const cstring debugLoggingAnnotation; /// Used by compiler implementer to limit debug log to the annotated IR context. - toString{ return absl::StrCat("@", name.string_view()); } + toString{ return absl::StrCat("@", name); } validate{ BUG_CHECK(!name.name.isNullOrEmpty(), "empty annotation name"); BUG_CHECK(!(needsParsing && !expr.empty()), @@ -395,8 +395,8 @@ class Argument { toString{ std::string result = ""; if (!name.name.isNullOrEmpty()) - absl::StrAppend(&result, name.toString().string_view(), " = "); - return absl::StrCat(result, expression->toString().string_view()); + absl::StrAppend(&result, name, " = "); + return absl::StrCat(result, expression); } } diff --git a/ir/expression.def b/ir/expression.def index dc8e00b71f2..289d22b07b8 100644 --- a/ir/expression.def +++ b/ir/expression.def @@ -293,7 +293,7 @@ class BoolLiteral : Literal { class StringLiteral : Literal { cstring value; validate{ if (value.isNull()) BUG("null StringLiteral"); } - toString{ return absl::StrCat("\"", value.escapeJson().string_view(), "\""); } + toString{ return absl::StrCat("\"", value.escapeJson(), "\""); } StringLiteral(ID v) : Literal(v.srcInfo), value(v.name) {} #emit operator IR::ID() const { return IR::ID(srcInfo, value); } @@ -333,9 +333,7 @@ abstract AbstractSlice : Operation_Ternary { class Slice : AbstractSlice { precedence = DBPrint::Prec_Postfix; stringOp = "[:]"; - toString{ return absl::StrCat(e0->toString().string_view(), - "[", e1->toString().string_view(), ":", - e2->toString().string_view(), "]"); } + toString{ return absl::StrCat(e0, "[", e1, ":", e2, "]"); } // After type checking e1 and e2 will be constants unsigned getH() const override { return e1->checkedTo()->asUnsigned(); } unsigned getL() const override { return e2->checkedTo()->asUnsigned(); } @@ -353,9 +351,7 @@ class Slice : AbstractSlice { class PlusSlice : AbstractSlice { precedence = DBPrint::Prec_Postfix; stringOp = "[+:]"; - toString{ return absl::StrCat(e0->toString().string_view(), - "[", e1->toString().string_view(), "+:", - e2->toString().string_view(), "]"); } + toString{ return absl::StrCat(e0, "[", e1, "+:", e2, "]"); } unsigned getH() const override { BUG_CHECK(e1->is(), "non-const PlusSlice not handled"); return e1->to()->asUnsigned() + e2->checkedTo()->asUnsigned() - 1; } @@ -376,7 +372,7 @@ class Member : Operation_Unary { int lsb() const; int msb() const; stringOp = "."; - toString{ return absl::StrCat(expr->toString().string_view(), ".", member.string_view()); } + toString{ return absl::StrCat(expr, ".", member); } } class Concat : Operation_Binary { @@ -396,7 +392,7 @@ class ArrayIndex : Operation_Binary { ArrayIndex { if (auto st = left ? left->type->to() : nullptr) type = st->elementType; } - toString{ return absl::StrCat(left->toString().string_view(), "[", right->toString().string_view(), "]"); } + toString{ return absl::StrCat(left, "[", right, "]"); } } class Range : Operation_Binary { @@ -440,7 +436,7 @@ class Cast : Operation_Unary { /// type, and 'type' will only be updated later when type inferencing occurs precedence = DBPrint::Prec_Prefix; stringOp = "(cast)"; - toString{ return absl::StrCat("(", destType->toString().string_view(), ")", expr->toString().string_view()); } + toString{ return absl::StrCat("(", destType, ")", expr); } validate{ BUG_CHECK(!destType->is(), "%1%: Cannot cast to unknown type", this); } } @@ -464,10 +460,10 @@ class MethodCallExpression : Expression { optional Vector arguments = new Vector; toString { return - absl::StrCat(method->toString().string_view(), "(", + absl::StrCat(method, "(", absl::StrJoin(*arguments, ", ", [](std::string *out, const Argument *arg) { - absl::StrAppend(out, arg->toString().string_view()); + absl::StrAppend(out, arg); }), ")"); } @@ -510,7 +506,7 @@ class BaseListExpression : Expression { absl::StrCat("{ ", absl::StrJoin(components, ", ", [](std::string *out, const Expression *comp) { - absl::StrAppend(out, comp->toString().string_view()); + absl::StrAppend(out, comp); }), " }"); } @@ -564,10 +560,7 @@ class StructExpression : Expression { absl::StrCat("{ ", absl::StrJoin(components, ", ", [](std::string *out, const NamedExpression *comp) { - absl::StrAppend(out, - comp->toString().string_view(), - " = ", - comp->expression->toString().string_view()); + absl::StrAppend(out, comp, " = ", comp->expression); }), " }"); } @@ -652,7 +645,7 @@ class SymbolicVariable : Expression { return label < other.label; } - toString { return absl::StrCat("|", label.string_view(), "(", type->toString().string_view(), ")|"); } + toString { return absl::StrCat("|", label, "(", type, ")|"); } dbprint { out << "|" + label +"(" << type << ")|"; } } diff --git a/ir/id.h b/ir/id.h index ee0a4e6acf2..92c344d2c3d 100644 --- a/ir/id.h +++ b/ir/id.h @@ -38,9 +38,10 @@ struct ID : Util::IHasSourceInfo, public IHasDbPrint { ID(Util::SourceInfo si, cstring n) : srcInfo(si), name(n), originalName(n) { if (n.isNullOrEmpty()) BUG("Identifier with no name"); } + // FIXME: Replace with single string_view constructor ID(const char *n) : ID(Util::SourceInfo(), cstring(n)) {} // NOLINT(runtime/explicit) ID(cstring n) : ID(Util::SourceInfo(), n) {} // NOLINT(runtime/explicit) - ID(std::string n) : ID(Util::SourceInfo(), n) {} // NOLINT(runtime/explicit) + ID(const std::string &n) : ID(Util::SourceInfo(), n) {} // NOLINT(runtime/explicit) ID(cstring n, cstring old) : ID(Util::SourceInfo(), n, old) {} void dbprint(std::ostream &out) const override { out << name; @@ -65,6 +66,11 @@ struct ID : Util::IHasSourceInfo, public IHasDbPrint { bool isDontCare() const { return name == "_"; } Util::SourceInfo getSourceInfo() const override { return srcInfo; } cstring toString() const override { return originalName.isNullOrEmpty() ? name : originalName; } + + template + friend void AbslStringify(Sink &sink, const ID &id) { + sink.Append(id.string_view()); + } }; } // namespace P4::IR diff --git a/ir/ir.def b/ir/ir.def index fa05a513732..233f2d9c114 100644 --- a/ir/ir.def +++ b/ir/ir.def @@ -454,7 +454,7 @@ class ReturnStatement : Statement { NullOK Expression expression; toString{ return absl::StrCat("return ", (expression ? - expression->toString().string_view() : "")); } + expression->toString() : "")); } } class EmptyStatement : Statement { @@ -464,9 +464,7 @@ class EmptyStatement : Statement { class AssignmentStatement : Statement { Expression left; Expression right; - toString{ return absl::StrCat(left->toString().string_view(), - " = ", - right->toString().string_view()); } + toString{ return absl::StrCat(left, " = ", right); } } class IfStatement : Statement { diff --git a/ir/node.h b/ir/node.h index bc6bb23af91..3e0c7af59f1 100644 --- a/ir/node.h +++ b/ir/node.h @@ -165,6 +165,11 @@ class Node : public virtual INode { bool operator!=(const Node &n) const { return !operator==(n); } + template + friend void AbslStringify(Sink &sink, const IR::Node *n) { + sink.Append(n->toString()); + } + DECLARE_TYPEINFO_WITH_TYPEID(Node, NodeKind::Node, INode); }; diff --git a/ir/type.def b/ir/type.def index 2a05cedf514..12866be4de4 100644 --- a/ir/type.def +++ b/ir/type.def @@ -107,7 +107,7 @@ class Type_Any : Type, ITypeVar { class Type_Fragment : Type { Type type; dbprint { out << "FRAGMENT(" << type << ")"; } - toString { return absl::StrCat("FRAGMENT(", type->toString().string_view(), ")"); } + toString { return absl::StrCat("FRAGMENT(", type, ")"); } const Type* getP4Type() const override { return nullptr; } } @@ -120,7 +120,7 @@ class Type_Fragment : Type { /// by type-checking. class Type_Type : Type { Type type; - toString { return absl::StrCat("Type(", type->toString().string_view(), ")"); } + toString { return absl::StrCat("Type(", type, ")"); } dbprint { out << "Type(" << type << ")"; } const Type* getP4Type() const override { return type; } validate { BUG_CHECK(!type->is(), "%1%: nested Type_Type", type); } @@ -168,7 +168,7 @@ class Type_Bits : Type_Base { cstring baseName() const { return isSigned ? "int"_cs : "bit"_cs; } int width_bits() const override { return size; } - toString{ return absl::StrCat(baseName().string_view(), "<", size, ">"); } + toString{ return absl::StrCat(baseName(), "<", size, ">"); } dbprint { out << toString(); } } @@ -226,7 +226,7 @@ class ParameterList : ISimpleNamespace { toString { return absl::StrJoin(parameters, ", ", [](std::string *out, const auto *p) { - absl::StrAppend(out, p->toString().string_view()); + absl::StrAppend(out, p); }); } #emit @@ -325,7 +325,7 @@ class TypeParameters : ISimpleNamespace { return absl::StrCat("<", absl::StrJoin(parameters, ", ", [](std::string *out, const auto *p) { - absl::StrAppend(out, p->toString().string_view()); + absl::StrAppend(out, p); }), ">"); } @@ -430,7 +430,7 @@ class Type_Header : Type_StructLike { class Type_Set : Type { Type elementType; dbprint{ Node::dbprint(out); out << "<" << elementType << ">"; } - toString { return absl::StrCat("set<", elementType->toString().string_view(), ">"); } + toString { return absl::StrCat("set<", elementType, ">"); } const Type* getP4Type() const override { return nullptr; } int width_bits() const override { /// returning the width of the set elements, not the set itself, which doesn't @@ -464,7 +464,7 @@ abstract Type_BaseList : Type, Type_Indexed { "<", absl::StrJoin(components, ", ", [](std::string *out, const auto *t) { - absl::StrAppend(out, t->toString().string_view()); + absl::StrAppend(out, t); }), ">"); } @@ -495,7 +495,7 @@ class Type_P4List : Type { Type elementType; const Type* getP4Type() const override; toString{ - return absl::StrCat("list<", elementType->toString().string_view(), ">"); + return absl::StrCat("list<", elementType, ">"); } } @@ -564,9 +564,9 @@ class Type_Stack : Type_Indexed, Type { Expression size; toString{ return - absl::StrCat(elementType->toString().string_view(), + absl::StrCat(elementType, "[", - sizeKnown() ? size->toString().string_view() : "?", + sizeKnown() ? size->toString() : "?", "]"); } dbprint{ out << elementType << "[" << size << "]"; } bool sizeKnown() const; @@ -595,11 +595,11 @@ class Type_Specialized : Type { const Type* getP4Type() const override; toString{ return - absl::StrCat(baseType->toString().string_view(), + absl::StrCat(baseType, "<", absl::StrJoin(*arguments, ", ", [](std::string *out, const auto *t) { - absl::StrAppend(out, t->toString().string_view()); + absl::StrAppend(out, t); }), ">"); } diff --git a/lib/bug_helper.h b/lib/bug_helper.h index c8f52eec75e..83d23fcf748 100644 --- a/lib/bug_helper.h +++ b/lib/bug_helper.h @@ -36,7 +36,7 @@ namespace detail { static inline std::pair getPositionTail(const Util::SourceInfo &info, std::string_view position, std::string_view tail) { - std::string_view posString = info.toPositionString().string_view(); + std::string_view posString = info.toPositionString(); std::string outTail(tail); if (position.empty()) { position = posString; diff --git a/lib/cstring.h b/lib/cstring.h index 08da01e4d86..035c92315b9 100644 --- a/lib/cstring.h +++ b/lib/cstring.h @@ -118,7 +118,7 @@ class cstring { // construct cstring from std::string_view. Do not use if possible, this is linear // time operation if string not exists in table, because the underlying string must be copied. - explicit cstring(std::string_view string) { // NOLINT(runtime/explicit) + explicit cstring(std::string_view string) { construct_from_shared(string.data(), string.length()); } @@ -178,7 +178,7 @@ class cstring { template cstring(Iter begin, Iter end) { - *this = std::string(begin, end); + *this = cstring(std::string(begin, end)); } char get(unsigned index) const { return (index < size()) ? str[index] : 0; } @@ -191,7 +191,7 @@ class cstring { std::string_view string_view() const { return str ? std::string_view(str) : std::string_view(""); } - explicit operator std::string_view() const { return string_view(); } + operator std::string_view() const { return string_view(); } // Size tests. Constant time except for size(), which is linear time. size_t size() const { @@ -202,6 +202,7 @@ class cstring { } bool isNull() const { return str == nullptr; } bool isNullOrEmpty() const { return str == nullptr ? true : str[0] == 0; } + explicit operator bool() const { return str; } // iterate over characters const char *begin() const { return str; } @@ -307,6 +308,11 @@ class cstring { cstring capitalize() const; /// Append this many spaces after each newline (and before the first string). cstring indent(size_t amount) const; + + template + friend void AbslStringify(Sink &sink, cstring s) { + sink.Append(s.string_view()); + } }; inline bool operator==(const char *a, cstring b) { return b == a; } @@ -350,19 +356,19 @@ inline std::string operator+(char a, cstring b) { } inline cstring cstring::operator+=(cstring a) { - *this = *this + a; + *this = cstring(*this + a); return *this; } inline cstring cstring::operator+=(const char *a) { - *this = *this + a; + *this = cstring(*this + a); return *this; } inline cstring cstring::operator+=(std::string a) { - *this = *this + a; + *this = cstring(*this + a); return *this; } inline cstring cstring::operator+=(char a) { - *this = *this + a; + *this = cstring(*this + a); return *this; } @@ -382,7 +388,7 @@ cstring cstring::make_unique(const T &inuse, cstring base, int &counter, char se cstring rv = base; do { snprintf(suffix, sizeof(suffix) / sizeof(suffix[0]), "%c%d", sep, counter++); - rv = base + suffix; + rv = cstring(base + (const char *)suffix); } while (inuse.count(rv)); return rv; } @@ -394,7 +400,7 @@ cstring cstring::make_unique(const T &inuse, cstring base, char sep) { } inline std::ostream &operator<<(std::ostream &out, cstring s) { - return out << (s ? s.c_str() : ""); + return out << (s.isNull() ? "" : s.string_view()); } } // namespace P4 diff --git a/lib/json.cpp b/lib/json.cpp index f2252502a47..28117557671 100644 --- a/lib/json.cpp +++ b/lib/json.cpp @@ -187,7 +187,7 @@ JsonObject *JsonObject::emplace(std::string_view label, IJson *value) { throw std::logic_error( absl::StrCat("Attempt to add to json object a value " "for a label which already exists ", - label, " ", s.string_view())); + label, " ", s)); } base::emplace(label, value); return this; diff --git a/lib/options.cpp b/lib/options.cpp index cc05daf7f96..4553bd981d8 100644 --- a/lib/options.cpp +++ b/lib/options.cpp @@ -77,7 +77,7 @@ std::vector *Util::Options::process(int argc, char *const argv[]) // If there's no such option, try single-character options. if (option == nullptr && opt.size() > 2) { - arg = opt.substr(2); + arg = opt.substr(2).c_str(); opt = opt.substr(0, 2); option = get(options, opt); } @@ -91,7 +91,7 @@ std::vector *Util::Options::process(int argc, char *const argv[]) } if (option == nullptr) { - remainingOptions.push_back(opt); + remainingOptions.push_back(opt.c_str()); } else { if (option->argName != nullptr && arg == nullptr && !(option->flags & OptionFlags::OptionalArgument)) { @@ -137,7 +137,7 @@ void Util::Options::usage() { for (const auto &o : optionOrder) { auto option = get(options, o); CHECK_NULL(option); - size_t len = strlen(o); + size_t len = o.size(); if (option->flags & OptionFlags::Hide) continue; *outStream << option->option; if (option->argName != nullptr) { diff --git a/lib/source_file.cpp b/lib/source_file.cpp index ac44e8fba10..0cb862dc9df 100644 --- a/lib/source_file.cpp +++ b/lib/source_file.cpp @@ -58,14 +58,11 @@ SourceInfo::SourceInfo(const InputSources *sources, SourcePosition start, Source } cstring SourceInfo::toString() const { - return absl::StrFormat("(%s)-(%s)", start.toString().string_view(), - end.toString().string_view()); + return absl::StrFormat("(%v)-(%v)", start.toString(), end.toString()); } std::ostream &operator<<(std::ostream &os, const SourceInfo &info) { - // FIXME: implement abseil stringify to skip cstring conversion here - os << absl::StrFormat("(%s)-(%s)", info.start.toString().string_view(), - info.end.toString().string_view()); + os << absl::StrFormat("(%v)-(%v)", info.start, info.end); return os; } @@ -312,7 +309,7 @@ cstring InputSources::toDebugString() const { builder << "---------------" << std::endl; for (const auto &lf : line_file_map) builder << lf.first << ": " << lf.second.toString() << std::endl; - return builder.str(); + return {builder}; } /////////////////////////////////////////////////// @@ -360,9 +357,7 @@ cstring SourceInfo::getLineNum() const { //////////////////////////////////////////////////////// -cstring SourceFileLine::toString() const { - return absl::StrFormat("%s(%d)", fileName.string_view(), sourceLine); -} +cstring SourceFileLine::toString() const { return absl::StrFormat("%v(%d)", fileName, sourceLine); } } // namespace P4::Util diff --git a/lib/source_file.h b/lib/source_file.h index 3958dd8cca1..32627a3bb43 100755 --- a/lib/source_file.h +++ b/lib/source_file.h @@ -26,6 +26,7 @@ limitations under the License. #include #include +#include "absl/strings/str_format.h" #include "cstring.h" #include "stringify.h" @@ -103,6 +104,11 @@ class SourcePosition final { unsigned getColumnNumber() const { return columnNumber; } + template + friend void AbslStringify(Sink &sink, const SourcePosition &p) { + absl::Format(&sink, "%d:%d", p.lineNumber, p.columnNumber); + } + private: // Input sources where this character position is interpreted. unsigned lineNumber = 0; @@ -259,7 +265,7 @@ class Comment final : IHasDbPrint, IHasSourceInfo { cstring toString() const override { std::stringstream str; dbprint(str); - return str.str(); + return {str}; } void dbprint(std::ostream &out) const override { if (singleLine) diff --git a/lib/stringify.h b/lib/stringify.h index 56430cec668..d46ad92f41e 100644 --- a/lib/stringify.h +++ b/lib/stringify.h @@ -89,7 +89,7 @@ inline constexpr bool has_toString_v = has_toString::value; template ()))> cstring toString(T value) { - return std::to_string(value); + return cstring(std::to_string(value)); } template diff --git a/midend/flattenInterfaceStructs.cpp b/midend/flattenInterfaceStructs.cpp index 87ae4b57c00..18156b44314 100644 --- a/midend/flattenInterfaceStructs.cpp +++ b/midend/flattenInterfaceStructs.cpp @@ -74,7 +74,7 @@ const IR::Node *ReplaceStructs::postorder(IR::Member *expression) { std::string prefix; while (auto mem = e->to()) { e = mem->expr; - prefix = absl::StrCat(".", mem->member.string_view(), prefix); + prefix = absl::StrCat(".", mem->member, prefix); } auto pe = e->to(); if (pe == nullptr) return expression; diff --git a/midend/nestedStructs.cpp b/midend/nestedStructs.cpp index c8ae8409e51..3cdd79fa43e 100644 --- a/midend/nestedStructs.cpp +++ b/midend/nestedStructs.cpp @@ -25,7 +25,7 @@ void ComplexValues::explode(std::string_view prefix, const IR::Type_Struct *type IR::Vector *result) { CHECK_NULL(type); for (const auto *f : type->fields) { - std::string fname = absl::StrCat(prefix, "_", f->name.string_view()); + std::string fname = absl::StrCat(prefix, "_", f->name); auto ftype = typeMap->getType(f, true); if (isNestedStruct(ftype)) { auto submap = new FieldsMap(ftype); diff --git a/tools/ir-generator/ir-generator.ypp b/tools/ir-generator/ir-generator.ypp index 05e6fe03471..294ab363ad8 100644 --- a/tools/ir-generator/ir-generator.ypp +++ b/tools/ir-generator/ir-generator.ypp @@ -272,7 +272,7 @@ method yyerror("'%s' invalid on method", IrMethod::modifier(mod)); } optArgList ')' optConst optOverride body { ($$ = $5)->body = $10; - if (!$10 || $10[0] == '=') { + if (!$10 || $10.startsWith("=")) { if (!$$->inImpl) yyerror("inline method %s with no body", $3); $$->inImpl = false; } @@ -361,7 +361,7 @@ nonRefType | lookup_scope IDENTIFIER { $$ = new NamedType(@2, $1, $2); } | lookup_scope OPTIONAL { $$ = new NamedType(@2, $1, "optional"_cs); } | nonRefType '<' type_args '>' { $$ = new TemplateInstantiation(@1+@4, $1, *$3); } - | nonRefType '[' INTEGER ']' { $$ = new ArrayType(@1+@4, $1, atoi($3)); } + | nonRefType '[' INTEGER ']' { $$ = new ArrayType(@1+@4, $1, atoi($3.c_str())); } ; type: nonRefType diff --git a/tools/ir-generator/methods.cpp b/tools/ir-generator/methods.cpp index eef3da6af31..0c5e84efbc8 100644 --- a/tools/ir-generator/methods.cpp +++ b/tools/ir-generator/methods.cpp @@ -71,7 +71,7 @@ const ordered_map IrMethod::Generate = { } buf << ";" << std::endl; buf << cl->indent << "}"; - return buf.str(); + return {buf}; }}}, {"equiv"_cs, {&NamedType::Bool(), @@ -126,7 +126,7 @@ const ordered_map IrMethod::Generate = { buf << ";" << std::endl; } buf << cl->indent << "}"; - return buf.str(); + return {buf}; }}}, {"operator<<"_cs, {&ReferenceType::OstreamRef, @@ -137,7 +137,7 @@ const ordered_map IrMethod::Generate = { buf << "{"; if (body) buf << LineDirective(srcInfo, true) << body; buf << LineDirective(true) << cl->indent << "return out; }"; - return buf.str(); + return {buf}; }}}, {"visit_children"_cs, {&NamedType::Void(), @@ -162,7 +162,7 @@ const ordered_map IrMethod::Generate = { needed = true; } buf << "}"; - return needed ? buf.str() : cstring(); + return needed ? buf : cstring(); }}}, {"validate"_cs, {&NamedType::Void(), @@ -189,7 +189,7 @@ const ordered_map IrMethod::Generate = { needed = true; } buf << " }"; - return needed ? buf.str() : cstring(); + return needed ? buf : cstring(); }}}, {"node_type_name"_cs, {&NamedType::Cstring(), @@ -198,7 +198,7 @@ const ordered_map IrMethod::Generate = { [](IrClass *cl, Util::SourceInfo, cstring) -> cstring { std::stringstream buf; buf << "{ return \"" << cl->containedIn << cl->name << "\"_cs; }"; - return buf.str(); + return {buf}; }}}, {"dbprint"_cs, {&NamedType::Void(), @@ -227,7 +227,7 @@ const ordered_map IrMethod::Generate = { } } buf << "}"; - return needed ? buf.str() : cstring(); + return needed ? buf : cstring(); }}}, {"toJSON"_cs, {&NamedType::Void(), @@ -247,7 +247,7 @@ const ordered_map IrMethod::Generate = { << "\\\" : \" << " << "this->" << f->name << ";" << std::endl; } buf << "}"; - return buf.str(); + return {buf}; }}}, {nullptr, {nullptr, @@ -264,7 +264,7 @@ const ordered_map IrMethod::Generate = { << std::endl; } buf << "}"; - return buf.str(); + return {buf}; }}}, {"fromJSON"_cs, {nullptr, @@ -275,7 +275,7 @@ const ordered_map IrMethod::Generate = { [](IrClass *cl, Util::SourceInfo, cstring) -> cstring { std::stringstream buf; buf << "{ return new " << cl->name << "(json); }"; - return buf.str(); + return {buf}; }}}, {"toString"_cs, {&NamedType::Cstring(), diff --git a/tools/ir-generator/type.h b/tools/ir-generator/type.h index f82e52595fe..3c7b31aabb4 100644 --- a/tools/ir-generator/type.h +++ b/tools/ir-generator/type.h @@ -19,6 +19,7 @@ limitations under the License. #include +#include "absl/strings/str_cat.h" #include "lib/cstring.h" #include "lib/source_file.h" @@ -67,7 +68,7 @@ struct LookupScope : public Util::IHasSourceInfo { Util::SourceInfo getSourceInfo() const override { return srcInfo; } cstring toString() const override { if (global) return "IR::"_cs; - return (in ? in->toString() + name : name) + "::"_cs; + return absl::StrCat(in ? in->toString() : "", name, "::"); } IrNamespace *resolve(const IrNamespace *) const; bool operator==(const LookupScope &l) const {