xref: /petsc/src/sys/objects/device/interface/mark_dcontext.cxx (revision 968e829e48493901028bbe48ce4189d1fde62b6d)
1 #include "petscdevice_interface_internal.hpp" /*I <petscdevice.h> I*/
2 
3 #include <petsc/private/cpp/object_pool.hpp>
4 #include <petsc/private/cpp/utility.hpp>
5 #include <petsc/private/cpp/unordered_map.hpp>
6 
7 #include <algorithm> // std::remove_if(), std::find_if()
8 #include <vector>
9 #include <string>
10 #include <sstream> // std::ostringstream
11 
12 #if defined(__clang__)
13   #pragma clang diagnostic push
14   #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
15 #endif
16 
17 // ==========================================================================================
18 // PetscEvent
19 // ==========================================================================================
20 
21 class PetscEventConstructor : public Petsc::ConstructorInterface<_n_PetscEvent, PetscEventConstructor> {
22 public:
23   PetscErrorCode construct_(PetscEvent event) const noexcept
24   {
25     PetscFunctionBegin;
26     PetscCall(PetscMemzero(event, sizeof(*event)));
27     PetscCall(underlying().reset(event));
28     PetscFunctionReturn(PETSC_SUCCESS);
29   }
30 
31   PetscErrorCode destroy_(PetscEvent event) const noexcept
32   {
33     PetscFunctionBegin;
34     PetscCall(underlying().reset(event));
35     PetscFunctionReturn(PETSC_SUCCESS);
36   }
37 
38   static PetscErrorCode reset_(PetscEvent event) noexcept
39   {
40     PetscFunctionBegin;
41     if (auto &destroy = event->destroy) {
42       PetscCall((*destroy)(event));
43       destroy = nullptr;
44     }
45     PetscAssert(!event->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Event failed to destroy its data member: %p", event->data);
46     event->dctx_id    = 0;
47     event->dctx_state = 0;
48     event->dtype      = PETSC_DEVICE_DEFAULT();
49     PetscFunctionReturn(PETSC_SUCCESS);
50   }
51 
52   static PetscErrorCode invalidate_(PetscEvent) noexcept { return PETSC_SUCCESS; }
53 };
54 
55 static Petsc::ObjectPool<_n_PetscEvent, PetscEventConstructor> event_pool;
56 
57 static PetscErrorCode PetscDeviceContextCreateEvent_Private(PetscDeviceContext dctx, PetscEvent *event)
58 {
59   PetscFunctionBegin;
60   PetscValidDeviceContext(dctx, 1);
61   PetscValidPointer(event, 2);
62   PetscCall(event_pool.allocate(event));
63   PetscCall(PetscDeviceContextGetDeviceType(dctx, &(*event)->dtype));
64   PetscTryTypeMethod(dctx, createevent, *event);
65   PetscFunctionReturn(PETSC_SUCCESS);
66 }
67 
68 static PetscErrorCode PetscEventDestroy_Private(PetscEvent *event)
69 {
70   PetscFunctionBegin;
71   PetscValidPointer(event, 1);
72   if (*event) PetscCall(event_pool.deallocate(event));
73   PetscFunctionReturn(PETSC_SUCCESS);
74 }
75 
76 static PetscErrorCode PetscDeviceContextRecordEvent_Private(PetscDeviceContext dctx, PetscEvent event)
77 {
78   PetscObjectId    id;
79   PetscObjectState state;
80 
81   PetscFunctionBegin;
82   PetscValidDeviceContext(dctx, 1);
83   PetscValidPointer(event, 2);
84   id    = PetscObjectCast(dctx)->id;
85   state = PetscObjectCast(dctx)->state;
86   // technically state can never be less than event->dctx_state (only equal) but we include
87   // it in the check just in case
88   if ((id == event->dctx_id) && (state <= event->dctx_state)) PetscFunctionReturn(PETSC_SUCCESS);
89   if (dctx->ops->recordevent) {
90     // REVIEW ME:
91     // TODO maybe move this to impls, as they can determine whether they can interoperate with
92     // other device types more readily
93     if (PetscDefined(USE_DEBUG) && (event->dtype != PETSC_DEVICE_HOST)) {
94       PetscDeviceType dtype;
95 
96       PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype));
97       PetscCheck(event->dtype == dtype, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Event type %s does not match device context type %s", PetscDeviceTypes[event->dtype], PetscDeviceTypes[dtype]);
98     }
99     PetscUseTypeMethod(dctx, recordevent, event);
100   }
101   event->dctx_id    = id;
102   event->dctx_state = state;
103   PetscFunctionReturn(PETSC_SUCCESS);
104 }
105 
106 static PetscErrorCode PetscDeviceContextWaitForEvent_Private(PetscDeviceContext dctx, PetscEvent event)
107 {
108   PetscFunctionBegin;
109   PetscValidDeviceContext(dctx, 1);
110   PetscValidPointer(event, 2);
111   // empty data implies you cannot wait on this event
112   if (!event->data) PetscFunctionReturn(PETSC_SUCCESS);
113   if (PetscDefined(USE_DEBUG)) {
114     const auto      etype = event->dtype;
115     PetscDeviceType dtype;
116 
117     PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype));
118     PetscCheck(etype == dtype, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Event type %s does not match device context type %s", PetscDeviceTypes[etype], PetscDeviceTypes[dtype]);
119   }
120   if (PetscObjectCast(dctx)->id == event->dctx_id) PetscFunctionReturn(PETSC_SUCCESS);
121   PetscTryTypeMethod(dctx, waitforevent, event);
122   PetscFunctionReturn(PETSC_SUCCESS);
123 }
124 
125 // ==========================================================================================
126 // PetscStackFrame
127 //
128 // A helper class that (when debugging is enabled) contains the stack frame from which
129 // PetscDeviceContextMakrIntentFromID(). It is intended to be derived from, since this enables
130 // empty-base-class optimization to kick in when debugging is disabled.
131 // ==========================================================================================
132 
133 template <bool use_debug>
134 struct PetscStackFrame;
135 
136 template <>
137 struct PetscStackFrame</* use_debug = */ true> {
138   std::string file{};
139   std::string function{};
140   int         line{};
141 
142   PetscStackFrame() = default;
143 
144   PetscStackFrame(const char *file_, const char *func_, int line_) noexcept : file(split_on_petsc_path_(file_)), function(func_), line(line_) { }
145 
146   bool operator==(const PetscStackFrame &other) const noexcept { return line == other.line && file == other.file && function == other.function; }
147 
148   PETSC_NODISCARD std::string to_string() const noexcept
149   {
150     std::string ret;
151 
152     ret = '(' + function + "() at " + file + ':' + std::to_string(line) + ')';
153     return ret;
154   }
155 
156 private:
157   static std::string split_on_petsc_path_(std::string &&in) noexcept
158   {
159     auto pos = in.find("petsc/src");
160 
161     if (pos == std::string::npos) pos = in.find("petsc/include");
162     if (pos == std::string::npos) pos = 0;
163     return in.substr(pos);
164   }
165 
166   friend std::ostream &operator<<(std::ostream &os, const PetscStackFrame &frame)
167   {
168     os << frame.to_string();
169     return os;
170   }
171 
172   friend void swap(PetscStackFrame &lhs, PetscStackFrame &rhs) noexcept
173   {
174     using std::swap;
175 
176     swap(lhs.file, rhs.file);
177     swap(lhs.function, rhs.function);
178     swap(lhs.line, rhs.line);
179   }
180 };
181 
182 template <>
183 struct PetscStackFrame</* use_debug = */ false> {
184   template <typename... T>
185   constexpr PetscStackFrame(T &&...) noexcept
186   {
187   }
188 
189   constexpr bool operator==(const PetscStackFrame &) const noexcept { return true; }
190 
191   PETSC_NODISCARD static std::string to_string() noexcept { return "(unknown)"; }
192 
193   friend std::ostream &operator<<(std::ostream &os, const PetscStackFrame &) noexcept
194   {
195     os << "(unknown)";
196     return os;
197   }
198 };
199 
200 // ==========================================================================================
201 // MarkedObjectMap
202 //
203 // A mapping from a PetscObjectId to a PetscEvent and (if debugging is enabled) a
204 // PetscStackFrame containing the location where PetscDeviceContextMarkIntentFromID was called
205 // ==========================================================================================
206 
207 class MarkedObjectMap : public Petsc::RegisterFinalizeable<MarkedObjectMap> {
208 public:
209   // Note we derive from PetscStackFrame so that the empty base class optimization can kick
210   // in. If it were just a member it would still take up storage in optimized builds
211   class snapshot_type : private PetscStackFrame<PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY)> {
212   public:
213     using frame_type = PetscStackFrame<PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY)>;
214 
215     snapshot_type() = default;
216     snapshot_type(PetscDeviceContext, frame_type) noexcept;
217 
218     ~snapshot_type() noexcept;
219 
220     // movable
221     snapshot_type(snapshot_type &&) noexcept;
222     snapshot_type &operator=(snapshot_type &&) noexcept;
223 
224     // not copyable
225     snapshot_type(const snapshot_type &) noexcept            = delete;
226     snapshot_type &operator=(const snapshot_type &) noexcept = delete;
227 
228     PETSC_NODISCARD PetscEvent        event() const noexcept { return event_; }
229     PETSC_NODISCARD const frame_type &frame() const noexcept { return *this; }
230     PETSC_NODISCARD frame_type       &frame() noexcept { return *this; }
231 
232     PETSC_NODISCARD PetscObjectId dctx_id() const noexcept
233     {
234       PetscFunctionBegin;
235       PetscAssertAbort(event(), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Snapshot %s does not contain an event!", frame().to_string().c_str());
236       PetscFunctionReturn(event()->dctx_id);
237     }
238 
239     PetscErrorCode ensure_event(PetscDeviceContext) noexcept;
240 
241     friend void swap(snapshot_type &, snapshot_type &) noexcept;
242 
243   private:
244     PetscEvent event_{}; // the state of device context when this snapshot was recorded
245 
246     PETSC_NODISCARD static PetscEvent init_event_(PetscDeviceContext) noexcept;
247   };
248 
249   // the "value" each key maps to
250   struct mapped_type {
251     using dependency_type = std::vector<snapshot_type>;
252 
253     mapped_type() noexcept;
254 
255     PetscMemoryAccessMode mode{PETSC_MEMORY_ACCESS_READ};
256     snapshot_type         last_write{};
257     dependency_type       dependencies{};
258   };
259 
260   using map_type = Petsc::UnorderedMap<PetscObjectId, mapped_type>;
261 
262   map_type map;
263 
264 private:
265   friend RegisterFinalizeable;
266 
267   PetscErrorCode finalize_() noexcept;
268 };
269 
270 // ==========================================================================================
271 // MarkedObjectMap::mapped_type -- Public API
272 // ==========================================================================================
273 
274 // workaround for clang bug that produces the following warning
275 //
276 // src/sys/objects/device/interface/mark_dcontext.cxx:253:5: error: default member initializer
277 // for 'mode' needed within definition of enclosing class 'MarkedObjectMap' outside of member
278 // functions
279 //     mapped_type() noexcept = default;
280 //     ^
281 // https://stackoverflow.com/questions/53408962/try-to-understand-compiler-error-message-default-member-initializer-required-be
282 MarkedObjectMap::mapped_type::mapped_type() noexcept = default;
283 
284 // ==========================================================================================
285 // MarkedObjectMap Private API
286 // ==========================================================================================
287 
288 inline PetscErrorCode MarkedObjectMap::finalize_() noexcept
289 {
290   PetscFunctionBegin;
291   PetscCall(PetscInfo(nullptr, "Finalizing marked object map\n"));
292   PetscCall(map.clear());
293   PetscFunctionReturn(PETSC_SUCCESS);
294 }
295 
296 // ==========================================================================================
297 // MarkedObjectMap::snapshot_type Private API
298 // ==========================================================================================
299 
300 inline PetscEvent MarkedObjectMap::snapshot_type::init_event_(PetscDeviceContext dctx) noexcept
301 {
302   PetscEvent event = nullptr;
303 
304   PetscFunctionBegin;
305   PetscCallAbort(PETSC_COMM_SELF, PetscDeviceContextCreateEvent_Private(dctx, &event));
306   PetscCallAbort(PETSC_COMM_SELF, PetscDeviceContextRecordEvent_Private(dctx, event));
307   PetscFunctionReturn(event);
308 }
309 
310 // ==========================================================================================
311 // MarkedObjectMap::snapshot_type Public API
312 // ==========================================================================================
313 
314 MarkedObjectMap::snapshot_type::snapshot_type(PetscDeviceContext dctx, frame_type frame) noexcept : frame_type(std::move(frame)), event_(init_event_(dctx)) { }
315 
316 MarkedObjectMap::snapshot_type::~snapshot_type() noexcept
317 {
318   PetscFunctionBegin;
319   PetscCallAbort(PETSC_COMM_SELF, PetscEventDestroy_Private(&event_));
320   PetscFunctionReturnVoid();
321 }
322 
323 // movable
324 MarkedObjectMap::snapshot_type::snapshot_type(snapshot_type &&other) noexcept : frame_type(std::move(other)), event_(Petsc::util::exchange(other.event_, nullptr)) { }
325 
326 MarkedObjectMap::snapshot_type &MarkedObjectMap::snapshot_type::operator=(snapshot_type &&other) noexcept
327 {
328   PetscFunctionBegin;
329   if (this != &other) {
330     frame_type::operator=(std::move(other));
331     PetscCallAbort(PETSC_COMM_SELF, PetscEventDestroy_Private(&event_));
332     event_ = Petsc::util::exchange(other.event_, nullptr);
333   }
334   PetscFunctionReturn(*this);
335 }
336 
337 PetscErrorCode MarkedObjectMap::snapshot_type::ensure_event(PetscDeviceContext dctx) noexcept
338 {
339   PetscFunctionBegin;
340   if (PetscUnlikely(!event_)) PetscCall(PetscDeviceContextCreateEvent_Private(dctx, &event_));
341   PetscFunctionReturn(PETSC_SUCCESS);
342 }
343 
344 void swap(MarkedObjectMap::snapshot_type &lhs, MarkedObjectMap::snapshot_type &rhs) noexcept
345 {
346   using std::swap;
347 
348   swap(lhs.frame(), rhs.frame());
349   swap(lhs.event_, rhs.event_);
350 }
351 
352 // A mapping between PetscObjectId (i.e. some PetscObject) to the list of PetscEvent's encoding
353 // the last time the PetscObject was accessed
354 static MarkedObjectMap marked_object_map;
355 
356 // ==========================================================================================
357 // Utility Functions
358 // ==========================================================================================
359 
360 PetscErrorCode PetscGetMarkedObjectMap_Internal(std::size_t *nkeys, PetscObjectId **keys, PetscMemoryAccessMode **modes, std::size_t **ndeps, PetscEvent ***dependencies)
361 {
362   std::size_t i    = 0;
363   const auto &map  = marked_object_map.map;
364   const auto  size = *nkeys = map.size();
365 
366   PetscFunctionBegin;
367   PetscCall(PetscMalloc4(size, keys, size, modes, size, ndeps, size, dependencies));
368   for (auto it_ = map.begin(); it_ != map.end(); ++it_) {
369     auto       &it = *it_;
370     std::size_t j  = 0;
371 
372     (*keys)[i]         = it.first;
373     (*modes)[i]        = it.second.mode;
374     (*ndeps)[i]        = it.second.dependencies.size();
375     (*dependencies)[i] = nullptr;
376     PetscCall(PetscMalloc1((*ndeps)[i], (*dependencies) + i));
377     for (auto &&dep : it.second.dependencies) (*dependencies)[i][j++] = dep.event();
378     ++i;
379   }
380   PetscFunctionReturn(PETSC_SUCCESS);
381 }
382 
383 PetscErrorCode PetscRestoreMarkedObjectMap_Internal(std::size_t nkeys, PetscObjectId **keys, PetscMemoryAccessMode **modes, std::size_t **ndeps, PetscEvent ***dependencies)
384 {
385   PetscFunctionBegin;
386   for (std::size_t i = 0; i < nkeys; ++i) PetscCall(PetscFree((*dependencies)[i]));
387   PetscCall(PetscFree4(*keys, *modes, *ndeps, *dependencies));
388   PetscFunctionReturn(PETSC_SUCCESS);
389 }
390 
391 template <typename T>
392 static PetscErrorCode PetscDeviceContextMapIterVisitor(PetscDeviceContext dctx, T &&callback) noexcept
393 {
394   const auto dctx_id    = PetscObjectCast(dctx)->id;
395   auto      &dctx_deps  = CxxDataCast(dctx)->deps;
396   auto      &object_map = marked_object_map.map;
397 
398   PetscFunctionBegin;
399   for (auto &&dep : dctx_deps) {
400     const auto mapit = object_map.find(dep);
401 
402     // Need this check since the final PetscDeviceContext may run through this *after* the map
403     // has been finalized (and cleared), and hence might fail to find its dependencies. This is
404     // perfectly valid since the user no longer cares about dangling dependencies after PETSc
405     // is finalized
406     if (PetscLikely(mapit != object_map.end())) {
407       auto      &deps = mapit->second.dependencies;
408       const auto end  = deps.end();
409       const auto it   = std::remove_if(deps.begin(), end, [&](const MarkedObjectMap::snapshot_type &obj) { return obj.dctx_id() == dctx_id; });
410 
411       PetscCall(callback(mapit, deps.cbegin(), static_cast<decltype(deps.cend())>(it)));
412       // remove ourselves
413       PetscCallCXX(deps.erase(it, end));
414       // continue to next object, but erase this one if it has no more dependencies
415       if (deps.empty()) PetscCallCXX(object_map.erase(mapit));
416     }
417   }
418   PetscCallCXX(dctx_deps.clear());
419   PetscFunctionReturn(PETSC_SUCCESS);
420 }
421 
422 PetscErrorCode PetscDeviceContextSyncClearMap_Internal(PetscDeviceContext dctx)
423 {
424   using map_iterator = MarkedObjectMap::map_type::const_iterator;
425   using dep_iterator = MarkedObjectMap::mapped_type::dependency_type::const_iterator;
426 
427   PetscFunctionBegin;
428   PetscCall(PetscDeviceContextMapIterVisitor(dctx, [&](map_iterator mapit, dep_iterator it, dep_iterator end) {
429     PetscFunctionBegin;
430     if (PetscDefined(USE_DEBUG_AND_INFO)) {
431       std::ostringstream oss;
432       const auto         mode = PetscMemoryAccessModeToString(mapit->second.mode);
433 
434       oss << "synced dctx " << PetscObjectCast(dctx)->id << ", remaining leaves for obj " << mapit->first << ": {";
435       while (it != end) {
436         oss << "[dctx " << it->dctx_id() << ", " << mode << ' ' << it->frame() << ']';
437         if (++it != end) oss << ", ";
438       }
439       oss << '}';
440       PetscCall(PetscInfo(nullptr, "%s\n", oss.str().c_str()));
441     }
442     PetscFunctionReturn(PETSC_SUCCESS);
443   }));
444   {
445     // the recursive sync clear map call is unbounded in case of a dependenct loop so we make a
446     // copy
447     // clang-format off
448     const std::vector<CxxData::upstream_type::value_type> upstream_copy(
449       std::make_move_iterator(CxxDataCast(dctx)->upstream.begin()),
450       std::make_move_iterator(CxxDataCast(dctx)->upstream.end())
451     );
452     // clang-format on
453 
454     // aftermath, clear our set of parents (to avoid infinite recursion) and mark ourselves as no
455     // longer contained (while the empty graph technically *is* always contained, it is not what
456     // we mean by it)
457     PetscCall(CxxDataCast(dctx)->clear());
458     //dctx->contained = PETSC_FALSE;
459     for (auto &&upstrm : upstream_copy) {
460       // check that this parent still points to what we originally thought it was
461       PetscCheck(upstrm.second.id == PetscObjectCast(upstrm.first)->id, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Upstream dctx %" PetscInt64_FMT " no longer exists, now has id %" PetscInt64_FMT, upstrm.second.id, PetscObjectCast(upstrm.first)->id);
462       PetscCall(PetscDeviceContextSyncClearMap_Internal(upstrm.first));
463     }
464   }
465   PetscFunctionReturn(PETSC_SUCCESS);
466 }
467 
468 PetscErrorCode PetscDeviceContextCheckNotOrphaned_Internal(PetscDeviceContext dctx)
469 {
470   std::ostringstream oss;
471   //const auto         allow = dctx->options.allow_orphans, contained = dctx->contained;
472   const auto allow = true, contained = true;
473   auto       wrote_to_oss = false;
474   using map_iterator      = MarkedObjectMap::map_type::const_iterator;
475   using dep_iterator      = MarkedObjectMap::mapped_type::dependency_type::const_iterator;
476 
477   PetscFunctionBegin;
478   PetscCall(PetscDeviceContextMapIterVisitor(dctx, [&](map_iterator mapit, dep_iterator it, dep_iterator end) {
479     PetscFunctionBegin;
480     if (allow || contained) PetscFunctionReturn(PETSC_SUCCESS);
481     wrote_to_oss = true;
482     oss << "- PetscObject (id " << mapit->first << "), intent " << PetscMemoryAccessModeToString(mapit->second.mode) << ' ' << it->frame();
483     if (std::distance(it, end) == 0) oss << " (orphaned)"; // we were the only dependency
484     oss << '\n';
485     PetscFunctionReturn(PETSC_SUCCESS);
486   }));
487   PetscCheck(!wrote_to_oss, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Destroying PetscDeviceContext ('%s', id %" PetscInt64_FMT ") would leave the following dangling (possibly orphaned) dependants:\n%s\nMust synchronize before destroying it, or allow it to be destroyed with orphans",
488              PetscObjectCast(dctx)->name ? PetscObjectCast(dctx)->name : "unnamed", PetscObjectCast(dctx)->id, oss.str().c_str());
489   PetscCall(CxxDataCast(dctx)->clear());
490   PetscFunctionReturn(PETSC_SUCCESS);
491 }
492 
493 #define DEBUG_INFO(mess, ...) PetscDebugInfo(dctx, "dctx %" PetscInt64_FMT " (%s) - obj %" PetscInt64_FMT " (%s): " mess, PetscObjectCast(dctx)->id, PetscObjectCast(dctx)->name ? PetscObjectCast(dctx)->name : "unnamed", id, name, ##__VA_ARGS__)
494 
495 // The current mode is compatible with the previous mode (i.e. read-read) so we need only
496 // update the existing version and possibly appeand ourselves to the dependency list
497 
498 template <bool use_debug>
499 static PetscErrorCode MarkFromID_CompatibleModes(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *PETSC_UNUSED name, bool *update_object_dependencies)
500 {
501   const auto dctx_id             = PetscObjectCast(dctx)->id;
502   auto      &object_dependencies = marked.dependencies;
503   const auto end                 = object_dependencies.end();
504   const auto it                  = std::find_if(object_dependencies.begin(), end, [&](const MarkedObjectMap::snapshot_type &obj) { return obj.dctx_id() == dctx_id; });
505 
506   PetscFunctionBegin;
507   PetscCall(DEBUG_INFO("new mode (%s) COMPATIBLE with %s mode (%s), no need to serialize\n", PetscMemoryAccessModeToString(mode), object_dependencies.empty() ? "default" : "old", PetscMemoryAccessModeToString(marked.mode)));
508   (void)mode;
509   if (it != end) {
510     using std::swap;
511 
512     // we have been here before, all we must do is update our entry then we can bail
513     PetscCall(DEBUG_INFO("found old self as dependency, updating\n"));
514     PetscAssert(CxxDataCast(dctx)->deps.find(id) != CxxDataCast(dctx)->deps.end(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "PetscDeviceContext %" PetscInt64_FMT " listed as dependency for object %" PetscInt64_FMT " (%s), but does not have the object in private dependency list!", dctx_id, id, name);
515     swap(it->frame(), frame);
516     PetscCall(PetscDeviceContextRecordEvent_Private(dctx, it->event()));
517     *update_object_dependencies = false;
518     PetscFunctionReturn(PETSC_SUCCESS);
519   }
520 
521   // we have not been here before, need to serialize with the last write event (if it exists)
522   // and add ourselves to the dependency list
523   if (const auto event = marked.last_write.event()) PetscCall(PetscDeviceContextWaitForEvent_Private(dctx, event));
524   PetscFunctionReturn(PETSC_SUCCESS);
525 }
526 
527 template <bool use_debug>
528 static PetscErrorCode MarkFromID_IncompatibleModes_UpdateLastWrite(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *PETSC_UNUSED name, bool *update_object_dependencies)
529 {
530   const auto      dctx_id    = PetscObjectCast(dctx)->id;
531   auto           &last_write = marked.last_write;
532   auto           &last_dep   = marked.dependencies.back();
533   PetscDeviceType dtype;
534 
535   PetscFunctionBegin;
536   PetscAssert(marked.dependencies.size() == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Can only have a single writer as dependency, have %zu!", marked.dependencies.size());
537   PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype));
538   if (last_dep.event()->dtype != dtype) {
539     PetscCall(DEBUG_INFO("moving last write dependency (intent %s)\n", PetscMemoryAccessModeToString(marked.mode)));
540     last_write = std::move(last_dep);
541     PetscFunctionReturn(PETSC_SUCCESS);
542   }
543 
544   // we match the device type of the dependency, we can reuse its event!
545   auto      &dctx_upstream_deps     = CxxDataCast(dctx)->deps;
546   const auto last_write_was_also_us = last_write.event() && (last_write.dctx_id() == dctx_id);
547   using std::swap;
548 
549   PetscCall(DEBUG_INFO("we matched the previous write dependency's (intent %s) device type (%s), swapping last dependency with last write\n", PetscMemoryAccessModeToString(marked.mode), PetscDeviceTypes[dtype]));
550   if (last_dep.event()->dctx_id != dctx_id) dctx_upstream_deps.emplace(id);
551   PetscAssert(dctx_upstream_deps.find(id) != dctx_upstream_deps.end(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Did not find id %" PetscInt64_FMT "in object dependencies, but we have apparently recorded the last dependency %s!", id,
552               last_write.frame().to_string().c_str());
553   swap(last_write, last_dep);
554   if (last_write_was_also_us) {
555     PetscCall(DEBUG_INFO("we were also the last write event (intent %s), updating\n", PetscMemoryAccessModeToString(mode)));
556     (void)mode;
557     // we are both the last to write *and* the last to leave a write event. This is the
558     // fast path, we only need to update the frame and update the recorded event
559     swap(last_dep.frame(), frame);
560     // last used to be last_write which is not guaranteed to have an event, so must
561     // create it now
562     PetscCall(last_dep.ensure_event(dctx));
563     PetscCall(PetscDeviceContextRecordEvent_Private(dctx, last_dep.event()));
564     *update_object_dependencies = false;
565   }
566   PetscFunctionReturn(PETSC_SUCCESS);
567 }
568 
569 // The current mode is NOT compatible with the previous mode. We must serialize with all events
570 // in the dependency list, possibly clear it, and update the previous write event
571 
572 template <bool use_debug>
573 static PetscErrorCode MarkFromID_IncompatibleModes(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *name, bool *update_object_dependencies)
574 {
575   auto &old_mode            = marked.mode;
576   auto &object_dependencies = marked.dependencies;
577 
578   PetscFunctionBegin;
579   // we are NOT compatible with the previous mode
580   PetscCall(DEBUG_INFO("new mode (%s) NOT COMPATIBLE with %s mode (%s), serializing then clearing (%zu) %s\n", PetscMemoryAccessModeToString(mode), object_dependencies.empty() ? "default" : "old", PetscMemoryAccessModeToString(old_mode),
581                        object_dependencies.size(), object_dependencies.size() == 1 ? "dependency" : "dependencies"));
582 
583   for (const auto &dep : object_dependencies) PetscCall(PetscDeviceContextWaitForEvent_Private(dctx, dep.event()));
584   // if the previous mode wrote, update the last write node with it
585   if (PetscMemoryAccessWrite(old_mode)) PetscCall(MarkFromID_IncompatibleModes_UpdateLastWrite(marked, dctx, id, mode, frame, name, update_object_dependencies));
586 
587   old_mode = mode;
588   // clear out the old dependencies if are about to append ourselves
589   if (*update_object_dependencies) object_dependencies.clear();
590   PetscFunctionReturn(PETSC_SUCCESS);
591 }
592 
593 template <bool use_debug>
594 static PetscErrorCode PetscDeviceContextMarkIntentFromID_Private(PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> frame, const char *name)
595 {
596   auto &marked                     = marked_object_map.map[id];
597   auto &object_dependencies        = marked.dependencies;
598   auto  update_object_dependencies = true;
599 
600   PetscFunctionBegin;
601   if ((marked.mode == PETSC_MEMORY_ACCESS_READ) && (mode == PETSC_MEMORY_ACCESS_READ)) {
602     PetscCall(MarkFromID_CompatibleModes(marked, dctx, id, mode, frame, name, &update_object_dependencies));
603   } else {
604     PetscCall(MarkFromID_IncompatibleModes(marked, dctx, id, mode, frame, name, &update_object_dependencies));
605   }
606   if (update_object_dependencies) {
607     // become the new leaf by appending ourselves
608     PetscCall(DEBUG_INFO("%s with intent %s\n", object_dependencies.empty() ? "dependency list is empty, creating new leaf" : "appending to existing leaves", PetscMemoryAccessModeToString(mode)));
609     PetscCallCXX(object_dependencies.emplace_back(dctx, std::move(frame)));
610     PetscCallCXX(CxxDataCast(dctx)->deps.emplace(id));
611   }
612   PetscFunctionReturn(PETSC_SUCCESS);
613 }
614 
615 #undef DEBUG_INFO
616 
617 /*@C
618   PetscDeviceContextMarkIntentFromID - Indicate a `PetscDeviceContext`s access intent to the
619   auto-dependency system
620 
621   Not Collective
622 
623   Input Parameters:
624 + dctx - The `PetscDeviceContext`
625 . id   - The `PetscObjectId` to mark
626 . mode - The desired access intent
627 - name - The object name (for debug purposes, ignored in optimized builds)
628 
629   Notes:
630   This routine formally informs the dependency system that `dctx` will access the object
631   represented by `id` with `mode` and adds `dctx` to `id`'s list of dependencies (termed
632   "leaves").
633 
634   If the existing set of leaves have an incompatible `PetscMemoryAccessMode` to `mode`, `dctx`
635   will be serialized against them.
636 
637   Level: intermediate
638 
639 .seealso: `PetscDeviceContextWaitForContext()`, `PetscDeviceContextSynchronize()`,
640 `PetscObjectGetId()`, `PetscMemoryAccessMode`
641 @*/
642 PetscErrorCode PetscDeviceContextMarkIntentFromID(PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, const char name[])
643 {
644 #if PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY)
645   const auto index    = petscstack.currentsize > 2 ? petscstack.currentsize - 2 : 0;
646   const auto file     = petscstack.file[index];
647   const auto function = petscstack.function[index];
648   const auto line     = petscstack.line[index];
649 #else
650   constexpr const char *file     = nullptr;
651   constexpr const char *function = nullptr;
652   constexpr auto        line     = 0;
653 #endif
654 
655   PetscFunctionBegin;
656   PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
657   if (name) PetscValidCharPointer(name, 4);
658   PetscCall(marked_object_map.register_finalize());
659   PetscCall(PetscLogEventBegin(DCONTEXT_Mark, dctx, nullptr, nullptr, nullptr));
660   PetscCall(PetscDeviceContextMarkIntentFromID_Private(dctx, id, mode, MarkedObjectMap::snapshot_type::frame_type{file, function, line}, name ? name : "unknown object"));
661   PetscCall(PetscLogEventEnd(DCONTEXT_Mark, dctx, nullptr, nullptr, nullptr));
662   PetscFunctionReturn(PETSC_SUCCESS);
663 }
664 
665 #if defined(__clang__)
666   #pragma clang diagnostic pop
667 #endif
668