CIRCT 24.0.0git
Loading...
Searching...
No Matches
TypedPorts.h
Go to the documentation of this file.
1//===- TypedPorts.h - Strongly-typed ESI port wrappers ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DO NOT EDIT!
10// This file is distributed as part of an ESI package. The source for this file
11// should always be modified within CIRCT.
12//
13//===----------------------------------------------------------------------===//
14//
15// Thin, non-owning wrappers around WriteChannelPort / ReadChannelPort that
16// verify type compatibility at connect() time and provide strongly-typed
17// write/read APIs. Purely additive — no changes to the untyped port classes.
18//
19//===----------------------------------------------------------------------===//
20
21// NOLINTNEXTLINE(llvm-header-guard)
22#ifndef ESI_TYPED_PORTS_H
23#define ESI_TYPED_PORTS_H
24
25#include "esi/Design.h"
26#include "esi/Ports.h"
27#include "esi/Services.h"
28#include "esi/Types.h"
29
30#include <algorithm>
31#include <array>
32#include <cstdint>
33#include <cstring>
34#include <functional>
35#include <future>
36#include <map>
37#include <memory>
38#include <mutex>
39#include <optional>
40#include <queue>
41#include <stdexcept>
42#include <string>
43#include <string_view>
44#include <type_traits>
45#include <typeinfo>
46
47namespace esi {
48
49//===----------------------------------------------------------------------===//
50// AcceleratorMismatchError — thrown for type mismatches and port-not-found.
51//===----------------------------------------------------------------------===//
52
53class AcceleratorMismatchError : public std::runtime_error {
54public:
55 using std::runtime_error::runtime_error;
56};
57
58//===----------------------------------------------------------------------===//
59// Helpers: unwrap TypeAliasType and width-aware serialization.
60//===----------------------------------------------------------------------===//
61
62/// Compute the wire byte count for a port type. Returns 0 if not a
63/// BitVectorType (meaning sizeof(T) should be used instead).
64/// Wire format info for a port type, cached at connect() time.
65struct WireInfo {
66 size_t bytes = 0; // (bitWidth+7)/8, or 0 if not a BitVectorType.
67 size_t bitWidth = 0;
68};
69
70inline WireInfo getWireInfo(const Type *portType) {
71 const Type *inner = unwrapTypeAlias(portType);
72 if (auto *bv = dynamic_cast<const BitVectorType *>(inner))
73 return {(bv->getWidth() + 7) / 8, bv->getWidth()};
74 return {};
75}
76
77/// Pack a C++ integral value into a MessageData with the given wire byte count.
78/// If wi.bytes is 0, falls back to sizeof(T).
79template <typename T>
81 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
82 if (wi.bytes > 0 && wi.bytes != sizeof(T)) {
83 std::vector<uint8_t> buf(wi.bytes, 0);
84 std::memcpy(buf.data(), &data, std::min(wi.bytes, sizeof(T)));
85 return MessageData(std::move(buf));
86 }
87 } else if constexpr (std::is_base_of_v<SegmentedMessageData, T>) {
88 return data.toMessageData();
89 }
90 return MessageData(reinterpret_cast<const uint8_t *>(&data), sizeof(T));
91}
92
93template <typename T>
94MessageData toMessageData(const T &data, const Type *portType) {
95 return toMessageData(data, getWireInfo(portType));
96}
97
98/// Unpack a MessageData into a C++ integral value with the given wire info.
99/// If the wire size differs from sizeof(T), copies available bytes into
100/// a zero-initialized value and sign-extends for signed types using the
101/// actual bit width to locate the sign bit.
102template <typename T>
104 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
105 if (wi.bytes > 0 && msg.getSize() == wi.bytes &&
106 wi.bitWidth < sizeof(T) * 8) {
107 // Copy wire bytes into a zero-initialized value.
108 T val = 0;
109 std::memcpy(&val, msg.getBytes(), std::min(wi.bytes, sizeof(T)));
110 // Sign-extend for signed types if the sign bit is set.
111 if constexpr (std::is_signed_v<T>) {
112 size_t signBit = wi.bitWidth - 1;
113 size_t signByte = signBit / 8;
114 uint8_t signMask = uint8_t(1) << (signBit % 8);
115 if (signByte < wi.bytes && (msg.getBytes()[signByte] & signMask)) {
116 // Set all bits above the sign bit to 1.
117 if (wi.bitWidth < sizeof(T) * 8)
118 val |= static_cast<T>(~T(0)) << wi.bitWidth;
119 }
120 }
121 return val;
122 }
123 }
124 return *msg.as<T>();
125}
126
127template <typename T>
128T fromMessageData(const MessageData &msg, const Type *portType) {
129 return fromMessageData<T>(msg, getWireInfo(portType));
130}
131
132namespace detail {
133
134/// Owning callback used by typed read deserializers.
135///
136/// Returning `false` means the callee did not accept the object and wants the
137/// exact same owned value retried later.
138template <typename T>
139using TypedReadOwnedCallback = std::function<bool(std::unique_ptr<T> &)>;
140
141template <typename T, typename = void>
142struct has_type_deserializer : std::false_type {};
143
144template <typename T>
145struct has_type_deserializer<T, std::void_t<typename T::TypeDeserializer>>
146 : std::true_type {};
147
148template <typename T>
150
151/// Default deserializer for simple 1:1 typed reads.
152///
153/// This path converts one raw message into one typed value and forwards it to
154/// the typed callback. If the callback rejects the decoded object, preserve it
155/// until the raw message is retried so the same owned object is presented
156/// again.
157template <typename T>
159public:
161
164
165 bool push(std::unique_ptr<SegmentedMessageData> &msg) {
166 std::scoped_lock<std::mutex> lock(mutex);
167 if (!msg)
168 throw std::runtime_error("PODTypeDeserializer::push: null message");
169
170 // Flush the buffer, bail if still full.
171 pokeLocked();
172 if (pendingOutput)
173 return false;
174
175 // Translate the raw message into a typed object. This always consumes the
176 // raw message.
177 MessageData scratch;
178 const MessageData &flat = msg->asMessageData(scratch);
179 pendingOutput = std::make_unique<T>(fromMessageData<T>(flat, wireInfo));
180 msg.reset();
181 pokeLocked();
182 return true;
183 }
184
185 bool poke() {
186 std::scoped_lock<std::mutex> lock(mutex);
187 return pokeLocked();
188 }
189
190private:
191 bool pokeLocked() {
193 pendingOutput.reset();
194 return true;
195 }
196 return false;
197 }
198
201 std::mutex mutex;
202 std::unique_ptr<T> pendingOutput;
203};
204
205template <typename T, typename = void>
209
210template <typename T>
211struct DeserializerSelector<T, std::void_t<typename T::TypeDeserializer>> {
212 using type = typename T::TypeDeserializer;
213};
214
215template <typename T>
217
218template <typename T>
220
221} // namespace detail
222
223/// Helper base class for stateful deserializers which may emit zero, one, or
224/// many typed outputs for each raw input message.
225///
226/// Derived classes implement `decode()` and must consume the raw input message
227/// before returning. This base class handles retrying blocked typed outputs and
228/// preserving them in FIFO order until the client accepts them.
229template <typename T>
231public:
233 using DecodedOutputs = std::vector<std::unique_ptr<T>>;
234
237
238 virtual ~QueuedDecodeTypeDeserializer() = default;
239
240 /// Push one raw message into the deserializer.
241 ///
242 /// Returns `false` only when previously decoded typed outputs are still
243 /// blocked on delivery. In that case `msg` is left untouched so the caller
244 /// can retry it later.
245 bool push(std::unique_ptr<SegmentedMessageData> &msg) {
246 std::scoped_lock<std::mutex> lock(mutex);
247 if (!msg)
248 throw std::runtime_error(
249 "QueuedDecodeTypeDeserializer::push: null message");
250
251 if (!pokeLocked())
252 return false;
253
254 DecodedOutputs decoded = decode(msg);
255 if (msg)
256 throw std::runtime_error(
257 "QueuedDecodeTypeDeserializer::push: decode must consume the "
258 "message");
259 for (std::unique_ptr<T> &value : decoded) {
260 if (!value)
261 throw std::runtime_error(
262 "QueuedDecodeTypeDeserializer::push: null decoded output");
263 pendingOutputs.push(std::move(value));
264 }
265
266 // Once decode() has consumed the raw message, keep any blocked typed
267 // outputs in the pending queue and report success. pokeLocked() still
268 // opportunistically drains what it can before returning.
269 pokeLocked();
270 return true;
271 }
272
273 /// Retry delivery of any typed outputs which were previously blocked by the
274 /// client callback.
275 bool poke() {
276 std::scoped_lock<std::mutex> lock(mutex);
277 return pokeLocked();
278 }
279
280protected:
281 /// Decode one raw message into zero or more typed outputs.
282 ///
283 /// Implementations must consume `msg` before returning, even when zero
284 /// outputs are produced.
285 virtual DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) = 0;
286
287private:
288 bool pokeLocked() {
289 while (!pendingOutputs.empty()) {
290 std::unique_ptr<T> &value = pendingOutputs.front();
291 if (!value)
292 throw std::runtime_error(
293 "QueuedDecodeTypeDeserializer::poke: null pending output");
294 if (!output(value))
295 return false;
296 pendingOutputs.pop();
297 }
298 return true;
299 }
300
302 std::queue<std::unique_ptr<T>> pendingOutputs;
303 std::mutex mutex;
304};
305
306/// Reusable serial-list window deserializer.
307///
308/// Walks the serial-list multi-burst protocol used by codegen'd window
309/// helpers -- zero or more `header(N>0) + N data` bursts terminated by a
310/// `header(0)` footer -- and emits a fully-formed `T` instance built from the
311/// accumulated header fields and data frames.
312///
313/// `T` must be a generated window helper that exposes:
314/// - nested `header_frame` / `data_frame` types of identical size,
315/// - `count_type`,
316/// - `static count_type T::_headerCount(const header_frame &)`,
317/// - `static std::unique_ptr<T> T::_fromFrames(const header_frame &,
318/// std::vector<data_frame> &&)`.
319///
320/// `T` typically declares `SerialListTypeDeserializer<T>` as a friend so the
321/// template can reach the (private) `header_frame` definition; the helpers
322/// themselves can stay private as well.
323template <typename T>
325public:
329
332
333private:
334 using header_frame = typename T::header_frame;
335 using data_frame = typename T::data_frame;
336 using count_type = typename T::count_type;
337
338 static_assert(sizeof(header_frame) == sizeof(data_frame),
339 "header and data frames must be the same width");
340 static constexpr size_t kFrameSize = sizeof(data_frame);
341
342 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) override {
343 DecodedOutputs out;
344 MessageData scratch;
345 const MessageData &flat = msg->asMessageData(scratch);
346 const uint8_t *bytes = flat.getBytes();
347 size_t size = flat.getSize();
348
349 size_t offset = 0;
350 while (offset < size) {
351 size_t needed = kFrameSize - partial_.size();
352 size_t chunk = std::min(needed, size - offset);
353 partial_.insert(partial_.end(), bytes + offset, bytes + offset + chunk);
354 offset += chunk;
355 if (partial_.size() != kFrameSize)
356 break;
357
358 if (remaining_ == 0) {
359 // Header or footer frame. Decode into a local frame first so we can
360 // inspect the count without committing. Only the first header of a
361 // transaction is guaranteed to carry valid static fields; the static
362 // slots of continuation and footer headers may be garbage.
363 header_frame frame{};
364 std::memcpy(&frame, partial_.data(), kFrameSize);
365 partial_.clear();
366 count_type batchCount = T::_headerCount(frame);
367 if (batchCount == 0) {
368 // Footer: emit the accumulated value using the first header's
369 // static fields.
370 if (!pending_header_)
371 throw std::runtime_error(
372 "SerialListTypeDeserializer: footer received before any "
373 "header");
374 out.push_back(
375 T::_fromFrames(*pending_header_, std::move(pending_frames_)));
376 pending_frames_.clear();
377 pending_header_.reset();
378 continue;
379 }
380
381 if (!pending_header_)
382 pending_header_ = frame;
383 remaining_ = batchCount;
384 continue;
385 }
386
387 // Data frame.
388 auto &frame = pending_frames_.emplace_back();
389 std::memcpy(&frame, partial_.data(), kFrameSize);
390 partial_.clear();
391 --remaining_;
392 }
393
394 msg.reset();
395 return out;
396 }
397
398 std::vector<uint8_t> partial_;
399 std::optional<header_frame> pending_header_;
400 std::vector<data_frame> pending_frames_;
402};
403
404//===----------------------------------------------------------------------===//
405// Type-trait: detect T::_ESI_ID (a static constexpr std::string_view).
406//===----------------------------------------------------------------------===//
407
408template <typename T, typename = void>
409struct has_esi_id : std::false_type {};
410
411template <typename T>
412struct has_esi_id<T, std::void_t<decltype(T::_ESI_ID)>>
413 : std::is_convertible<decltype(T::_ESI_ID), std::string_view> {};
414
415template <typename T>
416inline constexpr bool has_esi_id_v = has_esi_id<T>::value;
417
418// Detect T::_ESI_WINDOW_ID (a static constexpr std::string_view) for
419// generated SegmentedMessageData subclasses bound to a specific WindowType.
420template <typename T, typename = void>
421struct has_esi_window_id : std::false_type {};
422
423template <typename T>
424struct has_esi_window_id<T, std::void_t<decltype(T::_ESI_WINDOW_ID)>>
425 : std::is_convertible<decltype(T::_ESI_WINDOW_ID), std::string_view> {};
426
427template <typename T>
429
430//===----------------------------------------------------------------------===//
431// verifyTypeCompatibility<T>(const Type *portType)
432//
433// Checks that the ESI runtime Type is compatible with the C++ type T.
434// Dispatch order: _ESI_ID → void → bool → std::array → signed int →
435// unsigned int → error.
436//===----------------------------------------------------------------------===//
437
438// Detect ``std::array<T, N>``.
439template <typename T>
440struct is_std_array : std::false_type {};
441template <typename T, std::size_t N>
442struct is_std_array<std::array<T, N>> : std::true_type {};
443template <typename T>
445
446template <typename T>
447void verifyTypeCompatibility(const Type *portType) {
448 if (!portType)
449 throw AcceleratorMismatchError("Port type is null");
450
451 // Unwrap TypeAliasType to get the inner type for verification.
452 portType = unwrapTypeAlias(portType);
453
454 // If the port is a windowed type, verify the window id (if T declares one)
455 // and then continue checking the inner ('into') type.
456 if (auto *windowType = dynamic_cast<const WindowType *>(portType)) {
457 if constexpr (has_esi_window_id_v<T>) {
458 if (std::string_view(windowType->getID()) != T::_ESI_WINDOW_ID)
460 "ESI window mismatch: C++ type has _ESI_WINDOW_ID '" +
461 std::string(T::_ESI_WINDOW_ID) + "' but port window type is '" +
462 windowType->toString(/*oneLine=*/true) + "'");
463 } else {
465 "ESI type mismatch: port is a window type ('" +
466 windowType->toString(/*oneLine=*/true) +
467 "') but C++ type has no _ESI_WINDOW_ID");
468 }
469 portType = unwrapTypeAlias(windowType->getIntoType());
470 } else if constexpr (has_esi_window_id_v<T>) {
472 std::string("ESI type mismatch: C++ type has _ESI_WINDOW_ID '") +
473 std::string(T::_ESI_WINDOW_ID) + "' but port type is not a window: '" +
474 portType->toString(/*oneLine=*/true) + "'");
475 }
476
477 if constexpr (has_esi_id_v<T>) {
478 // Highest priority: user-defined ESI ID string comparison.
479 if (std::string_view(portType->getID()) != T::_ESI_ID)
481 "ESI type mismatch: C++ type has _ESI_ID '" +
482 std::string(T::_ESI_ID) + "' but port type is '" +
483 portType->toString(/*oneLine=*/true) + "'");
484 } else if constexpr (std::is_void_v<T>) {
485 if (!dynamic_cast<const VoidType *>(portType))
486 throw AcceleratorMismatchError("ESI type mismatch: expected VoidType for "
487 "void, but port type is '" +
488 portType->toString(/*oneLine=*/true) +
489 "'");
490 } else if constexpr (std::is_same_v<T, bool>) {
491 // bool maps to signless i1, which is BitsType with width <= 1.
492 auto *bits = dynamic_cast<const BitsType *>(portType);
493 if (!bits || bits->getWidth() > 1)
495 "ESI type mismatch: expected BitsType with width <= 1 for "
496 "bool, but port type is '" +
497 portType->toString(/*oneLine=*/true) + "'");
498 } else if constexpr (is_std_array_v<T>) {
499 // std::array<U, N> maps to ESI ArrayType with matching size and element
500 // type. The ArrayType's `reverse` flag controls only wire-byte ordering
501 // during serialization (handled in toMessageData/fromMessageData) and
502 // does not affect compatibility.
503 using Element = typename T::value_type;
504 constexpr size_t N = std::tuple_size<T>::value;
505 auto *arr = dynamic_cast<const ArrayType *>(portType);
506 if (!arr)
508 "ESI type mismatch: expected ArrayType for std::array, but port "
509 "type is '" +
510 portType->toString(/*oneLine=*/true) + "'");
511 if (arr->getSize() != N)
512 throw AcceleratorMismatchError("ESI type mismatch: ArrayType size " +
513 std::to_string(arr->getSize()) +
514 " does not match std::array size " +
515 std::to_string(N));
516 verifyTypeCompatibility<Element>(arr->getElementType());
517 } else if constexpr (std::is_integral_v<T> && std::is_signed_v<T>) {
518 auto *sint = dynamic_cast<const SIntType *>(portType);
519 if (!sint)
521 "ESI type mismatch: expected SIntType for signed integer, "
522 "but port type is '" +
523 portType->toString(/*oneLine=*/true) + "'");
524 if (sint->getWidth() > sizeof(T) * 8)
526 "ESI type mismatch: SIntType width " +
527 std::to_string(sint->getWidth()) + " does not fit in " +
528 std::to_string(sizeof(T) * 8) + "-bit signed integer");
529 // Require closest-size match: reject if a smaller C++ type would suffice.
530 if (sizeof(T) > 1 && sint->getWidth() <= (sizeof(T) / 2) * 8)
531 throw AcceleratorMismatchError("ESI type mismatch: SIntType width " +
532 std::to_string(sint->getWidth()) +
533 " should use a smaller C++ type than " +
534 std::to_string(sizeof(T) * 8) + "-bit");
535 } else if constexpr (std::is_integral_v<T> && std::is_unsigned_v<T>) {
536 // Accept UIntType (uiM) or BitsType (iM, signless).
537 auto *uintPort = dynamic_cast<const UIntType *>(portType);
538 auto *bits = dynamic_cast<const BitsType *>(portType);
539 if (!uintPort && !bits)
541 "ESI type mismatch: expected UIntType or BitsType for unsigned "
542 "integer, but port type is '" +
543 portType->toString(/*oneLine=*/true) + "'");
544 uint64_t width = uintPort ? uintPort->getWidth() : bits->getWidth();
545 if (width > sizeof(T) * 8)
547 "ESI type mismatch: bit width " + std::to_string(width) +
548 " does not fit in " + std::to_string(sizeof(T) * 8) +
549 "-bit unsigned integer");
550 // Require closest-size match: reject if a smaller C++ type would suffice.
551 if (sizeof(T) > 1 && width <= (sizeof(T) / 2) * 8)
552 throw AcceleratorMismatchError("ESI type mismatch: bit width " +
553 std::to_string(width) +
554 " should use a smaller C++ type than " +
555 std::to_string(sizeof(T) * 8) + "-bit");
556 } else {
558 std::string("Cannot verify type compatibility for C++ type '") +
559 typeid(T).name() + "' against ESI port type '" +
560 portType->toString(/*oneLine=*/true) + "'");
561 }
562}
563
564// Port-aware overload: when checking against a ChannelPort, also reconcile
565// the windowed wrapper. ChannelPort::getType() returns the unwrapped 'into'
566// type for windowed ports, so we have to consult getWindowType() directly to
567// detect the window and forward the original WindowType into the Type-based
568// overload above.
569template <typename T>
571 if (!port)
572 throw AcceleratorMismatchError("Port is null");
573 const WindowType *windowType = port->getWindowType();
574 if constexpr (has_esi_window_id_v<T>) {
575 if (!windowType)
577 std::string("ESI type mismatch: C++ type has _ESI_WINDOW_ID '") +
578 std::string(T::_ESI_WINDOW_ID) +
579 "' but port is not a window type ('" +
580 (port->getType() ? port->getType()->toString(/*oneLine=*/true)
581 : std::string("<null>")) +
582 "')");
583 } else {
584 if (windowType)
586 "ESI type mismatch: port is a window type ('" +
587 windowType->toString(/*oneLine=*/true) +
588 "') but C++ type has no _ESI_WINDOW_ID");
589 }
590 const Type *forwardType =
591 windowType ? static_cast<const Type *>(windowType) : port->getType();
592 verifyTypeCompatibility<T>(forwardType);
593}
594
595//===----------------------------------------------------------------------===//
596// TypedWritePort<T, SkipTypeCheck = false>
597//
598// When SkipTypeCheck is false, the `connect` method runs the type check via
599// `verifyTypeCompatibility<T>()`. When SkipTypeCheck is true, `connect`
600// skips that verification.
601//===----------------------------------------------------------------------===//
602
603template <typename T, bool SkipTypeCheck = false>
605public:
606 explicit TypedWritePort(WriteChannelPort &port) : inner(&port) {}
607 // NOLINTNEXTLINE(google-explicit-constructor)
609
610 void connect(const ChannelPort::ConnectOptions &opts = {std::nullopt,
611 false}) {
612 if (!inner)
613 throw AcceleratorMismatchError("TypedWritePort: null port pointer");
614 if (!SkipTypeCheck)
617 inner->connect(opts);
618 }
619
620 /// Callback mode data source: returns the next value to write, or nullptr
621 /// if none is available yet. See WriteChannelPort::DataFetchCallback.
622 using DataFetchCallback = std::function<std::unique_ptr<T>()>;
623
624 /// Connect in callback mode. If T is a SegmentedMessageData, fetched
625 /// messages are handed to the port as-is; otherwise they are serialized.
626 /// See WriteChannelPort::connect(DataFetchCallback, WriteErrorCallback,
627 /// const ConnectOptions &).
628 void
630 const ChannelPort::ConnectOptions &opts = {std::nullopt, false}) {
631 if (!inner)
632 throw AcceleratorMismatchError("TypedWritePort: null port pointer");
633 if (!fetch)
634 throw std::invalid_argument(
635 "TypedWritePort::connect: null data fetch callback");
636 if (!SkipTypeCheck)
640 if constexpr (std::is_base_of_v<SegmentedMessageData, T>) {
641 rawFetch = [fetch = std::move(fetch)]()
642 -> std::unique_ptr<SegmentedMessageData> { return fetch(); };
643 } else {
644 rawFetch = [fetch = std::move(fetch),
645 wireInfo =
646 wireInfo_]() -> std::unique_ptr<SegmentedMessageData> {
647 std::unique_ptr<T> value = fetch();
648 if (!value)
649 return nullptr;
650 return std::make_unique<MessageData>(
651 toMessageData(*value, wireInfo).takeData());
652 };
653 }
654 inner->connect(std::move(rawFetch), std::move(onError), opts);
655 }
656
657 /// See WriteChannelPort::notifyAsyncDataAvailable().
658 void notifyAsyncDataAvailable() { inner->notifyAsyncDataAvailable(); }
659
660 void write(const T &data) { inner->write(toMessageData(data, wireInfo_)); }
661
662 /// Write by taking ownership. If T is a SegmentedMessageData, this hands
663 /// the message directly to the port's segmented write path.
664 void write(std::unique_ptr<T> &data) {
665 if (!data)
666 throw std::runtime_error("TypedWritePort::write: null unique_ptr");
667 if constexpr (std::is_base_of_v<SegmentedMessageData, T>) {
668 inner->write(std::move(data));
669 } else {
670 write(*data);
671 data.reset();
672 }
673 }
674
675 bool tryWrite(const T &data) {
676 return inner->tryWrite(toMessageData(data, wireInfo_));
677 }
678
679 /// Non-blocking write by taking ownership. On success, `data` is consumed
680 /// (left null) and true is returned. On failure, `data` is left untouched so
681 /// the caller can retry. If T is a SegmentedMessageData, this hands the
682 /// message directly to the port's segmented tryWrite path.
683 bool tryWrite(std::unique_ptr<T> &data) {
684 if (!data)
685 throw std::runtime_error("TypedWritePort::tryWrite: null unique_ptr");
686 if constexpr (std::is_base_of_v<SegmentedMessageData, T>) {
687 std::unique_ptr<SegmentedMessageData> msg(data.release());
688 bool written;
689 try {
690 written = inner->tryWrite(msg);
691 } catch (...) {
692 data.reset(static_cast<T *>(msg.release()));
693 throw;
694 }
695 // On failure, the port did not take ownership; hand it back.
696 if (!written)
697 data.reset(static_cast<T *>(msg.release()));
698 return written;
699 } else {
700 if (!tryWrite(*data))
701 return false;
702 data.reset();
703 return true;
704 }
705 }
706
707 bool flush() { return inner->flush(); }
708 void disconnect() { inner->disconnect(); }
709 bool isConnected() const { return inner && inner->isConnected(); }
710
711 WriteChannelPort &raw() { return *inner; }
712 const WriteChannelPort &raw() const { return *inner; }
713
714private:
717};
718
719/// Specialization for void — write takes no data argument.
720template <>
721class TypedWritePort<void> {
722public:
723 explicit TypedWritePort(WriteChannelPort &port) : inner(&port) {}
724 // NOLINTNEXTLINE(google-explicit-constructor)
726
727 void connect(const ChannelPort::ConnectOptions &opts = {std::nullopt,
728 false}) {
729 if (!inner)
730 throw AcceleratorMismatchError("TypedWritePort: null port pointer");
732 inner->connect(opts);
733 }
734
735 /// Callback mode data source: returns true if a message should be written,
736 /// or false if none is available yet. See
737 /// WriteChannelPort::DataFetchCallback.
738 using DataFetchCallback = std::function<bool()>;
739
740 /// Connect in callback mode. See WriteChannelPort::connect(
741 /// DataFetchCallback, WriteErrorCallback, const ConnectOptions &).
742 void
744 const ChannelPort::ConnectOptions &opts = {std::nullopt, false}) {
745 if (!inner)
746 throw AcceleratorMismatchError("TypedWritePort: null port pointer");
747 if (!fetch)
748 throw std::invalid_argument(
749 "TypedWritePort::connect: null data fetch callback");
751 inner->connect(
752 [fetch = std::move(fetch)]() -> std::unique_ptr<SegmentedMessageData> {
753 if (!fetch())
754 return nullptr;
755 return std::make_unique<MessageData>(std::vector<uint8_t>{0});
756 },
757 std::move(onError), opts);
758 }
759
760 /// See WriteChannelPort::notifyAsyncDataAvailable().
761 void notifyAsyncDataAvailable() { inner->notifyAsyncDataAvailable(); }
762
763 void write() {
764 uint8_t zero = 0;
765 inner->write(MessageData(&zero, 1));
766 }
767
768 bool tryWrite() {
769 uint8_t zero = 0;
770 return inner->tryWrite(MessageData(&zero, 1));
771 }
772
773 bool flush() { return inner->flush(); }
774 void disconnect() { inner->disconnect(); }
775 bool isConnected() const { return inner && inner->isConnected(); }
776
777 WriteChannelPort &raw() { return *inner; }
778 const WriteChannelPort &raw() const { return *inner; }
779
780private:
782};
783
784//===----------------------------------------------------------------------===//
785// TypedReadPort<T>
786//===----------------------------------------------------------------------===//
787
788/// Strongly typed wrapper around a raw read channel.
789///
790/// For scalar/POD-like `T`, this performs a 1:1 conversion from raw messages.
791/// If `T` defines a nested `TypeDeserializer`, one instance is created per
792/// connection and drives both callback and polling reads through that
793/// deserializer.
794///
795/// Polling reads return `std::unique_ptr<T>` so complex decoded values can be
796/// delivered without an extra copy.
797template <typename T, bool SkipTypeCheck = false>
799public:
800 explicit TypedReadPort(ReadChannelPort &port) : inner(&port) {}
801 // NOLINTNEXTLINE(google-explicit-constructor)
803 TypedReadPort(const TypedReadPort &) = delete;
807
809 if (inner && mode != Mode::Disconnected)
810 disconnect();
811 }
812
813 /// Connect in polling mode.
814 ///
815 /// The port installs an internal typed output queue. `read()` and
816 /// `readAsync()` consume from that queue.
817 void connect(const ChannelPort::ConnectOptions &opts = {std::nullopt,
818 false}) {
819 if (!inner)
820 throw AcceleratorMismatchError("TypedReadPort: null port pointer");
823 emplaceDeserializer([this](std::unique_ptr<T> &value) -> bool {
824 return pollingState->enqueue(value);
825 });
826 try {
827 inner->connect(
828 [this](std::unique_ptr<SegmentedMessageData> &msg) -> bool {
829 assert(deserializer && "Deserializer should be connected");
830 return deserializer->push(msg);
831 },
832 opts);
833 } catch (...) {
835 throw;
836 }
838 }
839
840 /// Connect a non-owning typed callback.
841 ///
842 /// The callback sees the decoded value by reference. Returning `false`
843 /// requests that the same decoded value be retried later.
844 void connect(std::function<bool(const T &)> callback,
845 const ChannelPort::ConnectOptions &opts = {std::nullopt,
846 false}) {
847 connect([cb = std::move(callback)](
848 std::unique_ptr<T> &value) -> bool { return cb(*value); },
849 opts);
850 }
851
852 /// Connect an owning typed callback.
853 ///
854 /// This is the typed analogue of `ReadChannelPort::ReadCallback`: the
855 /// callback may take ownership of the decoded value or return `false` to
856 /// retry delivery later with the same object.
858 const ChannelPort::ConnectOptions &opts = {std::nullopt,
859 false}) {
860 if (!inner)
861 throw AcceleratorMismatchError("TypedReadPort: null port pointer");
863 emplaceDeserializer(std::move(callback));
864 try {
865 inner->connect(
866 [this](std::unique_ptr<SegmentedMessageData> &msg) -> bool {
867 assert(deserializer && "Deserializer should be connected");
868 return deserializer->push(msg);
869 },
870 opts);
871 } catch (...) {
873 throw;
874 }
875 // TODO: Hook callback-mode custom-deserializer poke() retries into the
876 // existing periodic poll/background-worker path.
878 }
879
880 /// Blocking typed read in polling mode.
881 std::unique_ptr<T> read() {
882 std::future<std::unique_ptr<T>> f = readAsync();
883 f.wait();
884 return f.get();
885 }
886
887 /// Asynchronous typed read in polling mode.
888 ///
889 /// The returned future yields ownership of the next decoded value.
890 std::future<std::unique_ptr<T>> readAsync() {
891 if (mode == Mode::Callback)
892 throw std::runtime_error(
893 "Cannot read from a callback channel. `connect()` without a "
894 "callback specified to use polling mode.");
896 throw std::runtime_error(
897 "Cannot read from a disconnected channel. `connect()` first.");
898
899 if (!pollingState)
900 throw std::runtime_error(
901 "Cannot read from a disconnected channel. `connect()` first.");
902
903 std::future<std::unique_ptr<T>> future = pollingState->readAsync();
904
905 if (deserializer)
906 deserializer->poke();
907 return future;
908 }
909
910 /// Set the maximum number of decoded typed values buffered in polling mode.
911 /// `0` means unbounded.
912 void setMaxDataQueueMsgs(uint64_t maxMsgs) {
913 maxDataQueueMsgs = maxMsgs;
914 if (pollingState)
915 pollingState->setMaxQueued(maxMsgs);
916 }
917
918 /// Disconnect the typed port and abandon any pending polling reads.
919 void disconnect() {
920 inner->disconnect();
923 }
924 bool isConnected() const { return inner && inner->isConnected(); }
925
926 ReadChannelPort &raw() { return *inner; }
927 const ReadChannelPort &raw() const { return *inner; }
928
929private:
933
935 deserializer.reset();
936 pollingState.reset();
937 }
938
941 deserializer.emplace(std::move(callback));
942 } else {
943 deserializer.emplace(std::move(callback), wireInfo_);
944 }
945 }
946
949 throw std::runtime_error("Channel already connected");
950 if constexpr (SkipTypeCheck) {
951 // Skip verification, but still compute wireInfo for the POD path so
952 // small / non-byte-aligned wire widths still encode correctly.
954 wireInfo_ = getWireInfo(inner->getType());
955 } else if constexpr (has_esi_id_v<T>) {
957 } else if constexpr (!detail::has_type_deserializer_v<T>) {
959 wireInfo_ = getWireInfo(inner->getType());
960 }
961 }
962
967 std::optional<Deserializer> deserializer;
968 std::optional<PollingState> pollingState;
969};
970
971/// Specialization for void — read discards data and returns nothing.
972template <>
973class TypedReadPort<void> {
974public:
975 explicit TypedReadPort(ReadChannelPort &port) : inner(&port) {}
976 // NOLINTNEXTLINE(google-explicit-constructor)
978 TypedReadPort(const TypedReadPort &) = delete;
982
984 if (inner && inner->isConnected())
985 disconnect();
986 }
987
988 void connect(const ChannelPort::ConnectOptions &opts = {std::nullopt,
989 false}) {
990 if (!inner)
991 throw AcceleratorMismatchError("TypedReadPort: null port pointer");
993 inner->connect(opts);
994 }
995
996 void connect(std::function<bool()> callback,
997 const ChannelPort::ConnectOptions &opts = {std::nullopt,
998 false}) {
999 if (!inner)
1000 throw AcceleratorMismatchError("TypedReadPort: null port pointer");
1002 inner->connect(
1003 [cb = std::move(callback)](MessageData) -> bool { return cb(); }, opts);
1004 }
1005
1006 void read() {
1007 MessageData outData;
1008 inner->read(outData);
1009 }
1010
1011 std::future<void> readAsync() {
1012 auto innerFuture = inner->readAsync();
1013 return std::async(
1014 std::launch::deferred,
1015 [f = std::move(innerFuture)]() mutable -> void { f.get(); });
1016 }
1017
1018 void disconnect() { inner->disconnect(); }
1019 bool isConnected() const { return inner && inner->isConnected(); }
1020
1021 ReadChannelPort &raw() { return *inner; }
1022 const ReadChannelPort &raw() const { return *inner; }
1023
1024private:
1026};
1027
1028//===----------------------------------------------------------------------===//
1029// TypedFunction<ArgT, ResultT>
1030//
1031// Strongly-typed function-call wrapper built on top of TypedWritePort and
1032// TypedReadPort. Implicitly constructible from `FuncService::Function *` (the
1033// return type of `BundlePort::getAs<FuncService::Function>()`); construction
1034// resolves the underlying raw "arg" / "result" channels but does not connect
1035// them until `connect()` is called.
1036//
1037// We intentionally bypass `FuncService::Function::call`. That helper returns
1038// the future from a single `result->readAsync()`, which only sees one raw
1039// frame and would race when the response is multi-frame or when calls are
1040// pipelined. Driving a `TypedReadPort<ResultT>` instead reuses its persistent
1041// per-port deserializer (so partial frames / pending outputs survive between
1042// calls) and its FIFO polling buffer (so pipelined `readAsync()` futures
1043// hand back per-call decoded values in call order, even when consumers
1044// `.get()` them out of order).
1045//===----------------------------------------------------------------------===//
1046
1047namespace detail {
1048
1049/// Standard ConnectOptions for typed function ports: untranslated frames so
1050/// the deserializer can see raw frame boundaries.
1052 return ChannelPort::ConnectOptions(/*bufferSize=*/std::nullopt,
1053 /*translateMessage=*/false);
1054}
1055
1056/// Convert a `std::future<std::unique_ptr<T>>` (as returned by
1057/// `TypedReadPort::readAsync()`) into a `std::future<T>`. Uses a deferred
1058/// async so `.get()` blocks only when the caller actually waits for the
1059/// value, preserving the per-call FIFO ordering of the underlying polling
1060/// buffer. A null `unique_ptr` from a misbehaving deserializer is reported
1061/// as a runtime error rather than dereferenced.
1062template <typename T>
1063std::future<T> awaitDecoded(std::future<std::unique_ptr<T>> inner) {
1064 return std::async(std::launch::deferred,
1065 [fut = std::move(inner)]() mutable -> T {
1066 std::unique_ptr<T> v = fut.get();
1067 if (!v)
1068 throw std::runtime_error(
1069 "TypedFunction: deserializer produced a null "
1070 "value");
1071 return std::move(*v);
1072 });
1073}
1074
1075/// Throw the standard "null Function pointer" error used by every
1076/// TypedFunction specialization.
1077[[noreturn]] inline void throwNullFunction() {
1079 "TypedFunction: null Function pointer (getAs failed or wrong type)");
1080}
1081
1082/// Throw a clear "not connected" error from `call()` paths.
1083[[noreturn]] inline void throwNotConnected() {
1084 throw std::runtime_error("TypedFunction: must be 'connect'ed before "
1085 "calling");
1086}
1087
1088/// Throw a clear "already connected" error from `connect()` paths.
1089[[noreturn]] inline void throwAlreadyConnected() {
1090 throw std::runtime_error("TypedFunction is already connected");
1091}
1092
1093} // namespace detail
1094
1095template <typename ArgT, typename ResultT, bool SkipTypeCheck = false>
1097public:
1098 /// Implicit conversion from Function* (returned by getAs<>()).
1099 // NOLINTNEXTLINE(google-explicit-constructor)
1101 TypedFunction(const TypedFunction &) = delete;
1103
1104 void connect() {
1105 if (!inner)
1107 if (argPort)
1109 argPort.emplace(&inner->getRawWrite("arg"));
1110 resultPort.emplace(&inner->getRawRead("result"));
1112 argPort->connect(opts);
1113 resultPort->connect(opts);
1114 }
1115
1116 std::future<ResultT> call(const ArgT &arg) {
1117 if (!argPort)
1119 // Serialize the per-call write+readAsync pair so the polling buffer's
1120 // FIFO matches the call FIFO. Pipelined calls are still allowed -- the
1121 // shared deserializer drains responses in wire order and the FIFO
1122 // ensures call N's future resolves to call N's result, regardless of
1123 // the order in which callers `.get()` the futures.
1124 std::scoped_lock<std::mutex> lock(callMutex);
1125 argPort->write(arg);
1126 return detail::awaitDecoded<ResultT>(resultPort->readAsync());
1127 }
1128
1129 /// Emplace-style call: constructs `ArgT` in-place from the forwarded
1130 /// arguments and forwards to `call(const ArgT &)`. SFINAE-disabled for the
1131 /// single-`ArgT`-argument case so it does not shadow the lvalue overload.
1132 template <
1133 typename First, typename... Rest,
1134 typename = std::enable_if_t<
1135 std::is_constructible_v<ArgT, First, Rest...> &&
1136 (!std::is_same_v<std::decay_t<First>, ArgT> || sizeof...(Rest) != 0)>>
1137 std::future<ResultT> call(First &&first, Rest &&...rest) {
1138 return call(ArgT(std::forward<First>(first), std::forward<Rest>(rest)...));
1139 }
1140
1141 /// Function-call operator overloads: forward to `call()`.
1142 template <typename... Args>
1143 auto operator()(Args &&...args)
1144 -> decltype(this->call(std::forward<Args>(args)...)) {
1145 return call(std::forward<Args>(args)...);
1146 }
1147
1149 const services::FuncService::Function &raw() const { return *inner; }
1150
1151private:
1153 std::optional<TypedWritePort<ArgT, SkipTypeCheck>> argPort;
1154 std::optional<TypedReadPort<ResultT, SkipTypeCheck>> resultPort;
1155 std::mutex callMutex;
1156};
1157
1158/// Partial specialization: void argument, typed result.
1159template <typename ResultT, bool SkipTypeCheck>
1160class TypedFunction<void, ResultT, SkipTypeCheck> {
1161public:
1162 // NOLINTNEXTLINE(google-explicit-constructor)
1164 TypedFunction(const TypedFunction &) = delete;
1166
1167 void connect() {
1168 if (!inner)
1170 if (argPort)
1172 argPort.emplace(&inner->getRawWrite("arg"));
1173 resultPort.emplace(&inner->getRawRead("result"));
1175 argPort->connect(opts);
1176 resultPort->connect(opts);
1177 }
1178
1179 std::future<ResultT> call() {
1180 if (!argPort)
1182 std::scoped_lock<std::mutex> lock(callMutex);
1183 argPort->write();
1184 return detail::awaitDecoded<ResultT>(resultPort->readAsync());
1185 }
1186
1187 /// Function-call operator overload: forwards to `call()`.
1188 std::future<ResultT> operator()() { return call(); }
1189
1191 const services::FuncService::Function &raw() const { return *inner; }
1192
1193private:
1195 std::optional<TypedWritePort<void>> argPort;
1196 std::optional<TypedReadPort<ResultT, SkipTypeCheck>> resultPort;
1197 std::mutex callMutex;
1198};
1199
1200/// Partial specialization: typed argument, void result.
1201template <typename ArgT, bool SkipTypeCheck>
1202class TypedFunction<ArgT, void, SkipTypeCheck> {
1203public:
1204 // NOLINTNEXTLINE(google-explicit-constructor)
1206 TypedFunction(const TypedFunction &) = delete;
1208
1209 void connect() {
1210 if (!inner)
1212 if (argPort)
1214 argPort.emplace(&inner->getRawWrite("arg"));
1215 resultPort.emplace(&inner->getRawRead("result"));
1217 argPort->connect(opts);
1218 resultPort->connect(opts);
1219 }
1220
1221 std::future<void> call(const ArgT &arg) {
1222 if (!argPort)
1224 std::scoped_lock<std::mutex> lock(callMutex);
1225 argPort->write(arg);
1226 return resultPort->readAsync();
1227 }
1228
1229 /// Emplace-style call: constructs `ArgT` in-place from the forwarded
1230 /// arguments and forwards to `call(const ArgT &)`. SFINAE-disabled for the
1231 /// single-`ArgT`-argument case so it does not shadow the lvalue overload.
1232 template <
1233 typename First, typename... Rest,
1234 typename = std::enable_if_t<
1235 std::is_constructible_v<ArgT, First, Rest...> &&
1236 (!std::is_same_v<std::decay_t<First>, ArgT> || sizeof...(Rest) != 0)>>
1237 std::future<void> call(First &&first, Rest &&...rest) {
1238 return call(ArgT(std::forward<First>(first), std::forward<Rest>(rest)...));
1239 }
1240
1241 /// Function-call operator overloads: forward to `call()`.
1242 template <typename... Args>
1243 auto operator()(Args &&...args)
1244 -> decltype(this->call(std::forward<Args>(args)...)) {
1245 return call(std::forward<Args>(args)...);
1246 }
1247
1249 const services::FuncService::Function &raw() const { return *inner; }
1250
1251private:
1253 std::optional<TypedWritePort<ArgT, SkipTypeCheck>> argPort;
1254 std::optional<TypedReadPort<void>> resultPort;
1255 std::mutex callMutex;
1256};
1257
1258/// Full specialization: void argument, void result.
1259template <bool SkipTypeCheck>
1260class TypedFunction<void, void, SkipTypeCheck> {
1261public:
1262 // NOLINTNEXTLINE(google-explicit-constructor)
1264 TypedFunction(const TypedFunction &) = delete;
1266
1267 void connect() {
1268 if (!inner)
1270 if (argPort)
1272 argPort.emplace(&inner->getRawWrite("arg"));
1273 resultPort.emplace(&inner->getRawRead("result"));
1275 argPort->connect(opts);
1276 resultPort->connect(opts);
1277 }
1278
1279 std::future<void> call() {
1280 if (!argPort)
1282 std::scoped_lock<std::mutex> lock(callMutex);
1283 argPort->write();
1284 return resultPort->readAsync();
1285 }
1286
1287 /// Function-call operator overload: forwards to `call()`.
1288 std::future<void> operator()() { return call(); }
1289
1291 const services::FuncService::Function &raw() const { return *inner; }
1292
1293private:
1295 std::optional<TypedWritePort<void>> argPort;
1296 std::optional<TypedReadPort<void>> resultPort;
1297 std::mutex callMutex;
1298};
1299
1300//===----------------------------------------------------------------------===//
1301// TypedCallback<ArgT, ResultT>
1302//
1303// Strongly-typed accelerator-callback wrapper built on top of TypedReadPort
1304// and TypedWritePort. Implicitly constructible from `CallService::Callback *`
1305// (the return type of `BundlePort::getAs<CallService::Callback>()`);
1306// construction resolves the underlying raw "arg" / "result" channels but
1307// does not connect them until `connect()` is called.
1308//
1309// We bypass `CallService::Callback::connect` for the same reason we bypass
1310// `FuncService::Function::call`: typed args may span multiple raw frames and
1311// we need the persistent stateful deserializer that `TypedReadPort<ArgT>`
1312// already provides.
1313//
1314// Note: the `quick` parameter is kept for API compatibility but has no
1315// effect in this design. The typed user callback is always dispatched inline
1316// from the read-channel callback thread (matching the previous
1317// custom-deserializer behavior). If service-thread dispatch is needed in the
1318// future, that can be layered on top by using `TypedReadPort` polling mode
1319// plus a worker.
1320//
1321// Lifetime: the TypedReadPort callback installed on `connect()` captures
1322// `this`. The wrapper is non-copyable and non-movable, so its address is
1323// stable for its entire lifetime. Destruction of the embedded TypedReadPort
1324// synchronously revokes the callback and waits for any in-flight callback
1325// dispatch to complete (see ReadChannelPort::disconnect), so the captured
1326// `this` cannot dangle. Callers must ensure the TypedCallback outlives any
1327// expected callback dispatch -- using a temporary like
1328// `TypedCallback<...>(cb).connect(...)` is safe only because the destructor
1329// runs at end-of-full-expression and disconnects before returning.
1330//===----------------------------------------------------------------------===//
1331
1332namespace detail {
1333
1334/// Throw the standard "null Callback pointer" error used by every
1335/// TypedCallback specialization.
1336[[noreturn]] inline void throwNullCallback() {
1338 "TypedCallback: null Callback pointer (getAs failed or wrong type)");
1339}
1340
1341/// Throw a clear "already connected" error from TypedCallback `connect()`
1342/// paths.
1343[[noreturn]] inline void throwCallbackAlreadyConnected() {
1344 throw std::runtime_error("TypedCallback is already connected");
1345}
1346
1347} // namespace detail
1348
1349template <typename ArgT, typename ResultT, bool SkipTypeCheck = false>
1351public:
1352 // NOLINTNEXTLINE(google-explicit-constructor)
1354 TypedCallback(const TypedCallback &) = delete;
1356
1357 void connect(std::function<ResultT(const ArgT &)> callback,
1358 bool quick = false) {
1359 (void)quick; // See class header.
1360 if (!inner)
1362 if (argPort)
1364 argPort.emplace(&inner->getRawRead("arg"));
1365 resultPort.emplace(&inner->getRawWrite("result"));
1367 resultPort->connect(opts);
1368 userCallback = std::move(callback);
1369 // The TypedReadPort callback runs on the read-channel callback thread
1370 // for every decoded ArgT. We forward to the user's callback and then
1371 // serialize the result through the TypedWritePort.
1372 argPort->connect(
1373 [this](const ArgT &arg) -> bool {
1374 ResultT result = userCallback(arg);
1375 resultPort->write(result);
1376 return true;
1377 },
1378 opts);
1379 }
1380
1382 const services::CallService::Callback &raw() const { return *inner; }
1383
1384private:
1386 std::optional<TypedReadPort<ArgT, SkipTypeCheck>> argPort;
1387 std::optional<TypedWritePort<ResultT, SkipTypeCheck>> resultPort;
1388 std::function<ResultT(const ArgT &)> userCallback;
1389};
1390
1391/// Partial specialization: void argument, typed result.
1392template <typename ResultT, bool SkipTypeCheck>
1393class TypedCallback<void, ResultT, SkipTypeCheck> {
1394public:
1395 // NOLINTNEXTLINE(google-explicit-constructor)
1397 TypedCallback(const TypedCallback &) = delete;
1399
1400 void connect(std::function<ResultT()> callback, bool quick = false) {
1401 (void)quick;
1402 if (!inner)
1404 if (argPort)
1406 argPort.emplace(&inner->getRawRead("arg"));
1407 resultPort.emplace(&inner->getRawWrite("result"));
1409 resultPort->connect(opts);
1410 userCallback = std::move(callback);
1411 argPort->connect(
1412 [this]() -> bool {
1413 ResultT result = userCallback();
1414 resultPort->write(result);
1415 return true;
1416 },
1417 opts);
1418 }
1419
1421 const services::CallService::Callback &raw() const { return *inner; }
1422
1423private:
1425 std::optional<TypedReadPort<void>> argPort;
1426 std::optional<TypedWritePort<ResultT, SkipTypeCheck>> resultPort;
1427 std::function<ResultT()> userCallback;
1428};
1429
1430/// Partial specialization: typed argument, void result.
1431template <typename ArgT, bool SkipTypeCheck>
1432class TypedCallback<ArgT, void, SkipTypeCheck> {
1433public:
1434 // NOLINTNEXTLINE(google-explicit-constructor)
1436 TypedCallback(const TypedCallback &) = delete;
1438
1439 void connect(std::function<void(const ArgT &)> callback, bool quick = false) {
1440 (void)quick;
1441 if (!inner)
1443 if (argPort)
1445 argPort.emplace(&inner->getRawRead("arg"));
1446 resultPort.emplace(&inner->getRawWrite("result"));
1448 resultPort->connect(opts);
1449 userCallback = std::move(callback);
1450 argPort->connect(
1451 [this](const ArgT &arg) -> bool {
1452 userCallback(arg);
1453 resultPort->write();
1454 return true;
1455 },
1456 opts);
1457 }
1458
1460 const services::CallService::Callback &raw() const { return *inner; }
1461
1462private:
1464 std::optional<TypedReadPort<ArgT, SkipTypeCheck>> argPort;
1465 std::optional<TypedWritePort<void>> resultPort;
1466 std::function<void(const ArgT &)> userCallback;
1467};
1468
1469/// Full specialization: void argument, void result.
1470template <bool SkipTypeCheck>
1471class TypedCallback<void, void, SkipTypeCheck> {
1472public:
1473 // NOLINTNEXTLINE(google-explicit-constructor)
1475 TypedCallback(const TypedCallback &) = delete;
1477
1478 void connect(std::function<void()> callback, bool quick = false) {
1479 (void)quick;
1480 if (!inner)
1482 if (argPort)
1484 argPort.emplace(&inner->getRawRead("arg"));
1485 resultPort.emplace(&inner->getRawWrite("result"));
1487 resultPort->connect(opts);
1488 userCallback = std::move(callback);
1489 argPort->connect(
1490 [this]() -> bool {
1491 userCallback();
1492 resultPort->write();
1493 return true;
1494 },
1495 opts);
1496 }
1497
1499 const services::CallService::Callback &raw() const { return *inner; }
1500
1501private:
1503 std::optional<TypedReadPort<void>> argPort;
1504 std::optional<TypedWritePort<void>> resultPort;
1505 std::function<void()> userCallback;
1506};
1507
1508//===----------------------------------------------------------------------===//
1509// IndexedPorts<T> — wrapper over std::map<int, T>.
1510//
1511// Constructed once from a moved std::map (populated via `try_emplace` so T
1512// need not be movable or default-constructible). Supports both mutable and
1513// const iteration / indexing so callers can invoke non-const methods on the
1514// stored ports (e.g. `connect()` on a typed port wrapper).
1515//===----------------------------------------------------------------------===//
1516
1517template <typename T>
1519public:
1520 explicit IndexedPorts(std::map<int, T> &&ports) : ports_(std::move(ports)) {}
1523 IndexedPorts(const IndexedPorts &) = delete;
1525
1526 T &operator[](int idx) { return ports_.at(idx); }
1527 const T &operator[](int idx) const { return ports_.at(idx); }
1528 auto begin() { return ports_.begin(); }
1529 auto end() { return ports_.end(); }
1530 auto begin() const { return ports_.cbegin(); }
1531 auto end() const { return ports_.cend(); }
1532 size_t size() const { return ports_.size(); }
1533 bool contains(int idx) const { return ports_.count(idx) > 0; }
1534
1535private:
1536 std::map<int, T> ports_;
1537};
1538
1539//===----------------------------------------------------------------------===//
1540// Port-lookup helpers: findPortOrThrow, findPortAsOrThrow, findPortIndices.
1541//
1542// `findPortOrThrow` and `findPortAsOrThrow` are thin wrappers over
1543// `HWModule::resolvePort` that translate "not found" into a thrown
1544// `AcceleratorMismatchError` (instead of a nullptr return) and the typed
1545// variant additionally `dynamic_cast`s to a service-specific subclass. They
1546// exist so generated facade code does not have to repeat the same
1547// boilerplate (build a single-element AppIDPath, check for null, format an
1548// error string) for every port lookup it performs.
1549//===----------------------------------------------------------------------===//
1550
1551/// Look up a BundlePort by AppID in `module`. Throws AcceleratorMismatchError
1552/// if the port is not found. The returned reference is mutable: even though
1553/// `HWModule::resolvePort` is a const method, the underlying port map stores
1554/// `BundlePort&` references, so callers can invoke non-const methods on the
1555/// returned port (e.g. `getRawRead`, `connect`).
1556inline BundlePort &findPortOrThrow(HWModule *module, const AppID &id) {
1557 AppIDPath lastLookup;
1558 BundlePort *port = module->resolvePort(AppIDPath{id}, lastLookup);
1559 if (!port)
1560 throw AcceleratorMismatchError("Expected port '" + id.toString() +
1561 "' not found in module");
1562 return *port;
1563}
1564
1565/// Look up a BundlePort by AppID and cast it to `T`. Throws
1566/// AcceleratorMismatchError if the port is missing or has the wrong runtime
1567/// type. The returned pointer is mutable.
1568template <typename T>
1569T *findPortAsOrThrow(HWModule *module, const AppID &id) {
1570 BundlePort &port = findPortOrThrow(module, id);
1571 T *result = port.getAs<T>();
1572 if (!result)
1573 throw AcceleratorMismatchError("Port '" + id.toString() +
1574 "' has unexpected type (expected " +
1575 typeid(T).name() + ")");
1576 return result;
1577}
1578
1579/// Return a sorted vector of the `idx` values for every port whose AppID name
1580/// matches `name`. Ports without an index are ignored.
1581inline std::vector<uint32_t> findPortIndices(HWModule *module,
1582 const std::string &name) {
1583 std::vector<uint32_t> indices;
1584 for (const auto &[appid, port] : module->getPorts())
1585 if (appid.name == name && appid.idx.has_value())
1586 indices.push_back(appid.idx.value());
1587 std::sort(indices.begin(), indices.end());
1588 return indices;
1589}
1590
1591} // namespace esi
1592
1593#endif // ESI_TYPED_PORTS_H
assert(baseType &&"element must be base type")
Arrays have a compile time specified (static) size and an element type.
Definition Types.h:301
Bit vectors include signed, unsigned, and signless integers.
Definition Types.h:211
Bits are just an array of bits.
Definition Types.h:224
Services provide connections to 'bundles' – collections of named, unidirectional communication channe...
Definition Ports.h:753
T * getAs() const
Cast this Bundle port to a subclass which is actually useful.
Definition Ports.h:781
Unidirectional channels are the basic communication primitive between the host and accelerator.
Definition Ports.h:119
const Type * getType() const
Definition Ports.h:224
const WindowType * getWindowType() const
If this port carries a windowed type, return the original WindowType (whose intoType is what getType(...
Definition Ports.h:229
Represents either the top level or an instance of a hardware module.
Definition Design.h:47
const std::map< AppID, BundlePort & > & getPorts() const
Access the module's ports by ID.
Definition Design.h:80
const T & operator[](int idx) const
std::map< int, T > ports_
IndexedPorts(std::map< int, T > &&ports)
auto end() const
auto begin() const
IndexedPorts & operator=(const IndexedPorts &)=delete
IndexedPorts(IndexedPorts &&)=default
IndexedPorts & operator=(IndexedPorts &&)=default
bool contains(int idx) const
T & operator[](int idx)
size_t size() const
IndexedPorts(const IndexedPorts &)=delete
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
const uint8_t * getBytes() const
Definition Common.h:216
const T * as() const
Cast to a type.
Definition Common.h:240
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:230
detail::TypedReadOwnedCallback< T > OutputCallback
Definition TypedPorts.h:232
QueuedDecodeTypeDeserializer(OutputCallback output)
Definition TypedPorts.h:235
virtual ~QueuedDecodeTypeDeserializer()=default
std::queue< std::unique_ptr< SerialCoordOutputBatch > > pendingOutputs
Definition TypedPorts.h:302
bool poke()
Retry delivery of any typed outputs which were previously blocked by the client callback.
Definition TypedPorts.h:275
bool push(std::unique_ptr< SegmentedMessageData > &msg)
Push one raw message into the deserializer.
Definition TypedPorts.h:245
virtual DecodedOutputs decode(std::unique_ptr< SegmentedMessageData > &msg)=0
Decode one raw message into zero or more typed outputs.
std::vector< std::unique_ptr< T > > DecodedOutputs
Definition TypedPorts.h:233
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
Definition Ports.cpp:143
static constexpr uint64_t DefaultMaxDataQueueMsgs
Default max data queue size set at connect time.
Definition Ports.h:646
Signed integer.
Definition Types.h:242
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Definition Common.cpp:62
std::vector< data_frame > pending_frames_
Definition TypedPorts.h:400
typename Base::DecodedOutputs DecodedOutputs
Definition TypedPorts.h:328
DecodedOutputs decode(std::unique_ptr< SegmentedMessageData > &msg) override
Decode one raw message into zero or more typed outputs.
Definition TypedPorts.h:342
typename Base::OutputCallback OutputCallback
Definition TypedPorts.h:327
std::optional< header_frame > pending_header_
Definition TypedPorts.h:399
SerialListTypeDeserializer(OutputCallback output)
Definition TypedPorts.h:330
QueuedDecodeTypeDeserializer< T > Base
Definition TypedPorts.h:326
typename T::header_frame header_frame
Definition TypedPorts.h:334
static constexpr size_t kFrameSize
Definition TypedPorts.h:340
typename T::count_type count_type
Definition TypedPorts.h:336
typename T::data_frame data_frame
Definition TypedPorts.h:335
std::vector< uint8_t > partial_
Definition TypedPorts.h:398
Root class of the ESI type system.
Definition Types.h:36
std::string toString(bool oneLine=false) const
Definition Types.cpp:120
ID getID() const
Definition Types.h:42
services::CallService::Callback * inner
std::optional< TypedReadPort< ArgT, SkipTypeCheck > > argPort
std::optional< TypedWritePort< void > > resultPort
const services::CallService::Callback & raw() const
std::function< void(const ArgT &)> userCallback
void connect(std::function< void(const ArgT &)> callback, bool quick=false)
TypedCallback(const TypedCallback &)=delete
services::CallService::Callback & raw()
TypedCallback & operator=(const TypedCallback &)=delete
TypedCallback(services::CallService::Callback *cb)
std::optional< TypedWritePort< ResultT, SkipTypeCheck > > resultPort
services::CallService::Callback & raw()
std::optional< TypedReadPort< void > > argPort
void connect(std::function< ResultT()> callback, bool quick=false)
TypedCallback(services::CallService::Callback *cb)
const services::CallService::Callback & raw() const
services::CallService::Callback * inner
TypedCallback & operator=(const TypedCallback &)=delete
std::optional< TypedWritePort< void > > resultPort
std::optional< TypedReadPort< void > > argPort
TypedCallback(services::CallService::Callback *cb)
services::CallService::Callback & raw()
void connect(std::function< void()> callback, bool quick=false)
TypedCallback & operator=(const TypedCallback &)=delete
TypedCallback(const TypedCallback &)=delete
const services::CallService::Callback & raw() const
services::CallService::Callback * inner
services::CallService::Callback * inner
std::optional< TypedReadPort< ArgT, SkipTypeCheck > > argPort
services::CallService::Callback & raw()
void connect(std::function< ResultT(const ArgT &)> callback, bool quick=false)
TypedCallback(services::CallService::Callback *cb)
std::optional< TypedWritePort< ResultT, SkipTypeCheck > > resultPort
TypedCallback & operator=(const TypedCallback &)=delete
std::function< ResultT(const ArgT &)> userCallback
const services::CallService::Callback & raw() const
TypedCallback(const TypedCallback &)=delete
auto operator()(Args &&...args) -> decltype(this->call(std::forward< Args >(args)...))
Function-call operator overloads: forward to call().
TypedFunction & operator=(const TypedFunction &)=delete
std::optional< TypedWritePort< ArgT, SkipTypeCheck > > argPort
std::future< void > call(First &&first, Rest &&...rest)
Emplace-style call: constructs ArgT in-place from the forwarded arguments and forwards to call(const ...
TypedFunction(const TypedFunction &)=delete
std::optional< TypedReadPort< void > > resultPort
const services::FuncService::Function & raw() const
services::FuncService::Function & raw()
std::future< void > call(const ArgT &arg)
services::FuncService::Function * inner
TypedFunction(services::FuncService::Function *func)
std::optional< TypedReadPort< ResultT, SkipTypeCheck > > resultPort
TypedFunction & operator=(const TypedFunction &)=delete
std::optional< TypedWritePort< void > > argPort
services::FuncService::Function & raw()
services::FuncService::Function * inner
std::future< ResultT > operator()()
Function-call operator overload: forwards to call().
const services::FuncService::Function & raw() const
TypedFunction(services::FuncService::Function *func)
const services::FuncService::Function & raw() const
TypedFunction(const TypedFunction &)=delete
TypedFunction & operator=(const TypedFunction &)=delete
services::FuncService::Function * inner
TypedFunction(services::FuncService::Function *func)
std::optional< TypedWritePort< void > > argPort
std::optional< TypedReadPort< void > > resultPort
services::FuncService::Function & raw()
std::future< void > operator()()
Function-call operator overload: forwards to call().
std::optional< TypedWritePort< ArgT, SkipTypeCheck > > argPort
std::optional< TypedReadPort< ResultT, SkipTypeCheck > > resultPort
std::future< ResultT > call(First &&first, Rest &&...rest)
Emplace-style call: constructs ArgT in-place from the forwarded arguments and forwards to call(const ...
TypedFunction(const TypedFunction &)=delete
services::FuncService::Function & raw()
std::mutex callMutex
auto operator()(Args &&...args) -> decltype(this->call(std::forward< Args >(args)...))
Function-call operator overloads: forward to call().
std::future< ResultT > call(const ArgT &arg)
TypedFunction & operator=(const TypedFunction &)=delete
const services::FuncService::Function & raw() const
TypedFunction(services::FuncService::Function *func)
Implicit conversion from Function* (returned by getAs<>()).
services::FuncService::Function * inner
TypedReadPort(const TypedReadPort &)=delete
TypedReadPort & operator=(TypedReadPort &&)=delete
TypedReadPort & operator=(const TypedReadPort &)=delete
ReadChannelPort * inner
TypedReadPort(ReadChannelPort &port)
Definition TypedPorts.h:975
TypedReadPort(ReadChannelPort *port)
Definition TypedPorts.h:977
TypedReadPort(TypedReadPort &&)=delete
std::future< void > readAsync()
void connect(const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Definition TypedPorts.h:988
ReadChannelPort & raw()
void connect(std::function< bool()> callback, const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Definition TypedPorts.h:996
const ReadChannelPort & raw() const
TypedReadPort(ReadChannelPort &port)
Definition TypedPorts.h:800
ReadChannelPort & raw()
Definition TypedPorts.h:926
detail::DeserializerFor< T > Deserializer
Definition TypedPorts.h:930
ReadChannelPort * inner
Definition TypedPorts.h:963
TypedReadPort & operator=(const TypedReadPort &)=delete
std::unique_ptr< T > read()
Blocking typed read in polling mode.
Definition TypedPorts.h:881
void connect(const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Connect in polling mode.
Definition TypedPorts.h:817
uint64_t maxDataQueueMsgs
Definition TypedPorts.h:966
void disconnect()
Disconnect the typed port and abandon any pending polling reads.
Definition TypedPorts.h:919
void setMaxDataQueueMsgs(uint64_t maxMsgs)
Set the maximum number of decoded typed values buffered in polling mode.
Definition TypedPorts.h:912
void emplaceDeserializer(detail::DeserializerOutputCallback< T > callback)
Definition TypedPorts.h:939
void connect(std::function< bool(const T &)> callback, const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Connect a non-owning typed callback.
Definition TypedPorts.h:844
const ReadChannelPort & raw() const
Definition TypedPorts.h:927
TypedReadPort & operator=(TypedReadPort &&)=delete
std::optional< PollingState > pollingState
Definition TypedPorts.h:968
TypedReadPort(const TypedReadPort &)=delete
std::optional< Deserializer > deserializer
Definition TypedPorts.h:967
void connect(detail::TypedReadOwnedCallback< T > callback, const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Connect an owning typed callback.
Definition TypedPorts.h:857
detail::PollingBuffer< std::unique_ptr< T > > PollingState
Definition TypedPorts.h:932
std::future< std::unique_ptr< T > > readAsync()
Asynchronous typed read in polling mode.
Definition TypedPorts.h:890
TypedReadPort(ReadChannelPort *port)
Definition TypedPorts.h:802
TypedReadPort(TypedReadPort &&)=delete
bool isConnected() const
Definition TypedPorts.h:924
WriteChannelPort * inner
Definition TypedPorts.h:781
TypedWritePort(WriteChannelPort &port)
Definition TypedPorts.h:723
std::function< bool()> DataFetchCallback
Callback mode data source: returns true if a message should be written, or false if none is available...
Definition TypedPorts.h:738
TypedWritePort(WriteChannelPort *port)
Definition TypedPorts.h:725
WriteChannelPort & raw()
Definition TypedPorts.h:777
void notifyAsyncDataAvailable()
See WriteChannelPort::notifyAsyncDataAvailable().
Definition TypedPorts.h:761
void connect(const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Definition TypedPorts.h:727
const WriteChannelPort & raw() const
Definition TypedPorts.h:778
void connect(DataFetchCallback fetch, WriteChannelPort::WriteErrorCallback onError, const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Connect in callback mode.
Definition TypedPorts.h:743
const WriteChannelPort & raw() const
Definition TypedPorts.h:712
std::function< std::unique_ptr< T >()> DataFetchCallback
Callback mode data source: returns the next value to write, or nullptr if none is available yet.
Definition TypedPorts.h:622
void connect(const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Definition TypedPorts.h:610
WriteChannelPort & raw()
Definition TypedPorts.h:711
void write(std::unique_ptr< T > &data)
Write by taking ownership.
Definition TypedPorts.h:664
bool tryWrite(const T &data)
Definition TypedPorts.h:675
bool isConnected() const
Definition TypedPorts.h:709
bool tryWrite(std::unique_ptr< T > &data)
Non-blocking write by taking ownership.
Definition TypedPorts.h:683
void notifyAsyncDataAvailable()
See WriteChannelPort::notifyAsyncDataAvailable().
Definition TypedPorts.h:658
TypedWritePort(WriteChannelPort &port)
Definition TypedPorts.h:606
void write(const T &data)
Definition TypedPorts.h:660
TypedWritePort(WriteChannelPort *port)
Definition TypedPorts.h:608
void connect(DataFetchCallback fetch, WriteChannelPort::WriteErrorCallback onError, const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Connect in callback mode.
Definition TypedPorts.h:629
WriteChannelPort * inner
Definition TypedPorts.h:715
Unsigned integer.
Definition Types.h:253
The "void" type is a special type which can be used to represent no type.
Definition Types.h:141
Windows represent a fixed-size sliding window over a stream of data.
Definition Types.h:334
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.cpp:867
std::function< void(std::exception_ptr)> WriteErrorCallback
Callback mode error handler.
Definition Ports.h:333
std::function< std::unique_ptr< SegmentedMessageData >()> DataFetchCallback
Callback mode data source.
Definition Ports.h:327
Default deserializer for simple 1:1 typed reads.
Definition TypedPorts.h:158
bool push(std::unique_ptr< SegmentedMessageData > &msg)
Definition TypedPorts.h:165
TypedReadOwnedCallback< T > OutputCallback
Definition TypedPorts.h:160
std::unique_ptr< T > pendingOutput
Definition TypedPorts.h:202
PODTypeDeserializer(OutputCallback output, WireInfo wireInfo)
Definition TypedPorts.h:162
Shared queue/promise helper for polling-style read APIs.
Definition Ports.h:47
A function call which gets attached to a service port.
Definition Services.h:437
A function call which gets attached to a service port.
Definition Services.h:385
constexpr bool has_type_deserializer_v
Definition TypedPorts.h:149
std::function< bool(std::unique_ptr< T > &)> TypedReadOwnedCallback
Owning callback used by typed read deserializers.
Definition TypedPorts.h:139
ChannelPort::ConnectOptions typedFunctionConnectOptions()
Standard ConnectOptions for typed function ports: untranslated frames so the deserializer can see raw...
void throwAlreadyConnected()
Throw a clear "already connected" error from connect() paths.
typename DeserializerSelector< T >::type DeserializerFor
Definition TypedPorts.h:216
void throwNullFunction()
Throw the standard "null Function pointer" error used by every TypedFunction specialization.
void throwNotConnected()
Throw a clear "not connected" error from call() paths.
void throwCallbackAlreadyConnected()
Throw a clear "already connected" error from TypedCallback connect() paths.
void throwNullCallback()
Throw the standard "null Callback pointer" error used by every TypedCallback specialization.
typename DeserializerFor< T >::OutputCallback DeserializerOutputCallback
Definition TypedPorts.h:219
std::future< T > awaitDecoded(std::future< std::unique_ptr< T > > inner)
Convert a std::future<std::unique_ptr<T>> (as returned by TypedReadPort::readAsync()) into a std::fut...
Definition esi.py:1
std::string toString(const std::any &a)
'Stringify' a std::any. This is used to log std::any values by some loggers.
Definition Logging.cpp:132
void verifyTypeCompatibility(const Type *portType)
Definition TypedPorts.h:447
MessageData toMessageData(const T &data, WireInfo wi)
Pack a C++ integral value into a MessageData with the given wire byte count.
Definition TypedPorts.h:80
std::vector< uint32_t > findPortIndices(HWModule *module, const std::string &name)
Return a sorted vector of the idx values for every port whose AppID name matches name.
WireInfo getWireInfo(const Type *portType)
Definition TypedPorts.h:70
BundlePort & findPortOrThrow(HWModule *module, const AppID &id)
Look up a BundlePort by AppID in module.
constexpr bool has_esi_id_v
Definition TypedPorts.h:416
T * findPortAsOrThrow(HWModule *module, const AppID &id)
Look up a BundlePort by AppID and cast it to T.
constexpr bool has_esi_window_id_v
Definition TypedPorts.h:428
constexpr bool is_std_array_v
Definition TypedPorts.h:444
T fromMessageData(const MessageData &msg, WireInfo wi)
Unpack a MessageData into a C++ integral value with the given wire info.
Definition TypedPorts.h:103
const Type * unwrapTypeAlias(const Type *type)
Unwrap TypeAliasType (possibly recursively) to get the underlying type.
Definition Types.h:193
Compute the wire byte count for a port type.
Definition TypedPorts.h:65
size_t bitWidth
Definition TypedPorts.h:67
PODTypeDeserializer< T > type
Definition TypedPorts.h:207