summaryrefslogtreecommitdiffstats
path: root/movement/movement.c
blob: d15c349f0370c9a6f52b8858ede45649ce6059fa (plain)
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
/*
 * MIT License
 *
 * Copyright (c) 2022 Joey Castillo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include "watch.h"
#include "movement.h"
#include "movement_config.h"

#if __EMSCRIPTEN__
#include <emscripten.h>
#endif

movement_state_t movement_state;
void * watch_face_contexts[MOVEMENT_NUM_FACES];
watch_date_time scheduled_tasks[MOVEMENT_NUM_FACES];
const int32_t movement_le_inactivity_deadlines[8] = {INT_MAX, 3600, 7200, 21600, 43200, 86400, 172800, 604800};
const int16_t movement_timeout_inactivity_deadlines[4] = {60, 120, 300, 1800};
movement_event_t event;

const int16_t movement_timezone_offsets[] = {
    -720,   //  0 : -12:00:00 (Baker Island Time)
    -660,   //  1 : -11:00:00 (Niue Time)
    -600,   //  2 : -10:00:00 (Hawaii-Aleutian Standard Time)
    -570,   //  3 :  -9:30:00 (Marquesas Islands Time)
    -540,   //  4 :  -9:00:00 (Alaska Standard Time)
    -480,   //  5 :  -8:00:00 (Pacific Standard Time)
    -420,   //  6 :  -7:00:00 (Mountain Standard Time)
    -360,   //  7 :  -6:00:00 (Central Standard Time)
    -300,   //  8 :  -5:00:00 (Eastern Standard Time)
    -270,   //  9 :  -4:30:00 (Venezuelan Standard Time)
    -240,   // 10 :  -4:00:00 (Atlantic Standard Time)
    -210,   // 11 :  -3:30:00 (Newfoundland Standard Time)
    -180,   // 12 :  -3:00:00 (Brasilia Time)
    -150,   // 13 :  -2:30:00 (Newfoundland Daylight Time)
    -120,   // 14 :  -2:00:00 (Fernando de Noronha Time)
    -60,    // 15 :  -1:00:00 (Azores Standard Time)
    0,      // 16 :   0:00:00 (UTC)
    60,     // 17 :   1:00:00 (Central European Time)
    120,    // 18 :   2:00:00 (South African Standard Time)
    180,    // 19 :   3:00:00 (Arabia Standard Time)
    210,    // 20 :   3:30:00 (Iran Standard Time)
    240,    // 21 :   4:00:00 (Georgia Standard Time)
    270,    // 22 :   4:30:00 (Afghanistan Time)
    300,    // 23 :   5:00:00 (Pakistan Standard Time)
    330,    // 24 :   5:30:00 (Indian Standard Time)
    345,    // 25 :   5:45:00 (Nepal Time)
    360,    // 26 :   6:00:00 (Kyrgyzstan time)
    390,    // 27 :   6:30:00 (Myanmar Time)
    420,    // 28 :   7:00:00 (Thailand Standard Time)
    480,    // 29 :   8:00:00 (China Standard Time, Australian Western Standard Time)
    525,    // 30 :   8:45:00 (Australian Central Western Standard Time)
    540,    // 31 :   9:00:00 (Japan Standard Time, Korea Standard Time)
    570,    // 32 :   9:30:00 (Australian Central Standard Time)
    600,    // 33 :  10:00:00 (Australian Eastern Standard Time)
    630,    // 34 :  10:30:00 (Lord Howe Standard Time)
    660,    // 35 :  11:00:00 (Solomon Islands Time)
    720,    // 36 :  12:00:00 (New Zealand Standard Time)
    765,    // 37 :  12:45:00 (Chatham Standard Time)
    780,    // 38 :  13:00:00 (Tonga Time)
    825,    // 39 :  13:45:00 (Chatham Daylight Time)
    840,    // 40 :  14:00:00 (Line Islands Time)
};

const char movement_valid_position_0_chars[] = " AaBbCcDdEeFGgHhIiJKLMNnOoPQrSTtUuWXYZ-='+\\/0123456789";
const char movement_valid_position_1_chars[] = " ABCDEFHlJLNORTtUX-='01378";

void cb_mode_btn_interrupt(void);
void cb_light_btn_interrupt(void);
void cb_alarm_btn_interrupt(void);
void cb_alarm_btn_extwake(void);
void cb_alarm_fired(void);
void cb_fast_tick(void);
void cb_tick(void);

static inline void _movement_reset_inactivity_countdown(void) {
    movement_state.le_mode_ticks = movement_le_inactivity_deadlines[movement_state.settings.bit.le_interval];
    movement_state.timeout_ticks = movement_timeout_inactivity_deadlines[movement_state.settings.bit.to_interval];
}

static inline void _movement_enable_fast_tick_if_needed(void) {
    if (!movement_state.fast_tick_enabled) {
        movement_state.fast_ticks = 0;
        watch_rtc_register_periodic_callback(cb_fast_tick, 128);
    }
}

static inline void _movement_disable_fast_tick_if_possible(void) {
    if ((movement_state.light_ticks == -1) &&
        (movement_state.alarm_ticks == -1) &&
        ((movement_state.light_down_timestamp + movement_state.mode_down_timestamp + movement_state.alarm_down_timestamp) == 0)) {
        movement_state.fast_tick_enabled = false;
        watch_rtc_disable_periodic_callback(128);
    }
}

static void _movement_handle_background_tasks(void) {
    for(uint8_t i = 0; i < MOVEMENT_NUM_FACES; i++) {
        // For each face, if the watch face wants a background task...
        if (watch_faces[i].wants_background_task != NULL && watch_faces[i].wants_background_task(&movement_state.settings, watch_face_contexts[i])) {
            // ...we give it one. pretty straightforward!
            movement_event_t background_event = { EVENT_BACKGROUND_TASK, 0 };
            watch_faces[i].loop(background_event, &movement_state.settings, watch_face_contexts[i]);
        }
    }
    movement_state.needs_background_tasks_handled = false;
}

static void _movement_handle_scheduled_tasks(void) {
    watch_date_time date_time = watch_rtc_get_date_time();
    uint8_t num_active_tasks = 0;

    for(uint8_t i = 0; i < MOVEMENT_NUM_FACES; i++) {
        if (scheduled_tasks[i].reg) {
            if (scheduled_tasks[i].reg == date_time.reg) {
                scheduled_tasks[i].reg = 0;
                movement_event_t background_event = { EVENT_BACKGROUND_TASK, 0 };
                watch_faces[i].loop(background_event, &movement_state.settings, watch_face_contexts[i]);
            } else {
                num_active_tasks++;
            }
        }
    }

    if (num_active_tasks == 0) {
        movement_state.has_scheduled_background_task = false;
    } else {
        _movement_reset_inactivity_countdown();
    }
}

void movement_request_tick_frequency(uint8_t freq) {
    if (freq == 128) return; // Movement uses the 128 Hz tick internally

    // disable all callbacks except the 128 Hz one
#if __EMSCRIPTEN__
    for (int i = 1; i < 128; i = i << 1) {
        watch_rtc_disable_periodic_callback(i);
    }
#else
    RTC->MODE2.INTENCLR.reg = 0xFE;
#endif

    movement_state.subsecond = 0;
    movement_state.tick_frequency = freq;
    if (freq) watch_rtc_register_periodic_callback(cb_tick, freq);
}

void movement_illuminate_led(void) {
    if (movement_state.settings.bit.led_duration) {
        watch_set_led_color(movement_state.settings.bit.led_red_color ? (0xF | movement_state.settings.bit.led_red_color << 4) : 0,
                            movement_state.settings.bit.led_green_color ? (0xF | movement_state.settings.bit.led_green_color << 4) : 0);
        movement_state.light_ticks = (movement_state.settings.bit.led_duration * 2 - 1) * 128;
        _movement_enable_fast_tick_if_needed();
    }
}

void movement_move_to_face(uint8_t watch_face_index) {
    movement_state.watch_face_changed = true;
    movement_state.next_watch_face = watch_face_index;
}

void movement_move_to_next_face(void) {
    movement_move_to_face((movement_state.current_watch_face + 1) % MOVEMENT_NUM_FACES);
}

void movement_schedule_background_task(watch_date_time date_time) {
    watch_date_time now = watch_rtc_get_date_time();
    if (date_time.reg > now.reg) {
        movement_state.has_scheduled_background_task = true;
        scheduled_tasks[movement_state.current_watch_face].reg = date_time.reg;
    }
}

void movement_cancel_background_task(void) {
    scheduled_tasks[movement_state.current_watch_face].reg = 0;
    bool other_tasks_scheduled = false;
    for(uint8_t i = 0; i < MOVEMENT_NUM_FACES; i++) {
        if (scheduled_tasks[i].reg != 0) {
            other_tasks_scheduled = true;
            break;
        }
    }
    movement_state.has_scheduled_background_task = other_tasks_scheduled;
}

void movement_play_signal(void) {
    watch_buzzer_play_note(BUZZER_NOTE_C8, 75);
    watch_buzzer_play_note(BUZZER_NOTE_REST, 100);
    watch_buzzer_play_note(BUZZER_NOTE_C8, 100);
}

void movement_play_alarm(void) {
    movement_state.alarm_ticks = 128 * 5 - 80; // 80 ticks short of 5 seconds, or 4.375 seconds (our beep is 0.375 seconds)
    _movement_enable_fast_tick_if_needed();
}

void app_init(void) {
    memset(&movement_state, 0, sizeof(movement_state));

    movement_state.settings.bit.led_green_color = 0xF;
    movement_state.settings.bit.button_should_sound = true;
    movement_state.settings.bit.le_interval = 1;
    movement_state.settings.bit.led_duration = 1;
    movement_state.settings.bit.time_zone = 16; // default to GMT
    movement_state.light_ticks = -1;
    movement_state.alarm_ticks = -1;
    _movement_reset_inactivity_countdown();

#if __EMSCRIPTEN__
    int32_t time_zone_offset = EM_ASM_INT({
        return -new Date().getTimezoneOffset();
    });
    for (int i = 0, count = sizeof(movement_timezone_offsets) / sizeof(movement_timezone_offsets[0]); i < count; i++) {
        if (movement_timezone_offsets[i] == time_zone_offset) {
            movement_state.settings.bit.time_zone = i;
            break;
        }
    }
#endif
}

void app_wake_from_backup(void) {
    movement_state.settings.reg = watch_get_backup_data(0);
}

void app_setup(void) {
    watch_store_backup_data(movement_state.settings.reg, 0);

    static bool is_first_launch = true;

    if (is_first_launch) {
        for(uint8_t i = 0; i < MOVEMENT_NUM_FACES; i++) {
            watch_face_contexts[i] = NULL;
            scheduled_tasks[i].reg = 0;
            is_first_launch = false;
        }

        // set up the 1 minute alarm (for background tasks and low power updates)
        watch_date_time alarm_time;
        alarm_time.reg = 0;
        alarm_time.unit.second = 59; // after a match, the alarm fires at the next rising edge of CLK_RTC_CNT, so 59 seconds lets us update at :00
        watch_rtc_register_alarm_callback(cb_alarm_fired, alarm_time, ALARM_MATCH_SS);
    }
    if (movement_state.le_mode_ticks != -1) {
        watch_disable_extwake_interrupt(BTN_ALARM);

        watch_enable_external_interrupts();
        watch_register_interrupt_callback(BTN_MODE, cb_mode_btn_interrupt, INTERRUPT_TRIGGER_BOTH);
        watch_register_interrupt_callback(BTN_LIGHT, cb_light_btn_interrupt, INTERRUPT_TRIGGER_BOTH);
        watch_register_interrupt_callback(BTN_ALARM, cb_alarm_btn_interrupt, INTERRUPT_TRIGGER_BOTH);

        watch_enable_buzzer();
        watch_enable_leds();
        watch_enable_display();

        movement_request_tick_frequency(1);

        for(uint8_t i = 0; i < MOVEMENT_NUM_FACES; i++) {
            watch_faces[i].setup(&movement_state.settings, i, &watch_face_contexts[i]);
        }

        watch_faces[movement_state.current_watch_face].activate(&movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
        event.subsecond = 0;
        event.event_type = EVENT_ACTIVATE;
    }
}

void app_prepare_for_standby(void) {
}

void app_wake_from_standby(void) {
}

bool app_loop(void) {
    if (movement_state.watch_face_changed) {
        if (movement_state.settings.bit.button_should_sound) {
            // low note for nonzero case, high note for return to watch_face 0
            watch_buzzer_play_note(movement_state.next_watch_face ? BUZZER_NOTE_C7 : BUZZER_NOTE_C8, 50);
        }
        watch_faces[movement_state.current_watch_face].resign(&movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
        movement_state.current_watch_face = movement_state.next_watch_face;
        watch_clear_display();
        movement_request_tick_frequency(1);
        watch_faces[movement_state.current_watch_face].activate(&movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
        event.subsecond = 0;
        event.event_type = EVENT_ACTIVATE;
        movement_state.watch_face_changed = false;
    }

    // if the LED should be off, turn it off
    if (movement_state.light_ticks == 0) {
        // unless the user is holding down the LIGHT button, in which case, give them more time.
        if (watch_get_pin_level(BTN_LIGHT)) {
            movement_state.light_ticks = 1;
        } else {
            watch_set_led_off();
            movement_state.light_ticks = -1;
            _movement_disable_fast_tick_if_possible();
        }
    }

    // handle background tasks, if the alarm handler told us we need to
    if (movement_state.needs_background_tasks_handled) _movement_handle_background_tasks();

    // if we have a scheduled background task, handle that here:
    if (event.event_type == EVENT_TICK && movement_state.has_scheduled_background_task) _movement_handle_scheduled_tasks();

    // if we have timed out of our low energy mode countdown, enter low energy mode.
    if (movement_state.le_mode_ticks == 0) {
        movement_state.le_mode_ticks = -1;
        watch_register_extwake_callback(BTN_ALARM, cb_alarm_btn_extwake, true);
        event.event_type = EVENT_NONE;
        event.subsecond = 0;

        // this is a little mini-runloop.
        // as long as le_mode_ticks is -1 (i.e. we are in low energy mode), we wake up here, update the screen, and go right back to sleep.
        while (movement_state.le_mode_ticks == -1) {
            // we also have to handle background tasks here in the mini-runloop
            if (movement_state.needs_background_tasks_handled) _movement_handle_background_tasks();

            event.event_type = EVENT_LOW_ENERGY_UPDATE;
            watch_faces[movement_state.current_watch_face].loop(event, &movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
            watch_enter_sleep_mode();
        }
        // as soon as le_mode_ticks is reset by the extwake handler, we bail out of the loop and reactivate ourselves.
        event.event_type = EVENT_ACTIVATE;
        // this is a hack tho: waking from sleep mode, app_setup does get called, but it happens before we have reset our ticks.
        // need to figure out if there's a better heuristic for determining how we woke up.
        app_setup();
    }

    static bool can_sleep = true;

    if (event.event_type) {
        event.subsecond = movement_state.subsecond;
        can_sleep = watch_faces[movement_state.current_watch_face].loop(event, &movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
        // escape hatch: a watch face may not resign on EVENT_MODE_BUTTON_DOWN. In that case, a long press of MODE should let them out.
        if (event.event_type == EVENT_MODE_LONG_PRESS) {
            movement_move_to_next_face();
            can_sleep = false;
        }
        event.event_type = EVENT_NONE;
    }

    // if we have timed out of our timeout countdown, give the app a hint that they can resign.
    if (movement_state.timeout_ticks == 0) {
        movement_state.timeout_ticks = -1;
        if (movement_state.settings.bit.to_always == false) {
            // if "timeout always" is false, give the current watch face a chance to exit gracefully...
            event.event_type = EVENT_TIMEOUT;
        }
        event.subsecond = movement_state.subsecond;
        watch_faces[movement_state.current_watch_face].loop(event, &movement_state.settings, watch_face_contexts[movement_state.current_watch_face]);
        event.event_type = EVENT_NONE;
        if (movement_state.settings.bit.to_always && movement_state.current_watch_face != 0) {
            // ...but if the user has "timeout always" set, give it the boot.
            movement_move_to_face(0);
        }
    }

    // Now that we've handled all display update tasks, handle the alarm.
    if (movement_state.alarm_ticks >= 0) {
        uint8_t buzzer_phase = (movement_state.alarm_ticks + 80) % 128;
        if(buzzer_phase == 127) {
            for(uint8_t i = 0; i < 4; i++) {
                // TODO: This method of playing the buzzer blocks the UI while it's beeping.
                // It might be better to time it with the fast tick.
                watch_buzzer_play_note(BUZZER_NOTE_C8, (i != 3) ? 50 : 75);
                if (i != 3) watch_buzzer_play_note(BUZZER_NOTE_REST, 50);
            }
        }
        if (movement_state.alarm_ticks == 0) {
            movement_state.alarm_ticks = -1;
            _movement_disable_fast_tick_if_possible();
        }
    }

    event.subsecond = 0;

    return can_sleep && (movement_state.light_ticks == -1) && !movement_state.is_buzzing;
}

static movement_event_type_t _figure_out_button_event(bool pin_level, movement_event_type_t button_down_event_type, uint8_t *down_timestamp) {
    // force alarm off if the user pressed a button.
    if (movement_state.alarm_ticks) movement_state.alarm_ticks = 0;

    if (pin_level) {
        // handle rising edge
        _movement_enable_fast_tick_if_needed();
        *down_timestamp = movement_state.fast_ticks + 1;
        return button_down_event_type;
    } else {
        // this line is hack but it handles the situation where the light button was held for more than 10 seconds.
        // fast tick is disabled by then, and the LED would get stuck on since there's no one left decrementing light_ticks.
        if (movement_state.light_ticks == 1) movement_state.light_ticks = 0;
        // now that that's out of the way, handle falling edge
        uint16_t diff = movement_state.fast_ticks - *down_timestamp;
        *down_timestamp = 0;
        _movement_disable_fast_tick_if_possible();
        // any press over a half second is considered a long press.
        if (diff > 64) return button_down_event_type + 2;
        else return button_down_event_type + 1;
    }
}

void cb_light_btn_interrupt(void) {
    bool pin_level = watch_get_pin_level(BTN_LIGHT);
    _movement_reset_inactivity_countdown();
    event.event_type = _figure_out_button_event(pin_level, EVENT_LIGHT_BUTTON_DOWN, &movement_state.light_down_timestamp);
}

void cb_mode_btn_interrupt(void) {
    bool pin_level = watch_get_pin_level(BTN_MODE);
    _movement_reset_inactivity_countdown();
    event.event_type = _figure_out_button_event(pin_level, EVENT_MODE_BUTTON_DOWN, &movement_state.mode_down_timestamp);
}

void cb_alarm_btn_interrupt(void) {
    bool pin_level = watch_get_pin_level(BTN_ALARM);
    _movement_reset_inactivity_countdown();
    event.event_type = _figure_out_button_event(pin_level, EVENT_ALARM_BUTTON_DOWN, &movement_state.alarm_down_timestamp);
}

void cb_alarm_btn_extwake(void) {
    // wake up!
    _movement_reset_inactivity_countdown();
}

void cb_alarm_fired(void) {
    movement_state.needs_background_tasks_handled = true;
}

void cb_fast_tick(void) {
    movement_state.fast_ticks++;
    if (movement_state.light_ticks > 0) movement_state.light_ticks--;
    if (movement_state.alarm_ticks > 0) movement_state.alarm_ticks--;
    // this is just a fail-safe; fast tick should be disabled as soon as the button is up, the LED times out, and/or the alarm finishes.
    // but if for whatever reason it isn't, this forces the fast tick off after 10 seconds.
    if (movement_state.fast_ticks >= 1280) watch_rtc_disable_periodic_callback(128);
}

void cb_tick(void) {
    event.event_type = EVENT_TICK;
    watch_date_time date_time = watch_rtc_get_date_time();
    if (date_time.unit.second != movement_state.last_second) {
        // TODO: can we consolidate these two ticks?
        if (movement_state.settings.bit.le_interval && movement_state.le_mode_ticks > 0) movement_state.le_mode_ticks--;
        if (movement_state.timeout_ticks > 0) movement_state.timeout_ticks--;

        movement_state.last_second = date_time.unit.second;
        movement_state.subsecond = 0;
    } else {
        movement_state.subsecond++;
    }
}
id='n2689' href='#n2689'>2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
--  Canonicalization pass
--  Copyright (C) 2002, 2003, 2004, 2005, 2008 Tristan Gingold
--
--  This program is free software: you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation, either version 2 of the License, or
--  (at your option) any later version.
--
--  This program is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License
--  along with this program.  If not, see <gnu.org/licenses>.

with Types; use Types;
with Flags; use Flags;
with Name_Table;
with Errorout; use Errorout;

with Vhdl.Errors; use Vhdl.Errors;
with Vhdl.Utils; use Vhdl.Utils;
with Vhdl.Sem;
with Vhdl.Sem_Inst;
with Vhdl.Sem_Specs;
with Vhdl.Nodes_Utils; use Vhdl.Nodes_Utils;
with PSL.Types; use PSL.Types;
with PSL.Nodes;
with PSL.Rewrites;
with PSL.Build;
with PSL.NFAs;
with PSL.NFAs.Utils;
with PSL.Errors; use PSL.Errors;
with Vhdl.Canon_PSL;

package body Vhdl.Canon is
   Canon_Flag_Set_Assoc_Formals : constant Boolean := False;

   --  Canonicalize the chain of declarations in Declaration_Chain of
   --  DECL_PARENT. PARENT must be the parent of the current statements chain,
   --  or NULL_IIR if DECL_PARENT has no corresponding current statments.
   --  TOP is used to add dependencies (from binding indications).
   procedure Canon_Declarations (Top : Iir_Design_Unit;
                                 Decl_Parent : Iir;
                                 Parent : Iir);
   function Canon_Declaration (Top : Iir_Design_Unit; Decl : Iir; Parent : Iir)
                              return Iir;

   procedure Canon_Concurrent_Stmts (Top : Iir_Design_Unit; Parent : Iir);
   procedure Canon_Simultaneous_Stmts (Top : Iir_Design_Unit; Chain : Iir);

   --  Canonicalize an association list.
   --  If ASSOCIATION_LIST is not null, then it is re-ordored and returned.
   --  If ASSOCIATION_LIST is null then:
   --    if INTERFACE_LIST is null then returns null.
   --    if INTERFACE_LIST is not null, a default list is created.
   function Canon_Association_Chain
     (Interface_Chain: Iir; Association_Chain: Iir; Loc : Iir)
     return Iir;

   --  Like Canon_Association_Chain but recurse on actuals.
   function Canon_Association_Chain_And_Actuals
     (Interface_Chain: Iir; Association_Chain: Iir; Loc : Iir)
     return Iir;

   --  Like Canon_Subprogram_Call, but recurse on actuals.
   procedure Canon_Subprogram_Call_And_Actuals (Call : Iir);

   --  Canonicalize block configuration CONF.
   --  TOP is used to added dependences to the design unit which CONF
   --  belongs to.
   procedure Canon_Block_Configuration (Top : Iir_Design_Unit;
                                        Conf : Iir_Block_Configuration);

   procedure Canon_Subtype_Indication (Def : Iir);
   procedure Canon_Subtype_Indication_If_Anonymous (Def : Iir);

   function Canon_Conditional_Signal_Assignment
     (Conc_Stmt : Iir; Proc : Iir; Parent : Iir; Clear : Boolean) return Iir;
   procedure Canon_Conditional_Signal_Assignment_Expression (Stmt : Iir);

   procedure Canon_Extract_Sensitivity_Aggregate
     (Aggr : Iir;
      Sensitivity_List : Iir_List;
      Is_Target : Boolean;
      Aggr_Type : Iir;
      Dim : Natural)
   is
      Assoc : Iir;
   begin
      Assoc := Get_Association_Choices_Chain (Aggr);
      if Get_Nbr_Elements (Get_Index_Subtype_List (Aggr_Type)) = Dim then
         while Assoc /= Null_Iir loop
            Canon_Extract_Sensitivity_Expression
              (Get_Associated_Expr (Assoc), Sensitivity_List, Is_Target);
            Assoc := Get_Chain (Assoc);
         end loop;
      else
         while Assoc /= Null_Iir loop
            Canon_Extract_Sensitivity_Aggregate
              (Get_Associated_Expr (Assoc), Sensitivity_List,
               Is_Target, Aggr_Type, Dim + 1);
            Assoc := Get_Chain (Assoc);
         end loop;
      end if;
   end Canon_Extract_Sensitivity_Aggregate;

   procedure Canon_Extract_Sensitivity_Expression
     (Expr: Iir; Sensitivity_List: Iir_List; Is_Target: Boolean := False)
   is
      El : Iir;
   begin
      if Get_Expr_Staticness (Expr) /= None then
         return;
      end if;

      case Get_Kind (Expr) is
         when Iir_Kind_Slice_Name =>
            if not Is_Target and then
              Get_Name_Staticness (Expr) >= Globally
            then
               if Is_Signal_Object (Expr) then
                  Add_Element (Sensitivity_List, Expr);
               end if;
            else
               declare
                  Suff : Iir;
               begin
                  Canon_Extract_Sensitivity_Expression
                    (Get_Prefix (Expr), Sensitivity_List, Is_Target);
                  Suff := Get_Suffix (Expr);
                  if Get_Kind (Suff)
                    not in Iir_Kinds_Scalar_Type_And_Subtype_Definition
                  then
                     Canon_Extract_Sensitivity_Expression
                       (Suff, Sensitivity_List, False);
                  end if;
               end;
            end if;

         when Iir_Kind_Selected_Element =>
            if not Is_Target and then
              Get_Name_Staticness (Expr) >= Globally
            then
               if Is_Signal_Object (Expr) then
                  Add_Element (Sensitivity_List, Expr);
               end if;
            else
               Canon_Extract_Sensitivity_Expression
                 (Get_Prefix (Expr), Sensitivity_List, Is_Target);
            end if;

         when Iir_Kind_Indexed_Name =>
            if not Is_Target
              and then Get_Name_Staticness (Expr) >= Globally
            then
               if Is_Signal_Object (Expr) then
                  Add_Element (Sensitivity_List, Expr);
               end if;
            else
               Canon_Extract_Sensitivity_Expression
                 (Get_Prefix (Expr), Sensitivity_List, Is_Target);
               declare
                  Flist : constant Iir_Flist := Get_Index_List (Expr);
                  El : Iir;
               begin
                  for I in Flist_First .. Flist_Last (Flist) loop
                     El := Get_Nth_Element (Flist, I);
                     Canon_Extract_Sensitivity_Expression
                       (El, Sensitivity_List, False);
                  end loop;
               end;
            end if;

         when Iir_Kind_Function_Call =>
            El := Get_Parameter_Association_Chain (Expr);
            while El /= Null_Iir loop
               case Get_Kind (El) is
                  when Iir_Kind_Association_Element_By_Expression =>
                     Canon_Extract_Sensitivity_Expression
                       (Get_Actual (El), Sensitivity_List, False);
                  when Iir_Kind_Association_Element_Open =>
                     null;
                  when Iir_Kind_Association_Element_By_Individual =>
                     null;
                  when others =>
                     Error_Kind ("canon_extract_sensitivity(call)", El);
               end case;
               El := Get_Chain (El);
            end loop;

         when Iir_Kind_Qualified_Expression
           | Iir_Kind_Type_Conversion
           | Iir_Kind_Allocator_By_Expression
           | Iir_Kind_Parenthesis_Expression =>
            Canon_Extract_Sensitivity_Expression
              (Get_Expression (Expr), Sensitivity_List, False);

         when Iir_Kind_Allocator_By_Subtype =>
            null;

         when Iir_Kind_Dereference
           | Iir_Kind_Implicit_Dereference =>
            Canon_Extract_Sensitivity_Expression
              (Get_Prefix (Expr), Sensitivity_List, False);

         when Iir_Kind_External_Variable_Name
           | Iir_Kind_External_Constant_Name =>
            null;

         when Iir_Kinds_Monadic_Operator =>
            Canon_Extract_Sensitivity_Expression
              (Get_Operand (Expr), Sensitivity_List, False);
         when Iir_Kinds_Dyadic_Operator =>
            Canon_Extract_Sensitivity_Expression
              (Get_Left (Expr), Sensitivity_List, False);
            Canon_Extract_Sensitivity_Expression
              (Get_Right (Expr), Sensitivity_List, False);

         when Iir_Kind_Range_Expression =>
            Canon_Extract_Sensitivity_Expression
              (Get_Left_Limit (Expr), Sensitivity_List, False);
            Canon_Extract_Sensitivity_Expression
              (Get_Right_Limit (Expr), Sensitivity_List, False);

         when Iir_Kinds_Type_Attribute =>
            null;
         when Iir_Kinds_Signal_Value_Attribute =>
            --  LRM 8.1
            --  An attribute name: [...]; otherwise, apply this rule to the
            --  prefix of the attribute name.
            Canon_Extract_Sensitivity_Expression
              (Get_Prefix (Expr), Sensitivity_List, False);

         when Iir_Kind_Interface_Signal_Declaration
           | Iir_Kind_Signal_Declaration
           | Iir_Kind_Guard_Signal_Declaration
           | Iir_Kinds_Signal_Attribute
           | Iir_Kind_Above_Attribute
           | Iir_Kind_External_Signal_Name =>
            --  LRM 8.1
            --  A simple name that denotes a signal, add the longest static
            --  prefix of the name to the sensitivity set;
            --
            --  An attribute name: if the designator denotes a signal
            --  attribute, add the longest static prefix of the name of the
            --  implicit signal denoted by the attribute name to the
            --  sensitivity set; [...]
            if not Is_Target then
               Add_Element (Sensitivity_List, Expr);
            end if;

         when Iir_Kind_Psl_Endpoint_Declaration =>
            declare
               List : constant Iir_List := Get_PSL_Clock_Sensitivity (Expr);
               It : List_Iterator;
            begin
               It := List_Iterate (List);
               while Is_Valid (It) loop
                  Add_Element (Sensitivity_List, Get_Element (It));
                  Next (It);
               end loop;
            end;

         when Iir_Kind_Object_Alias_Declaration =>
            if not Is_Target and then Is_Signal_Object (Expr) then
               Add_Element (Sensitivity_List, Expr);
            end if;

         when Iir_Kind_Constant_Declaration
           | Iir_Kind_Interface_Constant_Declaration
           | Iir_Kind_Iterator_Declaration
           | Iir_Kind_Variable_Declaration
           | Iir_Kind_Interface_Variable_Declaration
           | Iir_Kind_File_Declaration
           | Iir_Kinds_Quantity_Declaration =>
            null;

         when Iir_Kinds_Array_Attribute =>
            -- was Iir_Kind_Left_Array_Attribute
            -- ditto Right, Low, High, Length
            -- add Ascending, Range and Reverse_Range...
            null;
            --Canon_Extract_Sensitivity
            --  (Get_Prefix (Expr), Sensitivity_List, Is_Target);

         when Iir_Kind_Value_Attribute
           | Iir_Kind_Image_Attribute
           | Iir_Kinds_Scalar_Type_Attribute =>
            Canon_Extract_Sensitivity_Expression
              (Get_Parameter (Expr), Sensitivity_List, Is_Target);

         when Iir_Kind_Aggregate =>
            declare
               Aggr_Type : Iir;
            begin
               Aggr_Type := Get_Base_Type (Get_Type (Expr));
               case Get_Kind (Aggr_Type) is
                  when Iir_Kind_Array_Type_Definition =>
                     Canon_Extract_Sensitivity_Aggregate
                       (Expr, Sensitivity_List, Is_Target, Aggr_Type, 1);
                  when Iir_Kind_Record_Type_Definition =>
                     El := Get_Association_Choices_Chain (Expr);
                     while El /= Null_Iir loop
                        Canon_Extract_Sensitivity_Expression
                          (Get_Associated_Expr (El), Sensitivity_List,
                           Is_Target);
                        El := Get_Chain (El);
                     end loop;
                  when others =>
                     Error_Kind ("canon_extract_sensitivity(aggr)", Aggr_Type);
               end case;
            end;

         when Iir_Kind_Simple_Name
           | Iir_Kind_Selected_Name
           | Iir_Kind_Reference_Name =>
            Canon_Extract_Sensitivity_Expression
              (Get_Named_Entity (Expr), Sensitivity_List, Is_Target);

         when others =>
            Error_Kind ("canon_extract_sensitivity", Expr);
      end case;
   end Canon_Extract_Sensitivity_Expression;

   procedure Canon_Extract_Sensitivity_If_Not_Null
     (Expr: Iir; Sensitivity_List: Iir_List; Is_Target: Boolean := False) is
   begin
      if Expr /= Null_Iir then
         Canon_Extract_Sensitivity_Expression
           (Expr, Sensitivity_List, Is_Target);
      end if;
   end Canon_Extract_Sensitivity_If_Not_Null;

   procedure Canon_Extract_Sensitivity_Procedure_Call
     (Call : Iir; Sensitivity_List : Iir_List)
   is
      Assoc : Iir;
      Inter : Iir;
   begin
      Assoc := Get_Parameter_Association_Chain (Call);
      Inter := Get_Interface_Declaration_Chain (Get_Implementation (Call));
      while Assoc /= Null_Iir loop
         if (Get_Kind (Assoc) = Iir_Kind_Association_Element_By_Expression)
           and then (Get_Mode (Get_Association_Interface (Assoc, Inter))
                       /= Iir_Out_Mode)
         then
            Canon_Extract_Sensitivity_Expression
              (Get_Actual (Assoc), Sensitivity_List);
         end if;
         Next_Association_Interface (Assoc, Inter);
      end loop;
   end Canon_Extract_Sensitivity_Procedure_Call;

   procedure Canon_Extract_Sensitivity_Waveform (Chain : Iir; List : Iir_List)
   is
      We: Iir_Waveform_Element;
   begin
      We := Chain;
      while We /= Null_Iir loop
         Canon_Extract_Sensitivity_Expression (Get_We_Value (We), List);
         Canon_Extract_Sensitivity_If_Not_Null (Get_Time (We), List);
         We := Get_Chain (We);
      end loop;
   end Canon_Extract_Sensitivity_Waveform;

   procedure Canon_Extract_Sensitivity_Signal_Assignment_Common
     (Stmt : Iir; List : Iir_List) is
   begin
      Canon_Extract_Sensitivity_Expression (Get_Target (Stmt), List, True);
      Canon_Extract_Sensitivity_If_Not_Null
        (Get_Reject_Time_Expression (Stmt), List);
   end Canon_Extract_Sensitivity_Signal_Assignment_Common;

   procedure Canon_Extract_Sensitivity_Conditional_Signal_Assignment
     (Stmt : Iir; List : Iir_List)
   is
      Cwe : Iir;
   begin
      Canon_Extract_Sensitivity_Signal_Assignment_Common (Stmt, List);
      Cwe := Get_Conditional_Waveform_Chain (Stmt);
      while Cwe /= Null_Iir loop
         Canon_Extract_Sensitivity_If_Not_Null (Get_Condition (Cwe), List);
         Canon_Extract_Sensitivity_Waveform (Get_Waveform_Chain (Cwe), List);
         Cwe := Get_Chain (Cwe);
      end loop;
   end Canon_Extract_Sensitivity_Conditional_Signal_Assignment;

   procedure Canon_Extract_Sensitivity_Simple_Signal_Assignment
     (Stmt : Iir; List : Iir_List) is
   begin
      Canon_Extract_Sensitivity_Signal_Assignment_Common (Stmt, List);
      Canon_Extract_Sensitivity_Waveform (Get_Waveform_Chain (Stmt), List);
   end Canon_Extract_Sensitivity_Simple_Signal_Assignment;

   procedure Canon_Extract_Sensitivity_Selected_Signal_Assignment
     (Stmt : Iir; List : Iir_List)
   is
      Swf : Node;
      Wf : Node;
   begin
      Canon_Extract_Sensitivity_Signal_Assignment_Common (Stmt, List);
      Canon_Extract_Sensitivity_Expression (Get_Expression (Stmt), List);

      Swf := Get_Selected_Waveform_Chain (Stmt);
      while Swf /= Null_Node loop
         Wf := Get_Associated_Chain (Swf);
         if Wf /= Null_Iir then
            Canon_Extract_Sensitivity_Waveform (Wf, List);
         end if;
         Swf := Get_Chain (Swf);
      end loop;
   end Canon_Extract_Sensitivity_Selected_Signal_Assignment;

   procedure Canon_Extract_Sensitivity_Assertion_Statement
     (Stmt : Iir; List : Iir_List) is
   begin
      Canon_Extract_Sensitivity_Expression
        (Get_Assertion_Condition (Stmt), List);
      Canon_Extract_Sensitivity_If_Not_Null
        (Get_Severity_Expression (Stmt), List);
      Canon_Extract_Sensitivity_If_Not_Null
        (Get_Report_Expression (Stmt), List);
   end Canon_Extract_Sensitivity_Assertion_Statement;

   procedure Canon_Extract_Sensitivity_Statement
     (Stmt : Iir; List : Iir_List) is
   begin
      case Get_Kind (Stmt) is
         when Iir_Kind_Assertion_Statement =>
            --  LRM08 11.3
            --  * For each assertion, report, next, exit or return
            --    statement, apply the rule of 10.2 to each expression
            --    in the statement, and construct the union of the
            --    resulting sets.
            Canon_Extract_Sensitivity_Assertion_Statement (Stmt, List);
         when Iir_Kind_Report_Statement =>
            --  LRM08 11.3
            --  See assertion_statement case.
            Canon_Extract_Sensitivity_If_Not_Null
              (Get_Severity_Expression (Stmt), List);
            Canon_Extract_Sensitivity_Expression
              (Get_Report_Expression (Stmt), List);
         when Iir_Kind_Next_Statement
            | Iir_Kind_Exit_Statement =>
            --  LRM08 11.3
            --  See assertion_statement case.
            Canon_Extract_Sensitivity_If_Not_Null
              (Get_Condition (Stmt), List);
         when Iir_Kind_Return_Statement =>
            --  LRM08 11.3
            --  See assertion_statement case.
            Canon_Extract_Sensitivity_If_Not_Null
              (Get_Expression (Stmt), List);
         when Iir_Kind_Variable_Assignment_Statement =>
            --  LRM08 11.3
            --  * For each assignment statement, apply the rule of 10.2 to
            --    each expression occuring in the assignment, including any
            --    expressions occuring in the index names or slice names in
            --    the target, and construct the union of the resulting sets.
            Canon_Extract_Sensitivity_Expression
              (Get_Target (Stmt), List, True);
            Canon_Extract_Sensitivity_Expression
              (Get_Expression (Stmt), List, False);
         when Iir_Kind_Simple_Signal_Assignment_Statement =>
            --  LRM08 11.3
            --  See variable assignment statement case.
            Canon_Extract_Sensitivity_Simple_Signal_Assignment (Stmt, List);
         when Iir_Kind_Conditional_Signal_Assignment_Statement =>
            Canon_Extract_Sensitivity_Conditional_Signal_Assignment
              (Stmt, List);
         when Iir_Kind_If_Statement =>
            --  LRM08 11.3
            --  * For each if statement, apply the rule of 10.2 to the
            --    condition and apply this rule recursively to each
            --    sequence of statements within the if statement, and
            --    construct the union of the resuling sets.
            declare
               El1 : Iir := Stmt;
               Cond : Iir;
            begin
               loop
                  Cond := Get_Condition (El1);
                  if Cond /= Null_Iir then
                     Canon_Extract_Sensitivity_Expression (Cond, List);
                  end if;
                  Canon_Extract_Sensitivity_Sequential_Statement_Chain
                    (Get_Sequential_Statement_Chain (El1), List);
                  El1 := Get_Else_Clause (El1);
                  exit when El1 = Null_Iir;
               end loop;
            end;
         when Iir_Kind_Case_Statement =>
            --  LRM08 11.3
            --  * For each case statement, apply the rule of 10.2 to the
            --    expression and apply this rule recursively to each
            --    sequence of statements within the case statement, and
            --    construct the union of the resulting sets.
            Canon_Extract_Sensitivity_Expression (Get_Expression (Stmt), List);
            declare
               Choice : Iir;
            begin
               Choice := Get_Case_Statement_Alternative_Chain (Stmt);
               while Choice /= Null_Iir loop
                  Canon_Extract_Sensitivity_Sequential_Statement_Chain
                    (Get_Associated_Chain (Choice), List);
                  Choice := Get_Chain (Choice);
               end loop;
            end;
         when Iir_Kind_While_Loop_Statement =>
            --  LRM08 11.3
            --  * For each loop statement, apply the rule of 10.2 to each
            --    expression in the iteration scheme, if present, and apply
            --    this rule recursively to the sequence of statements within
            --    the loop statement, and construct the union of the
            --    resulting sets.
            Canon_Extract_Sensitivity_If_Not_Null
              (Get_Condition (Stmt), List);
            Canon_Extract_Sensitivity_Sequential_Statement_Chain
              (Get_Sequential_Statement_Chain (Stmt), List);
         when Iir_Kind_For_Loop_Statement =>
            --  LRM08 11.3
            --  See loop statement case.
            declare
               It : constant Iir := Get_Parameter_Specification (Stmt);
               It_Type : constant Iir := Get_Type (It);
               Rng     : constant Iir := Get_Range_Constraint (It_Type);
            begin
               if Get_Kind (Rng) = Iir_Kind_Range_Expression then
                  Canon_Extract_Sensitivity_Expression (Rng, List);
               end if;
            end;
            Canon_Extract_Sensitivity_Sequential_Statement_Chain
              (Get_Sequential_Statement_Chain (Stmt), List);
         when Iir_Kind_Null_Statement =>
            --  LRM08 11.3
            --  ?
            null;
         when Iir_Kind_Procedure_Call_Statement =>
            --  LRM08 11.3
            --  * For each procedure call statement, apply the rule of 10.2
            --    to each actual designator (other than OPEN) associated
            --    with each formal parameter of mode IN or INOUT, and
            --    construct the union of the resulting sets.
            Canon_Extract_Sensitivity_Procedure_Call
              (Get_Procedure_Call (Stmt), List);
         when others =>
            Error_Kind ("canon_extract_sensitivity_statement", Stmt);
      end case;
   end Canon_Extract_Sensitivity_Statement;

   procedure Canon_Extract_Sensitivity_Sequential_Statement_Chain
     (Chain : Iir; List : Iir_List)
   is
      Stmt : Iir;
   begin
      Stmt := Chain;
      while Stmt /= Null_Iir loop
         Canon_Extract_Sensitivity_Statement (Stmt, List);
         Stmt := Get_Chain (Stmt);
      end loop;
   end Canon_Extract_Sensitivity_Sequential_Statement_Chain;

   procedure Canon_Extract_Sensitivity_From_Callees
     (Callees_List : Iir_List; Sensitivity_List : Iir_List)
   is
      Callee : Iir;
      Orig_Callee : Iir;
      It : List_Iterator;
      Bod : Iir;
   begin
      --  LRM08 11.3
      --  Moreover, for each subprogram for which the process is a parent
      --  (see 4.3), the sensitivity list includes members of the set
      --  constructed by apply the preceding rule to the statements of the
      --  subprogram, but excluding the members that denote formal signal
      --  parameters or members of formal signal parameters of the subprogram
      --  or any of its parents.
      if Callees_List = Null_Iir_List then
         return;
      end if;
      It := List_Iterate (Callees_List);
      while Is_Valid (It) loop
         Callee := Get_Element (It);

         --  For subprograms of instantiated packages, refer to the
         --  uninstantiated subprogram.
         --  FIXME: not for macro-expanded packages
         Orig_Callee := Sem_Inst.Get_Origin (Callee);
         if Orig_Callee /= Null_Iir then
            Callee := Orig_Callee;
         end if;

         if not Get_Seen_Flag (Callee) then
            Set_Seen_Flag (Callee, True);
            case Get_All_Sensitized_State (Callee) is
               when Read_Signal =>
                  Bod := Get_Subprogram_Body (Callee);

                  --  Extract sensitivity from signals read in the body.
                  --  FIXME: what about signals read during in declarations ?
                  Canon_Extract_Sensitivity_Sequential_Statement_Chain
                    (Get_Sequential_Statement_Chain (Bod), Sensitivity_List);

                  --  Extract sensitivity from subprograms called.
                  Canon_Extract_Sensitivity_From_Callees
                    (Get_Callees_List (Bod), Sensitivity_List);

               when No_Signal =>
                  null;

               when Invalid_Signal =>
                  --  Cannot be here.  The error must have been detected.
                  raise Internal_Error;

               when Unknown =>
                  --  Must be a subprogram declared in a different design unit,
                  --  or a subprogram calling such a subprogram.
                  --  Only a package can apply to this case.
                  --  Will be checked at elaboration.
                  pragma Assert (not Flags.Flag_Elaborate);
                  null;
            end case;
         end if;
         Next (It);
      end loop;
   end Canon_Extract_Sensitivity_From_Callees;

   function Canon_Extract_Sensitivity_Process
     (Proc : Iir_Sensitized_Process_Statement) return Iir_List
   is
      Res : Iir_List;
   begin
      Res := Create_Iir_List;

      --  Signals read by statements.
      --  FIXME: justify why signals read in declarations don't care.
      Canon_Extract_Sensitivity_Sequential_Statement_Chain
        (Get_Sequential_Statement_Chain (Proc), Res);

      --  Signals read indirectly by subprograms called.
      Canon_Extract_Sensitivity_From_Callees (Get_Callees_List (Proc), Res);

      --  Reset Seen_Flag of proc and its callees.
      Set_Seen_Flag (Proc, True);
      Clear_Seen_Flag (Proc);

      return Res;
   end Canon_Extract_Sensitivity_Process;

   procedure Canon_Aggregate_Expression (Expr: Iir)
   is
      Assoc : Iir;
   begin
      Assoc := Get_Association_Choices_Chain (Expr);
      while Assoc /= Null_Iir loop
         case Get_Kind (Assoc) is
            when Iir_Kind_Choice_By_Others
              | Iir_Kind_Choice_By_None
              | Iir_Kind_Choice_By_Name =>
               null;
            when Iir_Kind_Choice_By_Expression =>
               Canon_Expression (Get_Choice_Expression (Assoc));
            when Iir_Kind_Choice_By_Range =>
               declare
                  Choice : constant Iir := Get_Choice_Range (Assoc);
               begin
                  if Get_Kind (Choice) = Iir_Kind_Range_Expression then
                     Canon_Expression (Choice);
                  end if;
               end;
            when others =>
               Error_Kind ("canon_aggregate_expression", Assoc);
         end case;
         Canon_Expression (Get_Associated_Expr (Assoc));
         Assoc := Get_Chain (Assoc);
      end loop;
   end Canon_Aggregate_Expression;

   -- canon on expressions, mainly for function calls.
   procedure Canon_Expression (Expr: Iir) is
   begin
      if Expr = Null_Iir then
         return;
      end if;
      case Get_Kind (Expr) is
         when Iir_Kind_Range_Expression =>
            Canon_Expression (Get_Left_Limit (Expr));
            Canon_Expression (Get_Right_Limit (Expr));

         when Iir_Kind_Slice_Name =>
            declare
               Suffix : Iir;
            begin
               Suffix := Strip_Denoting_Name (Get_Suffix (Expr));
               if Get_Kind (Suffix) /= Iir_Kind_Subtype_Declaration then
                  Canon_Expression (Suffix);
               end if;
               Canon_Expression (Get_Prefix (Expr));
            end;

         when Iir_Kind_Indexed_Name =>
            Canon_Expression (Get_Prefix (Expr));
            declare
               Flist : constant Iir_Flist := Get_Index_List (Expr);
               El : Iir;
            begin
               for I in Flist_First .. Flist_Last (Flist) loop
                  El := Get_Nth_Element (Flist, I);
                  Canon_Expression (El);
               end loop;
            end;

         when Iir_Kind_Selected_Element =>
            Canon_Expression (Get_Prefix (Expr));
         when Iir_Kind_Dereference
           | Iir_Kind_Implicit_Dereference =>
            Canon_Expression (Get_Prefix (Expr));

         when Iir_Kinds_Denoting_Name =>
            Canon_Expression (Get_Named_Entity (Expr));

         when Iir_Kinds_Monadic_Operator =>
            Canon_Expression (Get_Operand (Expr));
         when Iir_Kinds_Dyadic_Operator =>
            Canon_Expression (Get_Left (Expr));
            Canon_Expression (Get_Right (Expr));

         when Iir_Kind_Function_Call =>
            Canon_Subprogram_Call_And_Actuals (Expr);
            -- FIXME:
            -- should canon concatenation.

         when Iir_Kind_Parenthesis_Expression =>
            Canon_Expression (Get_Expression (Expr));
         when Iir_Kind_Type_Conversion
           | Iir_Kind_Qualified_Expression =>
            Canon_Expression (Get_Expression (Expr));
         when Iir_Kind_Aggregate =>
            Canon_Aggregate_Expression (Expr);
         when Iir_Kind_Allocator_By_Expression =>
            Canon_Expression (Get_Expression (Expr));
         when Iir_Kind_Allocator_By_Subtype =>
            declare
               Ind : constant Iir := Get_Subtype_Indication (Expr);
            begin
               if Get_Kind (Ind) = Iir_Kind_Array_Subtype_Definition then
                  Canon_Subtype_Indication (Ind);
               end if;
            end;

         when Iir_Kinds_Literal
           | Iir_Kind_Simple_Aggregate
           | Iir_Kind_Unit_Declaration =>
            null;

         when Iir_Kinds_Array_Attribute =>
            -- No need to canon parameter, since it is a locally static
            -- expression.
            declare
               Prefix : constant Iir := Get_Prefix (Expr);
            begin
               if Get_Kind (Prefix) in Iir_Kinds_Denoting_Name
                 and then (Get_Kind (Get_Named_Entity (Prefix))
                             in Iir_Kinds_Type_Declaration)
               then
                  --  No canon for types.
                  null;
               else
                  Canon_Expression (Prefix);
               end if;
            end;

         when Iir_Kinds_Type_Attribute =>
            null;
         when Iir_Kind_Stable_Attribute
           | Iir_Kind_Quiet_Attribute
           | Iir_Kind_Delayed_Attribute
           | Iir_Kind_Transaction_Attribute =>
            --  FIXME: add the default parameter ?
            Canon_Expression (Get_Prefix (Expr));
         when Iir_Kind_Event_Attribute
           | Iir_Kind_Last_Value_Attribute
           | Iir_Kind_Active_Attribute
           | Iir_Kind_Last_Event_Attribute
           | Iir_Kind_Last_Active_Attribute
           | Iir_Kind_Driving_Attribute
           | Iir_Kind_Driving_Value_Attribute =>
            Canon_Expression (Get_Prefix (Expr));

         when Iir_Kinds_Scalar_Type_Attribute
           | Iir_Kind_Image_Attribute
           | Iir_Kind_Value_Attribute =>
            Canon_Expression (Get_Parameter (Expr));

         when Iir_Kind_Simple_Name_Attribute
           | Iir_Kind_Path_Name_Attribute
           | Iir_Kind_Instance_Name_Attribute =>
            null;

         when Iir_Kind_Interface_Signal_Declaration
           | Iir_Kind_Signal_Declaration
           | Iir_Kind_Guard_Signal_Declaration
           | Iir_Kind_Constant_Declaration
           | Iir_Kind_Interface_Constant_Declaration
           | Iir_Kind_Iterator_Declaration
           | Iir_Kind_Variable_Declaration
           | Iir_Kind_Interface_Variable_Declaration
           | Iir_Kind_File_Declaration
           | Iir_Kind_Interface_File_Declaration
           | Iir_Kind_Object_Alias_Declaration
           | Iir_Kind_Psl_Endpoint_Declaration =>
            null;

         when Iir_Kind_Enumeration_Literal
           | Iir_Kind_Overflow_Literal =>
            null;

         when Iir_Kind_Element_Declaration =>
            null;

         when Iir_Kind_Attribute_Value
           | Iir_Kind_Attribute_Name =>
            null;

         when others =>
            Error_Kind ("canon_expression", Expr);
            null;
      end case;
   end Canon_Expression;

   procedure Canon_Expression_If_Valid (Expr : Iir) is
   begin
      if Is_Valid (Expr) then
         Canon_Expression (Expr);
      end if;
   end Canon_Expression_If_Valid;

   procedure Canon_PSL_Expression (Expr : PSL_Node)
   is
      use PSL.Nodes;
   begin
      case Get_Kind (Expr) is
         when N_HDL_Expr
           | N_HDL_Bool =>
            Canon_Expression (Get_HDL_Node (Expr));
         when N_True | N_EOS =>
            null;
         when N_Not_Bool =>
            Canon_PSL_Expression (Get_Boolean (Expr));
         when N_And_Bool
           | N_Or_Bool =>
            Canon_PSL_Expression (Get_Left (Expr));
            Canon_PSL_Expression (Get_Right (Expr));
         when others =>
            Error_Kind ("canon_psl_expression", Expr);
      end case;
   end Canon_PSL_Expression;

   procedure Canon_Discrete_Range (Rng : Iir) is
   begin
      case Get_Kind (Rng) is
         when Iir_Kind_Integer_Subtype_Definition
           | Iir_Kind_Enumeration_Subtype_Definition =>
            Canon_Expression (Get_Range_Constraint (Rng));
         when Iir_Kind_Enumeration_Type_Definition =>
            null;
         when others =>
            Error_Kind ("canon_discrete_range", Rng);
      end case;
   end Canon_Discrete_Range;

   --  Extract sensitivity of WAVEFORM.
   procedure Extract_Waveform_Sensitivity
     (Waveform : Iir; Sensitivity_List: Iir_List)
   is
      We : Iir_Waveform_Element;
   begin
      We := Waveform;
      while We /= Null_Iir loop
         Canon_Extract_Sensitivity_Expression
           (Get_We_Value (We), Sensitivity_List, False);
         We := Get_Chain (We);
      end loop;
   end Extract_Waveform_Sensitivity;

   --  Canon expression of WAVEFORM.
   procedure Canon_Waveform_Expression (Waveform : Iir)
   is
      We : Iir_Waveform_Element;
   begin
      if Get_Kind (Waveform) = Iir_Kind_Unaffected_Waveform then
         pragma Assert (Get_Chain (Waveform) = Null_Iir);
         return;
      end if;

      We := Waveform;
      while We /= Null_Iir loop
         Canon_Expression (Get_We_Value (We));
         if Get_Time (We) /= Null_Iir then
            Canon_Expression (Get_Time (We));
         end if;
         We := Get_Chain (We);
      end loop;
   end Canon_Waveform_Expression;

   -- Names associations by position,
   -- reorder associations by name,
   -- create omitted association,
   function Canon_Association_Chain
     (Interface_Chain : Iir; Association_Chain : Iir; Loc : Iir)
     return Iir
   is
      -- The canon list of association.
      N_Chain, Last : Iir;
      Inter : Iir;
      Assoc_El, Prev_Assoc_El, Next_Assoc_El : Iir;
      Formal : Iir;
      Assoc_Chain : Iir;

      Found : Boolean;
   begin
      if not Canon_Flag_Associations then
         return Association_Chain;
      end if;

      --  No argument, so return now.
      if Interface_Chain = Null_Iir then
         pragma Assert (Association_Chain = Null_Iir);
         return Null_Iir;
      end if;

      Chain_Init (N_Chain, Last);
      Assoc_Chain := Association_Chain;

      -- Reorder the list of association in the interface order.
      -- Add missing associations.
      Inter := Interface_Chain;
      while Inter /= Null_Iir loop
         --  Search associations with INTERFACE.
         Found := False;
         Assoc_El := Assoc_Chain;
         Prev_Assoc_El := Null_Iir;
         while Assoc_El /= Null_Iir loop
            Next_Assoc_El := Get_Chain (Assoc_El);

            Formal := Get_Formal (Assoc_El);
            if Formal  = Null_Iir then
               Formal := Inter;
               if Canon_Flag_Set_Assoc_Formals then
                  Set_Formal (Assoc_El, Inter);
               end if;
            else
               Formal := Get_Interface_Of_Formal (Formal);
            end if;

            if Formal = Inter then

               --  Remove ASSOC_EL from ASSOC_CHAIN
               if Prev_Assoc_El /= Null_Iir then
                  Set_Chain (Prev_Assoc_El, Next_Assoc_El);
               else
                  Assoc_Chain := Next_Assoc_El;
               end if;

               --  Append ASSOC_EL in N_CHAIN.
               Set_Chain (Assoc_El, Null_Iir);
               Chain_Append (N_Chain, Last, Assoc_El);

               case Iir_Kinds_Association_Element (Get_Kind (Assoc_El)) is
                  when Iir_Kind_Association_Element_Open =>
                     goto Done;
                  when Iir_Kind_Association_Element_By_Expression
                     | Iir_Kind_Association_Element_By_Name =>
                     if Get_Whole_Association_Flag (Assoc_El) then
                        goto Done;
                     end if;
                  when Iir_Kind_Association_Element_By_Individual =>
                     Found := True;
                  when Iir_Kind_Association_Element_Package
                    | Iir_Kind_Association_Element_Type
                    | Iir_Kind_Association_Element_Subprogram
                    | Iir_Kind_Association_Element_Terminal =>
                     goto Done;
               end case;
            elsif Found then
               --  No more associations.
               goto Done;
            else
               Prev_Assoc_El := Assoc_El;
            end if;
            Assoc_El := Next_Assoc_El;
         end loop;
         if Found then
            goto Done;
         end if;

         -- No association, use default expr.
         Assoc_El := Create_Iir (Iir_Kind_Association_Element_Open);
         Set_Artificial_Flag (Assoc_El, True);
         Set_Whole_Association_Flag (Assoc_El, True);
         Location_Copy (Assoc_El, Loc);

         if Canon_Flag_Set_Assoc_Formals then
            Set_Formal (Assoc_El, Inter);
         end if;

         Chain_Append (N_Chain, Last, Assoc_El);

         << Done >> null;
         Inter := Get_Chain (Inter);
      end loop;
      pragma Assert (Assoc_Chain = Null_Iir);

      return N_Chain;
   end Canon_Association_Chain;

   procedure Canon_Association_Chain_Actuals (Association_Chain : Iir)
   is
      Assoc_El : Iir;
   begin
      --  Canon actuals.
      Assoc_El := Association_Chain;
      while Assoc_El /= Null_Iir loop
         if Get_Kind (Assoc_El) = Iir_Kind_Association_Element_By_Expression
         then
            Canon_Expression (Get_Actual (Assoc_El));
         end if;
         Assoc_El := Get_Chain (Assoc_El);
      end loop;
   end Canon_Association_Chain_Actuals;

   function Canon_Association_Chain_And_Actuals
     (Interface_Chain: Iir; Association_Chain: Iir; Loc : Iir)
     return Iir
   is
      Res : Iir;
   begin
      Res := Canon_Association_Chain (Interface_Chain, Association_Chain, Loc);
      if Canon_Flag_Expressions then
         Canon_Association_Chain_Actuals (Res);
      end if;
      return Res;
   end Canon_Association_Chain_And_Actuals;

   procedure Canon_Subprogram_Call (Call : Iir)
   is
      Imp : constant Iir := Get_Implementation (Call);
      Inter_Chain : constant Iir := Get_Interface_Declaration_Chain (Imp);
      Assoc_Chain : Iir;
   begin
      Assoc_Chain := Get_Parameter_Association_Chain (Call);
      Assoc_Chain := Canon_Association_Chain (Inter_Chain, Assoc_Chain, Call);
      Set_Parameter_Association_Chain (Call, Assoc_Chain);
   end Canon_Subprogram_Call;

   procedure Canon_Subprogram_Call_And_Actuals (Call : Iir) is
   begin
      Canon_Subprogram_Call (Call);
      if Canon_Flag_Expressions then
         Canon_Association_Chain_Actuals
           (Get_Parameter_Association_Chain (Call));
      end if;
   end Canon_Subprogram_Call_And_Actuals;

   --  Create a default association list for INTERFACE_LIST.
   --  The default is a list of interfaces associated with open.
   function Canon_Default_Association_Chain (Interface_Chain : Iir)
     return Iir
   is
      Res : Iir;
      Last : Iir;
      Assoc, El : Iir;
   begin
      if not Canon_Flag_Associations then
         return Null_Iir;
      end if;

      El := Interface_Chain;
      Chain_Init (Res, Last);
      while El /= Null_Iir loop
         Assoc := Create_Iir (Iir_Kind_Association_Element_Open);
         Set_Whole_Association_Flag (Assoc, True);
         Set_Artificial_Flag (Assoc, True);
         if Canon_Flag_Set_Assoc_Formals then
            Set_Formal (Assoc, El);
         end if;
         Location_Copy (Assoc, El);
         Chain_Append (Res, Last, Assoc);
         El := Get_Chain (El);
      end loop;
      return Res;
   end Canon_Default_Association_Chain;

   function Canon_Conditional_Variable_Assignment_Statement (Stmt : Iir)
                                                            return Iir
   is
      Target : constant Iir := Get_Target (Stmt);
      Cond_Expr : Iir;
      Expr : Iir;
      Asgn : Iir;
      Res : Iir;
      El, N_El : Iir;
   begin
      Cond_Expr := Get_Conditional_Expression_Chain (Stmt);
      Res := Create_Iir (Iir_Kind_If_Statement);
      Set_Label (Res, Get_Label (Stmt));
      Set_Suspend_Flag (Res, False);
      El := Res;

      loop
         --  Fill if/elsif statement.
         Set_Parent (El, Get_Parent (Stmt));
         Location_Copy (El, Cond_Expr);
         Set_Condition (El, Get_Condition (Cond_Expr));

         --  Create simple variable assignment.
         Asgn := Create_Iir (Iir_Kind_Variable_Assignment_Statement);
         Location_Copy (Asgn, Cond_Expr);
         Set_Parent (Asgn, Res);
         Set_Target (Asgn, Target);
         Expr := Get_Expression (Cond_Expr);
         if Canon_Flag_Expressions then
            Canon_Expression (Expr);
         end if;
         Set_Expression (Asgn, Expr);

         Set_Sequential_Statement_Chain (El, Asgn);

         --  Next condition.
         Cond_Expr := Get_Chain (Cond_Expr);
         exit when Cond_Expr = Null_Iir;

         N_El := Create_Iir (Iir_Kind_Elsif);
         Set_Else_Clause (El, N_El);
         El := N_El;
      end loop;

      return Res;
   end Canon_Conditional_Variable_Assignment_Statement;

   function Canon_Conditional_Signal_Assignment_Statement (Stmt : Iir)
                                                         return Iir is
   begin
      return Canon_Conditional_Signal_Assignment
        (Stmt, Null_Iir, Get_Parent (Stmt), False);
   end Canon_Conditional_Signal_Assignment_Statement;

   --  Inner loop if any; used to canonicalize exit/next statement.
   Cur_Loop : Iir;

   function Canon_Sequential_Stmts (First : Iir) return Iir
   is
      Stmt: Iir;
      N_Stmt : Iir;
      Res, Last : Iir;
   begin
      Chain_Init (Res, Last);

      Stmt := First;
      while Stmt /= Null_Iir loop

         --  Keep the same statement by default.
         N_Stmt := Stmt;

         case Get_Kind (Stmt) is
            when Iir_Kind_If_Statement =>
               declare
                  Cond: Iir;
                  Clause: Iir;
                  Stmts : Iir;
               begin
                  Clause := Stmt;
                  while Clause /= Null_Iir loop
                     Cond := Get_Condition (Clause);
                     Canon_Expression_If_Valid (Cond);
                     Stmts := Get_Sequential_Statement_Chain (Clause);
                     Stmts := Canon_Sequential_Stmts (Stmts);
                     Set_Sequential_Statement_Chain (Clause, Stmts);
                     Clause := Get_Else_Clause (Clause);
                  end loop;
               end;

            when Iir_Kind_Simple_Signal_Assignment_Statement =>
               Canon_Expression (Get_Target (Stmt));
               Canon_Waveform_Expression (Get_Waveform_Chain (Stmt));

            when Iir_Kind_Conditional_Signal_Assignment_Statement =>
               Canon_Conditional_Signal_Assignment_Expression (Stmt);
               N_Stmt := Canon_Conditional_Signal_Assignment_Statement (Stmt);

            when Iir_Kind_Variable_Assignment_Statement =>
               Canon_Expression (Get_Target (Stmt));
               Canon_Expression (Get_Expression (Stmt));

            when Iir_Kind_Conditional_Variable_Assignment_Statement =>
               N_Stmt :=
                 Canon_Conditional_Variable_Assignment_Statement (Stmt);

            when Iir_Kind_Wait_Statement =>
               declare
                  List : Iir_List;
                  Expr : Iir;
               begin
                  Canon_Expression_If_Valid (Get_Timeout_Clause (Stmt));
                  Expr := Get_Condition_Clause (Stmt);
                  Canon_Expression_If_Valid (Expr);
                  List := Get_Sensitivity_List (Stmt);
                  if List = Null_Iir_List and then Expr /= Null_Iir then
                     List := Create_Iir_List;
                     Canon_Extract_Sensitivity_Expression (Expr, List, False);
                     Set_Sensitivity_List (Stmt, List);
                  end if;
               end;

            when Iir_Kind_Case_Statement =>
               Canon_Expression (Get_Expression (Stmt));
               declare
                  Choice: Iir;
                  Stmts : Iir;
               begin
                  Choice := Get_Case_Statement_Alternative_Chain (Stmt);
                  while Choice /= Null_Iir loop
                     -- FIXME: canon choice expr.
                     Stmts := Get_Associated_Chain (Choice);
                     Stmts := Canon_Sequential_Stmts (Stmts);
                     Set_Associated_Chain (Choice, Stmts);
                     Choice := Get_Chain (Choice);
                  end loop;
               end;

            when Iir_Kind_Assertion_Statement
              | Iir_Kind_Report_Statement =>
               if Get_Kind (Stmt) = Iir_Kind_Assertion_Statement then
                  Canon_Expression (Get_Assertion_Condition (Stmt));
               end if;
               Canon_Expression_If_Valid (Get_Report_Expression (Stmt));
               Canon_Expression_If_Valid (Get_Severity_Expression (Stmt));

            when Iir_Kind_For_Loop_Statement =>
               declare
                  Prev_Loop : constant Iir := Cur_Loop;
                  Stmts : Iir;
               begin
                  -- FIXME: decl.
                  Cur_Loop := Stmt;
                  if Canon_Flag_Expressions then
                     Canon_Discrete_Range
                       (Get_Type (Get_Parameter_Specification (Stmt)));
                  end if;
                  Stmts := Get_Sequential_Statement_Chain (Stmt);
                  Stmts := Canon_Sequential_Stmts (Stmts);
                  Set_Sequential_Statement_Chain (Stmt, Stmts);
                  Cur_Loop := Prev_Loop;
               end;

            when Iir_Kind_While_Loop_Statement =>
               declare
                  Stmts : Iir;
                  Prev_Loop : Iir;
               begin
                  Canon_Expression_If_Valid (Get_Condition (Stmt));
                  Prev_Loop := Cur_Loop;
                  Cur_Loop := Stmt;
                  Stmts := Get_Sequential_Statement_Chain (Stmt);
                  Stmts := Canon_Sequential_Stmts (Stmts);
                  Set_Sequential_Statement_Chain (Stmt, Stmts);
                  Cur_Loop := Prev_Loop;
               end;

            when Iir_Kind_Next_Statement
              | Iir_Kind_Exit_Statement =>
               declare
                  Loop_Label : Iir;
               begin
                  Canon_Expression_If_Valid (Get_Condition (Stmt));
                  Loop_Label := Get_Loop_Label (Stmt);
                  if Loop_Label = Null_Iir then
                     Set_Loop_Label (Stmt, Build_Simple_Name (Cur_Loop, Stmt));
                  end if;
               end;

            when Iir_Kind_Procedure_Call_Statement =>
               Canon_Subprogram_Call_And_Actuals (Get_Procedure_Call (Stmt));

            when Iir_Kind_Null_Statement =>
               null;

            when Iir_Kind_Return_Statement =>
               Canon_Expression (Get_Expression (Stmt));

            when others =>
               Error_Kind ("canon_sequential_stmts", Stmt);
         end case;

         Chain_Append (Res, Last, N_Stmt);

         Stmt := Get_Chain (Stmt);
      end loop;

      return Res;
   end Canon_Sequential_Stmts;

   --  Create a statement transform from concurrent_signal_assignment
   --  statement STMT (either selected or conditional).
   --  waveform transformation is not done.
   --  PROC is the process created.
   --  PARENT is the place where signal assignment must be placed.  This may
   --   be PROC, or an 'if' statement if the assignment is guarded.
   --  See LRM93 9.5
   procedure Canon_Concurrent_Signal_Assignment
     (Stmt: Iir;
      Proc: out Iir_Sensitized_Process_Statement;
      Chain : out Iir)
   is
      If_Stmt: Iir;
      Sensitivity_List : Iir_List;
   begin
      Proc := Create_Iir (Iir_Kind_Sensitized_Process_Statement);
      Location_Copy (Proc, Stmt);
      Set_Parent (Proc, Get_Parent (Stmt));
      Set_Chain (Proc, Get_Chain (Stmt));
      Sensitivity_List := Create_Iir_List;
      Set_Sensitivity_List (Proc, Sensitivity_List);
      Set_Is_Ref (Proc, True);
      Set_Process_Origin (Proc, Stmt);

      --  LRM93 9.5
      --  1. If a label appears on the concurrent signal assignment, then the
      --     same label appears on the process statement.
      Set_Label (Proc, Get_Label (Stmt));

      --  LRM93 9.5
      --  2.  The equivalent process statement is a postponed process if and
      --      only if the current signal assignment statement includes the
      --      reserved word POSTPONED.
      Set_Postponed_Flag (Proc, Get_Postponed_Flag (Proc));

      Canon_Extract_Sensitivity_Expression
        (Get_Target (Stmt), Sensitivity_List, True);

      if Get_Guard (Stmt) /= Null_Iir then
         --  LRM93 9.1
         --  If the option guarded appears in the concurrent signal assignment
         --  statement, then the concurrent signal assignment is called a
         --  guarded assignment.
         --  If the concurrent signal assignement statement is a guarded
         --  assignment and the target of the concurrent signal assignment is
         --  a guarded target, then the statement transform is as follow:
         --    if GUARD then
         --       signal_transform
         --    else
         --       disconnect_statements
         --    end if;
         --  Otherwise, if the concurrent signal assignment statement is a
         --  guarded assignement, but the target if the concurrent signal
         --  assignment is not a guarded target, the then statement transform
         --  is as follows:
         --   if GUARD then signal_transform end if;
         If_Stmt := Create_Iir (Iir_Kind_If_Statement);
         Set_Parent (If_Stmt, Proc);
         Set_Sequential_Statement_Chain (Proc, If_Stmt);
         Location_Copy (If_Stmt, Stmt);
         Canon_Extract_Sensitivity_Expression
           (Get_Guard (Stmt), Sensitivity_List, False);
         Set_Condition (If_Stmt, Get_Guard (Stmt));
         Set_Is_Ref (If_Stmt, True);
         Chain := If_Stmt;

         declare
            Target : Iir;
            Else_Clause : Iir_Elsif;
            Dis_Stmt : Iir_Signal_Assignment_Statement;
         begin
            Target := Get_Target (Stmt);
            if Get_Guarded_Target_State (Stmt) = True then
               --  The target is a guarded target.
               --  create the disconnection statement.
               Else_Clause := Create_Iir (Iir_Kind_Elsif);
               Location_Copy (Else_Clause, Stmt);
               Set_Else_Clause (If_Stmt, Else_Clause);
               Dis_Stmt :=
                 Create_Iir (Iir_Kind_Simple_Signal_Assignment_Statement);
               Location_Copy (Dis_Stmt, Stmt);
               Set_Parent (Dis_Stmt, If_Stmt);
               Set_Target (Dis_Stmt, Target);
               Set_Is_Ref (Dis_Stmt, True);
               Set_Sequential_Statement_Chain (Else_Clause, Dis_Stmt);
               --  XX
               Set_Waveform_Chain (Dis_Stmt, Null_Iir);
            end if;
         end;
      else
         --  LRM93 9.1
         --  Finally, if the concurrent signal assignment statement is not a
         --  guarded assignment, and the traget of the concurrent signal
         --  assignment is not a guarded target, then the statement transform
         --  is as follows:
         --     signal_transform
         Chain := Proc;
      end if;
   end Canon_Concurrent_Signal_Assignment;

   function Canon_Concurrent_Procedure_Call (Conc_Stmt : Iir)
     return Iir_Sensitized_Process_Statement
   is
      Call : constant Iir_Procedure_Call := Get_Procedure_Call (Conc_Stmt);
      Imp : constant Iir := Get_Implementation (Call);
      Proc : Iir_Sensitized_Process_Statement;
      Call_Stmt : Iir_Procedure_Call_Statement;
      Wait_Stmt : Iir_Wait_Statement;
      Sensitivity_List : Iir_List;
      Is_Sensitized : Boolean;
   begin
      --  Optimization: the process is a sensitized process only if the
      --  procedure is known not to have wait statement.  This is possible only
      --  when generating code at once for the whole design, otherwise this
      --  may create discrepencies in translate structures due to states.
      Is_Sensitized :=
        (Get_Wait_State (Imp) = False) and Flags.Flag_Whole_Analyze;

      --  LRM93 9.3
      --  The equivalent process statement has also no sensitivity list, an
      --  empty declarative part, and a statement part that consists of a
      --  procedure call statement followed by a wait statement.
      if Is_Sensitized then
         Proc := Create_Iir (Iir_Kind_Sensitized_Process_Statement);
      else
         Proc := Create_Iir (Iir_Kind_Process_Statement);
      end if;
      Location_Copy (Proc, Conc_Stmt);
      Set_Parent (Proc, Get_Parent (Conc_Stmt));
      Set_Chain (Proc, Get_Chain (Conc_Stmt));
      Set_Process_Origin (Proc, Conc_Stmt);
      Set_Procedure_Call (Conc_Stmt, Null_Iir);

      --  LRM93 9.3
      --  The equivalent process statement has a label if and only if the
      --  concurrent procedure call statement has a label; if the equivalent
      --  process statement has a label, it is the same as that of the
      --  concurrent procedure call statement.
      Set_Label (Proc, Get_Label (Conc_Stmt));

      --  LRM93 9.3
      --  The equivalent process statement is a postponed process if and only
      --  if the concurrent procedure call statement includes the reserved
      --  word POSTPONED.
      Set_Postponed_Flag (Proc, Get_Postponed_Flag (Conc_Stmt));

      Call_Stmt := Create_Iir (Iir_Kind_Procedure_Call_Statement);
      Set_Sequential_Statement_Chain (Proc, Call_Stmt);
      Location_Copy (Call_Stmt, Conc_Stmt);
      Set_Parent (Call_Stmt, Proc);
      Set_Procedure_Call (Call_Stmt, Call);

      --  LRM93 9.3
      --  If there exists a name that denotes a signal in the actual part of
      --  any association element in the concurrent procedure call statement,
      --  and that actual is associated with a formal parameter of mode IN or
      --  INOUT, then the equivalent process statement includes a final wait
      --  statement with a sensitivity clause that is constructed by taking
      --  the union of the sets constructed by applying th rule of Section 8.1
      --  to each actual part associated with a formal parameter.
      Sensitivity_List := Create_Iir_List;
      Canon_Extract_Sensitivity_Procedure_Call (Call, Sensitivity_List);
      if Is_Sensitized then
         Set_Sensitivity_List (Proc, Sensitivity_List);
         Set_Is_Ref (Proc, True);
      else
         Wait_Stmt := Create_Iir (Iir_Kind_Wait_Statement);
         Location_Copy (Wait_Stmt, Conc_Stmt);
         Set_Parent (Wait_Stmt, Proc);
         Set_Sensitivity_List (Wait_Stmt, Sensitivity_List);
         Set_Is_Ref (Wait_Stmt, True);
         Set_Chain (Call_Stmt, Wait_Stmt);
      end if;
      return Proc;
   end Canon_Concurrent_Procedure_Call;

   --  Return a statement from a waveform.
   function Canon_Wave_Transform (Orig_Stmt : Iir;
                                  Waveform_Chain : Iir_Waveform_Element;
                                  Proc : Iir;
                                  Is_First : Boolean)
                                 return Iir
   is
      Stmt : Iir;
      Sensitivity_List : Iir_List;
   begin
      if Get_Kind (Waveform_Chain) = Iir_Kind_Unaffected_Waveform then
         --  LRM 9.5.1 Conditionnal Signal Assignment
         --  If the waveform is of the form:
         --    UNAFFECTED
         --  then the wave transform in the corresponding process statement
         --  is of the form:
         --    NULL;
         --  In this example, the final NULL causes the driver to be unchanged,
         --  rather than disconnected.
         --  (This is the null statement not a null waveform element).
         Stmt := Create_Iir (Iir_Kind_Null_Statement);
      else
         --  LRM 9.5.1 Conditionnal Signal Assignment
         --  If the waveform is of the form:
         --    waveform_element1, waveform_element1, ..., waveform_elementN
         --  then the wave transform in the corresponding process statement is
         --  of the form:
         --    target <= [ delay_mechanism ] waveform_element1,
         --       waveform_element2, ..., waveform_elementN;
         Stmt := Create_Iir (Iir_Kind_Simple_Signal_Assignment_Statement);
         Set_Target (Stmt, Get_Target (Orig_Stmt));
         if not Is_First then
            Set_Is_Ref (Stmt, True);
         end if;
         if Proc /= Null_Iir then
            Sensitivity_List := Get_Sensitivity_List (Proc);
            Extract_Waveform_Sensitivity (Waveform_Chain, Sensitivity_List);
         end if;
         Set_Waveform_Chain (Stmt, Waveform_Chain);
         Set_Delay_Mechanism (Stmt, Get_Delay_Mechanism (Orig_Stmt));
         Set_Reject_Time_Expression
           (Stmt, Get_Reject_Time_Expression (Orig_Stmt));
         Set_Reject_Time_Expression (Orig_Stmt, Null_Iir);
      end if;
      Location_Copy (Stmt, Orig_Stmt);
      return Stmt;
   end Canon_Wave_Transform;

   --  Create signal_transform for a concurrent simple signal assignment.
   procedure Canon_Concurrent_Simple_Signal_Assignment
     (Conc_Stmt : Iir; Proc : Iir; Parent : Iir)
   is
      Stmt : Iir;
   begin
      Stmt := Canon_Wave_Transform
        (Conc_Stmt, Get_Waveform_Chain (Conc_Stmt), Proc, True);
      Set_Waveform_Chain (Conc_Stmt, Null_Iir);
      Set_Target (Conc_Stmt, Null_Iir);
      Set_Parent (Stmt, Parent);
      Set_Sequential_Statement_Chain (Parent, Stmt);
   end Canon_Concurrent_Simple_Signal_Assignment;

   procedure Canon_Conditional_Signal_Assignment_Expression (Stmt : Iir)
   is
      Cond_Wf : Iir_Conditional_Waveform;
   begin
      Cond_Wf := Get_Conditional_Waveform_Chain (Stmt);
      while Cond_Wf /= Null_Iir loop
         Canon_Expression_If_Valid (Get_Condition (Cond_Wf));
         Canon_Waveform_Expression (Get_Waveform_Chain (Cond_Wf));

         Cond_Wf := Get_Chain (Cond_Wf);
      end loop;
   end Canon_Conditional_Signal_Assignment_Expression;

   --  Create signal_transform for a concurrent conditional signal assignment.
   function Canon_Conditional_Signal_Assignment
     (Conc_Stmt : Iir; Proc : Iir; Parent : Iir; Clear : Boolean) return Iir
   is
      Expr : Iir;
      Stmt : Iir;
      Res1 : Iir;
      Last_Res : Iir;
      Wf : Iir;
      Cond_Wf : Iir_Conditional_Waveform;
      Cond_Wf_Chain : Iir_Conditional_Waveform;
   begin
      Cond_Wf_Chain := Get_Conditional_Waveform_Chain (Conc_Stmt);
      Stmt := Null_Iir;
      Cond_Wf := Cond_Wf_Chain;
      Last_Res := Null_Iir;

      while Cond_Wf /= Null_Iir loop
         Expr := Get_Condition (Cond_Wf);

         --  Canon waveform.
         Wf := Get_Waveform_Chain (Cond_Wf);
         Wf := Canon_Wave_Transform
           (Conc_Stmt, Wf, Proc, False); -- Cond_Wf = Cond_Wf_Chain);

         if Expr = Null_Iir and Cond_Wf = Cond_Wf_Chain then
            --  A conditional assignment that is in fact a simple one.  Usual
            --  case for concurrent signal assignment in vhdl 93.
            pragma Assert (Get_Chain (Cond_Wf) = Null_Iir);

            Set_Parent (Wf, Parent);
            Res1 := Wf;
            Stmt := Res1;
         else
            --  A real conditional signal assignment.

            --  Canon condition (if any).
            if Expr /= Null_Iir then
               if Proc /= Null_Iir then
                  Canon_Extract_Sensitivity_Expression
                    (Expr, Get_Sensitivity_List (Proc), False);
               end if;
            end if;
            if Stmt = Null_Iir then
               Res1 := Create_Iir (Iir_Kind_If_Statement);
               Set_Parent (Res1, Parent);
               Stmt := Res1;
            else
               Res1 := Create_Iir (Iir_Kind_Elsif);
               Set_Else_Clause (Last_Res, Res1);
            end if;
            Location_Copy (Res1, Cond_Wf);
            Set_Condition (Res1, Expr);
            Set_Sequential_Statement_Chain (Res1, Wf);
            Set_Parent (Wf, Stmt);
            Last_Res := Res1;
         end if;

         if Clear then
            Set_Condition (Cond_Wf, Null_Iir);
            Set_Waveform_Chain (Cond_Wf, Null_Iir);
         end if;

         Cond_Wf := Get_Chain (Cond_Wf);
      end loop;

      return Stmt;
   end Canon_Conditional_Signal_Assignment;

   --  Create signal_transform for a concurrent conditional signal assignment.
   procedure Canon_Concurrent_Conditional_Signal_Assignment
     (Conc_Stmt : Iir; Proc : Iir; Parent : Iir)
   is
      Stmt : Iir;
   begin
      Stmt := Canon_Conditional_Signal_Assignment
        (Conc_Stmt, Proc, Parent, True);
      Set_Sequential_Statement_Chain (Parent, Stmt);
   end Canon_Concurrent_Conditional_Signal_Assignment;

   procedure Canon_Selected_Signal_Assignment_Expression (Stmt : Iir)
   is
      Selected_Waveform : Iir;
      Waveform : Iir;
   begin
      Canon_Expression (Get_Expression (Stmt));

      Selected_Waveform := Get_Selected_Waveform_Chain (Stmt);
      while Selected_Waveform /= Null_Iir loop
         Waveform := Get_Associated_Chain (Selected_Waveform);
         if Waveform /= Null_Iir then
            Canon_Waveform_Expression (Waveform);
         end if;
         Selected_Waveform := Get_Chain (Selected_Waveform);
      end loop;
   end Canon_Selected_Signal_Assignment_Expression;

   procedure Canon_Concurrent_Selected_Signal_Assignment
     (Conc_Stmt : Iir; Proc : Iir; Parent : Iir)
   is
      Sensitivity_List : constant Iir_List := Get_Sensitivity_List (Proc);
      Expr : constant Iir := Get_Expression (Conc_Stmt);
      Selected_Waveform_Chain : constant Iir :=
        Get_Selected_Waveform_Chain (Conc_Stmt);
      Target : constant Iir := Get_Target (Conc_Stmt);
      Reject_Time : constant Iir := Get_Reject_Time_Expression (Conc_Stmt);
      Selected_Waveform : Iir;
      Case_Stmt: Iir_Case_Statement;
      Stmt : Iir;
      Waveform : Iir;
   begin
      Canon_Extract_Sensitivity_Expression (Expr, Sensitivity_List, False);

      if Vhdl_Std < Vhdl_08 then
         Case_Stmt := Create_Iir (Iir_Kind_Case_Statement);
         Set_Parent (Case_Stmt, Parent);
         Set_Sequential_Statement_Chain (Parent, Case_Stmt);
         Location_Copy (Case_Stmt, Conc_Stmt);

         Set_Expression (Case_Stmt, Expr);

         Set_Case_Statement_Alternative_Chain
           (Case_Stmt, Selected_Waveform_Chain);

         Selected_Waveform := Selected_Waveform_Chain;
         while Selected_Waveform /= Null_Iir loop
            Set_Parent (Selected_Waveform, Case_Stmt);
            Waveform := Get_Associated_Chain (Selected_Waveform);
            if Waveform /= Null_Iir then
               Stmt := Canon_Wave_Transform
                 (Conc_Stmt, Waveform, Proc,
                  Selected_Waveform = Selected_Waveform_Chain);
               Set_Parent (Stmt, Case_Stmt);
               Set_Associated_Chain (Selected_Waveform, Stmt);
            end if;
            Selected_Waveform := Get_Chain (Selected_Waveform);
         end loop;
      else
         Stmt := Create_Iir (Iir_Kind_Selected_Waveform_Assignment_Statement);
         Set_Parent (Stmt, Parent);
         Set_Sequential_Statement_Chain (Parent, Stmt);
         Location_Copy (Stmt, Conc_Stmt);

         Set_Expression (Stmt, Expr);

         Set_Target (Stmt, Target);
         Set_Delay_Mechanism (Stmt, Get_Delay_Mechanism (Conc_Stmt));
         Set_Reject_Time_Expression (Stmt, Reject_Time);

         Set_Selected_Waveform_Chain (Stmt, Selected_Waveform_Chain);
         Set_Selected_Waveform_Chain (Conc_Stmt, Null_Iir);
         Selected_Waveform := Selected_Waveform_Chain;
         while Selected_Waveform /= Null_Iir loop
            Waveform := Get_Associated_Chain (Selected_Waveform);
            Set_Parent (Selected_Waveform, Stmt);
            if Waveform /= Null_Iir then
               Extract_Waveform_Sensitivity (Waveform, Sensitivity_List);
            end if;
            Selected_Waveform := Get_Chain (Selected_Waveform);
         end loop;
      end if;

      --  Transfer ownership.
      Set_Expression (Conc_Stmt, Null_Iir);
      Set_Target (Conc_Stmt, Null_Iir);
      Set_Selected_Waveform_Chain (Conc_Stmt, Null_Iir);
      Set_Reject_Time_Expression (Conc_Stmt, Null_Iir);
   end Canon_Concurrent_Selected_Signal_Assignment;

   procedure Canon_Generate_Statement_Body
     (Top : Iir_Design_Unit; Bod : Iir) is
   begin
      Canon_Declarations (Top, Bod, Bod);
      Canon_Concurrent_Stmts (Top, Bod);
   end Canon_Generate_Statement_Body;

   --  Return TRUE iff NFA has an edge with an EOS.
   --  If so, we need to create a finalizer.
   function Psl_Need_Finalizer (Nfa : PSL_NFA) return Boolean
   is
      use PSL.NFAs;
      S : NFA_State;
      E : NFA_Edge;
   begin
      S := Get_Final_State (Nfa);
      E := Get_First_Dest_Edge (S);
      while E /= No_Edge loop
         if PSL.NFAs.Utils.Has_EOS (Get_Edge_Expr (E)) then
            return True;
         end if;
         E := Get_Next_Dest_Edge (E);
      end loop;
      return False;
   end Psl_Need_Finalizer;

   --  Size the NFA and extract clock sensitivity.
   procedure Canon_Psl_Clocked_NFA (Stmt : Iir)
   is
      Fa : constant PSL_NFA := Get_PSL_NFA (Stmt);
      Num : Natural;
      List : Iir_List;
   begin
      PSL.NFAs.Labelize_States (Fa, Num);
      Set_PSL_Nbr_States (Stmt, Int32 (Num));

      Set_PSL_EOS_Flag (Stmt, Psl_Need_Finalizer (Fa));

      List := Create_Iir_List;
      Canon_PSL.Canon_Extract_Sensitivity (Get_PSL_Clock (Stmt), List);
      Set_PSL_Clock_Sensitivity (Stmt, List);
   end Canon_Psl_Clocked_NFA;

   procedure Canon_Psl_Property_Directive (Stmt : Iir)
   is
      use PSL.Nodes;
      use PSL.NFAs;
      Prop : PSL_Node;
      Fa : PSL_NFA;
      Final : NFA_State;
   begin
      --  Rewrite (simplify) the property.
      Prop := Get_Psl_Property (Stmt);
      Prop := PSL.Rewrites.Rewrite_Property (Prop);
      Set_Psl_Property (Stmt, Prop);

      --  Generate the NFA.
      case Get_Kind (Prop) is
         when N_Async_Abort
            | N_Sync_Abort
            | N_Abort =>
            Prop := Get_Property (Prop);
            Set_PSL_Abort_Flag (Stmt, True);
         when others =>
            null;
      end case;
      Fa := PSL.Build.Build_FA (Prop);
      Set_PSL_NFA (Stmt, Fa);

      Final := Get_Final_State (Fa);
      if Get_First_Dest_Edge (Final) = No_Edge then
         Warning_Msg_Sem (Warnid_Useless, +Stmt, "property cannot fail");
      end if;

      Canon_Psl_Clocked_NFA (Stmt);
      if Canon_Flag_Expressions then
         Canon_PSL_Expression (Get_PSL_Clock (Stmt));
      end if;
   end Canon_Psl_Property_Directive;

   procedure Canon_Psl_Sequence_Directive (Stmt : Iir)
   is
      Seq : PSL_Node;
      Fa : PSL_NFA;
   begin
      Seq := Get_Psl_Sequence (Stmt);
      Seq := PSL.Rewrites.Rewrite_SERE (Seq);
      Set_Psl_Sequence (Stmt, Seq);

      --  Generate the NFA.
      Fa := PSL.Build.Build_SERE_FA (Seq);

      --  IEEE1850-2005 PSL 7.1.6
      --  cover {r} is semantically equivalent to cover {[*]; r}.  That is,
      --  there is an implicit [*] starting the sequence.
      if Get_Kind (Stmt) = Iir_Kind_Psl_Cover_Directive then
         PSL.NFAs.Utils.Set_Init_Loop (Fa);
      end if;
      Set_PSL_NFA (Stmt, Fa);

      Canon_Psl_Clocked_NFA (Stmt);
      if Canon_Flag_Expressions then
         Canon_PSL_Expression (Get_PSL_Clock (Stmt));
      end if;
   end Canon_Psl_Sequence_Directive;

   procedure Canon_Psl_Assert_Directive (Stmt : Iir) is
   begin
      Canon_Psl_Property_Directive (Stmt);
      if Canon_Flag_Expressions then
         Canon_Expression (Get_Report_Expression (Stmt));
      end if;
   end Canon_Psl_Assert_Directive;

   procedure Canon_Psl_Cover_Directive (Stmt : Iir) is
   begin
      Canon_Psl_Sequence_Directive (Stmt);
      if Canon_Flag_Expressions then
         Canon_Expression (Get_Report_Expression (Stmt));
      end if;
   end Canon_Psl_Cover_Directive;

   procedure Canon_If_Case_Generate_Statement_Body
     (Bod : Iir; Alt_Num : in out Natural; Top : Iir_Design_Unit) is
   begin
      if Canon_Flag_Add_Labels
        and then Get_Alternative_Label (Bod) = Null_Identifier
      then
         declare
            Str : String := Natural'Image (Alt_Num);
         begin
            --  Note: the label starts with a capitalized
            --  letter, to avoid any clash with user's
            --  identifiers.
            Str (1) := 'B';
            Set_Alternative_Label (Bod, Name_Table.Get_Identifier (Str));
         end;
      end if;

      Canon_Generate_Statement_Body (Top, Bod);
      Alt_Num := Alt_Num + 1;
   end Canon_If_Case_Generate_Statement_Body;

   function Canon_Concurrent_Assertion_Statement (Stmt : Iir) return Iir
   is
      Proc : Iir;
      Asrt : Iir;
      Expr : Iir;
      Sensitivity_List : Iir_List;
   begin
      -- Create a new entry.
      Proc := Create_Iir (Iir_Kind_Sensitized_Process_Statement);
      Location_Copy (Proc, Stmt);
      Set_Parent (Proc, Get_Parent (Stmt));
      Set_Chain (Proc, Get_Chain (Stmt));
      Set_Process_Origin (Proc, Stmt);

      --  LRM93 9.4
      --  The equivalent process statement has a label if and only if the
      --  current assertion statement has a label; if the equivalent process
      --  statement has a label; it is the same as that of the concurrent
      --  assertion statement.
      Set_Label (Proc, Get_Label (Stmt));

      --  LRM93 9.4
      --  The equivalent process statement is a postponed process if and only
      --  if the current assertion statement includes the reserved word
      --  POSTPONED.
      Set_Postponed_Flag (Proc, Get_Postponed_Flag (Stmt));

      Asrt := Create_Iir (Iir_Kind_Assertion_Statement);
      Set_Sequential_Statement_Chain (Proc, Asrt);
      Set_Parent (Asrt, Proc);
      Location_Copy (Asrt, Stmt);
      Sensitivity_List := Create_Iir_List;
      Set_Sensitivity_List (Proc, Sensitivity_List);
      Set_Is_Ref (Proc, True);

      -- Expand the expression, fill the sensitivity list,
      Expr := Get_Assertion_Condition (Stmt);
      Canon_Extract_Sensitivity_Expression (Expr, Sensitivity_List, False);
      Set_Assertion_Condition (Asrt, Expr);
      Set_Assertion_Condition (Stmt, Null_Iir);

      Expr := Get_Report_Expression (Stmt);
      Set_Report_Expression (Asrt, Expr);
      Set_Report_Expression (Stmt, Null_Iir);

      Expr := Get_Severity_Expression (Stmt);
      Set_Severity_Expression (Asrt, Expr);
      Set_Severity_Expression (Stmt, Null_Iir);

      return Proc;
   end Canon_Concurrent_Assertion_Statement;

   function Canon_Concurrent_Break_Statement (Stmt : Iir) return Iir
   is
      Proc : Iir;
      Brk : Iir;
      Sensitivity_List : Iir_List;
      Cond : Iir;
   begin
      -- Create a new entry.
      Proc := Create_Iir (Iir_Kind_Sensitized_Process_Statement);
      Location_Copy (Proc, Stmt);
      Set_Parent (Proc, Get_Parent (Stmt));
      Set_Chain (Proc, Get_Chain (Stmt));
      Set_Process_Origin (Proc, Stmt);

      --  AMS-LRM17 11.9 Concurrent break statement
      --  The equivalent process statement has a label if and only if the
      --  concurrent break statement has a label; if the equivalent process
      --  statement has a label, it is the same as that of the concurrent
      --  break statement.
      Set_Label (Proc, Get_Label (Stmt));

      --  AMS-LRM17 11.9 Concurrent break statement
      --  The equivalent process statement does not include the reserved word
      --  postponed, [...]
      Set_Postponed_Flag (Proc, False);

      Brk := Create_Iir (Iir_Kind_Break_Statement);
      Set_Sequential_Statement_Chain (Proc, Brk);
      Set_Parent (Brk, Proc);
      Location_Copy (Brk, Stmt);

      Cond := Get_Condition (Stmt);
      Set_Break_Element (Brk, Get_Break_Element (Stmt));
      Set_Break_Element (Stmt, Null_Iir);
      Set_Condition (Brk, Cond);
      Set_Condition (Stmt, Null_Iir);

      --  AMS-LRM17 11.9 Concurrent break statement
      --  If the concurrent break statement has a sensitivity clause, then
      --  the wait statement of the equivalent process statement contains the
      --  same sensitivity clause; otherwise, if a name that denotes a signal
      --  appears in the Boolean expression that defines the condition of the
      --  break, then the wait statement includes a sensitivity clause that is
      --  constructed by applying the rule of 10.2 to that expression;
      --  otherwise the wait statement contains no sensitivity clause.  The
      --  wait statement does not contain a condition clause of a timeout
      --  clause.
      Sensitivity_List := Get_Sensitivity_List (Stmt);
      if Sensitivity_List = Null_Iir_List and then Cond /= Null_Iir then
         Sensitivity_List := Create_Iir_List;
         Canon_Extract_Sensitivity_Expression (Cond, Sensitivity_List, False);
      end if;
      Set_Sensitivity_List (Proc, Sensitivity_List);
      Set_Is_Ref (Proc, True);

      return Proc;
   end Canon_Concurrent_Break_Statement;

   procedure Canon_Concurrent_Label (Stmt : Iir; Proc_Num : in out Natural) is
   begin
      --  Add a label if required.
      if Canon_Flag_Add_Labels then
         case Get_Kind (Stmt) is
            when Iir_Kind_Psl_Declaration
              | Iir_Kind_Psl_Default_Clock
              | Iir_Kind_Psl_Endpoint_Declaration =>
               null;
            when others =>
               if Get_Label (Stmt) = Null_Identifier then
                  declare
                     Str : String := Natural'Image (Proc_Num);
                  begin
                     --  Note: the label starts with a capitalized letter,
                     --  to avoid any clash with user's identifiers.
                     Str (1) := 'P';
                     Set_Label (Stmt, Name_Table.Get_Identifier (Str));
                  end;
                  Proc_Num := Proc_Num + 1;
               end if;
         end case;
      end if;
   end Canon_Concurrent_Label;

   procedure Canon_Concurrent_Statement
     (Stmt : in out Iir; Top : Iir_Design_Unit)
   is
      Sub_Chain : Iir;
      Proc : Iir;
   begin
      case Get_Kind (Stmt) is
         when Iir_Kind_Concurrent_Simple_Signal_Assignment =>
            if Canon_Flag_Expressions then
               Canon_Expression (Get_Target (Stmt));
               Canon_Waveform_Expression (Get_Waveform_Chain (Stmt));
            end if;

            if Canon_Flag_Concurrent_Stmts then
               Canon_Concurrent_Signal_Assignment (Stmt, Proc, Sub_Chain);
               Canon_Concurrent_Simple_Signal_Assignment
                 (Stmt, Proc, Sub_Chain);
               Stmt := Proc;
            end if;

         when Iir_Kind_Concurrent_Conditional_Signal_Assignment =>
            if Canon_Flag_Expressions then
               Canon_Expression (Get_Target (Stmt));
               Canon_Conditional_Signal_Assignment_Expression (Stmt);
            end if;

            if Canon_Flag_Concurrent_Stmts then
               Canon_Concurrent_Signal_Assignment (Stmt, Proc, Sub_Chain);
               Canon_Concurrent_Conditional_Signal_Assignment
                 (Stmt, Proc, Sub_Chain);
               Stmt := Proc;
            end if;

         when Iir_Kind_Concurrent_Selected_Signal_Assignment =>
            if Canon_Flag_Expressions then
               Canon_Expression (Get_Target (Stmt));
               Canon_Selected_Signal_Assignment_Expression (Stmt);
            end if;

            if Canon_Flag_Concurrent_Stmts then
               Canon_Concurrent_Signal_Assignment (Stmt, Proc, Sub_Chain);
               Canon_Concurrent_Selected_Signal_Assignment
                 (Stmt, Proc, Sub_Chain);
               Stmt := Proc;
            end if;

         when Iir_Kind_Concurrent_Assertion_Statement =>
            if Canon_Flag_Expressions then
               Canon_Expression (Get_Assertion_Condition (Stmt));
               Canon_Expression_If_Valid (Get_Report_Expression (Stmt));
               Canon_Expression_If_Valid (Get_Severity_Expression (Stmt));
            end if;

            if Canon_Flag_Concurrent_Stmts then
               Stmt := Canon_Concurrent_Assertion_Statement (Stmt);
            end if;

         when Iir_Kind_Concurrent_Break_Statement =>
            if Canon_Flag_Expressions then
               Canon_Expression_If_Valid (Get_Condition (Stmt));
            end if;
            if Canon_Flag_Concurrent_Stmts then
               Stmt := Canon_Concurrent_Break_Statement (Stmt);
            end if;

         when Iir_Kind_Concurrent_Procedure_Call_Statement =>
            declare
               Call : constant Iir_Procedure_Call :=
                 Get_Procedure_Call (Stmt);
               Imp : constant Iir := Get_Implementation (Call);
               Assoc_Chain : Iir;
            begin
               Assoc_Chain := Canon_Association_Chain_And_Actuals
                 (Get_Interface_Declaration_Chain (Imp),
                  Get_Parameter_Association_Chain (Call),
                  Call);
               Set_Parameter_Association_Chain (Call, Assoc_Chain);
            end;

            if Canon_Flag_Concurrent_Stmts then
               Stmt := Canon_Concurrent_Procedure_Call (Stmt);
            end if;

         when Iir_Kind_Sensitized_Process_Statement
           | Iir_Kind_Process_Statement =>
            Canon_Declarations (Top, Stmt, Null_Iir);
            if Canon_Flag_Sequentials_Stmts then
               declare
                  Stmts : Iir;
               begin
                  Stmts := Get_Sequential_Statement_Chain (Stmt);
                  Stmts := Canon_Sequential_Stmts (Stmts);
                  Set_Sequential_Statement_Chain (Stmt, Stmts);
               end;
            end if;
            if Canon_Flag_All_Sensitivity
              and then Canon_Flag_Sequentials_Stmts
              and then Get_Kind (Stmt) = Iir_Kind_Sensitized_Process_Statement
              and then Get_Sensitivity_List (Stmt) = Iir_List_All
            then
               Set_Sensitivity_List
                 (Stmt, Canon_Extract_Sensitivity_Process (Stmt));
            end if;

         when Iir_Kind_Component_Instantiation_Statement =>
            declare
               Inst : Iir;
               Assoc_Chain : Iir;
            begin
               Inst := Get_Instantiated_Unit (Stmt);
               Inst := Get_Entity_From_Entity_Aspect (Inst);
               Assoc_Chain := Canon_Association_Chain_And_Actuals
                 (Get_Generic_Chain (Inst),
                  Get_Generic_Map_Aspect_Chain (Stmt),
                  Stmt);
               Set_Generic_Map_Aspect_Chain (Stmt, Assoc_Chain);

               Assoc_Chain := Canon_Association_Chain_And_Actuals
                 (Get_Port_Chain (Inst),
                  Get_Port_Map_Aspect_Chain (Stmt),
                  Stmt);
               Set_Port_Map_Aspect_Chain (Stmt, Assoc_Chain);
            end;

         when Iir_Kind_Block_Statement =>
            declare
               Header : constant Iir_Block_Header := Get_Block_Header (Stmt);
               Guard : constant Iir_Guard_Signal_Declaration :=
                 Get_Guard_Decl (Stmt);
               Chain : Iir;
               Expr : Iir;
            begin
               if Guard /= Null_Iir then
                  Expr := Get_Guard_Expression (Guard);
                  Set_Guard_Sensitivity_List (Guard, Create_Iir_List);
                  Canon_Extract_Sensitivity_Expression
                    (Expr, Get_Guard_Sensitivity_List (Guard), False);
                  if Canon_Flag_Expressions then
                     Canon_Expression (Stmt);
                  end if;
               end if;
               if Header /= Null_Iir then
                  --  Generics.
                  Chain := Get_Generic_Map_Aspect_Chain (Header);
                  if Chain /= Null_Iir then
                     Chain := Canon_Association_Chain_And_Actuals
                       (Get_Generic_Chain (Header), Chain, Chain);
                  else
                     Chain := Canon_Default_Association_Chain
                       (Get_Generic_Chain (Header));
                  end if;
                  Set_Generic_Map_Aspect_Chain (Header, Chain);

                  --  Ports.
                  Chain := Get_Port_Map_Aspect_Chain (Header);
                  if Chain /= Null_Iir then
                     Chain := Canon_Association_Chain_And_Actuals
                       (Get_Port_Chain (Header), Chain, Chain);
                  else
                     Chain := Canon_Default_Association_Chain
                       (Get_Port_Chain (Header));
                  end if;
                  Set_Port_Map_Aspect_Chain (Header, Chain);
               end if;
               Canon_Declarations (Top, Stmt, Stmt);
               Canon_Concurrent_Stmts (Top, Stmt);
            end;

         when Iir_Kind_If_Generate_Statement =>
            declare
               Clause : Iir;
               Alt_Num : Natural;
            begin
               Clause := Stmt;
               Alt_Num := 1;
               while Clause /= Null_Iir loop
                  if Canon_Flag_Expressions then
                     Canon_Expression_If_Valid (Get_Condition (Stmt));
                  end if;

                  Canon_If_Case_Generate_Statement_Body
                    (Get_Generate_Statement_Body (Clause), Alt_Num, Top);

                  Clause := Get_Generate_Else_Clause (Clause);
               end loop;
            end;

         when Iir_Kind_Case_Generate_Statement =>
            declare
               Alt : Iir;
               Alt_Num : Natural;
            begin
               Alt_Num := 1;
               if Canon_Flag_Expressions then
                  Canon_Expression (Get_Expression (Stmt));
               end if;
               Alt := Get_Case_Statement_Alternative_Chain (Stmt);
               while Alt /= Null_Iir loop
                  if not Get_Same_Alternative_Flag (Alt) then
                     Canon_If_Case_Generate_Statement_Body
                       (Get_Associated_Block (Alt), Alt_Num, Top);
                  end if;

                  Alt := Get_Chain (Alt);
               end loop;
            end;

         when Iir_Kind_For_Generate_Statement =>
            declare
               Decl : constant Iir := Get_Parameter_Specification (Stmt);
               New_Decl : Iir;
            begin
               New_Decl := Canon_Declaration (Top, Decl, Null_Iir);
               pragma Assert (New_Decl = Decl);

               Canon_Generate_Statement_Body
                 (Top, Get_Generate_Statement_Body (Stmt));
            end;

         when Iir_Kind_Psl_Assert_Directive =>
            Canon_Psl_Assert_Directive (Stmt);
         when Iir_Kind_Psl_Assume_Directive =>
            Canon_Psl_Property_Directive (Stmt);
         when Iir_Kind_Psl_Cover_Directive =>
            Canon_Psl_Cover_Directive (Stmt);
         when Iir_Kind_Psl_Restrict_Directive =>
            Canon_Psl_Sequence_Directive (Stmt);

         when Iir_Kind_Psl_Default_Clock =>
            null;
         when Iir_Kind_Psl_Declaration =>
            declare
               use PSL.Nodes;
               Decl : constant PSL_Node := Get_Psl_Declaration (Stmt);
               Prop : PSL_Node;
               Fa : PSL_NFA;
            begin
               case Get_Kind (Decl) is
                  when N_Property_Declaration =>
                     Prop := Get_Property (Decl);
                     Prop := PSL.Rewrites.Rewrite_Property (Prop);
                     Set_Property (Decl, Prop);
                     if Get_Parameter_List (Decl) = Null_PSL_Node then
                        --  Generate the NFA.
                        Fa := PSL.Build.Build_FA (Prop);
                        Set_PSL_NFA (Stmt, Fa);
                     end if;
                  when N_Sequence_Declaration
                    | N_Endpoint_Declaration =>
                     Prop := Get_Sequence (Decl);
                     Prop := PSL.Rewrites.Rewrite_SERE (Prop);
                     Set_Sequence (Decl, Prop);
                  when others =>
                     Error_Kind ("canon psl_declaration", Decl);
               end case;
            end;
         when Iir_Kind_Psl_Endpoint_Declaration =>
            declare
               use PSL.Nodes;
               Decl : constant PSL_Node := Get_Psl_Declaration (Stmt);
               Seq : PSL_Node;
               Fa : PSL_NFA;
            begin
               pragma Assert (Get_Parameter_List (Decl) = Null_PSL_Node);
               Seq := Get_Sequence (Decl);
               Seq := PSL.Rewrites.Rewrite_SERE (Seq);
               Set_Sequence (Decl, Seq);
               --  Generate the NFA.
               Fa := PSL.Build.Build_SERE_FA (Seq);
               Set_PSL_NFA (Stmt, Fa);
               Canon_Psl_Clocked_NFA (Stmt);
            end;

         when Iir_Kind_Simple_Simultaneous_Statement =>
            if Canon_Flag_Expressions then
               Canon_Expression (Get_Simultaneous_Left (Stmt));
               Canon_Expression (Get_Simultaneous_Right (Stmt));
            end if;
         when Iir_Kind_Simultaneous_If_Statement =>
            declare
               Clause : Iir;
            begin
               Clause := Stmt;
               while Clause /= Null_Iir loop
                  if Canon_Flag_Expressions then
                     Canon_Expression_If_Valid (Get_Condition (Clause));
                  end if;
                  Canon_Simultaneous_Stmts
                    (Top, Get_Simultaneous_Statement_Chain (Clause));
                  Clause := Get_Else_Clause (Clause);
               end loop;
            end;
         when Iir_Kind_Simultaneous_Case_Statement =>
            declare
               Alt : Iir;
            begin
               if Canon_Flag_Expressions then
                  Canon_Expression (Get_Expression (Stmt));
               end if;
               Alt := Get_Case_Statement_Alternative_Chain (Stmt);
               while Alt /= Null_Iir loop
                  if not Get_Same_Alternative_Flag (Alt) then
                     Canon_Simultaneous_Stmts
                       (Top, Get_Associated_Block (Alt));
                  end if;
                  Alt := Get_Chain (Alt);
               end loop;
            end;
         when Iir_Kind_Simultaneous_Procedural_Statement =>
            Canon_Declarations (Top, Stmt, Null_Iir);
            if Canon_Flag_Sequentials_Stmts then
               declare
                  Stmts : Iir;
               begin
                  Stmts := Get_Sequential_Statement_Chain (Stmt);
                  Stmts := Canon_Sequential_Stmts (Stmts);
                  Set_Sequential_Statement_Chain (Stmt, Stmts);
               end;
            end if;
         when Iir_Kind_Simultaneous_Null_Statement =>
            null;

         when others =>
            Error_Kind ("canon_concurrent_statement", Stmt);
      end case;
   end Canon_Concurrent_Statement;

   procedure Canon_Concurrent_Stmts (Top : Iir_Design_Unit; Parent : Iir)
   is
      --  Current element in the chain of concurrent statements.
      Stmt : Iir;
      Prev_Stmt : Iir;

      Proc_Num : Natural := 0;
   begin
      Prev_Stmt := Null_Iir;
      Stmt := Get_Concurrent_Statement_Chain (Parent);
      while Stmt /= Null_Iir loop
         Canon_Concurrent_Label (Stmt, Proc_Num);

         Canon_Concurrent_Statement (Stmt, Top);

         --  STMT may have been changed.
         if Prev_Stmt = Null_Iir then
            Set_Concurrent_Statement_Chain (Parent, Stmt);
         else
            Set_Chain (Prev_Stmt, Stmt);
         end if;
         Prev_Stmt := Stmt;
         Stmt := Get_Chain (Stmt);
      end loop;
   end Canon_Concurrent_Stmts;

   procedure Canon_Simultaneous_Stmts (Top : Iir_Design_Unit; Chain : Iir)
   is
      Stmt : Iir;
      Prev_Stmt : Iir;
      Proc_Num : Natural := 0;
   begin
      Stmt := Chain;
      while Stmt /= Null_Iir loop
         Canon_Concurrent_Label (Stmt, Proc_Num);

         Prev_Stmt := Stmt;
         Canon_Concurrent_Statement (Stmt, Top);
         pragma Assert (Stmt = Prev_Stmt);

         Stmt := Get_Chain (Stmt);
      end loop;
   end Canon_Simultaneous_Stmts;

--    procedure Canon_Binding_Indication
--      (Component: Iir; Binding : Iir_Binding_Indication)
--    is
--       List : Iir_Association_List;
--    begin
--       if Binding = Null_Iir then
--          return;
--       end if;
--       List := Get_Generic_Map_Aspect_List (Binding);
--       List := Canon_Association_List (Get_Generic_List (Component), List);
--       Set_Generic_Map_Aspect_List (Binding, List);
--       List := Get_Port_Map_Aspect_List (Binding);
--       List := Canon_Association_List (Get_Port_List (Component), List);
--       Set_Port_Map_Aspect_List (Binding, List);
--    end Canon_Binding_Indication;

   procedure Add_Binding_Indication_Dependence (Top : Iir_Design_Unit;
                                                Binding : Iir)
   is
      Aspect : Iir;
      Ent : Iir;
   begin
      if Binding = Null_Iir then
         return;
      end if;
      Aspect := Get_Entity_Aspect (Binding);
      if Aspect = Null_Iir then
         return;
      end if;
      case Get_Kind (Aspect) is
         when Iir_Kind_Entity_Aspect_Entity =>
            if Get_Architecture (Aspect) /= Null_Iir then
               Add_Dependence (Top, Aspect);
            else
               Ent := Get_Entity (Aspect);
               pragma Assert (Ent /= Null_Iir);
               if Get_Kind (Ent) = Iir_Kind_Entity_Declaration then
                  Ent := Get_Design_Unit (Ent);
               end if;
               Add_Dependence (Top, Ent);
            end if;
         when Iir_Kind_Entity_Aspect_Configuration =>
            Add_Dependence (Top, Get_Design_Unit (Get_Configuration (Aspect)));
         when Iir_Kind_Entity_Aspect_Open =>
            null;
         when others =>
            Error_Kind ("add_binding_indication_dependence", Aspect);
      end case;
   end Add_Binding_Indication_Dependence;

   --  Canon the component_configuration or configuration_specification CFG.
   --  TOP is used to add dependences.
   procedure Canon_Component_Configuration (Top : Iir_Design_Unit; Cfg : Iir)
   is
      --  True iff CFG is a component_configuration.
      --  False iff CFG is a configuration_specification.
      Is_Config : constant Boolean :=
        Get_Kind (Cfg) = Iir_Kind_Component_Configuration;

      Bind : Iir;
      Comp : Iir;
      Instances : Iir_Flist;
      Entity_Aspect : Iir;
      Block : Iir_Block_Configuration;
      Map_Chain : Iir;
      Entity : Iir;
   begin
      Bind := Get_Binding_Indication (Cfg);
      if Bind = Null_Iir then
         --  Add a default binding indication
         --  Extract a component instantiation
         Instances := Get_Instantiation_List (Cfg);
         --  Designator_all and designator_others must have been replaced
         --  by a list during canon.
         pragma Assert (Instances not in Iir_Flists_All_Others);
         Bind := Get_Default_Binding_Indication
           (Get_Named_Entity (Get_Nth_Element (Instances, 0)));
         if Bind = Null_Iir then
            --  Component is not bound.
            return;
         end if;
         Set_Binding_Indication (Cfg, Bind);
         Set_Is_Ref (Cfg, True);
         Add_Binding_Indication_Dependence (Top, Bind);
         if Is_Config then
            Entity_Aspect := Get_Entity_Aspect (Bind);
            Entity := Get_Entity_From_Entity_Aspect (Entity_Aspect);
            case Get_Kind (Entity) is
               when Iir_Kind_Entity_Declaration =>
                  Sem_Specs.Sem_Check_Missing_Generic_Association
                    (Get_Generic_Chain (Entity),
                     Get_Generic_Map_Aspect_Chain (Bind),
                     Null_Iir,
                     Cfg);
               when Iir_Kind_Foreign_Module =>
                  null;
               when others =>
                  raise Internal_Error;
            end case;
         end if;
         return;
      else
         Entity_Aspect := Get_Entity_Aspect (Bind);
         if Entity_Aspect = Null_Iir then
            Entity_Aspect := Get_Default_Entity_Aspect (Bind);
            Set_Entity_Aspect (Bind, Entity_Aspect);
         end if;
         if Entity_Aspect /= Null_Iir then
            Add_Binding_Indication_Dependence (Top, Bind);
            Entity := Get_Entity_From_Entity_Aspect (Entity_Aspect);
            Comp := Get_Named_Entity (Get_Component_Name (Cfg));

            --  Canon generic map
            Map_Chain := Get_Generic_Map_Aspect_Chain (Bind);
            if Map_Chain = Null_Iir then
               if Is_Config and then Is_Valid (Entity) then
                  Map_Chain := Sem_Specs.Create_Default_Map_Aspect
                    (Comp, Entity, Sem_Specs.Map_Generic, Bind);
                  --  Check all non-associated generics have a default value.
                  Sem_Specs.Sem_Check_Missing_Generic_Association
                    (Get_Generic_Chain (Entity), Map_Chain, Null_Iir, Bind);
               end if;
            else
               Map_Chain := Canon_Association_Chain
                 (Get_Generic_Chain (Entity), Map_Chain, Map_Chain);
            end if;
            Set_Generic_Map_Aspect_Chain (Bind, Map_Chain);

            --  Canon port map
            Map_Chain := Get_Port_Map_Aspect_Chain (Bind);
            if Map_Chain = Null_Iir then
               if Is_Config and then Is_Valid (Entity) then
                  Map_Chain := Sem_Specs.Create_Default_Map_Aspect
                    (Comp, Entity, Sem_Specs.Map_Port, Bind);
               end if;
            else
               Map_Chain := Canon_Association_Chain
                 (Get_Port_Chain (Entity), Map_Chain, Map_Chain);
            end if;
            Set_Port_Map_Aspect_Chain (Bind, Map_Chain);

            if Is_Config then
               Block := Get_Block_Configuration (Cfg);
               if Block /= Null_Iir then
                  --  If there is no architecture_identifier in the binding,
                  --  set it from the block_configuration.
                  if Get_Kind (Entity_Aspect) = Iir_Kind_Entity_Aspect_Entity
                    and then Get_Architecture (Entity_Aspect) = Null_Iir
                  then
                     Entity := Get_Entity (Entity_Aspect);
                     pragma Assert
                       (Get_Kind (Entity) = Iir_Kind_Entity_Declaration);
                     Set_Architecture
                       (Entity_Aspect,
                        Build_Reference_Name
                          (Get_Block_Specification (Block)));
                  end if;
                  Canon_Block_Configuration (Top, Block);
               end if;
            end if;
         end if;
      end if;
   end Canon_Component_Configuration;

   --  Create the 'final' binding indication in case of incremental binding.
   procedure Canon_Incremental_Binding
     (Conf_Spec : Iir_Configuration_Specification;
      Comp_Conf : Iir_Component_Configuration;
      Parent : Iir)
   is
      --  Merge associations from FIRST_CHAIN and SEC_CHAIN.
      function Merge_Association_Chain
        (Inter_Chain : Iir; First_Chain : Iir; Sec_Chain : Iir) return Iir
      is
         --  Result (chain).
         First, Last : Iir;

         --  Copy an association and append new elements to FIRST/LAST.  In
         --  case of individual associations, all associations for the
         --  interface are copied.
         procedure Copy_Association
           (Assoc : in out Iir; Inter : in out Iir; Copy_Inter : Iir)
         is
            El : Iir;
            Formal : Iir;
         begin
            loop
               El := Create_Iir (Get_Kind (Assoc));
               Location_Copy (El, Assoc);

               --  Copy formal.
               --  Special case: formal comes from a default binding
               --  indication.  In that case Is_Forward_Ref is set, which makes
               --  it non-copiable by Sem_Inst.
               Formal := Get_Formal (Assoc);
               if Is_Valid (Formal) then
                  if Get_Kind (Formal) = Iir_Kind_Simple_Name
                    and then Get_Is_Forward_Ref (Formal)
                  then
                     Formal := Build_Simple_Name
                       (Get_Named_Entity (Formal), Formal);
                  else
                     Formal := Sem_Inst.Copy_Tree (Formal);
                  end if;
                  Set_Formal (El, Formal);
               else
                  Formal := Inter;
               end if;
               Set_Whole_Association_Flag
                 (El, Get_Whole_Association_Flag (Assoc));

               case Get_Kind (Assoc) is
                  when Iir_Kind_Association_Element_Open =>
                     null;
                  when Iir_Kind_Association_Element_By_Expression
                    | Iir_Kind_Association_Element_By_Name =>
                     Set_Actual (El, Sem_Inst.Copy_Tree (Get_Actual (Assoc)));
                     Set_Actual_Conversion
                       (El,
                        Sem_Inst.Copy_Tree (Get_Actual_Conversion (Assoc)));
                     Set_Formal_Conversion
                       (El,
                        Sem_Inst.Copy_Tree (Get_Formal_Conversion (Assoc)));
                     Set_Collapse_Signal_Flag
                       (Assoc,
                        Sem.Can_Collapse_Signals (Assoc, Formal));
                  when Iir_Kind_Association_Element_By_Individual =>
                     Set_Actual_Type (El, Get_Actual_Type (Assoc));
                  when others =>
                     Error_Kind ("copy_association", Assoc);
               end case;

               Chain_Append (First, Last, El);
               Next_Association_Interface (Assoc, Inter);
               exit when Assoc = Null_Iir;
               exit when
                 Get_Association_Interface (Assoc, Inter) /= Copy_Inter;
            end loop;
         end Copy_Association;

         procedure Advance
           (Assoc : in out Iir; Inter : in out Iir; Skip_Inter : Iir) is
         begin
            loop
               Next_Association_Interface (Assoc, Inter);
               exit when Assoc = Null_Iir;
               exit when
                 Get_Association_Interface (Assoc, Inter) /= Skip_Inter;
            end loop;
         end Advance;

         Inter : Iir;
         F_El : Iir;
         F_Inter : Iir;
         S_El : Iir;
         S_Inter : Iir;
      begin
         F_El := First_Chain;
         F_Inter := Inter_Chain;
         Chain_Init (First, Last);
         Inter := Inter_Chain;
         while Inter /= Null_Iir loop
            --  Consistency check.
            pragma Assert (Get_Association_Interface (F_El, F_Inter) = Inter);

            --  Find the association in the second chain.
            S_El := Find_First_Association_For_Interface
              (Sec_Chain, Inter_Chain, Inter);

            if S_El /= Null_Iir
              and then Get_Kind (S_El) /= Iir_Kind_Association_Element_Open
            then
               --  Exists and not open: use it.
               S_Inter := Inter;
               Copy_Association (S_El, S_Inter, Inter);
               Advance (F_El, F_Inter, Inter);
            else
               --  Does not exist: use the one from first chain.
               Copy_Association (F_El, F_Inter, Inter);
            end if;
            Inter := Get_Chain (Inter);
         end loop;
         return First;
      end Merge_Association_Chain;

      Comp_Name : constant Iir := Get_Component_Name (Conf_Spec);
      Comp : constant Iir := Get_Named_Entity (Comp_Name);
      Cs_Binding : constant Iir := Get_Binding_Indication (Conf_Spec);
      Cc_Binding : constant Iir := Get_Binding_Indication (Comp_Conf);
      Res : Iir_Component_Configuration;
      Cs_Chain : Iir;
      Res_Binding : Iir_Binding_Indication;
      Entity : Iir;
      Instance_List : Iir_List;
      Conf_Instance_List : Iir_Flist;
      Instance : Iir;
      Instance_Name : Iir;
      N_Nbr : Natural;
   begin
      --  Create the new component configuration
      Res := Create_Iir (Iir_Kind_Component_Configuration);
      Location_Copy (Res, Comp_Conf);
      Set_Parent (Res, Parent);
      Set_Component_Name (Res, Build_Reference_Name (Comp_Name));

      Res_Binding := Create_Iir (Iir_Kind_Binding_Indication);
      Location_Copy (Res_Binding, Res);
      Set_Binding_Indication (Res, Res_Binding);

      Entity := Get_Entity_From_Entity_Aspect (Get_Entity_Aspect (Cs_Binding));

      --  Merge generic map aspect.
      Cs_Chain := Get_Generic_Map_Aspect_Chain (Cs_Binding);
      if Cs_Chain = Null_Iir then
         Cs_Chain := Sem_Specs.Create_Default_Map_Aspect
           (Comp, Entity, Sem_Specs.Map_Generic, Cs_Binding);
      end if;
      Set_Generic_Map_Aspect_Chain
        (Res_Binding,
         Merge_Association_Chain (Get_Generic_Chain (Entity),