1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// SPDX-FileCopyrightText: 2023 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Wrap delay/constraint models and add the capability to tag signals with an associated clock.

use libreda_db::prelude as db;
use num_traits::Zero;
use smallvec::{smallvec, SmallVec};
use std::{collections::HashMap, num::NonZeroU32, ops::Deref, sync::RwLock};

use uom::si::f64::Time;

use crate::{
    traits::{
        cell_constraint_model::{CellConstraintArc, CellConstraintModel},
        cell_logic_model::{LogicModel, OutputFunction},
        timing_base::SignalTransitionType,
        CellDelayArc, CellDelayModel, CellModel, ConstraintBase, DelayBase, InterconnectDelayModel,
        LoadBase, Signal, TimingBase,
    },
    RequiredSignal, RiseFall,
};

/// Compact ID for marking signals with a clock.
///
/// Identifier for clocks, generated clocks, propagated clocks, inverted clocks, etc.
/// This struct is a wrapper around a 32-bit integer. It is used
/// as an efficient marker to associate nets with a clock source.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ClockId {
    /// Allow to efficiently encode `None` by using a non-zero integer.
    /// The lowest-significant bits indicate:
    /// * bit 0: this signal is marked as a clock signal
    /// * bit 1: inversion of the clock levels.
    /// * bit 2: signal can change on rising edge of clock
    /// * bit 3: signal can change on falling edge of clock
    ///
    /// For example, bit 1 and 2 are always set for a signal in the clock tree.
    /// When passing through a single-edge-triggered flip-flop one of the bits will be cleared.
    ///
    /// Id = 1 must not be used because the clock id = 0 is used for encoding `None`.
    ///
    id: NonZeroU32,
}

#[test]
fn test_clock_id_compact_encoding_of_option() {
    use core::mem::size_of;
    assert_eq!(size_of::<Option<ClockId>>(), size_of::<ClockId>());
}

impl std::fmt::Debug for ClockId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ClockId(index={}, flags=[", self.storage_index())?;

        // Display the enabled flags using letters.
        let flags = [
            ("C", ClockId::BIT_INDEX_IS_CLOCK),
            ("I", ClockId::BIT_INDEX_INVERTED),
            ("R", ClockId::BIT_INDEX_RISING_EDGE),
            ("F", ClockId::BIT_INDEX_FALLING_EDGE),
        ];
        for (symbol, bit_index) in flags {
            if self.get_bit(bit_index) {
                write!(f, "{}", symbol)?;
            }
        }

        write!(f, "])")
    }
}

impl ClockId {
    /// Number of least-significant bits which are used as flag bits.
    const NUM_FLAGS: usize = 4;
    const BIT_INDEX_IS_CLOCK: usize = 0;
    const BIT_INDEX_INVERTED: usize = 1;
    const BIT_INDEX_RISING_EDGE: usize = 2;
    const BIT_INDEX_FALLING_EDGE: usize = 3;

    /// Create a new clock ID from the index of the clock.
    /// The index is a 'pointer' to the specification of the clock.
    /// The ID is used to annotate signals in order to link them to a clock source.
    /// The ID does not only store this index but also keeps track of other properties such as
    /// on which clock events the signal can change.
    pub fn new(storage_index: u32) -> Self {
        // Make sure `id` is not zero (`0` this is used for encoding `None`).
        let id = storage_index + 1;

        // Add flags.
        let id = id << Self::NUM_FLAGS;

        let mut id = Self {
            id: NonZeroU32::new(id).unwrap(),
        };

        // By default, the signal can change on both clock edges.
        id.set_edge_sensitivity(RiseFall::Rise, true);
        id.set_edge_sensitivity(RiseFall::Fall, true);

        id
    }

    /// Create a new ID by taking the index from `self` and the bit flags from `other`.
    fn with_flags_from(&self, other: Self) -> Self {
        let mask = (1 << Self::NUM_FLAGS) - 1;

        let raw = self.id.get();
        // Clear flags.
        let cleared = raw & !mask;
        // Copy flags.
        let with_flags = cleared | (other.id.get() & mask);

        Self {
            id: NonZeroU32::new(with_flags).unwrap(),
        }
    }

    /// Get the index into the array of clocks.
    /// Points to the detailed description of the corresponding clock.
    pub fn storage_index(&self) -> usize {
        ((self.id.get() >> Self::NUM_FLAGS) - 1) as usize
    }

    /// Check if this ID refers to an inverted version of the clock.
    pub fn is_inverted(&self) -> bool {
        self.get_bit(Self::BIT_INDEX_INVERTED)
    }

    /// Test if this signal is marked as a clock signal.
    /// This flag gets cleared when a clock signal passes through a clock input
    /// of a sequential cell to a data output.
    pub fn is_clock(&self) -> bool {
        self.get_bit(Self::BIT_INDEX_IS_CLOCK)
    }

    /// Define if this signal is a clock or just a clocked signal otherwise.
    pub fn set_clock(&mut self, is_clock: bool) {
        self.set_bit(Self::BIT_INDEX_IS_CLOCK, is_clock)
    }

    /// Get the ID of the inverted clock.
    pub fn inverted(&self) -> Self {
        let mut inverted = *self;
        inverted.flip_bit(Self::BIT_INDEX_INVERTED);
        inverted
    }

    /// For actual signals: Test if the signal can change on the given edge type of the associated clock.
    /// For required signals: Test if the constraint applies to the given edge type of the associated clock.
    pub fn is_sensitive_on_edge(&self, edge_type: RiseFall) -> bool {
        let bit_idx = match edge_type {
            RiseFall::Rise => Self::BIT_INDEX_RISING_EDGE,
            RiseFall::Fall => Self::BIT_INDEX_FALLING_EDGE,
        };

        self.get_bit(bit_idx)
    }

    /// For actual signals: Define if the signal annotated with this ID can change on the given clock edge.
    pub fn set_edge_sensitivity(&mut self, edge_type: RiseFall, can_change: bool) {
        let bit_idx = match edge_type {
            RiseFall::Rise => Self::BIT_INDEX_RISING_EDGE,
            RiseFall::Fall => Self::BIT_INDEX_FALLING_EDGE,
        };

        self.set_bit(bit_idx, can_change);
    }

    /// Set the value of the bit at the given index.
    fn set_bit(&mut self, bit_idx: usize, value: bool) {
        debug_assert!(bit_idx < Self::NUM_FLAGS, "cannot modify the clock index");
        let id = self.id.get();

        // Clear flag.
        let id = id & (!(1 << bit_idx));
        // Conditionally set flag.
        let id = id | ((value as u32) << bit_idx);

        // Store the modified id.
        self.id = NonZeroU32::new(id).unwrap();
    }

    /// Flip the bit at the given index.
    /// # Panics
    /// Panics if the bitflip leads to an all-zero value.
    fn flip_bit(&mut self, bit_idx: usize) {
        debug_assert!(
            bit_idx < Self::NUM_FLAGS,
            "bit index out of range: cannot modify the clock index"
        );
        let id = self.id.get() ^ (1 << bit_idx);
        self.id = NonZeroU32::new(id).unwrap()
    }

    /// Get the value of the bit a the given index.
    fn get_bit(&self, bit_idx: usize) -> bool {
        debug_assert!(
            bit_idx < Self::NUM_FLAGS,
            "bit index out of range: cannot modify the clock index"
        );
        self.id.get() & (1 << bit_idx) != 0
    }
}

#[test]
fn test_create_clock_id() {
    let id = ClockId::new(7);
    assert_eq!(id.storage_index(), 7);
    // Check defaults:
    assert!(!id.is_clock());
    assert!(!id.is_inverted());
    assert!(id.is_sensitive_on_edge(RiseFall::Rise));
    assert!(id.is_sensitive_on_edge(RiseFall::Fall));
}

#[test]
fn test_clock_id_set_flags() {
    let mut id = ClockId::new(7);
    id.set_clock(true);
    assert!(id.is_clock());
    assert!(id.inverted().is_inverted());
    assert!(!id.inverted().inverted().is_inverted());
}

/// Signal representation wich can keep track of the clock(s) which launch the signal transition.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct SignalWithClock<S> {
    /// Underlying signal representation.
    inner: S,
    /// Clock which drives this signal.
    clock_id: Option<ClockId>,
}

impl<S> Deref for SignalWithClock<S> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<S> SignalWithClock<S> {
    /// Wrap a signal without clock ID.
    pub fn new(signal: S) -> Self {
        Self {
            inner: signal,
            clock_id: Default::default(),
        }
    }

    /// Set the ID of the clock which triggers this signal.
    pub fn with_clock_id(mut self, clock_id: Option<ClockId>) -> Self {
        self.set_clock_id(clock_id);
        self
    }

    /// Set or clear the associated clock ID.
    pub fn set_clock_id(&mut self, clock_id: Option<ClockId>) {
        self.clock_id = clock_id;
    }

    /// Get the ID of the clock which launches this signal.
    pub fn clock_id(&self) -> Option<ClockId> {
        self.clock_id
    }

    /// Access the underlying signal data.
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Get the underlying signal data.
    pub fn into_inner(self) -> S {
        self.inner
    }
}

impl<S> RequiredSignal for SignalWithClock<S> where S: RequiredSignal {}

impl<S> Signal for SignalWithClock<S>
where
    S: Signal,
{
    type LogicValue = S::LogicValue;

    fn logic_value(&self) -> Self::LogicValue {
        self.inner.logic_value()
    }

    fn transition_type(&self) -> SignalTransitionType {
        self.inner.transition_type()
    }

    fn with_transition_type(self, trans: SignalTransitionType) -> Self {
        let clock_id = self.clock_id;
        Self {
            inner: self.inner.with_transition_type(trans),
            clock_id,
        }
    }
}

/// Wrap a delay and/or constraint model and add the capability of tracking
/// clock sources.
#[derive(Debug)]
pub struct ClockAwareModel<M> {
    /// Underlying delay/constraint model.
    pub(crate) inner: M,
    /// Clock definitions.
    ///
    /// During signal propagation this does not need to be accessed most of the time.
    /// Only when merging signals from different clock domains it is necessary
    /// to acquire a read or even write lock.
    clocks: RwLock<Clocks>,
}

impl<M> Deref for ClockAwareModel<M> {
    type Target = M;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<M> ClockAwareModel<M> {
    /// Wrap a cell delay model.
    pub fn new(inner_model: M) -> Self {
        Self {
            inner: inner_model,
            clocks: Default::default(),
        }
    }

    /// Register a clock. Returns an ID which can be used for labelling signals with this clock.
    pub fn create_primary_clock(&mut self, period: Time, jitter: Time) -> ClockId {
        let clock_definition = PrimaryClockDefinition { period, jitter };

        self.clocks
            .write()
            .expect("failed to acquire read lock")
            .create_defined_clock(clock_definition)
    }

    /// Merge the clock IDs of two delay arcs.
    ///
    /// Typically, the clock IDs of two merging delay arcs are identical. In this case the clock ID remains the same.
    /// When joining delay arcs from different clock domains, it will be necessary to create a new clock ID
    /// which refers to the both clock domains being joined.
    fn join_clocks(&self, clock1: Option<ClockId>, clock2: Option<ClockId>) -> Option<ClockId> {
        // Merging two clocks.
        // Requires to create a new clock definition or find an existing one which matches.

        match (clock1, clock2) {
            // Both clock IDs are equal:
            (c1, c2) if c1 == c2 => c1,
            // Clock IDs are different:
            (Some(c1), Some(c2)) => {
                debug_assert_ne!(c1, c2);
                // Need to merge the two clock IDs.

                // Find existing merged clock ID, if any.
                let existing_id = {
                    let ids = smallvec::smallvec![c1, c2];
                    let clocks = self.clocks.read().expect("failed to acquire read-lock");
                    clocks.find_joined_clock_id(ids)
                };

                let joined_id = existing_id.unwrap_or_else(|| {
                    // Joined clock does not exist yet. Need to create it.
                    let ids = smallvec::smallvec![c1, c2];
                    let mut clocks = self.clocks.write().expect("failed to acquire write-lock");
                    clocks.create_joined_clock(ids)
                });

                Some(joined_id)
            }
            // Only one signal has a clock ID:
            (None, Some(c)) | (Some(c), None) => Some(c),
            // No clock ID present:
            (None, None) => None,
        }
    }

    fn join_clocks_of_required_signals(
        &self,
        clock1: Option<ClockId>,
        clock2: Option<ClockId>,
    ) -> Option<ClockId> {
        self.join_clocks(clock1, clock2)
    }

    /// Get clock period.
    fn clock_period(&self, clock_id: ClockId) -> Time {
        let clocks_guard = self.clocks.read().unwrap();
        let clock = clocks_guard.get_by_id(&clock_id);
        match clock {
            Clock::Primary(p) => p.period,
            Clock::Joined(_) => {
                // TODO
                // Make all timing fail by setting clock period to zero.
                Time::zero()
            }
        }
    }
}

/// Collection of defined/generated/derived clocks.
#[derive(Debug, Clone, Default)]
struct Clocks {
    /// Clock definitions.
    /// `ClockId`s refer to this definitions.
    clocks: Vec<Clock>,
    /// Lookup-table to find the clock ID which results from joining multiple clocks together.
    /// The clock IDs in the key of the map must be sorted lexicographically.
    joined_clocks: HashMap<SmallVec<[ClockId; 2]>, ClockId>,
}

impl Clocks {
    /// Create a new defined clock.
    /// Also creates the inverted clock.
    fn create_defined_clock(&mut self, clock_definition: PrimaryClockDefinition) -> ClockId {
        assert!(self.clocks.len() < u32::MAX as usize - 2);

        let mut new_id = self.next_id();
        new_id.set_clock(true);

        self.clocks.push(Clock::Primary(clock_definition));
        new_id
    }

    /// Get the next free clock ID.
    fn next_id(&self) -> ClockId {
        ClockId::new(self.clocks.len() as u32)
    }

    /// Get a clock by its ID.
    fn get_by_id(&self, id: &ClockId) -> &Clock {
        &self.clocks[id.storage_index()]
    }

    /// Find existing merged clock ID, if any.
    fn find_joined_clock_id(
        &self,
        mut source_clock_ids: SmallVec<[ClockId; 2]>,
    ) -> Option<ClockId> {
        // Normalize the list of IDs such that it can be used for table-lookup:
        source_clock_ids.sort();
        source_clock_ids.dedup();

        self.joined_clocks
            .get(&source_clock_ids)
            .copied()
            .or_else(|| {
                // Replace IDs of joined clocks with their primary sources.
                // This is the canonical form and guarantees finding the existing joined clock, if it exists.
                // But it has some overhead.
                let resolved_ids = self.resolve_joined_clocks(source_clock_ids.iter().copied());
                self.joined_clocks.get(&resolved_ids).copied()
            })
    }

    /// Replace IDs of joined clocks with the primary clock sources of the joined clocks.
    fn resolve_joined_clocks(&self, ids: impl Iterator<Item = ClockId>) -> SmallVec<[ClockId; 2]> {
        let mut primary_clock_ids: SmallVec<[_; 2]> = smallvec![];
        // Flatten the clock IDs such that the list contains only primary clock sources.
        for src_id in ids {
            match self.get_by_id(&src_id) {
                // Use primary clock IDs as is.
                Clock::Primary(_) => primary_clock_ids.push(src_id),
                // Resolve joined clocks.
                Clock::Joined(clock_def) => {
                    // Flatten.
                    for inner_id in &clock_def.source_clocks {
                        // Sanity check:
                        debug_assert!(
                            matches!(self.get_by_id(inner_id), Clock::Primary(_)),
                            "definition of joined clock should contain only primary clocks"
                        );
                        // Use flags from provided clock ID.
                        let primary_id = inner_id.with_flags_from(src_id);
                        primary_clock_ids.push(primary_id);
                    }
                }
            }
        }

        // Normalize
        primary_clock_ids.sort();
        primary_clock_ids.dedup();

        primary_clock_ids
    }

    /// Create new clock by joining delay arcs from multiple clock domains.
    fn create_joined_clock(&mut self, mut source_clock_ids: SmallVec<[ClockId; 2]>) -> ClockId {
        source_clock_ids.sort();
        source_clock_ids.dedup();

        let primary_clock_ids = self.resolve_joined_clocks(source_clock_ids.iter().copied());

        // Sanity check:
        debug_assert!(
            !self.joined_clocks.contains_key(&source_clock_ids),
            "joined clock already exists"
        );

        let clock_definition = JoinedClockDefinition {
            source_clocks: primary_clock_ids.clone(),
        };

        let new_id = self.next_id();
        // Store clock definition.
        self.clocks.push(Clock::Joined(clock_definition));

        // Register in lookup table.
        self.joined_clocks.insert(source_clock_ids, new_id);
        self.joined_clocks.insert(primary_clock_ids, new_id);

        new_id
    }
}

/// Definiton of a clock source.
/// This represents user-defined clocks.
#[derive(Debug, Clone)]
struct PrimaryClockDefinition {
    period: Time,
    jitter: Time,
}

/// Clock which emerged from joining delay arcs from multiple clock domains.
#[derive(Debug, Clone)]
struct JoinedClockDefinition {
    /// IDs of the clock which have been joined.
    source_clocks: SmallVec<[ClockId; 2]>,
}

#[derive(Debug, Clone)]
enum Clock {
    /// A clock defined by constraints.
    Primary(PrimaryClockDefinition),
    /// A clock which emerged by joining delay arcs from multiple clock domains.
    Joined(JoinedClockDefinition),
}

impl<M> LoadBase for ClockAwareModel<M>
where
    M: LoadBase,
{
    type Load = M::Load;

    fn sum_loads(&self, load1: &Self::Load, load2: &Self::Load) -> Self::Load {
        self.inner.sum_loads(load1, load2)
    }
}

impl<M> TimingBase for ClockAwareModel<M>
where
    M: TimingBase,
{
    type Signal = SignalWithClock<M::Signal>;

    type LogicValue = M::LogicValue;
}

impl<M> DelayBase for ClockAwareModel<M>
where
    M: DelayBase,
{
    type Delay = M::Delay;

    fn summarize_delays(&self, signal1: &Self::Signal, signal2: &Self::Signal) -> Self::Signal {
        let s = self.inner.summarize_delays(&signal1.inner, &signal2.inner);

        let clock_id = self.join_clocks(signal1.clock_id, signal2.clock_id);
        SignalWithClock { inner: s, clock_id }
    }

    fn get_delay(&self, from: &Self::Signal, to: &Self::Signal) -> Self::Delay {
        self.inner.get_delay(&from.inner, &to.inner)
    }
}

impl<M> ConstraintBase for ClockAwareModel<M>
where
    M: ConstraintBase,
{
    type Constraint = M::Constraint;

    type RequiredSignal = SignalWithClock<M::RequiredSignal>;

    type Slack = M::Slack;

    fn summarize_constraints(
        &self,
        constraint1: &Self::RequiredSignal,
        constraint2: &Self::RequiredSignal,
    ) -> Self::RequiredSignal {
        let constraint_without_clock = self
            .inner
            .summarize_constraints(constraint1.inner(), constraint2.inner());

        // Merge clock IDs.
        let clock_id =
            self.join_clocks_of_required_signals(constraint1.clock_id(), constraint2.clock_id());

        SignalWithClock {
            inner: constraint_without_clock,
            clock_id,
        }
    }

    fn solve_delay_constraint(
        &self,
        actual_delay: &Self::Delay,
        required_output: &Self::RequiredSignal,
        actual_signal: &Self::Signal,
    ) -> Self::RequiredSignal {
        let without_clock = self.inner.solve_delay_constraint(
            actual_delay,
            required_output.inner(),
            actual_signal.inner(),
        );

        SignalWithClock {
            inner: without_clock,
            clock_id: required_output.clock_id(),
        }
    }

    fn get_slack(
        &self,
        actual_signal: &Self::Signal,
        required_signal: &Self::RequiredSignal,
    ) -> Self::Slack {
        self.inner
            .get_slack(actual_signal.inner(), required_signal.inner())
    }

    fn add_clock_period(
        &self,
        required: Self::RequiredSignal,
        clock_period: Time,
    ) -> Self::RequiredSignal {
        SignalWithClock {
            inner: self.inner.add_clock_period(required.inner, clock_period),
            ..required
        }
    }
}

impl<M, N> CellModel<N> for ClockAwareModel<M>
where
    N: db::NetlistBase,
    M: CellModel<N>,
{
    fn ordered_pins(
        &self,
        cell: &<N>::CellId,
    ) -> Vec<<N as libreda_db::traits::NetlistIds>::PinId> {
        self.inner.ordered_pins(cell)
    }
}

impl<M, N> CellDelayModel<N> for ClockAwareModel<M>
where
    N: db::NetlistBase,
    M: CellDelayModel<N> + LogicModel<N>,
    M::LogicValue: libreda_logic::traits::LogicOps + TryInto<bool>,
{
    fn cell_output(
        &self,
        netlist: &N,
        arc: &CellDelayArc<N::PinId>,
        input_signal: &Self::Signal,
        output_load: &Self::Load,
        other_inputs: &impl Fn(&N::PinId) -> Option<Self::LogicValue>,
    ) -> Option<Self::Signal> {
        // Query the timing model.
        let output_signals_without_clock =
            self.inner
                .cell_output(netlist, arc, &input_signal.inner, output_load, other_inputs);

        // Get logic function of this output pin.
        let output_function = self.inner.pin_function(&arc.output_pin.0);

        // Distinguish between combinational and sequential outputs.
        let is_combinational_arc = match output_function {
            OutputFunction::Unknown => true, // Assume it is combinational.
            OutputFunction::Comb(_) => true,
            OutputFunction::Sequential(_) => false,
        };

        let clock_id = input_signal.clock_id.and_then(|input_clock_id| {
            if input_clock_id.is_clock() {
                // This is a clock signal.
                // The logic function of the cell may have an impact on the clock ID.

                // Construct the clock ID of the output signal.
                let mut output_clock_id = input_clock_id;

                // Remember on which clock edge this signal can change it's value.
                output_clock_id.set_edge_sensitivity(arc.input_pin.1, true);

                // Clear clock-flag when passing through a sequential delay arc.
                // When passing through a combinational circuit (buffer, inverter, mux, ...)
                // a clock signal is still considered a clock signal.
                output_clock_id.set_clock(is_combinational_arc);

                // For combinational arcs: investigate if the clock gets inverted or set to a constant.
                if is_combinational_arc {
                    let unateness = self.inner.timing_sense(
                        &arc.output_pin.0,
                        &arc.input_pin.0,
                        // Provide logic values of other inputs (if available):
                        &|pin| {
                            // Convert logic values to boolean values (if possible)
                            other_inputs(pin).and_then(|l| l.try_into().ok())
                        },
                    );

                    // Set flags according to the logic function of the arc.
                    use crate::cell_logic_model::Unateness;
                    match unateness {
                        Unateness::None => {
                            todo!("ClockId needs to know concept of 'unknown polarity'");
                        }
                        Unateness::Negative => Some(output_clock_id.inverted()),
                        Unateness::Positive => {
                            // Changes nothing about the semantics of the clock signal.
                            Some(output_clock_id)
                        }
                    }
                } else {
                    // Sequential arc.
                    // TODO
                    debug_assert!(
                        !output_clock_id.is_clock(),
                        "clock-flag should be cleared already"
                    );
                    Some(output_clock_id)
                }
            } else {
                // Not a clock signal.
                // The logic function of the cell has no impact on the clock ID.
                Some(input_clock_id)
            }
        });

        // Annotate the output signal with the derived clock ID.
        output_signals_without_clock.map(|s| SignalWithClock { inner: s, clock_id })
    }

    fn delay_arcs(
        &self,
        netlist: &N,
        cell_id: &N::CellId,
    ) -> impl Iterator<Item = CellDelayArc<N::PinId>> + '_ {
        self.inner.delay_arcs(netlist, cell_id)
    }
}

impl<M, N> CellConstraintModel<N> for ClockAwareModel<M>
where
    N: db::NetlistBase,
    M: CellConstraintModel<N>,
{
    fn get_required_input(
        &self,
        netlist: &N,
        arc: &CellConstraintArc<N::PinId>,
        constrained_pin_signal: &Self::Signal,
        related_pin_signal: &Self::Signal,
        other_inputs: &impl Fn(&<N>::PinId) -> Option<Self::Signal>,
        output_loads: &impl Fn(&<N>::PinId) -> Option<Self::Load>,
    ) -> Option<Self::RequiredSignal> {
        // Find clock ID associated with the required signal.
        let clock_id = related_pin_signal.clock_id().map(|mut clock_id| {
            // TODO: Set flags of clock ID.
            // Requires knowledge of the constraint type.
            // Most likely clear the "clock" flag.
            clock_id.set_clock(false);
            // Set default values:
            clock_id.set_edge_sensitivity(RiseFall::Rise, false);
            clock_id.set_edge_sensitivity(RiseFall::Fall, false);

            use SignalTransitionType::*;
            match related_pin_signal.transition_type() {
                Rise => clock_id.set_edge_sensitivity(RiseFall::Rise, true),
                Fall => clock_id.set_edge_sensitivity(RiseFall::Fall, true),
                Any => {
                    panic!("propagated signals should have a defined edge polarity");
                }
                Constant(_) => {
                    // Not sensitive to any clock edge because the related signal is constant.
                }
            };
            clock_id
        });

        let clock_period: Option<_> = clock_id.map(|c| self.clock_period(c));

        // Get the required signal from the underlying model.
        let required_signal_without_clock = self.inner.get_required_input(
            netlist,
            arc,
            &constrained_pin_signal.inner,
            &related_pin_signal.inner,
            &|pin_id| other_inputs(pin_id).map(|signal| signal.inner),
            output_loads,
        );

        // Add clock period to arrival time for setup constraints.
        let required_signal_without_clock = if let Some(t_clock) = clock_period {
            required_signal_without_clock.map(|r| self.inner.add_clock_period(r, t_clock))
        } else {
            required_signal_without_clock
        };

        // Annotate the signal with a clock ID.
        required_signal_without_clock.map(|signal| SignalWithClock {
            inner: signal,
            clock_id,
        })
    }

    fn constraint_arcs(
        &self,
        netlist: &N,
        cell_id: &<N>::CellId,
    ) -> impl Iterator<Item = CellConstraintArc<N::PinId>> + '_ {
        self.inner.constraint_arcs(netlist, cell_id)
    }
}

/// Wrapper around interconnect delay models.
///
/// Used to keep the link between signals and their clock domains.
/// The data-structure is zero-cost for the interconnect model.
/// The data-structure for the signals gets larger because of the additional clock ID.
#[derive(Debug, Clone)]
pub struct ClockAwareInterconnectModel<M> {
    /// Underlying interconnect model.
    inner: M,
}

impl<M> ClockAwareInterconnectModel<M> {
    /// Wrap an interconnect model.
    /// This is zero-cost. Best use a reference type as the inner model.
    pub fn new(inner_model: M) -> Self {
        Self { inner: inner_model }
    }
}

/// Delegate trait implementation to the inner model.
impl<M> LoadBase for ClockAwareInterconnectModel<M>
where
    M: LoadBase,
{
    type Load = M::Load;

    fn sum_loads(&self, load1: &Self::Load, load2: &Self::Load) -> Self::Load {
        self.inner.sum_loads(load1, load2)
    }
}

/// Delegate trait implementation to the inner model.
impl<M> TimingBase for ClockAwareInterconnectModel<M>
where
    M: TimingBase,
{
    type Signal = SignalWithClock<M::Signal>;

    type LogicValue = M::LogicValue;
}

/// Delegate trait implementation to the inner model.
impl<M> DelayBase for ClockAwareInterconnectModel<M>
where
    M: DelayBase,
{
    type Delay = M::Delay;
    fn summarize_delays(&self, signal1: &Self::Signal, signal2: &Self::Signal) -> Self::Signal {
        assert_eq!(
            signal1.clock_id, signal2.clock_id,
            "signals must have same clock ID" // TODO: Do they?
        );
        let signal_without_clock = self.inner.summarize_delays(&signal1.inner, &signal2.inner);

        Self::Signal {
            inner: signal_without_clock,
            clock_id: signal1.clock_id,
        }
    }

    fn get_delay(&self, from: &Self::Signal, to: &Self::Signal) -> Self::Delay {
        self.inner.get_delay(&from.inner, &to.inner)
    }
}

impl<M, N> InterconnectDelayModel<N> for ClockAwareInterconnectModel<M>
where
    N: db::NetlistBase,
    M: InterconnectDelayModel<N>,
{
    fn interconnect_output(
        &self,
        netlist: &N,
        source_terminal: &db::TerminalId<N>,
        input_signal: &Self::Signal,
        target_terminal: &db::TerminalId<N>,
        output_load: &Self::Load,
    ) -> Option<Self::Signal> {
        // Query the underlying interconnect model.
        let output_without_clock = self.inner.interconnect_output(
            netlist,
            source_terminal,
            &input_signal.inner,
            target_terminal,
            output_load,
        );

        // Propagate the clock ID.
        output_without_clock.map(|s| SignalWithClock {
            inner: s,
            clock_id: input_signal.clock_id,
        })
    }
}