aboutsummaryrefslogtreecommitdiffstats
path: root/os
diff options
context:
space:
mode:
authorgdisirio <gdisirio@35acf78f-673a-0410-8e92-d51de3d6d3f4>2012-05-19 12:28:14 +0000
committergdisirio <gdisirio@35acf78f-673a-0410-8e92-d51de3d6d3f4>2012-05-19 12:28:14 +0000
commitba01b11a39f178169fe1517458cbfc9c3f5f9a0f (patch)
tree93ff1d26d9b9b948131435a1503a73eb9b2a72c3 /os
parent60ed87c8418ecbab461e98efbfe170185cee2556 (diff)
downloadChibiOS-ba01b11a39f178169fe1517458cbfc9c3f5f9a0f.tar.gz
ChibiOS-ba01b11a39f178169fe1517458cbfc9c3f5f9a0f.tar.bz2
ChibiOS-ba01b11a39f178169fe1517458cbfc9c3f5f9a0f.zip
git-svn-id: svn://svn.code.sf.net/p/chibios/svn/trunk@4214 35acf78f-673a-0410-8e92-d51de3d6d3f4
Diffstat (limited to 'os')
-rw-r--r--os/hal/platforms/STM32F0xx/platform.mk1
-rw-r--r--os/hal/platforms/STM32F0xx/serial_lld.c322
-rw-r--r--os/hal/platforms/STM32F0xx/serial_lld.h182
3 files changed, 505 insertions, 0 deletions
diff --git a/os/hal/platforms/STM32F0xx/platform.mk b/os/hal/platforms/STM32F0xx/platform.mk
index f27c753f4..e34e8dd8e 100644
--- a/os/hal/platforms/STM32F0xx/platform.mk
+++ b/os/hal/platforms/STM32F0xx/platform.mk
@@ -1,5 +1,6 @@
# List of all the STM32F1xx platform files.
PLATFORMSRC = ${CHIBIOS}/os/hal/platforms/STM32F0xx/hal_lld.c \
+ ${CHIBIOS}/os/hal/platforms/STM32F0xx/serial_lld.c \
${CHIBIOS}/os/hal/platforms/STM32/GPIOv2/pal_lld.c
# Required include directories
diff --git a/os/hal/platforms/STM32F0xx/serial_lld.c b/os/hal/platforms/STM32F0xx/serial_lld.c
new file mode 100644
index 000000000..abb15b84a
--- /dev/null
+++ b/os/hal/platforms/STM32F0xx/serial_lld.c
@@ -0,0 +1,322 @@
+/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT 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 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT 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 <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file STM32/serial_lld.c
+ * @brief STM32 low level serial driver code.
+ *
+ * @addtogroup SERIAL
+ * @{
+ */
+
+#include "ch.h"
+#include "hal.h"
+
+#if HAL_USE_SERIAL || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Driver exported variables. */
+/*===========================================================================*/
+
+/** @brief USART1 serial driver identifier.*/
+#if STM32_SERIAL_USE_USART1 || defined(__DOXYGEN__)
+SerialDriver SD1;
+#endif
+
+/** @brief USART2 serial driver identifier.*/
+#if STM32_SERIAL_USE_USART2 || defined(__DOXYGEN__)
+SerialDriver SD2;
+#endif
+
+/*===========================================================================*/
+/* Driver local variables. */
+/*===========================================================================*/
+
+/** @brief Driver default configuration.*/
+static const SerialConfig default_config =
+{
+ SERIAL_DEFAULT_BITRATE,
+ 0,
+ USART_CR2_STOP1_BITS | USART_CR2_LINEN,
+ 0
+};
+
+/*===========================================================================*/
+/* Driver local functions. */
+/*===========================================================================*/
+
+/**
+ * @brief USART initialization.
+ * @details This function must be invoked with interrupts disabled.
+ *
+ * @param[in] sdp pointer to a @p SerialDriver object
+ * @param[in] config the architecture-dependent serial driver configuration
+ */
+static void usart_init(SerialDriver *sdp, const SerialConfig *config) {
+ USART_TypeDef *u = sdp->usart;
+
+ /*
+ * Baud rate setting.
+ */
+ if (sdp->usart == USART1)
+ u->BRR = STM32_USART1CLK / config->sc_speed;
+ else
+ u->BRR = STM32_PCLK / config->sc_speed;
+
+ /*
+ * Note that some bits are enforced.
+ */
+ u->CR1 = config->sc_cr1 | USART_CR1_UE | USART_CR1_PEIE |
+ USART_CR1_RXNEIE | USART_CR1_TE |
+ USART_CR1_RE;
+ u->CR2 = config->sc_cr2 | USART_CR2_LBDIE;
+ u->CR3 = config->sc_cr3 | USART_CR3_EIE;
+ u->ICR = 0xFFFFFFFF;
+}
+
+/**
+ * @brief USART de-initialization.
+ * @details This function must be invoked with interrupts disabled.
+ *
+ * @param[in] u pointer to an USART I/O block
+ */
+static void usart_deinit(USART_TypeDef *u) {
+
+ u->CR1 = 0;
+ u->CR2 = 0;
+ u->CR3 = 0;
+}
+
+#if STM32_SERIAL_USE_USART1 || STM32_SERIAL_USE_USART2
+/**
+ * @brief Error handling routine.
+ *
+ * @param[in] sdp pointer to a @p SerialDriver object
+ * @param[in] isr USART ISR register value
+ */
+static void set_error(SerialDriver *sdp, uint16_t isr) {
+ chnflags_t sts = 0;
+
+ if (isr & USART_ISR_ORE)
+ sts |= SD_OVERRUN_ERROR;
+ if (isr & USART_ISR_PE)
+ sts |= SD_PARITY_ERROR;
+ if (isr & USART_ISR_FE)
+ sts |= SD_FRAMING_ERROR;
+ if (isr & USART_ISR_NE)
+ sts |= SD_NOISE_ERROR;
+ chSysLockFromIsr();
+ chnAddFlagsI(sdp, sts);
+ chSysUnlockFromIsr();
+}
+
+/**
+ * @brief Common IRQ handler.
+ *
+ * @param[in] sdp communication channel associated to the USART
+ */
+static void serve_interrupt(SerialDriver *sdp) {
+ USART_TypeDef *u = sdp->usart;
+ uint16_t cr1 = u->CR1;
+ uint16_t isr;
+
+ /* Reading and clearing status.*/
+ isr = u->ISR;
+ u->ICR = isr;
+
+ /* Error condition detection.*/
+ if (isr & (USART_ISR_ORE | USART_ISR_NE | USART_ISR_FE | USART_ISR_PE))
+ set_error(sdp, isr);
+ /* Special case, LIN break detection.*/
+ if (isr & USART_ISR_LBD) {
+ chSysLockFromIsr();
+ chnAddFlagsI(sdp, SD_BREAK_DETECTED);
+ chSysUnlockFromIsr();
+ }
+ /* Data available.*/
+ if (isr & USART_ISR_RXNE) {
+ chSysLockFromIsr();
+ sdIncomingDataI(sdp, (uint8_t)u->RDR);
+ chSysUnlockFromIsr();
+ }
+ /* Transmission buffer empty.*/
+ if ((cr1 & USART_CR1_TXEIE) && (isr & USART_ISR_TXE)) {
+ msg_t b;
+ chSysLockFromIsr();
+ b = chOQGetI(&sdp->oqueue);
+ if (b < Q_OK) {
+ chnAddFlagsI(sdp, CHN_OUTPUT_EMPTY);
+ u->CR1 = (cr1 & ~USART_CR1_TXEIE) | USART_CR1_TCIE;
+ }
+ else
+ u->RDR = b;
+ chSysUnlockFromIsr();
+ }
+ /* Physical transmission end.*/
+ if (isr & USART_ISR_TC) {
+ chSysLockFromIsr();
+ chnAddFlagsI(sdp, CHN_TRANSMISSION_END);
+ chSysUnlockFromIsr();
+ u->CR1 = cr1 & ~USART_CR1_TCIE;
+ }
+}
+#endif
+
+#if STM32_SERIAL_USE_USART1 || defined(__DOXYGEN__)
+static void notify1(GenericQueue *qp) {
+
+ (void)qp;
+ USART1->CR1 |= USART_CR1_TXEIE;
+}
+#endif
+
+#if STM32_SERIAL_USE_USART2 || defined(__DOXYGEN__)
+static void notify2(GenericQueue *qp) {
+
+ (void)qp;
+ USART2->CR1 |= USART_CR1_TXEIE;
+}
+#endif
+
+/*===========================================================================*/
+/* Driver interrupt handlers. */
+/*===========================================================================*/
+
+#if STM32_SERIAL_USE_USART1 || defined(__DOXYGEN__)
+/**
+ * @brief USART1 interrupt handler.
+ *
+ * @isr
+ */
+CH_IRQ_HANDLER(USART1_IRQHandler) {
+
+ CH_IRQ_PROLOGUE();
+
+ serve_interrupt(&SD1);
+
+ CH_IRQ_EPILOGUE();
+}
+#endif
+
+#if STM32_SERIAL_USE_USART2 || defined(__DOXYGEN__)
+/**
+ * @brief USART2 interrupt handler.
+ *
+ * @isr
+ */
+CH_IRQ_HANDLER(USART2_IRQHandler) {
+
+ CH_IRQ_PROLOGUE();
+
+ serve_interrupt(&SD2);
+
+ CH_IRQ_EPILOGUE();
+}
+#endif
+
+/*===========================================================================*/
+/* Driver exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Low level serial driver initialization.
+ *
+ * @notapi
+ */
+void sd_lld_init(void) {
+
+#if STM32_SERIAL_USE_USART1
+ sdObjectInit(&SD1, NULL, notify1);
+ SD1.usart = USART1;
+#endif
+
+#if STM32_SERIAL_USE_USART2
+ sdObjectInit(&SD2, NULL, notify2);
+ SD2.usart = USART2;
+#endif
+}
+
+/**
+ * @brief Low level serial driver configuration and (re)start.
+ *
+ * @param[in] sdp pointer to a @p SerialDriver object
+ * @param[in] config the architecture-dependent serial driver configuration.
+ * If this parameter is set to @p NULL then a default
+ * configuration is used.
+ *
+ * @notapi
+ */
+void sd_lld_start(SerialDriver *sdp, const SerialConfig *config) {
+
+ if (config == NULL)
+ config = &default_config;
+
+ if (sdp->state == SD_STOP) {
+#if STM32_SERIAL_USE_USART1
+ if (&SD1 == sdp) {
+ rccEnableUSART1(FALSE);
+ nvicEnableVector(USART1_IRQn,
+ CORTEX_PRIORITY_MASK(STM32_SERIAL_USART1_PRIORITY));
+ }
+#endif
+#if STM32_SERIAL_USE_USART2
+ if (&SD2 == sdp) {
+ rccEnableUSART2(FALSE);
+ nvicEnableVector(USART2_IRQn,
+ CORTEX_PRIORITY_MASK(STM32_SERIAL_USART2_PRIORITY));
+ }
+#endif
+ }
+ usart_init(sdp, config);
+}
+
+/**
+ * @brief Low level serial driver stop.
+ * @details De-initializes the USART, stops the associated clock, resets the
+ * interrupt vector.
+ *
+ * @param[in] sdp pointer to a @p SerialDriver object
+ *
+ * @notapi
+ */
+void sd_lld_stop(SerialDriver *sdp) {
+
+ if (sdp->state == SD_READY) {
+ usart_deinit(sdp->usart);
+#if STM32_SERIAL_USE_USART1
+ if (&SD1 == sdp) {
+ rccDisableUSART1(FALSE);
+ nvicDisableVector(USART1_IRQn);
+ return;
+ }
+#endif
+#if STM32_SERIAL_USE_USART2
+ if (&SD2 == sdp) {
+ rccDisableUSART2(FALSE);
+ nvicDisableVector(USART2_IRQn);
+ return;
+ }
+#endif
+ }
+}
+
+#endif /* HAL_USE_SERIAL */
+
+/** @} */
diff --git a/os/hal/platforms/STM32F0xx/serial_lld.h b/os/hal/platforms/STM32F0xx/serial_lld.h
new file mode 100644
index 000000000..da41e66da
--- /dev/null
+++ b/os/hal/platforms/STM32F0xx/serial_lld.h
@@ -0,0 +1,182 @@
+/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT 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 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT 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 <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file STM32/serial_lld.h
+ * @brief STM32 low level serial driver header.
+ *
+ * @addtogroup SERIAL
+ * @{
+ */
+
+#ifndef _SERIAL_LLD_H_
+#define _SERIAL_LLD_H_
+
+#if HAL_USE_SERIAL || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Driver constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Driver pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @name Configuration options
+ * @{
+ */
+/**
+ * @brief USART1 driver enable switch.
+ * @details If set to @p TRUE the support for USART1 is included.
+ * @note The default is @p TRUE.
+ */
+#if !defined(STM32_SERIAL_USE_USART1) || defined(__DOXYGEN__)
+#define STM32_SERIAL_USE_USART1 TRUE
+#endif
+
+/**
+ * @brief USART2 driver enable switch.
+ * @details If set to @p TRUE the support for USART2 is included.
+ * @note The default is @p TRUE.
+ */
+#if !defined(STM32_SERIAL_USE_USART2) || defined(__DOXYGEN__)
+#define STM32_SERIAL_USE_USART2 TRUE
+#endif
+
+/**
+ * @brief USART1 interrupt priority level setting.
+ */
+#if !defined(STM32_SERIAL_USART1_PRIORITY) || defined(__DOXYGEN__)
+#define STM32_SERIAL_USART1_PRIORITY 3
+#endif
+
+/**
+ * @brief USART2 interrupt priority level setting.
+ */
+#if !defined(STM32_SERIAL_USART2_PRIORITY) || defined(__DOXYGEN__)
+#define STM32_SERIAL_USART2_PRIORITY 3
+#endif
+/** @} */
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if STM32_SERIAL_USE_USART1 && !STM32_HAS_USART1
+#error "USART1 not present in the selected device"
+#endif
+
+#if STM32_SERIAL_USE_USART2 && !STM32_HAS_USART2
+#error "USART2 not present in the selected device"
+#endif
+
+#if !STM32_SERIAL_USE_USART1 && !STM32_SERIAL_USE_USART2
+#error "SERIAL driver activated but no USART/UART peripheral assigned"
+#endif
+
+/*===========================================================================*/
+/* Driver data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief STM32 Serial Driver configuration structure.
+ * @details An instance of this structure must be passed to @p sdStart()
+ * in order to configure and start a serial driver operations.
+ * @note This structure content is architecture dependent, each driver
+ * implementation defines its own version and the custom static
+ * initializers.
+ */
+typedef struct {
+ /**
+ * @brief Bit rate.
+ */
+ uint32_t sc_speed;
+ /**
+ * @brief Initialization value for the CR1 register.
+ */
+ uint16_t sc_cr1;
+ /**
+ * @brief Initialization value for the CR2 register.
+ */
+ uint16_t sc_cr2;
+ /**
+ * @brief Initialization value for the CR3 register.
+ */
+ uint16_t sc_cr3;
+} SerialConfig;
+
+/**
+ * @brief @p SerialDriver specific data.
+ */
+#define _serial_driver_data \
+ _base_asynchronous_channel_data \
+ /* Driver state.*/ \
+ sdstate_t state; \
+ /* Input queue.*/ \
+ InputQueue iqueue; \
+ /* Output queue.*/ \
+ OutputQueue oqueue; \
+ /* Input circular buffer.*/ \
+ uint8_t ib[SERIAL_BUFFERS_SIZE]; \
+ /* Output circular buffer.*/ \
+ uint8_t ob[SERIAL_BUFFERS_SIZE]; \
+ /* End of the mandatory fields.*/ \
+ /* Pointer to the USART registers block.*/ \
+ USART_TypeDef *usart;
+
+/*===========================================================================*/
+/* Driver macros. */
+/*===========================================================================*/
+
+/*
+ * Extra USARTs definitions here (missing from the ST header file).
+ */
+#define USART_CR2_STOP1_BITS (0 << 12) /**< @brief CR2 1 stop bit value.*/
+#define USART_CR2_STOP0P5_BITS (1 << 12) /**< @brief CR2 0.5 stop bit value.*/
+#define USART_CR2_STOP2_BITS (2 << 12) /**< @brief CR2 2 stop bit value.*/
+#define USART_CR2_STOP1P5_BITS (3 << 12) /**< @brief CR2 1.5 stop bit value.*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#if STM32_SERIAL_USE_USART1 && !defined(__DOXYGEN__)
+extern SerialDriver SD1;
+#endif
+#if STM32_SERIAL_USE_USART2 && !defined(__DOXYGEN__)
+extern SerialDriver SD2;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void sd_lld_init(void);
+ void sd_lld_start(SerialDriver *sdp, const SerialConfig *config);
+ void sd_lld_stop(SerialDriver *sdp);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* HAL_USE_SERIAL */
+
+#endif /* _SERIAL_LLD_H_ */
+
+/** @} */
f='#n1002'>1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 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 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983
--  Evaluation of static expressions.
--  Copyright (C) 2002, 2003, 2004, 2005 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 Ada.Unchecked_Deallocation;
with Ada.Characters.Handling;
with Interfaces;

with Name_Table; use Name_Table;
with Str_Table;
with Flags; use Flags;
with Std_Names;
with Errorout; use Errorout;
with Areapools;

with Vhdl.Scanner;
with Vhdl.Errors; use Vhdl.Errors;
with Vhdl.Utils; use Vhdl.Utils;
with Vhdl.Std_Package; use Vhdl.Std_Package;
with Vhdl.Ieee.Std_Logic_1164;

with Elab.Vhdl_Objtypes;
with Elab.Vhdl_Types;
with Elab.Memtype;
with Synth.Vhdl_Eval;

with Grt.Types;
with Grt.Vhdl_Types;
with Grt.Fcvt;
with Grt.To_Strings;

package body Vhdl.Evaluation is
   --  If FORCE is true, always return a literal.
   function Eval_Expr_Keep_Orig (Expr : Iir; Force : Boolean) return Iir;

   function Eval_Check_Bound (Expr : Iir; Sub_Type : Iir) return Boolean;

   function Eval_Enum_To_String (Lit : Iir; Orig : Iir) return Iir;
   function Eval_Integer_Image (Val : Int64; Orig : Iir) return Iir;
   function Eval_Floating_Image (Val : Fp64; Orig : Iir) return Iir;
   function Eval_Floating_To_String_Format (Val : Fp64; Fmt : Iir; Orig : Iir)
                                           return Iir;

   function Eval_Scalar_Compare (Left, Right : Iir) return Compare_Type;

   function Get_Physical_Value (Expr : Iir) return Int64
   is
      pragma Unsuppress (Overflow_Check);
      Kind : constant Iir_Kind := Get_Kind (Expr);
      Unit : Iir;
   begin
      case Kind is
         when Iir_Kind_Physical_Int_Literal
           | Iir_Kind_Physical_Fp_Literal =>
            --  Extract Unit.
            Unit := Get_Physical_Literal
              (Get_Named_Entity (Get_Unit_Name (Expr)));
            pragma Assert (Get_Kind (Unit) = Iir_Kind_Integer_Literal);
            case Iir_Kinds_Physical_Literal (Kind) is
               when Iir_Kind_Physical_Int_Literal =>
                  return Get_Value (Expr) * Get_Value (Unit);
               when Iir_Kind_Physical_Fp_Literal =>
                  return Int64 (Get_Fp_Value (Expr) * Fp64 (Get_Value (Unit)));
            end case;
         when Iir_Kind_Integer_Literal =>
            return Get_Value (Expr);
         when Iir_Kind_Unit_Declaration =>
            return Get_Value (Get_Physical_Literal (Expr));
         when others =>
            Error_Kind ("get_physical_value", Expr);
      end case;
   end Get_Physical_Value;

   function Build_Integer (Val : Int64; Lit_Type : Iir; Orig : Iir) return Iir
   is
      Res : Iir_Integer_Literal;
   begin
      Res := Create_Iir (Iir_Kind_Integer_Literal);
      Location_Copy (Res, Orig);
      Set_Value (Res, Val);
      Set_Type (Res, Lit_Type);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Integer;

   function Build_Integer (Val : Int64; Origin : Iir) return Iir
   is
      Res : Iir_Integer_Literal;
   begin
      Res := Build_Integer (Val, Get_Type (Origin), Origin);
      Set_Literal_Origin (Res, Origin);
      return Res;
   end Build_Integer;

   function Build_Floating (Val : Fp64; Origin : Iir)
                           return Iir_Floating_Point_Literal
   is
      Res : Iir_Floating_Point_Literal;
   begin
      Res := Create_Iir (Iir_Kind_Floating_Point_Literal);
      Location_Copy (Res, Origin);
      Set_Fp_Value (Res, Val);
      Set_Type (Res, Get_Type (Origin));
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Floating;

   function Build_Enumeration_Constant
     (Val : Iir_Index32; Lit_Type : Iir; Orig : Iir) return Iir
   is
      Enum_Type : constant Iir := Get_Base_Type (Lit_Type);
      Enum_List : constant Iir_Flist :=
        Get_Enumeration_Literal_List (Enum_Type);
      Lit : constant Iir_Enumeration_Literal :=
        Get_Nth_Element (Enum_List, Integer (Val));
      Res : Iir_Enumeration_Literal;
   begin
      Res := Copy_Enumeration_Literal (Lit);
      Location_Copy (Res, Orig);
      return Res;
   end Build_Enumeration_Constant;

   function Build_Enumeration_Constant (Val : Iir_Index32; Origin : Iir)
     return Iir_Enumeration_Literal
   is
      Res : Iir_Enumeration_Literal;
   begin
      Res := Build_Enumeration_Constant (Val, Get_Type (Origin), Origin);
      Set_Literal_Origin (Res, Origin);
      return Res;
   end Build_Enumeration_Constant;

   function Build_Physical (Val : Int64; Origin : Iir)
                           return Iir_Integer_Literal
   is
      Res : Iir_Integer_Literal;
   begin
      Res := Create_Iir (Iir_Kind_Integer_Literal);
      Location_Copy (Res, Origin);
      Set_Value (Res, Val);
      Set_Type (Res, Get_Type (Origin));
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Physical;

   function Build_Discrete (Val : Int64; Origin : Iir) return Iir is
   begin
      case Get_Kind (Get_Type (Origin)) is
         when Iir_Kind_Enumeration_Type_Definition
           | Iir_Kind_Enumeration_Subtype_Definition =>
            return Build_Enumeration_Constant (Iir_Index32 (Val), Origin);
         when Iir_Kind_Integer_Type_Definition
           | Iir_Kind_Integer_Subtype_Definition =>
            return Build_Integer (Val, Origin);
         when others =>
            Error_Kind ("build_discrete", Get_Type (Origin));
      end case;
   end Build_Discrete;

   function Build_String (Val : String8_Id; Len : Nat32; Origin : Iir)
                         return Iir
   is
      Res : Iir;
   begin
      Res := Create_Iir (Iir_Kind_String_Literal8);
      Location_Copy (Res, Origin);
      Set_String8_Id (Res, Val);
      Set_String_Length (Res, Len);
      Set_Type (Res, Get_Type (Origin));
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_String;

   function Build_String (Str : String; Orig : Iir) return Iir
   is
      use Str_Table;
      Id : String8_Id;
   begin
      Id := Create_String8;
      for I in Str'Range loop
         Append_String8_Char (Str (I));
      end loop;
      return Build_String (Id, Int32 (Str'Length), Orig);
   end Build_String;


   --  Build a simple aggregate composed of EL_LIST from ORIGIN.  STYPE is the
   --  type of the aggregate.  DEF_TYPE should be either Null_Iir or STYPE.  It
   --  is set only when a new subtype has been created for the aggregate.
   function Build_Simple_Aggregate (El_List : Iir_Flist;
                                    Origin : Iir;
                                    Stype : Iir;
                                    Def_Type : Iir := Null_Iir)
                                   return Iir_Simple_Aggregate
   is
      Res : Iir_Simple_Aggregate;
   begin
      Res := Create_Iir (Iir_Kind_Simple_Aggregate);
      Location_Copy (Res, Origin);
      Set_Simple_Aggregate_List (Res, El_List);
      Set_Type (Res, Stype);
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      Set_Literal_Subtype (Res, Def_Type);
      return Res;
   end Build_Simple_Aggregate;

   function Build_Overflow (Origin : Iir; Expr_Type : Iir) return Iir
   is
      Res : Iir;
   begin
      Res := Create_Iir (Iir_Kind_Overflow_Literal);
      Location_Copy (Res, Origin);
      Set_Type (Res, Expr_Type);
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Overflow;

   function Build_Overflow (Origin : Iir) return Iir is
   begin
      return Build_Overflow (Origin, Get_Type (Origin));
   end Build_Overflow;

   function Build_Constant (Val : Iir; Origin : Iir) return Iir
   is
      Res : Iir;
   begin
      --  Note: this must work for any literals, because it may be used to
      --  replace a locally static constant by its initial value.
      case Get_Kind (Val) is
         when Iir_Kind_Integer_Literal =>
            Res := Create_Iir (Iir_Kind_Integer_Literal);
            Set_Value (Res, Get_Value (Val));

         when Iir_Kind_Floating_Point_Literal =>
            Res := Create_Iir (Iir_Kind_Floating_Point_Literal);
            Set_Fp_Value (Res, Get_Fp_Value (Val));

         when Iir_Kind_Enumeration_Literal =>
            return Build_Enumeration_Constant
              (Iir_Index32 (Get_Enum_Pos (Val)), Origin);

         when Iir_Kind_Physical_Int_Literal
           | Iir_Kind_Physical_Fp_Literal
           | Iir_Kind_Unit_Declaration =>
            Res := Create_Iir (Iir_Kind_Integer_Literal);
            Set_Value (Res, Get_Physical_Value (Val));

         when Iir_Kind_String_Literal8 =>
            Res := Create_Iir (Iir_Kind_String_Literal8);
            Set_String8_Id (Res, Get_String8_Id (Val));
            Set_String_Length (Res, Get_String_Length (Val));

         when Iir_Kind_Simple_Aggregate =>
            Res := Create_Iir (Iir_Kind_Simple_Aggregate);
            Set_Simple_Aggregate_List (Res, Get_Simple_Aggregate_List (Val));

         when Iir_Kind_Aggregate =>
            --  FIXME: ownership violation: both RES and VAL are parents of
            --   association_choices_chain and aggregate_info.
            --  But this aggregate is always temporary.
            --  TODO: add maybe_ref_chain.
            Res := Create_Iir (Iir_Kind_Aggregate);
            Set_Association_Choices_Chain
              (Res, Get_Association_Choices_Chain (Val));
            Set_Aggregate_Info (Res, Get_Aggregate_Info (Val));
            Set_Aggregate_Expand_Flag (Res, Get_Aggregate_Expand_Flag (Val));

         when Iir_Kind_Overflow_Literal =>
            Res := Create_Iir (Iir_Kind_Overflow_Literal);

         when others =>
            Error_Kind ("build_constant", Val);
      end case;
      Location_Copy (Res, Origin);
      Set_Type (Res, Get_Type (Origin));
      Set_Literal_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Constant;

   function Copy_Constant (Val : Iir) return Iir
   is
      Res : Iir;
   begin
      Res := Build_Constant (Val, Val);
      Set_Literal_Origin (Res, Null_Iir);
      return Res;
   end Copy_Constant;

   --  FIXME: origin ?
   function Build_Boolean (Cond : Boolean) return Iir is
   begin
      if Cond then
         return Boolean_True;
      else
         return Boolean_False;
      end if;
   end Build_Boolean;

   function Build_Enumeration (Val : Iir_Index32; Origin : Iir)
                              return Iir_Enumeration_Literal
   is
      Enum_Type : constant Iir := Get_Base_Type (Get_Type (Origin));
      Enum_List : constant Iir_Flist :=
        Get_Enumeration_Literal_List (Enum_Type);
   begin
      return Get_Nth_Element (Enum_List, Integer (Val));
   end Build_Enumeration;

   function Build_Enumeration (Val : Boolean; Origin : Iir)
                              return Iir_Enumeration_Literal
   is
      Enum_Type : constant Iir := Get_Base_Type (Get_Type (Origin));
      Enum_List : constant Iir_Flist :=
        Get_Enumeration_Literal_List (Enum_Type);
   begin
      return Get_Nth_Element (Enum_List, Boolean'Pos (Val));
   end Build_Enumeration;

   function Build_Constant_Range (Range_Expr : Iir; Origin : Iir) return Iir
   is
      Res : Iir;
   begin
      Res := Create_Iir (Iir_Kind_Range_Expression);
      Location_Copy (Res, Origin);
      Set_Type (Res, Get_Type (Range_Expr));
      Set_Left_Limit (Res, Get_Left_Limit (Range_Expr));
      Set_Right_Limit (Res, Get_Right_Limit (Range_Expr));
      Set_Direction (Res, Get_Direction (Range_Expr));
      Set_Range_Origin (Res, Origin);
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Build_Constant_Range;

   function Build_Extreme_Value (Is_Pos : Boolean; Origin : Iir) return Iir
   is
      Orig_Type : constant Iir := Get_Base_Type (Get_Type (Origin));
   begin
      case Get_Kind (Orig_Type) is
         when Iir_Kind_Integer_Type_Definition =>
            if Is_Pos then
               return Build_Integer (Int64'Last, Origin);
            else
               return Build_Integer (Int64'First, Origin);
            end if;
         when others =>
            Error_Kind ("build_extreme_value", Orig_Type);
      end case;
   end Build_Extreme_Value;

   --  Check VAL fits in the base type.
   function Build_Integer_Check (Val : Int64; Origin : Iir)
     return Iir_Integer_Literal
   is
      Atype : constant Iir := Get_Base_Type (Get_Type (Origin));
      subtype Rng_32 is Int64 range Int64 (Int32'First) .. Int64 (Int32'Last);
   begin
      if Get_Scalar_Size (Atype) = Scalar_32
        and then Val not in Rng_32
      then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Origin,
                          "arithmetic overflow in static expression");
         return Build_Overflow (Origin);
      end if;

      return Build_Integer (Val, Origin);
   end Build_Integer_Check;

   --  A_RANGE is a range expression, whose type, location, expr_staticness,
   --  left_limit and direction are set.
   --  Type of A_RANGE must have a range_constraint.
   --  Set the right limit of A_RANGE from LEN.
   procedure Set_Right_Limit_By_Length (A_Range : Iir; Len : Int64)
   is
      A_Type : constant Iir := Get_Type (A_Range);
      Left : constant Iir := Get_Left_Limit (A_Range);
      Right : Iir;
      Pos : Int64;
   begin
      pragma Assert (Get_Expr_Staticness (A_Range) = Locally);

      Pos := Eval_Pos (Left);
      case Get_Direction (A_Range) is
         when Dir_To =>
            Pos := Pos + Len - 1;
         when Dir_Downto =>
            Pos := Pos - Len + 1;
      end case;
      if Len > 0
        and then not Eval_Int_In_Range (Pos, Get_Range_Constraint (A_Type))
      then
         Error_Msg_Sem (+A_Range, "range length is beyond subtype length");
         Right := Left;
      else
         Right := Build_Discrete (Pos, A_Range);
         Set_Literal_Origin (Right, Null_Iir);
         Set_Right_Limit_Expr (A_Range, Right);
      end if;
      Set_Right_Limit (A_Range, Right);
   end Set_Right_Limit_By_Length;

   --  LRM08 9.3.2 Literals
   --  If there is a value to the left of the nominal leftmost bound (given by
   --  the 'LEFTOF) attribute, then the leftmost bound is the nominal leftmost
   --  bound, and the rightmost bound is the value to the left of the nominal
   --  leftmost bound.  Otherwise, the leftmost bound is the value to the
   --  right of the nominal leftmost bound, and the rightmost bound is the
   --  nominal leftmost bound.
   procedure Set_Enumeration_Null_Range_Limits (A_Range : Iir)
   is
      A_Type : constant Iir := Get_Type (A_Range);
      Btype : constant Iir := Get_Base_Type (A_Type);
      Enum_List : constant Iir_Flist := Get_Enumeration_Literal_List (Btype);
      Last_Enum : constant Natural := Flist_Last (Enum_List);
      Left : constant Iir := Get_Left_Limit (A_Range);
      Right : Iir;
      Pos : Int64;
      Invert : Boolean;
   begin
      pragma Assert (Get_Expr_Staticness (A_Range) = Locally);

      if Last_Enum = 0 then
         Error_Msg_Sem
           (+A_Range, "null range not supported for enumeration type %n",
            +A_Type);
         Right := Left;
      else
         Pos := Eval_Pos (Left);
         Invert := False;
         case Get_Direction (A_Range) is
            when Dir_To =>
               if Pos = 0 then
                  Pos := Pos + 1;
                  Invert := True;
               else
                  Pos := Pos - 1;
               end if;
            when Dir_Downto =>
               if Pos = Int64 (Last_Enum) then
                  Pos := Pos - 1;
                  Invert := True;
               else
                  Pos := Pos + 1;
               end if;
         end case;

         Right := Build_Discrete (Pos, A_Range);
         Set_Literal_Origin (Right, Null_Iir);

         if Invert then
            Set_Left_Limit_Expr (A_Range, Right);
            Set_Left_Limit (A_Range, Right);
            Set_Right_Limit (A_Range, Left);
         else
            Set_Right_Limit_Expr (A_Range, Right);
            Set_Right_Limit (A_Range, Right);
         end if;
      end if;
   end Set_Enumeration_Null_Range_Limits;

   --  Create a range of type A_TYPE whose length is LEN.
   --  Note: only two nodes are created:
   --  * the range_expression (node returned)
   --  * the right bound
   --  The left bound *IS NOT* created, but points to the left bound of A_TYPE.
   function Create_Range_By_Length
     (A_Type : Iir; Len : Int64; Loc : Location_Type)
     return Iir
   is
      Index_Constraint : Iir;
      Constraint : Iir;
   begin
      --  The left limit must be locally static in order to compute the right
      --  limit.
      pragma Assert (Get_Type_Staticness (A_Type) = Locally);

      Index_Constraint := Get_Range_Constraint (A_Type);
      Constraint := Create_Iir (Iir_Kind_Range_Expression);
      Set_Location (Constraint, Loc);
      Set_Expr_Staticness (Constraint, Locally);
      Set_Type (Constraint, A_Type);
      Set_Left_Limit (Constraint, Get_Left_Limit (Index_Constraint));
      Set_Direction (Constraint, Get_Direction (Index_Constraint));
      if Len = 0
        and then (Get_Kind (Get_Base_Type (A_Type))
                    = Iir_Kind_Enumeration_Type_Definition)
      then
         Set_Enumeration_Null_Range_Limits (Constraint);
      else
         Set_Right_Limit_By_Length (Constraint, Len);
      end if;
      return Constraint;
   end Create_Range_By_Length;

   function Create_Range_Subtype_From_Type (A_Type : Iir; Loc : Location_Type)
                                          return Iir
   is
      Res : Iir;
   begin
      pragma Assert (Get_Type_Staticness (A_Type) = Locally);

      case Get_Kind (A_Type) is
         when Iir_Kind_Enumeration_Type_Definition =>
            Res := Create_Iir (Iir_Kind_Enumeration_Subtype_Definition);
         when Iir_Kind_Integer_Subtype_Definition
           | Iir_Kind_Enumeration_Subtype_Definition =>
            Res := Create_Iir (Get_Kind (A_Type));
         when others =>
            Error_Kind ("create_range_subtype_by_length", A_Type);
      end case;
      Set_Location (Res, Loc);
      Set_Parent_Type (Res, A_Type);
      Set_Type_Staticness (Res, Locally);

      return Res;
   end Create_Range_Subtype_From_Type;

   --  Create a subtype of A_TYPE whose length is LEN.
   --  This is used to create subtypes for strings or aggregates.
   function Create_Range_Subtype_By_Length
     (A_Type : Iir; Len : Int64; Loc : Location_Type)
     return Iir
   is
      Res : Iir;
   begin
      Res := Create_Range_Subtype_From_Type (A_Type, Loc);

      Set_Range_Constraint (Res, Create_Range_By_Length (A_Type, Len, Loc));
      return Res;
   end Create_Range_Subtype_By_Length;

   function Create_Unidim_Array_From_Index
     (Base_Type : Iir; Index_Type : Iir; Loc : Iir)
     return Iir_Array_Subtype_Definition
   is
      Res : Iir_Array_Subtype_Definition;
   begin
      Res := Create_Array_Subtype (Base_Type, Get_Location (Loc));
      Set_Nth_Element (Get_Index_Subtype_List (Res), 0, Index_Type);
      Set_Type_Staticness (Res, Min (Get_Type_Staticness (Res),
                                     Get_Type_Staticness (Index_Type)));
      Set_Constraint_State (Res, Fully_Constrained);
      Set_Index_Constraint_Flag (Res, True);
      return Res;
   end Create_Unidim_Array_From_Index;

   function Create_Unidim_Array_By_Length
     (Base_Type : Iir; Len : Int64; Loc : Iir)
     return Iir_Array_Subtype_Definition
   is
      Index_Type : constant Iir := Get_Index_Type (Base_Type, 0);
      N_Index_Type : Iir;
   begin
      N_Index_Type := Create_Range_Subtype_By_Length
        (Index_Type, Len, Get_Location (Loc));
      return Create_Unidim_Array_From_Index (Base_Type, N_Index_Type, Loc);
   end Create_Unidim_Array_By_Length;

   procedure Free_Eval_Static_Expr (Res : Iir; Orig : Iir) is
   begin
      if Res /= Orig and then Get_Literal_Origin (Res) = Orig then
         Free_Iir (Res);
      end if;
   end Free_Eval_Static_Expr;

   --  Free the result RES of Eval_String_Literal called with ORIG, if created.
   procedure Free_Eval_String_Literal (Res : Iir; Orig : Iir)
   is
      L : Iir_Flist;
   begin
      if Res /= Orig then
         L := Get_Simple_Aggregate_List (Res);
         Destroy_Iir_Flist (L);
         Free_Iir (Res);
      end if;
   end Free_Eval_String_Literal;

   function String_Literal8_To_Simple_Aggregate (Str : Iir) return Iir
   is
      Element_Type : constant Iir := Get_Base_Type
        (Get_Element_Subtype (Get_Base_Type (Get_Type (Str))));
      Literal_List : constant Iir_Flist :=
        Get_Enumeration_Literal_List (Element_Type);

      Len : constant Nat32 := Get_String_Length (Str);
      Id : constant String8_Id := Get_String8_Id (Str);

      List : Iir_Flist;
      Lit : Iir;
   begin
      List := Create_Iir_Flist (Natural (Len));

      for I in 1 .. Len loop
         Lit := Get_Nth_Element
           (Literal_List, Natural (Str_Table.Element_String8 (Id, I)));
         Set_Nth_Element (List, Natural (I - 1), Lit);
      end loop;
      return Build_Simple_Aggregate (List, Str, Get_Type (Str));
   end String_Literal8_To_Simple_Aggregate;

   --  Return the offset of EXPR in RNG.  A result of 0 means the left bound,
   --  a result of 1 mean the next element after the left bound.
   --  Assume no overflow.
   function Eval_Pos_In_Range (Rng : Iir; Expr : Iir) return Iir_Index32
   is
      Left_Pos : constant Int64 := Eval_Pos (Get_Left_Limit (Rng));
      Pos : constant Int64 := Eval_Pos (Expr);
   begin
      case Get_Direction (Rng) is
         when Dir_To =>
            return Iir_Index32 (Pos - Left_Pos);
         when Dir_Downto =>
            return Iir_Index32 (Left_Pos - Pos);
      end case;
   end Eval_Pos_In_Range;

   procedure Build_Array_Choices_Vector
     (Vect : out Iir_Array; Choice_Range : Iir; Choices_Chain : Iir)
   is
      pragma Assert (Vect'First = 0);
      pragma Assert (Vect'Length = Eval_Discrete_Range_Length (Choice_Range));
      Assoc : Iir;
      Choice : Iir;
      Cur_Pos : Natural;
   begin
      --  Initialize Vect (to correctly handle 'others').
      Vect := (others => Null_Iir);

      Assoc := Choices_Chain;
      Cur_Pos := 0;
      Choice := Null_Iir;
      while Is_Valid (Assoc) loop
         if not Get_Same_Alternative_Flag (Assoc) then
            Choice := Assoc;
         end if;
         case Iir_Kinds_Array_Choice (Get_Kind (Assoc)) is
            when Iir_Kind_Choice_By_None =>
               Vect (Cur_Pos) := Choice;
               Cur_Pos := Cur_Pos + 1;
            when Iir_Kind_Choice_By_Range =>
               declare
                  Rng : constant Iir := Get_Choice_Range (Assoc);
                  Rng_Start : Iir;
                  Rng_Len : Int64;
               begin
                  if Get_Direction (Rng) = Get_Direction (Choice_Range) then
                     Rng_Start := Get_Left_Limit (Rng);
                  else
                     Rng_Start := Get_Right_Limit (Rng);
                  end if;
                  Cur_Pos := Natural
                    (Eval_Pos_In_Range (Choice_Range, Rng_Start));
                  Rng_Len := Eval_Discrete_Range_Length (Rng);
                  for I in 1 .. Rng_Len loop
                     Vect (Cur_Pos) := Choice;
                     Cur_Pos := Cur_Pos + 1;
                  end loop;
               end;
            when Iir_Kind_Choice_By_Expression =>
               Cur_Pos := Natural
                 (Eval_Pos_In_Range (Choice_Range,
                                     Get_Choice_Expression (Assoc)));
               Vect (Cur_Pos) := Choice;
            when Iir_Kind_Choice_By_Others =>
               for I in Vect'Range loop
                  if Vect (I) = Null_Iir then
                     Vect (I) := Choice;
                  end if;
               end loop;
         end case;
         Assoc := Get_Chain (Assoc);
      end loop;
   end Build_Array_Choices_Vector;

   function Array_Aggregate_To_Simple_Aggregate (Aggr : Iir) return Iir
   is
      Aggr_Type : constant Iir := Get_Type (Aggr);
      Index_Type : constant Iir := Get_Index_Type (Aggr_Type, 0);
      Index_Range : constant Iir := Eval_Static_Range (Index_Type);
      Len : constant Int64 := Eval_Discrete_Range_Length (Index_Range);
      Assocs : constant Iir := Get_Association_Choices_Chain (Aggr);
      Vect : Iir_Array (0 .. Integer (Len - 1));
      List : Iir_Flist;
      Assoc : Iir;
      Expr : Iir;
   begin
      Assoc := Assocs;
      while Is_Valid (Assoc) loop
         if not Get_Same_Alternative_Flag (Assoc) then
            Expr := Get_Associated_Expr (Assoc);
            if Get_Kind (Get_Type (Expr))
              in Iir_Kinds_Scalar_Type_And_Subtype_Definition
            then
               Expr := Eval_Expr_Keep_Orig (Expr, True);
               Set_Associated_Expr (Assoc, Expr);
            end if;
         end if;
         Assoc := Get_Chain (Assoc);
      end loop;

      Build_Array_Choices_Vector (Vect, Index_Range, Assocs);

      List := Create_Iir_Flist (Natural (Len));
      if Len > 0 then
         --  Workaround GNAT GPL2014 compiler bug.
         for I in Vect'Range loop
            Set_Nth_Element (List, I, Get_Associated_Expr (Vect (I)));
         end loop;
      end if;

      return Build_Simple_Aggregate (List, Aggr, Aggr_Type);
   end Array_Aggregate_To_Simple_Aggregate;

   function Eval_String_Literal (Str : Iir) return Iir is
   begin
      case Get_Kind (Str) is
         when Iir_Kind_String_Literal8 =>
            return String_Literal8_To_Simple_Aggregate (Str);

         when Iir_Kind_Aggregate =>
            return Array_Aggregate_To_Simple_Aggregate (Str);

         when Iir_Kind_Simple_Aggregate =>
            return Str;

         when others =>
            Error_Kind ("eval_string_literal", Str);
      end case;
   end Eval_String_Literal;

   package Synth_Helpers is
      use Elab.Vhdl_Objtypes;
      use Elab.Memtype;

      function Convert_Node_To_Typ (N : Iir) return Type_Acc;
      function Convert_Node_To_Memtyp (N : Iir) return Memtyp;
      function Convert_Memtyp_To_Node (Mt : Memtyp; Btype : Iir; Orig : Iir)
                                      return Iir;
   end Synth_Helpers;

   package body Synth_Helpers is
      use Elab.Vhdl_Types;

      function Convert_Discrete_Range (Rng : Iir) return Discrete_Range_Type is
      begin
         return Build_Discrete_Range_Type
           (Eval_Pos (Get_Left_Limit (Rng)),
            Eval_Pos (Get_Right_Limit (Rng)),
            Get_Direction (Rng));
      end Convert_Discrete_Range;

      function Convert_Node_To_Typ (N : Iir) return Type_Acc is
      begin
         case Get_Kind (N) is
            when Iir_Kind_Enumeration_Type_Definition =>
               return Elab_Enumeration_Type_Definition (N);
            when Iir_Kind_Integer_Type_Definition =>
               declare
                  Decl : constant Iir := Get_Type_Declarator (N);
                  St : constant Iir := Get_Subtype_Definition (Decl);
                  pragma Assert
                    (Get_Kind (St) = Iir_Kind_Integer_Subtype_Definition);
               begin
                  return Elab_Scalar_Type_Definition (N, St);
               end;
            when Iir_Kind_Integer_Subtype_Definition
              | Iir_Kind_Enumeration_Subtype_Definition =>
               declare
                  Rng : constant Iir := Get_Range_Constraint (N);
                  Base_Typ : Type_Acc;
                  Res_Rng : Discrete_Range_Type;
                  W : Uns32;
               begin
                  Base_Typ := Convert_Node_To_Typ (Get_Base_Type (N));
                  if Base_Typ.Kind in Type_Nets then
                     --  A subtype of a bit/logic type is still a bit/logic.
                     --  FIXME: bounds.
                     return Base_Typ;
                  end if;
                  Res_Rng := Convert_Discrete_Range (Rng);
                  W := Discrete_Range_Width (Res_Rng);
                  return Create_Discrete_Type (Res_Rng, Base_Typ.Sz, W);
               end;
            when Iir_Kind_Array_Type_Definition =>
               declare
                  El : Type_Acc;
                  Idx : Type_Acc;
               begin
                  El := Convert_Node_To_Typ (Get_Element_Subtype (N));
                  Idx := Convert_Node_To_Typ (Get_Index_Type (N, 0));
                  if El.Kind in Type_Nets then
                     return Create_Unbounded_Vector (El, Idx);
                  else
                     raise Internal_Error;
                     --  return Create_Unbounded_Array (Xx, El, Idx);
                  end if;
               end;
            when Iir_Kind_Array_Subtype_Definition =>
               declare
                  Idx : constant Iir := Get_Index_Type (N, 0);
                  El_Typ : Type_Acc;
                  Res_Rng : Discrete_Range_Type;
               begin
                  El_Typ := Convert_Node_To_Typ (Get_Element_Subtype (N));
                  pragma Assert (El_Typ.Kind in Type_Nets);
                  Res_Rng := Convert_Discrete_Range
                    (Get_Range_Constraint (Idx));
                  return Create_Vector_Type
                    (Synth_Bounds_From_Range (Res_Rng), El_Typ);
               end;

            when others =>
               Error_Kind ("convert_node_to_typ", N);
         end case;
         return null;
      end Convert_Node_To_Typ;

      function Convert_Node_To_Memtyp (N : Iir; Typ : Type_Acc) return Memtyp
      is
         Res : Memtyp;
      begin
         case Get_Kind (N) is
            when Iir_Kind_Aggregate =>
               declare
                  Sa : Iir;
               begin
                  Sa := Array_Aggregate_To_Simple_Aggregate (N);
                  Res := Convert_Node_To_Memtyp (Sa, Typ);
                  --  TODO: destroy SA
                  return Res;
               end;
            when Iir_Kind_Simple_Aggregate =>
               declare
                  Els : constant Iir_Flist := Get_Simple_Aggregate_List (N);
                  Last : constant Natural := Flist_Last (Els);
                  Val : Iir;
               begin
                  pragma Assert (Typ.Kind = Type_Vector);
                  Res := Create_Memory (Typ);

                  for I in Flist_First .. Last loop
                     --  Elements are static.
                     Val := Get_Nth_Element (Els, I);
                     Write_Discrete (Res.Mem + Size_Type (I) * Typ.Arr_El.Sz,
                                     Typ.Arr_El, Eval_Pos (Val));
                  end loop;
               end;
            when Iir_Kind_String_Literal8 =>
               declare
                  Element_Type : constant Iir := Get_Base_Type
                    (Get_Element_Subtype (Get_Base_Type (Get_Type (N))));
                  Literal_List : constant Iir_Flist :=
                    Get_Enumeration_Literal_List (Element_Type);

                  Len : constant Nat32 := Get_String_Length (N);
                  Id : constant String8_Id := Get_String8_Id (N);

                  Lit : Iir;
               begin
                  Res := Create_Memory (Typ);

                  for I in 1 .. Len loop
                     Lit := Get_Nth_Element
                       (Literal_List,
                        Natural (Str_Table.Element_String8 (Id, I)));
                     Write_Discrete (Res.Mem + Size_Type (I - 1), Typ.Arr_El,
                                     Int64 (Get_Enum_Pos (Lit)));
                  end loop;
               end;
            when Iir_Kind_Integer_Literal
              | Iir_Kind_Enumeration_Literal =>
               Res := Create_Memory (Typ);
               Write_Discrete (Res.Mem, Typ, Eval_Pos (N));

            when others =>
               Error_Kind ("convert_node_to_memtyp", N);
         end case;
         return Res;
      end Convert_Node_To_Memtyp;

      function Convert_Node_To_Memtyp (N : Iir) return Memtyp
      is
         Typ : Type_Acc;
      begin
         Typ := Convert_Node_To_Typ (Get_Type (N));
         return Convert_Node_To_Memtyp (N, Typ);
      end Convert_Node_To_Memtyp;

      function Convert_Discrete_To_Node (V : Int64; Vtype : Iir; Orig : Iir)
                                        return Iir is
      begin
         case Get_Kind (Vtype) is
            when Iir_Kind_Integer_Subtype_Definition =>
               return Build_Integer (V, Vtype, Orig);
            when Iir_Kind_Enumeration_Subtype_Definition
              | Iir_Kind_Enumeration_Type_Definition =>
               return Build_Enumeration_Constant
                 (Iir_Index32 (V), Vtype, Orig);
            when others =>
               Error_Kind ("convert_discrete_to_node", Vtype);
         end case;
      end Convert_Discrete_To_Node;

      function Convert_Bound_To_Node
        (Bnd : Bound_Type; Btype : Iir; Orig : Iir) return Iir
      is
         Rng : Iir;
         Limit : Iir;
      begin
         Rng := Create_Iir (Iir_Kind_Range_Expression);
         Location_Copy (Rng, Orig);
         Set_Expr_Staticness (Rng, Locally);
         Set_Type (Rng, Btype);
         Set_Direction (Rng, Bnd.Dir);
         Limit := Convert_Discrete_To_Node (Int64 (Bnd.Left), Btype, Orig);
         Set_Left_Limit_Expr (Rng, Limit);
         Set_Left_Limit (Rng, Limit);
         Limit := Convert_Discrete_To_Node (Int64 (Bnd.Right), Btype, Orig);
         Set_Right_Limit_Expr (Rng, Limit);
         Set_Right_Limit (Rng, Limit);
         return Rng;
      end Convert_Bound_To_Node;

      function Convert_Typ_To_Node (Typ : Type_Acc; Btype : Iir; Orig : Iir)
                                   return Iir
      is
         Res : Iir;
      begin
         case Get_Kind (Btype) is
            when Iir_Kind_Array_Type_Definition =>
               declare
                  Loc : constant Location_Type := Get_Location (Orig);
                  Base_Idx : constant Iir := Get_Index_Type (Btype, 0);
                  Rng : Iir;
                  Idx_Type : Iir;
               begin
                  Idx_Type := Create_Range_Subtype_From_Type (Base_Idx, Loc);
                  Rng := Convert_Bound_To_Node (Typ.Abound, Base_Idx, Orig);
                  Set_Range_Constraint (Idx_Type, Rng);

                  Res := Create_Array_Subtype (Btype, Loc);
                  Set_Nth_Element (Get_Index_Subtype_List (Res), 0, Idx_Type);
                  Set_Type_Staticness (Res, Locally);
                  Set_Constraint_State (Res, Fully_Constrained);
                  Set_Index_Constraint_Flag (Res, True);
                  return Res;
               end;
            when others =>
               Error_Kind ("convert_typ_to_node", Btype);
               return Null_Iir;
         end case;
      end Convert_Typ_To_Node;

      function Convert_Vect_To_Simple_Aggregate
        (Mt : Memtyp; Res_Type : Iir; Orig : Iir) return Iir
      is
         Element_Type : constant Iir := Get_Base_Type
           (Get_Element_Subtype (Get_Base_Type (Res_Type)));
         Literal_List : constant Iir_Flist :=
           Get_Enumeration_Literal_List (Element_Type);

         Len : constant Nat32 := Nat32 (Mt.Typ.Abound.Len);

         List : Iir_Flist;
         El : Int64;
         Lit : Iir;
      begin
         List := Create_Iir_Flist (Natural (Len));

         for I in 1 .. Len loop
            El := Read_Discrete (Mt.Mem + Size_Type (I - 1),
                                 Mt.Typ.Arr_El);
            Lit := Get_Nth_Element (Literal_List, Natural (El));
            Set_Nth_Element (List, Natural (I - 1), Lit);
         end loop;
         return Build_Simple_Aggregate (List, Orig, Res_Type, Res_Type);
      end Convert_Vect_To_Simple_Aggregate;

      function Convert_Memtyp_To_Node (Mt : Memtyp; Btype : Iir; Orig : Iir)
                                      return Iir
      is
         Res_Type : Iir;
      begin
         case Mt.Typ.Kind is
            when Type_Vector =>
               Res_Type := Convert_Typ_To_Node (Mt.Typ, Btype, Orig);
               return Convert_Vect_To_Simple_Aggregate
                 (Mt, Res_Type, Orig);
            when Type_Logic
              | Type_Bit =>
               return Convert_Discrete_To_Node
                 (Read_Discrete (Mt), Btype, Orig);
            when others =>
               raise Internal_Error;
         end case;
      end Convert_Memtyp_To_Node;
   end Synth_Helpers;

   function Eval_Ieee_Operator (Orig : Iir; Imp : Iir; Left : Iir; Right : Iir)
                               return Iir
   is
      use Areapools;
      use Elab.Vhdl_Objtypes;
      use Synth.Vhdl_Eval;
      use Synth_Helpers;

      Res_Type : constant Iir := Get_Return_Type (Imp);
      Marker : Mark_Type;
      Left_Mt, Right_Mt : Memtyp;
      Res_Typ : Type_Acc;
      Res_Mt : Memtyp;
      Res : Iir;
   begin
      Mark (Marker, Expr_Pool);

      Res_Typ := Convert_Node_To_Typ (Res_Type);
      Left_Mt := Convert_Node_To_Memtyp (Left);
      if Right /= Null_Iir then
         Right_Mt := Convert_Node_To_Memtyp (Right);
         Res_Mt := Eval_Static_Dyadic_Predefined
           (Imp, Res_Typ, Left_Mt, Right_Mt, Orig);
      else
         Res_Mt := Eval_Static_Monadic_Predefined
           (Imp, Left_Mt, Orig);
      end if;
      Res := Convert_Memtyp_To_Node (Res_Mt, Res_Type, Orig);
      Release (Marker, Expr_Pool);

      return Res;
   end Eval_Ieee_Operator;

   function Eval_Monadic_Operator (Orig : Iir; Operand : Iir) return Iir
   is
      pragma Unsuppress (Overflow_Check);
      subtype Iir_Predefined_Vector_Minmax is Iir_Predefined_Functions range
        Iir_Predefined_Vector_Minimum .. Iir_Predefined_Vector_Maximum;

      Imp : constant Iir := Get_Implementation (Orig);
      Func : Iir_Predefined_Functions;
   begin
      if Is_Overflow_Literal (Operand) then
         --  Propagate overflow.
         return Build_Overflow (Orig);
      end if;

      Func := Get_Implicit_Definition (Imp);
      case Func is
         when Iir_Predefined_Integer_Negation =>
            return Build_Integer (-Get_Value (Operand), Orig);
         when Iir_Predefined_Integer_Identity =>
            return Build_Integer (Get_Value (Operand), Orig);
         when Iir_Predefined_Integer_Absolute =>
            return Build_Integer (abs Get_Value (Operand), Orig);

         when Iir_Predefined_Floating_Negation =>
            return Build_Floating (-Get_Fp_Value (Operand), Orig);
         when Iir_Predefined_Floating_Identity =>
            return Build_Floating (Get_Fp_Value (Operand), Orig);
         when Iir_Predefined_Floating_Absolute =>
            return Build_Floating (abs Get_Fp_Value (Operand), Orig);

         when Iir_Predefined_Physical_Negation =>
            return Build_Physical (-Get_Physical_Value (Operand), Orig);
         when Iir_Predefined_Physical_Identity =>
            return Build_Physical (Get_Physical_Value (Operand), Orig);
         when Iir_Predefined_Physical_Absolute =>
            return Build_Physical (abs Get_Physical_Value (Operand), Orig);

         when Iir_Predefined_Boolean_Not
           | Iir_Predefined_Bit_Not =>
            return Build_Enumeration (Get_Enum_Pos (Operand) = 0, Orig);

         when Iir_Predefined_Bit_Condition =>
            return Build_Enumeration (Get_Enum_Pos (Operand) = 1, Orig);

         when Iir_Predefined_TF_Array_Not =>
            declare
               Lit_Val : Iir;
               O_List : Iir_Flist;
               R_List : Iir_Flist;
               El : Iir;
               Lit : Iir;
            begin
               Lit_Val := Eval_String_Literal (Operand);
               O_List := Get_Simple_Aggregate_List (Lit_Val);
               R_List := Create_Iir_Flist (Get_Nbr_Elements (O_List));

               for I in Flist_First .. Flist_Last (O_List) loop
                  El := Get_Nth_Element (O_List, I);
                  case Get_Enum_Pos (El) is
                     when 0 =>
                        Lit := Bit_1;
                     when 1 =>
                        Lit := Bit_0;
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (R_List, I, Lit);
               end loop;
               Free_Eval_String_Literal (Lit_Val, Operand);
               return Build_Simple_Aggregate
                 (R_List, Orig, Get_Type (Operand));
            end;

         when Iir_Predefined_Enum_To_String =>
            return Eval_Enum_To_String (Operand, Orig);
         when Iir_Predefined_Integer_To_String =>
            return Eval_Integer_Image (Get_Value (Operand), Orig);
         when Iir_Predefined_Floating_To_String =>
            return Eval_Floating_Image (Get_Fp_Value (Operand), Orig);

         when Iir_Predefined_Array_Char_To_String =>
            --  LRM08 5.7 String representation
            --  - For a given value that is of a one-dimensional array type
            --    whose element type is a character type that contains only
            --    character literals, the string representation has the same
            --    length as the given value.  Each element of the string
            --    representation is the same character literal as the matching
            --    element of the given value.
            declare
               Saggr : Iir;
               Lits : Iir_Flist;
               El : Iir;
               C : Character;
               String_Id : String8_Id;
               Len : Natural;
            begin
               Saggr := Eval_String_Literal (Operand);
               Lits := Get_Simple_Aggregate_List (Saggr);
               Len := Get_Nbr_Elements (Lits);
               String_Id := Str_Table.Create_String8;
               for I in Flist_First .. Flist_Last (Lits) loop
                  El := Get_Nth_Element (Lits, I);
                  C := Get_Character (Get_Identifier (El));
                  Str_Table.Append_String8_Char (C);
               end loop;
               Free_Eval_String_Literal (Saggr, Operand);

               return Build_String (String_Id, Nat32 (Len), Orig);
            end;

         when Iir_Predefined_Vector_Minimum
           | Iir_Predefined_Vector_Maximum =>
            --  LRM08 5.3.2.4 Predefined operations on array types
            declare
               Saggr : Iir;
               Lits : Iir_Flist;
               Res : Iir;
               El : Iir;
               Cmp : Compare_Type;
            begin
               Saggr := Eval_String_Literal (Operand);
               Lits := Get_Simple_Aggregate_List (Saggr);

               if Get_Nbr_Elements (Lits) = 0 then
                  declare
                     Typ : constant Iir :=
                       Get_Type (Get_Implementation (Orig));
                     Rng : constant Iir := Eval_Static_Range (Typ);
                  begin
                     case Iir_Predefined_Vector_Minmax (Func) is
                        when Iir_Predefined_Vector_Minimum =>
                           Res := Get_High_Limit (Rng);
                        when Iir_Predefined_Vector_Maximum =>
                           Res := Get_Low_Limit (Rng);
                     end case;
                     Res := Eval_Static_Expr (Res);
                  end;
               else
                  Res := Get_Nth_Element (Lits, 0);
                  for I in Flist_First .. Flist_Last (Lits) loop
                     El := Get_Nth_Element (Lits, I);
                     Cmp := Eval_Scalar_Compare (El, Res);
                     case Iir_Predefined_Vector_Minmax (Func) is
                        when Iir_Predefined_Vector_Minimum =>
                           if Cmp <= Compare_Eq then
                              Res := El;
                           end if;
                        when Iir_Predefined_Vector_Maximum =>
                           if Cmp >= Compare_Eq then
                              Res := El;
                           end if;
                     end case;
                  end loop;
               end if;
               Free_Eval_String_Literal (Saggr, Operand);
               return Res;
            end;

         when Iir_Predefined_IEEE_Explicit =>
            return Eval_Ieee_Operator (Orig, Imp, Operand, Null_Iir);

         when others =>
            Error_Internal (Orig, "eval_monadic_operator: " &
                            Iir_Predefined_Functions'Image (Func));
      end case;
   exception
      when Constraint_Error =>
         --  Can happen for absolute.
         Warning_Msg_Sem (Warnid_Runtime_Error, +Orig,
                          "arithmetic overflow in static expression");
         return Build_Overflow (Orig);
   end Eval_Monadic_Operator;

   function Eval_Dyadic_Bit_Array_Operator
     (Expr : Iir;
      Left, Right : Iir;
      Func : Iir_Predefined_Dyadic_TF_Array_Functions) return Iir
   is
      Expr_Type : constant Iir := Get_Type (Expr);
      El_Type : constant Iir :=
        Get_Base_Type (Get_Element_Subtype (Expr_Type));
      Enum_List : constant Iir_Flist := Get_Enumeration_Literal_List (El_Type);
      Cst_0 : constant Iir := Get_Nth_Element (Enum_List, 0);
      Cst_1 : constant Iir := Get_Nth_Element (Enum_List, 1);
      Left_Val, Right_Val : Iir;
      R_List, L_List : Iir_Flist;
      Len : Natural;
      Res : Iir;
      Res_List : Iir_Flist;
      El : Iir;
   begin
      Left_Val := Eval_String_Literal (Left);
      Right_Val := Eval_String_Literal (Right);

      L_List := Get_Simple_Aggregate_List (Left_Val);
      R_List := Get_Simple_Aggregate_List (Right_Val);
      Len := Get_Nbr_Elements (L_List);

      if Len /= Get_Nbr_Elements (R_List) then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                          "length of left and right operands mismatch");
         Res := Build_Overflow (Expr);
      else
         Res_List := Create_Iir_Flist (Len);

         case Func is
            when Iir_Predefined_TF_Array_And =>
               for I in 0 .. Len - 1 loop
                  El := Get_Nth_Element (L_List, I);
                  case Get_Enum_Pos (El) is
                     when 0 =>
                        null;
                     when 1 =>
                        El := Get_Nth_Element (R_List, I);
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (Res_List, I, El);
               end loop;
            when Iir_Predefined_TF_Array_Nand =>
               for I in 0 .. Len - 1 loop
                  El := Get_Nth_Element (L_List, I);
                  case Get_Enum_Pos (El) is
                     when 0 =>
                        El := Cst_1;
                     when 1 =>
                        El := Get_Nth_Element (R_List, I);
                        case Get_Enum_Pos (El) is
                           when 0 =>
                              El := Cst_1;
                           when 1 =>
                              El := Cst_0;
                           when others =>
                              raise Internal_Error;
                        end case;
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (Res_List, I, El);
               end loop;
            when Iir_Predefined_TF_Array_Or =>
               for I in 0 .. Len - 1 loop
                  El := Get_Nth_Element (L_List, I);
                  case Get_Enum_Pos (El) is
                     when 1 =>
                        null;
                     when 0 =>
                        El := Get_Nth_Element (R_List, I);
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (Res_List, I, El);
               end loop;
            when Iir_Predefined_TF_Array_Nor =>
               for I in 0 .. Len - 1 loop
                  El := Get_Nth_Element (L_List, I);
                  case Get_Enum_Pos (El) is
                     when 1 =>
                        El := Cst_0;
                     when 0 =>
                        El := Get_Nth_Element (R_List, I);
                        case Get_Enum_Pos (El) is
                           when 0 =>
                              El := Cst_1;
                           when 1 =>
                              El := Cst_0;
                           when others =>
                              raise Internal_Error;
                        end case;
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (Res_List, I, El);
               end loop;
            when Iir_Predefined_TF_Array_Xor =>
               for I in 0 .. Len - 1 loop
                  El := Get_Nth_Element (L_List, I);
                  case Get_Enum_Pos (El) is
                     when 1 =>
                        El := Get_Nth_Element (R_List, I);
                        case Get_Enum_Pos (El) is
                           when 0 =>
                              El := Cst_1;
                           when 1 =>
                              El := Cst_0;
                           when others =>
                              raise Internal_Error;
                        end case;
                     when 0 =>
                        El := Get_Nth_Element (R_List, I);
                     when others =>
                        raise Internal_Error;
                  end case;
                  Set_Nth_Element (Res_List, I, El);
               end loop;
            when others =>
               Error_Internal (Expr, "eval_dyadic_bit_array_functions: " &
                                 Iir_Predefined_Functions'Image (Func));
         end case;

         Res := Build_Simple_Aggregate (Res_List, Expr, Expr_Type);
      end if;

      Free_Eval_Static_Expr (Left_Val, Left);
      Free_Eval_Static_Expr (Right_Val, Right);

      --  The unconstrained type is replaced by the constrained one.
      Set_Type (Res, Get_Type (Left));
      return Res;
   end Eval_Dyadic_Bit_Array_Operator;

   --  Return TRUE if VAL /= 0.
   function Check_Integer_Division_By_Zero (Expr : Iir; Val : Iir)
                                           return Boolean
   is
   begin
      if Get_Value (Val) = 0 then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Expr, "division by 0");
         return False;
      else
         return True;
      end if;
   end Check_Integer_Division_By_Zero;

   function Eval_Shift_Operator
     (Left, Right : Iir; Origin : Iir; Func : Iir_Predefined_Shift_Functions)
     return Iir
   is
      Count : constant Int64 := Get_Value (Right);
      Arr_List : constant Iir_Flist := Get_Simple_Aggregate_List (Left);
      Len : constant Natural := Get_Nbr_Elements (Arr_List);
      Cnt : Natural;
      Res_List : Iir_Flist;
      Dir_Left : Boolean;
      E : Iir;
   begin
      --  LRM93 7.2.3
      --  That is, if R is 0 or if L is a null array, the return value is L.
      if Count = 0 or Len = 0 then
         return Build_Simple_Aggregate (Arr_List, Origin, Get_Type (Left));
      end if;
      case Func is
         when Iir_Predefined_Array_Sll
           | Iir_Predefined_Array_Sla
           | Iir_Predefined_Array_Rol =>
            Dir_Left := True;
         when Iir_Predefined_Array_Srl
           | Iir_Predefined_Array_Sra
           | Iir_Predefined_Array_Ror =>
            Dir_Left := False;
      end case;
      if Count < 0 then
         Cnt := Natural (-Count);
         Dir_Left := not Dir_Left;
      else
         Cnt := Natural (Count);
      end if;

      case Func is
         when Iir_Predefined_Array_Sll
           | Iir_Predefined_Array_Srl =>
            declare
               Enum_List : constant Iir_Flist :=
                 Get_Enumeration_Literal_List
                 (Get_Base_Type (Get_Element_Subtype (Get_Type (Left))));
            begin
               E := Get_Nth_Element (Enum_List, 0);
            end;
         when Iir_Predefined_Array_Sla
           | Iir_Predefined_Array_Sra =>
            if Dir_Left then
               E := Get_Nth_Element (Arr_List, Len - 1);
            else
               E := Get_Nth_Element (Arr_List, 0);
            end if;
         when Iir_Predefined_Array_Rol
           | Iir_Predefined_Array_Ror =>
            Cnt := Cnt mod Len;
            if not Dir_Left then
               Cnt := (Len - Cnt) mod Len;
            end if;
      end case;

      Res_List := Create_Iir_Flist (Len);

      case Func is
         when Iir_Predefined_Array_Sll
           | Iir_Predefined_Array_Srl
           | Iir_Predefined_Array_Sla
           | Iir_Predefined_Array_Sra =>
            if Dir_Left then
               if Cnt < Len then
                  for I in Cnt .. Len - 1 loop
                     Set_Nth_Element
                       (Res_List, I - Cnt, Get_Nth_Element (Arr_List, I));
                  end loop;
               else
                  Cnt := Len;
               end if;
               for I in 0 .. Cnt - 1 loop
                  Set_Nth_Element (Res_List, Len - Cnt + I, E);
               end loop;
            else
               if Cnt > Len then
                  Cnt := Len;
               end if;
               for I in 0 .. Cnt - 1 loop
                  Set_Nth_Element (Res_List, I, E);
               end loop;
               for I in Cnt .. Len - 1 loop
                  Set_Nth_Element
                    (Res_List, I, Get_Nth_Element (Arr_List, I - Cnt));
               end loop;
            end if;
         when Iir_Predefined_Array_Rol
           | Iir_Predefined_Array_Ror =>
            for I in 1 .. Len loop
               Set_Nth_Element
                 (Res_List, I - 1, Get_Nth_Element (Arr_List, Cnt));
               Cnt := Cnt + 1;
               if Cnt = Len then
                  Cnt := 0;
               end if;
            end loop;
      end case;
      return Build_Simple_Aggregate (Res_List, Origin, Get_Type (Left));
   end Eval_Shift_Operator;

   --  Concatenate all the elements of OPERANDS.
   --  The first element of OPERANDS is the rightest one, the last the
   --  leftest one.  All the elements are concatenation operators.
   --  All the elements are static.
   function Eval_Concatenation (Operands : Iir_Array) return Iir
   is
      pragma Assert (Operands'First = 1);
      Orig : constant Iir := Operands (1);
      Origin_Type : constant Iir := Get_Type (Orig);

      Ops_Val : Iir_Array (Operands'Range);
      Str_Lits : Iir_Array (Operands'Range);
      Left_Op : Iir;
      Left_Val : Iir;
      Left_Lit : Iir;
      Res_List : Iir_Flist;
      Res_Len : Natural;
      Res_Type : Iir;
      Def, Left_Def : Iir_Predefined_Functions;
      Op : Iir;
      El : Iir;
      El_List : Iir_Flist;
      El_Len : Natural;
      Err_Orig : Iir;

      --  To compute the index range of the result for vhdl87.
      Leftest_Non_Null : Iir;
      Bounds_From_Subtype : Boolean;
   begin
      --  Eval operands, compute length of the result.
      Err_Orig := Null_Iir;
      Res_Len := 0;
      for I in Operands'Range loop
         Op := Operands (I);
         Def := Get_Implicit_Definition (Get_Implementation (Op));
         if Get_Kind (Op) = Iir_Kind_Function_Call then
            El := Get_Actual
              (Get_Chain (Get_Parameter_Association_Chain (Op)));
         else
            El := Get_Right (Op);
         end if;
         Ops_Val (I) := Eval_Static_Expr (El);
         if Is_Overflow_Literal (Ops_Val (I)) then
            Err_Orig := El;
         else
            case Iir_Predefined_Concat_Functions (Def) is
               when Iir_Predefined_Array_Element_Concat
                 | Iir_Predefined_Element_Element_Concat =>
                  Res_Len := Res_Len + 1;
               when Iir_Predefined_Element_Array_Concat
                 | Iir_Predefined_Array_Array_Concat =>
                  Str_Lits (I) := Eval_String_Literal (Ops_Val (I));
                  El_List := Get_Simple_Aggregate_List (Str_Lits (I));
                  Res_Len := Res_Len + Get_Nbr_Elements (El_List);
            end case;
         end if;
      end loop;

      Op := Operands (Operands'Last);
      if Get_Kind (Op) = Iir_Kind_Function_Call then
         Left_Op := Get_Actual (Get_Parameter_Association_Chain (Op));
      else
         Left_Op := Get_Left (Op);
      end if;
      Left_Val := Eval_Static_Expr (Left_Op);
      if Is_Overflow_Literal (Left_Val) then
         Err_Orig := Left_Op;
      else
         Left_Def := Def;
         case Iir_Predefined_Concat_Functions (Left_Def) is
            when Iir_Predefined_Element_Array_Concat
              | Iir_Predefined_Element_Element_Concat =>
               Res_Len := Res_Len + 1;
            when Iir_Predefined_Array_Element_Concat
              | Iir_Predefined_Array_Array_Concat =>
               Left_Lit := Eval_String_Literal (Left_Val);
               El_List := Get_Simple_Aggregate_List (Left_Lit);
               Res_Len := Res_Len + Get_Nbr_Elements (El_List);
         end case;
      end if;

      --  Handle overflow.
      if Err_Orig /= Null_Iir then
         --  Free all.
         for I in Ops_Val'Range loop
            Free_Eval_Static_Expr (Ops_Val (I), Operands (I));
         end loop;
         Free_Eval_Static_Expr (Left_Val, Left_Op);

         return Build_Overflow (Err_Orig);
      end if;

      Res_List := Create_Iir_Flist (Res_Len);

      --  Do the concatenation.
      --  Left:
      Leftest_Non_Null := Null_Iir;
      case Iir_Predefined_Concat_Functions (Left_Def) is
         when Iir_Predefined_Element_Array_Concat
           | Iir_Predefined_Element_Element_Concat =>
            Set_Nth_Element (Res_List, 0, Left_Val);
            Bounds_From_Subtype := True;
            Res_Len := 1;
         when Iir_Predefined_Array_Element_Concat
           | Iir_Predefined_Array_Array_Concat =>
            El_List := Get_Simple_Aggregate_List (Left_Lit);
            Res_Len := Get_Nbr_Elements (El_List);
            for I in 0 .. Res_Len - 1 loop
               Set_Nth_Element (Res_List, I, Get_Nth_Element (El_List, I));
            end loop;
            Bounds_From_Subtype := Def = Iir_Predefined_Array_Element_Concat;
            if Res_Len > 0 then
               Leftest_Non_Null := Get_Type (Left_Lit);
            end if;
            Free_Eval_String_Literal (Left_Lit, Left_Val);
      end case;

      --  Right:
      for I in reverse Operands'Range loop
         Def := Get_Implicit_Definition (Get_Implementation (Operands (I)));
         case Iir_Predefined_Concat_Functions (Def) is
            when Iir_Predefined_Array_Element_Concat
              | Iir_Predefined_Element_Element_Concat =>
               Set_Nth_Element (Res_List, Res_Len, Ops_Val (I));
               Bounds_From_Subtype := True;
               Res_Len := Res_Len + 1;
            when Iir_Predefined_Element_Array_Concat
              | Iir_Predefined_Array_Array_Concat =>
               El_List := Get_Simple_Aggregate_List (Str_Lits (I));
               El_Len := Get_Nbr_Elements (El_List);
               for I in 0 .. El_Len - 1 loop
                  Set_Nth_Element
                    (Res_List, Res_Len + I, Get_Nth_Element (El_List, I));
               end loop;
               Bounds_From_Subtype := Bounds_From_Subtype
                 or Def = Iir_Predefined_Element_Array_Concat;
               if Leftest_Non_Null = Null_Iir and then El_Len /= 0 then
                  Leftest_Non_Null := Get_Type (Ops_Val (I));
               end if;
               Free_Eval_String_Literal (Str_Lits (I), Ops_Val (I));
               Res_Len := Res_Len + El_Len;
         end case;
      end loop;

      --  Compute subtype...
      if Flags.Vhdl_Std > Vhdl_87 then
         --  LRM93 7.2.4
         --  If both operands are null arrays, then the result of the
         --  concatenation is the right operand.
         if Res_Len = 0 then
            Res_Type := Get_Type (Get_Right (Operands (1)));
         else
            --  LRM93 7.2.4
            --  Otherwise, the direction and bounds of the result are
            --  determined as follows: let S be the index subtype of the base
            --  type of the result.  The direction of the result of the
            --  concatenation is the direction of S, and the left bound of the
            --  result is S'LEFT.
            Res_Type := Create_Unidim_Array_By_Length
              (Origin_Type, Int64 (Res_Len), Orig);
         end if;
      else
         --  LRM87 7.2.3
         --  The left bound of the result is the left operand, [...]
         --
         --  LRM87 7.2.3
         --  The direction of the result is the direction of the left
         --  operand, [...]
         --
         --  LRM87 7.2.3
         --  [...], unless the left operand is a null array, in which case
         --  the result of the concatenation is the right operand.

         --  Look for the first operand that is either an element or
         --  a non-null array.  If it is an element, create the bounds
         --  by length.  If it is an array, create the bounds from it.  If
         --  there is no such operand, use the leftest operands for the
         --  bounds.
         if Bounds_From_Subtype then
            --  There is at least one concatenation with an element.
            Res_Type := Create_Unidim_Array_By_Length
              (Origin_Type, Int64 (Res_Len), Orig);
         else
            if Res_Len = 0 then
               Res_Type := Get_Type (Get_Right (Operands (1)));
            else
               declare
                  Left_Index : constant Iir :=
                    Get_Index_Type (Leftest_Non_Null, 0);
                  Left_Range : constant Iir :=
                    Get_Range_Constraint (Left_Index);
                  Ret_Type : constant Iir :=
                    Get_Return_Type (Get_Implementation (Orig));
                  Rng_Type : constant Iir := Get_Index_Type (Ret_Type, 0);
                  A_Range : Iir;
                  Index_Type : Iir;
               begin
                  A_Range := Create_Iir (Iir_Kind_Range_Expression);
                  Location_Copy (A_Range, Orig);
                  Set_Type (A_Range, Rng_Type);
                  Set_Expr_Staticness (A_Range, Locally);
                  Set_Left_Limit (A_Range, Get_Left_Limit (Left_Range));
                  Set_Direction (A_Range, Get_Direction (Left_Range));
                  Set_Right_Limit_By_Length (A_Range, Int64 (Res_Len));

                  Index_Type := Create_Range_Subtype_From_Type
                    (Rng_Type, Get_Location (Orig));
                  Set_Range_Constraint (Index_Type, A_Range);
                  Res_Type := Create_Unidim_Array_From_Index
                    (Origin_Type, Index_Type, Orig);
               end;
            end if;
         end if;
      end if;

      for I in Ops_Val'Range loop
         Free_Eval_Static_Expr (Ops_Val (I), Operands (I));
      end loop;
      Free_Eval_Static_Expr (Left_Val, Left_Op);

      --  FIXME: this is not necessarily a string, it may be an aggregate if
      --  element type is not a character type.
      return Build_Simple_Aggregate (Res_List, Orig, Res_Type, Res_Type);
   end Eval_Concatenation;

   function Eval_Scalar_Compare (Left, Right : Iir) return Compare_Type
   is
      Ltype : constant Iir := Get_Base_Type (Get_Type (Left));
   begin
      pragma Assert
        (Get_Kind (Ltype) = Get_Kind (Get_Base_Type (Get_Type (Right))));

      case Get_Kind (Ltype) is
         when Iir_Kind_Enumeration_Type_Definition =>
            declare
               L_Pos : constant Iir_Int32 := Get_Enum_Pos (Left);
               R_Pos : constant Iir_Int32 := Get_Enum_Pos (Right);
            begin
               if L_Pos = R_Pos then
                  return Compare_Eq;
               else
                  if L_Pos < R_Pos then
                     return Compare_Lt;
                  else
                     return Compare_Gt;
                  end if;
               end if;
            end;
         when Iir_Kind_Physical_Type_Definition =>
            declare
               L_Val : constant Int64 := Get_Physical_Value (Left);
               R_Val : constant Int64 := Get_Physical_Value (Right);
            begin
               if L_Val = R_Val then
                  return Compare_Eq;
               else
                  if L_Val < R_Val then
                     return Compare_Lt;
                  else
                     return Compare_Gt;
                  end if;
               end if;
            end;
         when Iir_Kind_Integer_Type_Definition =>
            declare
               L_Val : constant Int64 := Get_Value (Left);
               R_Val : constant Int64 := Get_Value (Right);
            begin
               if L_Val = R_Val then
                  return Compare_Eq;
               else
                  if L_Val < R_Val then
                     return Compare_Lt;
                  else
                     return Compare_Gt;
                  end if;
               end if;
            end;
         when Iir_Kind_Floating_Type_Definition =>
            declare
               L_Val : constant Fp64 := Get_Fp_Value (Left);
               R_Val : constant Fp64 := Get_Fp_Value (Right);
            begin
               if L_Val = R_Val then
                  return Compare_Eq;
               else
                  if L_Val < R_Val then
                     return Compare_Lt;
                  else
                     return Compare_Gt;
                  end if;
               end if;
            end;
         when others =>
            Error_Kind ("eval_scalar_compare", Ltype);
      end case;
   end Eval_Scalar_Compare;

   function Eval_Array_Compare (Left, Right : Iir) return Compare_Type is
   begin
      if Get_Kind (Left) = Iir_Kind_String_Literal8
        and then Get_Kind (Right) = Iir_Kind_String_Literal8
      then
         --  Common case: both parameters are strings.
         declare
            L_Id : constant String8_Id := Get_String8_Id (Left);
            R_Id : constant String8_Id := Get_String8_Id (Right);
            L_Len : constant Int32 := Get_String_Length (Left);
            R_Len : constant Int32 := Get_String_Length (Right);
            L_El, R_El : Nat8;
            P : Nat32;
         begin
            P := 1;
            while P <= L_Len and P <= R_Len loop
               L_El := Str_Table.Element_String8 (L_Id, P);
               R_El := Str_Table.Element_String8 (R_Id, P);
               if L_El /= R_El then
                  if L_El < R_El then
                     return Compare_Lt;
                  else
                     return Compare_Gt;
                  end if;
               end if;
               P := P + 1;
            end loop;
            if L_Len = R_Len then
               return Compare_Eq;
            elsif L_Len < R_Len then
               return Compare_Lt;
            else
               return Compare_Gt;
            end if;
         end;
      else
         --  General case.
         declare
            Left_Val, Right_Val : Iir;
            R_List, L_List : Iir_Flist;
            R_Len, L_Len : Natural;
            P : Natural;
            Res : Compare_Type;
         begin
            Left_Val := Eval_String_Literal (Left);
            Right_Val := Eval_String_Literal (Right);

            L_List := Get_Simple_Aggregate_List (Left_Val);
            R_List := Get_Simple_Aggregate_List (Right_Val);
            L_Len := Get_Nbr_Elements (L_List);
            R_Len := Get_Nbr_Elements (R_List);

            Res := Compare_Eq;
            P := 0;
            while P < L_Len and P < R_Len loop
               Res := Eval_Scalar_Compare (Get_Nth_Element (L_List, P),
                                             Get_Nth_Element (R_List, P));
               exit when Res /= Compare_Eq;
               P := P + 1;
            end loop;
            if Res = Compare_Eq then
               if L_Len < R_Len then
                  Res := Compare_Lt;
               elsif L_Len > R_Len then
                  Res := Compare_Gt;
               end if;
            end if;

            Free_Eval_Static_Expr (Left_Val, Left);
            Free_Eval_Static_Expr (Right_Val, Right);

            return Res;
         end;
      end if;
   end Eval_Array_Compare;

   function Eval_Logic_Match_Equality (L, R : Iir_Int32; Loc : Iir)
                                      return Iir_Index32
   is
      use Vhdl.Ieee.Std_Logic_1164;
      Lb, Rb : Boolean;
   begin
      if L = Std_Logic_D_Pos or R = Std_Logic_D_Pos then
         Warning_Msg_Sem
           (Warnid_Analyze_Assert, +Loc,
            "STD_LOGIC_1164: '-' operand for matching ordering operator");
         return Std_Logic_1_Pos;
      end if;
      if L = Std_Logic_U_Pos or R = Std_Logic_U_Pos then
         return Std_Logic_U_Pos;
      end if;
      if L = Std_Logic_X_Pos
        or L = Std_Logic_Z_Pos
        or L = Std_Logic_W_Pos
      then
         return Std_Logic_X_Pos;
      end if;
      if R = Std_Logic_X_Pos
        or R = Std_Logic_Z_Pos
        or R = Std_Logic_W_Pos
      then
         return Std_Logic_X_Pos;
      end if;
      Lb := L = Std_Logic_1_Pos or L = Std_Logic_H_Pos;
      Rb := R = Std_Logic_1_Pos or R = Std_Logic_H_Pos;
      if Lb = Rb then
         return Std_Logic_1_Pos;
      else
         return Std_Logic_0_Pos;
      end if;
   end Eval_Logic_Match_Equality;

   function Eval_Logic_Or (L, R : Iir_Index32) return Iir_Index32
   is
      use Vhdl.Ieee.Std_Logic_1164;
   begin
      if L = Std_Logic_1_Pos or L = Std_Logic_H_Pos
        or R = Std_Logic_1_Pos or R = Std_Logic_H_Pos
      then
         return Std_Logic_1_Pos;
      elsif (L = Std_Logic_0_Pos or L = Std_Logic_L_Pos)
        and (R = Std_Logic_0_Pos or R = Std_Logic_L_Pos)
      then
         return Std_Logic_0_Pos;
      elsif L = Std_Logic_U_Pos or R = Std_Logic_U_Pos then
         return Std_Logic_U_Pos;
      else
         return Std_Logic_X_Pos;
      end if;
   end Eval_Logic_Or;

   function Eval_Logic_Not (X : Iir_Index32) return Iir_Index32
   is
      use Vhdl.Ieee.Std_Logic_1164;
   begin
      if X = Std_Logic_0_Pos or X = Std_Logic_L_Pos then
         return Std_Logic_1_Pos;
      elsif X = Std_Logic_1_Pos or X = Std_Logic_H_Pos then
         return Std_Logic_0_Pos;
      elsif X = Std_Logic_U_Pos then
         return Std_Logic_U_Pos;
      else
         return Std_Logic_X_Pos;
      end if;
   end Eval_Logic_Not;

   function Eval_Logic_Match_Inequality (L, R : Iir_Int32; Loc : Iir)
                                         return Iir_Index32
   is
      E : Iir_Index32;
   begin
      --  Defined as the not operator applied to the equal operator
      E := Eval_Logic_Match_Equality (L, R, Loc);
      return Eval_Logic_Not (E);
   end Eval_Logic_Match_Inequality;

   function Eval_Logic_Match_Less (L, R : Iir_Int32; Loc : Iir)
                                   return Iir_Index32
   is
      use Vhdl.Ieee.Std_Logic_1164;
   begin
      --  LRM19 9.2.3 table
      --  '-' always returns 'X'
      if L = Std_Logic_D_Pos or R = Std_Logic_D_Pos then
         Warning_Msg_Sem
           (Warnid_Analyze_Assert, +Loc,
            "STD_LOGIC_1164: '-' operand for matching ordering operator");
         return Std_Logic_X_Pos;
      end if;

      --  'U' always returns 'U'
      if L = Std_Logic_U_Pos or R = Std_Logic_U_Pos then
         return Std_Logic_U_Pos;
      end if;

      --  Only when R is '1' or 'H' will we ever return '1'
      if R = Std_Logic_1_Pos or R = Std_Logic_H_Pos then
         if L = Std_Logic_0_Pos or L = Std_Logic_L_Pos then
            --  L = [0,L] R = [1,H]
            return Std_Logic_1_Pos;
         elsif L = Std_Logic_1_Pos or L = Std_Logic_H_Pos then
            --  L = [1,H] R = [1,H]
            return Std_Logic_0_Pos;
         else
            --  Everything else is 'X'
            return Std_Logic_X_Pos;
         end if;
      elsif R = Std_Logic_0_Pos or R = Std_Logic_L_Pos then
         --  R = [0,1]
         return Std_Logic_0_Pos;
      else
         --  Everything else is 'X'
         return Std_Logic_X_Pos;
      end if;
   end Eval_Logic_Match_Less;

   function Eval_Logic_Match_Less_Equal (L, R : Iir_Int32; Loc : Iir)
                                         return Iir_Index32
   is
      Less : Iir_Index32;
      Equal : Iir_Index32;
   begin
      --  LRM19 9.2.3
      --  ?<= is defined as (< or =)
      Less := Eval_Logic_Match_Less (L, R, Loc);
      Equal := Eval_Logic_Match_Equality (L, R, Loc);
      return Eval_Logic_Or (Less, Equal);
   end Eval_Logic_Match_Less_Equal;

   function Eval_Logic_Match_Greater (L, R : Iir_Int32; Loc : Iir)
                                      return Iir_Index32
   is
      Le : Iir_Index32;
   begin
      --  LRM19 9.2.3
      --  ?> is defined as not(?<=)
      Le := Eval_Logic_Match_Less_Equal (L, R, Loc);
      return Eval_Logic_Not (Le);
   end Eval_Logic_Match_Greater;

   function Eval_Logic_Match_Greater_Equal (L, R : Iir_Int32; Loc : Iir)
                                            return Iir_Index32
   is
      Less : Iir_Index32;
   begin
      --  LRM19 9.2.3
      --  ?>= is defined as not(?<)
      Less := Eval_Logic_Match_Less (L, R, Loc);
      return Eval_Logic_Not (Less);
   end Eval_Logic_Match_Greater_Equal;

   function Eval_Equality (Left, Right : Iir) return Boolean;

   --  CHOICES is a chain of choice from a record aggregate; FEL is an Flist
   --  whose length is the number of element of the record type.
   --  Fill FEL with the associated expressions from CHOICES, so that it is
   --  easier to deal than the aggregate as elements are ordered.
   procedure Fill_Flist_From_Record_Aggregate (Choices : Iir; Fel : Iir_Flist)
   is
      Pos : Natural;
      Ch : Iir;
      Expr : Iir;
   begin
      Pos := 0;
      Ch := Choices;
      while Ch /= Null_Iir loop
         Expr := Get_Associated_Expr (Ch);
         case Iir_Kinds_Record_Choice (Get_Kind (Ch)) is
            when Iir_Kind_Choice_By_None =>
               Set_Nth_Element (Fel, Pos, Expr);
               Pos := Pos + 1;
            when Iir_Kind_Choice_By_Name =>
               Pos := Natural (Get_Element_Position
                                 (Get_Named_Entity (Get_Choice_Name (Ch))));
               Set_Nth_Element (Fel, Pos, Expr);
            when Iir_Kind_Choice_By_Others =>
               for I in 0 .. Get_Nbr_Elements (Fel) - 1 loop
                  if Get_Nth_Element (Fel, I) = Null_Iir then
                     Set_Nth_Element (Fel, I, Expr);
                  end if;
               end loop;
         end case;
         Ch := Get_Chain (Ch);
      end loop;
   end Fill_Flist_From_Record_Aggregate;

   function Eval_Record_Equality (Left, Right : Iir) return Boolean
   is
      pragma Assert (Get_Kind (Left) = Iir_Kind_Aggregate);
      pragma Assert (Get_Kind (Right) = Iir_Kind_Aggregate);
      Lch, Rch : Iir;
   begin
      Lch := Get_Association_Choices_Chain (Left);
      Rch := Get_Association_Choices_Chain (Right);

      if Get_Kind (Lch) = Iir_Kind_Choice_By_None
        and then Get_Kind (Rch) = Iir_Kind_Choice_By_None
      then
         --  All choices are positionnal.
         while Lch /= Null_Iir loop
            pragma Assert (Rch /= Null_Iir);
            pragma Assert (Get_Kind (Lch) = Iir_Kind_Choice_By_None);
            pragma Assert (Get_Kind (Rch) = Iir_Kind_Choice_By_None);
            if not Eval_Equality (Get_Associated_Expr (Lch),
                                  Get_Associated_Expr (Rch))
            then
               return False;
            end if;
            Lch := Get_Chain (Lch);
            Rch := Get_Chain (Rch);
         end loop;
         pragma Assert (Rch = Null_Iir);
         return True;
      else
         declare
            Els : constant Iir_Flist :=
              Get_Elements_Declaration_List (Get_Type (Left));
            Nels : constant Natural := Get_Nbr_Elements (Els);
            Lel, Rel : Iir_Flist;
            Res : Boolean;
         begin
            Lel := Create_Iir_Flist (Nels);
            Rel := Create_Iir_Flist (Nels);
            Fill_Flist_From_Record_Aggregate (Lch, Lel);
            Fill_Flist_From_Record_Aggregate (Rch, Rel);

            Res := True;
            for I in 0 .. Nels - 1 loop
               if not Eval_Equality (Get_Nth_Element (Lel, I),
                                     Get_Nth_Element (Rel, I))
               then
                  Res := False;
                  exit;
               end if;
            end loop;

            Destroy_Iir_Flist (Lel);
            Destroy_Iir_Flist (Rel);

            return Res;
         end;
      end if;
   end Eval_Record_Equality;

   function Eval_Equality (Left, Right : Iir) return Boolean
   is
      Ltype : constant Iir := Get_Base_Type (Get_Type (Left));
   begin
      pragma Assert
        (Get_Kind (Ltype) = Get_Kind (Get_Base_Type (Get_Type (Right))));

      case Get_Kind (Ltype) is
         when Iir_Kind_Enumeration_Type_Definition =>
            return Get_Enum_Pos (Left) = Get_Enum_Pos (Right);
         when Iir_Kind_Physical_Type_Definition =>
            return Get_Physical_Value (Left) = Get_Physical_Value (Right);
         when Iir_Kind_Integer_Type_Definition =>
            return Get_Value (Left) = Get_Value (Right);
         when Iir_Kind_Floating_Type_Definition =>
            return Get_Fp_Value (Left) = Get_Fp_Value (Right);
         when Iir_Kind_Array_Type_Definition =>
            return Eval_Array_Compare (Left, Right) = Compare_Eq;
         when Iir_Kind_Record_Type_Definition =>
            return Eval_Record_Equality (Left, Right);
         when others =>
            Error_Kind ("eval_equality", Ltype);
      end case;
   end Eval_Equality;

   --  ORIG is either a dyadic operator or a function call.
   function Eval_Dyadic_Operator (Orig : Iir; Imp : Iir; Left, Right : Iir)
                                 return Iir
   is
      pragma Unsuppress (Overflow_Check);
      Func : constant Iir_Predefined_Functions :=
        Get_Implicit_Definition (Imp);
   begin
      if Is_Overflow_Literal (Left) or else Is_Overflow_Literal (Right) then
         return Build_Overflow (Orig);
      end if;

      case Func is
         when Iir_Predefined_Integer_Plus =>
            return Build_Integer_Check
              (Get_Value (Left) + Get_Value (Right), Orig);
         when Iir_Predefined_Integer_Minus =>
            return Build_Integer_Check
              (Get_Value (Left) - Get_Value (Right), Orig);
         when Iir_Predefined_Integer_Mul =>
            return Build_Integer_Check
              (Get_Value (Left) * Get_Value (Right), Orig);
         when Iir_Predefined_Integer_Div =>
            if Check_Integer_Division_By_Zero (Orig, Right) then
               return Build_Integer_Check
                 (Get_Value (Left) / Get_Value (Right), Orig);
            else
               return Build_Overflow (Orig);
            end if;
         when Iir_Predefined_Integer_Mod =>
            if Check_Integer_Division_By_Zero (Orig, Right) then
               return Build_Integer_Check
                 (Get_Value (Left) mod Get_Value (Right), Orig);
            else
               return Build_Overflow (Orig);
            end if;
         when Iir_Predefined_Integer_Rem =>
            if Check_Integer_Division_By_Zero (Orig, Right) then
               return Build_Integer_Check
                 (Get_Value (Left) rem Get_Value (Right), Orig);
            else
               return Build_Overflow (Orig);
            end if;
         when Iir_Predefined_Integer_Exp =>
            return Build_Integer_Check
              (Get_Value (Left) ** Integer (Get_Value (Right)), Orig);

         when Iir_Predefined_Integer_Equality =>
            return Build_Boolean (Get_Value (Left) = Get_Value (Right));
         when Iir_Predefined_Integer_Inequality =>
            return Build_Boolean (Get_Value (Left) /= Get_Value (Right));
         when Iir_Predefined_Integer_Greater_Equal =>
            return Build_Boolean (Get_Value (Left) >= Get_Value (Right));
         when Iir_Predefined_Integer_Greater =>
            return Build_Boolean (Get_Value (Left) > Get_Value (Right));
         when Iir_Predefined_Integer_Less_Equal =>
            return Build_Boolean (Get_Value (Left) <= Get_Value (Right));
         when Iir_Predefined_Integer_Less =>
            return Build_Boolean (Get_Value (Left) < Get_Value (Right));

         when Iir_Predefined_Integer_Minimum =>
            if Get_Value (Left) < Get_Value (Right) then
               return Left;
            else
               return Right;
            end if;
         when Iir_Predefined_Integer_Maximum =>
            if Get_Value (Left) > Get_Value (Right) then
               return Left;
            else
               return Right;
            end if;

         when Iir_Predefined_Floating_Equality =>
            return Build_Boolean (Get_Fp_Value (Left) = Get_Fp_Value (Right));
         when Iir_Predefined_Floating_Inequality =>
            return Build_Boolean (Get_Fp_Value (Left) /= Get_Fp_Value (Right));
         when Iir_Predefined_Floating_Greater =>
            return Build_Boolean (Get_Fp_Value (Left) > Get_Fp_Value (Right));
         when Iir_Predefined_Floating_Greater_Equal =>
            return Build_Boolean (Get_Fp_Value (Left) >= Get_Fp_Value (Right));
         when Iir_Predefined_Floating_Less =>
            return Build_Boolean (Get_Fp_Value (Left) < Get_Fp_Value (Right));
         when Iir_Predefined_Floating_Less_Equal =>
            return Build_Boolean (Get_Fp_Value (Left) <= Get_Fp_Value (Right));

         when Iir_Predefined_Floating_Minus =>
            return Build_Floating
              (Get_Fp_Value (Left) - Get_Fp_Value (Right), Orig);
         when Iir_Predefined_Floating_Plus =>
            return Build_Floating
              (Get_Fp_Value (Left) + Get_Fp_Value (Right), Orig);
         when Iir_Predefined_Floating_Mul =>
            return Build_Floating
              (Get_Fp_Value (Left) * Get_Fp_Value (Right), Orig);
         when Iir_Predefined_Floating_Div =>
            if Get_Fp_Value (Right) = 0.0 then
               Warning_Msg_Sem (Warnid_Runtime_Error, +Orig,
                                "right operand of division is 0");
               return Build_Overflow (Orig);
            else
               return Build_Floating
                 (Get_Fp_Value (Left) / Get_Fp_Value (Right), Orig);
            end if;
         when Iir_Predefined_Floating_Exp =>
            declare
               Exp : Int64;
               Res : Fp64;
               Val : Fp64;
            begin
               Res := 1.0;
               Val := Get_Fp_Value (Left);
               --  LRM08 9.2.8 Misellaneous operators
               --  Exponentiation with an integer exponent is equivalent to
               --  repeated multiplication of the left operand by itself for
               --  a number of times indicated by the absolute value of the
               --  exponent and from left to right; [...]
               --  GHDL: use the standard power-of-2 approach.  This is not
               --  strictly equivalent however.
               Exp := abs Get_Value (Right);
               while Exp /= 0 loop
                  if Exp mod 2 = 1 then
                     Res := Res * Val;
                  end if;
                  Exp := Exp / 2;
                  Val := Val * Val;
               end loop;
               --  LRM08 9.2.8 Misellaneous operators
               --  [...] if the exponent is negative then the result is the
               --  reciprocal of that [...]
               if Get_Value (Right) < 0 then
                  Res := 1.0 / Res;
               end if;
               return Build_Floating (Res, Orig);
            end;

         when Iir_Predefined_Floating_Minimum =>
            if Get_Fp_Value (Left) < Get_Fp_Value (Right) then
               return Left;
            else
               return Right;
            end if;
         when Iir_Predefined_Floating_Maximum =>
            if Get_Fp_Value (Left) > Get_Fp_Value (Right) then
               return Left;
            else
               return Right;
            end if;

         when Iir_Predefined_Physical_Equality =>
            return Build_Boolean
              (Get_Physical_Value (Left) = Get_Physical_Value (Right));
         when Iir_Predefined_Physical_Inequality =>
            return Build_Boolean
              (Get_Physical_Value (Left) /= Get_Physical_Value (Right));
         when Iir_Predefined_Physical_Greater_Equal =>
            return Build_Boolean
              (Get_Physical_Value (Left) >= Get_Physical_Value (Right));
         when Iir_Predefined_Physical_Greater =>
            return Build_Boolean
              (Get_Physical_Value (Left) > Get_Physical_Value (Right));
         when Iir_Predefined_Physical_Less_Equal =>
            return Build_Boolean
              (Get_Physical_Value (Left) <= Get_Physical_Value (Right));
         when Iir_Predefined_Physical_Less =>
            return Build_Boolean
              (Get_Physical_Value (Left) < Get_Physical_Value (Right));

         when Iir_Predefined_Physical_Physical_Div =>
            return Build_Integer
              (Get_Physical_Value (Left) / Get_Physical_Value (Right), Orig);
         when Iir_Predefined_Physical_Integer_Div =>
            return Build_Physical
              (Get_Physical_Value (Left) / Get_Value (Right), Orig);
         when Iir_Predefined_Physical_Minus =>
            return Build_Physical
              (Get_Physical_Value (Left) - Get_Physical_Value (Right), Orig);
         when Iir_Predefined_Physical_Plus =>
            return Build_Physical
              (Get_Physical_Value (Left) + Get_Physical_Value (Right), Orig);
         when Iir_Predefined_Integer_Physical_Mul =>
            return Build_Physical
              (Get_Value (Left) * Get_Physical_Value (Right), Orig);
         when Iir_Predefined_Physical_Integer_Mul =>
            return Build_Physical
              (Get_Physical_Value (Left) * Get_Value (Right), Orig);
         when Iir_Predefined_Real_Physical_Mul =>
            --  FIXME: overflow??
            return Build_Physical
              (Int64 (Get_Fp_Value (Left)
                          * Fp64 (Get_Physical_Value (Right))), Orig);
         when Iir_Predefined_Physical_Real_Mul =>
            --  FIXME: overflow??
            return Build_Physical
              (Int64 (Fp64 (Get_Physical_Value (Left))
                          * Get_Fp_Value (Right)), Orig);
         when Iir_Predefined_Physical_Real_Div =>
            --  FIXME: overflow??
            return Build_Physical
              (Int64 (Fp64 (Get_Physical_Value (Left))
                          / Get_Fp_Value (Right)), Orig);

         when Iir_Predefined_Physical_Mod =>
            return Build_Physical
              (Get_Physical_Value (Left) mod Get_Value (Right), Orig);
         when Iir_Predefined_Physical_Rem =>
            return Build_Physical
              (Get_Physical_Value (Left) rem Get_Value (Right), Orig);

         when Iir_Predefined_Physical_Minimum =>
            return Build_Physical (Int64'Min (Get_Physical_Value (Left),
                                                  Get_Physical_Value (Right)),
                                   Orig);
         when Iir_Predefined_Physical_Maximum =>
            return Build_Physical (Int64'Max (Get_Physical_Value (Left),
                                                  Get_Physical_Value (Right)),
                                   Orig);

         when Iir_Predefined_Element_Array_Concat
           | Iir_Predefined_Array_Element_Concat
           | Iir_Predefined_Array_Array_Concat
           | Iir_Predefined_Element_Element_Concat =>
            raise Internal_Error;

         when Iir_Predefined_Enum_Equality
           | Iir_Predefined_Bit_Match_Equality =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) = Get_Enum_Pos (Right), Orig);
         when Iir_Predefined_Enum_Inequality
           | Iir_Predefined_Bit_Match_Inequality =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) /= Get_Enum_Pos (Right), Orig);
         when Iir_Predefined_Enum_Greater_Equal
           | Iir_Predefined_Bit_Match_Greater_Equal =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) >= Get_Enum_Pos (Right), Orig);
         when Iir_Predefined_Enum_Greater
           | Iir_Predefined_Bit_Match_Greater =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) > Get_Enum_Pos (Right), Orig);
         when Iir_Predefined_Enum_Less_Equal
           | Iir_Predefined_Bit_Match_Less_Equal =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) <= Get_Enum_Pos (Right), Orig);
         when Iir_Predefined_Enum_Less
           | Iir_Predefined_Bit_Match_Less =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) < Get_Enum_Pos (Right), Orig);

         when Iir_Predefined_Enum_Minimum =>
            if Get_Enum_Pos (Left) < Get_Enum_Pos (Right) then
               return Left;
            else
               return Right;
            end if;
         when Iir_Predefined_Enum_Maximum =>
            if Get_Enum_Pos (Left) > Get_Enum_Pos (Right) then
               return Left;
            else
               return Right;
            end if;

         when Iir_Predefined_Boolean_And
           | Iir_Predefined_Bit_And =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) = 1 and Get_Enum_Pos (Right) = 1, Orig);
         when Iir_Predefined_Boolean_Nand
           | Iir_Predefined_Bit_Nand =>
            return Build_Enumeration
              (not (Get_Enum_Pos (Left) = 1 and Get_Enum_Pos (Right) = 1),
               Orig);
         when Iir_Predefined_Boolean_Or
           | Iir_Predefined_Bit_Or =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) = 1 or Get_Enum_Pos (Right) = 1, Orig);
         when Iir_Predefined_Boolean_Nor
           | Iir_Predefined_Bit_Nor =>
            return Build_Enumeration
              (not (Get_Enum_Pos (Left) = 1 or Get_Enum_Pos (Right) = 1),
               Orig);
         when Iir_Predefined_Boolean_Xor
           | Iir_Predefined_Bit_Xor =>
            return Build_Enumeration
              (Get_Enum_Pos (Left) = 1 xor Get_Enum_Pos (Right) = 1, Orig);
         when Iir_Predefined_Boolean_Xnor
           | Iir_Predefined_Bit_Xnor =>
            return Build_Enumeration
              (not (Get_Enum_Pos (Left) = 1 xor Get_Enum_Pos (Right) = 1),
               Orig);

         when Iir_Predefined_Dyadic_TF_Array_Functions =>
            --  FIXME: only for bit ?
            return Eval_Dyadic_Bit_Array_Operator (Orig, Left, Right, Func);

         when Iir_Predefined_Universal_R_I_Mul =>
            return Build_Floating
              (Get_Fp_Value (Left) * Fp64 (Get_Value (Right)), Orig);
         when Iir_Predefined_Universal_I_R_Mul =>
            return Build_Floating
              (Fp64 (Get_Value (Left)) * Get_Fp_Value (Right), Orig);
         when Iir_Predefined_Universal_R_I_Div =>
            return Build_Floating
              (Get_Fp_Value (Left) / Fp64 (Get_Value (Right)), Orig);

         when Iir_Predefined_Array_Sll
           | Iir_Predefined_Array_Srl
           | Iir_Predefined_Array_Sla
           | Iir_Predefined_Array_Sra
           | Iir_Predefined_Array_Rol
           | Iir_Predefined_Array_Ror =>
            declare
               Left_Aggr : Iir;
               Res : Iir;
            begin
               Left_Aggr := Eval_String_Literal (Left);
               Res := Eval_Shift_Operator (Left_Aggr, Right, Orig, Func);
               Free_Eval_String_Literal (Left_Aggr, Left);
               return Res;
            end;

         when Iir_Predefined_Array_Equality =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) = Compare_Eq);
         when Iir_Predefined_Array_Inequality =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) /= Compare_Eq);
         when Iir_Predefined_Array_Less =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) = Compare_Lt);
         when Iir_Predefined_Array_Less_Equal =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) <= Compare_Eq);
         when Iir_Predefined_Array_Greater =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) = Compare_Gt);
         when Iir_Predefined_Array_Greater_Equal =>
            return Build_Boolean
              (Eval_Array_Compare (Left, Right) >= Compare_Eq);

         when Iir_Predefined_Record_Equality =>
            return Build_Boolean (Eval_Record_Equality (Left, Right));
         when Iir_Predefined_Record_Inequality =>
            return Build_Boolean (not Eval_Record_Equality (Left, Right));

         when Iir_Predefined_Real_To_String_Format =>
            return Eval_Floating_To_String_Format
              (Get_Fp_Value (Left), Right, Orig);

         when Iir_Predefined_Boolean_Not
           | Iir_Predefined_Boolean_Rising_Edge
           | Iir_Predefined_Boolean_Falling_Edge
           | Iir_Predefined_Bit_Not
           | Iir_Predefined_Bit_Rising_Edge
           | Iir_Predefined_Bit_Falling_Edge
           | Iir_Predefined_Integer_Absolute
           | Iir_Predefined_Integer_Identity
           | Iir_Predefined_Integer_Negation
           | Iir_Predefined_Floating_Absolute
           | Iir_Predefined_Floating_Negation
           | Iir_Predefined_Floating_Identity
           | Iir_Predefined_Physical_Absolute
           | Iir_Predefined_Physical_Identity
           | Iir_Predefined_Physical_Negation
           | Iir_Predefined_Error
           | Iir_Predefined_Access_Equality
           | Iir_Predefined_Access_Inequality
           | Iir_Predefined_TF_Array_Not
           | Iir_Predefined_Now_Function
           | Iir_Predefined_Real_Now_Function
           | Iir_Predefined_Frequency_Function
           | Iir_Predefined_Deallocate
           | Iir_Predefined_Write
           | Iir_Predefined_Read
           | Iir_Predefined_Read_Length
           | Iir_Predefined_Flush
           | Iir_Predefined_File_Open
           | Iir_Predefined_File_Open_Status
           | Iir_Predefined_File_Close
           | Iir_Predefined_Endfile
           | Iir_Predefined_Array_Char_To_String
           | Iir_Predefined_Bit_Vector_To_Ostring
           | Iir_Predefined_Bit_Vector_To_Hstring =>
            --  Not binary or never locally static.
            Error_Internal (Orig, "eval_dyadic_operator: " &
                              Iir_Predefined_Functions'Image (Func));

         when Iir_Predefined_Bit_Condition =>
            raise Internal_Error;

         when Iir_Predefined_Array_Minimum
           | Iir_Predefined_Array_Maximum
           | Iir_Predefined_Vector_Minimum
           | Iir_Predefined_Vector_Maximum =>
            raise Internal_Error;

         when Iir_Predefined_Std_Ulogic_Match_Equality =>
            return Build_Enumeration
              (Eval_Logic_Match_Equality (Get_Enum_Pos (Left),
                                          Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Std_Ulogic_Match_Inequality =>
            return Build_Enumeration
              (Eval_Logic_Match_Inequality (Get_Enum_Pos (Left),
                                            Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Std_Ulogic_Match_Less =>
            return Build_Enumeration
              (Eval_Logic_Match_Less (Get_Enum_Pos (Left),
                                      Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Std_Ulogic_Match_Greater =>
            return Build_Enumeration
              (Eval_Logic_Match_Greater (Get_Enum_Pos (Left),
                                         Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Std_Ulogic_Match_Greater_Equal =>
            return Build_Enumeration
              (Eval_Logic_Match_Greater_Equal (Get_Enum_Pos (Left),
                                               Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Std_Ulogic_Match_Less_Equal =>
            return Build_Enumeration
              (Eval_Logic_Match_Less_Equal (Get_Enum_Pos (Left),
                                            Get_Enum_Pos (Right), Orig),
               Orig);

         when Iir_Predefined_Real_To_String_Digits
           | Iir_Predefined_Time_To_String_Unit =>
            --  TODO: to_string with a format parameter
            raise Internal_Error;

         when Iir_Predefined_TF_Array_Element_And
           | Iir_Predefined_TF_Element_Array_And
           | Iir_Predefined_TF_Array_Element_Or
           | Iir_Predefined_TF_Element_Array_Or
           | Iir_Predefined_TF_Array_Element_Nand
           | Iir_Predefined_TF_Element_Array_Nand
           | Iir_Predefined_TF_Array_Element_Nor
           | Iir_Predefined_TF_Element_Array_Nor
           | Iir_Predefined_TF_Array_Element_Xor
           | Iir_Predefined_TF_Element_Array_Xor
           | Iir_Predefined_TF_Array_Element_Xnor
           | Iir_Predefined_TF_Element_Array_Xnor =>
            return Eval_Ieee_Operator (Orig, Imp, Left, Right);

         when Iir_Predefined_TF_Reduction_And
           | Iir_Predefined_TF_Reduction_Or
           | Iir_Predefined_TF_Reduction_Nand
           | Iir_Predefined_TF_Reduction_Nor
           | Iir_Predefined_TF_Reduction_Xor
           | Iir_Predefined_TF_Reduction_Xnor
           | Iir_Predefined_TF_Reduction_Not =>
            --  TODO
            raise Internal_Error;

         when Iir_Predefined_Bit_Array_Match_Equality
           | Iir_Predefined_Bit_Array_Match_Inequality
           | Iir_Predefined_Std_Ulogic_Array_Match_Equality
           | Iir_Predefined_Std_Ulogic_Array_Match_Inequality =>
            --  TODO
            raise Internal_Error;

         when Iir_Predefined_Enum_To_String
           | Iir_Predefined_Integer_To_String
           | Iir_Predefined_Floating_To_String
           | Iir_Predefined_Physical_To_String =>
            --  Not dyadic
            raise Internal_Error;

         when Iir_Predefined_IEEE_Explicit =>
            return Eval_Ieee_Operator (Orig, Imp, Left, Right);

         when Iir_Predefined_None =>
            --  Not static
            raise Internal_Error;
      end case;
   exception
      when Constraint_Error =>
         Warning_Msg_Sem (Warnid_Runtime_Error, +Orig,
                          "arithmetic overflow in static expression");
         return Build_Overflow (Orig);
   end Eval_Dyadic_Operator;

   --  Get the parameter of an attribute, or 1 if doesn't exist.
   function Eval_Attribute_Parameter_Or_1 (Attr : Iir) return Natural
   is
      Parameter : constant Iir := Get_Parameter (Attr);
   begin
      if Is_Null (Parameter) or else Is_Error (Parameter) then
         return 1;
      else
         return Natural (Get_Value (Parameter));
      end if;
   end Eval_Attribute_Parameter_Or_1;

   --  Evaluate any array attribute, return the type for the prefix.
   function Eval_Array_Attribute (Attr : Iir) return Iir
   is
      Prefix : Iir;
      Prefix_Type : Iir;
      Dim : Natural;
   begin
      Prefix := Get_Prefix (Attr);
      case Get_Kind (Prefix) is
         when Iir_Kinds_Object_Declaration --  FIXME: remove
           | Iir_Kind_Selected_Element
           | Iir_Kind_Indexed_Name
           | Iir_Kind_Slice_Name
           | Iir_Kind_Subtype_Declaration
           | Iir_Kind_Type_Declaration
           | Iir_Kind_Implicit_Dereference
           | Iir_Kind_Function_Call
           | Iir_Kind_Attribute_Value
           | Iir_Kind_Attribute_Name
           | Iir_Kind_Subtype_Attribute
           | Iir_Kind_Element_Attribute =>
            Prefix_Type := Get_Type (Prefix);
         when Iir_Kinds_Subtype_Definition =>
            Prefix_Type := Prefix;
         when Iir_Kinds_Denoting_Name =>
            Prefix_Type := Get_Type (Prefix);
         when others =>
            Error_Kind ("eval_array_attribute", Prefix);
      end case;
      if Get_Kind (Prefix_Type) /= Iir_Kind_Array_Subtype_Definition then
         Error_Kind ("eval_array_attribute(2)", Prefix_Type);
      end if;

      Dim := Eval_Attribute_Parameter_Or_1 (Attr);
      return Get_Nth_Element (Get_Index_Subtype_List (Prefix_Type), Dim - 1);
   end Eval_Array_Attribute;

   function Eval_Integer_Image (Val : Int64; Orig : Iir) return Iir
   is
      Img : String (1 .. 24); --  23 is enough, 24 is rounded.
      L : Natural;
      V : Int64;
   begin
      V := Val;
      L := Img'Last;
      loop
         Img (L) := Character'Val (Character'Pos ('0') + abs (V rem 10));
         V := V / 10;
         L := L - 1;
         exit when V = 0;
      end loop;
      if Val < 0 then
         Img (L) := '-';
         L := L - 1;
      end if;
      return Build_String (Img (L + 1 .. Img'Last), Orig);
   end Eval_Integer_Image;

   function Eval_Floating_Image (Val : Fp64; Orig : Iir) return Iir
   is
      --  Sign (1) + digit (1) + dot (1) + digits (15) + 'e' (1) + sign (1)
      --  + exp_digits (4) -> 24.
      Str : String (1 .. 25);
      P : Natural;

      Res : Iir;
   begin
      P := Str'First;

      Grt.Fcvt.Format_Image (Str, P, Interfaces.IEEE_Float_64 (Val));

      Res := Build_String (Str (1 .. P), Orig);
      --  FIXME: this is not correct since the type is *not* constrained.
      Set_Type (Res, Create_Unidim_Array_By_Length
                (Get_Type (Orig), Int64 (P), Orig));
      return Res;
   end Eval_Floating_Image;

   function Eval_Floating_To_String_Format (Val : Fp64; Fmt : Iir; Orig : Iir)
                                           return Iir
   is
      pragma Assert (Get_Kind (Fmt) = Iir_Kind_String_Literal8);
      Fmt_Len : constant Int32 := Get_String_Length (Fmt);
   begin
      if Fmt_Len > 32 then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Orig,
                          "format parameter too long");
         return Build_Overflow (Orig);
      end if;
      declare
         use Str_Table;
         use Grt.Types;
         use Grt.To_Strings;
         Fmt_Id : constant String8_Id := Get_String8_Id (Fmt);
         Fmt_Str : String (1 .. Natural (Fmt_Len) + 1);

         Res : String_Real_Format;
         Last : Natural;
      begin
         for I in 1 .. Fmt_Len loop
            Fmt_Str (Positive (I)) := Char_String8 (Fmt_Id, I);
         end loop;
         Fmt_Str (Fmt_Str'Last) := ASCII.NUL;

         Grt.To_Strings.To_String
           (Res, Last, Ghdl_F64 (Val), To_Ghdl_C_String (Fmt_Str'Address));

         return Build_String (Res (1 .. Last), Orig);
      end;
   end Eval_Floating_To_String_Format;

   function Eval_Enumeration_Image (Lit : Iir; Orig : Iir) return Iir
   is
      Name : constant String := Image_Identifier (Lit);
   begin
      return Build_String (Name, Orig);
   end Eval_Enumeration_Image;

   function Build_Enumeration_Value (Val : String; Enum, Expr : Iir) return Iir
   is
      List  : constant Iir_Flist := Get_Enumeration_Literal_List (Enum);
      Value : String (Val'range);
      Id : Name_Id;
      Res : Iir;
   begin
      if Val'Length = 3
        and then Val (Val'First) = ''' and then Val (Val'Last) = '''
      then
         --  A single character.
         Id := Get_Identifier (Val (Val'First + 1));
      else
         for I in Val'range loop
            Value (I) := Ada.Characters.Handling.To_Lower (Val (I));
         end loop;
         Id := Get_Identifier (Value);
      end if;
      Res := Find_Name_In_Flist (List, Id);
      if Res /= Null_Iir then
         return Build_Constant (Res, Expr);
      else
         Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                          "value %i not in enumeration %n", (+Id, +Enum));
         return Build_Overflow (Expr);
      end if;
   end Build_Enumeration_Value;

   function Eval_Physical_Image (Phys, Expr: Iir) return Iir
   is
      --  Reduces to the base unit (e.g. femtoseconds).
      Value : constant String := Int64'Image (Get_Physical_Value (Phys));
      Unit : constant Iir :=
        Get_Primary_Unit (Get_Base_Type (Get_Type (Phys)));
      UnitName : constant String := Image_Identifier (Unit);
      Image_Id : constant String8_Id := Str_Table.Create_String8;
      Length : Nat32 := Value'Length + UnitName'Length + 1;
   begin
      for I in Value'range loop
         -- Suppress the Ada +ve integer'image leading space
         if I > Value'first or else Value (I) /= ' ' then
            Str_Table.Append_String8_Char (Value (I));
         else
            Length := Length - 1;
         end if;
      end loop;
      Str_Table.Append_String8_Char (' ');
      for I in UnitName'range loop
         Str_Table.Append_String8_Char (UnitName (I));
      end loop;

      return Build_String (Image_Id, Length, Expr);
   end Eval_Physical_Image;

   function Build_Physical_Value (Val: String; Phys_Type, Expr: Iir) return Iir
   is
      UnitName : String (Val'range);
      Mult : Int64;
      Sep : Natural;
      Found_Unit : Boolean := false;
      Found_Real : Boolean := false;
      Unit : Iir;
   begin
      -- Separate string into numeric value and make lowercase unit.
      for I in reverse Val'range loop
         UnitName (I) := Ada.Characters.Handling.To_Lower (Val (I));
         if Vhdl.Scanner.Is_Whitespace (Val (I)) and Found_Unit then
            Sep := I;
            exit;
         else
            Found_Unit := true;
         end if;
      end loop;

      -- Unit name  is UnitName(Sep+1..Unit'Last)
      for I in Val'First .. Sep loop
         if Val (I) = '.' then
            Found_Real := true;
         end if;
      end loop;

      -- Chain down the units looking for matching one
      Unit := Get_Primary_Unit (Phys_Type);
      while Unit /= Null_Iir loop
         exit when (UnitName (Sep + 1 .. UnitName'Last)
                      = Image_Identifier (Unit));
         Unit := Get_Chain (Unit);
      end loop;
      if Unit = Null_Iir then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                          "Unit """ & UnitName (Sep + 1 .. UnitName'Last)
                            & """ not in physical type");
         return Build_Overflow (Expr);
      end if;

      Mult := Get_Value (Get_Physical_Literal (Unit));
      if Found_Real then
         return Build_Physical
           (Int64 (Fp64'Value (Val (Val'First .. Sep))
                         * Fp64 (Mult)),
            Expr);
      else
         return Build_Physical
           (Int64'Value (Val (Val'First .. Sep)) * Mult, Expr);
      end if;
   end Build_Physical_Value;

   function Eval_Enum_To_String (Lit : Iir; Orig : Iir) return Iir
   is
      use Str_Table;
      Id : constant Name_Id := Get_Identifier (Lit);
      Image_Id : constant String8_Id := Str_Table.Create_String8;
      Len : Natural;
   begin
      if Get_Base_Type (Get_Type (Lit)) = Character_Type_Definition then
         --  LRM08 5.7 String representations
         --  - For a given value of type CHARACTER, the string representation
         --    contains one element that is the given value.
         Append_String8 (Nat8 (Get_Enum_Pos (Lit)));
         Len := 1;
      elsif Is_Character (Id) then
         --  LRM08 5.7 String representations
         --  - For a given value of an enumeration type other than CHARACTER,
         --    if the value is a character literal, the string representation
         --    contains a single element that is the character literal; [...]
         Append_String8_Char (Get_Character (Id));
         Len := 1;
      else
         --  LRM08 5.7 String representations
         --  - [...] otherwise, the string representation is the sequence of
         --    characters in the identifier that is the given value.
         declare
            Img : constant String := Image (Id);
         begin
            if Img (Img'First) /= '\' then
               Append_String8_String (Img);
               Len := Img'Length;
            else
               declare
                  Skip : Boolean;
                  C : Character;
               begin
                  Len := 0;
                  Skip := False;
                  for I in Img'First + 1 .. Img'Last - 1 loop
                     if Skip then
                        Skip := False;
                     else
                        C := Img (I);
                        Append_String8_Char (C);
                        Skip := C = '\';
                        Len := Len + 1;
                     end if;
                  end loop;
               end;
            end if;
         end;
      end if;
      return Build_String (Image_Id, Nat32 (Len), Orig);
   end Eval_Enum_To_String;

   function Eval_Incdec (Expr : Iir; N : Int64; Origin : Iir) return Iir
   is
      P : Int64;
   begin
      case Get_Kind (Expr) is
         when Iir_Kind_Integer_Literal =>
            return Build_Integer (Get_Value (Expr) + N, Origin);
         when Iir_Kind_Enumeration_Literal =>
            P := Int64 (Get_Enum_Pos (Expr)) + N;
            if P < 0
              or else (P >= Int64
                         (Get_Nbr_Elements
                            (Get_Enumeration_Literal_List
                               (Get_Base_Type (Get_Type (Expr))))))
            then
               Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                                "static constant violates bounds");
               return Build_Overflow (Origin);
            else
               return Build_Enumeration (Iir_Index32 (P), Origin);
            end if;
         when Iir_Kind_Physical_Int_Literal
           | Iir_Kind_Unit_Declaration =>
            return Build_Physical (Get_Physical_Value (Expr) + N, Origin);
         when others =>
            Error_Kind ("eval_incdec", Expr);
      end case;
   end Eval_Incdec;

   function Convert_Range (Rng : Iir; Res_Type : Iir; Loc : Iir) return Iir
   is
      Res_Btype : Iir;

      function Create_Bound (Val : Iir) return Iir
      is
         R : Iir;
      begin
         R := Create_Iir (Iir_Kind_Integer_Literal);
         Location_Copy (R, Loc);
         Set_Value (R, Get_Value (Val));
         Set_Type (R, Res_Btype);
         Set_Expr_Staticness (R, Locally);
         return R;
      end Create_Bound;

      Res : Iir;
      Lit : Iir;
   begin
      Res_Btype := Get_Base_Type (Res_Type);
      Res := Create_Iir (Iir_Kind_Range_Expression);
      Location_Copy (Res, Loc);
      Set_Type (Res, Res_Btype);
      Lit := Create_Bound (Get_Left_Limit (Rng));
      Set_Left_Limit (Res, Lit);
      Set_Left_Limit_Expr (Res, Lit);
      Lit := Create_Bound (Get_Right_Limit (Rng));
      Set_Right_Limit (Res, Lit);
      Set_Right_Limit_Expr (Res, Lit);
      Set_Direction (Res, Get_Direction (Rng));
      Set_Expr_Staticness (Res, Locally);
      return Res;
   end Convert_Range;

   function Eval_Array_Type_Conversion (Conv : Iir; Val : Iir) return Iir
   is
      Conv_Type : constant Iir := Get_Type (Conv);
      Val_Type : constant Iir := Get_Type (Val);
      Conv_Index_Type : constant Iir := Get_Index_Type (Conv_Type, 0);
      Val_Index_Type : constant Iir := Get_Index_Type (Val_Type, 0);
      Index_Type : Iir;
      Res_Type : Iir;
      Res : Iir;
      Rng : Iir;
   begin
      --  The expression is either a simple aggregate or a (bit) string.
      Res := Build_Constant (Val, Conv);
      if Get_Constraint_State (Conv_Type) = Fully_Constrained then
         Set_Type (Res, Conv_Type);
         if not Eval_Is_In_Bound (Val, Conv_Type, True) then
            Warning_Msg_Sem (Warnid_Runtime_Error, +Conv,
                             "non matching length in type conversion");
            return Build_Overflow (Conv);
         end if;
         return Res;
      else
         if Get_Base_Type (Conv_Index_Type) = Get_Base_Type (Val_Index_Type)
         then
            Index_Type := Val_Index_Type;
         else
            --  Convert the index range.
            --  It is an integer type.
            Rng := Convert_Range (Get_Range_Constraint (Val_Index_Type),
                                  Conv_Index_Type, Conv);
            Index_Type := Create_Iir (Iir_Kind_Integer_Subtype_Definition);
            Location_Copy (Index_Type, Conv);
            Set_Range_Constraint (Index_Type, Rng);
            Set_Parent_Type (Index_Type, Conv_Index_Type);
            Set_Type_Staticness (Index_Type, Locally);
         end if;
         Res_Type := Create_Unidim_Array_From_Index
           (Get_Base_Type (Conv_Type), Index_Type, Conv);
         Set_Type (Res, Res_Type);
         Set_Type_Conversion_Subtype (Conv, Res_Type);
         return Res;
      end if;
   end Eval_Array_Type_Conversion;

   function Eval_Type_Conversion (Conv : Iir) return Iir
   is
      Expr : constant Iir := Get_Expression (Conv);
      Val : Iir;
      Val_Type : Iir;
      Conv_Type : Iir;
      Res : Iir;
   begin
      Val := Eval_Static_Expr (Expr);
      Val_Type := Get_Base_Type (Get_Type (Val));
      Conv_Type := Get_Base_Type (Get_Type (Conv));
      if Conv_Type = Val_Type then
         Res := Build_Constant (Val, Conv);
      else
         case Get_Kind (Conv_Type) is
            when Iir_Kind_Integer_Type_Definition =>
               case Get_Kind (Val_Type) is
                  when Iir_Kind_Integer_Type_Definition =>
                     Res := Build_Integer (Get_Value (Val), Conv);
                  when Iir_Kind_Floating_Type_Definition =>
                     Res := Build_Integer
                       (Int64 (Get_Fp_Value (Val)), Conv);
                  when others =>
                     Error_Kind ("eval_type_conversion(1)", Val_Type);
               end case;
            when Iir_Kind_Floating_Type_Definition =>
               case Get_Kind (Val_Type) is
                  when Iir_Kind_Integer_Type_Definition =>
                     Res := Build_Floating (Fp64 (Get_Value (Val)), Conv);
                  when Iir_Kind_Floating_Type_Definition =>
                     Res := Build_Floating (Get_Fp_Value (Val), Conv);
                  when others =>
                     Error_Kind ("eval_type_conversion(2)", Val_Type);
               end case;
            when Iir_Kind_Array_Type_Definition =>
               --  Not a scalar, do not check bounds.
               return Eval_Array_Type_Conversion (Conv, Val);
            when others =>
               Error_Kind ("eval_type_conversion(3)", Conv_Type);
         end case;
      end if;
      if not Eval_Is_In_Bound (Res, Get_Type (Conv), True) then
         Warning_Msg_Sem (Warnid_Runtime_Error, +Conv,
                          "result of conversion out of bounds");
         Free_Eval_Static_Expr (Res, Conv);
         Res := Build_Overflow (Conv);
      end if;
      return Res;
   end Eval_Type_Conversion;

   function Eval_Physical_Literal (Expr : Iir) return Iir
   is
      Val : Iir;
   begin
      case Get_Kind (Expr) is
         when Iir_Kind_Physical_Fp_Literal =>
            Val := Expr;
         when Iir_Kind_Physical_Int_Literal =>
            --  Create a copy even if the literal has the primary unit.  This
            --  is required for ownership rule.
            Val := Expr;
         when Iir_Kind_Unit_Declaration =>
            Val := Expr;
         when Iir_Kinds_Denoting_Name =>
            Val := Get_Named_Entity (Expr);
            pragma Assert (Get_Kind (Val) = Iir_Kind_Unit_Declaration);
         when others =>
            Error_Kind ("eval_physical_literal", Expr);
      end case;
      return Build_Physical (Get_Physical_Value (Val), Expr);
   end Eval_Physical_Literal;

   function Eval_Value_Attribute
     (Value : String; Atype : Iir; Orig : Iir) return Iir
   is
      Base_Type : constant Iir := Get_Base_Type (Atype);
      First, Last : Positive;
   begin
      --  LRM93 14.1 Predefined attributes.
      --  Leading and trailing whitespace are ignored.
      First := Value'First;
      Last := Value'Last;
      while First <= Last loop
         exit when not Vhdl.Scanner.Is_Whitespace (Value (First));
         First := First + 1;
      end loop;
      while Last >= First loop
         exit when not Vhdl.Scanner.Is_Whitespace (Value (Last));
         Last := Last - 1;
      end loop;

      --  TODO: do not use 'value, use the same function as the scanner.
      declare
         Value1 : String renames Value (First .. Last);
      begin
         case Get_Kind (Base_Type) is
            when Iir_Kind_Integer_Type_Definition =>
               declare
                  use Grt.To_Strings;
                  use Grt.Types;
                  use Grt.Vhdl_Types;
                  Res : Value_I64_Result;
               begin
                  Res := Value_I64 (To_Std_String_Basep (Value1'Address),
                                    Value1'Length, 0);
                  if Res.Status = Value_Ok then
                     return Build_Discrete (Int64 (Res.Val), Orig);
                  else
                     Warning_Msg_Sem
                       (Warnid_Runtime_Error, +Get_Parameter (Orig),
                        "incorrect parameter for value attribute");
                     return Build_Overflow (Orig);
                  end if;
               end;
            when Iir_Kind_Enumeration_Type_Definition =>
               return Build_Enumeration_Value (Value1, Base_Type, Orig);
            when Iir_Kind_Floating_Type_Definition =>
               return Build_Floating (Fp64'Value (Value1), Orig);
            when Iir_Kind_Physical_Type_Definition =>
               return Build_Physical_Value (Value1, Base_Type, Orig);
            when others =>
               Error_Kind ("eval_value_attribute", Base_Type);
         end case;
      end;
   end Eval_Value_Attribute;

   --  Be sure that all expressions within an aggregate have been evaluated.
   procedure Eval_Aggregate (Aggr : Iir)
   is
      Assoc : Iir;
      Expr : Iir;
   begin
      Assoc := Get_Association_Choices_Chain (Aggr);
      while Is_Valid (Assoc) loop
         case Iir_Kinds_Choice (Get_Kind (Assoc)) is
            when Iir_Kind_Choice_By_None =>
               null;
            when Iir_Kind_Choice_By_Name =>
               null;
            when Iir_Kind_Choice_By_Range =>
               Set_Choice_Range
                 (Assoc, Eval_Range (Get_Choice_Range (Assoc)));
            when Iir_Kind_Choice_By_Expression =>
               Set_Choice_Expression
                 (Assoc, Eval_Expr (Get_Choice_Expression (Assoc)));
            when Iir_Kind_Choice_By_Others =>
               null;
         end case;
         if not Get_Same_Alternative_Flag (Assoc) then
            Expr := Get_Associated_Expr (Assoc);
         end if;
         if Get_Kind (Expr) = Iir_Kind_Aggregate then
            Eval_Aggregate (Expr);
         end if;
         Assoc := Get_Chain (Assoc);
      end loop;
   end Eval_Aggregate;

   function Eval_Selected_Element (Expr : Iir) return Iir
   is
      Selected_El : constant Iir := Get_Named_Entity (Expr);
      El_Pos : constant Iir_Index32 := Get_Element_Position (Selected_El);
      Prefix : Iir;
      Cur_Pos : Iir_Index32;
      Assoc : Iir;
      Assoc_Expr : Iir;
      Res : Iir;
   begin
      Prefix := Get_Prefix (Expr);
      Prefix := Eval_Static_Expr (Prefix);
      if Is_Overflow_Literal (Prefix) then
         return Build_Overflow (Expr, Get_Type (Expr));
      end if;

      pragma Assert (Get_Kind (Prefix) = Iir_Kind_Aggregate);
      Assoc := Get_Association_Choices_Chain (Prefix);
      Cur_Pos := 0;
      Assoc_Expr := Null_Iir;
      loop
         if not Get_Same_Alternative_Flag (Assoc) then
            Assoc_Expr := Assoc;
         end if;
         case Iir_Kinds_Record_Choice (Get_Kind (Assoc)) is
            when Iir_Kind_Choice_By_None =>
               exit when Cur_Pos = El_Pos;
               Cur_Pos := Cur_Pos + 1;
            when Iir_Kind_Choice_By_Name =>
               declare
                  Choice : constant Iir := Get_Choice_Name (Assoc);
               begin
                  exit when Get_Element_Position (Get_Named_Entity (Choice))
                    = El_Pos;
               end;
            when Iir_Kind_Choice_By_Others =>
               exit;
         end case;
         Assoc := Get_Chain (Assoc);
      end loop;

      --  Eval element and save it.
      Res := Eval_Expr_Keep_Orig (Get_Associated_Expr (Assoc_Expr), True);
      Set_Associated_Expr (Assoc_Expr, Res);
      return Res;
   end Eval_Selected_Element;

   function Eval_Indexed_Aggregate (Prefix : Iir; Expr : Iir) return Iir
   is
      Indexes : constant Iir_Flist := Get_Index_List (Expr);
      Prefix_Type : constant Iir := Get_Type (Prefix);
      Indexes_Type : constant Iir_Flist :=
        Get_Index_Subtype_List (Prefix_Type);
      Idx : Iir;
      Assoc : Iir;
      Assoc_Expr : Iir;
      Aggr_Bounds : Iir;
      Aggr : Iir;
      Cur_Pos : Int64;
      Res : Iir;
   begin
      Aggr := Prefix;

      for Dim in Flist_First .. Flist_Last (Indexes) loop
         Idx := Get_Nth_Element (Indexes, Dim);

         --  Find Idx in choices.
         Assoc := Get_Association_Choices_Chain (Aggr);
         Aggr_Bounds := Eval_Static_Range
           (Get_Nth_Element (Indexes_Type, Dim));
         Cur_Pos := Eval_Pos (Eval_Discrete_Range_Left (Aggr_Bounds));
         Assoc_Expr := Null_Iir;
         loop
            if not Get_Same_Alternative_Flag (Assoc) then
               Assoc_Expr := Assoc;
            end if;
            case Get_Kind (Assoc) is
               when Iir_Kind_Choice_By_None =>
                  exit when Cur_Pos = Eval_Pos (Idx);
                  case Get_Direction (Aggr_Bounds) is
                     when Dir_To =>
                        Cur_Pos := Cur_Pos + 1;
                     when Dir_Downto =>
                        Cur_Pos := Cur_Pos - 1;
                  end case;
               when Iir_Kind_Choice_By_Expression =>
                  exit when Eval_Is_Eq (Get_Choice_Expression (Assoc), Idx);
               when Iir_Kind_Choice_By_Range =>
                  declare
                     Rng : Iir;
                  begin
                     Rng := Get_Choice_Range (Assoc);
                     Rng := Eval_Static_Range (Rng);
                     exit when Eval_Int_In_Range (Eval_Pos (Idx), Rng);
                  end;
               when Iir_Kind_Choice_By_Others =>
                  exit;
               when others =>
                  raise Internal_Error;
            end case;
            Assoc := Get_Chain (Assoc);
         end loop;
         Aggr := Get_Associated_Expr (Assoc_Expr);
      end loop;

      --  Eval element and save it.
      Res := Eval_Expr_Keep_Orig (Aggr, True);
      Set_Associated_Expr (Assoc_Expr, Res);

      return Res;
   end Eval_Indexed_Aggregate;

   function Eval_Indexed_String_Literal8 (Str : Iir; Expr : Iir) return Iir
   is
      Str_Type : constant Iir := Get_Type (Str);

      Index_Type : constant Iir := Get_Index_Type (Str_Type, 0);
      Index_Range : constant Iir := Eval_Static_Range (Index_Type);

      Indexes : constant Iir_Flist := Get_Index_List (Expr);

      Id : constant String8_Id := Get_String8_Id (Str);

      Idx : Iir;
      Pos : Iir_Index32;
   begin
      Idx := Eval_Static_Expr (Get_Nth_Element (Indexes, 0));
      Pos := Eval_Pos_In_Range (Index_Range, Idx);

      return Build_Enumeration_Constant
        (Iir_Index32 (Str_Table.Element_String8 (Id, Int32 (Pos + 1))), Expr);
   end Eval_Indexed_String_Literal8;

   function Eval_Indexed_Simple_Aggregate (Aggr : Iir; Expr : Iir) return Iir
   is
      Aggr_Type : constant Iir := Get_Type (Aggr);

      Index_Type : constant Iir := Get_Index_Type (Aggr_Type, 0);
      Index_Range : constant Iir := Eval_Static_Range (Index_Type);

      Indexes : constant Iir_Flist := Get_Index_List (Expr);

      Idx : Iir;
      Pos : Iir_Index32;
      El : Iir;
   begin
      Idx := Eval_Static_Expr (Get_Nth_Element (Indexes, 0));
      Set_Nth_Element (Indexes, 0, Idx);
      Pos := Eval_Pos_In_Range (Index_Range, Idx);

      El := Get_Nth_Element (Get_Simple_Aggregate_List (Aggr), Natural (Pos));
      return Build_Constant (El, Expr);
   end Eval_Indexed_Simple_Aggregate;

   function Eval_Indexed_Name (Expr : Iir) return Iir
   is
      Prefix : Iir;
   begin
      Prefix := Get_Prefix (Expr);
      Prefix := Eval_Static_Expr (Prefix);

      declare
         Prefix_Type : constant Iir := Get_Type (Prefix);
         Indexes_Type : constant Iir_Flist :=
           Get_Index_Subtype_List (Prefix_Type);
         Indexes_List : constant Iir_Flist := Get_Index_List (Expr);
         Prefix_Index : Iir;
         Index : Iir;
      begin
         for I in Flist_First .. Flist_Last (Indexes_Type) loop
            Prefix_Index := Get_Nth_Element (Indexes_Type, I);

            --  Eval index.
            Index := Get_Nth_Element (Indexes_List, I);
            Index := Eval_Static_Expr (Index);
            Set_Nth_Element (Indexes_List, I, Index);

            --  Return overflow if out of range.
            if not Eval_Is_In_Bound (Index, Prefix_Index) then
               return Build_Overflow (Expr, Get_Type (Expr));
            end if;
         end loop;
      end;

      case Get_Kind (Prefix) is
         when Iir_Kind_Aggregate =>
            return Eval_Indexed_Aggregate (Prefix, Expr);
         when Iir_Kind_String_Literal8 =>
            return Eval_Indexed_String_Literal8 (Prefix, Expr);
         when Iir_Kind_Simple_Aggregate =>
            return Eval_Indexed_Simple_Aggregate (Prefix, Expr);
         when Iir_Kind_Overflow_Literal =>
            return Build_Overflow (Expr, Get_Type (Expr));
         when others =>
            Error_Kind ("eval_indexed_name", Prefix);
      end case;
   end Eval_Indexed_Name;

   function Eval_Indexed_Aggregate_By_Offset
     (Aggr : Iir; Off : Iir_Index32; Dim : Natural := 0) return Iir
   is
      Prefix_Type : constant Iir := Get_Type (Aggr);
      Indexes_Type : constant Iir_Flist :=
        Get_Index_Subtype_List (Prefix_Type);
      Assoc : Iir;
      Assoc_Expr : Iir;
      Assoc_Len : Iir_Index32;
      Aggr_Bounds : Iir;
      Cur_Off : Iir_Index32;
      Res : Iir;
      Left_Pos : Int64;
      Assoc_Pos : Int64;
   begin
      Aggr_Bounds := Eval_Static_Range (Get_Nth_Element (Indexes_Type, Dim));
      Left_Pos := Eval_Pos (Eval_Discrete_Range_Left (Aggr_Bounds));

      Cur_Off := 0;
      Assoc := Get_Association_Choices_Chain (Aggr);
      Assoc_Expr := Null_Iir;
      while Assoc /= Null_Iir loop
         if not Get_Same_Alternative_Flag (Assoc) then
            Assoc_Expr := Assoc;
         end if;
         case Get_Kind (Assoc) is
            when Iir_Kind_Choice_By_None =>
               if Get_Element_Type_Flag (Assoc) then
                  if Off = Cur_Off then
                     return Get_Associated_Expr (Assoc);
                  end if;
                  Assoc_Len := 1;
               else
                  Res := Get_Associated_Expr (Assoc);
                  Assoc_Len := Iir_Index32
                    (Eval_Discrete_Range_Length
                       (Get_Index_Type (Get_Type (Res), 0)));
                  if Off >= Cur_Off and then Off < Cur_Off + Assoc_Len then
                     return Eval_Indexed_Name_By_Offset (Res, Off - Cur_Off);
                  end if;
               end if;
               Cur_Off := Cur_Off + Assoc_Len;
            when Iir_Kind_Choice_By_Expression =>
               Assoc_Pos := Eval_Pos (Get_Choice_Expression (Assoc));
               case Get_Direction (Aggr_Bounds) is
                  when Dir_To =>
                     Cur_Off := Iir_Index32 (Assoc_Pos - Left_Pos);
                  when Dir_Downto =>
                     Cur_Off := Iir_Index32 (Left_Pos - Assoc_Pos);
               end case;
               if Cur_Off = Off then
                  return Get_Associated_Expr (Assoc);
               end if;
            when Iir_Kind_Choice_By_Range =>
               declare
                  Rng : Iir;
                  Left : Int64;
                  Right : Int64;
                  Hi, Lo : Int64;
                  Lo_Off, Hi_Off : Iir_Index32;
               begin
                  Rng := Eval_Range (Get_Choice_Range (Assoc));
                  Set_Choice_Range (Assoc, Rng);

                  Left := Eval_Pos (Get_Left_Limit (Rng));
                  Right := Eval_Pos (Get_Right_Limit (Rng));
                  case Get_Direction (Rng) is
                     when Dir_To =>
                        Lo := Left;
                        Hi := Right;
                     when Dir_Downto =>
                        Lo := Right;
                        Hi := Left;
                  end case;
                  case Get_Direction (Aggr_Bounds) is
                     when Dir_To =>
                        Lo_Off := Iir_Index32 (Lo - Left_Pos);
                        Hi_Off := Iir_Index32 (Hi - Left_Pos);
                     when Dir_Downto =>
                        Lo_Off := Iir_Index32 (Left_Pos - Lo);
                        Hi_Off := Iir_Index32 (Left_Pos - Hi);
                  end case;
                  if Off >= Lo_Off and then Off <= Hi_Off then
                     Res := Get_Associated_Expr (Assoc);
                     if Get_Element_Type_Flag (Assoc) then
                        return Res;
                     else
                        return Eval_Indexed_Name_By_Offset
                          (Res, Off - Lo_Off);
                     end if;
                  end if;
               end;
            when Iir_Kind_Choice_By_Others =>
               return Get_Associated_Expr (Assoc_Expr);
            when others =>
               raise Internal_Error;
         end case;
         Assoc := Get_Chain (Assoc);
      end loop;
      raise Internal_Error;
   end Eval_Indexed_Aggregate_By_Offset;

   function Eval_Indexed_Name_By_Offset (Prefix : Iir; Off : Iir_Index32)
                                        return Iir
   is
   begin
      case Get_Kind (Prefix) is
         when Iir_Kind_Aggregate =>
            return Eval_Indexed_Aggregate_By_Offset (Prefix, Off);
         when Iir_Kind_String_Literal8 =>
            declare
               Id : constant String8_Id := Get_String8_Id (Prefix);
               El_Type : constant Iir :=
                 Get_Element_Subtype (Get_Type (Prefix));
               Enums : constant Iir_Flist :=
                 Get_Enumeration_Literal_List (El_Type);
               Lit : Pos32;
            begin
               Lit := Str_Table.Element_String8 (Id, Int32 (Off + 1));
               return Get_Nth_Element (Enums, Natural (Lit));
            end;
         when Iir_Kind_Simple_Aggregate =>
            return Get_Nth_Element (Get_Simple_Aggregate_List (Prefix),
                                    Natural (Off));
         when others =>
            Error_Kind ("eval_indexed_name_by_offset", Prefix);
      end case;
   end Eval_Indexed_Name_By_Offset;

   function Eval_Static_Expr (Expr: Iir) return Iir
   is
      Res : Iir;
      Val : Iir;
   begin
      case Get_Kind (Expr) is
         when Iir_Kinds_Denoting_Name =>
            return Eval_Static_Expr (Get_Named_Entity (Expr));

         when Iir_Kind_Integer_Literal
           | Iir_Kind_Enumeration_Literal
           | Iir_Kind_Floating_Point_Literal
           | Iir_Kind_String_Literal8
           | Iir_Kind_Overflow_Literal
           | Iir_Kind_Physical_Int_Literal
           | Iir_Kind_Physical_Fp_Literal =>
            return Expr;
         when Iir_Kind_Constant_Declaration =>
            Val := Eval_Static_Expr (Get_Default_Value (Expr));
            --  Type of the expression should be type of the constant
            --  declaration at least in case of array subtype.
            --  If the constant is declared as an unconstrained array, get type
            --  from the default value.
            --  FIXME: handle this during semantisation of the declaration:
            --    add an implicit subtype conversion node ?
            --  FIXME: this currently creates a node at each evalation.
            if Get_Kind (Get_Type (Val)) = Iir_Kind_Array_Type_Definition then
               Res := Build_Constant (Val, Expr);
               Set_Type (Res, Get_Type (Val));
               return Res;
            else
               return Val;
            end if;
         when Iir_Kind_Object_Alias_Declaration =>
            return Eval_Static_Expr (Get_Name (Expr));
         when Iir_Kind_Unit_Declaration =>
            return Get_Physical_Literal (Expr);
         when Iir_Kind_Simple_Aggregate =>
            return Expr;
         when Iir_Kind_Aggregate =>
            Eval_Aggregate (Expr);
            return Expr;

         when Iir_Kind_Selected_Element =>
            return Eval_Selected_Element (Expr);
         when Iir_Kind_Indexed_Name =>
            return Eval_Indexed_Name (Expr);

         when Iir_Kind_Parenthesis_Expression =>
            return Eval_Static_Expr (Get_Expression (Expr));
         when Iir_Kind_Qualified_Expression =>
            return Eval_Static_Expr (Get_Expression (Expr));
         when Iir_Kind_Type_Conversion =>
            return Eval_Type_Conversion (Expr);

         when Iir_Kinds_Monadic_Operator =>
            declare
               Operand : Iir;
            begin
               Operand := Eval_Static_Expr (Get_Operand (Expr));
               return Eval_Monadic_Operator (Expr, Operand);
            end;
         when Iir_Kinds_Dyadic_Operator =>
            declare
               Imp : constant Iir := Get_Implementation (Expr);
               Left : constant Iir := Get_Left (Expr);
               Right : constant Iir := Get_Right (Expr);
               Left_Val, Right_Val : Iir;
               Res : Iir;
            begin
               if (Get_Implicit_Definition (Imp)
                     in Iir_Predefined_Concat_Functions)
               then
                  return Eval_Concatenation ((1 => Expr));
               else
                  Left_Val := Eval_Static_Expr (Left);
                  Right_Val := Eval_Static_Expr (Right);

                  Res := Eval_Dyadic_Operator (Expr, Imp, Left_Val, Right_Val);

                  Free_Eval_Static_Expr (Left_Val, Left);
                  Free_Eval_Static_Expr (Right_Val, Right);

                  return Res;
               end if;
            end;

         when Iir_Kind_Attribute_Name =>
            --  An attribute name designates an attribute value.
            declare
               Attr_Expr : constant Iir :=
                 Get_Attribute_Name_Expression (Expr);
               Val : Iir;
            begin
               Val := Eval_Static_Expr (Attr_Expr);
               --  FIXME: see constant_declaration.
               --  Currently, this avoids weird nodes, such as a string literal
               --  whose type is an unconstrained array type.
               Res := Build_Constant (Val, Expr);
               Set_Type (Res, Get_Type (Val));
               return Res;
            end;

         when Iir_Kind_Pos_Attribute =>
            declare
               Param : constant Iir := Get_Parameter (Expr);
               Val : Iir;
               Res : Iir;
            begin
               Val := Eval_Static_Expr (Param);
               --  FIXME: check bounds, handle overflow.
               Res := Build_Integer (Eval_Pos (Val), Expr);
               Free_Eval_Static_Expr (Val, Param);
               return Res;
            end;
         when Iir_Kind_Val_Attribute =>
            declare
               Expr_Type : constant Iir := Get_Type (Expr);
               Val_Expr : Iir;
               Val : Int64;
            begin
               Val_Expr := Eval_Static_Expr (Get_Parameter (Expr));
               Val := Eval_Pos (Val_Expr);
               --  Note: the type of 'val is a base type.
               --  FIXME: handle VHDL93 restrictions.
               if Get_Kind (Expr_Type) = Iir_Kind_Enumeration_Type_Definition
                 and then
                 not Eval_Int_In_Range (Val, Get_Range_Constraint (Expr_Type))
               then
                  Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                                   "static argument out of the type range");
                  return Build_Overflow (Expr);
               end if;
               if Get_Kind (Get_Base_Type (Get_Type (Expr)))
                 = Iir_Kind_Physical_Type_Definition
               then
                  return Build_Physical (Val, Expr);
               else
                  return Build_Discrete (Val, Expr);
               end if;
            end;
         when Iir_Kind_Image_Attribute =>
            declare
               Param : Iir;
               Param_Type : Iir;
            begin
               Param := Get_Parameter (Expr);
               Param := Eval_Static_Expr (Param);
               Set_Parameter (Expr, Param);

               --  Special case for overflow.
               if not Eval_Is_In_Bound (Param, Get_Type (Get_Prefix (Expr)))
               then
                  return Build_Overflow (Expr);
               end if;

               Param_Type := Get_Base_Type (Get_Type (Param));
               case Get_Kind (Param_Type) is
                  when Iir_Kind_Integer_Type_Definition =>
                     return Eval_Integer_Image (Get_Value (Param), Expr);
                  when Iir_Kind_Floating_Type_Definition =>
                     return Eval_Floating_Image (Get_Fp_Value (Param), Expr);
                  when Iir_Kind_Enumeration_Type_Definition =>
                     return Eval_Enumeration_Image (Param, Expr);
                  when Iir_Kind_Physical_Type_Definition =>
                     return Eval_Physical_Image (Param, Expr);
                  when others =>
                     Error_Kind ("eval_static_expr('image)", Param);
               end case;
            end;
         when Iir_Kind_Value_Attribute =>
            declare
               Param : Iir;
            begin
               Param := Get_Parameter (Expr);
               Param := Eval_Static_Expr (Param);
               Set_Parameter (Expr, Param);
               if Get_Kind (Param) /= Iir_Kind_String_Literal8 then
                  --  FIXME: Isn't it an implementation restriction.
                  Warning_Msg_Sem (Warnid_Runtime_Error, +Expr,
                                   "'value argument not a string");
                  return Build_Overflow (Expr);
               else
                  return Eval_Value_Attribute
                    (Image_String_Lit (Param), Get_Type (Expr), Expr);
               end if;
            end;

         when Iir_Kind_Left_Type_Attribute =>
            return Eval_Static_Expr
              (Get_Left_Limit (Eval_Static_Range (Get_Prefix (Expr))));
         when Iir_Kind_Right_Type_Attribute =>
            return Eval_Static_Expr
              (Get_Right_Limit (Eval_Static_Range (Get_Prefix (Expr))));
         when Iir_Kind_High_Type_Attribute =>
            return Eval_Static_Expr
              (Get_High_Limit (Eval_Static_Range (Get_Prefix (Expr))));
         when Iir_Kind_Low_Type_Attribute =>
            return Eval_Static_Expr
              (Get_Low_Limit (Eval_Static_Range (Get_Prefix (Expr))));
         when Iir_Kind_Ascending_Type_Attribute =>
            return Build_Boolean
              (Get_Direction (Eval_Static_Range (Get_Prefix (Expr))) = Dir_To);

         when Iir_Kind_Length_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Build_Discrete (Eval_Discrete_Type_Length (Index), Expr);
            end;
         when Iir_Kind_Left_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Eval_Static_Expr
                 (Get_Left_Limit (Get_Range_Constraint (Index)));
            end;
         when Iir_Kind_Right_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Eval_Static_Expr
                 (Get_Right_Limit (Get_Range_Constraint (Index)));
            end;
         when Iir_Kind_Low_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Eval_Static_Expr
                 (Get_Low_Limit (Get_Range_Constraint (Index)));
            end;
         when Iir_Kind_High_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Eval_Static_Expr
                 (Get_High_Limit (Get_Range_Constraint (Index)));
            end;
         when Iir_Kind_Ascending_Array_Attribute =>
            declare
               Index : Iir;
            begin
               Index := Eval_Array_Attribute (Expr);
               return Build_Boolean
                 (Get_Direction (Get_Range_Constraint (Index)) = Dir_To);
            end;

         when Iir_Kind_Pred_Attribute =>
            Res := Eval_Incdec
              (Eval_Static_Expr (Get_Parameter (Expr)), -1, Expr);
            Eval_Check_Bound (Res, Get_Type (Get_Prefix (Expr)));
            return Res;
         when Iir_Kind_Succ_Attribute =>
            Res := Eval_Incdec
              (Eval_Static_Expr (Get_Parameter (Expr)), +1, Expr);
            Eval_Check_Bound (Res, Get_Type (Get_Prefix (Expr)));
            return Res;
         when Iir_Kind_Leftof_Attribute
           | Iir_Kind_Rightof_Attribute =>
            declare
               Rng : Iir;
               N : Int64;
               Prefix_Type : constant Iir := Get_Type (Get_Prefix (Expr));
               Res : Iir;
            begin
               Rng := Eval_Static_Range (Prefix_Type);
               case Get_Direction (Rng) is
                  when Dir_To =>
                     N := 1;
                  when Dir_Downto =>
                     N := -1;
               end case;
               case Get_Kind (Expr) is
                  when Iir_Kind_Leftof_Attribute =>
                     N := -N;
                  when Iir_Kind_Rightof_Attribute =>
                     null;
                  when others =>
                     raise Internal_Error;
               end case;
               Res := Eval_Incdec
                 (Eval_Static_Expr (Get_Parameter (Expr)), N, Expr);
               Eval_Check_Bound (Res, Prefix_Type);
               return Res;
            end;

         when Iir_Kind_Simple_Name_Attribute =>
            declare
               use Str_Table;
               Img : constant String :=
                 Image (Get_Simple_Name_Identifier (Expr));
               Id : String8_Id;
            begin
               Id := Create_String8;
               for I in Img'Range loop
                  Append_String8_Char (Img (I));
               end loop;
               return Build_String (Id, Nat32 (Img'Length), Expr);
            end;

         when Iir_Kind_Null_Literal =>
            return Expr;

         when Iir_Kind_Function_Call =>
            declare
               Imp : constant Iir := Get_Implementation (Expr);
               Left, Right : Iir;
            begin
               if (Get_Implicit_Definition (Imp)
                     in Iir_Predefined_Concat_Functions)
               then
                  return Eval_Concatenation ((1 => Expr));
               else
                  --  Note: there can't be association by name.
                  Left := Get_Parameter_Association_Chain (Expr);
                  Right := Get_Chain (Left);

                  Left := Eval_Static_Expr (Get_Actual (Left));
                  if Right = Null_Iir then
                     return Eval_Monadic_Operator (Expr, Left);
                  else
                     Right := Eval_Static_Expr (Get_Actual (Right));
                     return Eval_Dyadic_Operator (Expr, Imp, Left, Right);
                  end if;
               end if;
            end;

         when Iir_Kind_Error =>
            return Expr;
         when others =>
            Error_Kind ("eval_static_expr", Expr);
      end case;
   end Eval_Static_Expr;

   --  If FORCE is true, always return a literal.
   function Eval_Expr_Keep_Orig (Expr : Iir; Force : Boolean) return Iir
   is
      Res : Iir;
   begin
      case Get_Kind (Expr) is
         when Iir_Kinds_Denoting_Name =>
            declare
               Orig : constant Iir := Get_Named_Entity (Expr);
            begin
               Res := Eval_Static_Expr (Orig);
               if Res /= Orig or else Force then
                  return Build_Constant (Res, Expr);
               else
                  return Expr;
               end if;
            end;
         when others =>
            Res := Eval_Static_Expr (Expr);
            if Res /= Expr
              and then Get_Literal_Origin (Res) /= Expr
            then
               --  Need to build a constant if the result is a different
               --  literal not tied to EXPR.
               return Build_Constant (Res, Expr);
            else
               return Res;
            end if;
      end case;
   end Eval_Expr_Keep_Orig;

   function Eval_Expr (Expr: Iir) return Iir is
   begin
      if Get_Expr_Staticness (Expr) /= Locally then
         Error_Msg_Sem (+Expr, "expression must be locally static");
         return Expr;
      else
         return Eval_Expr_Keep_Orig (Expr, False);
      end if;
   end Eval_Expr;

   --  Subroutine of Can_Eval_Composite_Value.  Return True iff EXPR is
   --  considered as a small composite.
   function Is_Small_Composite_Value (Expr : Iir) return Boolean
   is
      Expr_Type : constant Iir := Get_Type (Expr);
      Indexes : Iir_Flist;
      Len : Int64;
   begin
      --  Consider only arrays.  Records are never composite.
      if Get_Kind (Expr_Type) /= Iir_Kind_Array_Subtype_Definition then
         return False;
      end if;

      --  Element must be scalar.
      if Get_Kind (Get_Element_Subtype (Expr_Type))
        not in Iir_Kinds_Scalar_Type_And_Subtype_Definition
      then
         return False;
      end if;

      Indexes := Get_Index_Subtype_List (Expr_Type);

      --  Multi-dimensional arrays aren't considered as small.
      if Get_Nbr_Elements (Indexes) /= 1 then
         return False;
      end if;

      Len := Eval_Discrete_Type_Length (Get_Nth_Element (Indexes, 0));
      return Len <= 128;
   end Is_Small_Composite_Value;

   function Can_Eval_Composite_Value (Expr : Iir; Top : Boolean := False)
                                     return Boolean;

   --  Return True if EXPR should be evaluated.
   function Can_Eval_Value (Expr : Iir; Top : Boolean) return Boolean is
   begin
      --  Always evaluate scalar values.
      if Get_Kind (Get_Type (Expr))
        in Iir_Kinds_Scalar_Type_And_Subtype_Definition
      then
         return True;
      end if;
      return Can_Eval_Composite_Value (Expr, Top);
   end Can_Eval_Value;

   --  For composite values.
   --  Evaluating a composite value is a trade-off: it can simplify the
   --  generated code if the value is small enough, or it can be a bad idea if
   --  the value is very large.  It is very easy to create large static
   --  composite values (like: bit_vector'(1 to 10**4 => '0'))
   function Can_Eval_Composite_Value (Expr : Iir; Top : Boolean := False)
                                     return Boolean
   is
      --  We are only considering static values.
      pragma Assert (Get_Expr_Staticness (Expr) = Locally);

      --  We are only considering composite types.
      pragma Assert (Get_Kind (Get_Type (Expr))
                       not in Iir_Kinds_Scalar_Type_And_Subtype_Definition);
   begin
      case Get_Kind (Expr) is
         when Iir_Kind_Type_Conversion
           | Iir_Kind_Qualified_Expression =>
            --  Not yet handled.
            return False;
         when Iir_Kinds_Denoting_Name =>
            return Can_Eval_Composite_Value (Get_Named_Entity (Expr), Top);
         when Iir_Kind_Constant_Declaration =>
            --  Pass through names only for small values.
            if Top or else not Is_Small_Composite_Value (Expr) then
               return False;
            else
               return Can_Eval_Composite_Value (Get_Default_Value (Expr));
            end if;
         when Iir_Kind_Attribute_Name =>
            if Top or else not Is_Small_Composite_Value (Expr) then
               return False;
            else
               return Can_Eval_Composite_Value
                 (Get_Attribute_Name_Expression (Expr));
            end if;
         when Iir_Kinds_Dyadic_Operator =>
            --  Concatenation can increase the size.
            --  Others (rol, ror...) don't.
            return Can_Eval_Value (Get_Left (Expr), False)
              and then Can_Eval_Value (Get_Right (Expr), False);
         when Iir_Kinds_Monadic_Operator =>
            --  For not.
            return Can_Eval_Composite_Value (Get_Operand (Expr));
         when Iir_Kind_Aggregate =>
            return Is_Small_Composite_Value (Expr);
         when Iir_Kinds_Literal
           | Iir_Kind_Enumeration_Literal
           | Iir_Kind_Simple_Aggregate
           | Iir_Kind_Image_Attribute
           | Iir_Kind_Simple_Name_Attribute =>
            return True;
         when Iir_Kind_Overflow_Literal =>
            return True;
         when Iir_Kind_Function_Call =>
            --  Either using post-fixed notation or implicit functions like
            --  to_string.
            --  Cannot be a user function (won't be locally static).
            declare
               Assoc : Iir;
               Assoc_Expr : Iir;
            begin
               Assoc := Get_Parameter_Association_Chain (Expr);
               while Is_Valid (Assoc) loop
                  case Iir_Kinds_Association_Element_Parameters
                    (Get_Kind (Assoc))
                  is
                     when Iir_Kind_Association_Element_By_Expression
                        | Iir_Kind_Association_Element_By_Name =>
                        Assoc_Expr := Get_Actual (Assoc);
                        if not Can_Eval_Value (Assoc_Expr, False) then
                           return False;
                        end if;
                     when Iir_Kind_Association_Element_Open =>
                        null;
                     when Iir_Kind_Association_Element_By_Individual =>
                        return False;
                  end case;
                  Assoc := Get_Chain (Assoc);
               end loop;
               return True;
            end;

         when others =>
            --  Be safe, don't crash on unhandled expression.
            --  Error_Kind ("can_eval_composite_value", Expr);
            return False;
      end case;
   end Can_Eval_Composite_Value;

   function Eval_Expr_If_Static (Expr : Iir) return Iir is
   begin
      if Expr /= Null_Iir and then Get_Expr_Staticness (Expr) = Locally then
         --  Evaluate only when there is a positive effect.
         if Can_Eval_Value (Expr, True) then
            return Eval_Expr_Keep_Orig (Expr, False);
         else
            return Expr;
         end if;
      else
         return Expr;
      end if;
   end Eval_Expr_If_Static;

   function Eval_Expr_Check (Expr : Iir; Sub_Type : Iir) return Iir
   is
      Res : Iir;
   begin
      Res := Eval_Expr_Keep_Orig (Expr, False);
      Eval_Check_Bound (Res, Sub_Type);
      return Res;
   end Eval_Expr_Check;

   function Eval_Expr_Check_If_Static (Expr : Iir; Atype : Iir) return Iir
   is
      Res : Iir;
   begin
      if Expr /= Null_Iir and then Get_Expr_Staticness (Expr) = Locally then
         --  Expression is static and can be evaluated.  Don't try to
         --  evaluate non-scalar expressions, that may create too large data.
         if Get_Kind (Atype) in Iir_Kinds_Scalar_Type_And_Subtype_Definition
         then
            Res := Eval_Expr_Keep_Orig (Expr, False);
         else
            Res := Expr;
         end if;

         if Res /= Null_Iir
           and then Get_Type_Staticness (Atype) = Locally
           and then Get_Kind (Atype) in Iir_Kinds_Range_Type_Definition
         then
            --  Check bounds (as this can be done).
            if not Eval_Check_Bound (Res, Atype) then
               Res := Build_Overflow (Res, Atype);
            end if;
         end if;

         return Res;
      else
         return Expr;
      end if;
   end Eval_Expr_Check_If_Static;

   function Eval_Int_In_Range (Val : Int64; Bound : Iir) return Boolean
   is
      L, R : Iir;
   begin
      case Get_Kind (Bound) is
         when Iir_Kind_Range_Expression =>
            L := Get_Left_Limit (Bound);
            R := Get_Right_Limit (Bound);
            if Get_Kind (L) = Iir_Kind_Overflow_Literal
              or else Get_Kind (R) = Iir_Kind_Overflow_Literal
            then
               return True;
            end if;
            case Get_Direction (Bound) is
               when Dir_To =>
                  return Val >= Eval_Pos (L) and then Val <= Eval_Pos (R);
               when Dir_Downto =>
                  return Val <= Eval_Pos (L) and then Val >= Eval_Pos (R);
            end case;
         when others =>
            Error_Kind ("eval_int_in_range", Bound);
      end case;
      return True;
   end Eval_Int_In_Range;

   function Eval_Phys_In_Range (Val : Int64; Bound : Iir) return Boolean
   is
      Left, Right : Int64;
   begin
      case Get_Kind (Bound) is
         when Iir_Kind_Range_Expression =>
            case Get_Kind (Get_Type (Get_Left_Limit (Bound))) is
               when Iir_Kind_Integer_Type_Definition
                 | Iir_Kind_Integer_Subtype_Definition =>
                  Left := Get_Value (Get_Left_Limit (Bound));
                  Right := Get_Value (Get_Right_Limit (Bound));
               when Iir_Kind_Physical_Type_Definition
                 | Iir_Kind_Physical_Subtype_Definition =>
                  Left := Get_Physical_Value (Get_Left_Limit (Bound));
                  Right := Get_Physical_Value (Get_Right_Limit (Bound));
               when others =>
                  Error_Kind ("eval_phys_in_range(1)", Get_Type (Bound));
            end case;
            case Get_Direction (Bound) is
               when Dir_To =>
                  if Val < Left or else Val > Right then
                     return False;
                  end if;