File: sql_optimizer.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (11787 lines) | stat: -rw-r--r-- 461,821 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
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
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
/* Copyright (c) 2000, 2025, Oracle and/or its affiliates.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2.0,
  as published by the Free Software Foundation.

  This program is designed to work with certain software (including
  but not limited to OpenSSL) that is licensed under separate terms,
  as designated in a particular file or component or in included license
  documentation.  The authors of MySQL hereby grant you an additional
  permission to link the program and your derivative works with the
  separately licensed software that they have either included with
  the program or referenced in the documentation.

  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, version 2.0, for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

/**
  @file

  @brief Optimize query expressions: Make optimal table join order, select
         optimal access methods per table, apply grouping, sorting and
         limit processing.

  @defgroup Query_Optimizer  Query Optimizer
  @{
*/

#include "sql/sql_optimizer.h"
#include "my_base.h"
#include "sql/sql_optimizer_internal.h"

#include <limits.h>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <deque>
#include <limits>
#include <new>
#include <string>
#include <utility>
#include <vector>

#include "field_types.h"  // enum_field_types
#include "ft_global.h"
#include "m_ctype.h"
#include "mem_root_deque.h"
#include "memory_debugging.h"
#include "my_bit.h"  // my_count_bits
#include "my_bitmap.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "sql/check_stack.h"
#include "sql/current_thd.h"
#include "sql/debug_sync.h"  // DEBUG_SYNC
#include "sql/derror.h"      // ER_THD
#include "sql/enum_query_type.h"
#include "sql/error_handler.h"  // Functional_index_error_handler
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_row.h"
#include "sql/item_subselect.h"
#include "sql/item_sum.h"  // Item_sum
#include "sql/iterators/basic_row_iterators.h"
#include "sql/iterators/timing_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/join_optimizer.h"
#include "sql/join_optimizer/walk_access_paths.h"
#include "sql/key.h"
#include "sql/key_spec.h"
#include "sql/lock.h"    // mysql_unlock_some_tables
#include "sql/mysqld.h"  // stage_optimizing
#include "sql/nested_join.h"
#include "sql/opt_costmodel.h"
#include "sql/opt_explain.h"  // join_type_str
#include "sql/opt_hints.h"    // hint_table_state
#include "sql/opt_trace.h"    // Opt_trace_object
#include "sql/opt_trace_context.h"
#include "sql/parse_tree_node_base.h"
#include "sql/parser_yystype.h"
#include "sql/query_options.h"
#include "sql/query_result.h"
#include "sql/range_optimizer/partition_pruning.h"
#include "sql/range_optimizer/path_helpers.h"
#include "sql/range_optimizer/range_optimizer.h"
#include "sql/sql_base.h"  // init_ftfuncs
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_const_folding.h"
#include "sql/sql_error.h"
#include "sql/sql_join_buffer.h"  // JOIN_CACHE
#include "sql/sql_planner.h"      // calculate_condition_filter
#include "sql/sql_test.h"         // print_where
#include "sql/sql_tmp_table.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql/window.h"
#include "sql_string.h"
#include "template_utils.h"

using std::ceil;
using std::max;
using std::min;

const char *antijoin_null_cond = "<ANTIJOIN-NULL>";

static bool optimize_semijoin_nests_for_materialization(JOIN *join);
static void calculate_materialization_costs(JOIN *join, Table_ref *sj_nest,
                                            uint n_tables,
                                            Semijoin_mat_optimize *sjm);
static bool make_join_query_block(JOIN *join, Item *item);
static bool list_contains_unique_index(JOIN_TAB *tab,
                                       bool (*find_func)(Field *, void *),
                                       void *data);
static bool find_field_in_item_list(Field *field, void *data);
static bool find_field_in_order_list(Field *field, void *data);
static TABLE *get_sort_by_table(ORDER *a, ORDER *b, Table_ref *tables);
static void trace_table_dependencies(Opt_trace_context *trace,
                                     JOIN_TAB *join_tabs, uint table_count);
static bool update_ref_and_keys(THD *thd, Key_use_array *keyuse,
                                JOIN_TAB *join_tab, uint tables, Item *cond,
                                table_map normal_tables,
                                Query_block *query_block,
                                SARGABLE_PARAM **sargables);
static bool pull_out_semijoin_tables(JOIN *join);
static void add_loose_index_scan_and_skip_scan_keys(JOIN *join,
                                                    JOIN_TAB *join_tab);
static ha_rows get_quick_record_count(THD *thd, JOIN_TAB *tab, ha_rows limit,
                                      Item *condition);
static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables,
                               table_map *cached_eq_ref_tables,
                               table_map *eq_ref_tables);
static bool setup_join_buffering(JOIN_TAB *tab, JOIN *join, uint no_jbuf_after);

static bool test_if_skip_sort_order(JOIN_TAB *tab, ORDER_with_src &order,
                                    ha_rows select_limit, const bool no_changes,
                                    const Key_map *map, int *best_idx);

static Item_func_match *test_if_ft_index_order(ORDER *order);

static uint32 get_key_length_tmp_table(Item *item);
static bool can_switch_from_ref_to_range(THD *thd, JOIN_TAB *tab,
                                         enum_order ordering,
                                         bool recheck_range);

static bool has_not_null_predicate(Item *cond, Item_field *not_null_item);

JOIN::JOIN(THD *thd_arg, Query_block *select)
    : query_block(select),
      thd(thd_arg),
      // @todo Can this be substituted with select->is_explicitly_grouped()?
      grouped(select->is_explicitly_grouped()),
      // Inner tables may always be considered to be constant:
      const_table_map(INNER_TABLE_BIT),
      found_const_table_map(INNER_TABLE_BIT),
      // Needed in case optimizer short-cuts, set properly in
      // make_tmp_tables_info()
      fields(&select->fields),
      tmp_table_param(thd_arg->mem_root),
      lock(thd->lock),
      // @todo Can this be substituted with select->is_implicitly_grouped()?
      implicit_grouping(select->is_implicitly_grouped()),
      select_distinct(select->is_distinct()),
      keyuse_array(thd->mem_root),
      order(select->order_list.first, ESC_ORDER_BY),
      group_list(select->group_list.first, ESC_GROUP_BY),
      m_windows(select->m_windows),
      /*
        Those four members are meaningless before JOIN::optimize(), so force a
        crash if they are used before that.
      */
      where_cond(reinterpret_cast<Item *>(1)),
      having_cond(reinterpret_cast<Item *>(1)),
      having_for_explain(reinterpret_cast<Item *>(1)),
      tables_list(reinterpret_cast<Table_ref *>(1)),
      current_ref_item_slice(REF_SLICE_SAVED_BASE),
      with_json_agg(select->json_agg_func_used()) {
  rollup_state = RollupState::NONE;
  if (select->order_list.first) explain_flags.set(ESC_ORDER_BY, ESP_EXISTS);
  if (select->group_list.first) explain_flags.set(ESC_GROUP_BY, ESP_EXISTS);
  if (select->is_distinct()) explain_flags.set(ESC_DISTINCT, ESP_EXISTS);
  if (m_windows.elements > 0) explain_flags.set(ESC_WINDOWING, ESP_EXISTS);
  // Calculate the number of groups
  for (ORDER *group = group_list.order; group; group = group->next)
    send_group_parts++;
}

bool JOIN::alloc_ref_item_slice(THD *thd_arg, int sliceno) {
  assert(sliceno > 0);
  assert(ref_items[sliceno].is_null());
  size_t count = ref_items[0].size();
  Item **slice = thd_arg->mem_root->ArrayAlloc<Item *>(count);
  if (slice == nullptr) return true;
  ref_items[sliceno] = Ref_item_array(slice, count);
  return false;
}

bool JOIN::alloc_indirection_slices() {
  const int num_slices = REF_SLICE_WIN_1 + m_windows.elements;

  assert(ref_items == nullptr);
  ref_items = (*THR_MALLOC)->ArrayAlloc<Ref_item_array>(num_slices);
  if (ref_items == nullptr) return true;

  tmp_fields =
      (*THR_MALLOC)
          ->ArrayAlloc<mem_root_deque<Item *>>(num_slices, *THR_MALLOC);
  if (tmp_fields == nullptr) return true;

  return false;
}

/**
  The List<Item_equal> in COND_EQUAL partially overlaps with the argument list
  in various Item_cond via C-style casts. However, the hypergraph optimizer can
  modify the lists in Item_cond (by calling compile()), causing an Item_equal to
  be replaced with Item_func_eq, and this can cause a List<Item_equal> not to
  contain Item_equal pointers anymore. This is is obviously bad if anybody wants
  to actually look into these lists after optimization (in particular, NDB
  wants this).

  Since untangling this spaghetti seems very hard, we solve it by brute force:
  Make a copy of all the COND_EQUAL lists, so that they no longer reach into the
  Item_cond. This allows us to modify the Item_cond at will.
 */
static void SaveCondEqualLists(COND_EQUAL *cond_equal) {
  if (cond_equal == nullptr) {
    return;
  }
  List<Item_equal> copy;
  for (Item_equal &item : cond_equal->current_level) {
    copy.push_back(&item);
  }
  cond_equal->current_level = std::move(copy);
  SaveCondEqualLists(cond_equal->upper_levels);
}

bool JOIN::check_access_path_with_fts() const {
  // Only relevant to the old optimizer.
  assert(!thd->lex->using_hypergraph_optimizer());

  assert(query_block->has_ft_funcs());
  assert(rollup_state != RollupState::NONE);

  // Find all tables referenced from non-aggregated MATCH calls in the SELECT
  // list or in any hidden items lifted to the SELECT list from other clauses.
  table_map fulltext_tables = 0;
  for (Item *field : *fields) {
    WalkItem(field, enum_walk::PREFIX | enum_walk::POSTFIX,
             NonAggregatedFullTextSearchVisitor(
                 [&fulltext_tables](Item_func_match *item) {
                   fulltext_tables |= item->used_tables();
                   return false;
                 }));
  }

  if (fulltext_tables == 0) return false;

  // See if any of those tables is accessed without materialization between the
  // table access path and the aggregate access path.
  bool found = false;
  WalkAccessPaths(
      root_access_path(), this, WalkAccessPathPolicy::ENTIRE_QUERY_BLOCK,
      [fulltext_tables, &found](const AccessPath *path, const JOIN *) {
        if (path->type == AccessPath::AGGREGATE) {
          // Does the aggregate path access any of "fulltext_tables" without an
          // intermediate materialization step? GetUsedTableMap() does not see
          // through materialization and returns RAND_TABLE_BIT instead of the
          // actual tables if "path" reads materialized results.
          found |=
              Overlaps(fulltext_tables,
                       GetUsedTableMap(path, /*include_pruned_tables=*/true));
        }
        return found;
      });

  if (found) {
    my_error(ER_NOT_SUPPORTED_YET, MYF(0),
             "reading non-aggregated results of the MATCH full-text search "
             "function after GROUP BY WITH ROLLUP");
    return true;
  }

  return false;
}

/**
  Optimizes one query block into a query execution plan (QEP.)

  This is the entry point to the query optimization phase. This phase
  applies both logical (equivalent) query rewrites, cost-based join
  optimization, and rule-based access path selection. Once an optimal
  plan is found, the member function creates/initializes all
  structures needed for query execution. The main optimization phases
  are outlined below:

    -# Logical transformations:
      - Outer to inner joins transformation.
      - Equality/constant propagation.
      - Partition pruning.
      - COUNT(*), MIN(), MAX() constant substitution in case of
        implicit grouping.
      - ORDER BY optimization.
    -# Perform cost-based optimization of table order and access path
       selection. See JOIN::make_join_plan()
    -# Post-join order optimization:
       - Create optimal table conditions from the where clause and the
         join conditions.
       - Inject outer-join guarding conditions.
       - Adjust data access methods after determining table condition
         (several times.)
       - Optimize ORDER BY/DISTINCT.
    -# Code generation
       - Set data access functions.
       - Try to optimize away sorting/distinct.
       - Setup temporary table usage for grouping and/or sorting.

  @retval false Success.
  @retval true Error, error code saved in member JOIN::error.
*/
bool JOIN::optimize(bool finalize_access_paths) {
  DBUG_TRACE;

  uint no_jbuf_after = UINT_MAX;
  Query_block *const set_operand_block =
      query_expression()->non_simple_result_query_block();

  assert(query_block->leaf_table_count == 0 ||
         thd->lex->is_query_tables_locked() ||
         query_block == set_operand_block);
  assert(tables == 0 && primary_tables == 0 && tables_list == (Table_ref *)1);

  // to prevent double initialization on EXPLAIN
  if (optimized) return false;

  DEBUG_SYNC(thd, "before_join_optimize");

  THD_STAGE_INFO(thd, stage_optimizing);

  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_object trace_optimize(trace, "join_optimization");
  trace_optimize.add_select_number(query_block->select_number);
  Opt_trace_array trace_steps(trace, "steps");

  count_field_types(query_block, &tmp_table_param, *fields, false, false);

  assert(tmp_table_param.sum_func_count == 0 || !group_list.empty() ||
         implicit_grouping);

  const bool has_windows = m_windows.elements != 0;

  if (has_windows && Window::setup_windows2(thd, &m_windows))
    return true; /* purecov: inspected */

  if (query_block->olap == ROLLUP_TYPE && optimize_rollup())
    return true; /* purecov: inspected */

  if (alloc_func_list()) return true; /* purecov: inspected */

  if (query_block->get_optimizable_conditions(thd, &where_cond, &having_cond))
    return true;

  for (Item_rollup_group_item *item : query_block->rollup_group_items) {
    rollup_group_items.push_back(item);
  }
  for (Item_rollup_sum_switcher *item : query_block->rollup_sums) {
    rollup_sums.push_back(item);
  }

  set_optimized();

  tables_list = query_block->leaf_tables;

  if (alloc_indirection_slices()) return true;

  // The base ref items from query block are assigned as JOIN's ref items
  ref_items[REF_SLICE_ACTIVE] = query_block->base_ref_items;

  /* dump_TABLE_LIST_graph(query_block, query_block->leaf_tables); */
  /*
    Run optimize phase for all derived tables/views used in this SELECT,
    including those in semi-joins.
  */
  // if (query_block->materialized_derived_table_count) {
  {  // WL#6570
    for (Table_ref *tl = query_block->leaf_tables; tl; tl = tl->next_leaf) {
      tl->access_path_for_derived = nullptr;
      if (tl->is_view_or_derived()) {
        if (tl->optimize_derived(thd)) return true;
      } else if (tl->is_table_function()) {
        TABLE *const table = tl->table;
        if (!table->has_storage_handler()) {
          if (setup_tmp_table_handler(
                  thd, table,
                  query_block->active_options() | TMP_TABLE_ALL_COLUMNS))
            return true; /* purecov: inspected */
        }

        table->file->stats.records = 2;
      }
    }
  }

  if (thd->lex->using_hypergraph_optimizer()) {
    // The hypergraph optimizer also wants all subselect items to be optimized,
    // so that it has cost information to attach to filter nodes.
    for (Query_expression *unit = query_block->first_inner_query_expression();
         unit; unit = unit->next_query_expression()) {
      // Derived tables and const subqueries are already optimized
      if (!unit->is_optimized() &&
          unit->optimize(thd, /*materialize_destination=*/nullptr,
                         /*create_iterators=*/false,
                         /*finalize_access_paths=*/false))
        return true;
    }

    // The hypergraph optimizer does not do const tables,
    // nor does it evaluate subqueries during optimization.
    query_block->add_active_options(OPTION_NO_CONST_TABLES |
                                    OPTION_NO_SUBQUERY_DURING_OPTIMIZATION);
  }

  has_lateral = false;

  /* dump_TABLE_LIST_graph(query_block, query_block->leaf_tables); */

  row_limit = ((select_distinct || !order.empty() || !group_list.empty())
                   ? HA_POS_ERROR
                   : query_expression()->select_limit_cnt);
  // m_select_limit is used to decide if we are likely to scan the whole table.
  m_select_limit = query_expression()->select_limit_cnt;

  if (query_expression()->first_query_block()->active_options() &
      OPTION_FOUND_ROWS) {
    /*
      Calculate found rows (ie., keep counting rows even after we hit LIMIT) if
      - LIMIT is set, and
      - This is the outermost query block (for a UNION query, this is the
        block that contains the limit applied on the final UNION
        evaluation, cf query_term.h for explanation).
     */
    calc_found_rows = m_select_limit != HA_POS_ERROR &&
                      (!query_expression()->is_set_operation() ||
                       query_block == set_operand_block);
  }
  if (having_cond || calc_found_rows) m_select_limit = HA_POS_ERROR;

  if (query_expression()->select_limit_cnt == 0 && !calc_found_rows) {
    zero_result_cause = "Zero limit";
    best_rowcount = 0;
    create_access_paths_for_zero_rows();
    goto setup_subq_exit;
  }

  if (where_cond || query_block->outer_join) {
    if (optimize_cond(thd, &where_cond, &cond_equal, &query_block->m_table_nest,
                      &query_block->cond_value)) {
      error = 1;
      DBUG_PRINT("error", ("Error from optimize_cond"));
      return true;
    }
    if (query_block->cond_value == Item::COND_FALSE) {
      zero_result_cause = "Impossible WHERE";
      best_rowcount = 0;
      create_access_paths_for_zero_rows();
      goto setup_subq_exit;
    }
  }
  if (having_cond) {
    if (optimize_cond(thd, &having_cond, &cond_equal, nullptr,
                      &query_block->having_value)) {
      error = 1;
      DBUG_PRINT("error", ("Error from optimize_cond"));
      return true;
    }
    if (query_block->having_value == Item::COND_FALSE) {
      zero_result_cause = "Impossible HAVING";
      best_rowcount = 0;
      create_access_paths_for_zero_rows();
      goto setup_subq_exit;
    }
  }

  if (query_block->partitioned_table_count && prune_table_partitions()) {
    error = 1;
    DBUG_PRINT("error", ("Error from prune_partitions"));
    return true;
  }

  /*
     Try to optimize count(*), min() and max() to const fields if
     there is implicit grouping (aggregate functions but no
     group_list). In this case, the result set shall only contain one
     row.
  */
  if (tables_list && implicit_grouping &&
      !(query_block->active_options() & OPTION_NO_CONST_TABLES)) {
    aggregate_evaluated outcome;
    if (optimize_aggregated_query(thd, query_block, *fields, where_cond,
                                  &outcome)) {
      error = 1;
      DBUG_PRINT("error", ("Error from optimize_aggregated_query"));
      return true;
    }
    switch (outcome) {
      case AGGR_REGULAR:
        // Query was not (fully) evaluated. Revert to regular optimization.
        break;
      case AGGR_DELAYED:
        // Query was not (fully) evaluated. Revert to regular optimization,
        // but indicate that storage engine supports HA_COUNT_ROWS_INSTANT.
        select_count = true;
        break;
      case AGGR_COMPLETE: {
        // All SELECT expressions are fully evaluated
        DBUG_PRINT("info", ("Select tables optimized away"));
        zero_result_cause = "Select tables optimized away";
        tables_list = nullptr;  // All tables resolved
        best_rowcount = 1;
        const_tables = tables = primary_tables = query_block->leaf_table_count;
        AccessPath *path =
            NewFakeSingleRowAccessPath(thd, /*count_examined_rows=*/true);
        path = attach_access_paths_for_having_and_limit(path);
        m_root_access_path = path;
        /*
          There are no relevant conditions left from the WHERE;
          optimize_aggregated_query() will not return AGGR_COMPLETE if there are
          any table-independent conditions, and all other conditions have been
          optimized away by it. Thus, remove the condition, unless we have
          EXPLAIN (in which case we will keep it for printing).
        */
        if (!thd->lex->is_explain()) {
#ifndef NDEBUG
          // Verify, to be sure.
          if (where_cond != nullptr) {
            Item *table_independent_conds = make_cond_for_table(
                thd, where_cond, PSEUDO_TABLE_BITS, table_map(0),
                /*exclude_expensive_cond=*/true);
            assert(table_independent_conds == nullptr);
          }
#endif
          where_cond = nullptr;
        }
        goto setup_subq_exit;
      }
      case AGGR_EMPTY:
        // It was detected that the result tables are empty
        DBUG_PRINT("info", ("No matching min/max row"));
        zero_result_cause = "No matching min/max row";
        create_access_paths_for_zero_rows();
        goto setup_subq_exit;
    }
  }
  if (tables_list == nullptr) {
    DBUG_PRINT("info", ("No tables"));
    best_rowcount = 1;
    error = 0;
    if (make_tmp_tables_info()) return true;
    count_field_types(query_block, &tmp_table_param, *fields, false, false);
    // Make plan visible for EXPLAIN
    set_plan_state(NO_TABLES);
    create_access_paths();
    return false;
  }
  error = -1;  // Error is sent to client

  {
    m_windowing_steps = false;  // initialization
    m_windows_sort = false;
    List_iterator<Window> li(m_windows);
    Window *w;
    while ((w = li++))
      if (w->needs_sorting()) {
        m_windows_sort = true;
        break;
      }
  }

  sort_by_table = get_sort_by_table(order.order, group_list.order,
                                    query_block->leaf_tables);

  if ((where_cond || !group_list.empty() || !order.empty()) &&
      substitute_gc(thd, query_block, where_cond, group_list.order,
                    order.order)) {
    // We added hidden fields to the all_fields list, count them.
    count_field_types(query_block, &tmp_table_param, query_block->fields, false,
                      false);
  }
  // Ensure there are no errors prior making query plan
  if (thd->is_error()) return true;

  if (thd->lex->using_hypergraph_optimizer()) {
    // Get the WHERE and HAVING clauses with the IN-to-EXISTS predicates
    // removed, so that we can plan both with and without the IN-to-EXISTS
    // conversion.
    Item *where_cond_no_in2exists = remove_in2exists_conds(where_cond);
    Item *having_cond_no_in2exists = remove_in2exists_conds(having_cond);

    std::string trace_str;
    std::string *trace_ptr = thd->opt_trace.is_started() ? &trace_str : nullptr;

    SaveCondEqualLists(cond_equal);

    m_root_access_path = FindBestQueryPlan(thd, query_block, trace_ptr);
    if (finalize_access_paths && m_root_access_path != nullptr) {
      if (FinalizePlanForQueryBlock(thd, query_block)) {
        return true;
      }
    }

    // If this query block was modified by IN-to-EXISTS conversion,
    // the outer query block may want to undo that conversion and materialize
    // us instead, depending on cost. (Materialization has high initial cost,
    // but looking up in the materialized table is typically cheaper than
    // running the entire query.) If so, we will need to plan the query again,
    // but with all extra conditions added by IN-to-EXISTS removed, as those
    // are specific to the values referred to by the outer query.
    //
    // Thus, we detect this here, and plan a second query plan. There are
    // computations that could be shared between the two plans (e.g. join order
    // between tables for which there is no IN-to-EXISTS-related condition),
    // so it is somewhat wasteful, but experiments have shown that planning
    // both at the same time quickly clutters the code with such handling;
    // there are so many places such filters could be added (base table filters,
    // filters after various types of joins, join conditions, post-join filters,
    // HAVING, possibly others) that trying to plan paths both with and without
    // them incurs complexity that is not justified by the small computational
    // gain it would bring.
    if (where_cond != where_cond_no_in2exists ||
        having_cond != having_cond_no_in2exists) {
      if (trace_ptr != nullptr) {
        *trace_ptr +=
            "\nPlanning an alternative with in2exists conditions removed:\n";
      }
      where_cond = where_cond_no_in2exists;
      having_cond = having_cond_no_in2exists;
      assert(!finalize_access_paths);
      m_root_access_path_no_in2exists =
          FindBestQueryPlan(thd, query_block, trace_ptr);
    } else {
      m_root_access_path_no_in2exists = nullptr;
    }

    if (trace != nullptr) {
      Opt_trace_object trace_wrapper2(&thd->opt_trace);
      Opt_trace_array join_optimizer(&thd->opt_trace, "join_optimizer");

      // Split by newlines.
      for (size_t pos = 0; pos < trace_str.size();) {
        size_t len = strcspn(trace_str.data() + pos, "\n");
        join_optimizer.add_utf8(trace_str.data() + pos, len);
        pos += len + 1;
      }
    }
    if (m_root_access_path == nullptr) {
      return true;
    }
    set_plan_state(PLAN_READY);
    DEBUG_SYNC(thd, "after_join_optimize");
    return false;
  }

  // ----------------------------------------------------------------------------
  //       All of this is never called for the hypergraph join optimizer!
  // ----------------------------------------------------------------------------

  assert(!thd->lex->using_hypergraph_optimizer());
  // Don't expect to get here if the hypergraph optimizer is enabled via an
  // optimizer switch. We only check it for regular statements. Prepared
  // statements and stored programs use the optimizer that was active when the
  // statement was prepared, and don't check the optimizer switch for each
  // subsequent execution.
  assert(!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_HYPERGRAPH_OPTIMIZER) ||
         !thd->stmt_arena->is_regular());

  // Set up join order and initial access paths
  THD_STAGE_INFO(thd, stage_statistics);
  if (make_join_plan()) {
    if (thd->killed) thd->send_kill_message();
    DBUG_PRINT("error", ("Error: JOIN::make_join_plan() failed"));
    return true;
  }

  // At this stage, join_tab==NULL, JOIN_TABs are listed in order by best_ref.
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  if (zero_result_cause != nullptr) {  // Can be set by make_join_plan().
    create_access_paths_for_zero_rows();
    goto setup_subq_exit;
  }

  if (rollup_state == RollupState::NONE) {
    /* Remove distinct if only const tables */
    select_distinct &= !plan_is_const();
  }

  if (const_tables && !thd->locked_tables_mode &&
      !(query_block->active_options() & SELECT_NO_UNLOCK)) {
    TABLE *ct[MAX_TABLES];
    for (uint i = 0; i < const_tables; i++) {
      ct[i] = best_ref[i]->table();
      ct[i]->file->ha_index_or_rnd_end();
    }
    mysql_unlock_some_tables(thd, ct, const_tables);
  }
  if (!where_cond && query_block->outer_join) {
    /* Handle the case where we have an OUTER JOIN without a WHERE */
    where_cond = new Item_func_true();  // Always true
  }

  error = 0;
  /*
    Among the equal fields belonging to the same multiple equality
    choose the one that is to be retrieved first and substitute
    all references to these in where condition for a reference for
    the selected field.
  */
  if (where_cond) {
    where_cond =
        substitute_for_best_equal_field(thd, where_cond, cond_equal, map2table);
    if (thd->is_error()) {
      error = 1;
      DBUG_PRINT("error", ("Error from substitute_for_best_equal"));
      return true;
    }
    where_cond->update_used_tables();
    DBUG_EXECUTE("where",
                 print_where(thd, where_cond, "after substitute_best_equal",
                             QT_ORDINARY););
  }

  /*
    Perform the same optimization on field evaluation for all join conditions.
  */
  for (uint i = const_tables; i < tables; ++i) {
    JOIN_TAB *const tab = best_ref[i];
    if (tab->position() && tab->join_cond()) {
      tab->set_join_cond(substitute_for_best_equal_field(
          thd, tab->join_cond(), tab->cond_equal, map2table));
      if (thd->is_error()) {
        error = 1;
        DBUG_PRINT("error", ("Error from substitute_for_best_equal"));
        return true;
      }
      tab->join_cond()->update_used_tables();
      if (tab->join_cond())
        tab->join_cond()->walk(&Item::cast_incompatible_args,
                               enum_walk::POSTFIX, nullptr);
    }
  }

  if (init_ref_access()) {
    error = 1;
    DBUG_PRINT("error", ("Error from init_ref_access"));
    return true;
  }

  // Update table dependencies after assigning ref access fields
  update_depend_map();

  THD_STAGE_INFO(thd, stage_preparing);

  if (make_join_query_block(this, where_cond)) {
    if (thd->is_error()) return true;

    zero_result_cause = "Impossible WHERE noticed after reading const tables";
    create_access_paths_for_zero_rows();
    goto setup_subq_exit;
  }

  // Inject cast nodes into the WHERE conditions
  if (where_cond)
    where_cond->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX,
                     nullptr);

  error = -1; /* if goto err */

  if (optimize_distinct_group_order()) return true;

  if ((query_block->active_options() & SELECT_NO_JOIN_CACHE) ||
      query_block->ftfunc_list->elements)
    no_jbuf_after = 0;

  /* Perform FULLTEXT search before all regular searches */
  if (query_block->has_ft_funcs() && optimize_fts_query()) return true;

  /*
    By setting child_subquery_can_materialize so late we gain the following:
    JOIN::compare_costs_of_subquery_strategies() can test this variable to
    know if we are have finished evaluating constant conditions, which itself
    helps determining fanouts.
  */
  child_subquery_can_materialize = true;

  /*
    It's necessary to check const part of HAVING cond as
    there is a chance that some cond parts may become
    const items after make_join_plan() (for example
    when Item is a reference to const table field from
    outer join).
    This check is performed only for those conditions
    which do not use aggregate functions. In such case
    temporary table may not be used and const condition
    elements may be lost during further having
    condition transformation in JOIN::exec.
  */
  if (having_cond && !having_cond->has_aggregation() && (const_tables > 0)) {
    having_cond->update_used_tables();
    if (remove_eq_conds(thd, having_cond, &having_cond,
                        &query_block->having_value)) {
      error = 1;
      DBUG_PRINT("error", ("Error from remove_eq_conds"));
      return true;
    }
    if (query_block->having_value == Item::COND_FALSE) {
      having_cond = new Item_func_false();
      zero_result_cause =
          "Impossible HAVING noticed after reading const tables";
      create_access_paths_for_zero_rows();
      goto setup_subq_exit;
    }
  }

  // Inject cast nodes into the HAVING conditions
  if (having_cond)
    having_cond->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX,
                      nullptr);

  // Traverse the expressions and inject cast nodes to compatible data types,
  // if needed.
  for (Item *item : *fields) {
    item->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX, nullptr);
  }

  // Also GROUP BY expressions, so that find_in_group_list() doesn't
  // inadvertently fail because the SELECT list has casts that GROUP BY doesn't.
  for (ORDER *ord = group_list.order; ord != nullptr; ord = ord->next) {
    (*ord->item)
        ->walk(&Item::cast_incompatible_args, enum_walk::POSTFIX, nullptr);
  }

  // See if this subquery can be evaluated with subselect_indexsubquery_engine
  if (const int ret = replace_index_subquery()) {
    if (ret == -1) {
      // Error (e.g. allocation failed, or some condition was attempted
      // evaluated statically and failed).
      return true;
    }

    create_access_paths_for_index_subquery();
    set_plan_state(PLAN_READY);
    /*
      We leave optimize() because the rest of it is only about order/group
      which those subqueries don't have and about setting up plan which
      we're not going to use due to different execution method.
    */
    return false;
  }

  {
    /*
      If the hint FORCE INDEX FOR ORDER BY/GROUP BY is used for the first
      table (it does not make sense for other tables) then we cannot do join
      buffering.
    */
    if (!plan_is_const()) {
      const TABLE *const first = best_ref[const_tables]->table();
      if ((first->force_index_order && !order.empty()) ||
          (first->force_index_group && !group_list.empty()))
        no_jbuf_after = 0;
    }

    bool simple_sort = true;
    Table_map_restorer deps_lateral(&deps_of_remaining_lateral_derived_tables);
    // Check whether join cache could be used
    for (uint i = const_tables; i < tables; i++) {
      JOIN_TAB *const tab = best_ref[i];
      if (!tab->position()) continue;
      if (setup_join_buffering(tab, this, no_jbuf_after)) return true;
      if (tab->use_join_cache() != JOIN_CACHE::ALG_NONE) simple_sort = false;
      assert(tab->type() != JT_FT ||
             tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
      if (has_lateral && get_lateral_deps(*best_ref[i]) != 0) {
        deps_of_remaining_lateral_derived_tables =
            calculate_deps_of_remaining_lateral_derived_tables(all_table_map,
                                                               i + 1);
      }
    }
    if (!simple_sort) {
      /*
        A join buffer is used for this table. We here inform the optimizer
        that it should not rely on rows of the first non-const table being in
        order thanks to an index scan; indeed join buffering of the present
        table subsequently changes the order of rows.
      */
      simple_order = simple_group = false;
    }
  }

  if (!plan_is_const() && !order.empty()) {
    /*
      Force using of tmp table if sorting by a SP or UDF function due to
      their expensive and probably non-deterministic nature.
    */
    for (ORDER *tmp_order = order.order; tmp_order;
         tmp_order = tmp_order->next) {
      Item *item = *tmp_order->item;
      if (item->is_expensive()) {
        /* Force tmp table without sort */
        simple_order = simple_group = false;
        break;
      }
    }
  }

  /*
    Check if we need to create a temporary table prior to any windowing.

    (1) If there is ROLLUP, which happens before DISTINCT, windowing and ORDER
    BY, any of those clauses needs the result of ROLLUP in a tmp table.

    Rows which ROLLUP adds to the result are visible only to DISTINCT,
    windowing and ORDER BY which we handled above. So for the rest of
    conditions ((2), etc), we can do as if there were no ROLLUP.

    (2) If all tables are constant, the query's result is guaranteed to have 0
    or 1 row only, so all SQL clauses discussed below (DISTINCT, ORDER BY,
    GROUP BY, windowing, SQL_BUFFER_RESULT) are useless and need no tmp
    table.

    (3) If there is GROUP BY which isn't resolved by using an index or sorting
    the first table, we need a tmp table to compute the grouped rows.
    GROUP BY happens before windowing; so it is a pre-windowing tmp
    table.

    (4) (5) If there is DISTINCT, or ORDER BY which isn't resolved by using an
    index or sorting the first table, those clauses need an input tmp table.
    If we have windowing, as those clauses are used after windowing, they can
    use the last window's tmp table.

    (6) If there are different ORDER BY and GROUP BY orders, ORDER BY needs an
    input tmp table, so it's like (5).

    (7) If the user wants us to buffer the result, we need a tmp table. But
    windowing creates one anyway, and so does the materialization of a derived
    table.

    See also the computation of Window::m_short_circuit,
    where we make sure to create a tmp table if the clauses above want one.

    (8) If the first windowing step needs sorting, filesort() will be used; it
    can sort one table but not a join of tables, so we need a tmp table
    then. If GROUP BY was optimized away, the pre-windowing result is 0 or 1
    row so doesn't need sorting.
  */

  if (rollup_state != RollupState::NONE &&  // (1)
      (select_distinct || has_windows || !order.empty()))
    need_tmp_before_win = true;

  /*
    If we have full-text columns involved in aggregation, we may need to
    materialize them. Materialization is needed if the result of a full-text
    search (the MATCH function) is accessed after aggregation, as the saving and
    loading of rows in AggregateIterator does not include FTS information. If we
    have a GROUP BY, we'll either have an aggregate-to-table or a sort, which
    fixes the issue. However, in the case of implicit grouping, we need to force
    the temporary table here.
   */
  if (!need_tmp_before_win && implicit_grouping &&
      contains_non_aggregated_fts()) {
    need_tmp_before_win = true;
  }

  if (!plan_is_const())  // (2)
  {
    if ((!group_list.empty() && !simple_group) ||                       // (3)
        (!has_windows && (select_distinct ||                            // (4)
                          (!order.empty() && !simple_order) ||          // (5)
                          (!group_list.empty() && !order.empty()))) ||  // (6)
        ((query_block->active_options() & OPTION_BUFFER_RESULT) &&
         !has_windows &&
         !(query_expression()->derived_table &&
           query_expression()
               ->derived_table->uses_materialization())) ||     // (7)
        (has_windows && (primary_tables - const_tables) > 1 &&  // (8)
         m_windows[0]->needs_sorting() && !group_optimized_away))
      need_tmp_before_win = true;
  }

  DBUG_EXECUTE("info", TEST_join(this););

  if (alloc_qep(tables)) return (error = 1); /* purecov: inspected */

  if (!plan_is_const()) {
    // Test if we can use an index instead of sorting
    test_skip_sort();

    if (finalize_table_conditions(thd)) return true;
  }

  if (make_join_readinfo(this, no_jbuf_after))
    return true; /* purecov: inspected */

  if (make_tmp_tables_info()) return true;

  /*
    If we decided to not sort after all, update the cost of the JOIN.
    Windowing sorts are handled elsewhere
  */
  if (sort_cost > 0.0 &&
      !explain_flags.any(ESP_USING_FILESORT, ESC_WINDOWING)) {
    best_read -= sort_cost;
    sort_cost = 0.0;
  }

  count_field_types(query_block, &tmp_table_param, *fields, false, false);

  create_access_paths();

  // Creating iterators may evaluate a constant hash join condition, which may
  // fail:
  if (thd->is_error()) return true;

  if (rollup_state != RollupState::NONE && query_block->has_ft_funcs()) {
    if (check_access_path_with_fts()) {
      return true;
    }
  }

  /*
    At this stage, we have set up an AccessPath 'plan'. Traverse the
    AccessPath structures and find components which may be offloaded to
    the engines. This process is allowed to modify the AccessPath itself.
    (Removing/modifying FILTERs where pushed to the engines, change JOIN*
    algorithms being used, modify aggregate expressions, ...).
    This will later affects which type of Iterator we should create. Thus no
    Iterators should be set up until after push_to_engines() has completed.

    Note that when the Hypergraph optimizer is used, there is an entirely
    different code path to push_to_engine(). (We create the AcccesPath directly
    instead of converting the QEP_TABs into an AccessPath structure).
    In the HG case we push_to_engine() when FinalizePlanForQueryBlock()
    has finalized the 'plan'.
  */
  if (push_to_engines()) return true;

  // Make plan visible for EXPLAIN
  set_plan_state(PLAN_READY);

  DEBUG_SYNC(thd, "after_join_optimize");

  error = 0;
  return false;

setup_subq_exit:

  assert(zero_result_cause != nullptr);
  assert(m_root_access_path != nullptr);
  /*
    Even with zero matching rows, subqueries in the HAVING clause may
    need to be evaluated if there are aggregate functions in the
    query. If this JOIN is part of an outer query, subqueries in HAVING may
    be evaluated several times in total; so subquery materialization makes
    sense.
  */
  child_subquery_can_materialize = true;

  trace_steps.end();  // because all steps are done
  Opt_trace_object(trace, "empty_result").add_alnum("cause", zero_result_cause);

  having_for_explain = having_cond;
  error = 0;

  if (!qep_tab && best_ref) {
    /*
      After creation of JOIN_TABs in make_join_plan(), we have shortcut due to
      some zero_result_cause. For simplification, if we have JOIN_TABs we
      want QEP_TABs too.
    */
    if (alloc_qep(tables)) return true; /* purecov: inspected */
    unplug_join_tabs();
  }

  set_plan_state(ZERO_RESULT);
  return false;
}

void JOIN::change_to_access_path_without_in2exists() {
  if (m_root_access_path_no_in2exists != nullptr) {
    m_root_access_path = m_root_access_path_no_in2exists;
  }
}

void JOIN::create_access_paths_for_zero_rows() {
  if (send_row_on_empty_set()) {
    // Aggregate no rows into an aggregate row.
    m_root_access_path =
        NewZeroRowsAggregatedAccessPath(thd, zero_result_cause);
    m_root_access_path =
        attach_access_paths_for_having_and_limit(m_root_access_path);
  } else {
    // Send no row at all (so also no need to check HAVING or LIMIT).
    m_root_access_path = NewZeroRowsAccessPath(thd, zero_result_cause);
  }
  m_root_access_path =
      attach_access_path_for_update_or_delete(m_root_access_path);
}

/**
  Push (parts of) the query execution down to the storage engines if they
  can provide faster execution of the query, or part of it.

  The handler will inspect the QEP through the
  AQP (Abstract Query Plan) and extract from it whatever
  it might implement of pushed execution.

  It is the responsibility of the handler to store
  any information it need for the later execution of
  pushed queries and conditions.

  @retval false Success.
  @retval true Error, error code saved in member JOIN::error.
*/
bool JOIN::push_to_engines() {
  DBUG_TRACE;
  assert(m_root_access_path != nullptr);

  for (Table_ref *tl = query_block->leaf_tables; tl; tl = tl->next_leaf) {
    const handlerton *hton = tl->table->file->hton_supporting_engine_pushdown();
    if (hton != nullptr) {  // Involved an engine supporting pushdown.
      if (unlikely(hton->push_to_engine(thd, m_root_access_path, this))) {
        return true;
      }
      break;  // Assume that at most a single handlerton per query support
              // pushdown
    }
  }
  return false;
}

/**
  Substitute all expressions in the WHERE condition and ORDER/GROUP lists
  that match generated columns (GC) expressions with GC fields, if any.

  @details This function does 3 things:
  1) Creates list of all GC fields that are a part of a key and the GC
    expression is a function. All query tables are scanned. If there's no
    such fields, function exits.
  2) By means of Item::compile() WHERE clause is transformed.
    @see Item_func::gc_subst_transformer() for details.
  3) If there's ORDER/GROUP BY clauses, this function tries to substitute
    expressions in these lists with GC too. It removes from the list of
    indexed GC all elements which index blocked by hints. This is done to
    reduce amount of further work. Next it goes through ORDER/GROUP BY list
    and matches the expression in it against GC expressions in indexed GC
    list. When a match is found, the expression is replaced with a new
    Item_field for the matched GC field. Also, this new field is added to
    the hidden part of all_fields list.

  @param thd         thread handle
  @param query_block  the current select
  @param where_cond  the WHERE condition, possibly NULL
  @param group_list  the GROUP BY clause, possibly NULL
  @param order       the ORDER BY clause, possibly NULL

  @return true if the GROUP BY clause or the ORDER BY clause was
          changed, false otherwise
*/

bool substitute_gc(THD *thd, Query_block *query_block, Item *where_cond,
                   ORDER *group_list, ORDER *order) {
  List<Field> indexed_gc;
  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_object subst_gc(trace, "substitute_generated_columns");

  // Collect all GCs that are a part of a key
  for (Table_ref *tl = query_block->leaf_tables; tl; tl = tl->next_leaf) {
    if (tl->table->s->keys == 0) continue;
    for (uint i = 0; i < tl->table->s->fields; i++) {
      Field *fld = tl->table->field[i];
      if (fld->is_gcol() &&
          !(fld->part_of_key.is_clear_all() &&
            fld->part_of_prefixkey.is_clear_all()) &&
          fld->gcol_info->expr_item->can_be_substituted_for_gc()) {
        // Don't check allowed keys here as conditions/group/order use
        // different keymaps for that.
        indexed_gc.push_back(fld);
      }
    }
  }
  // No GC in the tables used in the query
  if (indexed_gc.elements == 0) return false;

  if (where_cond) {
    // Item_func::compile will dereference this pointer, provide valid value.
    uchar i, *dummy = &i;
    if (where_cond->compile(&Item::gc_subst_analyzer, &dummy,
                            &Item::gc_subst_transformer,
                            pointer_cast<uchar *>(&indexed_gc)) == nullptr)
      return true;
    subst_gc.add("resulting_condition", where_cond);
  }

  // An error occur during substitution. Let caller handle it.
  if (thd->is_error()) return false;

  if (!(group_list || order)) return false;
  // Filter out GCs that do not have index usable for GROUP/ORDER
  Field *gc;
  List_iterator<Field> li(indexed_gc);

  while ((gc = li++)) {
    Key_map tkm = gc->part_of_key;
    tkm.intersect(group_list ? gc->table->keys_in_use_for_group_by
                             : gc->table->keys_in_use_for_order_by);
    if (tkm.is_clear_all()) li.remove();
  }
  if (!indexed_gc.elements) return false;

  // Index could be used for ORDER only if there is no GROUP
  ORDER *list = group_list ? group_list : order;
  bool changed = false;
  for (ORDER *ord = list; ord; ord = ord->next) {
    li.rewind();
    if (!(*ord->item)->can_be_substituted_for_gc()) continue;
    while ((gc = li++)) {
      Item_field *const field =
          get_gc_for_expr(*ord->item, gc, gc->result_type());
      if (field != nullptr) {
        changed = true;
        /* Add new field to field list. */
        Item **new_field = query_block->add_hidden_item(field);
        thd->change_item_tree(ord->item, *new_field);
        query_block->hidden_items_from_optimization++;
        break;
      }
    }
  }
  // An error occur during substitution. Let caller handle it.
  if (thd->is_error()) return false;

  if (changed && trace->is_started()) {
    String str;
    Query_block::print_order(
        thd, &str, list,
        enum_query_type(QT_TO_SYSTEM_CHARSET | QT_SHOW_SELECT_NUMBER |
                        QT_NO_DEFAULT_DB));
    subst_gc.add_utf8(group_list ? "resulting_GROUP_BY" : "resulting_ORDER_BY",
                      str.ptr(), str.length());
  }
  return changed;
}

/**
   Sets the plan's state of the JOIN. This is always the final step of
   optimization; starting from this call, we expose the plan to other
   connections (via EXPLAIN CONNECTION) so the plan has to be final.
   keyread_optim is set here.
 */
void JOIN::set_plan_state(enum_plan_state plan_state_arg) {
  // A plan should not change to another plan:
  assert(plan_state_arg == NO_PLAN || plan_state == NO_PLAN);
  if (plan_state == NO_PLAN && plan_state_arg != NO_PLAN) {
    if (qep_tab != nullptr) {
      /*
        We want to cover primary tables, tmp tables. Note that
        make_tmp_tables_info() may have added a sort to the first non-const
        primary table, so it's important to do this assignment after
        make_tmp_tables_info().
      */
      for (uint i = const_tables; i < tables; ++i) {
        qep_tab[i].set_condition_optim();
        qep_tab[i].set_keyread_optim();
      }
    }
  }

  DEBUG_SYNC(thd, "before_set_plan");

  // If SQLCOM_END, no thread is explaining our statement anymore.
  const bool need_lock = thd->query_plan.get_command() != SQLCOM_END;

  if (need_lock) thd->lock_query_plan();
  plan_state = plan_state_arg;
  if (need_lock) thd->unlock_query_plan();
}

bool JOIN::alloc_qep(uint n) {
  static_assert(MAX_TABLES <= INT_MAX8, "plan_idx needs to be wide enough.");

  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  qep_tab = new (thd->mem_root)
      QEP_TAB[n + 1];        // The last one holds only the final op_type.
  if (!qep_tab) return true; /* purecov: inspected */
  for (uint i = 0; i < n; ++i) qep_tab[i].init(best_ref[i]);
  return false;
}

void QEP_TAB::init(JOIN_TAB *jt) {
  jt->share_qs(this);
  set_table(table());  // to update table()->reginfo.qep_tab
  table_ref = jt->table_ref;
}

/// @returns semijoin strategy for this table.
uint QEP_TAB::get_sj_strategy() const {
  if (first_sj_inner() == NO_PLAN_IDX) return SJ_OPT_NONE;
  const uint s = join()->qep_tab[first_sj_inner()].position()->sj_strategy;
  assert(s != SJ_OPT_NONE);
  return s;
}

/**
  Return the index used for a table in a QEP

  The various access methods have different places where the index/key
  number is stored, so this function is needed to return the correct value.

  @returns index number, or MAX_KEY if not applicable.

  JT_SYSTEM and JT_ALL does not use an index, and will always return MAX_KEY.

  JT_INDEX_MERGE supports more than one index. Hence MAX_KEY is returned and
  a further inspection is needed.
*/
uint QEP_TAB::effective_index() const {
  switch (type()) {
    case JT_SYSTEM:
      assert(ref().key == -1);
      return MAX_KEY;

    case JT_CONST:
    case JT_EQ_REF:
    case JT_REF_OR_NULL:
    case JT_REF:
      assert(ref().key != -1);
      return uint(ref().key);

    case JT_INDEX_SCAN:
    case JT_FT:
      return index();

    case JT_INDEX_MERGE:
      assert(used_index(range_scan()) == MAX_KEY);
      return MAX_KEY;

    case JT_RANGE:
      return used_index(range_scan());

    case JT_ALL:
    default:
      // @todo Check why JT_UNKNOWN is a valid value here.
      assert(type() == JT_ALL || type() == JT_UNKNOWN);
      return MAX_KEY;
  }
}

uint JOIN_TAB::get_sj_strategy() const {
  if (first_sj_inner() == NO_PLAN_IDX) return SJ_OPT_NONE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(join());
  JOIN_TAB *tab = join()->best_ref[first_sj_inner()];
  uint s = tab->position()->sj_strategy;
  assert(s != SJ_OPT_NONE);
  return s;
}

int JOIN::replace_index_subquery() {
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  if (!group_list.empty() ||
      !(query_expression()->item &&
        query_expression()->item->substype() == Item_subselect::IN_SUBS) ||
      primary_tables != 1 || !where_cond ||
      query_expression()->is_set_operation())
    return 0;

  // Guaranteed by remove_redundant_subquery_clauses():
  assert(order.empty() && !select_distinct);

  Item_in_subselect *const in_subs =
      static_cast<Item_in_subselect *>(query_expression()->item);
  bool found_engine = false;

  JOIN_TAB *const first_join_tab = best_ref[0];

  if (in_subs->strategy == Subquery_strategy::SUBQ_MATERIALIZATION) {
    // We cannot have two engines at the same time
  } else if (first_join_tab->table_ref->is_view_or_derived() &&
             first_join_tab->table_ref->derived_query_expression()
                 ->is_recursive()) {
    // The index subquery engine, which runs the derived table machinery
    // from the old executor, is not capable of materializing a WITH RECURSIVE
    // query from the iterator executor. Thus, be conservative here, so that the
    // case never happens.
  } else if (having_cond == nullptr) {
    const join_type type = first_join_tab->type();
    if ((type == JT_EQ_REF || type == JT_REF) &&
        first_join_tab->ref().items[0]->item_name.ptr() == in_left_expr_name) {
      found_engine = true;
    }
  } else if (first_join_tab->type() == JT_REF_OR_NULL &&
             first_join_tab->ref().items[0]->item_name.ptr() ==
                 in_left_expr_name &&
             having_cond->created_by_in2exists()) {
    found_engine = true;
  }

  if (!found_engine) return 0;

  /* Remove redundant predicates and cache constant expressions  */
  if (finalize_table_conditions(thd)) return -1;

  if (alloc_qep(tables)) return -1; /* purecov: inspected */
  unplug_join_tabs();

  error = 0;
  QEP_TAB *const first_qep_tab = &qep_tab[0];

  if (first_qep_tab->table()->covering_keys.is_set(first_qep_tab->ref().key)) {
    assert(!first_qep_tab->table()->no_keyread);
    first_qep_tab->table()->set_keyread(true);
  }

  subselect_indexsubquery_engine *engine =
      new (thd->mem_root) subselect_indexsubquery_engine(
          first_qep_tab->table(), first_qep_tab->table_ref,
          first_qep_tab->ref(), first_qep_tab->type(),
          down_cast<Item_in_subselect *>(query_expression()->item),
          first_qep_tab->condition(), having_cond);
  query_expression()->item->set_indexsubquery_engine(engine);
  return 1;
}

bool JOIN::optimize_distinct_group_order() {
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  const bool windowing = m_windows.elements > 0;
  const bool may_trace = select_distinct || !group_list.empty() ||
                         !order.empty() || windowing ||
                         tmp_table_param.sum_func_count;
  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_disable_I_S trace_disabled(trace, !may_trace);
  Opt_trace_object wrapper(trace);
  Opt_trace_object trace_opt(trace, "optimizing_distinct_group_by_order_by");
  /* Optimize distinct away if possible */
  {
    ORDER *org_order = order.order;
    order = ORDER_with_src(
        remove_const(order.order, where_cond, rollup_state == RollupState::NONE,
                     &simple_order, false),
        order.src, /*const_optimized=*/true);
    if (thd->is_error()) {
      error = 1;
      DBUG_PRINT("error", ("Error from remove_const"));
      return true;
    }

    /*
      If we are using ORDER BY NULL or ORDER BY const_expression,
      return result in any order (even if we are using a GROUP BY)
    */
    if (order.empty() && org_order) skip_sort_order = true;
  }
  /*
     Check if we can optimize away GROUP BY/DISTINCT.
     We can do that if there are no aggregate functions, the
     fields in DISTINCT clause (if present) and/or columns in GROUP BY
     (if present) contain direct references to all key parts of
     an unique index (in whatever order) and if the key parts of the
     unique index cannot contain NULLs.
     Note that the unique keys for DISTINCT and GROUP BY should not
     be the same (as long as they are unique).

     The FROM clause must contain a single non-constant table.

     @todo Apart from the LIS test, every condition depends only on facts
     which can be known in Query_block::prepare(), possibly this block should
     move there.
  */

  JOIN_TAB *const tab = best_ref[const_tables];

  if (plan_is_single_table() && (!group_list.empty() || select_distinct) &&
      !tmp_table_param.sum_func_count &&
      (!tab->range_scan() ||
       tab->range_scan()->type != AccessPath::GROUP_INDEX_SKIP_SCAN)) {
    if (!group_list.empty() && rollup_state == RollupState::NONE &&
        list_contains_unique_index(tab, find_field_in_order_list,
                                   (void *)group_list.order)) {
      /*
        We have found that grouping can be removed since groups correspond to
        only one row anyway.
      */
      group_list.clean();
      grouped = false;
    }
    if (select_distinct &&
        list_contains_unique_index(tab, find_field_in_item_list, fields)) {
      select_distinct = false;
      trace_opt.add("distinct_is_on_unique", true)
          .add("removed_distinct", true);
    }
  }
  if (!(!group_list.empty() || tmp_table_param.sum_func_count || windowing) &&
      select_distinct &&
      (plan_is_single_table() || query_block->original_tables_map == 1) &&
      rollup_state == RollupState::NONE) {
    int order_idx = -1, group_idx = -1;
    /*
      We are only using one table. In this case we change DISTINCT to a
      GROUP BY query if:
      - The GROUP BY can be done through indexes (no sort) and the ORDER
        BY only uses selected fields.
        (In this case we can later optimize away GROUP BY and ORDER BY)
      - We are scanning the whole table without LIMIT
        This can happen if:
        - We are using CALC_FOUND_ROWS
        - We are using an ORDER BY that can't be optimized away.
      - Selected expressions are not set functions (those cannot be put
      into GROUP BY).

      We don't want to use this optimization when we are using LIMIT
      because in this case we can just create a temporary table that
      holds LIMIT rows and stop when this table is full.
    */
    if (!order.empty()) {
      skip_sort_order = test_if_skip_sort_order(
          tab, order, m_select_limit,
          true,  // no_changes
          &tab->table()->keys_in_use_for_order_by, &order_idx);
      count_field_types(query_block, &tmp_table_param, *fields, false, false);
    }
    ORDER *o;
    bool all_order_fields_used;
    if ((o = create_order_from_distinct(
             thd, ref_items[REF_SLICE_ACTIVE], order.order, fields,
             /*skip_aggregates=*/true,
             /*convert_bit_fields_to_long=*/true, &all_order_fields_used))) {
      group_list = ORDER_with_src(o, ESC_DISTINCT);
      const bool skip_group =
          skip_sort_order &&
          test_if_skip_sort_order(tab, group_list, m_select_limit,
                                  true,  // no_changes
                                  &tab->table()->keys_in_use_for_group_by,
                                  &group_idx);
      count_field_types(query_block, &tmp_table_param, *fields, false, false);
      // ORDER BY and GROUP BY are using different indexes, can't skip sorting
      if (group_idx >= 0 && order_idx >= 0 && group_idx != order_idx)
        skip_sort_order = false;
      if ((skip_group && all_order_fields_used) ||
          m_select_limit == HA_POS_ERROR ||
          (!order.empty() && !skip_sort_order)) {
        /*  Change DISTINCT to GROUP BY */
        select_distinct = false;
        /*
          group_list was created with ORDER BY clause as prefix and
          replaces it. So it must respect ordering. If there is no
          ORDER BY, GROUP BY need not have to provide order.
        */
        if (order.empty()) {
          for (ORDER *group = group_list.order; group; group = group->next)
            group->direction = ORDER_NOT_RELEVANT;
        }
        if (all_order_fields_used && skip_sort_order && !order.empty()) {
          /*
            Force MySQL to read the table in sorted order to get result in
            ORDER BY order.
          */
          tmp_table_param.allow_group_via_temp_table = false;
        }
        grouped = true;  // For end_write_group
        trace_opt.add("changed_distinct_to_group_by", true);
      } else
        group_list.clean();
    } else if (thd->is_fatal_error())  // End of memory
      return true;
  }
  simple_group = false;

  ORDER *old_group_list = group_list.order;
  group_list = ORDER_with_src(
      remove_const(group_list.order, where_cond,
                   rollup_state == RollupState::NONE, &simple_group, true),
      group_list.src, /*const_optimized=*/true);
  if (thd->is_error()) {
    error = 1;
    DBUG_PRINT("error", ("Error from remove_const"));
    return true;
  }
  if (old_group_list && group_list.empty()) select_distinct = false;

  if (group_list.empty() && grouped) {
    order.clean();  // The output has only one row
    simple_order = true;
    select_distinct = false;  // No need in distinct for 1 row
    group_optimized_away = true;
  }

  calc_group_buffer(this, group_list.order);
  send_group_parts = tmp_table_param.group_parts; /* Save org parts */

  /*
     If ORDER BY is a prefix of GROUP BY and if windowing or ROLLUP
     doesn't change this order, ORDER BY can be removed and we can
     enforce GROUP BY to provide order.
     Also true if the result is one row.
  */
  if ((test_if_subpart(group_list.order, order.order) && !m_windows_sort &&
       query_block->olap != ROLLUP_TYPE) ||
      (group_list.empty() && tmp_table_param.sum_func_count)) {
    if (!order.empty()) {
      order.clean();
      trace_opt.add("removed_order_by", true);
    }
    if (is_indexed_agg_distinct(this, nullptr)) streaming_aggregation = false;
  }

  return false;
}

void JOIN::test_skip_sort() {
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  JOIN_TAB *const tab = best_ref[const_tables];

  assert(m_ordered_index_usage == ORDERED_INDEX_VOID);

  if (!group_list.empty())  // GROUP BY honoured first
                            // (DISTINCT was rewritten to GROUP BY if skippable)
  {
    /*
      If the SQL_BIG_RESULT option is set on the query block or a JSON
      aggregation function is used, check if it is possible to sort using index
      for GROUP BY and thus avoid materializing the row set to disk, unless:

      1. A group min-max optimization will be used, or
      2. Some non-aggregated full-text search results must be accessible after
         aggregation.
    */
    if (!(query_block->active_options() & SELECT_BIG_RESULT || with_json_agg) ||
        (tab->range_scan() &&
         tab->range_scan()->type == AccessPath::GROUP_INDEX_SKIP_SCAN) ||
        contains_non_aggregated_fts()) {
      if (simple_group &&    // GROUP BY is possibly skippable
          !select_distinct)  // .. if not preceded by a DISTINCT
      {
        /*
          Calculate a possible 'limit' of table rows for 'GROUP BY':
          A specified 'LIMIT' is relative to the final resultset.
          'need_tmp' implies that there will be more postprocessing
          so the specified 'limit' should not be enforced yet.
         */
        const ha_rows limit =
            (need_tmp_before_win ? HA_POS_ERROR : m_select_limit);
        int dummy;

        if (test_if_skip_sort_order(tab, group_list, limit, false,
                                    &tab->table()->keys_in_use_for_group_by,
                                    &dummy)) {
          m_ordered_index_usage = ORDERED_INDEX_GROUP_BY;
        }
      }

      /*
        If we are going to use semi-join LooseScan, it will depend
        on the selected index scan to be used.  If index is not used
        for the GROUP BY, we risk that sorting is put on the LooseScan
        table.  In order to avoid this, force use of temporary table.
        TODO: Explain the allow_group_via_temp_table part of the test below.
       */
      if ((m_ordered_index_usage != ORDERED_INDEX_GROUP_BY) &&
          (tmp_table_param.allow_group_via_temp_table ||
           (tab->emb_sj_nest &&
            tab->position()->sj_strategy == SJ_OPT_LOOSE_SCAN))) {
        need_tmp_before_win = true;
        simple_order = simple_group = false;  // Force tmp table without sort
      }
    }
  } else if (!order.empty() &&  // ORDER BY wo/ preceding GROUP BY
             (simple_order ||
              skip_sort_order) &&  // which is possibly skippable,
             !m_windows_sort)      // and WFs will not shuffle rows
  {
    int dummy;
    if ((skip_sort_order = test_if_skip_sort_order(
             tab, order, m_select_limit, false,
             &tab->table()->keys_in_use_for_order_by, &dummy))) {
      m_ordered_index_usage = ORDERED_INDEX_ORDER_BY;
      /*
        Update plan cost if there is only one table. Multi-table/join scenarios
        are more complex and will not reflect updated costs after access change.
      */
      if (primary_tables == 1 && tab->table()->s->has_secondary_engine()) {
        best_read = qep_tab->position()->prefix_cost + sort_cost;
      }
    }
  }
}

/**
  Test if ORDER BY is a single MATCH function(ORDER BY MATCH)
  and sort order is descending.

  @param order                 pointer to ORDER struct.

  @retval
    Pointer to MATCH function if order is 'ORDER BY MATCH() DESC'
  @retval
    NULL otherwise
*/

static Item_func_match *test_if_ft_index_order(ORDER *order) {
  if (order && order->next == nullptr && order->direction == ORDER_DESC &&
      is_function_of_type(*order->item, Item_func::FT_FUNC))
    return down_cast<Item_func_match *>(*order->item)->get_master();

  return nullptr;
}

/**
  Test if this is a prefix index.

  @param   table     table
  @param   idx       index to check

  @return TRUE if this is a prefix index
*/
bool is_prefix_index(TABLE *table, uint idx) {
  if (!table || !table->key_info) {
    return false;
  }

  KEY *key_info = table->key_info;
  uint key_parts = key_info[idx].user_defined_key_parts;
  KEY_PART_INFO *key_part = key_info[idx].key_part;

  for (uint i = 0; i < key_parts; i++, key_part++) {
    if (key_part->field &&
        !(table->field[key_part->fieldnr - 1]
              ->part_of_prefixkey.is_clear_all()) &&
        !(key_info->flags & (HA_FULLTEXT | HA_SPATIAL))) {
      return true;
    }
  }
  return false;
}

/**
  Test if one can use the key to resolve ordering.

  @param order_src           Sort order
  @param table               Table to sort
  @param idx                 Index to check
  @param[out] used_key_parts NULL by default, otherwise return value for
                             used key parts.
  @param[out] skip_quick     Whether found index can be used for backward range
                             scans

  @note
    used_key_parts is set to correct key parts used if return value != 0
    (On other cases, used_key_part may be changed)
    Note that the value may actually be greater than the number of index
    key parts. This can happen for storage engines that have the primary
    key parts as a suffix for every secondary key.

  @retval
    1   key is ok.
  @retval
    0   Key can't be used
  @retval
    -1   Reverse key can be used
*/

int test_if_order_by_key(ORDER_with_src *order_src, TABLE *table, uint idx,
                         uint *used_key_parts, bool *skip_quick) {
  DBUG_TRACE;
  KEY_PART_INFO *key_part, *key_part_end;
  key_part = table->key_info[idx].key_part;
  key_part_end = key_part + table->key_info[idx].user_defined_key_parts;
  key_part_map const_key_parts = table->const_key_parts[idx];
  int reverse = 0;
  uint key_parts;
  bool on_pk_suffix = false;
  // Whether [extended] key has key parts with mixed ASC/DESC order
  bool mixed_order = false;
  // Order direction of the first key part
  bool reverse_sorted = (bool)(key_part->key_part_flag & HA_REVERSE_SORT);
  ORDER *order = order_src->order;
  *skip_quick = false;

  for (; order; order = order->next, const_key_parts >>= 1) {
    /*
      Since only fields can be indexed, ORDER BY <something> that is
      not a field cannot be resolved by using an index.
    */
    Item *real_itm = (*order->item)->real_item();
    if (real_itm->type() != Item::FIELD_ITEM) return 0;

    const Field *field = down_cast<const Item_field *>(real_itm)->field;

    /*
      Skip key parts that are constants in the WHERE clause if these are
      already removed in the ORDER expression by check_field_is_const().
      If they are not removed in the ORDER expression yet, then we skip
      the constant keyparts that are not part of the ORDER expression.
    */
    for (; const_key_parts & 1 && key_part < key_part_end &&
           (order_src->is_const_optimized() || key_part->field != field);
         const_key_parts >>= 1) {
      key_part++;
    }

    /* Avoid usage of prefix index for sorting a partition table */
    if (table->part_info && key_part != table->key_info[idx].key_part &&
        key_part != key_part_end && is_prefix_index(table, idx))
      return 0;

    if (key_part == key_part_end) {
      /*
        We are at the end of the key. Check if the engine has the primary
        key as a suffix to the secondary keys. If it has continue to check
        the primary key as a suffix.
      */
      if (!on_pk_suffix &&
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
          table->s->primary_key != MAX_KEY && table->s->primary_key != idx) {
        on_pk_suffix = true;
        key_part = table->key_info[table->s->primary_key].key_part;
        key_part_end =
            key_part +
            table->key_info[table->s->primary_key].user_defined_key_parts;
        const_key_parts = table->const_key_parts[table->s->primary_key];

        /*
          Skip key parts that are constants in the WHERE clause if these are
          already removed in the ORDER expression by check_field_is_const().
          If they are not removed in the ORDER expression yet, then we skip
          the constant keyparts that are not part of the ORDER expression.
        */
        for (; const_key_parts & 1 && key_part < key_part_end &&
               (order_src->is_const_optimized() || key_part->field != field);
             const_key_parts >>= 1) {
          key_part++;
        }
        /*
         The primary and secondary key parts were all const (i.e. there's
         one row).  The sorting doesn't matter.
        */
        if (key_part == key_part_end && reverse == 0) {
          key_parts = 0;
          reverse = 1;
          goto ok;
        }
      } else
        return 0;
    }

    if (key_part->field != field || !field->part_of_sortkey.is_set(idx))
      return 0;
    if (order->direction != ORDER_NOT_RELEVANT) {
      const enum_order keypart_order =
          (key_part->key_part_flag & HA_REVERSE_SORT) ? ORDER_DESC : ORDER_ASC;
      /* set flag to 1 if we can use read-next on key, else to -1 */
      int cur_scan_dir = (order->direction == keypart_order) ? 1 : -1;
      if (reverse && cur_scan_dir != reverse) return 0;
      reverse = cur_scan_dir;  // Remember if reverse
    }
    mixed_order |=
        (reverse_sorted != (bool)((key_part)->key_part_flag & HA_REVERSE_SORT));

    key_part++;
  }
  /*
   The index picked here might be used for range scans with multiple ranges.
   This will require tricky reordering in case of ranges would have to be
   scanned backward and index consists of mixed ASC/DESC key parts. Due to that
   backward scans on such indexes are disabled.
  */
  if (mixed_order && reverse < 0) *skip_quick = true;

  if (!reverse) {
    /*
      We get here when the key is suitable and we don't care about it's
      order, i.e. GROUP BY/DISTINCT. Use forward scan.
    */
    reverse = 1;
  }
  if (on_pk_suffix) {
    uint used_key_parts_secondary = table->key_info[idx].user_defined_key_parts;
    uint used_key_parts_pk =
        (uint)(key_part - table->key_info[table->s->primary_key].key_part);
    key_parts = used_key_parts_pk + used_key_parts_secondary;

    if (reverse == -1 &&
        (!(table->file->index_flags(idx, used_key_parts_secondary - 1, true) &
           HA_READ_PREV) ||
         !(table->file->index_flags(table->s->primary_key,
                                    used_key_parts_pk - 1, true) &
           HA_READ_PREV)))
      reverse = 0;  // Index can't be used
  } else {
    key_parts = (uint)(key_part - table->key_info[idx].key_part);
    if (reverse == -1 &&
        !(table->file->index_flags(idx, key_parts - 1, true) & HA_READ_PREV))
      reverse = 0;  // Index can't be used
  }
ok:
  if (used_key_parts != nullptr) *used_key_parts = key_parts;
  return reverse;
}

/**
  Find shortest key suitable for full table scan.

  @param table                 Table to scan
  @param usable_keys           Allowed keys

  @note
     As far as
     1) clustered primary key entry data set is a set of all record
        fields (key fields and not key fields) and
     2) secondary index entry data is a union of its key fields and
        primary key fields (at least InnoDB and its derivatives don't
        duplicate primary key fields there, even if the primary and
        the secondary keys have a common subset of key fields),
     then secondary index entry data is always a subset of primary key entry.
     Unfortunately, key_info[nr].key_length doesn't show the length
     of key/pointer pair but a sum of key field lengths only, thus
     we can't estimate index IO volume comparing only this key_length
     value of secondary keys and clustered PK.
     So, try secondary keys first, and choose PK only if there are no
     usable secondary covering keys or found best secondary key include
     all table fields (i.e. same as PK):

  @return
    MAX_KEY     no suitable key found
    key index   otherwise
*/

uint find_shortest_key(TABLE *table, const Key_map *usable_keys) {
  uint best = MAX_KEY;
  uint usable_clustered_pk = (table->file->primary_key_is_clustered() &&
                              table->s->primary_key != MAX_KEY &&
                              usable_keys->is_set(table->s->primary_key))
                                 ? table->s->primary_key
                                 : MAX_KEY;
  if (!usable_keys->is_clear_all()) {
    uint min_length = (uint)~0;
    for (uint nr = 0; nr < table->s->keys; nr++) {
      if (nr == usable_clustered_pk) continue;
      if (usable_keys->is_set(nr)) {
        /*
          Cannot do full index scan on rtree index. It is not supported by
          Innodb as it's rtree index does not store data, but only the
          minimum bouding box (maybe makes sense only for geometries of
          type POINT). Index scans on rtrees are probabaly not supported
          by other storage engines either.
          A multi-valued key requires unique filter, and won't be the most
          fast option even if it will be the shortest one.
         */
        const KEY &key_ref = table->key_info[nr];
        assert(!(key_ref.flags & HA_MULTI_VALUED_KEY) &&
               !(key_ref.flags & HA_SPATIAL));
        if (key_ref.key_length < min_length) {
          min_length = key_ref.key_length;
          best = nr;
        }
      }
    }
  }
  if (usable_clustered_pk != MAX_KEY) {
    /*
     If the primary key is clustered and found shorter key covers all table
     fields then primary key scan normally would be faster because amount of
     data to scan is the same but PK is clustered.
     It's safe to compare key parts with table fields since duplicate key
     parts aren't allowed.
     */
    if (best == MAX_KEY ||
        table->key_info[best].user_defined_key_parts >= table->s->fields)
      best = usable_clustered_pk;
  }
  return best;
}

/**
  Test if a second key is the subkey of the first one.

  @param key_part              First key parts
  @param ref_key_part          Second key parts
  @param ref_key_part_end      Last+1 part of the second key

  @note
    Second key MUST be shorter than the first one.

  @retval
    1	is a subkey
  @retval
    0	no sub key
*/

inline bool is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
                      KEY_PART_INFO *ref_key_part_end) {
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
    if (!key_part->field->eq(ref_key_part->field)) return false;
  return true;
}

/**
  Test if REF_OR_NULL optimization will be used if the specified
  ref_key is used for REF-access to 'tab'

  @retval
    true	JT_REF_OR_NULL will be used
  @retval
    false	no JT_REF_OR_NULL access
*/

static bool is_ref_or_null_optimized(const JOIN_TAB *tab, uint ref_key) {
  if (tab->keyuse()) {
    const Key_use *keyuse = tab->keyuse();
    while (keyuse->key != ref_key && keyuse->table_ref == tab->table_ref)
      keyuse++;

    const table_map const_tables = tab->join()->const_table_map;
    while (keyuse->key == ref_key && keyuse->table_ref == tab->table_ref) {
      if (!(keyuse->used_tables & ~const_tables)) {
        if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) return true;
      }
      keyuse++;
    }
  }
  return false;
}

/**
  Test if we can use one of the 'usable_keys' instead of 'ref' key
  for sorting.

  @param order The query block's order clause.
  @param tab   Current JOIN_TAB.
  @param ref			Number of key, used for WHERE clause
  @param ref_key_parts Index columns used for ref lookup.
  @param usable_keys		Keys for testing

  @return
    - MAX_KEY			If we can't use other key
    - the number of found key	Otherwise
*/

static uint test_if_subkey(ORDER_with_src *order, JOIN_TAB *tab, uint ref,
                           uint ref_key_parts, const Key_map *usable_keys) {
  uint nr;
  uint min_length = (uint)~0;
  uint best = MAX_KEY;
  TABLE *table = tab->table();
  KEY_PART_INFO *ref_key_part = table->key_info[ref].key_part;
  KEY_PART_INFO *ref_key_part_end = ref_key_part + ref_key_parts;

  for (nr = 0; nr < table->s->keys; nr++) {
    bool skip_quick;
    if (usable_keys->is_set(nr) &&
        table->key_info[nr].key_length < min_length &&
        table->key_info[nr].user_defined_key_parts >= ref_key_parts &&
        is_subkey(table->key_info[nr].key_part, ref_key_part,
                  ref_key_part_end) &&
        !is_ref_or_null_optimized(tab, nr) &&
        test_if_order_by_key(order, table, nr, nullptr, &skip_quick) &&
        !skip_quick) {
      min_length = table->key_info[nr].key_length;
      best = nr;
    }
  }
  return best;
}

/**
  It is not obvious to see that test_if_skip_sort_order() never changes the
  plan if no_changes is true. So we double-check: creating an instance of this
  class saves some important access-path-related information of the current
  table; when the instance is destroyed, the latest access-path information is
  compared with saved data.
*/

class Plan_change_watchdog {
#ifndef NDEBUG
 public:
  /**
    @param tab_arg     table whose access path is being determined
    @param no_changes_arg whether a change to the access path is allowed
  */
  Plan_change_watchdog(const JOIN_TAB *tab_arg, const bool no_changes_arg) {
    if (no_changes_arg) {
      tab = tab_arg;
      type = tab->type();
      if ((quick = tab->range_scan())) quick_index = used_index(quick);
      use_quick = tab->use_quick;
      ref_key = tab->ref().key;
      ref_key_parts = tab->ref().key_parts;
      index = tab->index();
    } else {
      tab = nullptr;
      type = JT_UNKNOWN;
      quick = nullptr;
      ref_key = ref_key_parts = index = 0;
      use_quick = QS_NONE;
    }
  }
  ~Plan_change_watchdog() {
    if (tab == nullptr) return;
    // changes are not allowed, we verify:
    assert(tab->type() == type);
    assert(tab->range_scan() == quick);
    assert(quick == nullptr || used_index(tab->range_scan()) == quick_index);
    assert(tab->use_quick == use_quick);
    assert(tab->ref().key == ref_key);
    assert(tab->ref().key_parts == ref_key_parts);
    assert(tab->index() == index);
  }

 private:
  const JOIN_TAB *tab;  ///< table, or NULL if changes are allowed
  enum join_type type;  ///< copy of tab->type()
  // "Range / index merge" info
  const AccessPath *quick{nullptr};  ///< copy of tab->select->quick
  uint quick_index{0};               ///< copy of tab->select->quick->index
  enum quick_type use_quick;         ///< copy of tab->use_quick
  // "ref access" info
  int ref_key;         ///< copy of tab->ref().key
  uint ref_key_parts;  /// copy of tab->ref().key_parts
  // Other index-related info
  uint index;  ///< copy of tab->index
#else          // in non-debug build, empty class
 public:
  Plan_change_watchdog(const JOIN_TAB *, const bool) {}
#endif
};

/**
  Test if we can skip ordering by using an index.

  If the current plan is to use an index that provides ordering, the
  plan will not be changed. Otherwise, if an index can be used, the
  JOIN_TAB / tab->select struct is changed to use the index.

  The index must cover all fields in @<order@>, or it will not be considered.

  @param tab           NULL or JOIN_TAB of the accessed table
  @param order         Linked list of ORDER BY arguments
  @param select_limit  LIMIT value, or HA_POS_ERROR if no limit
  @param no_changes    No changes will be made to the query plan.
  @param map           Key_map of applicable indexes.
  @param [out] order_idx Number of index selected, -1 if no applicable index
                       found

  @todo
    - sergeyp: Results of all index merge selects actually are ordered
    by clustered PK values.

  @note
  This function may change tmp_table_param.precomputed_group_by. This
  affects how create_tmp_table() treats aggregation functions, so
  count_field_types() must be called again to make sure this is taken
  into consideration.

  @retval
    0    We have to use filesort to do the sorting
  @retval
    1    We can use an index.
*/

static bool test_if_skip_sort_order(JOIN_TAB *tab, ORDER_with_src &order,
                                    ha_rows select_limit, const bool no_changes,
                                    const Key_map *map, int *order_idx) {
  DBUG_TRACE;
  int ref_key;
  uint ref_key_parts = 0;
  int order_direction = 0;
  uint used_key_parts = 0;
  TABLE *const table = tab->table();
  JOIN *const join = tab->join();
  THD *const thd = join->thd;
  AccessPath *const save_range_scan = tab->range_scan();
  int best_key = -1;
  double best_read_time = 0;
  bool set_up_ref_access_to_key = false;
  bool can_skip_sorting = false;  // used as return value
  int changed_key = -1;

  /* Check that we are always called with first non-const table */
  assert((uint)tab->idx() == join->const_tables);

  Plan_change_watchdog watchdog(tab, no_changes);
  *order_idx = -1;
  /* Sorting a single row can always be skipped */
  if (tab->type() == JT_EQ_REF || tab->type() == JT_CONST ||
      tab->type() == JT_SYSTEM) {
    return true;
  }

  /*
    Check if FT index can be used to retrieve result in the required order.
    It is possible if ordering is on the first non-constant table.
  */
  if (!join->order.empty() && join->simple_order) {
    /*
      Check if ORDER is DESC, ORDER BY is a single MATCH function.
    */
    Item_func_match *ft_func = test_if_ft_index_order(order.order);
    /*
      Two possible cases when we can skip sort order:
      1. FT_SORTED must be set(Natural mode, no ORDER BY).
      2. If FT_SORTED flag is not set then
      the engine should support deferred sorting. Deferred sorting means
      that sorting is postponed utill the start of index reading(InnoDB).
      In this case we set FT_SORTED flag here to let the engine know that
      internal sorting is needed.
    */
    if (ft_func && ft_func->ft_handler && ft_func->ordered_result()) {
      /*
        FT index scan is used, so the only additional requirement is
        that ORDER BY MATCH function is the same as the function that
        is used for FT index.
      */
      if (tab->type() == JT_FT &&
          ft_func->eq(tab->position()->key->val, true)) {
        ft_func->set_hints(join, FT_SORTED, select_limit, false);
        return true;
      }
      /*
        No index is used, it's possible to use FT index for ORDER BY if
        LIMIT is present and does not exceed count of the records in FT index
        and there is no WHERE condition since a condition may potentially
        require more rows to be fetch from FT index.
      */
      if (!tab->condition() && select_limit != HA_POS_ERROR &&
          select_limit <= ft_func->get_count()) {
        /* test_if_ft_index_order() always returns master MATCH function. */
        assert(!ft_func->master);
        /* ref is not set since there is no WHERE condition */
        assert(tab->ref().key == -1);

        /*Make EXPLAIN happy */
        tab->set_type(JT_FT);
        tab->ref().key = ft_func->key;
        tab->ref().key_parts = 0;
        tab->set_index(ft_func->key);
        tab->set_ft_func(ft_func);

        /* Setup FT handler */
        ft_func->set_hints(join, FT_SORTED, select_limit, true);
        ft_func->score_from_index_scan = true;
        table->file->ft_handler = ft_func->ft_handler;
        return true;
      }
    }
  }

  /*
    Keys disabled by ALTER TABLE ... DISABLE KEYS should have already
    been taken into account.
  */
  Key_map usable_keys = *map;

  for (ORDER *tmp_order = order.order; tmp_order; tmp_order = tmp_order->next) {
    const Item *item = (*tmp_order->item)->real_item();
    if (item->type() != Item::FIELD_ITEM) {
      usable_keys.clear_all();
      return false;
    }
    usable_keys.intersect(
        down_cast<const Item_field *>(item)->field->part_of_sortkey);
    if (usable_keys.is_clear_all()) return false;  // No usable keys
  }
  if (tab->type() == JT_REF_OR_NULL || tab->type() == JT_FT) return false;

  ref_key = -1;
  /* Test if constant range in WHERE */
  if (tab->type() == JT_REF) {
    assert(tab->ref().key >= 0 && tab->ref().key_parts);
    ref_key = tab->ref().key;
    ref_key_parts = tab->ref().key_parts;
  } else if (tab->type() == JT_RANGE || tab->type() == JT_INDEX_MERGE) {
    // Range found by opt_range
    /*
      assume results are not ordered when index merge is used
      TODO: sergeyp: Results of all index merge selects actually are ordered
      by clustered PK values.
    */

    if (tab->range_scan()->type == AccessPath::INDEX_MERGE ||
        tab->range_scan()->type == AccessPath::ROWID_UNION ||
        tab->range_scan()->type == AccessPath::ROWID_INTERSECTION)
      return false;
    ref_key = used_index(tab->range_scan());
    ref_key_parts = get_used_key_parts(tab->range_scan());
  } else if (tab->type() == JT_INDEX_SCAN) {
    // The optimizer has decided to use an index scan.
    ref_key = tab->index();
    ref_key_parts = actual_key_parts(&table->key_info[tab->index()]);
  }

  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper_1(trace);
  Opt_trace_object trace_skip_sort_order(
      trace, "reconsidering_access_paths_for_index_ordering");
  trace_skip_sort_order.add_alnum(
      "clause", (order.src == ESC_ORDER_BY ? "ORDER BY" : "GROUP BY"));
  Opt_trace_array trace_steps(trace, "steps");

  if (ref_key >= 0) {
    /*
      We come here when ref/index scan/range scan access has been set
      up for this table. Do not change access method if ordering is
      provided already.
    */
    if (!usable_keys.is_set(ref_key)) {
      /*
        We come here when ref_key is not among usable_keys, try to find a
        usable prefix key of that key.
      */
      uint new_ref_key;
      /*
        If using index only read, only consider other possible index only
        keys
      */
      if (table->covering_keys.is_set(ref_key))
        usable_keys.intersect(table->covering_keys);

      if ((new_ref_key = test_if_subkey(&order, tab, ref_key, ref_key_parts,
                                        &usable_keys)) < MAX_KEY) {
        /* Found key that can be used to retrieve data in sorted order */
        if (tab->ref().key >= 0) {
          /*
            We'll use ref access method on key new_ref_key. The actual change
            is done further down in this function where we update the plan.
          */
          set_up_ref_access_to_key = true;
        } else if (!no_changes) {
          /*
            The range optimizer constructed QUICK_RANGE for ref_key, and
            we want to use instead new_ref_key as the index. We can't
            just change the index of the quick select, because this may
            result in an inconsistent RowIterator object. Below we
            create a new RowIterator from scratch so that all its
            parameres are set correctly by the range optimizer.

            Note that the range optimizer is NOT called if
            no_changes==true. This reason is that the range optimizer
            cannot find a QUICK that can return ordered result unless
            index access (ref or index scan) is also able to do so
            (which test_if_order_by_key () will tell).
            Admittedly, range access may be much more efficient than
            e.g. index scan, but the only thing that matters when
            no_change==true is the answer to the question: "Is it
            possible to avoid sorting if an index is used to access
            this table?". The answer does not depend on the outcome of
            the range optimizer.
          */
          Key_map new_ref_key_map;  // Force the creation of quick select
          new_ref_key_map.set_bit(new_ref_key);  // only for new_ref_key.

          Opt_trace_object trace_wrapper_2(trace);
          Opt_trace_object trace_recest(trace, "rows_estimation");
          trace_recest.add_utf8_table(tab->table_ref)
              .add_utf8("index", table->key_info[new_ref_key].name);
          AccessPath *range_scan;
          MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                                 thd->variables.range_alloc_block_size);
          const bool no_quick =
              test_quick_select(
                  thd, thd->mem_root, &temp_mem_root, new_ref_key_map, 0,
                  0,  // empty table_map
                  join->calc_found_rows
                      ? HA_POS_ERROR
                      : join->query_expression()->select_limit_cnt,
                  false,  // don't force quick range
                  order.order->direction, tab->table(),
                  tab->skip_records_in_range(),
                  // we are after make_join_query_block():
                  tab->condition(), &tab->needed_reg, tab->table()->force_index,
                  join->query_block, &range_scan) <= 0;
          assert(tab->range_scan() == save_range_scan);
          tab->set_range_scan(range_scan);
          if (no_quick) {
            can_skip_sorting = false;
            goto fix_ICP;
          }
        }
        ref_key = new_ref_key;
        changed_key = new_ref_key;
      }
    }
    bool dummy;
    /* Check if we get the rows in requested sorted order by using the key */
    if (usable_keys.is_set(ref_key))
      // Last parameter can be ignored as it'll be checked later, if needed
      order_direction =
          test_if_order_by_key(&order, table, ref_key, &used_key_parts, &dummy);
  }
  if (ref_key < 0 || order_direction <= 0) {
    /*
      There is no ref/index scan/range scan access set up for this
      table, or it does not provide the requested ordering, or it uses
      backward scan. Do a cost-based search on all keys.
    */
    uint best_key_parts = 0;
    uint saved_best_key_parts = 0;
    int best_key_direction = 0;
    ha_rows table_records = table->file->stats.records;

    /*
      If an index scan that cannot provide ordering has been selected
      then do not use the index scan key as starting hint to
      test_if_cheaper_ordering()
    */
    const int ref_key_hint =
        (order_direction == 0 && tab->type() == JT_INDEX_SCAN) ? -1 : ref_key;

    // Does the query have a "FORCE INDEX [FOR GROUP BY] (idx)" (if clause is
    // group by) or a "FORCE INDEX [FOR ORDER BY] (idx)" (if clause is order
    // by)?
    const bool is_group_by =
        join && join->grouped && order.order == join->group_list.order;
    const bool is_force_index =
        table->force_index ||
        (is_group_by ? table->force_index_group : table->force_index_order);

    // We try to find an ordering_index alternative over the chosen plan, if:
    // 1. "prefer_ordering_index" switch is on or
    // 2. Force index for order/group is specified or
    // 3. Optimizer has chosen to do table scan currently.
    if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_PREFER_ORDERING_INDEX) ||
        is_force_index || ref_key == -1)
      test_if_cheaper_ordering(tab, &order, table, usable_keys, ref_key_hint,
                               select_limit, &best_key, &best_key_direction,
                               &select_limit, &best_key_parts,
                               &saved_best_key_parts, &best_read_time);

    // Try backward scan for previously found key
    if (best_key < 0 && order_direction < 0) goto check_reverse_order;

    if (best_key < 0) {
      // No usable key has been found
      can_skip_sorting = false;
      goto fix_ICP;
    }
    /*
      If found index will use backward index scan, ref_key uses backward
      range/ref, pick the latter as it has better selectivity.
    */
    if (order_direction < 0 && order_direction == best_key_direction) {
      best_key = -1;  // reset found best key
      goto check_reverse_order;
    }

    /*
      filesort() and join cache are usually faster than reading in
      index order and not using join cache. Don't use index scan
      unless:
       - the user specified FORCE INDEX [FOR {GROUP|ORDER} BY] (have to assume
         the user knows what's best)
       - the chosen index is clustered primary key (table scan is not cheaper)
    */
    if (!is_force_index && (select_limit >= table_records) &&
        (tab->type() == JT_ALL &&
         join->primary_tables > join->const_tables + 1) &&
        ((unsigned)best_key != table->s->primary_key ||
         !table->file->primary_key_is_clustered())) {
      can_skip_sorting = false;
      goto fix_ICP;
    }

    if (table->quick_keys.is_set(best_key) &&
        !tab->quick_order_tested.is_set(best_key) && best_key != ref_key) {
      tab->quick_order_tested.set_bit(best_key);
      Opt_trace_object trace_wrapper_3(trace);
      Opt_trace_object trace_recest(trace, "rows_estimation");
      trace_recest.add_utf8_table(tab->table_ref)
          .add_utf8("index", table->key_info[best_key].name);

      Key_map keys_to_use;            // Force the creation of quick select
      keys_to_use.set_bit(best_key);  // only best_key.
      MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                             thd->variables.range_alloc_block_size);
      AccessPath *range_scan;
      test_quick_select(
          thd, thd->mem_root, &temp_mem_root, keys_to_use, 0,
          0,  // empty table_map
          join->calc_found_rows ? HA_POS_ERROR
                                : join->query_expression()->select_limit_cnt,
          true,  // force quick range
          order.order->direction, tab->table(), tab->skip_records_in_range(),
          tab->condition(), &tab->needed_reg, tab->table()->force_index,
          join->query_block, &range_scan);
      if (order_direction < 0 && tab->range_scan() != nullptr &&
          tab->range_scan() != save_range_scan) {
        /*
          We came here in case when 3 indexes are available for quick
          select:
            1 - found by join order optimizer (greedy search) and saved in
                save_range_scan
            2 - constructed far above, as better suited for order by, but it was
                found that it requires backward scan.
            3 - constructed right above
          In this case we drop quick #2 as #3 is expected to be better.
        */
        destroy(tab->range_scan());
        tab->set_range_scan(nullptr);
      }
      /*
        If tab->range_scan() pointed to another quick than save_range_scan, we
        would lose access to it and leak memory.
      */
      assert(tab->range_scan() == save_range_scan ||
             tab->range_scan() == nullptr);
      tab->set_range_scan(range_scan);
    }
    order_direction = best_key_direction;
    /*
      saved_best_key_parts is actual number of used keyparts found by the
      test_if_order_by_key function. It could differ from keyinfo->key_parts,
      thus we have to restore it in case of desc order as it affects
      ReverseIndexRangeScanIterator behaviour.
    */
    used_key_parts =
        (order_direction == -1) ? saved_best_key_parts : best_key_parts;
    changed_key = best_key;
    // We will use index scan or range scan:
    set_up_ref_access_to_key = false;
  }

check_reverse_order:
  assert(order_direction != 0);

  if (order_direction == -1)  // If ORDER BY ... DESC
  {
    if (tab->range_scan()) {
      /*
        Don't reverse the sort order, if it's already done.
        (In some cases test_if_order_by_key() can be called multiple times
      */
      if (is_reverse_sorted_range(tab->range_scan())) {
        can_skip_sorting = true;
        goto fix_ICP;
      }
      // test_if_cheaper_ordering() might disable range scan on current index
      if (tab->table()->quick_keys.is_set(used_index(tab->range_scan())) &&
          reverse_sort_possible(tab->range_scan()))
        can_skip_sorting = true;
      else {
        can_skip_sorting = false;
        goto fix_ICP;
      }
    } else {
      // Other index access (ref or scan) poses no problem
      can_skip_sorting = true;
    }
  } else {
    // ORDER BY ASC poses no problem
    can_skip_sorting = true;
  }

  assert(can_skip_sorting);

  /*
    Update query plan with access pattern for doing
    ordered access according to what we have decided
    above.
  */
  if (!no_changes)  // We are allowed to update QEP
  {
    if (set_up_ref_access_to_key) {
      /*
        We'll use ref access method on key changed_key. In general case
        the index search tuple for changed_ref_key will be different (e.g.
        when one index is defined as (part1, part2, ...) and another as
        (part1, part2(N), ...) and the WHERE clause contains
        "part1 = const1 AND part2=const2".
        So we build tab->ref() from scratch here.
      */
      Key_use *keyuse = tab->keyuse();
      while (keyuse->key != (uint)changed_key &&
             keyuse->table_ref == tab->table_ref)
        keyuse++;

      if (create_ref_for_key(join, tab, keyuse, tab->prefix_tables())) {
        can_skip_sorting = false;
        goto fix_ICP;
      }

      assert(tab->type() != JT_REF_OR_NULL && tab->type() != JT_FT);

      // Changing the key makes filter_effect obsolete
      tab->position()->filter_effect = COND_FILTER_STALE;

      /*
        Check if it is possible to shift from ref to range. The index chosen
        for 'ref' has changed since the last time this function was called.
      */
      if (can_switch_from_ref_to_range(thd, tab, order.order->direction,
                                       true)) {
        // Allow the code to fall-through to the next if condition.
        set_up_ref_access_to_key = false;
        best_key = changed_key;
      }
    }
    if (!set_up_ref_access_to_key && best_key >= 0) {
      // Cancel any ref-access previously set up
      tab->ref().key = -1;
      tab->ref().key_parts = 0;

      /*
        If ref_key used index tree reading only ('Using index' in EXPLAIN),
        and best_key doesn't, then revert the decision.
      */
      if (!table->covering_keys.is_set(best_key)) table->set_keyread(false);
      // Create an index scan if the table is not a temporary table that uses
      // Temptable engine (Does not support index_first() and index_last()) and
      // if there was no new range scan created.
      if (!(is_temporary_table(tab->table_ref) &&
            tab->table_ref->table->s->db_type() == temptable_hton) &&
          ((!tab->range_scan() || tab->range_scan() == save_range_scan))) {
        // Avoid memory leak:
        assert(tab->range_scan() == save_range_scan ||
               tab->range_scan() == nullptr);
        tab->set_range_scan(nullptr);
        tab->set_index(best_key);
        tab->set_type(JT_INDEX_SCAN);  // Read with index_first(), index_next()
        /*
          There is a bug. When we change here, e.g. from group_min_max to
          index scan: loose index scan expected to read a small number of rows
          (jumping through the index), this small number was in
          position()->rows_fetched; index scan will read much more, so
          rows_fetched should be updated. So should the filtering effect.
          It is visible in main.distinct in trunk:
          explain SELECT distinct a from t3 order by a desc limit 2;
          id	select_type	table	partitions	type
          possible_keys	key	key_len	ref	rows	filtered	Extra 1
          SIMPLE	t3	NULL	index	a	a	5	NULL
          40	25.00	Using index "rows=40" should be ~200 i.e. # of records
          in table. Filter should be 100.00 (no WHERE).
        */
        table->file->ha_index_or_rnd_end();
        tab->position()->filter_effect = COND_FILTER_STALE;
      } else if (tab->type() != JT_ALL) {
        /*
          We're about to use a quick access to the table.
          We need to change the access method so as the quick access
          method is actually used.
        */
        assert(tab->range_scan());
        assert(used_index(tab->range_scan()) == (uint)best_key);
        tab->set_type(calc_join_type(tab->range_scan()));
        tab->use_quick = QS_RANGE;
        if (is_loose_index_scan(tab->range_scan()))
          join->tmp_table_param.precomputed_group_by = true;
        tab->position()->filter_effect = COND_FILTER_STALE;
      }
    }  // best_key >= 0

    if (order_direction == -1)  // If ORDER BY ... DESC
    {
      if (tab->range_scan()) {
        /* ORDER BY range_key DESC */
        if (make_reverse(used_key_parts, tab->range_scan())) {
          /* purecov: begin inspected */
          can_skip_sorting = false;  // Reverse sort failed -> filesort
          goto fix_ICP;
          /* purecov: end */
        }
        tab->set_type(calc_join_type(tab->range_scan()));
        tab->position()->filter_effect = COND_FILTER_STALE;
      } else if (tab->type() == JT_REF &&
                 tab->ref().key_parts <= used_key_parts) {
        /*
          SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC

          Use a traversal function that starts by reading the last row
          with key part (A) and then traverse the index backwards.
        */
        tab->reversed_access = true;

        /*
          The current implementation of the reverse RefIterator does not
          work well in combination with ICP and can lead to increased
          execution time. Setting changed_key to the current key
          (based on that we change the access order for the key) will
          ensure that a pushed index condition will be cancelled.
        */
        changed_key = tab->ref().key;
      } else if (tab->type() == JT_INDEX_SCAN)
        tab->reversed_access = true;
    } else if (tab->range_scan())
      set_need_sorted_output(tab->range_scan());

  }  // QEP has been modified

fix_ICP:
  /*
    Cleanup:
    We may have both a 'tab->range_scan()' and 'save_range_scan' (original)
    at this point. Delete the one that we won't use.
  */
  if (can_skip_sorting && !no_changes) {
    if (tab->type() == JT_INDEX_SCAN &&
        select_limit < table->file->stats.records) {
      assert(select_limit > 0);
      tab->position()->rows_fetched = select_limit;
      /*
        Update the cost data if secondary engine is active as it is needed to
        make the query offload decision later.
      */
      if (best_read_time > 0 && join->primary_tables == 1 &&
          table->s->has_secondary_engine()) {
        tab->position()->read_cost = best_read_time;
        /*
          Assume no filter at this point to calculate the access cost. This
          will be updated later to proper values when/if filter_effect is
          updated. The logic is to ensure the cost covers accessing at least
          LIMIT number of rows using the access method. If there exists a WHERE
          clause, then more than LIMIT number of rows needs to be accessed.
          Ideally we should calculate proper filtering effect and update
          rows_fetched to include the filtering effect as well. Eg:
          tab->position()->rows_fetched = select_limit / filter_effect;
        */
        tab->position()->filter_effect = COND_FILTER_ALLPASS;
        // Update the cost values accordingly.
        tab->position()->set_prefix_join_cost(tab->idx(), join->cost_model());
      }
      // Update filter effect to reflect the access change.
      tab->position()->filter_effect = COND_FILTER_STALE_NO_CONST;
    }

    // Keep current (ordered) tab->range_scan()
    if (save_range_scan != tab->range_scan()) destroy(save_range_scan);
  } else {
    // Restore original save_range_scan
    if (tab->range_scan() != save_range_scan) {
      destroy(tab->range_scan());
      tab->set_range_scan(save_range_scan);
    }
  }

  trace_steps.end();
  Opt_trace_object trace_change_index(trace, "index_order_summary");
  trace_change_index.add_utf8_table(tab->table_ref)
      .add("index_provides_order", can_skip_sorting)
      .add_alnum("order_direction",
                 order_direction == 1
                     ? "asc"
                     : ((order_direction == -1) ? "desc" : "undefined"));

  if (changed_key >= 0) {
    // switching to another index
    // Should be no pushed index conditions at this point
    assert(!table->file->pushed_idx_cond);
    if (unlikely(trace->is_started())) {
      trace_change_index.add_utf8("index", table->key_info[changed_key].name);
      trace_change_index.add("plan_changed", !no_changes);
      if (!no_changes)
        trace_change_index.add_alnum("access_type", join_type_str[tab->type()]);
    }
  } else if (unlikely(trace->is_started())) {
    trace_change_index.add_utf8(
        "index", ref_key >= 0 ? table->key_info[ref_key].name : "unknown");
    trace_change_index.add("plan_changed", false);
  }
  *order_idx = best_key < 0 ? ref_key : best_key;
  return can_skip_sorting;
}

/**
  Prune partitions for all tables of a join (query block).

  Requires that tables have been locked.

  @returns false if success, true if error
*/

bool JOIN::prune_table_partitions() {
  assert(query_block->partitioned_table_count);

  for (Table_ref *tbl = query_block->leaf_tables; tbl; tbl = tbl->next_leaf) {
    // This will try to prune non-static conditions, which can be probed after
    // the tables are locked.

    // Predicates for pruning of this table must be placed in the outer-most
    // join nest (Predicates in other join nests, or in the WHERE clause,
    // would have caused an outer join to be converted to an inner join,
    // and thus there would be no join nest graph to traverse)
    // Look up the join nest hierarchy for the outermost condition:
    Item *cond = where_cond;
    const table_map tbl_map = tbl->map();
    for (Table_ref *nest = tbl; nest != nullptr; nest = nest->embedding) {
      if (nest->join_cond_optim() != nullptr &&
          Overlaps(tbl_map, nest->join_cond_optim()->used_tables())) {
        cond = nest->join_cond_optim();
        // For an anti-join operation, a synthetic left join nest is added above
        // the anti-join nest. Make sure that we skip this when searching for
        // the predicate to prune.
        if (nest->is_aj_nest()) break;
      }
    }
    if (prune_partitions(thd, tbl->table, query_block, cond)) {
      return true;
    }
  }

  return false;
}

/**
  A helper function to check whether it's better to use range than ref.

  @details
  Heuristic: Switch from 'ref' to 'range' access if 'range'
  access can utilize more keyparts than 'ref' access. Conditions
  for doing switching:

  1) Range access is possible
  2) 'ref' access and 'range' access uses the same index
  3) Used parts of key shouldn't have nullable parts & ref_or_null isn't used.
  4) 'ref' access depends on a constant, not a value read from a
     table earlier in the join sequence.

     Rationale: if 'ref' depends on a value from another table,
     the join condition is not used to limit the rows read by
     'range' access (that would require dynamic range - 'Range
     checked for each record'). In other words, if 'ref' depends
     on a value from another table, we have a query with
     conditions of the form

      this_table.idx_col1 = other_table.col AND   <<- used by 'ref'
      this_table.idx_col1 OP @<const@> AND        <<- used by 'range'
      this_table.idx_col2 OP @<const@> AND ...    <<- used by 'range'

     and an index on (idx_col1,idx_col2,...). But the fact that
     'range' access uses more keyparts does not mean that it is
     more selective than 'ref' access because these access types
     utilize different parts of the query condition. We
     therefore trust the cost based choice made by
     best_access_path() instead of forcing a heuristic choice
     here.
  5) 'range' access uses more keyparts than 'ref' access
  6) ORDER BY might make range better than table scan:
     Check possibility of range scan even if it was previously deemed unviable
     (for example when table scan was estimated to be cheaper). If yes,
     range-access should be chosen only for larger key length.

  @param thd           To re-run range optimizer.
  @param tab           JOIN_TAB to check
  @param ordering      Used as a parameter to call test_quick_select.
  @param recheck_range Check possibility of range scan even if it is currently
                       unviable.

  @return true   Range is better than ref
  @return false  Ref is better or switch isn't possible

  @todo: This decision should rather be made in best_access_path()
*/

static bool can_switch_from_ref_to_range(THD *thd, JOIN_TAB *tab,
                                         enum_order ordering,
                                         bool recheck_range) {
  if ((tab->range_scan() &&                                            // 1)
       tab->position()->key->key == used_index(tab->range_scan())) ||  // 2)
      recheck_range) {
    uint keyparts = 0, length = 0;
    table_map dep_map = 0;
    bool maybe_null = false;

    calc_length_and_keyparts(tab->position()->key, tab,
                             tab->position()->key->key, tab->prefix_tables(),
                             nullptr, &length, &keyparts, &dep_map,
                             &maybe_null);

    if (thd->is_error()) {
      return true;
    }
    if (!maybe_null &&  // 3)
        !dep_map)       // 4)
    {
      if (recheck_range)  // 6)
      {
        Key_map new_ref_key_map;
        new_ref_key_map.set_bit(tab->ref().key);

        Opt_trace_context *const trace = &thd->opt_trace;
        Opt_trace_object trace_wrapper(trace);
        Opt_trace_object can_switch(
            trace, "check_if_range_uses_more_keyparts_than_ref");
        Opt_trace_object trace_cond(
            trace, "rerunning_range_optimizer_for_single_index");

        AccessPath *range_scan;
        MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                               thd->variables.range_alloc_block_size);
        if (test_quick_select(
                thd, thd->mem_root, &temp_mem_root, new_ref_key_map, 0,
                0,  // empty table_map
                tab->join()->row_limit, false, ordering, tab->table(),
                tab->skip_records_in_range(),
                tab->join_cond() ? tab->join_cond() : tab->join()->where_cond,
                &tab->needed_reg, recheck_range, tab->join()->query_block,
                &range_scan) > 0) {
          if (length < get_max_used_key_length(range_scan)) {
            destroy(tab->range_scan());
            tab->set_range_scan(range_scan);
            return true;
          }
          Opt_trace_object(trace, "access_type_unchanged")
              .add("ref_key_length", length)
              .add("range_key_length", get_max_used_key_length(range_scan));
          destroy(range_scan);
        }
      } else
        return length < get_max_used_key_length(tab->range_scan());  // 5)
    }
  }
  return false;
}

/**
 An utility function - apply heuristics and optimize access methods to tables.
 Currently this function can change REF to RANGE and ALL to INDEX scan if
 latter is considered to be better (not cost-based) than the former.
 @note Side effect - this function could set 'Impossible WHERE' zero
 result.
*/

void JOIN::adjust_access_methods() {
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  for (uint i = const_tables; i < tables; i++) {
    JOIN_TAB *const tab = best_ref[i];
    Table_ref *const tl = tab->table_ref;

    if (tab->type() == JT_ALL) {
      /*
       It's possible to speedup query by switching from full table scan to
       the scan of covering index, due to less data being read.
       Prerequisites for this are:
       1) Keyread (i.e index only scan) is allowed (table isn't updated/deleted
         from)
       2) Covering indexes are available
       3) This isn't a derived table/materialized view
      */
      if (!tab->table()->no_keyread &&                    //  1
          !tab->table()->covering_keys.is_clear_all() &&  //  2
          !tl->uses_materialization())                    //  3
      {
        /*
        It has turned out that the change commented out below, while speeding
        things up for disk-bound loads, slows them down for cases when the data
        is in disk cache (see BUG#35850):
        //  See bug #26447: "Using the clustered index for a table scan
        //  is always faster than using a secondary index".
        if (table->s->primary_key != MAX_KEY &&
            table->file->primary_key_is_clustered())
          tab->index= table->s->primary_key;
        else
          tab->index=find_shortest_key(table, & table->covering_keys);
        */
        if (tab->position()->sj_strategy != SJ_OPT_LOOSE_SCAN)
          tab->set_index(
              find_shortest_key(tab->table(), &tab->table()->covering_keys));
        tab->set_type(JT_INDEX_SCAN);  // Read with index_first / index_next
        // From table scan to index scan, thus filter effect needs no recalc.
      }
    } else if (tab->type() == JT_REF) {
      if (can_switch_from_ref_to_range(thd, tab, ORDER_NOT_RELEVANT, false)) {
        tab->set_type(JT_RANGE);

        Opt_trace_context *const trace = &thd->opt_trace;
        Opt_trace_object wrapper(trace);
        Opt_trace_object(trace, "access_type_changed")
            .add_utf8_table(tl)
            .add_utf8("index",
                      tab->table()->key_info[tab->position()->key->key].name)
            .add_alnum("old_type", "ref")
            .add_alnum("new_type", join_type_str[tab->type()])
            .add_alnum("cause", "uses_more_keyparts");

        tab->use_quick = QS_RANGE;
        tab->position()->filter_effect = COND_FILTER_STALE;
      } else {
        // Cleanup quick, REF/REF_OR_NULL/EQ_REF, will be clarified later
        ::destroy(tab->range_scan());
        tab->set_range_scan(nullptr);
      }
    }
    // Ensure AM consistency
    assert(!(tab->range_scan() &&
             (tab->type() == JT_REF || tab->type() == JT_ALL)));
    assert((tab->type() != JT_RANGE && tab->type() != JT_INDEX_MERGE) ||
           tab->range_scan());
    if (!tab->const_keys.is_clear_all() &&
        tab->table()->reginfo.impossible_range &&
        ((i == const_tables && tab->type() == JT_REF) ||
         ((tab->type() == JT_ALL || tab->type() == JT_RANGE ||
           tab->type() == JT_INDEX_MERGE || tab->type() == JT_INDEX_SCAN) &&
          tab->use_quick != QS_RANGE)) &&
        !tab->table_ref->is_inner_table_of_outer_join())
      zero_result_cause = "Impossible WHERE noticed after reading const tables";
  }
}

static JOIN_TAB *alloc_jtab_array(THD *thd, uint table_count) {
  JOIN_TAB *t = new (thd->mem_root) JOIN_TAB[table_count];
  if (!t) return nullptr; /* purecov: inspected */

  QEP_shared *qs = new (thd->mem_root) QEP_shared[table_count];
  if (!qs) return nullptr; /* purecov: inspected */

  for (uint i = 0; i < table_count; ++i) t[i].set_qs(qs++);

  return t;
}

/**
  Set up JOIN_TAB structs according to the picked join order in best_positions.
  This allocates execution structures so may be called only after we have the
  very final plan. It must be called after
  Optimize_table_order::fix_semijoin_strategies().

  @return False if success, True if error

  @details
    - create join->join_tab array and copy from existing JOIN_TABs in join order
    - create helper structs for materialized semi-join handling
    - finalize semi-join strategy choices
    - Number of intermediate tables "tmp_tables" is calculated.
    - "tables" and "primary_tables" are recalculated.
    - for full and index scans info of estimated # of records is updated.
    - in a helper function:
      - all heuristics are applied and the final access method type is picked
        for each join_tab (only test_if_skip_sort_order() could override it)
      - AM consistency is ensured (e.g only range and index merge are allowed
        to have quick select set).
      - if "Impossible WHERE" is detected - appropriate zero_result_cause is
        set.

   Notice that intermediate tables will not have a POSITION reference; and they
   will not have a TABLE reference before the final stages of code generation.

   @todo the block which sets tab->type should move to adjust_access_methods
   for unification.
*/

bool JOIN::get_best_combination() {
  DBUG_TRACE;

  // At this point "tables" and "primary"tables" represent the same:
  assert(tables == primary_tables);

  /*
    Allocate additional space for tmp tables.
    Number of plan nodes:
      # of regular input tables (including semi-joined ones) +
      # of semi-join nests for materialization +
      1? + // For GROUP BY (or implicit grouping when we have windowing)
      1? + // For DISTINCT
      1? + // For aggregation functions aggregated in outer query
           // when used with distinct
      1? + // For ORDER BY
      1?   // buffer result

    Up to 2 tmp tables + N window output tmp are allocated (NOTE: windows also
    have frame buffer tmp tables, but those are not relevant here).
  */
  uint num_tmp_tables =
      (!group_list.empty() || (implicit_grouping && m_windows.elements > 0)
           ? 1
           : 0) +
      (select_distinct ? (tmp_table_param.outer_sum_func_count ? 2 : 1) : 0) +
      (order.empty() ? 0 : 1) +
      (query_block->active_options() &
               (SELECT_BIG_RESULT | OPTION_BUFFER_RESULT)
           ? 1
           : 0) +
      m_windows.elements + 1; /* the presence of windows may increase need for
                                 grouping tmp tables, cf. de-optimization
                                 in make_tmp_tables_info
                               */
  if (num_tmp_tables > (2 + m_windows.elements))
    num_tmp_tables = 2 + m_windows.elements;

  /*
    Rearrange queries with materialized semi-join nests so that the semi-join
    nest is replaced with a reference to a materialized temporary table and all
    materialized subquery tables are placed after the intermediate tables.
    After the following loop, "inner_target" is the position of the first
    subquery table (if any). "outer_target" is the position of first outer
    table, and will later be used to track the position of any materialized
    temporary tables.
  */
  const bool has_semijoin = !query_block->sj_nests.empty();
  uint outer_target = 0;
  uint inner_target = primary_tables + num_tmp_tables;
  uint sjm_nests = 0;

  if (has_semijoin) {
    for (uint tableno = 0; tableno < primary_tables;) {
      if (sj_is_materialize_strategy(best_positions[tableno].sj_strategy)) {
        sjm_nests++;
        inner_target -= (best_positions[tableno].n_sj_tables - 1);
        tableno += best_positions[tableno].n_sj_tables;
      } else
        tableno++;
    }
  }

  JOIN_TAB *tmp_join_tabs = nullptr;
  if (sjm_nests + num_tmp_tables) {
    // join_tab array only has "primary_tables" tables. We need those more:
    if (!(tmp_join_tabs = alloc_jtab_array(thd, sjm_nests + num_tmp_tables)))
      return true; /* purecov: inspected */
  }

  // To check that we fill the array correctly: fill it with zeros first
  memset(best_ref, 0,
         sizeof(JOIN_TAB *) * (primary_tables + sjm_nests + num_tmp_tables));

  int sjm_index = tables;  // Number assigned to materialized temporary table
  int remaining_sjm_inner = 0;
  bool err = false;
  for (uint tableno = 0; tableno < tables; tableno++) {
    POSITION *const pos = best_positions + tableno;
    if (has_semijoin && sj_is_materialize_strategy(pos->sj_strategy)) {
      assert(outer_target < inner_target);

      Table_ref *const sj_nest = pos->table->emb_sj_nest;

      // Handle this many inner tables of materialized semi-join
      remaining_sjm_inner = pos->n_sj_tables;

      /*
        If we fail in some allocation below, we cannot bail out immediately;
        that would put us in a difficult situation to clean up; imagine we
        have planned this layout:
          outer1 - sj_mat_tmp1 - outer2 - sj_mat_tmp2 - outer3
        We have successfully filled a JOIN_TAB for sj_mat_tmp1, and are
        failing to fill a JOIN_TAB for sj_mat_tmp2 (OOM). So we want to quit
        this function, which will lead to cleanup functions.
        But sj_mat_tmp1 is in this->best_ref only, outer3 is in this->join_tab
        only: what is the array to traverse for cleaning up? What is the
        number of tables to loop over?
        So: if we fail in the present loop, we record the error but continue
        filling best_ref; when it's fully filled, bail out, because then
        best_ref can be used as reliable array for cleaning up.
      */
      JOIN_TAB *const tab = tmp_join_tabs++;
      best_ref[outer_target] = tab;
      tab->set_join(this);
      tab->set_idx(outer_target);

      /*
        Up to this point there cannot be a failure. JOIN_TAB has been filled
        enough to be clean-able.
      */

      Semijoin_mat_exec *const sjm_exec = new (thd->mem_root) Semijoin_mat_exec(
          sj_nest, (pos->sj_strategy == SJ_OPT_MATERIALIZE_SCAN),
          remaining_sjm_inner, outer_target, inner_target);

      tab->set_sj_mat_exec(sjm_exec);

      if (!sjm_exec || setup_semijoin_materialized_table(
                           tab, sjm_index, pos, best_positions + sjm_index))
        err = true; /* purecov: inspected */

      outer_target++;
      sjm_index++;
    }
    /*
      Locate join_tab target for the table we are considering.
      (remaining_sjm_inner becomes negative for non-SJM tables, this can be
       safely ignored).
    */
    const uint target =
        (remaining_sjm_inner--) > 0 ? inner_target++ : outer_target++;
    JOIN_TAB *const tab = pos->table;

    best_ref[target] = tab;
    tab->set_idx(target);
    tab->set_position(pos);
    TABLE *const table = tab->table();
    if (tab->type() != JT_CONST && tab->type() != JT_SYSTEM) {
      if (pos->sj_strategy == SJ_OPT_LOOSE_SCAN && tab->range_scan() &&
          used_index(tab->range_scan()) != pos->loosescan_key) {
        /*
          We must use the duplicate-eliminating index, so this QUICK is not
          an option.
        */
        ::destroy(tab->range_scan());
        tab->set_range_scan(nullptr);
      }
      if (table->is_intersect() || table->is_except()) {
        tab->set_type(JT_ALL);  // INTERSECT, EXCEPT can't use ref access yet
      } else if (!pos->key) {
        if (tab->range_scan())
          tab->set_type(calc_join_type(tab->range_scan()));
        else
          tab->set_type(JT_ALL);
      } else {
        // REF or RANGE, clarify later when prefix tables are set for JOIN_TABs
        tab->set_type(JT_REF);
      }
    }
    assert(tab->type() != JT_UNKNOWN);

    assert(table->reginfo.join_tab == tab);
    if (!tab->join_cond())
      table->reginfo.not_exists_optimize = false;  // Only with LEFT JOIN
    map2table[tab->table_ref->tableno()] = tab;
  }

  // Count the materialized semi-join tables as regular input tables
  tables += sjm_nests + num_tmp_tables;
  // Set the number of non-materialized tables:
  primary_tables = outer_target;

  /*
    Between the last outer table or sj-mat tmp table, and the first sj-mat
    inner table, there may be 2 slots for sort/group/etc tmp tables:
  */
  for (uint i = 0; i < num_tmp_tables; ++i) {
    const uint idx = outer_target + i;
    tmp_join_tabs->set_join(this);
    tmp_join_tabs->set_idx(idx);
    assert(best_ref[idx] == nullptr);  // verify that not overwriting
    best_ref[idx] = tmp_join_tabs++;
    /*
      note that set_table() cannot be called yet. We may not even use this
      JOIN_TAB in the end, it's dummy at the moment. Which can be tested with
      "position()!=NULL".
    */
  }

  // make array unreachable: should walk JOIN_TABs by best_ref now
  join_tab = nullptr;

  if (err) return true; /* purecov: inspected */

  if (has_semijoin) {
    set_semijoin_info();

    // Update equalities and keyuses after having added SJ materialization
    if (update_equalities_for_sjm()) return true;
  }
  if (!plan_is_const()) {
    // Assign map of "available" tables to all tables belonging to query block
    set_prefix_tables();
    adjust_access_methods();
  }
  // Calculate outer join info
  if (query_block->outer_join) make_outerjoin_info();

  // sjm is no longer needed, trash it. To reuse it, reset its members!
  for (Table_ref *sj_nest : query_block->sj_nests) {
    TRASH(&sj_nest->nested_join->sjm, sizeof(sj_nest->nested_join->sjm));
  }

  return false;
}

/**
   Finds the dependencies of the remaining lateral derived tables.

   @param plan_tables  map of all tables that the planner is processing
                       (tables already in plan and tables to be added to plan).
   @param idx          index of the table which the planner is currently
                       considering.
   @return             A map of the dependencies of the remaining
                       lateral derived tables (from best_ref[idx] and on).
*/
table_map JOIN::calculate_deps_of_remaining_lateral_derived_tables(
    table_map plan_tables, uint idx) const {
  assert(has_lateral);
  table_map deps = 0;
  auto last = best_ref + tables;
  for (auto **pos = best_ref + idx; pos < last; pos++) {
    if ((*pos)->table_ref && ((*pos)->table_ref->map() & plan_tables)) {
      deps |= get_lateral_deps(**pos);
    }
  }
  return deps;
}

/*
  Revise usage of join buffer for the specified table and the whole nest

  SYNOPSIS
    revise_cache_usage()
      tab    join table for which join buffer usage is to be revised

  DESCRIPTION
    The function revise the decision to use a join buffer for the table 'tab'.
    If this table happened to be among the inner tables of a nested outer join/
    semi-join the functions denies usage of join buffers for all of them

  RETURN
    none
*/

static void revise_cache_usage(JOIN_TAB *join_tab) {
  plan_idx first_inner = join_tab->first_inner();
  JOIN *const join = join_tab->join();
  if (first_inner != NO_PLAN_IDX) {
    plan_idx end_tab = join_tab->idx();
    for (first_inner = join_tab->first_inner(); first_inner != NO_PLAN_IDX;
         first_inner = join->best_ref[first_inner]->first_upper()) {
      for (plan_idx i = end_tab - 1; i >= first_inner; --i)
        join->best_ref[i]->set_use_join_cache(JOIN_CACHE::ALG_NONE);
      end_tab = first_inner;
    }
  } else if (join_tab->get_sj_strategy() == SJ_OPT_FIRST_MATCH) {
    plan_idx first_sj_inner = join_tab->first_sj_inner();
    for (plan_idx i = join_tab->idx() - 1; i >= first_sj_inner; --i) {
      JOIN_TAB *tab = join->best_ref[i];
      if (tab->first_sj_inner() == first_sj_inner)
        tab->set_use_join_cache(JOIN_CACHE::ALG_NONE);
    }
  } else
    join_tab->set_use_join_cache(JOIN_CACHE::ALG_NONE);
  assert(join->qep_tab == nullptr);
}

/**
  Set up join buffering for a specified table, if possible.

  @param tab             joined table to check join buffer usage for
  @param join            join for which the check is performed
  @param no_jbuf_after   don't use join buffering after table with this number

  @return false if successful, true if error.
          Currently, allocation errors for join cache objects are ignored,
          and regular execution is chosen silently.

  @details
    The function finds out whether the table 'tab' can be joined using a join
    buffer. This check is performed after the best execution plan for 'join'
    has been chosen. If the function decides that a join buffer can be employed
    then it selects the most appropriate join cache type, which later will
    be instantiated by init_join_cache().
    If it has already been decided to not use join buffering for this table,
    no action is taken.

    Often it is already decided that join buffering will be used earlier in
    the optimization process, and this will also ensure that the most correct
    cost for the operation is calculated, and hence the probability of
    choosing an optimal join plan is higher. However, some join buffering
    decisions cannot currently be taken before this stage, hence we need this
    function to decide the most accurate join buffering strategy.

    @todo Long-term it is the goal that join buffering strategy is decided
    when the plan is selected.

    The result of the check and the type of the join buffer to be used
    depend on:
      - the access method to access rows of the joined table
      - whether the join table is an inner table of an outer join or semi-join
      - the optimizer_switch settings for join buffering
      - the join 'options'.
    In any case join buffer is not used if the number of the joined table is
    greater than 'no_jbuf_after'.

    If block_nested_loop is turned on, and if all other criteria for using
    join buffering is fulfilled (see below), then join buffer is used
    for any join operation (inner join, outer join, semi-join) with 'JT_ALL'
    access method.  In that case, a JOIN_CACHE_BNL type is always employed.

    If an index is used to access rows of the joined table and
  batched_key_access is on, then a JOIN_CACHE_BKA type is employed.

    If the function decides that a join buffer can be used to join the table
    'tab' then it sets @c tab->use_join_cache to reflect the chosen algorithm.

  @note
    For a nested outer join/semi-join, currently, we either use join buffers for
    all inner tables or for none of them.

    Join buffering is enabled for a few more cases for secondary engine.
    Currently if blocked nested loop(BNL) is employed for join buffering,
    it is replaced by hash joins in the executor. So the reasons for disabling
    join buffering because of the way BNL works are no more valid. This gives
    us an oppotunity to enable join buffering for more cases. However,
    we enable it only for secondary engine (in particular for semijoins),
    because of the following reasons:
    Secondary engine does not care about the cost based decisions
    involved in arriving at the best possible semijoin strategy;
    because it can only interpret a plan using "FirstMatch" strategy
    and can only do table scans. So the choices are very limited.
    However, it's not the case for mysql. There are serveral semijoin
    stratagies that could be picked. And these are picked based
    on the assumption that a nested-loop join(NLJ) would be used because
    optimizer currently generates plans only for NLJs and not
    hash joins. So, when executor replaces with hash joins, the number
    of rows that would be looked into for a particular semijoin strategy
    will differ from what the optimizer presumed while picking that
    strategy.
    For mysql server, we could enable join buffering for more cases, when
    a cost model for using hash joins is developed and optimizer could
    generate plans for hash joins.

  @todo
    Support BKA inside SJ-Materialization nests. When doing this, we'll need
    to only store sj-inner tables in the join buffer.
    @verbatim
        JOIN_TAB *first_tab= join->join_tab+join->const_tables;
        uint n_tables= i-join->const_tables;
        / *
          We normally put all preceding tables into the join buffer, except
          for the constant tables.
          If we're inside a semi-join materialization nest, e.g.

             outer_tbl1  outer_tbl2  ( inner_tbl1, inner_tbl2 ) ...
                                                       ^-- we're here

          then we need to put into the join buffer only the tables from
          within the nest.
        * /
        if (i >= first_sjm_table && i < last_sjm_table)
        {
          n_tables= i - first_sjm_table; // will be >0 if we got here
          first_tab= join->join_tab + first_sjm_table;
        }
    @endverbatim
*/

static bool setup_join_buffering(JOIN_TAB *tab, JOIN *join,
                                 uint no_jbuf_after) {
  ASSERT_BEST_REF_IN_JOIN_ORDER(join);
  Cost_estimate cost;
  ha_rows rows;
  uint bufsz = 4096;
  uint join_cache_flags = 0;
  const bool bnl_on = hint_table_state(join->thd, tab->table_ref, BNL_HINT_ENUM,
                                       OPTIMIZER_SWITCH_BNL);
  const bool bka_on = hint_table_state(join->thd, tab->table_ref, BKA_HINT_ENUM,
                                       OPTIMIZER_SWITCH_BKA);

  const uint tableno = tab->idx();
  const uint tab_sj_strategy = tab->get_sj_strategy();

  /*
    If all key_parts are null_rejecting, the MultiRangeRowIterator will
    eliminate all NULL values in the key set, such that
    HA_MRR_NO_NULL_ENDPOINTS can be promised.
  */
  const key_part_map keypart_map = make_prev_keypart_map(tab->ref().key_parts);
  if (tab->ref().null_rejecting == keypart_map) {
    join_cache_flags |= HA_MRR_NO_NULL_ENDPOINTS;
  }

  // Set preliminary join cache setting based on decision from greedy search
  if (!join->select_count)
    tab->set_use_join_cache(tab->position()->use_join_buffer
                                ? JOIN_CACHE::ALG_BNL
                                : JOIN_CACHE::ALG_NONE);

  if (tableno == join->const_tables) {
    assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
    return false;
  }

  if (!(bnl_on || bka_on)) goto no_join_cache;

  /*
    psergey-todo: why the below when execution code seems to handle the
    "range checked for each record" case?
  */
  if (tab->use_quick == QS_DYNAMIC_RANGE) goto no_join_cache;

  /* No join buffering if prevented by no_jbuf_after */
  if (tableno > no_jbuf_after) goto no_join_cache;

  /*
    An inner table of an outer join nest must not use join buffering if
    the first inner table of that outer join nest does not use join buffering.
    This condition is not handled by earlier optimizer stages.
  */
  if (tab->first_inner() != NO_PLAN_IDX && tab->first_inner() != tab->idx() &&
      !join->best_ref[tab->first_inner()]->use_join_cache())
    goto no_join_cache;
  /*
    The first inner table of an outer join nest must not use join buffering
    if the tables in the embedding outer join nest do not use join buffering.
    This condition is not handled by earlier optimizer stages.
  */
  if (tab->first_upper() != NO_PLAN_IDX &&
      !join->best_ref[tab->first_upper()]->use_join_cache())
    goto no_join_cache;

  if (tab->table()->pos_in_table_list->is_table_function() && tab->dependent)
    goto no_join_cache;

  switch (tab_sj_strategy) {
    case SJ_OPT_FIRST_MATCH:
      /*
        Use join cache with FirstMatch semi-join strategy only when semi-join
        contains only one table.
        As mentioned earlier (in comments), we lift this restriction for
        secondary engine.
      */
      if (!(current_thd->lex->m_sql_cmd != nullptr &&
            current_thd->lex->m_sql_cmd->using_secondary_storage_engine())) {
        if (!tab->is_single_inner_of_semi_join()) {
          assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
          goto no_join_cache;
        }
      }
      break;

    case SJ_OPT_LOOSE_SCAN:
      /* No join buffering if this semijoin nest is handled by loosescan */
      assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
      goto no_join_cache;

    case SJ_OPT_MATERIALIZE_LOOKUP:
    case SJ_OPT_MATERIALIZE_SCAN:
      /*
        The Materialize strategies reuse the join_tab belonging to the
        first table that was materialized. Neither table can use join buffering:
        - The first table in a join never uses join buffering.
        - The join_tab used for looking up a row in the materialized table, or
          scanning the rows of a materialized table, cannot use join buffering.
        We allow join buffering for the remaining tables of the materialized
        semi-join nest.
      */
      if (tab->first_sj_inner() == tab->idx()) {
        assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
        goto no_join_cache;
      }
      break;

    case SJ_OPT_DUPS_WEEDOUT:
    // This strategy allows the same join buffering as a regular join would.
    case SJ_OPT_NONE:
      break;
  }

  /*
    The following code prevents use of join buffering when there is an
    outer join operation and first match semi-join strategy is used, because:

    Outer join needs a "match flag" to track that a row should be
    NULL-complemented, such flag being attached to first inner table's cache
    (tracks whether the cached row from outer table got a match, in which case
    no NULL-complemented row is needed).

    FirstMatch also needs a "match flag", such flag is attached to sj inner
    table's cache (tracks whether the cached row from outer table already got
    a first match in the sj-inner table, in which case we don't need to join
    this cached row again)
     - but a row in a cache has only one "match flag"
     - so if "sj inner table"=="first inner", there is a problem.

    As mentioned earlier(in comments), we lift this restriction for
    secondary engine.
  */
  if (!(current_thd->lex->m_sql_cmd != nullptr &&
        current_thd->lex->m_sql_cmd->using_secondary_storage_engine())) {
    if (tab_sj_strategy == SJ_OPT_FIRST_MATCH &&
        tab->is_inner_table_of_outer_join())
      goto no_join_cache;
  }

  if (join->deps_of_remaining_lateral_derived_tables &
      (tab->prefix_tables() & ~tab->added_tables())) {
    /*
      Even though the planner said "no jbuf please", the switch below may
      force it.
      If first-dependency-of-lateral-table < table-we-plan-for <=
      lateral-table, disable join buffering.
      Reason for this rule:
      consider a plan t1-t2-dt where dt is LATERAL and depends only on t1, and
      imagine t2 could do join buffering: then we buffer many rows of t1, then
      read one row of t2, fetch row#1 of t1 from cache, then materialize "dt"
      (as it depends on t1) and send row to client; then fetch row#2 of t1
      from cache, rematerialize "dt": it's very inefficient. So we forbid join
      buffering on t2; this way, the signal "row of t1 changed" is emitted at
      the level of t1's operator, i.e. much less often, as one row of t1 may
      serve N rows of t2 before changing.
      On the other hand, t1 can do join buffering.
      A nice side-effect is to disable join buffering for "dt" itself. If
      "dt" would do join buffering: "dt" buffers many rows from t1/t2, then in a
      second phase we read one row from "dt" and join it with the many rows
      from t1/t2; but we cannot read a row from "dt" without first choosing a
      row of t1/t2 as "dt" depends on t1.
      See similar code in best_access_path().
    */
    goto no_join_cache;
  }

  switch (tab->type()) {
    case JT_ALL:
    case JT_INDEX_SCAN:
    case JT_RANGE:
    case JT_INDEX_MERGE:
      if (!bnl_on) {
        assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
        goto no_join_cache;
      }

      if (!join->select_count) tab->set_use_join_cache(JOIN_CACHE::ALG_BNL);
      return false;
    case JT_SYSTEM:
    case JT_CONST:
    case JT_REF:
    case JT_EQ_REF:
      if (!bka_on) {
        assert(tab->use_join_cache() == JOIN_CACHE::ALG_NONE);
        goto no_join_cache;
      }

      /*
        Disable BKA for materializable derived tables/views as they aren't
        instantiated yet.
      */
      if (tab->table_ref->uses_materialization()) goto no_join_cache;

      /*
        Can't use BKA for subquery if dealing with a subquery that can
        turn a ref access into a "full scan on NULL key" table scan.

        @see Item_in_optimizer::val_int()
        @see subselect_iterator_engine::exec()
        @see Index_lookup::cond_guards
        @see push_index_cond()

        @todo: This choice to not use BKA should be done before making
        cost estimates, e.g. in set_join_buffer_properties(). That
        happens before cond guards are set up, so instead of doing the
        check below, BKA should be disabled if
         - We are in an IN subquery, and
         - The IN predicate is not a top_level_item, and
         - The left_expr of the IN predicate may contain NULL values
           (left_expr->maybe_null)
      */
      if (tab->has_guarded_conds()) goto no_join_cache;

      if (tab->table()->covering_keys.is_set(tab->ref().key))
        join_cache_flags |= HA_MRR_INDEX_ONLY;
      rows = tab->table()->file->multi_range_read_info(
          tab->ref().key, 10, 20, &bufsz, &join_cache_flags, &cost);
      /*
        Cannot use BKA if
        1. MRR scan cannot be performed, or
        2. MRR default implementation is used, or
        3. HA_MRR_NO_ASSOCIATION flag is set
      */
      if ((rows == HA_POS_ERROR) ||                        // 1
          (join_cache_flags & HA_MRR_USE_DEFAULT_IMPL) ||  // 2
          (join_cache_flags & HA_MRR_NO_ASSOCIATION))      // 3
        goto no_join_cache;

      tab->set_use_join_cache(JOIN_CACHE::ALG_BKA);

      tab->join_cache_flags = join_cache_flags;
      return false;
    default:;
  }

no_join_cache:
  revise_cache_usage(tab);
  tab->set_use_join_cache(JOIN_CACHE::ALG_NONE);
  return false;
}

/*****************************************************************************
  Make some simple condition optimization:
  If there is a test 'field = const' change all refs to 'field' to 'const'
  Remove all dummy tests 'item = item', 'const op const'.
  Remove all 'item is NULL', when item can never be null!
  Return in cond_value false if condition is impossible (1 = 2)
*****************************************************************************/

class COND_CMP : public ilink<COND_CMP> {
 public:
  static void *operator new(size_t size) { return (*THR_MALLOC)->Alloc(size); }
  static void operator delete(void *ptr [[maybe_unused]],
                              size_t size [[maybe_unused]]) {
    TRASH(ptr, size);
  }

  Item *and_level;
  Item_func *cmp_func;
  COND_CMP(Item *a, Item_func *b) : and_level(a), cmp_func(b) {}
};

Item_equal *find_item_equal(COND_EQUAL *cond_equal,
                            const Item_field *item_field, bool *inherited_fl) {
  Item_equal *item = nullptr;
  bool in_upper_level = false;
  while (cond_equal) {
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
    while ((item = li++)) {
      if (item->contains(item_field->field)) goto finish;
    }
    in_upper_level = true;
    cond_equal = cond_equal->upper_levels;
  }
  in_upper_level = false;
finish:
  *inherited_fl = in_upper_level;
  return item;
}

/**
  Get the best field substitution for a given field.

  If the field is member of a multiple equality, look up that equality
  and return the most appropriate field. Usually this is the equivalenced
  field belonging to the outer-most table in the join order, but
  @see Item_field::get_subst_item() for details.
  Otherwise, return the same field.

  @param item_field The field that we are seeking a substitution for.
  @param cond_equal multiple equalities to search in

  @return The substituted field.
*/

Item_field *get_best_field(Item_field *item_field, COND_EQUAL *cond_equal) {
  bool dummy;
  Item_equal *item_eq = find_item_equal(cond_equal, item_field, &dummy);
  if (!item_eq) return item_field;

  return item_eq->get_subst_item(item_field);
}

/**
  Check whether an equality can be used to build multiple equalities.

    This function first checks whether the equality (left_item=right_item)
    is a simple equality i.e. one that equates a field with another field
    or a constant (field=field_item or field=const_item).
    If this is the case the function looks for a multiple equality
    in the lists referenced directly or indirectly by cond_equal inferring
    the given simple equality. If it doesn't find any, it builds a multiple
    equality that covers the predicate, i.e. the predicate can be inferred
    from this multiple equality.
    The built multiple equality could be obtained in such a way:
    create a binary  multiple equality equivalent to the predicate, then
    merge it, if possible, with one of old multiple equalities.
    This guarantees that the set of multiple equalities covering equality
    predicates will be minimal.

  EXAMPLE:
    For the where condition
    @code
      WHERE a=b AND b=c AND
            (b=2 OR f=e)
    @endcode
    the check_equality will be called for the following equality
    predicates a=b, b=c, b=2 and f=e.
    - For a=b it will be called with *cond_equal=(0,[]) and will transform
      *cond_equal into (0,[Item_equal(a,b)]).
    - For b=c it will be called with *cond_equal=(0,[Item_equal(a,b)])
      and will transform *cond_equal into CE=(0,[Item_equal(a,b,c)]).
    - For b=2 it will be called with *cond_equal=(ptr(CE),[])
      and will transform *cond_equal into (ptr(CE),[Item_equal(2,a,b,c)]).
    - For f=e it will be called with *cond_equal=(ptr(CE), [])
      and will transform *cond_equal into (ptr(CE),[Item_equal(f,e)]).

  @note
    Now only fields that have the same type definitions (verified by
    the Field::eq_def method) are placed to the same multiple equalities.
    Because of this some equality predicates are not eliminated and
    can be used in the constant propagation procedure.
    We could weaken the equality test as soon as at least one of the
    equal fields is to be equal to a constant. It would require a
    more complicated implementation: we would have to store, in
    general case, its own constant for each fields from the multiple
    equality. But at the same time it would allow us to get rid
    of constant propagation completely: it would be done by the call
    to build_equal_items_for_cond.

    The implementation does not follow exactly the above rules to
    build a new multiple equality for the equality predicate.
    If it processes the equality of the form field1=field2, it
    looks for multiple equalities me1 containing field1 and me2 containing
    field2. If only one of them is found the function expands it with
    the lacking field. If multiple equalities for both fields are
    found they are merged. If both searches fail a new multiple equality
    containing just field1 and field2 is added to the existing
    multiple equalities.
    If the function processes the predicate of the form field1=const,
    it looks for a multiple equality containing field1. If found, the
    function checks the constant of the multiple equality. If the value
    is unknown, it is setup to const. Otherwise the value is compared with
    const and the evaluation of the equality predicate is performed.
    When expanding/merging equality predicates from the upper levels
    the function first copies them for the current level. It looks
    acceptable, as this happens rarely. The implementation without
    copying would be much more complicated.

  @param thd         Thread handler
  @param left_item   left term of the equality to be checked
  @param right_item  right term of the equality to be checked
  @param item        equality item if the equality originates from a condition
                     predicate, 0 if the equality is the result of row
                     elimination
  @param cond_equal  multiple equalities that must hold together with the
                     equality
  @param[out] simple_equality
                     true  if the predicate is a simple equality predicate
                           to be used for building multiple equalities
                     false otherwise

  @returns false if success, true if error
*/

static bool check_simple_equality(THD *thd, Item *left_item, Item *right_item,
                                  Item *item, COND_EQUAL *cond_equal,
                                  bool *simple_equality) {
  *simple_equality = false;

  if (left_item->type() == Item::REF_ITEM &&
      down_cast<Item_ref *>(left_item)->ref_type() == Item_ref::VIEW_REF) {
    if (down_cast<Item_ref *>(left_item)->is_outer_reference()) return false;
    left_item = left_item->real_item();
  }
  if (right_item->type() == Item::REF_ITEM &&
      down_cast<Item_ref *>(right_item)->ref_type() == Item_ref::VIEW_REF) {
    if (down_cast<Item_ref *>(right_item)->is_outer_reference()) return false;
    right_item = right_item->real_item();
  }
  const Item_field *left_item_field, *right_item_field;

  if (left_item->type() == Item::FIELD_ITEM &&
      right_item->type() == Item::FIELD_ITEM &&
      (left_item_field = down_cast<const Item_field *>(left_item)) &&
      (right_item_field = down_cast<const Item_field *>(right_item)) &&
      !left_item_field->depended_from && !right_item_field->depended_from) {
    /* The predicate the form field1=field2 is processed */

    const Field *const left_field = left_item_field->field;
    const Field *const right_field = right_item_field->field;

    if (!left_field->eq_def(right_field)) return false;

    /* Search for multiple equalities containing field1 and/or field2 */
    bool left_copyfl, right_copyfl;
    Item_equal *left_item_equal =
        find_item_equal(cond_equal, left_item_field, &left_copyfl);
    Item_equal *right_item_equal =
        find_item_equal(cond_equal, right_item_field, &right_copyfl);

    /* As (NULL=NULL) != TRUE we can't just remove the predicate f=f */
    if (left_field->eq(right_field)) /* f = f */
    {
      *simple_equality =
          !((left_field->is_nullable() || left_field->table->is_nullable()) &&
            !left_item_equal);
      return false;
    }

    if (left_item_equal && left_item_equal == right_item_equal) {
      /*
        The equality predicate is inference of one of the existing
        multiple equalities, i.e the condition is already covered
        by upper level equalities
      */
      *simple_equality = true;
      return false;
    }

    /* Copy the found multiple equalities at the current level if needed */
    if (left_copyfl) {
      /* left_item_equal of an upper level contains left_item */
      left_item_equal = new Item_equal(left_item_equal);
      if (left_item_equal == nullptr) return true;
      cond_equal->current_level.push_back(left_item_equal);
    }
    if (right_copyfl) {
      /* right_item_equal of an upper level contains right_item */
      right_item_equal = new Item_equal(right_item_equal);
      if (right_item_equal == nullptr) return true;
      cond_equal->current_level.push_back(right_item_equal);
    }

    if (left_item_equal) {
      /* left item was found in the current or one of the upper levels */
      if (!right_item_equal)
        left_item_equal->add(down_cast<Item_field *>(right_item));
      else {
        /* Merge two multiple equalities forming a new one */
        if (left_item_equal->merge(thd, right_item_equal)) return true;
        /* Remove the merged multiple equality from the list */
        List_iterator<Item_equal> li(cond_equal->current_level);
        while ((li++) != right_item_equal)
          ;
        li.remove();
      }
    } else {
      /* left item was not found neither the current nor in upper levels  */
      if (right_item_equal) {
        right_item_equal->add(down_cast<Item_field *>(left_item));
      } else {
        /* None of the fields was found in multiple equalities */
        Item_equal *item_equal =
            new Item_equal(down_cast<Item_field *>(left_item),
                           down_cast<Item_field *>(right_item));
        if (item_equal == nullptr) return true;
        cond_equal->current_level.push_back(item_equal);
      }
    }
    *simple_equality = true;
    return false;
  }

  {
    /* The predicate of the form field=const/const=field is processed */
    Item *const_item = nullptr;
    Item_field *field_item = nullptr;
    if (left_item->type() == Item::FIELD_ITEM &&
        (field_item = down_cast<Item_field *>(left_item)) &&
        field_item->depended_from == nullptr &&
        right_item->const_for_execution()) {
      const_item = right_item;
    } else if (right_item->type() == Item::FIELD_ITEM &&
               (field_item = down_cast<Item_field *>(right_item)) &&
               field_item->depended_from == nullptr &&
               left_item->const_for_execution()) {
      const_item = left_item;
    }

    // Don't evaluate subqueries if they are disabled during optimization.
    if (const_item != nullptr &&
        !evaluate_during_optimization(const_item,
                                      thd->lex->current_query_block()))
      return false;

    /*
      If the constant expression contains a reference to the field
      (for example, a = (a IS NULL)), we don't want to replace the
      field with the constant expression as it makes the predicates
      more complex and may introduce cycles in the Item tree.
    */
    if (const_item != nullptr &&
        const_item->walk(&Item::find_field_processor, enum_walk::POSTFIX,
                         pointer_cast<uchar *>(field_item->field)))
      return false;

    if (const_item && field_item->result_type() == const_item->result_type()) {
      if (field_item->result_type() == STRING_RESULT) {
        const CHARSET_INFO *cs = field_item->field->charset();
        if (!item) {
          Item_func_eq *const eq_item = new Item_func_eq(left_item, right_item);
          if (eq_item == nullptr || eq_item->set_cmp_func()) return true;
          eq_item->quick_fix_field();
          item = eq_item;
        }
        if ((cs != down_cast<Item_func *>(item)->compare_collation()) ||
            !cs->coll->propagate(cs, nullptr, 0))
          return false;
        // Don't build multiple equalities mixing strings and JSON, not even
        // when they have the same collation, since string comparison and JSON
        // comparison are very different.
        if ((field_item->data_type() == MYSQL_TYPE_JSON) !=
            (const_item->data_type() == MYSQL_TYPE_JSON)) {
          return false;
        }
        // Similarly, strings and temporal types have different semantics for
        // equality comparison.
        if (const_item->is_temporal()) {
          // No multiple equality for string columns compared to temporal
          // values. See also comment in comparable_in_index().
          if (!field_item->is_temporal()) {
            return false;
          }
          // No multiple equality for TIME columns compared to temporal values.
          // See also comment in comparable_in_index().
          if (const_item->is_temporal_with_date() &&
              !field_item->is_temporal_with_date()) {
            return false;
          }
        }
      }

      bool copyfl;
      Item_equal *item_equal = find_item_equal(cond_equal, field_item, &copyfl);
      if (copyfl) {
        item_equal = new Item_equal(item_equal);
        if (item_equal == nullptr) return true;
        cond_equal->current_level.push_back(item_equal);
      }
      if (item_equal) {
        if (item_equal->const_arg() != nullptr) {
          // Make sure that the existing const and new one are of comparable
          // collation.
          DTCollation cmp_collation;
          if (cmp_collation.set(const_item->collation,
                                item_equal->const_arg()->collation,
                                MY_COLL_CMP_CONV) ||
              cmp_collation.derivation == DERIVATION_NONE) {
            return false;
          }
        }
        /*
          The flag cond_false will be set to 1 after this, if item_equal
          already contains a constant and its value is  not equal to
          the value of const_item.
        */
        if (item_equal->add(thd, const_item, field_item)) return true;
      } else {
        item_equal = new Item_equal(const_item, field_item);
        if (item_equal == nullptr) return true;
        cond_equal->current_level.push_back(item_equal);
      }
      *simple_equality = true;
      return false;
    }
  }
  return false;
}

/**
  Convert row equalities into a conjunction of regular equalities.

    The function converts a row equality of the form (E1,...,En)=(E'1,...,E'n)
    into a list of equalities E1=E'1,...,En=E'n. For each of these equalities
    Ei=E'i the function checks whether it is a simple equality or a row
    equality. If it is a simple equality it is used to expand multiple
    equalities of cond_equal. If it is a row equality it converted to a
    sequence of equalities between row elements. If Ei=E'i is neither a
    simple equality nor a row equality the item for this predicate is added
    to eq_list.

  @param thd        thread handle
  @param left_row   left term of the row equality to be processed
  @param right_row  right term of the row equality to be processed
  @param cond_equal multiple equalities that must hold together with the
                    predicate
  @param eq_list    results of conversions of row equalities that are not
                    simple enough to form multiple equalities
  @param[out] simple_equality
                    true if the row equality is composed of only
                    simple equalities.

  @returns false if conversion succeeded, true if any error.
*/

static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row,
                               COND_EQUAL *cond_equal, List<Item> *eq_list,
                               bool *simple_equality) {
  *simple_equality = false;
  uint n = left_row->cols();
  for (uint i = 0; i < n; i++) {
    bool is_converted;
    Item *left_item = left_row->element_index(i);
    Item *right_item = right_row->element_index(i);
    if (left_item->type() == Item::ROW_ITEM &&
        right_item->type() == Item::ROW_ITEM) {
      if (check_row_equality(thd, down_cast<Item_row *>(left_item),
                             down_cast<Item_row *>(right_item), cond_equal,
                             eq_list, &is_converted))
        return true;
      if (!is_converted) thd->lex->current_query_block()->cond_count++;
    } else {
      if (check_simple_equality(thd, left_item, right_item, nullptr, cond_equal,
                                &is_converted))
        return true;
      thd->lex->current_query_block()->cond_count++;
    }

    if (!is_converted) {
      Item_func_eq *const eq_item = new Item_func_eq(left_item, right_item);
      if (eq_item == nullptr) return true;
      if (eq_item->set_cmp_func()) {
        // Failed to create cmp func -> not only simple equalitities
        return true;
      }
      eq_item->quick_fix_field();
      eq_list->push_back(eq_item);
    }
  }
  *simple_equality = true;
  return false;
}

/**
  Eliminate row equalities and form multiple equalities predicates.

    This function checks whether the item is a simple equality
    i.e. the one that equates a field with another field or a constant
    (field=field_item or field=constant_item), or, a row equality.
    For a simple equality the function looks for a multiple equality
    in the lists referenced directly or indirectly by cond_equal inferring
    the given simple equality. If it doesn't find any, it builds/expands
    multiple equality that covers the predicate.
    Row equalities are eliminated substituted for conjunctive regular
    equalities which are treated in the same way as original equality
    predicates.

  @param thd        thread handle
  @param item       predicate to process
  @param cond_equal multiple equalities that must hold together with the
                    predicate
  @param eq_list    results of conversions of row equalities that are not
                    simple enough to form multiple equalities
  @param[out] equality
                    true if re-writing rules have been applied
                    false otherwise, i.e.
                      if the predicate is not an equality, or
                      if the equality is neither a simple nor a row equality

  @returns false if success, true if error

  @note If the equality was created by IN->EXISTS, it may be removed later by
  subquery materialization. So we don't mix this possibly temporary equality
  with others; if we let it go into a multiple-equality (Item_equal), then we
  could not remove it later. There is however an exception: if the outer
  expression is a constant, it is safe to leave the equality even in
  materialization; all it can do is preventing NULL/FALSE distinction but if
  such distinction mattered the equality would be in a triggered condition so
  we would not come to this function. And injecting constants is good because
  it makes the materialized table smaller.
*/

static bool check_equality(THD *thd, Item *item, COND_EQUAL *cond_equal,
                           List<Item> *eq_list, bool *equality) {
  *equality = false;
  assert(item->is_bool_func());
  Item_func *item_func;
  if (item->type() == Item::FUNC_ITEM &&
      (item_func = down_cast<Item_func *>(item))->functype() ==
          Item_func::EQ_FUNC) {
    Item *left_item = item_func->arguments()[0];
    Item *right_item = item_func->arguments()[1];

    if (item->created_by_in2exists() && !left_item->const_item())
      return false;  // See note above

    if (left_item->type() == Item::ROW_ITEM &&
        right_item->type() == Item::ROW_ITEM) {
      thd->lex->current_query_block()->cond_count--;
      return check_row_equality(thd, down_cast<Item_row *>(left_item),
                                down_cast<Item_row *>(right_item), cond_equal,
                                eq_list, equality);
    } else
      return check_simple_equality(thd, left_item, right_item, item, cond_equal,
                                   equality);
  }

  return false;
}

/**
  Replace all equality predicates in a condition by multiple equality items.

    At each 'and' level the function detects items for equality predicates
    and replaces them by a set of multiple equality items of class Item_equal,
    taking into account inherited equalities from upper levels.
    If an equality predicate is used not in a conjunction it's just
    replaced by a multiple equality predicate.
    For each 'and' level the function set a pointer to the inherited
    multiple equalities in the cond_equal field of the associated
    object of the type Item_cond_and.
    The function also traverses the cond tree and for each field reference
    sets a pointer to the multiple equality item containing the field, if there
    is any. If this multiple equality equates fields to a constant the
    function replaces the field reference by the constant in the cases
    when the field is not of a string type or when the field reference is
    just an argument of a comparison predicate.
    The function also determines the maximum number of members in
    equality lists of each Item_cond_and object assigning it to
    thd->lex->current_query_block()->max_equal_elems.

  @note
    Multiple equality predicate =(f1,..fn) is equivalent to the conjunction of
    f1=f2, .., fn-1=fn. It substitutes any inference from these
    equality predicates that is equivalent to the conjunction.
    Thus, =(a1,a2,a3) can substitute for ((a1=a3) AND (a2=a3) AND (a2=a1)) as
    it is equivalent to ((a1=a2) AND (a2=a3)).
    The function always makes a substitution of all equality predicates occurred
    in a conjunction for a minimal set of multiple equality predicates.
    This set can be considered as a canonical representation of the
    sub-conjunction of the equality predicates.
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by
    (=(t1.a,t2.b,t3.c) AND t2.b>5), not by
    (=(t1.a,t2.b) AND =(t1.a,t3.c) AND t2.b>5);
    while (t1.a=t2.b AND t2.b>5 AND t3.c=t4.d) is replaced by
    (=(t1.a,t2.b) AND =(t3.c=t4.d) AND t2.b>5),
    but if additionally =(t4.d,t2.b) is inherited, it
    will be replaced by (=(t1.a,t2.b,t3.c,t4.d) AND t2.b>5)

    The function performs the substitution in a recursive descent of
    the condition tree, passing to the next AND level a chain of multiple
    equality predicates which have been built at the upper levels.
    The Item_equal items built at the level are attached to other
    non-equality conjuncts as a sublist. The pointer to the inherited
    multiple equalities is saved in the and condition object (Item_cond_and).
    This chain allows us for any field reference occurrence to easily find a
    multiple equality that must be held for this occurrence.
    For each AND level we do the following:
    - scan it for all equality predicate (=) items
    - join them into disjoint Item_equal() groups
    - process the included OR conditions recursively to do the same for
      lower AND levels.

    We need to do things in this order as lower AND levels need to know about
    all possible Item_equal objects in upper levels.

  @param thd          thread handle
  @param cond         condition(expression) where to make replacement
  @param[out] retcond returned condition
  @param inherited    path to all inherited multiple equality items
  @param do_inherit   whether or not to inherit equalities from other parts
                      of the condition

  @returns false if success, true if error
*/

static bool build_equal_items_for_cond(THD *thd, Item *cond, Item **retcond,
                                       COND_EQUAL *inherited, bool do_inherit) {
  Item_equal *item_equal;
  COND_EQUAL cond_equal;
  cond_equal.upper_levels = inherited;
  assert(cond->is_bool_func());
  if (check_stack_overrun(thd, STACK_MIN_SIZE, nullptr))
    return true;  // Fatal error flag is set!

  const enum Item::Type cond_type = cond->type();
  if (cond_type == Item::COND_ITEM) {
    List<Item> eq_list;
    Item_cond *const item_cond = down_cast<Item_cond *>(cond);
    const bool and_level = item_cond->functype() == Item_func::COND_AND_FUNC;
    List<Item> *args = item_cond->argument_list();

    List_iterator<Item> li(*args);
    Item *item;

    if (and_level) {
      /*
         Retrieve all conjuncts of this level detecting the equality
         that are subject to substitution by multiple equality items and
         removing each such predicate from the conjunction after having
         found/created a multiple equality whose inference the predicate is.
       */
      while ((item = li++)) {
        /*
          PS/SP note: we can safely remove a node from AND-OR
          structure here because it's restored before each
          re-execution of any prepared statement/stored procedure.
        */
        bool equality;
        if (check_equality(thd, item, &cond_equal, &eq_list, &equality))
          return true;
        if (equality) li.remove();
      }

      /*
        Check if we eliminated all the predicates of the level, e.g.
        (a=a AND b=b AND a=a).
      */
      if (!args->elements && !cond_equal.current_level.elements &&
          !eq_list.elements) {
        *retcond = new Item_func_true();
        return *retcond == nullptr;
      }

      List_iterator_fast<Item_equal> it(cond_equal.current_level);
      while ((item_equal = it++)) {
        if (item_equal->resolve_type(thd)) return true;
        item_equal->update_used_tables();
        thd->lex->current_query_block()->max_equal_elems =
            std::max(thd->lex->current_query_block()->max_equal_elems,
                     item_equal->members());
      }

      Item_cond_and *const item_cond_and = down_cast<Item_cond_and *>(cond);
      item_cond_and->cond_equal = cond_equal;
      inherited = &item_cond_and->cond_equal;
    }
    /*
       Make replacement of equality predicates for lower levels
       of the condition expression.
    */
    li.rewind();
    while ((item = li++)) {
      Item *new_item;
      if (build_equal_items_for_cond(thd, item, &new_item, inherited,
                                     do_inherit))
        return true;
      if (new_item != item) {
        /* This replacement happens only for standalone equalities */
        /*
          This is ok with PS/SP as the replacement is done for
          arguments of an AND/OR item, which are restored for each
          execution of PS/SP.
        */
        li.replace(new_item);
      }
    }
    if (and_level) {
      args->concat(&eq_list);
      args->concat((List<Item> *)&cond_equal.current_level);
    }
  } else if (cond->type() == Item::FUNC_ITEM) {
    List<Item> eq_list;
    /*
      If an equality predicate forms the whole and level,
      we call it standalone equality and it's processed here.
      E.g. in the following where condition
      WHERE a=5 AND (b=5 or a=c)
      (b=5) and (a=c) are standalone equalities.
      In general we can't leave alone standalone eqalities:
      for WHERE a=b AND c=d AND (b=c OR d=5)
      b=c is replaced by =(a,b,c,d).
     */
    bool equality;
    if (check_equality(thd, cond, &cond_equal, &eq_list, &equality))
      return true;
    if (equality) {
      int n = cond_equal.current_level.elements + eq_list.elements;
      if (n == 0) {
        *retcond = new Item_func_true();
        return *retcond == nullptr;
      } else if (n == 1) {
        if ((item_equal = cond_equal.current_level.pop())) {
          if (item_equal->resolve_type(thd)) return true;
          item_equal->update_used_tables();
          thd->lex->current_query_block()->max_equal_elems =
              std::max(thd->lex->current_query_block()->max_equal_elems,
                       item_equal->members());
          *retcond = item_equal;
          return false;
        }

        *retcond = eq_list.pop();
        return false;
      } else {
        /*
          Here a new AND level must be created. It can happen only
          when a row equality is processed as a standalone predicate.
        */
        Item_cond_and *and_cond = new Item_cond_and(eq_list);
        if (and_cond == nullptr) return true;

        and_cond->quick_fix_field();
        List<Item> *args = and_cond->argument_list();
        List_iterator_fast<Item_equal> it(cond_equal.current_level);
        while ((item_equal = it++)) {
          if (item_equal->resolve_type(thd)) return true;
          item_equal->update_used_tables();
          thd->lex->current_query_block()->max_equal_elems =
              std::max(thd->lex->current_query_block()->max_equal_elems,
                       item_equal->members());
        }
        and_cond->cond_equal = cond_equal;
        args->concat((List<Item> *)&cond_equal.current_level);

        *retcond = and_cond;
        return false;
      }
    }

    if (do_inherit) {
      /*
        For each field reference in cond, not from equal item predicates,
        set a pointer to the multiple equality it belongs to (if there is any)
        as soon the field is not of a string type or the field reference is
        an argument of a comparison predicate.
      */
      uchar *is_subst_valid = (uchar *)1;
      cond = cond->compile(&Item::subst_argument_checker, &is_subst_valid,
                           &Item::equal_fields_propagator, (uchar *)inherited);
      if (cond == nullptr) return true;
    }
    cond->update_used_tables();
  }
  *retcond = cond;
  return false;
}

/**
  Build multiple equalities for a WHERE condition and all join conditions that
  inherit these multiple equalities.

    The function first applies the build_equal_items_for_cond function
    to build all multiple equalities for condition cond utilizing equalities
    referred through the parameter inherited. The extended set of
    equalities is returned in the structure referred by the cond_equal_ref
    parameter. After this the function calls itself recursively for
    all join conditions whose direct references can be found in join_list
    and who inherit directly the multiple equalities just having built.

  @note
    The join condition used in an outer join operation inherits all equalities
    from the join condition of the embedding join, if there is any, or
    otherwise - from the where condition.
    This fact is not obvious, but presumably can be proved.
    Consider the following query:
    @code
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t2.a=t4.a
        WHERE t1.a=t2.a;
    @endcode
    If the join condition in the query inherits =(t1.a,t2.a), then we
    can build the multiple equality =(t1.a,t2.a,t3.a,t4.a) that infers
    the equality t3.a=t4.a. Although the join condition
    t1.a=t3.a AND t2.a=t4.a AND t3.a=t4.a is not equivalent to the one
    in the query the latter can be replaced by the former: the new query
    will return the same result set as the original one.

    Interesting that multiple equality =(t1.a,t2.a,t3.a,t4.a) allows us
    to use t1.a=t3.a AND t3.a=t4.a under the join condition:
    @code
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a
        WHERE t1.a=t2.a
    @endcode
    This query equivalent to:
    @code
      SELECT * FROM (t1 LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a),t2
        WHERE t1.a=t2.a
    @endcode
    Similarly the original query can be rewritten to the query:
    @code
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t2.a=t4.a AND t3.a=t4.a
        WHERE t1.a=t2.a
    @endcode
    that is equivalent to:
    @code
      SELECT * FROM (t2 LEFT JOIN (t3,t4)ON t2.a=t4.a AND t3.a=t4.a), t1
        WHERE t1.a=t2.a
    @endcode
    Thus, applying equalities from the where condition we basically
    can get more freedom in performing join operations.
    Although we don't use this property now, it probably makes sense to use
    it in the future.

  @param thd		     Thread handler
  @param cond                condition to build the multiple equalities for
  @param[out] retcond        Returned condition
  @param inherited           path to all inherited multiple equality items
  @param do_inherit          whether or not to inherit equalities from other
                             parts of the condition
  @param join_list           list of join tables that the condition refers to
  @param[out] cond_equal_ref pointer to the structure to place built
                             equalities in

  @returns false if success, true if error
*/

bool build_equal_items(THD *thd, Item *cond, Item **retcond,
                       COND_EQUAL *inherited, bool do_inherit,
                       mem_root_deque<Table_ref *> *join_list,
                       COND_EQUAL **cond_equal_ref) {
  COND_EQUAL *cond_equal = nullptr;

  if (cond) {
    if (build_equal_items_for_cond(thd, cond, &cond, inherited, do_inherit))
      return true;
    cond->update_used_tables();
    // update_used_tables() returns void but can still fail.
    if (thd->is_error()) return true;

    const enum Item::Type cond_type = cond->type();
    if (cond_type == Item::COND_ITEM &&
        down_cast<Item_cond *>(cond)->functype() == Item_func::COND_AND_FUNC)
      cond_equal = &down_cast<Item_cond_and *>(cond)->cond_equal;
    else if (cond_type == Item::FUNC_ITEM &&
             down_cast<Item_func *>(cond)->functype() ==
                 Item_func::MULT_EQUAL_FUNC) {
      cond_equal = new (thd->mem_root) COND_EQUAL;
      if (cond_equal == nullptr) return true;
      cond_equal->current_level.push_back(down_cast<Item_equal *>(cond));
    }
  }
  if (cond_equal) {
    cond_equal->upper_levels = inherited;
    inherited = cond_equal;
  }
  *cond_equal_ref = cond_equal;

  if (join_list) {
    for (Table_ref *table : *join_list) {
      if (table->join_cond_optim()) {
        mem_root_deque<Table_ref *> *nested_join_list =
            table->nested_join ? &table->nested_join->m_tables : nullptr;
        Item *join_cond;
        if (build_equal_items(thd, table->join_cond_optim(), &join_cond,
                              inherited, do_inherit, nested_join_list,
                              &table->cond_equal))
          return true;
        table->set_join_cond_optim(join_cond);
      }
    }
  }

  *retcond = cond;
  return false;
}

/**
  Compare field items by table order in the execution plan.

    field1 considered as better than field2 if the table containing
    field1 is accessed earlier than the table containing field2.
    The function finds out what of two fields is better according
    this criteria.

  @param field1          first field item to compare
  @param field2          second field item to compare
  @param table_join_idx  index to tables determining table order

  @retval
   -1  if field1 is better than field2
  @retval
    1  if field2 is better than field1
  @retval
    0  otherwise
*/

static int compare_fields_by_table_order(Item_field *field1, Item_field *field2,
                                         JOIN_TAB **table_join_idx) {
  int cmp = 0;
  bool outer_ref = false;
  if (field1->is_outer_reference()) {
    outer_ref = true;
    cmp = -1;
  }
  if (field2->is_outer_reference()) {
    outer_ref = true;
    cmp++;
  }
  if (outer_ref) return cmp;

  /*
    table_join_idx is NULL if this function was not called from JOIN::optimize()
    but from e.g. mysql_delete() or mysql_update(). In these cases
    there is only one table and both fields belong to it. Example
    condition where this is the case: t1.fld1=t1.fld2
  */
  if (!table_join_idx) return 0;

  // Locate JOIN_TABs thanks to table_join_idx, then compare their index.
  cmp = table_join_idx[field1->table_ref->tableno()]->idx() -
        table_join_idx[field2->table_ref->tableno()]->idx();
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
}

/**
  Generate minimal set of simple equalities equivalent to a multiple equality.

    The function retrieves the fields of the multiple equality item
    item_equal and  for each field f:
    - if item_equal contains const it generates the equality f=const_item;
    - otherwise, if f is not the first field, generates the equality
      f=item_equal->get_first().
    All generated equality are added to the cond conjunction.

  @param thd             the session context
  @param cond            condition to add the generated equality to
  @param upper_levels    structure to access multiple equality of upper levels
  @param item_equal      multiple equality to generate simple equality from

  @note
    Before generating an equality function checks that it has not
    been generated for multiple equalities of the upper levels.
    E.g. for the following where condition
    WHERE a=5 AND ((a=b AND b=c) OR  c>4)
    the upper level AND condition will contain =(5,a),
    while the lower level AND condition will contain =(5,a,b,c).
    When splitting =(5,a,b,c) into a separate equality predicates
    we should omit 5=a, as we have it already in the upper level.
    The following where condition gives us a more complicated case:
    WHERE t1.a=t2.b AND t3.c=t4.d AND (t2.b=t3.c OR t4.e>5 ...) AND ...
    Given the tables are accessed in the order t1->t2->t3->t4 for
    the selected query execution plan the lower level multiple
    equality =(t1.a,t2.b,t3.c,t4.d) formally  should be converted to
    t1.a=t2.b AND t1.a=t3.c AND t1.a=t4.d. But t1.a=t2.a will be
    generated for the upper level. Also t3.c=t4.d will be generated there.
    So only t1.a=t3.c should be left in the lower level.
    If cond is equal to 0, then not more then one equality is generated
    and a pointer to it is returned as the result of the function.

  @return
    - The condition with generated simple equalities or
    a pointer to the simple generated equality, if success.
    - 0, otherwise.
*/

static Item *eliminate_item_equal(THD *thd, Item *cond,
                                  COND_EQUAL *upper_levels,
                                  Item_equal *item_equal) {
  List<Item> eq_list;
  Item *eq_item = nullptr;
  if (item_equal->const_item() && !item_equal->val_int())
    return new Item_func_false();
  Item *const item_const = item_equal->const_arg();
  auto it = item_equal->get_fields().begin();
  if (!item_const) {
    /*
      If there is a const item, match all field items with the const item,
      otherwise match the second and subsequent field items with the first one:
    */
    it++;
  }
  while (it != item_equal->get_fields().end()) {
    /*
      Generate an equality of the form:
      item_field = some previous field in item_equal's list.

      First see if we really need to generate it:
    */
    Item_field *item_field = &*it++;  // Field to generate equality for.
    Item_equal *const upper = item_field->find_item_equal(upper_levels);
    if (upper)  // item_field is in this upper equality
    {
      if (item_const && upper->const_arg())
        continue;  // Const at both levels, no need to generate at current level
      /*
        If the upper-level multiple equality contains this item, there is no
        need to generate the equality, unless item_field belongs to a
        semi-join nest that is used for Materialization, and refers to tables
        that are outside of the materialized semi-join nest,
        As noted in Item_equal::get_subst_item(), subquery materialization
        does not have this problem.
      */
      JOIN_TAB *const tab = item_field->field->table->reginfo.join_tab;

      if (!(tab && sj_is_materialize_strategy(tab->get_sj_strategy()))) {
        Item_field *item_match;
        auto li = item_equal->get_fields().begin();
        while ((item_match = &*li++) != item_field) {
          if (item_match->find_item_equal(upper_levels) == upper)
            break;  // (item_match, item_field) is also in upper level equality
        }
        if (item_match != item_field) continue;
      }
    }  // ... if (upper).

    /*
      item_field should be compared with the head of the multiple equality
      list.
      item_field may refer to a table that is within a semijoin materialization
      nest. In that case, the order of the join_tab entries may look like:

        ot1 ot2 <subquery> ot5 SJM(it3 it4)

      If we have a multiple equality

        (ot1.c1, ot2.c2, <subquery>.c it3.c3, it4.c4, ot5.c5),

      we should generate the following equalities:
        1. ot1.c1 = ot2.c2
        2. ot1.c1 = <subquery>.c
        3. it3.c3 = it4.c4
        4. ot1.c1 = ot5.c5

      Equalities 1) and 4) are regular equalities between two outer tables.
      Equality 2) is an equality that matches the outer query with a
      materialized temporary table. It is either performed as a lookup
      into the materialized table (SJM-lookup), or as a condition on the
      outer table (SJM-scan).
      Equality 3) is evaluated during semijoin materialization.

      If there is a const item, match against this one.
      Otherwise, match against the first field item in the multiple equality,
      unless the item is within a materialized semijoin nest, in case it will
      be matched against the first item within the SJM nest.
      @see JOIN::set_prefix_tables()
      @see Item_equal::get_subst_item()
    */

    Item *const head =
        item_const ? item_const : item_equal->get_subst_item(item_field);
    if (head == item_field) continue;

    // we have a pair, can generate 'item_field=head'
    if (eq_item) eq_list.push_back(eq_item);

    if (head->type() == Item::FIELD_ITEM) {
      // Store away all fields that were considered equal, so that we are able
      // to undo this operation later if we have to. See
      // Item_func::ensure_multi_equality_fields_are_available for more details.
      Item_field *head_field = down_cast<Item_field *>(head);
      head_field->set_item_equal_all_join_nests(item_equal);
    }
    eq_item = new Item_func_eq(item_field, head);

    if (!eq_item || down_cast<Item_func_eq *>(eq_item)->set_cmp_func())
      return nullptr;

    eq_item->quick_fix_field();
    if (item_const != nullptr) {
      eq_item->apply_is_true();
      Item::cond_result res;
      if (fold_condition(thd, eq_item, &eq_item, &res)) return nullptr;
      if (res == Item::COND_FALSE) {
        eq_item = new (thd->mem_root) Item_func_false();
        if (eq_item == nullptr) return nullptr;
        return eq_item;  // entire AND is false
      } else if (res == Item::COND_TRUE) {
        eq_item = new (thd->mem_root) Item_func_true();
        if (eq_item == nullptr) return nullptr;
      }
    }
  }  // ... while ((item_field= it++))

  if (!cond && !eq_list.head()) {
    if (!eq_item) return new Item_func_true();
    return eq_item;
  }

  if (eq_item) eq_list.push_back(eq_item);
  if (!cond)
    cond = new Item_cond_and(eq_list);
  else {
    assert(cond->type() == Item::COND_ITEM);
    if (eq_list.elements) ((Item_cond *)cond)->add_at_head(&eq_list);
  }

  cond->quick_fix_field();
  cond->update_used_tables();

  return cond;
}

/**
  Substitute every field reference in a condition by the best equal field
  and eliminate all multiple equality predicates.

    The function retrieves the cond condition and for each encountered
    multiple equality predicate it sorts the field references in it
    according to the order of tables specified by the table_join_idx
    parameter. Then it eliminates the multiple equality predicate by
    replacing it with the conjunction of simple equality predicates
    equating every field from the multiple equality to the first
    field in it, or to the constant, if there is any.
    After this, the function retrieves all other conjuncted
    predicates and substitutes every field reference by the field reference
    to the first equal field or equal constant if there are any.

  @param thd             the session context
  @param cond            condition to process
  @param cond_equal      multiple equalities to take into consideration
  @param table_join_idx  index to tables determining field preference

  @note
    At the first glance, a full sort of fields in multiple equality
    seems to be an overkill. Yet it's not the case due to possible
    new fields in multiple equality item of lower levels. We want
    the order in them to comply with the order of upper levels.

  @return
    The transformed condition, or NULL in case of error
*/

Item *substitute_for_best_equal_field(THD *thd, Item *cond,
                                      COND_EQUAL *cond_equal,
                                      JOIN_TAB **table_join_idx) {
  assert(cond->is_bool_func());
  if (cond->type() == Item::COND_ITEM) {
    List<Item> *cond_list = ((Item_cond *)cond)->argument_list();

    bool and_level =
        ((Item_cond *)cond)->functype() == Item_func::COND_AND_FUNC;
    if (and_level) {
      cond_equal = &((Item_cond_and *)cond)->cond_equal;
      cond_list->disjoin((List<Item> *)&cond_equal->current_level);

      List_iterator_fast<Item_equal> it(cond_equal->current_level);
      auto cmp = [table_join_idx](Item_field *f1, Item_field *f2) {
        return compare_fields_by_table_order(f1, f2, table_join_idx);
      };
      Item_equal *item_equal;
      while ((item_equal = it++)) {
        item_equal->sort(cmp);
      }
    }

    List_iterator<Item> li(*cond_list);
    Item *item;
    while ((item = li++)) {
      Item *new_item = substitute_for_best_equal_field(thd, item, cond_equal,
                                                       table_join_idx);
      if (new_item == nullptr) return nullptr;
      /*
        This works OK with PS/SP re-execution as changes are made to
        the arguments of AND/OR items only
      */
      if (new_item != item) li.replace(new_item);
    }

    if (and_level) {
      List_iterator_fast<Item_equal> it(cond_equal->current_level);
      Item_equal *item_equal;
      while ((item_equal = it++)) {
        cond = eliminate_item_equal(thd, cond, cond_equal->upper_levels,
                                    item_equal);
        if (cond == nullptr) return nullptr;
        // This occurs when eliminate_item_equal() founds that cond is
        // always false and substitutes it with a false value.
        // Due to this, value of item_equal will be 0, so just return it.
        if (cond->type() != Item::COND_ITEM) break;
      }
    }
    if (cond->type() == Item::COND_ITEM &&
        !((Item_cond *)cond)->argument_list()->elements)
      cond = cond->val_bool() ? implicit_cast<Item *>(new Item_func_true())
                              : implicit_cast<Item *>(new Item_func_false());
  } else if (cond->type() == Item::FUNC_ITEM &&
             (down_cast<Item_func *>(cond))->functype() ==
                 Item_func::MULT_EQUAL_FUNC) {
    Item_equal *item_equal = down_cast<Item_equal *>(cond);
    item_equal->sort([table_join_idx](Item_field *f1, Item_field *f2) {
      return compare_fields_by_table_order(f1, f2, table_join_idx);
    });
    if (cond_equal && cond_equal->current_level.head() == item_equal)
      cond_equal = cond_equal->upper_levels;
    return eliminate_item_equal(thd, nullptr, cond_equal, item_equal);
  } else {
    uchar *dummy = nullptr;
    if (cond->compile(&Item::visit_all_analyzer, &dummy,
                      &Item::replace_equal_field, nullptr) == nullptr)
      return nullptr;
  }
  return cond;
}

/**
  change field = field to field = const for each found field = const in the
  and_level

  @param thd      Thread handler
  @param save_list  saved list of COND_CMP
  @param and_father father of AND op
  @param cond       Condition where fields are replaced with constant values
  @param field      The field that will be substituted
  @param value      The substitution value

  @returns false if success, true if error
*/

static bool change_cond_ref_to_const(THD *thd, I_List<COND_CMP> *save_list,
                                     Item *and_father, Item *cond, Item *field,
                                     Item *value) {
  assert(cond->real_item()->is_bool_func());
  if (cond->type() == Item::COND_ITEM) {
    Item_cond *const item_cond = down_cast<Item_cond *>(cond);
    bool and_level = item_cond->functype() == Item_func::COND_AND_FUNC;
    List_iterator<Item> li(*item_cond->argument_list());
    Item *item;
    while ((item = li++)) {
      if (change_cond_ref_to_const(thd, save_list, and_level ? cond : item,
                                   item, field, value))
        return true;
    }
    return false;
  }
  if (cond->eq_cmp_result() == Item::COND_OK)
    return false;  // Not a boolean function

  Item_bool_func2 *func = down_cast<Item_bool_func2 *>(cond);
  Item **args = func->arguments();
  Item *left_item = args[0];
  Item *right_item = args[1];
  Item_func::Functype functype = func->functype();

  if (right_item->eq(field, false) && left_item != value &&
      right_item->cmp_context == field->cmp_context &&
      (left_item->result_type() != STRING_RESULT ||
       value->result_type() != STRING_RESULT ||
       left_item->collation.collation == value->collation.collation)) {
    Item *const clone = value->clone_item();
    if (thd->is_error()) return true;

    if (clone == nullptr) return false;

    clone->collation.set(right_item->collation);
    thd->change_item_tree(args + 1, clone);
    func->update_used_tables();
    if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
        and_father != cond && !left_item->const_item()) {
      cond->marker = Item::MARKER_CONST_PROPAG;
      COND_CMP *const cond_cmp = new COND_CMP(and_father, func);
      if (cond_cmp == nullptr) return true;

      save_list->push_back(cond_cmp);
    }
    if (func->set_cmp_func()) return true;
  } else if (left_item->eq(field, false) && right_item != value &&
             left_item->cmp_context == field->cmp_context &&
             (right_item->result_type() != STRING_RESULT ||
              value->result_type() != STRING_RESULT ||
              right_item->collation.collation == value->collation.collation)) {
    Item *const clone = value->clone_item();
    if (thd->is_error()) return true;

    if (clone == nullptr) return false;

    clone->collation.set(left_item->collation);
    thd->change_item_tree(args, clone);
    value = clone;
    func->update_used_tables();
    if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
        and_father != cond && !right_item->const_item()) {
      args[0] = args[1];  // For easy check
      thd->change_item_tree(args + 1, value);
      cond->marker = Item::MARKER_CONST_PROPAG;
      COND_CMP *const cond_cmp = new COND_CMP(and_father, func);
      if (cond_cmp == nullptr) return true;

      save_list->push_back(cond_cmp);
    }
    if (func->set_cmp_func()) return true;
  }
  return false;
}

/**
  Propagate constant values in a condition

  @param thd        Thread handler
  @param save_list  saved list of COND_CMP
  @param and_father father of AND op
  @param cond       Condition for which constant values are propagated

  @returns false if success, true if error
*/
static bool propagate_cond_constants(THD *thd, I_List<COND_CMP> *save_list,
                                     Item *and_father, Item *cond) {
  assert(cond->real_item()->is_bool_func());
  if (cond->type() == Item::COND_ITEM) {
    Item_cond *const item_cond = down_cast<Item_cond *>(cond);
    bool and_level = item_cond->functype() == Item_func::COND_AND_FUNC;
    List_iterator_fast<Item> li(*item_cond->argument_list());
    Item *item;
    I_List<COND_CMP> save;
    while ((item = li++)) {
      if (propagate_cond_constants(thd, &save, and_level ? cond : item, item))
        return true;
    }
    if (and_level) {  // Handle other found items
      I_List_iterator<COND_CMP> cond_itr(save);
      COND_CMP *cond_cmp;
      while ((cond_cmp = cond_itr++)) {
        Item **args = cond_cmp->cmp_func->arguments();
        if (!args[0]->const_item() &&
            change_cond_ref_to_const(thd, &save, cond_cmp->and_level,
                                     cond_cmp->and_level, args[0], args[1]))
          return true;
      }
    }
  } else if (and_father != cond &&
             cond->marker != Item::MARKER_CONST_PROPAG)  // In a AND group
  {
    Item_func *func;
    if (cond->type() == Item::FUNC_ITEM &&
        (func = down_cast<Item_func *>(cond)) &&
        (func->functype() == Item_func::EQ_FUNC ||
         func->functype() == Item_func::EQUAL_FUNC)) {
      Item **args = func->arguments();
      bool left_const = args[0]->const_item();
      bool right_const = args[1]->const_item();
      if (!(left_const && right_const) &&
          args[0]->result_type() == args[1]->result_type()) {
        if (right_const) {
          Item *item = args[1];
          if (resolve_const_item(thd, &item, args[0])) return true;
          thd->change_item_tree(&args[1], item);
          func->update_used_tables();
          if (change_cond_ref_to_const(thd, save_list, and_father, and_father,
                                       args[0], args[1]))
            return true;
        } else if (left_const) {
          Item *item = args[0];
          if (resolve_const_item(thd, &item, args[1])) return true;
          thd->change_item_tree(&args[0], item);
          func->update_used_tables();
          if (change_cond_ref_to_const(thd, save_list, and_father, and_father,
                                       args[1], args[0]))
            return true;
        }
      }
    }
  }

  return false;
}

/**
  Assign each nested join structure a bit in nested_join_map.

  @param join_list     List of tables
  @param first_unused  Number of first unused bit in nested_join_map before the
                       call

  @note
    This function is called after simplify_joins(), when there are no
    redundant nested joins.
    We cannot have more nested joins in a query block than there are tables,
    so as long as the number of bits in nested_join_map is not less than the
    maximum number of tables in a query block, nested_join_map can never
    overflow.

  @return
    First unused bit in nested_join_map after the call.
*/

uint build_bitmap_for_nested_joins(mem_root_deque<Table_ref *> *join_list,
                                   uint first_unused) {
  DBUG_TRACE;
  for (Table_ref *table : *join_list) {
    NESTED_JOIN *nested_join;
    if ((nested_join = table->nested_join)) {
      // We should have a join condition or a semi-join condition or both
      assert((table->join_cond() != nullptr) || table->is_sj_nest());

      nested_join->nj_map = 0;
      nested_join->nj_total = 0;
      /*
        We only record nested join information for outer join nests.
        Tables belonging in semi-join nests are recorded in the
        embedding outer join nest, if one exists.
      */
      if (table->join_cond()) {
        assert(first_unused < sizeof(nested_join_map) * 8);
        nested_join->nj_map = (nested_join_map)1 << first_unused++;
        nested_join->nj_total = nested_join->m_tables.size();
      } else if (table->is_sj_nest()) {
        NESTED_JOIN *const outer_nest =
            table->embedding ? table->embedding->nested_join : nullptr;
        /*
          The semi-join nest has already been counted into the table count
          for the outer join nest as one table, so subtract 1 from the
          table count.
        */
        if (outer_nest)
          outer_nest->nj_total += (nested_join->m_tables.size() - 1);
      } else
        assert(false);

      first_unused =
          build_bitmap_for_nested_joins(&nested_join->m_tables, first_unused);
    }
  }
  return first_unused;
}

/** Update the dependency map for the tables. */

void JOIN::update_depend_map() {
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  for (uint tableno = 0; tableno < tables; tableno++) {
    JOIN_TAB *const tab = best_ref[tableno];
    Index_lookup *const ref = &tab->ref();
    table_map depend_map = 0;
    Item **item = ref->items;
    for (uint i = 0; i < ref->key_parts; i++, item++)
      depend_map |= (*item)->used_tables();
    depend_map &= ~PSEUDO_TABLE_BITS;
    ref->depend_map = depend_map;
    for (JOIN_TAB **tab2 = map2table; depend_map; tab2++, depend_map >>= 1) {
      if (depend_map & 1) ref->depend_map |= (*tab2)->ref().depend_map;
    }
  }
}

/** Update the dependency map for the sort order. */

void JOIN::update_depend_map(ORDER *order) {
  DBUG_TRACE;
  for (; order; order = order->next) {
    table_map depend_map;
    order->item[0]->update_used_tables();
    order->depend_map = depend_map =
        order->item[0]->used_tables() & ~INNER_TABLE_BIT;
    order->used = 0;
    // Not item_sum(), RAND() and no reference to table outside of sub select
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT)) &&
        !order->item[0]->has_aggregation()) {
      for (JOIN_TAB **tab = map2table; depend_map; tab++, depend_map >>= 1) {
        if (depend_map & 1) order->depend_map |= (*tab)->ref().depend_map;
      }
    }
  }
}

/**
  Update equalities and keyuse references after semi-join materialization
  strategy is chosen.

  @details
    For each multiple equality that contains a field that is selected
    from a subquery, and that subquery is executed using a semi-join
    materialization strategy, add the corresponding column in the materialized
    temporary table to the equality.
    For each injected semi-join equality that is not converted to
    multiple equality, replace the reference to the expression selected
    from the subquery with the corresponding column in the temporary table.

    This is needed to properly reflect the equalities that involve injected
    semi-join equalities when materialization strategy is chosen.
    @see eliminate_item_equal() for how these equalities are used to generate
    correct equality predicates.

    The MaterializeScan semi-join strategy requires some additional processing:
    All primary tables after the materialized temporary table must be inspected
    for keyuse objects that point to expressions from the subquery tables.
    These references must be replaced with references to corresponding columns
    in the materialized temporary table instead. Those primary tables using
    ref access will thus be made to depend on the materialized temporary table
    instead of the subquery tables.

    Only the injected semi-join equalities need this treatment, other predicates
    will be handled correctly by the regular item substitution process.

  @return False if success, true if error
*/

bool JOIN::update_equalities_for_sjm() {
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  List_iterator<Semijoin_mat_exec> sj_it(sjm_exec_list);
  Semijoin_mat_exec *sjm_exec;
  while ((sjm_exec = sj_it++)) {
    Table_ref *const sj_nest = sjm_exec->sj_nest;

    Item *cond;
    /*
      Conditions involving SJ-inner tables are only to be found in the closest
      nest's condition, which may be an AJ nest, a LEFT JOIN nest, or the
      WHERE clause.
    */
    if (sj_nest->is_aj_nest())
      cond = sj_nest->join_cond_optim();
    else if (sj_nest->outer_join_nest())
      cond = sj_nest->outer_join_nest()->join_cond_optim();
    else
      cond = where_cond;
    if (!cond) continue;

    uchar *dummy = nullptr;
    cond = cond->compile(&Item::equality_substitution_analyzer, &dummy,
                         &Item::equality_substitution_transformer,
                         (uchar *)sj_nest);
    if (cond == nullptr) return true;

    cond->update_used_tables();

    // Loop over all primary tables that follow the materialized table
    for (uint j = sjm_exec->mat_table_index + 1; j < primary_tables; j++) {
      JOIN_TAB *const tab = best_ref[j];
      for (Key_use *keyuse = tab->position()->key;
           keyuse && keyuse->table_ref == tab->table_ref &&
           keyuse->key == tab->position()->key->key;
           keyuse++) {
        uint fieldno = 0;
        for (Item *old : sj_nest->nested_join->sj_inner_exprs) {
          if (old->real_item()->eq(keyuse->val->real_item(), false)) {
            /*
              Replace the expression selected from the subquery with the
              corresponding column of the materialized temporary table.
            */
            keyuse->val = sj_nest->nested_join->sjm.mat_fields[fieldno];
            keyuse->used_tables = keyuse->val->used_tables();
            break;
          }
          fieldno++;
        }
      }
    }
  }

  return false;
}

/**
  Assign set of available (prefix) tables to all tables in query block.
  Also set added tables, ie the tables added in each JOIN_TAB compared to the
  previous JOIN_TAB.
  This function must be called for every query block after the table order
  has been determined.
*/

void JOIN::set_prefix_tables() {
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);
  assert(!plan_is_const());
  /*
    The const tables are available together with the first non-const table in
    the join order.
  */
  table_map const initial_tables_map =
      const_table_map | (allow_outer_refs ? OUTER_REF_TABLE_BIT : 0);

  table_map current_tables_map = initial_tables_map;
  table_map prev_tables_map = (table_map)0;
  table_map saved_tables_map = (table_map)0;

  JOIN_TAB *last_non_sjm_tab = nullptr;  // Track the last non-sjm table

  for (uint i = const_tables; i < tables; i++) {
    JOIN_TAB *const tab = best_ref[i];
    if (!tab->table()) continue;
    /*
      Tables that are within SJ-Materialization nests cannot have their
      conditions referring to preceding non-const tables.
       - If we're looking at the first SJM table, reset current_tables_map
         to refer to only allowed tables
      @see Item_equal::get_subst_item()
      @see eliminate_item_equal()
    */
    if (sj_is_materialize_strategy(tab->get_sj_strategy())) {
      const table_map sjm_inner_tables = tab->emb_sj_nest->sj_inner_tables;
      if (!(sjm_inner_tables & current_tables_map)) {
        saved_tables_map = current_tables_map;
        current_tables_map = initial_tables_map;
        prev_tables_map = (table_map)0;
      }

      current_tables_map |= tab->table_ref->map();
      tab->set_prefix_tables(current_tables_map, prev_tables_map);
      prev_tables_map = current_tables_map;

      if (!(sjm_inner_tables & ~current_tables_map)) {
        /*
          At the end of a semi-join materialization nest,
          add non-deterministic expressions to the last table of the nest:
        */
        tab->add_prefix_tables(RAND_TABLE_BIT);

        // Restore the previous map:
        current_tables_map = saved_tables_map;
        prev_tables_map =
            last_non_sjm_tab ? last_non_sjm_tab->prefix_tables() : (table_map)0;
      }
    } else {
      last_non_sjm_tab = tab;
      current_tables_map |= tab->table_ref->map();
      tab->set_prefix_tables(current_tables_map, prev_tables_map);
      prev_tables_map = current_tables_map;
    }
  }
  /*
    Non-deterministic expressions must be added to the last table's condition.
    It solves problem with queries like SELECT * FROM t1 WHERE rand() > 0.5
  */
  if (last_non_sjm_tab != nullptr)
    last_non_sjm_tab->add_prefix_tables(RAND_TABLE_BIT);
}

/**
  Calculate best possible join order and initialize the join structure.

  @return true if success, false if error.

  The JOIN object is populated with statistics about the query,
  and a plan with table order and access method selection is made.

  The list of tables to be optimized is taken from query_block->leaf_tables.
  JOIN::where_cond is also used in the optimization.
  As a side-effect, JOIN::keyuse_array is populated with key_use information.

  Here is an overview of the logic of this function:

  - Initialize JOIN data structures and setup basic dependencies between tables.

  - Update dependencies based on join information.

  - Make key descriptions (update_ref_and_keys()).

  - Pull out semi-join tables based on table dependencies.

  - Extract tables with zero or one rows as const tables.

  - Read contents of const tables, substitute columns from these tables with
    actual data. Also keep track of empty tables vs. one-row tables.

  - After const table extraction based on row count, more tables may
    have become functionally dependent. Extract these as const tables.

  - Add new sargable predicates based on retrieved const values.

  - Calculate number of rows to be retrieved from each table.

  - Calculate cost of potential semi-join materializations.

  - Calculate best possible join order based on available statistics.

  - Fill in remaining information for the generated join order.
*/

bool JOIN::make_join_plan() {
  DBUG_TRACE;

  SARGABLE_PARAM *sargables = nullptr;

  Opt_trace_context *const trace = &thd->opt_trace;

  if (init_planner_arrays())  // Create and initialize the arrays
    return true;

  // Outer join dependencies were initialized above, now complete the analysis.
  if (query_block->outer_join || query_block->is_recursive()) {
    if (propagate_dependencies()) {
      /*
        Catch illegal join order.
        SQL2011 forbids:
        WITH RECURSIVE rec AS (
        ... UNION ALL SELECT ... FROM tbl LEFT JOIN rec ON...)c...
        MySQL also forbids the same query with STRAIGHT_JOIN instead of LEFT
        JOIN, because the algorithm of with-recursive imposes that "rec" be
        first in plan, i.e. "tbl" depends on "rec", but STRAIGHT_JOIN imposes
        the opposite dependency.
      */
      assert(query_block->is_recursive());
      my_error(ER_CTE_RECURSIVE_FORBIDDEN_JOIN_ORDER, MYF(0),
               query_block->recursive_reference->alias);
      return true;
    }
    init_key_dependencies();
  }

  if (unlikely(trace->is_started()))
    trace_table_dependencies(trace, join_tab, primary_tables);

  // Build the key access information, which is the basis for ref access.
  if (where_cond || query_block->outer_join) {
    if (update_ref_and_keys(thd, &keyuse_array, join_tab, tables, where_cond,
                            ~query_block->outer_join, query_block, &sargables))
      return true;
  }

  /*
    Pull out semi-join tables based on dependencies. Dependencies are valid
    throughout the lifetime of a query, so this operation can be performed
    on the first optimization only.
  */
  if (!query_block->sj_pullout_done && !query_block->sj_nests.empty() &&
      pull_out_semijoin_tables(this))
    return true;

  query_block->sj_pullout_done = true;
  const uint sj_nests = query_block->sj_nests.size();  // Changed by pull-out

  if (!(query_block->active_options() & OPTION_NO_CONST_TABLES)) {
    // Detect tables that are const (0 or 1 row) and read their contents.
    if (extract_const_tables()) return true;

    // Detect tables that are functionally dependent on const values.
    if (extract_func_dependent_tables()) return true;
  }
  // Possibly able to create more sargable predicates from const rows.
  if (const_tables && sargables) update_sargable_from_const(sargables);

  // Make a first estimate of the fanout for each table in the query block.
  if (estimate_rowcount()) return true;

  /*
    Apply join order hints, with the exception of
    JOIN_FIXED_ORDER and STRAIGHT_JOIN.
  */
  if (query_block->opt_hints_qb &&
      !(query_block->active_options() & SELECT_STRAIGHT_JOIN))
    query_block->opt_hints_qb->apply_join_order_hints(this);

  if (sj_nests) {
    set_semijoin_embedding();
    query_block->update_semijoin_strategies(thd);
  }

  if (!plan_is_const()) optimize_keyuse();

  allow_outer_refs = true;

  if (sj_nests && optimize_semijoin_nests_for_materialization(this))
    return true;

  // Choose the table order based on analysis done so far.
  if (Optimize_table_order(thd, this, nullptr).choose_table_order())
    return true;

  DBUG_EXECUTE_IF("bug13820776_1", thd->killed = THD::KILL_QUERY;);
  if (thd->killed || thd->is_error()) return true;

  // If this is a subquery, decide between In-to-exists and materialization
  if (query_expression()->item && decide_subquery_strategy()) return true;

  refine_best_rowcount();

  positions = nullptr;  // But keep best_positions for get_best_combination

  // Generate an execution plan from the found optimal join order.
  if (get_best_combination()) return true;

  // Cleanup after update_ref_and_keys has added keys for derived tables.
  if (query_block->materialized_derived_table_count) finalize_derived_keys();

  // No need for this struct after new JOIN_TAB array is set up.
  best_positions = nullptr;

  // Some called function may still set error status unnoticed
  if (thd->is_error()) return true;

  // There is at least one empty const table
  if (const_table_map != found_const_table_map)
    zero_result_cause = "no matching row in const table";

  return false;
}

/**
  Initialize scratch arrays for the join order optimization

  @returns false if success, true if error

  @note If something fails during initialization, JOIN::cleanup()
        will free anything that has been partially allocated and set up.
        Arrays are created in the execution mem_root, so they will be
        deleted automatically when the mem_root is re-initialized.
*/

bool JOIN::init_planner_arrays() {
  // Up to one extra slot per semi-join nest is needed (if materialized)
  const uint sj_nests = query_block->sj_nests.size();
  const uint table_count = query_block->leaf_table_count;

  assert(primary_tables == 0 && tables == 0);

  if (!(join_tab = alloc_jtab_array(thd, table_count))) return true;

  /*
    We add 2 cells:
    - because planning stage uses 0-termination so needs +1
    - because after get_best_combination, we don't use 0-termination but
    need +2, to host at most 2 tmp sort/group/distinct tables.
  */
  if (!(best_ref = (JOIN_TAB **)thd->alloc(
            sizeof(JOIN_TAB *) *
            (table_count + sj_nests + 2 + m_windows.elements))))
    return true;

  // sort/group tmp tables have no map
  if (!(map2table = (JOIN_TAB **)thd->alloc(sizeof(JOIN_TAB *) *
                                            (table_count + sj_nests))))
    return true;

  if (!(positions = new (thd->mem_root) POSITION[table_count])) return true;

  if (!(best_positions = new (thd->mem_root) POSITION[table_count + sj_nests]))
    return true;

  /*
    Initialize data structures for tables to be joined.
    Initialize dependencies between tables.
  */
  JOIN_TAB **best_ref_p = best_ref;
  Table_ref *tl = query_block->leaf_tables;

  for (JOIN_TAB *tab = join_tab; tl; tab++, tl = tl->next_leaf, best_ref_p++) {
    *best_ref_p = tab;
    TABLE *const table = tl->table;
    tab->table_ref = tl;
    tab->set_table(table);
    const int err = tl->fetch_number_of_rows();
    if (err) {
      table->file->print_error(err, MYF(0));
      return true;
    }
    // Initialize the cost model for the table.
    table->init_cost_model(cost_model());

    all_table_map |= tl->map();
    tab->set_join(this);

    if (tl->is_updated() || tl->is_deleted()) {
      // As we update or delete rows, we can't read the index
      table->no_keyread = true;
    }

    tab->dependent = tl->dep_tables;  // Initialize table dependencies
    if (query_block->is_recursive()) {
      if (query_block->recursive_reference != tl)
        // Recursive reference must go first
        tab->dependent |= query_block->recursive_reference->map();
      else {
        // Recursive reference mustn't use any index
        table->covering_keys.clear_all();
        table->keys_in_use_for_group_by.clear_all();
        table->keys_in_use_for_order_by.clear_all();
      }
    }
    if (tl->schema_table) table->file->stats.records = 2;
    table->quick_condition_rows = table->file->stats.records;

    tab->init_join_cond_ref(tl);

    if (tl->outer_join_nest()) {
      // tab belongs to a nested join, maybe to several embedding joins
      tab->embedding_map = 0;
      for (Table_ref *embedding = tl->embedding; embedding;
           embedding = embedding->embedding) {
        NESTED_JOIN *const nested_join = embedding->nested_join;
        tab->embedding_map |= nested_join->nj_map;
        tab->dependent |= embedding->dep_tables;
      }
    } else if (tab->join_cond()) {
      // tab is the only inner table of an outer join
      tab->embedding_map = 0;
      for (Table_ref *embedding = tl->embedding; embedding;
           embedding = embedding->embedding)
        tab->embedding_map |= embedding->nested_join->nj_map;
    }

    if (tl->is_derived() && tl->derived_query_expression()->m_lateral_deps)
      has_lateral = true;

    tables++;  // Count number of initialized tables
  }

  primary_tables = tables;
  *best_ref_p = nullptr;  // Last element of array must be NULL

  return false;
}

/**
  Propagate dependencies between tables due to outer join relations.

  @returns false if success, true if error

  Build transitive closure for relation 'to be dependent on'.
  This will speed up the plan search for many cases with outer joins,
  as well as allow us to catch illegal cross references.
  Warshall's algorithm is used to build the transitive closure.
  As we may restart the outer loop up to 'table_count' times, the
  complexity of the algorithm is O((number of tables)^3).
  However, most of the iterations will be shortcircuited when
  there are no dependencies to propagate.
*/

bool JOIN::propagate_dependencies() {
  for (uint i = 0; i < tables; i++) {
    if (!join_tab[i].dependent) continue;

    // Add my dependencies to other tables depending on me
    uint j;
    JOIN_TAB *tab;
    for (j = 0, tab = join_tab; j < tables; j++, tab++) {
      if (tab->dependent & join_tab[i].table_ref->map()) {
        const table_map was_dependent = tab->dependent;
        tab->dependent |= join_tab[i].dependent;
        /*
          If we change dependencies for a table we already have
          processed: Redo dependency propagation from this table.
        */
        if (i > j && tab->dependent != was_dependent) {
          i = j - 1;
          break;
        }
      }
    }
  }

  JOIN_TAB *const tab_end = join_tab + tables;
  for (JOIN_TAB *tab = join_tab; tab < tab_end; tab++) {
    if ((tab->dependent & tab->table_ref->map())) return true;
  }

  return false;
}

/**
  Extract const tables based on row counts.

  @returns false if success, true if error

  This extraction must be done for each execution.
  Tables containing exactly zero or one rows are marked as const, but
  notice the additional constraints checked below.
  Tables that are extracted have their rows read before actual execution
  starts and are placed in the beginning of the join_tab array.
  Thus, they do not take part in join order optimization process,
  which can significantly reduce the optimization time.
  The data read from these tables can also be regarded as "constant"
  throughout query execution, hence the column values can be used for
  additional constant propagation and extraction of const tables based
  on eq-ref properties.

  The tables are given the type JT_SYSTEM.
*/

bool JOIN::extract_const_tables() {
  enum enum_const_table_extraction {
    extract_no_table = 0,
    extract_empty_table = 1,
    extract_const_table = 2
  };

  JOIN_TAB *const tab_end = join_tab + tables;
  for (JOIN_TAB *tab = join_tab; tab < tab_end; tab++) {
    TABLE *const table = tab->table();
    Table_ref *const tl = tab->table_ref;
    enum enum_const_table_extraction extract_method = extract_const_table;

    const bool all_partitions_pruned_away = table->all_partitions_pruned_away;

    if (tl->outer_join_nest()) {
      /*
        Table belongs to a nested join, no candidate for const table extraction.
      */
      extract_method = extract_no_table;
    } else if (tl->embedding && tl->embedding->is_sj_or_aj_nest()) {
      /*
        Table belongs to a semi-join.
        We do not currently pull out const tables from semi-join nests.
      */
      extract_method = extract_no_table;
    } else if (tab->join_cond()) {
      // tab is the only inner table of an outer join, extract empty tables
      extract_method = extract_empty_table;
    }
    switch (extract_method) {
      case extract_no_table:
        break;

      case extract_empty_table:
        // Extract tables with zero rows, but only if statistics are exact
        if ((table->file->stats.records == 0 || all_partitions_pruned_away) &&
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT))
          mark_const_table(tab, nullptr);
        break;

      case extract_const_table:
        /*
          Extract tables with zero or one rows, but do not extract tables that
           1. are dependent upon other tables, or
           2. have no exact statistics, or
           3. are full-text searched
           4. a derived table which has a stored function
        */
        const bool explain_mode = thd->lex->is_explain();
        if ((table->s->system || table->file->stats.records <= 1 ||
             all_partitions_pruned_away) &&
            !tab->dependent &&                                              // 1
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&  // 2
            !tl->is_fulltext_searched() &&                                  // 3
            !(explain_mode && tl->is_view_or_derived() &&
              tl->has_stored_program()))  // 4
          mark_const_table(tab, nullptr);
        break;
    }
  }

  // Read const tables (tables matching no more than 1 rows)
  if (!const_tables) return false;

  for (POSITION *p_pos = positions, *p_end = p_pos + const_tables;
       p_pos < p_end; p_pos++) {
    JOIN_TAB *const tab = p_pos->table;
    const int status = join_read_const_table(tab, p_pos);
    if (status > 0)
      return true;
    else if (status == 0) {
      found_const_table_map |= tab->table_ref->map();
      tab->table_ref->optimized_away = true;
    }
  }

  return false;
}

/**
  Extract const tables based on functional dependencies.

  @returns false if success, true if error

  This extraction must be done for each execution.

  Mark as const the tables that
   - are functionally dependent on constant values, or
   - are inner tables of an outer join and contain exactly zero or one rows

  Tables that are extracted have their rows read before actual execution
  starts and are placed in the beginning of the join_tab array, just as
  described for JOIN::extract_const_tables().

  The tables are given the type JT_CONST.
*/

bool JOIN::extract_func_dependent_tables() {
  // loop until no more const tables are found
  bool ref_changed;
  // Tables referenced by others; if they're const the others may be too.
  table_map found_ref;
  do {
  more_const_tables_found:
    ref_changed = false;
    found_ref = 0;

    // Loop over all tables that are not already determined to be const
    for (JOIN_TAB **pos = best_ref + const_tables; *pos; pos++) {
      JOIN_TAB *const tab = *pos;
      TABLE *const table = tab->table();
      Table_ref *const tl = tab->table_ref;
      /*
        If equi-join condition by a key is null rejecting and after a
        substitution of a const table the key value happens to be null
        then we can state that there are no matches for this equi-join.
      */
      Key_use *keyuse = tab->keyuse();
      if (keyuse && tab->join_cond() && !tab->embedding_map) {
        /*
          When performing an outer join operation if there are no matching rows
          for the single row of the outer table all the inner tables are to be
          null complemented and thus considered as constant tables.
          Here we apply this consideration to the case of outer join operations
          with a single inner table only because the case with nested tables
          would require a more thorough analysis.
          TODO. Apply single row substitution to null complemented inner tables
          for nested outer join operations.
        */
        while (keyuse->table_ref == tl) {
          if (!(keyuse->val->used_tables() & ~const_table_map) &&
              keyuse->val->is_null() && keyuse->null_rejecting &&
              (tl->embedding == nullptr ||
               !tl->embedding->is_sj_or_aj_nest())) {
            table->set_null_row();
            table->const_table = true;
            found_const_table_map |= tl->map();
            mark_const_table(tab, keyuse);
            goto more_const_tables_found;
          }
          keyuse++;
        }
      }

      if (tab->dependent)  // If dependent on some table
      {
        // All dependent tables must be const
        if (tab->dependent & ~const_table_map) {
          found_ref |= tab->dependent;
          continue;
        }
        /*
          Mark a dependent table as constant if
           1. it has exactly zero or one rows (it is a system table), and
           2. it is not within a nested outer join, and
           3. it does not have an expensive outer join condition.
              This is because we have to determine whether an outer-joined table
              has a real row or a null-extended row in the optimizer phase.
              We have no possibility to evaluate its join condition at
              execution time, when it is marked as a system table.
        */
        if (table->file->stats.records <= 1L &&                             // 1
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&  // 1
            !tl->outer_join_nest() &&                                       // 2
            !(tab->join_cond() && tab->join_cond()->is_expensive()))        // 3
        {  // system table
          mark_const_table(tab, nullptr);
          const int status =
              join_read_const_table(tab, positions + const_tables - 1);
          if (status > 0)
            return true;
          else if (status == 0)
            found_const_table_map |= tl->map();
          continue;
        }
      }

      // Check if table can be read by key or table only uses const refs

      if ((keyuse = tab->keyuse())) {
        while (keyuse->table_ref == tl) {
          Key_use *const start_keyuse = keyuse;
          const uint key = keyuse->key;
          tab->keys().set_bit(key);  // QQ: remove this ?

          table_map refs = 0;
          Key_map const_ref, eq_part;
          do {
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize) {
              if (!((~found_const_table_map) & keyuse->used_tables))
                const_ref.set_bit(keyuse->keypart);
              else
                refs |= keyuse->used_tables;
              eq_part.set_bit(keyuse->keypart);
            }
            keyuse++;
          } while (keyuse->table_ref == tl && keyuse->key == key);

          /*
            Extract const tables with proper key dependencies.
            Exclude tables that
             1. are full-text searched, or
             2. are part of nested outer join, or
             3. are part of semi-join, or
             4. have an expensive outer join condition.
             5. are blocked by handler for const table optimize.
             6. are not going to be used, typically because they are streamed
                instead of materialized
                (see Query_expression::can_materialize_directly_into_result()).
             7. key evaluated in stored program in EXPLAIN mode
          */
          if (eq_part.is_prefix(table->key_info[key].user_defined_key_parts) &&
              !tl->is_fulltext_searched() &&                              // 1
              !tl->outer_join_nest() &&                                   // 2
              !(tl->embedding && tl->embedding->is_sj_or_aj_nest()) &&    // 3
              !(tab->join_cond() && tab->join_cond()->is_expensive()) &&  // 4
              !(table->file->ha_table_flags() & HA_BLOCK_CONST_TABLE) &&  // 5
              table->is_created() &&                                      // 6
              !(thd->lex->is_explain() &&
                start_keyuse->val->has_stored_program())) {  // 7
            if (table->key_info[key].flags & HA_NOSAME) {
              if (const_ref == eq_part) {  // Found everything for ref.
                ref_changed = true;
                mark_const_table(tab, start_keyuse);
                if (create_ref_for_key(this, tab, start_keyuse,
                                       found_const_table_map))
                  return true;
                const int status =
                    join_read_const_table(tab, positions + const_tables - 1);
                if (status > 0)
                  return true;
                else if (status == 0)
                  found_const_table_map |= tl->map();
                break;
              } else
                found_ref |= refs;  // Table is const if all refs are const
            } else if (const_ref == eq_part)
              tab->const_keys.set_bit(key);
          }
        }
      }
    }
  } while
      /*
        A new const table appeared, that is referenced by others, so re-check
        others:
      */
      ((const_table_map & found_ref) && ref_changed);

  return false;
}

/**
  Update info on indexes that can be used for search lookups as
  reading const tables may has added new sargable predicates.
*/

void JOIN::update_sargable_from_const(SARGABLE_PARAM *sargables) {
  for (; sargables->field; sargables++) {
    Field *const field = sargables->field;
    JOIN_TAB *const tab = field->table->reginfo.join_tab;
    Key_map possible_keys = field->key_start;
    possible_keys.intersect(field->table->keys_in_use_for_query);
    bool is_const = true;
    for (uint j = 0; j < sargables->num_values; j++)
      is_const &= sargables->arg_value[j]->const_item();
    if (is_const) {
      tab->const_keys.merge(possible_keys);
      tab->keys().merge(possible_keys);
    }
  }
}

double find_worst_seeks(const TABLE *table, double num_rows,
                        double table_scan_cost) {
  /*
    Set a max value for the cost of seek operations we can expect
    when using key lookup. This can't be too high as otherwise we
    are likely to use table scan.
  */
  double worst_seeks =
      min(table->file->worst_seek_times(num_rows / 10), table_scan_cost * 3);
  const double min_worst_seek = table->file->worst_seek_times(2.0);
  return std::max(worst_seeks, min_worst_seek);  // Fix for small tables
}

/**
  Estimate the number of matched rows for each joined table.
  Set up range scan for tables that have proper predicates.
  Eliminate tables that have filter conditions that are always false based on
  analysis performed in resolver phase or analysis of range scan predicates.

  @returns false if success, true if error
*/

bool JOIN::estimate_rowcount() {
  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_array trace_records(trace, "rows_estimation");

  JOIN_TAB *const tab_end = join_tab + tables;
  for (JOIN_TAB *tab = join_tab; tab < tab_end; tab++) {
    Opt_trace_object trace_table(trace);
    trace_table.add_utf8_table(tab->table_ref);
    if (tab->type() == JT_SYSTEM || tab->type() == JT_CONST) {
      trace_table.add("rows", 1)
          .add("cost", 1)
          .add_alnum("table_type",
                     (tab->type() == JT_SYSTEM) ? "system" : "const")
          .add("empty", tab->table()->has_null_row());

      // Only one matching row and one block to read
      tab->set_records(tab->found_records = 1);
      tab->worst_seeks = tab->table()->file->worst_seek_times(1.0);
      tab->read_time = tab->worst_seeks;
      continue;
    }
    // Approximate number of found rows and cost to read them
    tab->set_records(tab->found_records = tab->table()->file->stats.records);
    const Cost_estimate table_scan_time = tab->table()->file->table_scan_cost();
    tab->read_time = table_scan_time.total_cost();

    tab->worst_seeks =
        find_worst_seeks(tab->table(), tab->found_records, tab->read_time);

    /*
      Add to tab->const_keys the indexes for which all group fields or
      all select distinct fields participate in one index.
      Add to tab->skip_scan_keys indexes which can be used for skip
      scan access if no aggregates are present.
    */
    add_loose_index_scan_and_skip_scan_keys(this, tab);

    // Perform range analysis if the table has keys that can be used.
    Table_ref *const tl = tab->table_ref;
    Item *condition = nullptr;
    /*
      For an inner table of an outer join, the join condition is either
      attached to the actual table, or to the embedding join nest.
      For tables that are inner-joined or semi-joined, the join condition
      is taken from the WHERE condition.
    */
    if (tl->is_inner_table_of_outer_join()) {
      for (Table_ref *t = tl; t != nullptr; t = t->embedding) {
        if (t->join_cond() != nullptr) {
          condition = t->join_cond();
          break;
        }
      }
      assert(condition != nullptr);
    } else {
      condition = where_cond;
    }
    bool always_false_cond = false, range_analysis_done = false;
    if (!tab->const_keys.is_clear_all() ||
        !tab->skip_scan_keys.is_clear_all()) {
      /*
        This call fills tab->range_scan() with the best range access method
        possible for this table, and only if it's better than table scan.
        It also fills tab->needed_reg.
      */
      ha_rows records = get_quick_record_count(thd, tab, row_limit, condition);

      if (records == 0 && thd->is_error()) return true;
      if (records == 0 && tab->table()->reginfo.impossible_range)
        always_false_cond = true;
      if (records != HA_POS_ERROR) {
        tab->found_records = records;
        tab->read_time = tab->range_scan() ? tab->range_scan()->cost : 0.0;
      }
      range_analysis_done = true;
    } else if (tab->join_cond() != nullptr && tab->join_cond()->const_item() &&
               tab->join_cond()->val_int() == 0) {
      always_false_cond = true;
    }

    /*
      Check for "always false" and mark table as "const".
      Exclude outer-joined tables unless the table is the single outer-joined
      table in the query block (this also eliminates tables inside
      outer-joined derived tables).
      Exclude semi-joined and anti-joined tables (only those tables that are
      functionally dependent can be marked "const", and subsequently pulled
      out of their semi-join nests).
    */
    if (always_false_cond &&
        (!tl->is_inner_table_of_outer_join() || tl->embedding == nullptr) &&
        (!(tl->embedding != nullptr && tl->embedding->is_sj_or_aj_nest()))) {
      /*
        Always false WHERE condition or (outer) join condition.
        In case of outer join, mark that one empty NULL row is matched.
        In case of WHERE, don't set found_const_table_map to get the
        caller to abort with a zero row result.
      */
      mark_const_table(tab, nullptr);
      tab->set_type(JT_CONST);  // Override setting made in mark_const_table()
      if (tab->join_cond() != nullptr) {
        // Generate an empty row
        trace_table.add("returning_empty_null_row", true)
            .add_alnum("cause", "always_false_outer_join_condition");
        found_const_table_map |= tl->map();
        tab->table()->set_null_row();  // All fields are NULL
      } else {
        trace_table.add("rows", 0).add_alnum("cause",
                                             "impossible_where_condition");
      }
    } else if (!range_analysis_done) {
      Opt_trace_object(trace, "table_scan")
          .add("rows", tab->found_records)
          .add("cost", tab->read_time);
    }
  }
  return false;
}

/**
  Set semi-join embedding join nest pointers.

  Set pointer to embedding semi-join nest for all semi-joined tables.
  This is the closest semi-join or anti-join nest.
  Note that this must be done for every table inside all semi-join nests,
  even for tables within outer join nests embedded in semi-join nests.
  A table can never be part of multiple semi-join nests, hence no
  ambiguities can ever occur.
  Note also that the pointer is not set for Table_ref objects that
  are outer join nests within semi-join nests.
*/

void JOIN::set_semijoin_embedding() {
  assert(!query_block->sj_nests.empty());

  JOIN_TAB *const tab_end = join_tab + primary_tables;

  for (JOIN_TAB *tab = join_tab; tab < tab_end; tab++) {
    tab->emb_sj_nest = nullptr;
    for (Table_ref *tl = tab->table_ref; tl->embedding; tl = tl->embedding) {
      if (tl->embedding->is_sj_or_aj_nest()) {
        assert(!tab->emb_sj_nest);
        tab->emb_sj_nest = tl->embedding;
        // Let the up-walk continue, to assert there's no AJ/SJ nest above.
      }
    }
  }
}

/**
  @brief Check if semijoin's compared types allow materialization.

  @param[in,out] sj_nest Semi-join nest containing information about correlated
         expressions. Set nested_join->sjm.scan_allowed to true if
         MaterializeScan strategy allowed. Set nested_join->sjm.lookup_allowed
         to true if MaterializeLookup strategy allowed

  @details
    This is a temporary fix for BUG#36752.

    There are two subquery materialization strategies for semijoin:

    1. Materialize and do index lookups in the materialized table. See
       BUG#36752 for description of restrictions we need to put on the
       compared expressions.

       In addition, since indexes are not supported for BLOB columns,
       this strategy can not be used if any of the columns in the
       materialized table will be BLOB/GEOMETRY columns.  (Note that
       also columns for non-BLOB values that may be greater in size
       than CONVERT_IF_BIGGER_TO_BLOB, will be represented as BLOB
       columns.)

    2. Materialize and then do a full scan of the materialized table.
       The same criteria as for MaterializeLookup are applied, except that
       BLOB/GEOMETRY columns are allowed.
*/

static void semijoin_types_allow_materialization(Table_ref *sj_nest) {
  DBUG_TRACE;

  assert(sj_nest->nested_join->sj_outer_exprs.size() ==
         sj_nest->nested_join->sj_inner_exprs.size());

  if (sj_nest->nested_join->sj_outer_exprs.size() > MAX_REF_PARTS ||
      sj_nest->nested_join->sj_outer_exprs.size() == 0) {
    // building an index is impossible
    sj_nest->nested_join->sjm.scan_allowed = false;
    sj_nest->nested_join->sjm.lookup_allowed = false;
    return;
  }

  sj_nest->nested_join->sjm.scan_allowed = true;
  sj_nest->nested_join->sjm.lookup_allowed = true;

  bool blobs_involved = false;
  uint total_lookup_index_length = 0;
  uint max_key_length, max_key_part_length, max_key_parts;
  /*
    Maximum lengths for keys and key parts that are supported by
    the temporary table storage engine(s).
  */
  get_max_key_and_part_length(&max_key_length, &max_key_part_length,
                              &max_key_parts);
  auto it1 = sj_nest->nested_join->sj_outer_exprs.begin();
  auto it2 = sj_nest->nested_join->sj_inner_exprs.begin();
  while (it1 != sj_nest->nested_join->sj_outer_exprs.end() &&
         it2 != sj_nest->nested_join->sj_inner_exprs.end()) {
    Item *outer = *it1++;
    Item *inner = *it2++;
    assert(outer->real_item() && inner->real_item());
    if (!types_allow_materialization(outer, inner)) {
      sj_nest->nested_join->sjm.scan_allowed = false;
      sj_nest->nested_join->sjm.lookup_allowed = false;
      return;
    }
    blobs_involved |= inner->is_blob_field();

    // Calculate the index length of materialized table
    const uint lookup_index_length = get_key_length_tmp_table(inner);
    if (lookup_index_length > max_key_part_length)
      sj_nest->nested_join->sjm.lookup_allowed = false;
    total_lookup_index_length += lookup_index_length;
  }
  if (total_lookup_index_length > max_key_length)
    sj_nest->nested_join->sjm.lookup_allowed = false;

  if (blobs_involved) sj_nest->nested_join->sjm.lookup_allowed = false;

  DBUG_PRINT("info", ("semijoin_types_allow_materialization: ok, allowed"));
}

/**
  Index dive can be skipped if the following conditions are satisfied:
  F1) For a single table query:
     a) FORCE INDEX applies to a single index.
     b) No subquery is present.
     c) Fulltext Index is not involved.
     d) No GROUP-BY or DISTINCT clause.
     e.I) No ORDER-BY clause or
     e.II) The given index can provide the order.

  F2) Not applicable to multi-table query.

  @param tab   JOIN_TAB object.
  @param thd   THD object.
*/

static bool check_skip_records_in_range_qualification(JOIN_TAB *tab, THD *thd) {
  Query_block *select = thd->lex->current_query_block();
  TABLE *table = tab->table();

  if ((!table->force_index ||
       table->keys_in_use_for_query.bits_set() != 1) ||   // F1.a
      !select->parent_lex->is_single_level_stmt() ||      // F1.b
      select->has_ft_funcs() ||                           // F1.c
      (select->is_grouped() || select->is_distinct()) ||  // F1.d
      select->m_current_table_nest->size() != 1)          // F2
    return false;

  /*
    Index dive is needed to get accurate cost from storage engine. When all
    above criteria is met, there are 2 use for the cost. Row access and sort.

    F1.e.I) If there is no ORDER BY then getting accurate cost is not needed as
    row access is enforced by force index.

    F1.e.II) If there is an ORDER BY and the chosen index (enforced by FORCE
    INDEX) for row access can provide order then the cost is not really used.
    Hence accurate cost calculation is not needed.
  */

  // F1.e.I
  if (!select->is_ordered()) return true;

  int idx = table->keys_in_use_for_query.get_first_set();
  uint used_key_parts;
  bool skip_quick;
  ORDER_with_src order_src(select->order_list.first, ESC_ORDER_BY);
  int key_order = test_if_order_by_key(&order_src, table, idx, &used_key_parts,
                                       &skip_quick);
  // Condition F1.e.II
  return key_order != 0;
}

/*****************************************************************************
  Create JOIN_TABS, make a guess about the table types,
  Approximate how many records will be used in each table
*****************************************************************************/

/**
  Returns estimated number of rows that could be fetched by given
  access method.

  The function calls the range optimizer to estimate the cost of the
  cheapest QUICK_* index access method to scan one or several of the
  'keys' using the conditions 'select->cond'. The range optimizer
  compares several different types of 'quick select' methods (range
  scan, index merge, loose index scan) and selects the cheapest one.

  If the best index access method is cheaper than a table- and an index
  scan, then the range optimizer also constructs the corresponding
  QUICK_* object and assigns it to select->quick. In most cases this
  is the QUICK_* object used at later (optimization and execution)
  phases.

  @param thd       Session that runs the query.
  @param tab       JOIN_TAB of source table.
  @param limit     maximum number of rows to select.
  @param condition the condition to be used for the range check,

  @note
    In case of valid range, a RowIterator object will be constructed and
    saved in select->quick.

  @return Estimated number of result rows selected from 'tab'.

  @retval HA_POS_ERROR For derived tables/views or if an error occur.
  @retval 0            If impossible query (i.e. certainly no rows will be
                       selected.)
*/
static ha_rows get_quick_record_count(THD *thd, JOIN_TAB *tab, ha_rows limit,
                                      Item *condition) {
  DBUG_TRACE;
  uchar buff[STACK_BUFF_ALLOC];
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
    return 0;  // Fatal error flag is set
  Table_ref *const tl = tab->table_ref;
  tab->set_skip_records_in_range(
      check_skip_records_in_range_qualification(tab, thd));

  // Derived tables aren't filled yet, so no stats are available.
  if (!tl->uses_materialization()) {
    AccessPath *range_scan;
    Key_map keys_to_use = tab->const_keys;
    keys_to_use.merge(tab->skip_scan_keys);
    MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                           thd->variables.range_alloc_block_size);
    int error = test_quick_select(
        thd, thd->mem_root, &temp_mem_root, keys_to_use, 0,
        0,  // empty table_map
        limit,
        false,  // don't force quick range
        ORDER_NOT_RELEVANT, tab->table(), tab->skip_records_in_range(),
        condition, &tab->needed_reg, tab->table()->force_index,
        tab->join()->query_block, &range_scan);
    tab->set_range_scan(range_scan);

    if (error == 1) return range_scan->num_output_rows();
    if (error == -1) {
      tl->table->reginfo.impossible_range = true;
      return 0;
    }
    DBUG_PRINT("warning", ("Couldn't use record count on const keypart"));
  } else if (tl->is_table_function() || tl->materializable_is_const(thd)) {
    tl->fetch_number_of_rows();
    return tl->table->file->stats.records;
  }
  return HA_POS_ERROR;
}

/*
  Get estimated record length for semi-join materialization temptable

  SYNOPSIS
    get_tmp_table_rec_length()
      items  IN subquery's select list.

  DESCRIPTION
    Calculate estimated record length for semi-join materialization
    temptable. It's an estimate because we don't follow every bit of
    create_tmp_table()'s logic. This isn't necessary as the return value of
    this function is used only for cost calculations.

  RETURN
    Length of the temptable record, in bytes
*/

static uint get_tmp_table_rec_length(const mem_root_deque<Item *> &items) {
  uint len = 0;
  for (Item *item : VisibleFields(items)) {
    switch (item->result_type()) {
      case REAL_RESULT:
        len += sizeof(double);
        break;
      case INT_RESULT:
        if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
          len += 8;
        else
          len += 4;
        break;
      case STRING_RESULT:
        /* DATE/TIME and GEOMETRY fields have STRING_RESULT result type.  */
        if (item->is_temporal() || item->data_type() == MYSQL_TYPE_GEOMETRY)
          len += 8;
        else
          len += item->max_length;
        break;
      case DECIMAL_RESULT:
        len += 10;
        break;
      case ROW_RESULT:
      default:
        assert(0); /* purecov: deadcode */
        break;
    }
  }
  return len;
}

/**
   Writes to the optimizer trace information about dependencies between
   tables.
   @param trace  optimizer trace
   @param join_tabs  all JOIN_TABs of the join
   @param table_count how many JOIN_TABs in the 'join_tabs' array
*/
static void trace_table_dependencies(Opt_trace_context *trace,
                                     JOIN_TAB *join_tabs, uint table_count) {
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_array trace_dep(trace, "table_dependencies");
  for (uint i = 0; i < table_count; i++) {
    Table_ref *table_ref = join_tabs[i].table_ref;
    Opt_trace_object trace_one_table(trace);
    trace_one_table.add_utf8_table(table_ref).add(
        "row_may_be_null", table_ref->table->is_nullable());
    const table_map map = table_ref->map();
    assert(map < (1ULL << table_count));
    for (uint j = 0; j < table_count; j++) {
      if (map & (1ULL << j)) {
        trace_one_table.add("map_bit", j);
        break;
      }
    }
    Opt_trace_array depends_on(trace, "depends_on_map_bits");
    static_assert(sizeof(table_ref->map()) <= 64,
                  "RAND_TABLE_BIT may be in join_tabs[i].dependent, so we test "
                  "all 64 bits.");
    for (uint j = 0; j < 64; j++) {
      if (join_tabs[i].dependent & (1ULL << j)) depends_on.add(j);
    }
  }
}

/**
  Add to join_tab[i]->condition() "table.field IS NOT NULL" conditions
  we've inferred from ref/eq_ref access performed.

    This function is a part of "Early NULL-values filtering for ref access"
    optimization.

    Example of this optimization:
    For query SELECT * FROM t1,t2 WHERE t2.key=t1.field @n
    and plan " any-access(t1), ref(t2.key=t1.field) " @n
    add "t1.field IS NOT NULL" to t1's table condition. @n

    Description of the optimization:

      We look through equalities chosen to perform ref/eq_ref access,
      pick equalities that have form "tbl.part_of_key = othertbl.field"
      (where othertbl is a non-const table and othertbl.field may be NULL)
      and add them to conditions on corresponding tables (othertbl in this
      example).

      Exception from that is the case when referred_tab->join != join.
      I.e. don't add NOT NULL constraints from any embedded subquery.
      Consider this query:
      @code
      SELECT A.f2 FROM t1 LEFT JOIN t2 A ON A.f2 = f1
      WHERE A.f3=(SELECT MIN(f3) FROM  t2 C WHERE A.f4 = C.f4) OR A.f3 IS NULL;
      @endcode
      Here condition A.f3 IS NOT NULL is going to be added to the WHERE
      condition of the embedding query.
      Another example:
      SELECT * FROM t10, t11 WHERE (t10.a < 10 OR t10.a IS NULL)
      AND t11.b <=> t10.b AND (t11.a = (SELECT MAX(a) FROM t12
      WHERE t12.b = t10.a ));
      Here condition t10.a IS NOT NULL is going to be added.
      In both cases addition of NOT NULL condition will erroneously reject
      some rows of the result set.
      referred_tab->join != join constraint would disallow such additions.

      This optimization doesn't affect the choices that ref, range, or join
      optimizer make. This was intentional because this was added after 4.1
      was GA.

    Implementation overview
      1. update_ref_and_keys() accumulates info about null-rejecting
         predicates in in Key_field::null_rejecting
      1.1 add_key_part saves these to Key_use.
      2. create_ref_for_key copies them to Index_lookup.
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->m_condition of
         appropriate JOIN_TAB members.

  @returns false on success, true on error
*/

static bool add_not_null_conds(JOIN *join) {
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(join);
  for (uint i = join->const_tables; i < join->tables; i++) {
    JOIN_TAB *const tab = join->best_ref[i];
    if ((tab->type() != JT_REF && tab->type() != JT_EQ_REF &&
         tab->type() != JT_REF_OR_NULL) ||
        tab->table()->is_nullable()) {
      continue;
    }
    for (uint keypart = 0; keypart < tab->ref().key_parts; keypart++) {
      if ((tab->ref().null_rejecting & ((key_part_map)1 << keypart)) == 0) {
        continue;
      }
      Item *const item = tab->ref().items[keypart]->real_item();
      if (item->type() != Item::FIELD_ITEM || !item->is_nullable()) continue;
      Item_field *const not_null_item = down_cast<Item_field *>(item);
      JOIN_TAB *referred_tab = not_null_item->field->table->reginfo.join_tab;
      /*
        For UPDATE queries such as:
        UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
        not_null_item is the t1.f1, but it's referred_tab is 0.
      */
      if (referred_tab == nullptr || referred_tab->join() != join) continue;
      /* Skip if we already have a 'not null' predicate for 'item' */
      if (has_not_null_predicate(referred_tab->condition(), not_null_item))
        continue;
      Item *notnull = new Item_func_isnotnull(not_null_item);
      if (notnull == nullptr) return true;
      /*
        We need to do full fix_fields() call here in order to have correct
        notnull->const_item(). This is needed e.g. by test_quick_select
        when it is called from make_join_query_block after this function is
        called.
      */
      if (notnull->fix_fields(join->thd, &notnull)) return true;
      DBUG_EXECUTE("where",
                   print_where(join->thd, notnull, referred_tab->table()->alias,
                               QT_ORDINARY););
      referred_tab->and_with_condition(notnull);
    }
  }
  return false;
}

/**
  Check all existing AND'ed predicates in 'cond' for an existing
  'is not null 'not_null_item''-predicate.

  A condition consisting of multiple AND'ed terms is recursively
  decomposed in the search for the specified not null predicate.

  @param  cond           Condition to be checked.
  @param  not_null_item  The item in: 'is not null 'item'' to search for

  @return true if 'is not null 'not_null_item'' is a predicate
          in the specified 'cond'.
*/
static bool has_not_null_predicate(Item *cond, Item_field *not_null_item) {
  if (cond == nullptr) return false;
  if (cond->type() == Item::FUNC_ITEM) {
    Item_func *item_func = down_cast<Item_func *>(cond);
    const Item_func::Functype func_type = item_func->functype();
    return (func_type == Item_func::ISNOTNULL_FUNC &&
            item_func->key_item() == not_null_item);
  } else if (cond->type() == Item::COND_ITEM) {
    Item_cond *item_cond = down_cast<Item_cond *>(cond);
    if (item_cond->functype() == Item_func::COND_AND_FUNC) {
      List_iterator<Item> li(*item_cond->argument_list());
      Item *item;
      while ((item = li++)) {
        if (has_not_null_predicate(item, not_null_item)) return true;
      }
    }
  }
  return false;
}

/**
  Check if given expression only uses fields covered by index @a keyno in the
  table tbl. The expression can use any fields in any other tables.

  The expression is guaranteed not to be AND or OR - those constructs are
  handled outside of this function.

  Restrict some function types from being pushed down to storage engine:
  a) Don't push down the triggered conditions with exception for
  IS_NOT_NULL_COMPL trigger condition since the NULL-complemented rows are added
  at a later stage in the iterators, so we won't see NULL-complemented rows when
  evaluating it as an index condition. Nested outer joins execution code may
  need to evaluate a condition several times (both triggered and untriggered).
     TODO: Consider cloning the triggered condition and using the copies for:
        1. push the first copy down, to have most restrictive index condition
           possible.
        2. Put the second copy into tab->m_condition.
  b) Stored functions contain a statement that might start new operations (like
     DML statements) from within the storage engine. This does not work against
     all SEs.
  c) Subqueries might contain nested subqueries and involve more tables.
     TODO: ROY: CHECK THIS
  d) Do not push down internal functions of type DD_INTERNAL_FUNC. When ICP is
     enabled, pushing internal functions to storage engine for evaluation will
     open data-dictionary tables. In InnoDB storage engine this will result in
     situation like recursive latching of same page by the same thread. To avoid
     such situation, internal functions of type DD_INTERNAL_FUNC are not pushed
  to storage engine for evaluation.

  @param  item           Expression to check
  @param  tbl            The table having the index
  @param  keyno          The index number
  @param  other_tbls_ok  true <=> Fields of other non-const tables are allowed

  @return false if No, true if Yes
*/

bool uses_index_fields_only(Item *item, TABLE *tbl, uint keyno,
                            bool other_tbls_ok) {
  // Restrictions b and c.
  if (item->has_stored_program() || item->has_subquery()) return false;

  // No table fields in const items
  if (item->const_for_execution()) return true;

  const Item::Type item_type = item->type();

  switch (item_type) {
    case Item::FUNC_ITEM: {
      Item_func *item_func = (Item_func *)item;
      const Item_func::Functype func_type = item_func->functype();

      if (func_type == Item_func::DD_INTERNAL_FUNC)  // Restriction d.
        return false;

      // Restriction a.
      if (func_type == Item_func::TRIG_COND_FUNC &&
          down_cast<Item_func_trig_cond *>(item_func)->get_trig_type() !=
              Item_func_trig_cond::IS_NOT_NULL_COMPL) {
        return false;
      }

      /* This is a function, apply condition recursively to arguments */
      if (item_func->argument_count() > 0) {
        Item **item_end =
            (item_func->arguments()) + item_func->argument_count();
        for (Item **child = item_func->arguments(); child != item_end;
             child++) {
          if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
            return false;
        }
      }
      return true;
    }
    case Item::COND_ITEM: {
      /*
        This is a AND/OR condition. Regular AND/OR clauses are handled by
        make_cond_for_index() which will chop off the part that can be
        checked with index. This code is for handling non-top-level AND/ORs,
        e.g. func(x AND y).
      */
      List_iterator<Item> li(*((Item_cond *)item)->argument_list());
      Item *cond_item;
      while ((cond_item = li++)) {
        if (!uses_index_fields_only(cond_item, tbl, keyno, other_tbls_ok))
          return false;
      }
      return true;
    }
    case Item::FIELD_ITEM: {
      const Item_field *item_field = down_cast<const Item_field *>(item);
      if (item_field->field->table != tbl) return other_tbls_ok;
      /*
        The below is probably a repetition - the first part checks the
        other two, but let's play it safe:
      */
      return item_field->field->part_of_key.is_set(keyno) &&
             item_field->field->type() != MYSQL_TYPE_GEOMETRY &&
             item_field->field->type() != MYSQL_TYPE_BLOB;
    }
    case Item::REF_ITEM:
      return uses_index_fields_only(item->real_item(), tbl, keyno,
                                    other_tbls_ok);
    default:
      return false; /* Play it safe, don't push unknown non-const items */
  }
}

/**
  Optimize semi-join nests that could be run with sj-materialization

  @param join           The join to optimize semi-join nests for

  @details
    Optimize each of the semi-join nests that can be run with
    materialization. For each of the nests, we
     - Generate the best join order for this "sub-join" and remember it;
     - Remember the sub-join execution cost (it's part of materialization
       cost);
     - Calculate other costs that will be incurred if we decide
       to use materialization strategy for this semi-join nest.

    All obtained information is saved and will be used by the main join
    optimization pass.

  @return false if successful, true if error
*/

static bool optimize_semijoin_nests_for_materialization(JOIN *join) {
  DBUG_TRACE;
  Opt_trace_context *const trace = &join->thd->opt_trace;

  for (Table_ref *sj_nest : join->query_block->sj_nests) {
    /* As a precaution, reset pointers that were used in prior execution */
    sj_nest->nested_join->sjm.positions = nullptr;

    /* Calculate the cost of materialization if materialization is allowed. */
    if (sj_nest->nested_join->sj_enabled_strategies &
        OPTIMIZER_SWITCH_MATERIALIZATION) {
      /* A semi-join nest should not contain tables marked as const */
      assert(!(sj_nest->sj_inner_tables & join->const_table_map));

      Opt_trace_object trace_wrapper(trace);
      Opt_trace_object trace_sjmat(
          trace, "execution_plan_for_potential_materialization");
      Opt_trace_array trace_sjmat_steps(trace, "steps");
      /*
        Try semijoin materialization if the semijoin is classified as
        non-trivially-correlated.
      */
      if (sj_nest->nested_join->sj_corr_tables) continue;
      /*
        Check whether data types allow execution with materialization.
      */
      semijoin_types_allow_materialization(sj_nest);

      if (!sj_nest->nested_join->sjm.scan_allowed &&
          !sj_nest->nested_join->sjm.lookup_allowed)
        continue;

      if (Optimize_table_order(join->thd, join, sj_nest).choose_table_order())
        return true;
      const uint n_tables = my_count_bits(sj_nest->sj_inner_tables);
      calculate_materialization_costs(join, sj_nest, n_tables,
                                      &sj_nest->nested_join->sjm);
      /*
        Cost data is in sj_nest->nested_join->sjm. We also need to save the
        plan:
      */
      if (!(sj_nest->nested_join->sjm.positions =
                (POSITION *)join->thd->alloc(sizeof(POSITION) * n_tables)))
        return true;
      memcpy(sj_nest->nested_join->sjm.positions,
             join->best_positions + join->const_tables,
             sizeof(POSITION) * n_tables);
    }
  }
  return false;
}

/*
  Check if table's Key_use elements have an eq_ref(outer_tables) candidate

  SYNOPSIS
    find_eq_ref_candidate()
      tl                Table to be checked
      sj_inner_tables   Bitmap of inner tables. eq_ref(inner_table) doesn't
                        count.

  DESCRIPTION
    Check if table's Key_use elements have an eq_ref(outer_tables) candidate

  TODO
    Check again if it is feasible to factor common parts with constant table
    search

  RETURN
    true  - There exists an eq_ref(outer-tables) candidate
    false - Otherwise
*/

static bool find_eq_ref_candidate(Table_ref *tl, table_map sj_inner_tables) {
  Key_use *keyuse = tl->table->reginfo.join_tab->keyuse();

  if (keyuse) {
    while (true) /* For each key */
    {
      const uint key = keyuse->key;
      KEY *const keyinfo = tl->table->key_info + key;
      key_part_map bound_parts = 0;
      if ((keyinfo->flags & (HA_NOSAME)) == HA_NOSAME) {
        do /* For all equalities on all key parts */
        {
          /* Check if this is "t.keypart = expr(outer_tables) */
          if (!(keyuse->used_tables & sj_inner_tables) &&
              !(keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)) {
            /*
              Consider only if the resulting condition does not pass a NULL
              value through. Especially needed for a UNIQUE index on NULLable
              columns where a duplicate row is possible with NULL values.
            */
            if (keyuse->null_rejecting || !keyuse->val->is_nullable() ||
                !keyinfo->key_part[keyuse->keypart].field->is_nullable())
              bound_parts |= (key_part_map)1 << keyuse->keypart;
          }
          keyuse++;
        } while (keyuse->key == key && keyuse->table_ref == tl);

        if (bound_parts == LOWER_BITS(uint, keyinfo->user_defined_key_parts))
          return true;
        if (keyuse->table_ref != tl) return false;
      } else {
        do {
          keyuse++;
          if (keyuse->table_ref != tl) return false;
        } while (keyuse->key == key);
      }
    }
  }
  return false;
}

/**
  Pull tables out of semi-join nests based on functional dependencies

  @param join  The join where to do the semi-join table pullout

  @return False if successful, true if error (Out of memory)

  @details
    Pull tables out of semi-join nests based on functional dependencies,
    ie. if a table is accessed via eq_ref(outer_tables).
    The function may be called several times, the caller is responsible
    for setting up proper key information that this function acts upon.

    PRECONDITIONS
    When this function is called, the join may have several semi-join nests
    but it is guaranteed that one semi-join nest does not contain another.
    For functionally dependent tables to be pulled out, key information must
    have been calculated (see update_ref_and_keys()).

    POSTCONDITIONS
     * Tables that were pulled out are removed from the semi-join nest they
       belonged to and added to the parent join nest.
     * For these tables, the used_tables and not_null_tables fields of
       the semi-join nest they belonged to will be adjusted.
       The semi-join nest is also marked as correlated, and
       sj_corr_tables and sj_depends_on are adjusted if necessary.
     * Semi-join nests' sj_inner_tables is set equal to used_tables

    NOTE
    Table pullout may make uncorrelated subquery correlated. Consider this
    example:

     ... WHERE oe IN (SELECT it1.primary_key WHERE p(it1, it2) ... )

    here table it1 can be pulled out (we have it1.primary_key=oe which gives
    us functional dependency). Once it1 is pulled out, all references to it1
    from p(it1, it2) become references to outside of the subquery and thus
    make the subquery (i.e. its semi-join nest) correlated.
    Making the subquery (i.e. its semi-join nest) correlated prevents us from
    using Materialization or LooseScan to execute it.
*/

static bool pull_out_semijoin_tables(JOIN *join) {
  DBUG_TRACE;

  assert(!join->query_block->sj_nests.empty());

  Opt_trace_context *const trace = &join->thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_array trace_pullout(trace, "pulled_out_semijoin_tables");

  /* Try pulling out tables from each semi-join nest */
  for (auto sj_list_it = join->query_block->sj_nests.begin();
       sj_list_it != join->query_block->sj_nests.end();) {
    Table_ref *sj_nest = *sj_list_it;
    if (sj_nest->is_aj_nest()) {
      ++sj_list_it;
      continue;
    }
    table_map pulled_tables = 0;
    /*
      Calculate set of tables within this semi-join nest that have
      other dependent tables. They cannot be pulled out. For example, with
      t1 SEMIJOIN (t2 LEFT JOIN t3 ON ...) ON t1.a=t2.pk,
      t2 cannot be pulled out because t3 depends on it.
    */
    table_map dep_tables = 0;
    for (Table_ref *tbl : sj_nest->nested_join->m_tables) {
      if (tbl->dep_tables & sj_nest->nested_join->used_tables)
        dep_tables |= tbl->dep_tables;
    }
    /*
      Find which tables we can pull out based on key dependency data.
      Note that pulling one table out can allow us to pull out some
      other tables too.
    */
    bool pulled_a_table;
    do {
      pulled_a_table = false;
      for (Table_ref *tbl : sj_nest->nested_join->m_tables) {
        if (tbl->table && !(pulled_tables & tbl->map()) &&
            !(dep_tables & tbl->map())) {
          if (find_eq_ref_candidate(
                  tbl, sj_nest->nested_join->used_tables & ~pulled_tables)) {
            pulled_a_table = true;
            pulled_tables |= tbl->map();
            Opt_trace_object(trace).add_utf8_table(tbl).add(
                "functionally_dependent", true);
            /*
              Pulling a table out of uncorrelated subquery in general makes
              it correlated. See the NOTE to this function.
            */
            sj_nest->nested_join->sj_corr_tables |= tbl->map();
            sj_nest->nested_join->sj_depends_on |= tbl->map();
          }
        }
      }
    } while (pulled_a_table);

    /*
      Move the pulled out Table_ref elements to the parents.
    */
    sj_nest->nested_join->used_tables &= ~pulled_tables;
    sj_nest->nested_join->not_null_tables &= ~pulled_tables;

    /* sj_inner_tables is a copy of nested_join->used_tables */
    sj_nest->sj_inner_tables = sj_nest->nested_join->used_tables;

    bool remove = false;
    if (pulled_tables) {
      mem_root_deque<Table_ref *> *upper_join_list =
          (sj_nest->embedding != nullptr)
              ? &sj_nest->embedding->nested_join->m_tables
              : &join->query_block->m_table_nest;

      Prepared_stmt_arena_holder ps_arena_holder(join->thd);

      for (auto child_li = sj_nest->nested_join->m_tables.begin();
           child_li != sj_nest->nested_join->m_tables.end();) {
        Table_ref *tbl = *child_li;
        if (tbl->table && !(sj_nest->nested_join->used_tables & tbl->map())) {
          /*
            Pull the table up in the same way as simplify_joins() does:
            update join_list and embedding pointers but keep next[_local]
            pointers.
          */
          child_li = sj_nest->nested_join->m_tables.erase(child_li);

          upper_join_list->push_back(tbl);

          tbl->join_list = upper_join_list;
          tbl->embedding = sj_nest->embedding;
        } else {
          ++child_li;
        }
      }

      /* Remove the sj-nest itself if we've removed everything from it */
      if (!sj_nest->nested_join->used_tables) {
        upper_join_list->erase(std::find(upper_join_list->begin(),
                                         upper_join_list->end(), sj_nest));
        /* Also remove it from the list of SJ-nests: */
        remove = true;
      }
    }

    if (remove) {
      sj_list_it = join->query_block->sj_nests.erase(sj_list_it);
    } else {
      ++sj_list_it;
    }
  }
  return false;
}

/* Values in optimize */
#define KEY_OPTIMIZE_EXISTS 1
#define KEY_OPTIMIZE_REF_OR_NULL 2

/**
  Merge new key definitions to old ones, remove those not used in both.

  This is called for OR between different levels.

  To be able to do 'ref_or_null' we merge a comparison of a column
  and 'column IS NULL' to one test.  This is useful for sub select queries
  that are internally transformed to something like:.

  @code
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
  @endcode

  Key_field::null_rejecting is processed as follows: @n
  result has null_rejecting=true if it is set for both ORed references.
  for example:
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false

  @todo
    The result of this is that we're missing some 'ref' accesses.
    OptimizerTeam: Fix this
*/

static Key_field *merge_key_fields(Key_field *start, Key_field *new_fields,
                                   Key_field *end, uint and_level) {
  if (start == new_fields) return start;  // Impossible or
  if (new_fields == end) return start;    // No new fields, skip all

  Key_field *first_free = new_fields;

  /* Mark all found fields in old array */
  for (; new_fields != end; new_fields++) {
    const Field *const new_field = new_fields->item_field->field;

    for (Key_field *old = start; old != first_free; old++) {
      const Field *const old_field = old->item_field->field;

      /*
        Check that the Field objects are the same, as we may have several
        Item_field objects pointing to the same Field:
      */
      if (old_field == new_field) {
        /*
          NOTE: below const_item() call really works as "!used_tables()", i.e.
          it can return false where it is feasible to make it return true.

          The cause is as follows: Some of the tables are already known to be
          const tables (the detection code is in JOIN::make_join_plan(),
          above the update_ref_and_keys() call), but we didn't propagate
          information about this: TABLE::const_table is not set to true, and
          Item::update_used_tables() hasn't been called for each item.
          The result of this is that we're missing some 'ref' accesses.
          TODO: OptimizerTeam: Fix this
        */
        if (!new_fields->val->const_item()) {
          /*
            If the value matches, we can use the key reference.
            If not, we keep it until we have examined all new values
          */
          if (old->val->eq(new_fields->val, old_field->binary())) {
            old->level = and_level;
            old->optimize =
                ((old->optimize & new_fields->optimize & KEY_OPTIMIZE_EXISTS) |
                 ((old->optimize | new_fields->optimize) &
                  KEY_OPTIMIZE_REF_OR_NULL));
            old->null_rejecting =
                (old->null_rejecting && new_fields->null_rejecting);
          }
        } else if (old->eq_func && new_fields->eq_func &&
                   old->val->eq_by_collation(new_fields->val,
                                             old_field->binary(),
                                             old_field->charset())) {
          old->level = and_level;
          old->optimize =
              ((old->optimize & new_fields->optimize & KEY_OPTIMIZE_EXISTS) |
               ((old->optimize | new_fields->optimize) &
                KEY_OPTIMIZE_REF_OR_NULL));
          old->null_rejecting =
              (old->null_rejecting && new_fields->null_rejecting);
        } else if (old->eq_func && new_fields->eq_func &&
                   ((old->val->const_item() && old->val->is_null()) ||
                    new_fields->val->is_null())) {
          /* field = expression OR field IS NULL */
          old->level = and_level;
          old->optimize = KEY_OPTIMIZE_REF_OR_NULL;
          /*
            Remember the NOT NULL value unless the value does not depend
            on other tables.
          */
          if (!old->val->used_tables() && old->val->is_null())
            old->val = new_fields->val;
          /* The referred expression can be NULL: */
          old->null_rejecting = false;
        } else {
          /*
            We are comparing two different const.  In this case we can't
            use a key-lookup on this so it's better to remove the value
            and let the range optimizer handle it
          */
          if (old == --first_free)  // If last item
            break;
          *old = *first_free;  // Remove old value
          old--;               // Retry this value
        }
      }
    }
  }
  /* Remove all not used items */
  for (Key_field *old = start; old != first_free;) {
    if (old->level != and_level) {  // Not used in all levels
      if (old == --first_free) break;
      *old = *first_free;  // Remove old value
      continue;
    }
    old++;
  }
  return first_free;
}

/**
  Given a field, return its index in semi-join's select list, or UINT_MAX

  @param item_field Field to be looked up in select list

  @retval =UINT_MAX Field is not from a semijoin-transformed subquery
  @retval <UINT_MAX Index in select list of subquery

  @details
  Given a field, find its table; then see if the table is within a
  semi-join nest and if the field was in select list of the subquery
  (if subquery was part of a quantified comparison predicate), or
  the field was a result of subquery decorrelation.
  If it was, then return the field's index in the select list.
  The value is used by LooseScan strategy.
*/

static uint get_semi_join_select_list_index(Item_field *item_field) {
  Table_ref *emb_sj_nest = item_field->table_ref->embedding;
  if (emb_sj_nest && emb_sj_nest->is_sj_or_aj_nest()) {
    const mem_root_deque<Item *> &items =
        emb_sj_nest->nested_join->sj_inner_exprs;
    for (size_t i = 0; i < items.size(); i++) {
      const Item *sel_item = items[i];
      if (sel_item->type() == Item::FIELD_ITEM &&
          down_cast<const Item_field *>(sel_item)->field->eq(item_field->field))
        return i;
    }
  }
  return UINT_MAX;
}

/**
   @brief
   If EXPLAIN or if the --safe-updates option is enabled, add a warning that an
   index cannot be used for ref access.

   @details
   If EXPLAIN or if the --safe-updates option is enabled, add a warning for each
   index that cannot be used for ref access due to either type conversion or
   different collations on the field used for comparison

   Example type conversion (char compared to int):

   CREATE TABLE t1 (url char(1) PRIMARY KEY);
   SELECT * FROM t1 WHERE url=1;

   Example different collations (danish vs german2):

   CREATE TABLE t1 (url char(1) PRIMARY KEY) collate latin1_danish_ci;
   SELECT * FROM t1 WHERE url='1' collate latin1_german2_ci;

   @param thd                Thread for the connection that submitted the query
   @param field              Field used in comparison
   @param cant_use_index     Indexes that cannot be used for lookup
 */
static void warn_index_not_applicable(THD *thd, const Field *field,
                                      const Key_map cant_use_index) {
  Functional_index_error_handler functional_index_error_handler(field, thd);

  if (thd->lex->is_explain() ||
      thd->variables.option_bits & OPTION_SAFE_UPDATES)
    for (uint j = 0; j < field->table->s->keys; j++)
      if (cant_use_index.is_set(j))
        push_warning_printf(thd, Sql_condition::SL_WARNING,
                            ER_WARN_INDEX_NOT_APPLICABLE,
                            ER_THD(thd, ER_WARN_INDEX_NOT_APPLICABLE), "ref",
                            field->table->key_info[j].name, field->field_name);
}

/**
  Add a possible key to array of possible keys if it's usable as a key

  @param [in,out] key_fields Used as an input parameter in the sense that it is
  a pointer to a pointer to a memory area where an array of Key_field objects
  will stored. It is used as an out parameter in the sense that the pointer will
  be updated to point beyond the last Key_field written.

  @param thd                session context
  @param and_level          And level, to be stored in Key_field
  @param cond               Condition predicate
  @param item_field         Field used in comparison
  @param eq_func            True if we used =, <=> or IS NULL
  @param value              Array of values used for comparison with field
  @param num_values         Number of elements in the array of values
  @param usable_tables      Tables which can be used for key optimization
  @param sargables          IN/OUT Array of found sargable candidates.
                            Will be ignored in case eq_func is true.

  @note
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
    table, we store this to be able to do not exists optimization later.


  @returns false if success, true if error
*/

static bool add_key_field(THD *thd, Key_field **key_fields, uint and_level,
                          Item_func *cond, Item_field *item_field, bool eq_func,
                          Item **value, uint num_values,
                          table_map usable_tables, SARGABLE_PARAM **sargables) {
  assert(cond->is_bool_func());
  assert(eq_func || sargables);
  assert(cond->functype() == Item_func::EQ_FUNC ||
         cond->functype() == Item_func::NE_FUNC ||
         cond->functype() == Item_func::GT_FUNC ||
         cond->functype() == Item_func::LT_FUNC ||
         cond->functype() == Item_func::GE_FUNC ||
         cond->functype() == Item_func::LE_FUNC ||
         cond->functype() == Item_func::MULT_EQUAL_FUNC ||
         cond->functype() == Item_func::EQUAL_FUNC ||
         cond->functype() == Item_func::LIKE_FUNC ||
         cond->functype() == Item_func::ISNULL_FUNC ||
         cond->functype() == Item_func::ISNOTNULL_FUNC ||
         cond->functype() == Item_func::BETWEEN ||
         cond->functype() == Item_func::IN_FUNC ||
         cond->functype() == Item_func::MEMBER_OF_FUNC ||
         cond->functype() == Item_func::SP_EQUALS_FUNC ||
         cond->functype() == Item_func::SP_WITHIN_FUNC ||
         cond->functype() == Item_func::SP_CONTAINS_FUNC ||
         cond->functype() == Item_func::SP_INTERSECTS_FUNC ||
         cond->functype() == Item_func::SP_DISJOINT_FUNC ||
         cond->functype() == Item_func::SP_COVERS_FUNC ||
         cond->functype() == Item_func::SP_COVEREDBY_FUNC ||
         cond->functype() == Item_func::SP_OVERLAPS_FUNC ||
         cond->functype() == Item_func::SP_TOUCHES_FUNC ||
         cond->functype() == Item_func::SP_CROSSES_FUNC);

  Field *const field = item_field->field;
  Table_ref *const tl = item_field->table_ref;

  if (tl->table->reginfo.join_tab == nullptr) {
    /*
       Due to a bug in IN-to-EXISTS (grep for real_item() in item_subselect.cc
       for more info), an index over a field from an outer query might be
       considered here, which is incorrect. Their query has been fully
       optimized already so their reginfo.join_tab is NULL and we reject them.
    */
    return false;
  }

  DBUG_PRINT("info", ("add_key_field for field %s", field->field_name));
  uint exists_optimize = 0;
  if (!tl->derived_keys_ready && tl->uses_materialization() &&
      !tl->table->is_created()) {
    bool allocated;
    if (tl->update_derived_keys(thd, field, value, num_values, &allocated))
      return true;
    if (!allocated) return false;
  }
  if (!field->is_flag_set(PART_KEY_FLAG)) {
    // Don't remove column IS NULL on a LEFT JOIN table
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
        !tl->table->is_nullable() || field->is_nullable())
      return false;  // Not a key. Skip it
    exists_optimize = KEY_OPTIMIZE_EXISTS;
    assert(num_values == 1);
  } else {
    table_map used_tables = 0;
    bool optimizable = false;
    for (uint i = 0; i < num_values; i++) {
      used_tables |= (value[i])->used_tables();
      if (!((value[i])->used_tables() & (tl->map() | RAND_TABLE_BIT)))
        optimizable = true;
    }
    if (!optimizable) return false;
    if (!(usable_tables & tl->map())) {
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
          !tl->table->is_nullable() || field->is_nullable())
        return false;  // Can't use left join optimize
      exists_optimize = KEY_OPTIMIZE_EXISTS;
    } else {
      JOIN_TAB *stat = tl->table->reginfo.join_tab;
      Key_map possible_keys = field->key_start;
      possible_keys.intersect(tl->table->keys_in_use_for_query);
      stat[0].keys().merge(possible_keys);  // Add possible keys

      /*
        Save the following cases:
        Field op constant
        Field LIKE constant where constant doesn't start with a wildcard
        Field = field2 where field2 is in a different table
        Field op formula
        Field IS NULL
        Field IS NOT NULL
        Field BETWEEN ...
        Field IN ...
      */
      stat[0].key_dependent |= used_tables;

      bool is_const = true;
      for (uint i = 0; i < num_values; i++) {
        if (!(is_const &= value[i]->const_for_execution())) break;
      }
      if (is_const)
        stat[0].const_keys.merge(possible_keys);
      else if (!eq_func) {
        /*
          Save info to be able check whether this predicate can be
          considered as sargable for range analysis after reading const tables.
          We do not save info about equalities as update_const_equal_items
          will take care of updating info on keys from sargable equalities.
        */
        assert(sargables);
        (*sargables)--;
        /*
          The sargables and key_fields arrays share the same memory
          buffer, and grow from opposite directions, so make sure they
          don't cross.
        */
        assert(*sargables > reinterpret_cast<SARGABLE_PARAM *>(*key_fields));
        (*sargables)->field = field;
        (*sargables)->arg_value = value;
        (*sargables)->num_values = num_values;
      }
      /*
        We can't always use indexes when comparing a string index to a
        number. cmp_type() is checked to allow compare of dates to numbers.
        eq_func is NEVER true when num_values > 1
       */
      if (!eq_func) return false;

      /*
        Check if the field and value are comparable in the index.
       */
      if (!comparable_in_index(cond, field, Field::itRAW, cond->functype(),
                               *value) ||
          (field->cmp_type() == STRING_RESULT &&
           field->match_collation_to_optimize_range() &&
           field->charset() != cond->compare_collation())) {
        warn_index_not_applicable(stat->join()->thd, field, possible_keys);
        return false;
      }
    }
  }
  /*
    For the moment eq_func is always true. This slot is reserved for future
    extensions where we want to remembers other things than just eq comparisons
  */
  assert(eq_func);
  /*
    Calculate the "null rejecting" property based on the type of predicate.
    Only the <=> operator and the IS NULL and IS NOT NULL clauses may return
    true on nullable operands that have the NULL value - assuming that all
    other predicates are augmented with IS TRUE or IS FALSE truth clause,
    so that all UNKNOWN results are converted to TRUE or FALSE.

    The "null rejecting" property can be combined with the left and right
    operands to perform certain optimizations.

    If the condition has form "left.field = right.keypart" and left.field can
    be NULL, there will be no matches if left.field is NULL.
    We use null_rejecting in add_not_null_conds() to add
    'left.field IS NOT NULL' to tab->m_condition, if this is not an outer
    join. We also use it to shortcut reading rows from table "right" when
    left.field is found to be a NULL value (in RefIterator and BKA).

    It is also possible to apply optimizations to the indexed table.
    If the operation is null rejecting and there is a unique index over
    the key field, an eq_ref operation can be performed on the index, since
    we have no interest in the NULL values.

    Notice however that the null rejecting property may be cancelled out
    by the KEY_OPTIMIZE_REF_OR_NULL property: this can be set when having:

      left.field = right.keypart OR right.keypart IS NULL.
  */
  const bool null_rejecting = cond->functype() != Item_func::EQUAL_FUNC &&
                              cond->functype() != Item_func::ISNULL_FUNC &&
                              cond->functype() != Item_func::ISNOTNULL_FUNC;

  /* Store possible eq field */
  new (*key_fields) Key_field(item_field, *value, and_level, exists_optimize,
                              eq_func, null_rejecting, nullptr,
                              get_semi_join_select_list_index(item_field));
  (*key_fields)++;
  /*
    The sargables and key_fields arrays share the same memory buffer,
    and grow from opposite directions, so make sure they don't
    cross. But if sargables was NULL, eq_func had to be true and we
    don't write any sargables.
  */
  assert(sargables == nullptr ||
         *key_fields < reinterpret_cast<Key_field *>(*sargables));

  return false;
}

/**
  Add possible keys to array of possible keys originated from a simple
  predicate.

    @param  thd            session context
    @param[in,out] key_fields Pointer to add key, if usable
                           is incremented if key was stored in the array
    @param  and_level      And level, to be stored in Key_field
    @param  cond           Condition predicate
    @param  field_item     Field used in comparison
    @param  eq_func        True if we used =, <=> or IS NULL
    @param  val            Value used for comparison with field
                           Is NULL for BETWEEN and IN
    @param  num_values     Number of elements in the array of values
    @param  usable_tables  Tables which can be used for key optimization
    @param  sargables      IN/OUT Array of found sargable candidates

  @note
    If field items f1 and f2 belong to the same multiple equality and
    a key is added for f1, the the same key is added for f2.

  @returns false if success, true if error
*/

static bool add_key_equal_fields(THD *thd, Key_field **key_fields,
                                 uint and_level, Item_func *cond,
                                 Item_field *field_item, bool eq_func,
                                 Item **val, uint num_values,
                                 table_map usable_tables,
                                 SARGABLE_PARAM **sargables) {
  assert(cond->is_bool_func());

  if (add_key_field(thd, key_fields, and_level, cond, field_item, eq_func, val,
                    num_values, usable_tables, sargables))
    return true;
  Item_equal *item_equal = field_item->item_equal;
  if (item_equal == nullptr) return false;
  /*
    Add to the set of possible key values every substitution of
    the field for an equal field included into item_equal
  */
  for (Item_field &item : item_equal->get_fields()) {
    if (!field_item->field->eq(item.field)) {
      if (add_key_field(thd, key_fields, and_level, cond, &item, eq_func, val,
                        num_values, usable_tables, sargables))
        return true;
    }
  }
  return false;
}

/**
  Check if an expression is a non-outer field.

  Checks if an expression is a field and belongs to the current select.

  @param   field  Item expression to check

  @return boolean
     @retval true   the expression is a local field
     @retval false  it's something else
*/

static bool is_local_field(Item *field) {
  return field->real_item()->type() == Item::FIELD_ITEM &&
         !field->is_outer_reference() &&
         !down_cast<Item_ident *>(field)->depended_from &&
         !down_cast<Item_ident *>(field->real_item())->depended_from;
}

/**
  Check if a row constructor expression is over columns in the same query block.

  @param item_row Row expression to check.

  @return boolean
  @retval true  The expression is a local column reference.
  @retval false It's something else.
*/
static bool is_row_of_local_columns(Item_row *item_row) {
  for (uint i = 0; i < item_row->cols(); ++i)
    if (!is_local_field(item_row->element_index(i))) return false;
  return true;
}

/**
   The guts of the ref optimizer. This function, along with the other
   add_key_* functions, make up a recursive procedure that analyzes a
   condition expression (a tree of AND and OR predicates) and does
   many things.

   @param thd      session context
   @param join     The query block involving the condition.
   @param [in,out] key_fields Start of memory buffer, see below.
   @param [in,out] and_level Current 'and level', see below.
   @param cond The conditional expression to analyze.
   @param usable_tables Tables not in this bitmap will not be examined.
   @param [in,out] sargables End of memory buffer, see below.

   @returns false if success, true if error

   This documentation is the result of reverse engineering and may
   therefore not capture the full gist of the procedure, but it is
   known to do the following:

   - Populate a raw memory buffer from two directions at the same time. An
     'array' of Key_field objects fill the buffer from low to high addresses
     whilst an 'array' of SARGABLE_PARAM's fills the buffer from high to low
     addresses. At the first call to this function, it is assumed that
     key_fields points to the beginning of the buffer and sargables point to the
     end (except for a poor-mans 'null element' at the very end).

   - Update a number of properties in the JOIN_TAB's that can be used
     to find search keys (sargables).

     - JOIN_TAB::keys
     - JOIN_TAB::key_dependent
     - JOIN_TAB::const_keys (dictates if the range optimizer will be run
       later.)

   The Key_field objects are marked with something called an 'and_level', which
   does @b not correspond to their nesting depth within the expression tree. It
   is rather a tag to group conjunctions together. For instance, in the
   conditional expression

   @code
     a = 0 AND b = 0
   @endcode

   two Key_field's are produced, both having an and_level of 0.

   In an expression such as

   @code
     a = 0 AND b = 0 OR a = 1
   @endcode

   three Key_field's are produced, the first two corresponding to 'a = 0' and
   'b = 0', respectively, both with and_level 0. The third one corresponds to
   'a = 1' and has an and_level of 1.

   A separate function, merge_key_fields() performs ref access validation on
   the Key_field array on the recursice ascent. If some Key_field's cannot be
   used for ref access, the key_fields pointer is rolled back. All other
   modifications to the query plan remain.
*/
bool add_key_fields(THD *thd, JOIN *join, Key_field **key_fields,
                    uint *and_level, Item *cond, table_map usable_tables,
                    SARGABLE_PARAM **sargables) {
  assert(cond->is_bool_func());

  if (cond->type() == Item_func::COND_ITEM) {
    List_iterator_fast<Item> li(*((Item_cond *)cond)->argument_list());
    Key_field *org_key_fields = *key_fields;

    if (down_cast<Item_cond *>(cond)->functype() == Item_func::COND_AND_FUNC) {
      Item *item;
      while ((item = li++)) {
        if (add_key_fields(thd, join, key_fields, and_level, item,
                           usable_tables, sargables))
          return true;
      }
      for (; org_key_fields != *key_fields; org_key_fields++)
        org_key_fields->level = *and_level;
    } else {
      (*and_level)++;
      if (add_key_fields(thd, join, key_fields, and_level, li++, usable_tables,
                         sargables))
        return true;
      Item *item;
      while ((item = li++)) {
        Key_field *start_key_fields = *key_fields;
        (*and_level)++;
        if (add_key_fields(thd, join, key_fields, and_level, item,
                           usable_tables, sargables))
          return true;
        *key_fields = merge_key_fields(org_key_fields, start_key_fields,
                                       *key_fields, ++(*and_level));
      }
    }
    return false;
  }

  /*
    Subquery optimization: Conditions that are pushed down into subqueries
    are wrapped into Item_func_trig_cond. We process the wrapped condition
    but need to set cond_guard for Key_use elements generated from it.
  */
  if (cond->type() == Item::FUNC_ITEM &&
      down_cast<Item_func *>(cond)->functype() == Item_func::TRIG_COND_FUNC) {
    Item *const cond_arg = down_cast<Item_func *>(cond)->arguments()[0];
    if (join->group_list.empty() && join->order.empty() &&
        join->query_expression()->item &&
        join->query_expression()->item->substype() == Item_subselect::IN_SUBS &&
        !join->query_expression()->is_set_operation()) {
      Key_field *save = *key_fields;
      if (add_key_fields(thd, join, key_fields, and_level, cond_arg,
                         usable_tables, sargables))
        return true;
      // Indicate that this ref access candidate is for subquery lookup:
      for (; save != *key_fields; save++)
        save->cond_guard = ((Item_func_trig_cond *)cond)->get_trig_var();
    }
    return false;
  }

  /* If item is of type 'field op field/constant' add it to key_fields */
  if (cond->type() != Item::FUNC_ITEM) return false;
  Item_func *const cond_func = down_cast<Item_func *>(cond);
  auto optimize = cond_func->select_optimize(thd);
  // Catch errors that might be thrown during select_optimize()
  if (thd->is_error()) return true;
  switch (optimize) {
    case Item_func::OPTIMIZE_NONE:
      break;
    case Item_func::OPTIMIZE_KEY: {
      Item **values;
      /*
        Build list of possible keys for 'a BETWEEN low AND high'.
        It is handled similar to the equivalent condition
        'a >= low AND a <= high':
      */
      if (cond_func->functype() == Item_func::BETWEEN) {
        Item_field *field_item;
        bool equal_func = false;
        uint num_values = 2;
        values = cond_func->arguments();

        bool binary_cmp =
            (values[0]->real_item()->type() == Item::FIELD_ITEM)
                ? ((Item_field *)values[0]->real_item())->field->binary()
                : true;

        /*
          Additional optimization: If 'low = high':
          Handle as if the condition was "t.key = low".
        */
        if (!((Item_func_between *)cond_func)->negated &&
            values[1]->eq(values[2], binary_cmp)) {
          equal_func = true;
          num_values = 1;
        }

        /*
          Append keys for 'field <cmp> value[]' if the
          condition is of the form::
          '<field> BETWEEN value[1] AND value[2]'
        */
        if (is_local_field(values[0])) {
          field_item = (Item_field *)(values[0]->real_item());
          if (add_key_equal_fields(thd, key_fields, *and_level, cond_func,
                                   field_item, equal_func, &values[1],
                                   num_values, usable_tables, sargables))
            return true;
        }
        /*
          Append keys for 'value[0] <cmp> field' if the
          condition is of the form:
          'value[0] BETWEEN field1 AND field2'
        */
        for (uint i = 1; i <= num_values; i++) {
          if (is_local_field(values[i])) {
            field_item = (Item_field *)(values[i]->real_item());
            if (add_key_equal_fields(thd, key_fields, *and_level, cond_func,
                                     field_item, equal_func, values, 1,
                                     usable_tables, sargables))
              return true;
          }
        }
      }  // if ( ... Item_func::BETWEEN)
      else if (cond_func->functype() == Item_func::MEMBER_OF_FUNC &&
               is_local_field(cond_func->key_item())) {
        // The predicate is <val> IN (<typed array>)
        add_key_equal_fields(thd, key_fields, *and_level, cond_func,
                             (Item_field *)(cond_func->key_item()->real_item()),
                             true, cond_func->arguments(), 1, usable_tables,
                             sargables);
      } else if (cond_func->functype() == Item_func::JSON_CONTAINS ||
                 cond_func->functype() == Item_func::JSON_OVERLAPS) {
        /*
          Applicability analysis was done during substitute_gc().
          Check here that a typed array field is used and there's a key over
          it.
          1) func has a key item
          2) key item is a local field
          3) key item is a typed array field
          If so, mark appropriate index as available for range optimizer
        */
        if (!cond_func->key_item() ||                  // 1
            !is_local_field(cond_func->key_item()) ||  // 2
            !cond_func->key_item()->returns_array())   // 3
          break;
        const Field *field =
            (down_cast<const Item_field *>(cond_func->key_item()))->field;
        JOIN_TAB *tab = field->table->reginfo.join_tab;
        Key_map possible_keys = field->key_start;

        possible_keys.intersect(field->table->keys_in_use_for_query);
        tab->keys().merge(possible_keys);      // Add possible keys
        tab->const_keys.merge(possible_keys);  // Add possible keys
      }                                        // if (... Item_func::CONTAINS)
      // The predicate is IN or <>
      else if (is_local_field(cond_func->key_item()) &&
               !cond_func->is_outer_reference()) {
        values = cond_func->arguments() + 1;
        if (cond_func->functype() == Item_func::NE_FUNC &&
            is_local_field(cond_func->arguments()[1]))
          values--;
        assert(cond_func->functype() != Item_func::IN_FUNC ||
               cond_func->argument_count() != 2);
        if (add_key_equal_fields(
                thd, key_fields, *and_level, cond_func,
                (Item_field *)(cond_func->key_item()->real_item()), false,
                values, cond_func->argument_count() - 1, usable_tables,
                sargables))
          return true;
      } else if (cond_func->functype() == Item_func::IN_FUNC &&
                 cond_func->key_item()->type() == Item::ROW_ITEM) {
        /*
          The condition is (column1, column2, ... ) IN ((const1_1, const1_2),
          ...) and there is an index on (column1, column2, ...)

          The code below makes sure that the row constructor on the lhs indeed
          contains only column references before calling add_key_field on them.

          We can't do a ref access on IN, yet here we are. Why? We need
          to run add_key_field() only because it verifies that there are
          only constant expressions in the rows on the IN's rhs, see
          comment above the call to add_key_field() below.

          Actually, We could in theory do a ref access if the IN rhs
          contained just a single row, but there is a hack in the parser
          causing such IN predicates be parsed as row equalities.
        */
        Item_row *lhs_row = static_cast<Item_row *>(cond_func->key_item());
        if (is_row_of_local_columns(lhs_row)) {
          for (uint i = 0; i < lhs_row->cols(); ++i) {
            Item *const lhs_item = lhs_row->element_index(i)->real_item();
            assert(lhs_item->type() == Item::FIELD_ITEM);
            Item_field *const lhs_column = static_cast<Item_field *>(lhs_item);
            // j goes from 1 since arguments()[0] is the lhs of IN.
            for (uint j = 1; j < cond_func->argument_count(); ++j) {
              // Here we pick out the i:th column in the j:th row.
              Item *rhs_item = cond_func->arguments()[j];
              assert(rhs_item->type() == Item::ROW_ITEM);
              Item_row *rhs_row = static_cast<Item_row *>(rhs_item);
              assert(rhs_row->cols() == lhs_row->cols());
              Item **rhs_expr_ptr = rhs_row->addr(i);
              /*
                add_key_field() will write a Key_field on each call
                here, but we don't care, it will never be used. We only
                call it for the side effect: update JOIN_TAB::const_keys
                so the range optimizer can be invoked. We pass a
                scrap buffer and pointer here.
              */
              Key_field scrap_key_field = **key_fields;
              Key_field *scrap_key_field_ptr = &scrap_key_field;
              if (add_key_field(thd, &scrap_key_field_ptr, *and_level,
                                cond_func, lhs_column,
                                true,  // eq_func
                                rhs_expr_ptr,
                                1,  // Number of expressions: one
                                usable_tables,
                                nullptr))  // sargables
                return true;
              // The pointer is not supposed to increase by more than one.
              assert(scrap_key_field_ptr <= &scrap_key_field + 1);
            }
          }
        }
      }
      break;
    }
    case Item_func::OPTIMIZE_OP: {
      bool equal_func = (cond_func->functype() == Item_func::EQ_FUNC ||
                         cond_func->functype() == Item_func::EQUAL_FUNC);

      if (is_local_field(cond_func->arguments()[0])) {
        if (add_key_equal_fields(
                thd, key_fields, *and_level, cond_func,
                (Item_field *)(cond_func->arguments()[0])->real_item(),
                equal_func, cond_func->arguments() + 1, 1, usable_tables,
                sargables))
          return true;
      } else {
        Item *real_item = cond_func->arguments()[0]->real_item();
        if (real_item->type() == Item::FUNC_ITEM) {
          Item_func *func_item = down_cast<Item_func *>(real_item);
          if (func_item->functype() == Item_func::COLLATE_FUNC) {
            Item *key_item = func_item->key_item();
            if (key_item->type() == Item::FIELD_ITEM) {
              if (add_key_equal_fields(thd, key_fields, *and_level, cond_func,
                                       down_cast<Item_field *>(key_item),
                                       equal_func, cond_func->arguments() + 1,
                                       1, usable_tables, sargables))
                return true;
            }
          }
        }
      }
      if (is_local_field(cond_func->arguments()[1]) &&
          cond_func->functype() != Item_func::LIKE_FUNC) {
        if (add_key_equal_fields(
                thd, key_fields, *and_level, cond_func,
                (Item_field *)(cond_func->arguments()[1])->real_item(),
                equal_func, cond_func->arguments(), 1, usable_tables,
                sargables))
          return true;
      } else {
        Item *real_item = cond_func->arguments()[1]->real_item();
        if (real_item->type() == Item::FUNC_ITEM) {
          Item_func *func_item = down_cast<Item_func *>(real_item);
          if (func_item->functype() == Item_func::COLLATE_FUNC) {
            Item *key_item = func_item->key_item();
            if (key_item->type() == Item::FIELD_ITEM) {
              if (add_key_equal_fields(thd, key_fields, *and_level, cond_func,
                                       down_cast<Item_field *>(key_item),
                                       equal_func, cond_func->arguments(), 1,
                                       usable_tables, sargables))
                return true;
            }
          }
        }
      }

      break;
    }
    case Item_func::OPTIMIZE_NULL:
      /* column_name IS [NOT] NULL */
      if (is_local_field(cond_func->arguments()[0]) &&
          !cond_func->is_outer_reference()) {
        Item *tmp = new Item_null;
        if (tmp == nullptr) return true;
        if (add_key_equal_fields(
                thd, key_fields, *and_level, cond_func,
                (Item_field *)(cond_func->arguments()[0])->real_item(),
                cond_func->functype() == Item_func::ISNULL_FUNC, &tmp, 1,
                usable_tables, sargables))
          return true;
      }
      break;
    case Item_func::OPTIMIZE_EQUAL:
      Item_equal *item_equal = (Item_equal *)cond;
      Item *const_item = item_equal->const_arg();
      if (const_item) {
        /*
          For each field field1 from item_equal consider the equality
          field1=const_item as a condition allowing an index access of the table
          with field1 by the keys value of field1.
        */
        for (Item_field &item : item_equal->get_fields()) {
          if (add_key_field(thd, key_fields, *and_level, cond_func, &item, true,
                            &const_item, 1, usable_tables, sargables))
            return true;
        }
      } else {
        /*
          Consider all pairs of different fields included into item_equal.
          For each of them (field1, field1) consider the equality
          field1=field2 as a condition allowing an index access of the table
          with field1 by the keys value of field2.
        */
        for (Item_field &outer : item_equal->get_fields()) {
          for (Item_field &inner : item_equal->get_fields()) {
            if (!outer.field->eq(inner.field)) {
              Item *inner_ptr = &inner;
              if (add_key_field(thd, key_fields, *and_level, cond_func, &outer,
                                true, &inner_ptr, 1, usable_tables, sargables))
                return true;
            }
          }
        }
      }
      break;
  }
  return false;
}

/*
  Add all keys with uses 'field' for some keypart
  If field->and_level != and_level then only mark key_part as const_part

  RETURN
   0 - OK
   1 - Out of memory.
*/

static bool add_key_part(Key_use_array *keyuse_array, Key_field *key_field) {
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS)) {
    const Field *const field = key_field->item_field->field;
    Table_ref *const tl = key_field->item_field->table_ref;
    TABLE *const table = tl->table;

    for (uint key = 0; key < table->s->keys; key++) {
      if (!(table->keys_in_use_for_query.is_set(key))) continue;
      if (table->key_info[key].flags & (HA_FULLTEXT | HA_SPATIAL))
        continue;  // ToDo: ft-keys in non-ft queries.   SerG

      uint key_parts = actual_key_parts(&table->key_info[key]);
      for (uint part = 0; part < key_parts; part++) {
        if (field->eq(table->key_info[key].key_part[part].field)) {
          const Key_use keyuse(tl, key_field->val,
                               key_field->val->used_tables(), key, part,
                               key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL,
                               (key_part_map)1 << part,
                               ~(ha_rows)0,  // will be set in optimize_keyuse
                               key_field->null_rejecting, key_field->cond_guard,
                               key_field->sj_pred_no);
          if (keyuse_array->push_back(keyuse))
            return true; /* purecov: inspected */
        }
      }
    }
  }
  return false;
}

/**
   Function parses WHERE condition and add key_use for FT index
   into key_use array if suitable MATCH function is found.
   Condition should be a set of AND expression, OR is not supported.
   MATCH function should be a part of simple expression.
   Simple expression is MATCH only function or MATCH is a part of
   comparison expression ('>=' or '>' operations are supported).
   It also sets FT_HINTS values(op_type, op_value).

   @param keyuse_array      Key_use array
   @param cond              WHERE condition
   @param usable_tables     usable tables
   @param simple_match_expr true if this is the first call false otherwise.
                            if MATCH function is found at first call it means
                            that MATCH is simple expression, otherwise, in case
                            of AND/OR condition this parameter will be false.

   @retval
   true if FT key was added to Key_use array
   @retval
   false if no key was added to Key_use array

*/

static bool add_ft_keys(Key_use_array *keyuse_array, Item *cond,
                        table_map usable_tables, bool simple_match_expr) {
  Item_func_match *cond_func = nullptr;

  if (!cond) return false;

  assert(cond->is_bool_func());

  if (cond->type() == Item::FUNC_ITEM) {
    Item_func *func = down_cast<Item_func *>(cond);
    Item_func::Functype functype = func->functype();
    if (functype == Item_func::MATCH_FUNC) {
      func = down_cast<Item_func *>(func->arguments()[0]);
      functype = func->functype();
    }
    enum ft_operation op_type = FT_OP_NO;
    double op_value = 0.0;
    if (functype == Item_func::FT_FUNC) {
      cond_func = down_cast<Item_func_match *>(func)->get_master();
      cond_func->set_hints_op(op_type, op_value);
    } else if (func->arg_count == 2) {
      Item *arg0 = func->arguments()[0];
      Item *arg1 = func->arguments()[1];
      if (arg1->const_item() && is_function_of_type(arg0, Item_func::FT_FUNC) &&
          ((functype == Item_func::GE_FUNC &&
            (op_value = arg1->val_real()) > 0) ||
           (functype == Item_func::GT_FUNC &&
            (op_value = arg1->val_real()) >= 0))) {
        cond_func = down_cast<Item_func_match *>(arg0)->get_master();
        if (functype == Item_func::GE_FUNC)
          op_type = FT_OP_GE;
        else if (functype == Item_func::GT_FUNC)
          op_type = FT_OP_GT;
        cond_func->set_hints_op(op_type, op_value);
      } else if (arg0->const_item() &&
                 is_function_of_type(arg1, Item_func::FT_FUNC) &&
                 ((functype == Item_func::LE_FUNC &&
                   (op_value = arg0->val_real()) > 0) ||
                  (functype == Item_func::LT_FUNC &&
                   (op_value = arg0->val_real()) >= 0))) {
        cond_func = down_cast<Item_func_match *>(arg1)->get_master();
        if (functype == Item_func::LE_FUNC)
          op_type = FT_OP_GE;
        else if (functype == Item_func::LT_FUNC)
          op_type = FT_OP_GT;
        cond_func->set_hints_op(op_type, op_value);
      }
    }
  } else if (cond->type() == Item::COND_ITEM) {
    List_iterator_fast<Item> li(*down_cast<Item_cond *>(cond)->argument_list());

    if (down_cast<Item_cond *>(cond)->functype() == Item_func::COND_AND_FUNC) {
      Item *item;
      while ((item = li++))
        if (add_ft_keys(keyuse_array, item, usable_tables, false)) return true;
    }
  }

  if (!cond_func || cond_func->key == NO_SUCH_KEY ||
      !(usable_tables & cond_func->table_ref->map()))
    return false;

  Table_ref *tbl = cond_func->table_ref;
  if (!tbl->table->keys_in_use_for_query.is_set(cond_func->key)) return false;

  cond_func->set_simple_expression(simple_match_expr);

  const Key_use keyuse(tbl, cond_func, cond_func->key_item()->used_tables(),
                       cond_func->key, FT_KEYPART,
                       0,            // optimize
                       0,            // keypart_map
                       ~(ha_rows)0,  // ref_table_rows
                       false,        // null_rejecting
                       nullptr,      // cond_guard
                       UINT_MAX);    // sj_pred_no
  tbl->table->reginfo.join_tab->keys().set_bit(cond_func->key);
  return keyuse_array->push_back(keyuse);
}

/**
  Compares two keyuse elements.

  @param a first Key_use element
  @param b second Key_use element

  Compare Key_use elements so that they are sorted as follows:
    -# By table.
    -# By key for each table.
    -# By keypart for each key.
    -# Const values.
    -# Ref_or_null.

  @retval true If a < b.
  @retval false If a >= b.
*/
static bool sort_keyuse(const Key_use &a, const Key_use &b) {
  if (a.table_ref->tableno() != b.table_ref->tableno())
    return a.table_ref->tableno() < b.table_ref->tableno();
  if (a.key != b.key) return a.key < b.key;
  if (a.keypart != b.keypart) return a.keypart < b.keypart;
  // Place const values before other ones
  bool a_const = a.used_tables & ~OUTER_REF_TABLE_BIT;
  bool b_const = b.used_tables & ~OUTER_REF_TABLE_BIT;
  if (a_const != b_const) return b_const;
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
  return (a.optimize & KEY_OPTIMIZE_REF_OR_NULL) <
         (b.optimize & KEY_OPTIMIZE_REF_OR_NULL);
}

/*
  Add to Key_field array all 'ref' access candidates within nested join.

    This function populates Key_field array with entries generated from the
    ON condition of the given nested join, and does the same for nested joins
    contained within this nested join.

  @param          thd                 session context
  @param[in]      nested_join_table   Nested join pseudo-table to process
  @param[in,out]  end                 End of the key field array
  @param[in,out]  and_level           And-level
  @param[in,out]  sargables           Array of found sargable candidates

  @returns false if success, true if error

  @note
    We can add accesses to the tables that are direct children of this nested
    join (1), and are not inner tables w.r.t their neighbours (2).

    Example for #1 (outer brackets pair denotes nested join this function is
    invoked for):
    @code
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
    @endcode
    Example for #2:
    @code
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
    @endcode
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
    t1 only.
    Example #3:
    @code
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
    @endcode
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
*/

static bool add_key_fields_for_nj(THD *thd, JOIN *join,
                                  Table_ref *nested_join_table, Key_field **end,
                                  uint *and_level, SARGABLE_PARAM **sargables) {
  mem_root_deque<Table_ref *> &join_list =
      nested_join_table->nested_join->m_tables;
  auto li = join_list.begin();
  auto li_end = join_list.end();
  auto li2 = join_list.begin();
  auto li2_end = join_list.end();
  bool have_another = false;
  table_map tables = 0;
  Table_ref *table;

  while ((table = (li != li_end) ? *li++ : nullptr) ||
         (have_another && li2 != join_list.end() &&
          (li = li2, li_end = li2_end, have_another = false,
           (li != li_end) && (table = *li++)))) {
    if (table->nested_join) {
      if (!table->join_cond_optim()) {
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
        have_another = true;
        li2 = li;
        li2_end = li_end;
        li = table->nested_join->m_tables.begin();
        li_end = table->nested_join->m_tables.end();
      } else {
        if (add_key_fields_for_nj(thd, join, table, end, and_level, sargables))
          return true;
      }
    } else if (!table->join_cond_optim())
      tables |= table->map();
  }
  if (nested_join_table->join_cond_optim()) {
    if (add_key_fields(thd, join, end, and_level,
                       nested_join_table->join_cond_optim(), tables, sargables))
      return true;
  }
  return false;
}

///  @} (end of group RefOptimizerModule)

/**
  Check for the presence of AGGFN(DISTINCT a) queries that may be subject
  to loose index scan.


  Check if the query is a subject to AGGFN(DISTINCT) using loose index scan
  (GroupIndexSkipScanIterator).
  Optionally (if out_args is supplied) will push the arguments of
  AGGFN(DISTINCT) to the list

  Check for every COUNT(DISTINCT), AVG(DISTINCT) or
  SUM(DISTINCT). These can be resolved by Loose Index Scan as long
  as all the aggregate distinct functions refer to the same
  fields. Thus:

  SELECT AGGFN(DISTINCT a, b), AGGFN(DISTINCT b, a)... => can use LIS
  SELECT AGGFN(DISTINCT a),    AGGFN(DISTINCT a)   ... => can use LIS
  SELECT AGGFN(DISTINCT a, b), AGGFN(DISTINCT a)   ... => cannot use LIS
  SELECT AGGFN(DISTINCT a),    AGGFN(DISTINCT b)   ... => cannot use LIS
  etc.

  @param      join       the join to check
  @param[out] out_args   Collect the arguments of the aggregate functions
                         to a list. We don't worry about duplicates as
                         these will be sorted out later in
                         get_best_group_min_max.

  @return                does the query qualify for indexed AGGFN(DISTINCT)
    @retval   true       it does
    @retval   false      AGGFN(DISTINCT) must apply distinct in it.
*/

bool is_indexed_agg_distinct(JOIN *join,
                             mem_root_deque<Item_field *> *out_args) {
  Item_sum **sum_item_ptr;
  bool result = false;
  Field_map first_aggdistinct_fields;

  if (join->query_block->original_tables_map > 1 || /* reference more than 1
                                                       table originally */
      join->select_distinct ||                      /* or a DISTINCT */
      join->query_block->olap == ROLLUP_TYPE)       /* Check (B3) for ROLLUP */
    return false;

  if (join->make_sum_func_list(*join->fields, true)) return false;

  for (sum_item_ptr = join->sum_funcs; *sum_item_ptr; sum_item_ptr++) {
    Item_sum *sum_item = *sum_item_ptr;
    Field_map cur_aggdistinct_fields;
    Item *expr;
    /* aggregate is not AGGFN(DISTINCT) or more than 1 argument to it */
    switch (sum_item->sum_func()) {
      case Item_sum::MIN_FUNC:
      case Item_sum::MAX_FUNC:
        continue;
      case Item_sum::COUNT_DISTINCT_FUNC:
        break;
      case Item_sum::AVG_DISTINCT_FUNC:
      case Item_sum::SUM_DISTINCT_FUNC:
        if (sum_item->argument_count() == 1) break;
        [[fallthrough]];
      default:
        return false;
    }

    for (uint i = 0; i < sum_item->argument_count(); i++) {
      expr = sum_item->get_arg(i);
      /* The AGGFN(DISTINCT) arg is not an attribute? */
      if (expr->real_item()->type() != Item::FIELD_ITEM) return false;

      Item_field *item = static_cast<Item_field *>(expr->real_item());
      if (out_args) out_args->push_back(item);

      cur_aggdistinct_fields.set_bit(item->field->field_index());
      result = true;
    }
    /*
      If there are multiple aggregate functions, make sure that they all
      refer to exactly the same set of columns.
    */
    if (first_aggdistinct_fields.is_clear_all())
      first_aggdistinct_fields.merge(cur_aggdistinct_fields);
    else if (first_aggdistinct_fields != cur_aggdistinct_fields)
      return false;
  }

  return result;
}

/**
  Print keys that were appended to join_tab->const_keys because they
  can be used for GROUP BY or DISTINCT to the optimizer trace.

  @param trace     The optimizer trace context we're adding info to
  @param join_tab  The table the indexes cover
  @param new_keys  The keys that are considered useful because they can
                   be used for GROUP BY or DISTINCT
  @param cause     Zero-terminated string with reason for adding indexes
                   to const_keys

  @see add_group_and_distinct_keys()
 */
static void trace_indexes_added_group_distinct(Opt_trace_context *trace,
                                               const JOIN_TAB *join_tab,
                                               const Key_map new_keys,
                                               const char *cause) {
  if (likely(!trace->is_started())) return;

  KEY *key_info = join_tab->table()->key_info;
  Key_map existing_keys = join_tab->const_keys;
  uint nbrkeys = join_tab->table()->s->keys;

  Opt_trace_object trace_summary(trace, "const_keys_added");
  {
    Opt_trace_array trace_key(trace, "keys");
    for (uint j = 0; j < nbrkeys; j++)
      if (new_keys.is_set(j) && !existing_keys.is_set(j))
        trace_key.add_utf8(key_info[j].name);
  }
  trace_summary.add_alnum("cause", cause);
}

/**
  Discover the indexes that might be used for GROUP BY or DISTINCT queries or
  indexes that might be used for SKIP SCAN.

  If the query has a GROUP BY clause, find all indexes that contain
  all GROUP BY fields, and add those indexes to join_tab->const_keys
  and join_tab->keys.

  If the query has a DISTINCT clause, find all indexes that contain
  all SELECT fields, and add those indexes to join_tab->const_keys and
  join_tab->keys. This allows later on such queries to be processed by
  a GroupIndexSkipScanIterator.

  If the query does not have GROUP BY clause or any aggregate function
  the function collects possible keys to use for skip scan access.

  Note that indexes that are not usable for resolving GROUP
  BY/DISTINCT may also be added in some corner cases. For example, an
  index covering 'a' and 'b' is not usable for the following query but
  is still added: "SELECT DISTINCT a+b FROM t1". This is not a big
  issue because a) although the optimizer will consider using the
  index, it will not chose it (so minor calculation cost added but not
  wrong result) and b) it applies only to corner cases.

  @param join      the current join
  @param join_tab  joined table
*/

static void add_loose_index_scan_and_skip_scan_keys(JOIN *join,
                                                    JOIN_TAB *join_tab) {
  assert(join_tab->const_keys.is_subset(join_tab->keys()));

  mem_root_deque<Item_field *> indexed_fields(join->thd->mem_root);
  ORDER *cur_group;
  const char *cause;

  /* Find the indexes that might be used for skip scan queries. */
  if (join->where_cond != nullptr &&
      join->query_block->original_tables_map == 1 &&
      join->query_block->original_tables_map == join_tab->table_ref->map() &&
      join->group_list.empty() &&
      !is_indexed_agg_distinct(join, &indexed_fields) &&
      !join->select_distinct) {
    bool use_skip_scan =
        hint_table_state(join->thd, join_tab->table_ref, SKIP_SCAN_HINT_ENUM,
                         OPTIMIZER_SKIP_SCAN);
    /*
      if skip_scan for a table is off, and the hint is applicable to all
      indexes, skip processing for possible keys. If the hint has index
      mentioned then skip_scan can be used with other indexes.
    */
    if (!use_skip_scan && join_tab->table_ref->opt_hints_table != nullptr &&
        join_tab->table_ref->opt_hints_table
            ->get_compound_key_hint(SKIP_SCAN_HINT_ENUM)
            ->is_key_map_clear_all())
      return;
    join->where_cond->walk(&Item::collect_item_field_processor,
                           enum_walk::POSTFIX, (uchar *)&indexed_fields);
    Key_map possible_keys;
    possible_keys.set_all();
    join_tab->skip_scan_keys.clear_all();
    for (Item_field *cur_item : indexed_fields) {
      if (cur_item->used_tables() != join_tab->table_ref->map()) return;
      possible_keys.intersect(cur_item->field->part_of_key);
    }
    join_tab->skip_scan_keys.merge(possible_keys);
    cause = "skip_scan";
    return;
  }

  if (!join->group_list.empty()) {
    /* Collect all query fields referenced in the GROUP clause. */
    for (cur_group = join->group_list.order; cur_group;
         cur_group = cur_group->next)
      (*cur_group->item)
          ->walk(&Item::collect_item_field_processor, enum_walk::POSTFIX,
                 (uchar *)&indexed_fields);
    cause = "group_by";
  } else if (join->select_distinct) {
    /* Collect all query fields referenced in the SELECT clause. */
    for (Item *item : VisibleFields(*join->fields)) {
      item->walk(&Item::collect_item_field_processor, enum_walk::POSTFIX,
                 (uchar *)&indexed_fields);
    }
    cause = "distinct";
  } else if (join->tmp_table_param.sum_func_count &&
             is_indexed_agg_distinct(join, &indexed_fields)) {
    /*
      SELECT list with AGGFN(distinct col). The query qualifies for
      loose index scan, and is_indexed_agg_distinct() has already
      collected all referenced fields into indexed_fields.
    */
    join->streaming_aggregation = true;
    cause = "indexed_distinct_aggregate";
  } else
    return;

  if (indexed_fields.empty()) return;

  Key_map possible_keys = join_tab->table()->keys_in_use_for_query;
  possible_keys.merge(join_tab->table()->keys_in_use_for_group_by);

  /* Intersect the keys of all group fields. */
  for (Item_field *cur_item : indexed_fields) {
    if (cur_item->used_tables() != join_tab->table_ref->map()) {
      /*
        Doing GROUP BY or DISTINCT on a field in another table so no
        index in this table is usable
      */
      return;
    } else
      possible_keys.intersect(cur_item->field->part_of_key);
  }

  /*
    At this point, possible_keys has key bits set only for usable
    indexes because indexed_fields is non-empty and if any of the
    fields belong to a different table the function would exit in the
    loop above.
  */

  if (!possible_keys.is_clear_all() &&
      !possible_keys.is_subset(join_tab->const_keys)) {
    trace_indexes_added_group_distinct(&join->thd->opt_trace, join_tab,
                                       possible_keys, cause);
    join_tab->const_keys.merge(possible_keys);
    join_tab->keys().merge(possible_keys);
  }

  assert(join_tab->const_keys.is_subset(join_tab->keys()));
}

/**
  Update keyuse array with all possible keys we can use to fetch rows.

  @param       thd            session context
  @param[out]  keyuse         Put here ordered array of Key_use structures
  @param       join_tab       Array in table number order
  @param       tables         Number of tables in join
  @param       cond           WHERE condition (note that the function analyzes
                              join_tab[i]->join_cond() too)
  @param       normal_tables  Tables not inner w.r.t some outer join (ones
                              for which we can make ref access based the WHERE
                              clause)
  @param       query_block     current SELECT
  @param[out]  sargables      Array of found sargable candidates

  @returns false if success, true if error
*/

static bool update_ref_and_keys(THD *thd, Key_use_array *keyuse,
                                JOIN_TAB *join_tab, uint tables, Item *cond,
                                table_map normal_tables,
                                Query_block *query_block,
                                SARGABLE_PARAM **sargables) {
  assert(cond == nullptr || cond->is_bool_func());
  uint and_level, i;
  Key_field *key_fields, *end, *field;
  size_t sz;
  uint m = max(query_block->max_equal_elems, 1U);
  JOIN *const join = query_block->join;
  /*
    We use the same piece of memory to store both  Key_field
    and SARGABLE_PARAM structure.
    Key_field values are placed at the beginning this memory
    while  SARGABLE_PARAM values are put at the end.
    All predicates that are used to fill arrays of Key_field
    and SARGABLE_PARAM structures have at most 2 arguments
    except BETWEEN predicates that have 3 arguments and
    IN predicates.
    This any predicate if it's not BETWEEN/IN can be used
    directly to fill at most 2 array elements, either of Key_field
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
    can be filled as this predicate is considered as
    saragable with respect to each of its argument.
    An IN predicate can require at most 1 element as currently
    it is considered as sargable only for its first argument.
    Multiple equality can add  elements that are filled after
    substitution of field arguments by equal fields. There
    can be not more than query_block->max_equal_elems such
    substitutions.
  */
  sz = max(sizeof(Key_field), sizeof(SARGABLE_PARAM)) *
       (((query_block->cond_count + 1) * 2 + query_block->between_count) * m +
        1);
  if (!(key_fields = (Key_field *)thd->alloc(sz)))
    return true; /* purecov: inspected */
  and_level = 0;
  field = end = key_fields;
  *sargables = (SARGABLE_PARAM *)key_fields +
               (sz - sizeof((*sargables)[0].field)) / sizeof(SARGABLE_PARAM);
  /* set a barrier for the array of SARGABLE_PARAM */
  (*sargables)[0].field = nullptr;

  if (cond) {
    if (add_key_fields(thd, join, &end, &and_level, cond, normal_tables,
                       sargables))
      return true;

    // The relevant secondary engines don't support antijoin, so don't enable
    // this optimization for them.
    if (thd->secondary_engine_optimization() !=
        Secondary_engine_optimization::SECONDARY) {
      for (Key_field *fld = field; fld != end; fld++) {
        /* Mark that we can optimize LEFT JOIN */
        if (fld->val->type() == Item::NULL_ITEM &&
            !fld->item_field->field->is_nullable()) {
          /*
            Example:
            SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.a WHERE t2.a IS NULL;
            this just wants rows of t1 where t1.a does not exist in t2.
          */
          fld->item_field->field->table->reginfo.not_exists_optimize = true;
        }
      }
    }
  }

  for (i = 0; i < tables; i++) {
    /*
      Block the creation of keys for inner tables of outer joins.
      Here only the outer joins that can not be converted to
      inner joins are left and all nests that can be eliminated
      are flattened.
      In the future when we introduce conditional accesses
      for inner tables in outer joins these keys will be taken
      into account as well.
    */
    if (join_tab[i].join_cond()) {
      if (add_key_fields(thd, join, &end, &and_level, join_tab[i].join_cond(),
                         join_tab[i].table_ref->map(), sargables))
        return true;
    }
  }

  /* Process ON conditions for the nested joins */
  for (Table_ref *tl : query_block->m_table_nest) {
    if (tl->nested_join &&
        add_key_fields_for_nj(thd, join, tl, &end, &and_level, sargables))
      return true;
  }

  /* Generate keys descriptions for derived tables */
  if (query_block->materialized_derived_table_count) {
    if (join->generate_derived_keys()) return true;
  }
  /* fill keyuse with found key parts */
  for (; field != end; field++) {
    if (add_key_part(keyuse, field)) return true;
  }

  if (query_block->ftfunc_list->elements) {
    if (add_ft_keys(keyuse, cond, normal_tables, true)) return true;
  }

  /*
    Sort the array of possible keys and remove the following key parts:
    - ref if there is a keypart which is a ref and a const.
      (e.g. if there is a key(a,b) and the clause is a=3 and b=7 and b=t2.d,
      then we skip the key part corresponding to b=t2.d)
    - keyparts without previous keyparts
      (e.g. if there is a key(a,b,c) but only b < 5 (or a=2 and c < 3) is
      used in the query, we drop the partial key parts from consideration).
    Special treatment for ft-keys.
  */
  if (!keyuse->empty()) {
    Key_use *save_pos, *use;

    std::stable_sort(keyuse->begin(), keyuse->begin() + keyuse->size(),
                     sort_keyuse);

    const Key_use key_end(nullptr, nullptr, 0, 0, 0, 0, 0, 0, false, nullptr,
                          0);
    if (keyuse->push_back(key_end))  // added for easy testing
      return true;

    use = save_pos = keyuse->begin();
    const Key_use *prev = &key_end;
    bool found_eq_constant = false;
    for (i = 0; i < keyuse->size() - 1; i++, use++) {
      TABLE *const table = use->table_ref->table;
      if (use->val->const_for_execution() &&
          use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
        table->const_key_parts[use->key] |= use->keypart_map;
      if (use->keypart != FT_KEYPART) {
        if (use->key == prev->key && use->table_ref == prev->table_ref) {
          if (prev->keypart + 1 < use->keypart ||
              (prev->keypart == use->keypart && found_eq_constant))
            continue;                  /* remove */
        } else if (use->keypart != 0)  // First found must be 0
          continue;
      }

      /*
        Protect against self assignment.
        The compiler *may* generate a call to memcpy() to do the assignment,
        and that is undefined behaviour (memory overlap).
       */
      if (save_pos != use) *save_pos = *use;
      prev = use;
      found_eq_constant = use->val->const_for_execution();
      /* Save ptr to first use */
      if (!table->reginfo.join_tab->keyuse())
        table->reginfo.join_tab->set_keyuse(save_pos);
      table->reginfo.join_tab->checked_keys.set_bit(use->key);
      save_pos++;
    }
    i = (uint)(save_pos - keyuse->begin());
    keyuse->at(i) = key_end;
    keyuse->chop(i);
  }
  print_keyuse_array(thd, &thd->opt_trace, keyuse);
  /*
    Number of functions here call val_x() methods, which might throw an error.
    Catch those errors here.
  */
  return thd->is_error();
}

/**
  Create a keyuse array for a table with a primary key.
  To be used when creating a materialized temporary table.

  @param thd         THD pointer, for memory allocation
  @param keyparts    Number of key parts in the primary key
  @param fields      fields
  @param outer_exprs List of items used for key lookup

  @return Pointer to created keyuse array, or NULL if error
*/
Key_use_array *create_keyuse_for_table(
    THD *thd, uint keyparts, Item_field **fields,
    const mem_root_deque<Item *> &outer_exprs) {
  void *mem = thd->alloc(sizeof(Key_use_array));
  if (!mem) return nullptr;
  Key_use_array *keyuses = new (mem) Key_use_array(thd->mem_root);

  auto outer_expr_it = outer_exprs.begin();

  for (uint keypartno = 0; keypartno < keyparts; keypartno++) {
    Item *const item = *outer_expr_it++;
    Key_field key_field(fields[keypartno], item, 0, 0, true,
                        // null_rejecting must be true for field items only,
                        // add_not_null_conds() is incapable of handling
                        // other item types.
                        (item->type() == Item::FIELD_ITEM), nullptr, UINT_MAX);
    if (add_key_part(keyuses, &key_field)) return nullptr;
  }
  const Key_use key_end(nullptr, nullptr, 0, 0, 0, 0, 0, 0, false, nullptr, 0);
  if (keyuses->push_back(key_end))  // added for easy testing
    return nullptr;

  return keyuses;
}

/**
  Move const tables first in the position array.

  Increment the number of const tables and set same basic properties for the
  const table.
  A const table looked up by a key has type JT_CONST.
  A const table with a single row has type JT_SYSTEM.

  @param tab    Table that is designated as a const table
  @param key    The key definition to use for this table (NULL if table scan)
*/

void JOIN::mark_const_table(JOIN_TAB *tab, Key_use *key) {
  POSITION *const position = positions + const_tables;
  position->table = tab;
  position->key = key;
  position->rows_fetched = 1.0;  // This is a const table
  position->filter_effect = 1.0;
  position->prefix_rowcount = 1.0;
  position->read_cost = 0.0;
  position->ref_depend_map = 0;
  position->loosescan_key = MAX_KEY;  // Not a LooseScan
  position->sj_strategy = SJ_OPT_NONE;
  positions->use_join_buffer = false;

  // Move the const table as far down as possible in best_ref
  JOIN_TAB **pos = best_ref + const_tables + 1;
  for (JOIN_TAB *next = best_ref[const_tables]; next != tab; pos++) {
    JOIN_TAB *const tmp = pos[0];
    pos[0] = next;
    next = tmp;
  }
  best_ref[const_tables] = tab;

  tab->set_type(key ? JT_CONST : JT_SYSTEM);

  const_table_map |= tab->table_ref->map();

  const_tables++;
}

void JOIN::make_outerjoin_info() {
  DBUG_TRACE;

  assert(query_block->outer_join);
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  query_block->reset_nj_counters();

  for (uint i = const_tables; i < tables; ++i) {
    JOIN_TAB *const tab = best_ref[i];
    TABLE *const table = tab->table();
    if (!table) continue;

    Table_ref *const tbl = tab->table_ref;
    /*
      If 'tbl' is inside a SJ/AJ nest served by materialization, we must
      limit setting first_inner, last_inner and first_upper for join nests
      inside the materialized table. Indeed it is the SJ-tmp table, and not
      'tbl', which interacts with the nests outer to the SJ/AJ nest.
    */
    const bool sj_mat_inner =
        sj_is_materialize_strategy(tab->get_sj_strategy());

    if (tbl->outer_join) {
      /*
        Table tab is the only one inner table for outer join.
        (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a
        is in the query above.)
      */
      tab->set_last_inner(i);
      tab->set_first_inner(i);
      tab->init_join_cond_ref(tbl);
      tab->cond_equal = tbl->cond_equal;
      /*
        If this outer join nest is embedded in another join nest,
        link the join-tabs:
      */
      Table_ref *const outer_join_nest = tbl->outer_join_nest();
      if (outer_join_nest) {
        assert(outer_join_nest->nested_join->first_nested != NO_PLAN_IDX);
        if (!sj_mat_inner ||
            (tab->emb_sj_nest->sj_inner_tables &
             best_ref[outer_join_nest->nested_join->first_nested]
                 ->table_ref->map()))
          tab->set_first_upper(outer_join_nest->nested_join->first_nested);
      }
    }
    for (Table_ref *embedding = tbl->embedding; embedding;
         embedding = embedding->embedding) {
      // When reaching the outer tables of the materialized temporary table,
      // the decoration for this table is complete.
      if (sj_mat_inner && embedding == tab->emb_sj_nest) break;
      // Ignore join nests that are not outer join nests:
      if (!embedding->join_cond_optim()) continue;
      NESTED_JOIN *const nested_join = embedding->nested_join;
      if (!nested_join->nj_counter) {
        /*
          Table tab is the first inner table for nested_join.
          Save reference to it in the nested join structure.
        */
        nested_join->first_nested = i;
        // The table's condition is set to point to the join nest's condition
        tab->init_join_cond_ref(embedding);
        tab->cond_equal = tbl->cond_equal;

        Table_ref *const outer_join_nest = embedding->outer_join_nest();
        if (outer_join_nest) {
          assert(outer_join_nest->nested_join->first_nested != NO_PLAN_IDX);
          if (!sj_mat_inner ||
              (tab->emb_sj_nest->sj_inner_tables &
               best_ref[outer_join_nest->nested_join->first_nested]
                   ->table_ref->map()))
            tab->set_first_upper(outer_join_nest->nested_join->first_nested);
        }
      }
      if (tab->first_inner() == NO_PLAN_IDX)
        tab->set_first_inner(nested_join->first_nested);
      /*
        If including the sj-mat tmp table, this also implicitly
        includes the inner tables of the sj-nest.
      */
      nested_join->nj_counter +=
          tab->sj_mat_exec() ? tab->sj_mat_exec()->table_count : 1;
      if (nested_join->nj_counter < nested_join->nj_total) break;
      // Table tab is the last inner table for nested join.
      best_ref[nested_join->first_nested]->set_last_inner(i);
    }
  }
}

/**
  Build a condition guarded by match variables for embedded outer joins.
  When generating a condition for a table as part of an outer join condition
  or the WHERE condition, the table in question may also be part of an
  embedded outer join. In such cases, the condition must be guarded by
  the match variable for this embedded outer join. Such embedded outer joins
  may also be recursively embedded in other joins.

  The function recursively adds guards for a condition ascending from tab
  to root_tab, which is the first inner table of an outer join,
  or NULL if the condition being handled is the WHERE clause.

  @param join      the current join
  @param idx       index of the first inner table for the inner-most outer join
  @param cond      the predicate to be guarded (must be set)
  @param root_idx  index of the inner table to stop at
                   (is NO_PLAN_IDX if this is the WHERE clause)

  @return
    -  pointer to the guarded predicate, if success
    -  NULL if error
*/

static Item *add_found_match_trig_cond(JOIN *join, plan_idx idx, Item *cond,
                                       plan_idx root_idx) {
  ASSERT_BEST_REF_IN_JOIN_ORDER(join);
  assert(cond->is_bool_func());

  for (; idx != root_idx; idx = join->best_ref[idx]->first_upper()) {
    if (!(cond = new Item_func_trig_cond(cond, nullptr, join, idx,
                                         Item_func_trig_cond::FOUND_MATCH)))
      return nullptr;

    cond->quick_fix_field();
    cond->update_used_tables();
  }

  return cond;
}

/**
   Helper for JOIN::attach_join_conditions().
   Attaches bits of 'join_cond' to each table in the range [first_inner,
   last_tab], with proper guards.
   If 'sj_mat_cond' is true, we do not see first_inner (and tables on the same
   level of it) as inner to anything, as they're at the top from the POV of
   the materialization of the tmp table. So, if the SJ-mat nest is A LJ B,
   A will get a part of condition without any guard; B will get another part
   with a guard on A->found_match. It's like pushing a WHERE.
*/
bool JOIN::attach_join_condition_to_nest(plan_idx first_inner,
                                         plan_idx last_tab, Item *join_cond,
                                         bool is_sj_mat_cond) {
  /*
    Add the constant part of the join condition to the first inner table
    of the outer join.
  */
  Item *cond =
      make_cond_for_table(thd, join_cond, const_table_map, table_map(0), false);
  if (cond) {
    if (!is_sj_mat_cond) {
      cond = new Item_func_trig_cond(cond, nullptr, this, first_inner,
                                     Item_func_trig_cond::IS_NOT_NULL_COMPL);
      if (!cond) return true;
      if (cond->fix_fields(thd, nullptr)) return true;
    }
    if (best_ref[first_inner]->and_with_condition(cond)) return true;
  }
  /*
    Split the non-constant part of the join condition into parts that
    can be attached to the inner tables of the outer join.
  */
  for (plan_idx i = first_inner; i <= last_tab; ++i) {
    table_map prefix_tables = best_ref[i]->prefix_tables();
    table_map added_tables = best_ref[i]->added_tables();

    /*
      When handling the first inner table of an outer join, we may also
      reference all tables ahead of this table:
    */
    if (i == first_inner) added_tables = prefix_tables;
    /*
      We need RAND_TABLE_BIT on the last inner table, in case there is a
      non-deterministic function in the join condition.
      (RAND_TABLE_BIT is set for the last table of the join plan,
      but this is not sufficient for join conditions, which may have a
      last inner table that is ahead of the last table of the join plan).
    */
    if (i == last_tab) {
      prefix_tables |= RAND_TABLE_BIT;
      added_tables |= RAND_TABLE_BIT;
    }
    cond =
        make_cond_for_table(thd, join_cond, prefix_tables, added_tables, false);
    if (cond == nullptr) continue;
    /*
      If the table is part of an outer join that is embedded in the
      outer join currently being processed, wrap the condition in
      triggered conditions for match variables of such embedded outer joins.
    */
    if (!(cond = add_found_match_trig_cond(
              this, best_ref[i]->first_inner(), cond,
              is_sj_mat_cond ? NO_PLAN_IDX : first_inner)))
      return true;

    if (!is_sj_mat_cond) {
      // Add the guard turning the predicate off for the null-complemented row.
      cond = new Item_func_trig_cond(cond, nullptr, this, first_inner,
                                     Item_func_trig_cond::IS_NOT_NULL_COMPL);
      if (!cond) return true;
      if (cond->fix_fields(thd, nullptr)) return true;
    }
    // Add the generated condition to the existing table condition
    if (best_ref[i]->and_with_condition(cond)) return true;
  }
  return false;
}

/**
  Attach outer join conditions to generated table conditions in an optimal way.

  @param last_tab - Last table that has been added to the current plan.
                    Pre-condition: If this is the last inner table of an outer
                    join operation, a join condition is attached to the first
                    inner table of that outer join operation.

  @return false if success, true if error.

  Outer join conditions are attached to individual tables, but we can analyze
  those conditions only when reaching the last inner table of an outer join
  operation. Notice also that a table can be last within several outer join
  nests, hence the outer for() loop of this function.

  Example:
    SELECT * FROM t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) ON t1.a=t2.a

    Table t3 is last both in the join nest (t2 - t3) and in (t1 - (t2 - t3))
    Thus, join conditions for both join nests will be evaluated when reaching
    this table.

  For each outer join operation processed, the join condition is split
  optimally over the inner tables of the outer join. The split-out conditions
  are later referred to as table conditions (but note that several table
  conditions stemming from different join operations may be combined into
  a composite table condition).

  Example:
    Consider the above query once more.
    The predicate t1.a=t2.a can be evaluated when rows from t1 and t2 are ready,
    ie at table t2. The predicate t2.a=t3.a can be evaluated at table t3.

  Each non-constant split-out table condition is guarded by a match variable
  that enables it only when a matching row is found for all the embedded
  outer join operations.

  Each split-out table condition is guarded by a variable that turns the
  condition off just before a null-complemented row for the outer join
  operation is formed. Thus, the join condition will not be checked for
  the null-complemented row.
*/

bool JOIN::attach_join_conditions(plan_idx last_tab) {
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  JOIN_TAB *lt = best_ref[last_tab];

  for (plan_idx first_inner = lt->first_inner();
       first_inner != NO_PLAN_IDX &&
       best_ref[first_inner]->last_inner() == last_tab;
       first_inner = best_ref[first_inner]->first_upper()) {
    /*
      Table last_tab is the last inner table of an outer join, locate
      the corresponding join condition from the first inner table of the
      same outer join:
    */
    Item *const join_cond = best_ref[first_inner]->join_cond();
    assert(join_cond);
    if (attach_join_condition_to_nest(first_inner, last_tab, join_cond, false))
      return true;
  }
  if (sj_is_materialize_strategy(lt->get_sj_strategy())) {
    plan_idx mat_tbl = NO_PLAN_IDX;
    /*
      The SJ nest's condition contains both the SJ equality condition and the
       WHERE of the replaced subquery. This WHERE must be pushed to SJ-inner
       tables for evaluation during materialization!
    */
    Semijoin_mat_exec *sjm = nullptr;
    for (plan_idx j = last_tab;; j--) {
      sjm = best_ref[j]->sj_mat_exec();
      if (sjm && sjm->sj_nest == lt->emb_sj_nest) {
        // 'j' is the sj-mat tmp table
        mat_tbl = j;
        break;
      }
    }
    assert(sjm);
    if (sjm->inner_table_index + sjm->table_count - 1 == (uint)last_tab) {
      // we're at last table of sjmat nest
      Item *join_cond = best_ref[mat_tbl]->join_cond();
      Table_ref *tr = best_ref[mat_tbl]->table_ref;
      while (join_cond == nullptr && tr->embedding != nullptr &&
             tr->embedding->is_derived()) {
        // If subquery table(s) come from a derived table
        join_cond = tr->embedding->join_cond();
        tr = tr->embedding;
        assert(tr->is_merged());
      }
      if (join_cond && attach_join_condition_to_nest(sjm->inner_table_index,
                                                     last_tab, join_cond, true))
        return true;
    }
  }

  /*
    See if 'last_tab' is the first inner of an antijoin nest,
    then add a IS NULL condition on it.
    By attaching the condition to the first inner table, we know that if
    it is not satisfied we can just jump back to the table right before
    it.
  */
  if (lt->table_ref->embedding && lt->table_ref->embedding->is_aj_nest() &&
      last_tab == lt->first_inner() &&
      /*
        Exception: in A AJ (B LJ C) where C is a single table: there is no
        join nest for C as it's single; C->embedding is thus the AJ nest; but
        C->first_inner() is C (as it's the first inner of the LJ operation).
        In that case it's not the first inner table of the AJ.
        Catch this case:
      */
      !lt->table_ref->join_cond()) {
    Item *cond = new Item_func_false();
    if (!cond) return true;
    // This is a signal for JOIN::create_access_paths
    cond->item_name.set(antijoin_null_cond);
    /*
      For A AJ B ON COND, we need an IS NULL condition which
      is tested on the result rows of A LEFT JOIN B ON COND.
      It must be tested only after the "match status" of a row of B has been
      decided, so is wrapped in a condition triggered by B->found_match.
      To have it test IS NULL, it's wrapped in a triggered condition which is
      false if B is not NULL-complemented.
      We needn't wrap this condition with triggers from upper nests, hence the
      last argument of the call below.
    */
    cond = add_found_match_trig_cond(this, last_tab, cond, lt->first_upper());
    if (!cond) return true;
    cond = new Item_func_trig_cond(cond, nullptr, this, last_tab,
                                   Item_func_trig_cond::IS_NOT_NULL_COMPL);
    if (!cond) return true;
    if (cond->fix_fields(thd, nullptr)) return true;
    if (lt->and_with_condition(cond)) return true;
    lt->table()->reginfo.not_exists_optimize = true;

    // The relevant secondary engines don't support antijoin, so don't enable
    // this optimization for them.
    assert(thd->secondary_engine_optimization() !=
           Secondary_engine_optimization::SECONDARY);
  }

  return false;
}

/*****************************************************************************
  Remove calculation with tables that aren't yet read. Remove also tests
  against fields that are read through key where the table is not a
  outer join table.
  We can't remove tests that are made against columns which are stored
  in sorted order.
*****************************************************************************/

static Item *part_of_refkey(TABLE *table, Index_lookup *ref,
                            const Field *field) {
  uint ref_parts = ref->key_parts;
  if (ref_parts) {
    if (ref->has_guarded_conds()) return nullptr;

    const KEY_PART_INFO *key_part = table->key_info[ref->key].key_part;

    for (uint part = 0; part < ref_parts; part++, key_part++)
      if (field->eq(key_part->field) &&
          !(key_part->key_part_flag & HA_PART_KEY_SEG))
        return ref->items[part];
  }
  return nullptr;
}

bool ref_lookup_subsumes_comparison(THD *thd, Field *field, Item *right_item,
                                    bool can_evaluate, bool *subsumes) {
  *subsumes = false;
  right_item = right_item->real_item();
  if (right_item->type() == Item::FIELD_ITEM) {
    *subsumes = field->eq_def(down_cast<Item_field *>(right_item)->field);
    return false;
  } else if (right_item->type() == Item::CACHE_ITEM) {
    // remove equalities injected by IN->EXISTS transformation
    *subsumes = down_cast<Item_cache *>(right_item)->eq_def(field);
    return false;
  }
  bool right_is_null = true;
  if (can_evaluate) {
    assert(evaluate_during_optimization(right_item,
                                        thd->lex->current_query_block()));
    right_is_null = right_item->is_nullable() && right_item->is_null();
    if (thd->is_error()) return true;
  }
  if (!right_is_null) {
    /*
      We can remove all fields except:
      1. String data types:
       - For BINARY/VARBINARY fields with equality against a
         string: Ref access can return more rows than match the
         string. The reason seems to be that the string constant
         is not "padded" to the full length of the field when
         setting up ref access. @todo Change how ref access for
         BINARY/VARBINARY fields are done so that only qualifying
         rows are returned from the storage engine.
      2. Float data type: Comparison of float can differ
       - When we search "WHERE field=value" using an index,
         the "value" side is converted from double to float by
         Field_float::store(), then two floats are compared.
       - When we search "WHERE field=value" without indexes,
         the "field" side is converted from float to double by
         Field_float::val_real(), then two doubles are compared.
    */
    if (field->type() == MYSQL_TYPE_STRING &&
        field->charset()->pad_attribute == NO_PAD) {
      /*
        For "NO PAD" collations on CHAR columns, this function must return
        false, because removal of trailing space in CHAR columns makes the
        table value and the index value compare differently. As the column
        strips trailing spaces, it can return false candidates. Further
        comparison of the actual table values is required.
       */
      return false;
    }
    if (!((field->type() == MYSQL_TYPE_STRING ||  // 1
           field->type() == MYSQL_TYPE_VARCHAR) &&
          field->binary()) &&
        !(field->type() == MYSQL_TYPE_FLOAT && field->decimals() > 0))  // 2
    {
      *subsumes = !right_item->save_in_field_no_warnings(field, true);
      if (thd->is_error()) return true;
    }
  }
  return false;
}

/**
  @brief
  Identify redundant predicates.

  @details
  Test if the equality predicate 'left_item = right_item' is redundant
  due to a REF-access already being set up on the table, where 'left_item' is
  part of the REF-key being used, and 'right_item' is equal to the key value
  specified for that field in the key.
  In such cases the predicate is known to be 'true' for any rows retrieved
  from that table. Thus it is redundant.

  @param thd         session context
  @param left_item   The Item_field possibly being part of A ref-KEY.
  @param right_item  The equality value specified for 'left_item'.
  @param[out] redundant true if predicate is redundant, false otherwise

  @returns false if success, true if error

  @note See comments in reduce_cond_for_table() about careful
  usage/modifications of test_if_ref().
*/

static bool test_if_ref(THD *thd, Item_field *left_item, Item *right_item,
                        bool *redundant) {
  *redundant = false;
  if (left_item->depended_from)
    return false;  // don't even read join_tab of inner subquery!
  Field *field = left_item->field;
  JOIN_TAB *join_tab = field->table->reginfo.join_tab;
  if (join_tab == nullptr) return false;

  ASSERT_BEST_REF_IN_JOIN_ORDER(join_tab->join());

  // No need to change const test
  if (!field->table->const_table &&
      /* "ref_or_null" implements "x=y or x is null", not "x=y" */
      (join_tab->type() != JT_REF_OR_NULL)) {
    Item *ref_item = part_of_refkey(field->table, &join_tab->ref(), field);
    if (ref_item != nullptr && ref_item->eq(right_item, true)) {
      if (ref_lookup_subsumes_comparison(
              thd, field, right_item,
              right_item->const_for_execution() &&
                  !(thd->lex->is_explain() && right_item->has_stored_program()),
              redundant)) {
        return true;
      }
    }
  }
  return false;  // keep predicate
}

/**
  @brief
  Remove redundant predicates from condition, return the reduced condition.

  @details
  A predicate of the form 'field = value' may be redundant if the
  (ref-) access chosen for the table use an index containing 'field',
  where 'value' is specified as (part of) its ref-key. This method remove
  such redundant predicates, thus reducing the condition, possibly
  eliminating it entirely.

  If comparing 'values' against outer-joined tables, these are possibly
  'null-extended'. Thus the usage of these values in the ref-key, is not
  sufficient anymore to guarantee that 'field = value' is 'TRUE'.
  The 'null_extended' argument hold the table_map of any such possibly
  null-extended tables which are excluded from the above 'reduce' logic.

  Any tables referred in Item_func_trig_cond(FOUND_MATCH) conditions are
  aggregated into this null_extended table_map.

  @param thd            thread handler
  @param cond           The condition to be 'reduced'.
  @param null_extended  table_map of possibly null-extended outer-tables.
  @param[out] reduced   The condition with redundant predicates removed,
                        possibly nullptr.

  @returns              false if success, true if error
*/
static bool reduce_cond_for_table(THD *thd, Item *cond, table_map null_extended,
                                  Item **reduced) {
  DBUG_TRACE;
  DBUG_EXECUTE("where",
               print_where(current_thd, cond, "cond term", QT_ORDINARY););

  *reduced = nullptr;

  if (cond->type() == Item::COND_ITEM) {
    List<Item> *arguments = down_cast<Item_cond *>(cond)->argument_list();
    List_iterator<Item> li(*arguments);
    if (down_cast<Item_cond *>(cond)->functype() == Item_func::COND_AND_FUNC) {
      Item *item;
      while ((item = li++)) {
        Item *upd_item;
        if (reduce_cond_for_table(thd, item, null_extended, &upd_item)) {
          return true;
        }
        if (upd_item == nullptr) {
          li.remove();
        } else if (upd_item != item) {
          li.replace(upd_item);
        }
      }
      switch (arguments->elements) {
        case 0:
          return false;  // All 'true' -> And-cond true
        case 1:
          *reduced = arguments->head();
          return false;
      }
    } else {  // Or list
      Item *item;
      while ((item = li++)) {
        Item *upd_item;
        if (reduce_cond_for_table(thd, item, null_extended, &upd_item)) {
          return true;
        }
        if (upd_item == nullptr) {
          return false;  // Term 'true' -> entire Or-cond true
        } else if (upd_item != item) {
          li.replace(upd_item);
        }
      }
    }
  } else if (cond->type() == Item::FUNC_ITEM) {
    Item_func *func = down_cast<Item_func *>(cond);
    if (func->functype() == Item_func::TRIG_COND_FUNC) {
      Item_func_trig_cond *func_trig = down_cast<Item_func_trig_cond *>(func);
      if (func_trig->get_trig_type() == Item_func_trig_cond::FOUND_MATCH) {
        /*
          All inner-tables are possible null-extended when evaluating
          the 'FOUND_MATCH'. Thus, predicates embedded in this trig_cond,
          referring these tables, should not be eliminated.
          -> Add to null_extended map.
        */
        null_extended |= func_trig->get_inner_tables();
      }

      Item *cond_arg = func->arguments()[0];
      Item *upd_arg;
      if (reduce_cond_for_table(thd, cond_arg, null_extended, &upd_arg)) {
        return true;
      }
      if (upd_arg == nullptr) {
        return false;
      }
      func->arguments()[0] = upd_arg;
    } else if (func->functype() == Item_func::EQ_FUNC) {
      /*
        Remove equalities that are guaranteed to be true by use of 'ref' access
        method.
        Note that ref access implements "table1.field1 <=>
        table2.indexed_field2", i.e. if it passed a NULL field1, it will return
        NULL indexed_field2 if there are.
        Thus the equality "table1.field1 = table2.indexed_field2",
        is equivalent to "ref access AND table1.field1 IS NOT NULL"
        i.e. "ref access and proper setting/testing of ref->null_rejecting".
        Thus, we must be careful, that when we remove equalities below we also
        set ref->null_rejecting, and test it at execution; otherwise wrong NULL
        matches appear.
        So:
        - for the optimization phase, the code which is below, and the code in
        test_if_ref(), and in add_key_field(), must be kept in sync: if the
        applicability conditions in one place are relaxed, they should also be
        relaxed elsewhere.
        - for the execution phase, all possible execution methods must test
        ref->null_rejecting.
      */
      Item *left_item = func->arguments()[0]->real_item();
      Item *right_item = func->arguments()[1]->real_item();
      bool redundant = false;
      if (left_item->type() == Item::FIELD_ITEM &&
          !(left_item->used_tables() & null_extended) &&
          test_if_ref(thd, down_cast<Item_field *>(left_item), right_item,
                      &redundant)) {
        return true;
      }
      if (redundant) {
        return false;
      }
      if (right_item->type() == Item::FIELD_ITEM &&
          !(right_item->used_tables() & null_extended) &&
          test_if_ref(thd, down_cast<Item_field *>(right_item), left_item,
                      &redundant)) {
        return true;
      }
      if (redundant) {
        return false;
      }
    }
  }
  *reduced = cond;
  return false;
}

/**
  @brief
  Remove redundant predicates and cache constant expressions.

  @details
  Do a final round on pushed down table conditions and HAVING
  clause. Optimize them for faster execution by removing
  predicates being obsolete due to the access path selected
  for the table. Constant expressions are also cached
  to avoid evaluating them for each row being compared.

  @param thd     thread handler

  @returns false if success, true if error

  @note This function is run after conditions have been pushed down to
        individual tables, so transformation is applied to JOIN_TAB::condition
        and not to the WHERE condition.
*/
bool JOIN::finalize_table_conditions(THD *thd) {
  /*
    Unnecessary to reduce conditions for const tables as they are only
    evaluated once.
  */
  assert(!plan_is_const());
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_array trace_tables(trace, "finalizing_table_conditions");

  for (uint i = const_tables; i < tables; i++) {
    Item *condition = best_ref[i]->condition();
    if (condition == nullptr) continue;

    /*
      Table predicates known to be true by the selected
      (ref-)access method may be removed from the condition
    */
    Opt_trace_object trace_cond(trace);
    trace_cond.add_utf8_table(best_ref[i]->table_ref);
    trace_cond.add("original_table_condition", condition);

    /*
      Calculate the set of possibly NULL extended tables when 'condition'
      is evaluated. As it is evaluated on a found row from table, that
      table is subtracted from the nullable tables. Note that a FOUND_MATCH
      trigger is a special case, handled in reduce_cond_for_table().
    */
    const table_map null_extended =
        query_block->outer_join & ~best_ref[i]->table_ref->map();
    if (reduce_cond_for_table(thd, condition, null_extended, &condition)) {
      return true;
    }
    if (condition != nullptr) condition->update_used_tables();

    /*
      Cache constant expressions in table conditions.
      (Moved down from WHERE- and ON-clauses)
    */
    if (condition != nullptr) {
      cache_const_expr_arg cache_arg;
      cache_const_expr_arg *analyzer_arg = &cache_arg;
      condition = condition->compile(
          &Item::cache_const_expr_analyzer, (uchar **)&analyzer_arg,
          &Item::cache_const_expr_transformer, (uchar *)&cache_arg);
      if (condition == nullptr) return true;
    }

    trace_cond.add("final_table_condition   ", condition);
    best_ref[i]->set_condition(condition);
  }

  /* Cache constant expressions in HAVING-clauses. */
  if (having_cond != nullptr) {
    cache_const_expr_arg cache_arg;
    cache_const_expr_arg *analyzer_arg = &cache_arg;
    having_cond = having_cond->compile(
        &Item::cache_const_expr_analyzer, (uchar **)&analyzer_arg,
        &Item::cache_const_expr_transformer, (uchar *)&cache_arg);
    if (having_cond == nullptr) return true;
  }
  return false;
}

/**
  @brief
  Add keys to derived tables'/views' result tables in a list

  @details
  This function generates keys for all derived tables/views of the query_block
  to which this join corresponds to with help of the
  Table_ref:generate_keys function.

  @return false all keys were successfully added.
  @return true OOM error
*/

bool JOIN::generate_derived_keys() {
  assert(query_block->materialized_derived_table_count);

  for (Table_ref *table = query_block->leaf_tables; table;
       table = table->next_leaf) {
    table->derived_keys_ready = true;
    /* Process tables that aren't materialized yet. */
    if (table->uses_materialization() && !table->table->is_created() &&
        table->generate_keys())
      return true;
  }
  return false;
}

/**
  For each materialized derived table/view, informs every TABLE of the key it
  will (not) use, segregates used keys from unused keys in TABLE::key_info,
  and eliminates unused keys.
*/

void JOIN::finalize_derived_keys() {
  assert(query_block->materialized_derived_table_count);
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  table_map processed_tables = 0;

  for (uint i = 0; i < tables; i++) {
    TABLE *const table = best_ref[i]->table();
    Table_ref *const tr = best_ref[i]->table_ref;
    /*
      Process the table's key definitions if:
      1) it is a materialized derived table, and
      2) it is not yet instantiated, and
      3) it has some keys defined, and
      4) it has not yet been processed (may happen if there are more than one
         local references to the same CTE, which are processed on seeing the
         first reference).
    */
    if (table == nullptr || !tr->uses_materialization() ||  // (1)
        table->is_created() ||                              // (2)
        table->s->keys == 0 ||                              // (3)
        (processed_tables & tr->map())) {                   // (4)
      continue;
    }
    /*
      Collect all used keys before starting to shuffle them:
      First create a map from key number to the table using the key:
    */
    assert(table->s->keys <= MAX_INDEXES);
    TABLE *table_map[MAX_INDEXES];
    for (uint j = 0; j < table->s->keys; j++) {
      table_map[j] = nullptr;
    }

    Key_map used_keys;

    // Mark all unique indexes as in use, since they have an effect
    // (deduplication) whether any expression refers to them or not.
    // In particular, they are used if we want to materialize a UNION DISTINCT
    // directly into the derived table.
    for (uint key_idx = 0; key_idx < table->s->keys; ++key_idx) {
      if (table->key_info[key_idx].flags & HA_NOSAME) {
        used_keys.set_bit(key_idx);
      }
    }
    // Same for the hash key used for manual deduplication, if any.
    // (It always has index 0 if it exists.)
    if (table->hash_field) {
      used_keys.set_bit(0);
    }

    Derived_refs_iterator it(tr);

    while (TABLE *t = it.get_next()) {
      if (t->pos_in_table_list->query_block != query_block) {
        continue;
      }
      JOIN_TAB *jtab = t->reginfo.join_tab;
      Key_use *const keyuse = jtab->position()->key;
      if (keyuse != nullptr) {
        used_keys.set_bit(keyuse->key);
        table_map[keyuse->key] = t;
      } else {
        jtab->keys().clear_all();
        jtab->const_keys.clear_all();
        processed_tables |= t->pos_in_table_list->map();
      }
    }
    /*
      This call is required to establish the initial value for
      TABLE_SHARE::first_unused_tmp_key.
    */
    (void)table->s->find_first_unused_tmp_key(used_keys);

    // Process keys in increasing key order
    for (uint j = 0; j < table->s->keys; j++) {
      TABLE *const t = table_map[j];
      if (t == nullptr) continue;

      /*
        Eliminate possible keys created by this JOIN and which it doesn't use.
        Collect all keys of this table which are used by any reference in
        this query block. Any other query block doesn't matter as:
        - either it was optimized before, so it's not using a key we may
          want to drop.
        - or it was optimized in this same window, so:
          * either we own the window, then any key we may want to
            drop is not visible to it.
          * or it owns the window, then we are using only existing keys.
        - or it will be optimized after, so it's not using any key yet.

        used_keys is a mix of possible used keys and existing used keys.
      */
      if (t->pos_in_table_list->query_block != query_block) {
        continue;
      }

      JOIN_TAB *jtab = t->reginfo.join_tab;
      Key_use *const keyuse = jtab->position()->key;
      assert(keyuse != nullptr);

      // Also updates table->s->first_unused_tmp_key.
      uint new_idx = t->s->find_first_unused_tmp_key(used_keys);

      const uint old_idx = keyuse->key;
      assert(old_idx != new_idx);

      if (old_idx > new_idx) {
        assert(t->s->owner_of_possible_tmp_keys == query_block);
        Derived_refs_iterator it1(tr);
        while (TABLE *t1 = it1.get_next()) {
          /*
            Unlike the collection of used_keys, references from other query
            blocks must be considered here, as they need a key_info array
            consistent with the to-be-changed table->s->keys.
          */
          t1->move_tmp_key(old_idx, it1.is_first());
        }
        used_keys.clear_bit(old_idx);
        used_keys.set_bit(new_idx);
      } else {
        new_idx = old_idx;  // Index stays at same slot
      }

      /*
        If the key was created by earlier-optimized query blocks, and is
        already used by nonlocal references, those don't need any further
        update: they are already setup to use it and we're not moving the key.
        If the key was created by this query block, nonlocal references cannot
        possibly be referencing it.
        In both cases, only local references need to update their Key_use.
      */
      Derived_refs_iterator it2(tr);
      while (TABLE *t2 = it2.get_next()) {
        if (t2->pos_in_table_list->query_block != query_block) continue;
        JOIN_TAB *jt2 = t2->reginfo.join_tab;
        Key_use *ku2 = jt2->position()->key;
        if (ku2 != nullptr && ku2->key == old_idx) {
          processed_tables |= t2->pos_in_table_list->map();
          const bool key_is_const = jt2->const_keys.is_set(old_idx);
          // tab->keys() was never set, so must be set
          jt2->keys().clear_all();
          jt2->keys().set_bit(new_idx);
          jt2->const_keys.clear_all();
          if (key_is_const) jt2->const_keys.set_bit(new_idx);
          for (Key_use *kit = ku2;
               kit->table_ref == jt2->table_ref && kit->key == old_idx; kit++) {
            kit->key = new_idx;
          }
        }
      }
    }

    // Finally, we know how many keys remain in the table.
    if (table->s->owner_of_possible_tmp_keys != query_block) continue;

    // Release lock:
    table->s->owner_of_possible_tmp_keys = nullptr;
    it.rewind();
    while (TABLE *t = it.get_next()) {
      t->drop_unused_tmp_keys(it.is_first());
    }
  }
}

/**
  @brief
  Extract a condition that can be checked after reading given table

  @param thd        Current session.
  @param cond       Condition to analyze
  @param tables     Tables for which "current field values" are available
  @param used_table Table(s) that we are extracting the condition for (may
                    also include PSEUDO_TABLE_BITS, and may be zero)
  @param exclude_expensive_cond  Do not push expensive conditions

  @retval <>NULL Generated condition
  @retval = NULL Already checked, OR error

  @details
    Extract the condition that can be checked after reading the table(s)
    specified in @c used_table, given that current-field values for tables
    specified in @c tables bitmap are available.
    If @c used_table is 0, extract conditions for all tables in @c tables.

    This function can be used to extract conditions relevant for a table
    in a join order. Together with its caller, it will ensure that all
    conditions are attached to the first table in the join order where all
    necessary fields are available, and it will also ensure that a given
    condition is attached to only one table.
    To accomplish this, first initialize @c tables to the empty
    set. Then, loop over all tables in the join order, set @c used_table to
    the bit representing the current table, accumulate @c used_table into the
    @c tables set, and call this function. To ensure correct handling of
    const expressions and outer references, add the const table map and
    OUTER_REF_TABLE_BIT to @c used_table for the first table. To ensure
    that random expressions are evaluated for the final table, add
    RAND_TABLE_BIT to @c used_table for the final table.

    The function assumes that constant, inexpensive parts of the condition
    have already been checked. Constant, expensive parts will be attached
    to the first table in the join order, provided that the above call
    sequence is followed.

    The call order will ensure that conditions covering tables in @c tables
    minus those in @c used_table, have already been checked.

    The function takes into account that some parts of the condition are
    guaranteed to be true by employed 'ref' access methods (the code that
    does this is located at the end, search down for "EQ_FUNC").

  @note
    make_cond_for_info_schema() uses an algorithm similar to
    make_cond_for_table().
*/

Item *make_cond_for_table(THD *thd, Item *cond, table_map tables,
                          table_map used_table, bool exclude_expensive_cond) {
  /*
    May encounter an Item_cache_int as "condition" here, so cannot
    assert that it satisfies is_bool_func().
  */
  /*
    Ignore this condition if
     1. We are extracting conditions for a specific table, and
     2. that table is not referenced by the condition, but not if
     3. this is a constant condition not checked at optimization time and
        this is the first table we are extracting conditions for.
       (Assuming that used_table == tables for the first table.)
  */
  if (used_table &&                                     // 1
      !(cond->used_tables() & used_table) &&            // 2
      !(cond->is_expensive() && used_table == tables))  // 3
    return nullptr;

  if (cond->type() == Item::COND_ITEM) {
    if (((Item_cond *)cond)->functype() == Item_func::COND_AND_FUNC) {
      /* Create new top level AND item */
      Item_cond_and *new_cond = new Item_cond_and;
      if (!new_cond) return nullptr;
      List_iterator<Item> li(*((Item_cond *)cond)->argument_list());
      Item *item;
      while ((item = li++)) {
        Item *fix = make_cond_for_table(thd, item, tables, used_table,
                                        exclude_expensive_cond);
        if (fix) new_cond->argument_list()->push_back(fix);
      }
      switch (new_cond->argument_list()->elements) {
        case 0:
          return nullptr;  // Always true
        case 1:
          return new_cond->argument_list()->head();
        default:
          if (new_cond->fix_fields(thd, nullptr)) return nullptr;
          return new_cond;
      }
    } else {  // Or list
      Item_cond_or *new_cond = new Item_cond_or;
      if (!new_cond) return nullptr;
      List_iterator<Item> li(*((Item_cond *)cond)->argument_list());
      Item *item;
      while ((item = li++)) {
        Item *fix = make_cond_for_table(thd, item, tables, table_map(0),
                                        exclude_expensive_cond);
        if (!fix) return nullptr;  // Always true
        new_cond->argument_list()->push_back(fix);
      }
      if (new_cond->fix_fields(thd, nullptr)) return nullptr;
      return new_cond;
    }
  }

  /*
    Omit this condition if
     1. Some tables referred by the condition are not available, or
     2. We are extracting conditions for all tables, the condition is
        considered 'expensive', and we want to delay evaluation of such
        conditions to the execution phase.
  */
  if ((cond->used_tables() & ~tables) ||                                // 1
      (!used_table && exclude_expensive_cond && cond->is_expensive()))  // 2
    return nullptr;

  return cond;
}

/**
  Separates the predicates in a join condition and pushes them to the
  join step where all involved tables are available in the join prefix.
  ON clauses from JOIN expressions are also pushed to the most appropriate step.

  @param join Join object where predicates are pushed.

  @param cond Pointer to condition which may contain an arbitrary number of
              predicates, combined using AND, OR and XOR items.
              If NULL, equivalent to a predicate that returns true for all
              row combinations.


  @retval true  Found impossible WHERE clause, or out-of-memory
  @retval false Other
*/

static bool make_join_query_block(JOIN *join, Item *cond) {
  assert(cond == nullptr || cond->is_bool_func());
  THD *thd = join->thd;
  Opt_trace_context *const trace = &thd->opt_trace;
  DBUG_TRACE;
  ASSERT_BEST_REF_IN_JOIN_ORDER(join);

  // Add IS NOT NULL conditions to table conditions:
  if (add_not_null_conds(join)) return true;

  /*
    Extract constant conditions that are part of the WHERE clause.
    Constant parts of join conditions from outer joins are attached to
    the appropriate table condition in JOIN::attach_join_conditions().
  */
  if (cond) /* Because of GroupIndexSkipScanIterator */
  {         /* there may be a select without a cond. */
    if (join->primary_tables > 1)
      cond->update_used_tables();  // Table number may have changed
    if (join->plan_is_const() &&
        join->query_block->master_query_expression() ==
            thd->lex->unit)  // The outer-most query block
      join->const_table_map |= RAND_TABLE_BIT;
  }
  /*
    Extract conditions that depend on constant tables.
    The const part of the query's WHERE clause can be checked immediately
    and if it is not satisfied then the join has empty result
  */
  Item *const_cond = nullptr;
  if (cond)
    const_cond = make_cond_for_table(thd, cond, join->const_table_map,
                                     table_map(0), true);

  // Add conditions added by add_not_null_conds()
  for (uint i = 0; i < join->const_tables; i++) {
    if (and_conditions(&const_cond, join->best_ref[i]->condition()))
      return true;
  }
  DBUG_EXECUTE("where",
               print_where(thd, const_cond, "constants", QT_ORDINARY););
  if (const_cond != nullptr &&
      evaluate_during_optimization(const_cond, join->query_block)) {
    const bool const_cond_result = const_cond->val_int() != 0;
    if (thd->is_error()) return true;

    Opt_trace_object trace_const_cond(trace);
    trace_const_cond.add("condition_on_constant_tables", const_cond)
        .add("condition_value", const_cond_result);
    if (const_cond_result) {
      /*
        If all the tables referred by the condition are const tables and
        if the condition is not expensive, we can remove the where condition
        as it will always evaluate to "true".
      */
      if (join->plan_is_const() &&
          !(cond->used_tables() & ~join->const_table_map) &&
          !cond->is_expensive()) {
        DBUG_PRINT("info", ("Found always true WHERE condition"));
        join->where_cond = nullptr;
      }
    } else {
      DBUG_PRINT("info", ("Found impossible WHERE condition"));
      return true;
    }
  }

  /*
    Extract remaining conditions from WHERE clause and join conditions,
    and attach them to the most appropriate table condition. This means that
    a condition will be evaluated as soon as all fields it depends on are
    available. For outer join conditions, the additional criterion is that
    we must have determined whether outer-joined rows are available, or
    have been NULL-extended, see JOIN::attach_join_conditions() for details.
  */
  {
    Opt_trace_object trace_wrapper(trace);
    Opt_trace_object trace_conditions(trace, "attaching_conditions_to_tables");
    trace_conditions.add("original_condition", cond);
    Opt_trace_array trace_attached_comp(trace,
                                        "attached_conditions_computation");

    for (uint i = join->const_tables; i < join->tables; i++) {
      JOIN_TAB *const tab = join->best_ref[i];

      if (!tab->position()) continue;
      /*
        first_inner is the X in queries like:
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
      */
      const plan_idx first_inner = tab->first_inner();
      const table_map used_tables = tab->prefix_tables();
      const table_map current_map = tab->added_tables();
      Item *tmp = nullptr;

      if (cond)
        tmp = make_cond_for_table(thd, cond, used_tables, current_map, false);
      /* Add conditions added by add_not_null_conds(). */
      if (and_conditions(&tmp, tab->condition())) return true;

      if (cond && !tmp && tab->range_scan()) {  // Outer join
        assert(tab->type() == JT_RANGE || tab->type() == JT_INDEX_MERGE);
        /*
          Hack to handle the case where we only refer to a table
          in the ON part of an OUTER JOIN. In this case we want the code
          below to check if we should use 'quick' instead.
        */
        DBUG_PRINT("info", ("Item_func_true"));
        tmp = new Item_func_true();  // Always true
      }
      if (tmp || !cond || tab->type() == JT_REF ||
          tab->type() == JT_REF_OR_NULL || tab->type() == JT_EQ_REF ||
          first_inner != NO_PLAN_IDX) {
        DBUG_EXECUTE("where",
                     print_where(thd, tmp, tab->table()->alias, QT_ORDINARY););
        /*
          If tab is an inner table of an outer join operation,
          add a match guard to the pushed down predicate.
          The guard will turn the predicate on only after
          the first match for outer tables is encountered.
        */
        if (cond && tmp) {
          /*
            Because of GroupIndexSkipScanIterator there may be a select without
            a cond, so neutralize the hack above.
          */
          if (!(tmp = add_found_match_trig_cond(join, first_inner, tmp,
                                                NO_PLAN_IDX)))
            return true;
          tab->set_condition(tmp);
        } else {
          tab->set_condition(nullptr);
        }

        DBUG_EXECUTE("where",
                     print_where(thd, tmp, tab->table()->alias, QT_ORDINARY););

        if (tab->range_scan()) {
          if (tab->needed_reg.is_clear_all() && tab->type() != JT_CONST) {
            /*
              We keep (for now) the QUICK AM calculated in
              get_quick_record_count().
            */
          } else {
            destroy(tab->range_scan());
            tab->set_range_scan(nullptr);
          }
        }

        if ((tab->type() == JT_ALL || tab->type() == JT_RANGE ||
             tab->type() == JT_INDEX_MERGE || tab->type() == JT_INDEX_SCAN) &&
            tab->use_quick != QS_RANGE) {
          /*
            We plan to scan (table/index/range scan).
            Check again if we should use an index. We can use an index if:

            1a) There is a condition that range optimizer can work on, and
            1b) There are non-constant conditions on one or more keys, and
            1c) Some of the non-constant fields may have been read
                already. This may be the case if this is not the first
                table in the join OR this is a subselect with
                non-constant conditions referring to an outer table
                (dependent subquery)
                or,
            2a) There are conditions only relying on constants
            2b) This is the first non-constant table
            2c) There is a limit of rows to read that is lower than
                the fanout for this table, predicate filters included
                (i.e., the estimated number of rows that will be
                produced for this table per row combination of
                previous tables)
            2d) The query is NOT run with FOUND_ROWS() (because in that
                case we have to scan through all rows to count them anyway)
          */
          enum {
            DONT_RECHECK,
            NOT_FIRST_TABLE,
            LOW_LIMIT
          } recheck_reason = DONT_RECHECK;

          assert(tab->const_keys.is_subset(tab->keys()));

          const join_type orig_join_type = tab->type();
          const AccessPath *const orig_range_scan = tab->range_scan();

          if (cond &&                              // 1a
              (tab->keys() != tab->const_keys) &&  // 1b
              (i > 0 ||                            // 1c
               (join->query_block->master_query_expression()->item &&
                cond->is_outer_reference())))
            recheck_reason = NOT_FIRST_TABLE;
          else if (!tab->const_keys.is_clear_all() &&  // 2a
                   i == join->const_tables &&          // 2b
                   (join->query_expression()->select_limit_cnt <
                    (tab->position()->rows_fetched *
                     tab->position()->filter_effect)) &&  // 2c
                   !join->calc_found_rows)                // 2d
            recheck_reason = LOW_LIMIT;

          // Don't recheck if the storage engine does not support index access.
          if ((tab->table()->file->ha_table_flags() & HA_NO_INDEX_ACCESS) != 0)
            recheck_reason = DONT_RECHECK;

          if (tab->position()->sj_strategy == SJ_OPT_LOOSE_SCAN) {
            /*
              Semijoin loose scan has settled for a certain index-based access
              method with suitable characteristics, don't substitute it.
            */
            recheck_reason = DONT_RECHECK;
          }

          if (recheck_reason != DONT_RECHECK) {
            Opt_trace_object trace_one_table(trace);
            trace_one_table.add_utf8_table(tab->table_ref);
            Opt_trace_object trace_table(trace, "rechecking_index_usage");
            if (recheck_reason == NOT_FIRST_TABLE)
              trace_table.add_alnum("recheck_reason", "not_first_table");
            else
              trace_table.add_alnum("recheck_reason", "low_limit")
                  .add("limit", join->query_expression()->select_limit_cnt)
                  .add("row_estimate", tab->position()->rows_fetched *
                                           tab->position()->filter_effect);

            /* Join with outer join condition */
            Item *orig_cond = tab->condition();
            tab->and_with_condition(tab->join_cond());

            /*
              We can't call sel->cond->fix_fields,
              as it will break tab->join_cond() if it's AND condition
              (fix_fields currently removes extra AND/OR levels).
              Yet attributes of the just built condition are not needed.
              Thus we call sel->cond->quick_fix_field for safety.
            */
            if (tab->condition() && !tab->condition()->fixed)
              tab->condition()->quick_fix_field();

            Key_map usable_keys = tab->keys();
            enum_order interesting_order = ORDER_NOT_RELEVANT;

            if (recheck_reason == LOW_LIMIT) {
              int read_direction = 0;

              /*
                If the current plan is to use range, then check if the
                already selected index provides the order dictated by the
                ORDER BY clause.
              */
              if (tab->range_scan() &&
                  used_index(tab->range_scan()) != MAX_KEY) {
                const uint ref_key = used_index(tab->range_scan());
                bool skip_quick;
                read_direction = test_if_order_by_key(
                    &join->order, tab->table(), ref_key, nullptr, &skip_quick);
                if (skip_quick) read_direction = 0;
                /*
                  If the index provides order there is no need to recheck
                  index usage; we already know from the former call to
                  test_quick_select() that a range scan on the chosen
                  index is cheapest. Note that previous calls to
                  test_quick_select() did not take order direction
                  (ASC/DESC) into account, so in case of DESC ordering
                  we still need to recheck.
                */
                if (read_direction == 1 ||
                    (read_direction == -1 &&
                     reverse_sort_possible(tab->range_scan()) &&
                     !make_reverse(get_used_key_parts(tab->range_scan()),
                                   tab->range_scan()))) {
                  recheck_reason = DONT_RECHECK;
                }
              }

              // We do a cost based search for an ordering index here, if:
              // 1. "prefer_ordering_index" switch is on or
              // 2. An index is forced for order by or
              // 3. Optimizer has chosen to do table scan.
              if (recheck_reason != DONT_RECHECK &&
                  (thd->optimizer_switch_flag(
                       OPTIMIZER_SWITCH_PREFER_ORDERING_INDEX) ||
                   tab->table()->force_index_order || tab->type() == JT_ALL)) {
                DBUG_EXECUTE_IF("prefer_ordering_index_check", {
                  const char act[] =
                      "now wait_for "
                      "signal.prefer_ordering_index_check_continue";
                  assert(!debug_sync_set_action(current_thd,
                                                STRING_WITH_LEN(act)));
                });

                int best_key = -1;
                ha_rows select_limit =
                    join->query_expression()->select_limit_cnt;

                /* Use index specified in FORCE INDEX FOR ORDER BY, if any. */
                if (tab->table()->force_index_order)
                  usable_keys.intersect(tab->table()->keys_in_use_for_order_by);

                // Do a cost based search on the indexes that give sort order.
                test_if_cheaper_ordering(
                    tab, &join->order, tab->table(), usable_keys, -1,
                    select_limit, &best_key, &read_direction, &select_limit);
                if (best_key < 0)
                  recheck_reason = DONT_RECHECK;  // No usable keys
                else {
                  // Only usable_key is the best_key chosen
                  usable_keys.clear_all();
                  usable_keys.set_bit(best_key);
                  interesting_order =
                      (read_direction == -1 ? ORDER_DESC : ORDER_ASC);
                }
              }
            }

            bool search_if_impossible = recheck_reason != DONT_RECHECK;
            if (search_if_impossible) {
              if (tab->range_scan()) {
                destroy(tab->range_scan());
                tab->set_type(JT_ALL);
              }
              AccessPath *range_scan;
              MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                                     thd->variables.range_alloc_block_size);
              search_if_impossible =
                  test_quick_select(
                      thd, thd->mem_root, &temp_mem_root, usable_keys,
                      used_tables & ~tab->table_ref->map(), 0,
                      join->calc_found_rows
                          ? HA_POS_ERROR
                          : join->query_expression()->select_limit_cnt,
                      false,  // don't force quick range
                      interesting_order, tab->table(),
                      tab->skip_records_in_range(), tab->condition(),
                      &tab->needed_reg, tab->table()->force_index,
                      join->query_block, &range_scan) < 0;
              tab->set_range_scan(range_scan);
            }
            tab->set_condition(orig_cond);
            if (search_if_impossible) {
              /*
                Before reporting "Impossible WHERE" for the whole query
                we have to check isn't it only "impossible ON" instead
              */
              if (!tab->join_cond())
                return true;  // No ON, so it's really "impossible WHERE"
              Opt_trace_object trace_without_on(trace, "without_ON_clause");
              if (tab->range_scan()) {
                destroy(tab->range_scan());
                tab->set_type(JT_ALL);
              }
              AccessPath *range_scan;
              MEM_ROOT temp_mem_root(key_memory_test_quick_select_exec,
                                     thd->variables.range_alloc_block_size);
              const bool impossible_where =
                  test_quick_select(
                      thd, thd->mem_root, &temp_mem_root, tab->keys(),
                      used_tables & ~tab->table_ref->map(), 0,
                      join->calc_found_rows
                          ? HA_POS_ERROR
                          : join->query_expression()->select_limit_cnt,
                      false,  // don't force quick range
                      ORDER_NOT_RELEVANT, tab->table(),
                      tab->skip_records_in_range(), tab->condition(),
                      &tab->needed_reg, tab->table()->force_index,
                      join->query_block, &range_scan) < 0;
              tab->set_range_scan(range_scan);
              if (impossible_where) return true;  // Impossible WHERE
            }

            /*
              Access method changed. This is after deciding join order
              and access method for all other tables so the info
              updated below will not have any effect on the execution
              plan.
            */
            if (tab->range_scan())
              tab->set_type(calc_join_type(tab->range_scan()));

          }  // end of "if (recheck_reason != DONT_RECHECK)"

          if (!tab->table()->quick_keys.is_subset(tab->checked_keys) ||
              !tab->needed_reg.is_subset(tab->checked_keys)) {
            tab->keys().merge(tab->table()->quick_keys);
            tab->keys().merge(tab->needed_reg);

            /*
              The logic below for assigning tab->use_quick is strange.
              It bases the decision of which access method to use
              (dynamic range, range, scan) based on seemingly
              unrelated information like the presence of another index
              with too bad selectivity to be used.

              Consider the following scenario:

              The join optimizer has decided to use join order
              (t1,t2), and 'tab' is currently t2. Further, assume that
              there is a join condition between t1 and t2 using some
              range operator (e.g. "t1.x < t2.y").

              It has been decided that a table scan is best for t2.
              make_join_query_block() then reran the range optimizer a few
              lines up because there is an index 't2.good_idx'
              covering the t2.y column. If 'good_idx' is the only
              index in t2, the decision below will be to use dynamic
              range. However, if t2 also has another index 't2.other'
              which the range access method can be used on but
              selectivity is bad (#rows estimate is high), then table
              scan is chosen instead.

              Thus, the choice of DYNAMIC RANGE vs SCAN depends on the
              presence of an index that has so bad selectivity that it
              will not be used anyway.
            */
            if (!tab->needed_reg.is_clear_all() &&
                (tab->table()->quick_keys.is_clear_all() ||
                 (tab->range_scan() &&
                  (tab->range_scan()->num_output_rows() >= 100.0)))) {
              tab->use_quick = QS_DYNAMIC_RANGE;
              tab->set_type(JT_ALL);
            } else
              tab->use_quick = QS_RANGE;
          }

          if (tab->type() != orig_join_type ||
              tab->range_scan() != orig_range_scan)  // Access method changed
            tab->position()->filter_effect = COND_FILTER_STALE;
        }
      }

      if (join->attach_join_conditions(i)) return true;
    }
    trace_attached_comp.end();

    /*
      In outer joins the loop above, in iteration for table #i, may push
      conditions to a table before #i. Thus, the processing below has to be in
      a separate loop:
    */
    Opt_trace_array trace_attached_summary(trace,
                                           "attached_conditions_summary");
    for (uint i = join->const_tables; i < join->tables; i++) {
      JOIN_TAB *const tab = join->best_ref[i];
      if (!tab->table()) continue;
      Item *const tab_cond = tab->condition();
      Opt_trace_object trace_one_table(trace);
      trace_one_table.add_utf8_table(tab->table_ref).add("attached", tab_cond);
      if (tab_cond && tab_cond->has_subquery())  // traverse only if needed
      {
        /*
          Why we pass walk_subquery=false: imagine
          WHERE t1.col IN (SELECT * FROM t2
                             WHERE t2.col IN (SELECT * FROM t3)
          and tab==t1. The grandchild subquery (SELECT * FROM t3) should not
          be marked as "in condition of t1" but as "in condition of t2", for
          correct calculation of the number of its executions.
        */
        std::pair<Query_block *, int> pair_object(join->query_block, i);
        tab_cond->walk(&Item::inform_item_in_cond_of_tab, enum_walk::POSTFIX,
                       pointer_cast<uchar *>(&pair_object));
      }
    }
  }
  return false;
}

/**
  Remove the following expressions from ORDER BY and GROUP BY:
  Constant expressions @n
  Expression that only uses tables that are of type EQ_REF and the reference
  is in the ORDER list or if all refereed tables are of the above type.

  In the following, the X field can be removed:
  @code
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
  @endcode

  These can't be optimized:
  @code
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
  @endcode

  @param  join         join object
  @param  start_order  clause being analyzed (ORDER BY, GROUP BY...)
  @param  tab          table
  @param  cached_eq_ref_tables  bitmap: bit Z is set if the table of map Z
  was already the subject of an eq_ref_table() call for the same clause; then
  the return value of this previous call can be found at bit Z of
  'eq_ref_tables'
  @param  eq_ref_tables see above.
*/

static bool eq_ref_table(JOIN *join, ORDER *start_order, JOIN_TAB *tab,
                         table_map *cached_eq_ref_tables,
                         table_map *eq_ref_tables) {
  /* We can skip const tables only if not an outer table */
  if (tab->type() == JT_CONST && tab->first_inner() == NO_PLAN_IDX) return true;
  if (tab->type() != JT_EQ_REF || tab->table()->is_nullable()) return false;

  const table_map map = tab->table_ref->map();
  uint found = 0;

  for (Item **ref_item = tab->ref().items,
            **end = ref_item + tab->ref().key_parts;
       ref_item != end; ref_item++) {
    if (!(*ref_item)->const_item()) {  // Not a const ref
      ORDER *order;
      for (order = start_order; order; order = order->next) {
        if ((*ref_item)->eq(order->item[0], false)) break;
      }
      if (order) {
        if (!(order->used & map)) {
          found++;
          order->used |= map;
        }
        continue;  // Used in ORDER BY
      }
      if (!only_eq_ref_tables(join, start_order, (*ref_item)->used_tables(),
                              cached_eq_ref_tables, eq_ref_tables))
        return false;
    }
  }
  /* Check that there was no reference to table before sort order */
  for (; found && start_order; start_order = start_order->next) {
    if (start_order->used & map) {
      found--;
      continue;
    }
    if (start_order->depend_map & map) return false;
  }
  return true;
}

/// @see eq_ref_table()
static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables,
                               table_map *cached_eq_ref_tables,
                               table_map *eq_ref_tables) {
  tables &= ~PSEUDO_TABLE_BITS;
  for (JOIN_TAB **tab = join->map2table; tables; tab++, tables >>= 1) {
    if (tables & 1) {
      const table_map map = (*tab)->table_ref->map();
      bool is_eq_ref;
      if (*cached_eq_ref_tables & map)  // then there exists a cached bit
        is_eq_ref = *eq_ref_tables & map;
      else {
        is_eq_ref = eq_ref_table(join, order, *tab, cached_eq_ref_tables,
                                 eq_ref_tables);
        if (is_eq_ref)
          *eq_ref_tables |= map;
        else
          *eq_ref_tables &= ~map;
        *cached_eq_ref_tables |= map;  // now there exists a cached bit
      }
      if (!is_eq_ref) return false;
    }
  }
  return true;
}

/**
  Check if an expression in ORDER BY or GROUP BY is a duplicate of a
  preceding expression.

  @param  first_order   the first expression in the ORDER BY or
                        GROUP BY clause
  @param  possible_dup  the expression that might be a duplicate of
                        another expression preceding it the ORDER BY
                        or GROUP BY clause

  @returns true if possible_dup is a duplicate, false otherwise
*/
static bool duplicate_order(const ORDER *first_order,
                            const ORDER *possible_dup) {
  const ORDER *order;
  for (order = first_order; order; order = order->next) {
    if (order == possible_dup) {
      // all expressions preceding possible_dup have been checked.
      return false;
    } else {
      const Item *it1 = order->item[0]->real_item();
      const Item *it2 = possible_dup->item[0]->real_item();

      if (it1->eq(it2, false)) return true;
    }
  }
  return false;
}

/**
  Remove all constants and check if ORDER only contains simple
  expressions.

  simple_order is set to true if sort_order only uses fields from head table
  and the head table is not a LEFT JOIN table.

  @param first_order   List of GROUP BY or ORDER BY sub-clauses.
  @param cond          WHERE condition.
  @param change        If true, remove sub-clauses that need not be evaluated.
                       If this is not set, then only simple_order is calculated.
  @param[out] simple_order  Set to true if we are only using simple expressions.
  @param group_by      True if first_order represents a grouping operation.

  @returns new sort order, after const elimination (when change is true).
*/

ORDER *JOIN::remove_const(ORDER *first_order, Item *cond, bool change,
                          bool *simple_order, bool group_by) {
  DBUG_TRACE;

  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  if (plan_is_const())
    return change ? nullptr : first_order;  // No need to sort

  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_disable_I_S trace_disabled(trace, first_order == nullptr);
  Opt_trace_object trace_simpl(
      trace, group_by ? "simplifying_group_by" : "simplifying_order_by");
  if (trace->is_started()) {
    String str;
    Query_block::print_order(
        thd, &str, first_order,
        enum_query_type(QT_TO_SYSTEM_CHARSET | QT_SHOW_SELECT_NUMBER |
                        QT_NO_DEFAULT_DB));
    trace_simpl.add_utf8("original_clause", str.ptr(), str.length());
  }
  Opt_trace_array trace_each_item(trace, "items");

  JOIN_TAB *const first_tab = best_ref[const_tables];
  table_map first_table = first_tab->table_ref->map();
  table_map not_const_tables = ~const_table_map;
  table_map ref;
  // Caches to avoid repeating eq_ref_table() calls, @see eq_ref_table()
  table_map eq_ref_tables = 0, cached_eq_ref_tables = 0;

  ORDER **prev_ptr = &first_order;
  *simple_order = !first_tab->join_cond();

  // De-optimization in conjunction with window functions
  if (group_by && m_windows.elements > 0) *simple_order = false;

  update_depend_map(first_order);

  for (ORDER *order = first_order; order; order = order->next) {
    Opt_trace_object trace_one_item(trace);
    trace_one_item.add("item", order->item[0]);
    table_map order_tables = order->item[0]->used_tables();

    if (order->item[0]->has_aggregation() || order->item[0]->has_wf() ||
        /*
          If the outer table of an outer join is const (either by itself or
          after applying WHERE condition), grouping on a field from such a
          table will be optimized away and filesort without temporary table
          will be used unless we prevent that now. Filesort is not fit to
          handle joins and the join condition is not applied. We can't detect
          the case without an expensive test, however, so we force temporary
          table for all queries containing more than one table, ROLLUP, and an
          outer join.
         */
        (primary_tables > 1 && rollup_state == RollupState::INITED &&
         query_block->outer_join)) {
      *simple_order = false;  // Must use a temporary table to sort
    } else if ((order_tables & not_const_tables) == 0 &&
               evaluate_during_optimization(order->item[0], query_block)) {
      if (order->item[0]->has_subquery()) {
        if (!thd->lex->is_explain()) {
          Opt_trace_array trace_subselect(trace, "subselect_evaluation");
          String str;
          order->item[0]->val_str(&str);
        }
        order->item[0]->mark_subqueries_optimized_away();
      }
      trace_one_item.add("uses_only_constant_tables", true);
      continue;  // skip const item
    } else if (duplicate_order(first_order, order)) {
      /*
        If 'order' is a duplicate of an expression earlier in the
        ORDER/GROUP BY sequence, it can be removed from the ORDER BY
        or GROUP BY clause.
      */
      trace_one_item.add("duplicate_item", true);
      continue;
    } else if (order->in_field_list && order->item[0]->has_subquery()) {
      /*
        If the order item is a subquery that is also in the field
        list, a temp table should be used to avoid evaluating the
        subquery for each row both when a) creating a sort index and
        b) getting the value.
          Example: "SELECT (SELECT ... ) as a ... GROUP BY a;"
       */
      *simple_order = false;
    } else if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)) {
      *simple_order = false;
    } else {
      if (cond != nullptr && check_field_is_const(cond, order->item[0])) {
        trace_one_item.add("equals_constant_in_where", true);
        continue;
      }
      if ((ref = order_tables & (not_const_tables ^ first_table))) {
        if (!(order_tables & first_table) &&
            only_eq_ref_tables(this, first_order, ref, &cached_eq_ref_tables,
                               &eq_ref_tables)) {
          trace_one_item.add("eq_ref_to_preceding_items", true);
          continue;
        }
        *simple_order = false;  // Must do a temp table to sort
      }
    }
    if (change) *prev_ptr = order;  // use this entry
    prev_ptr = &order->next;
  }
  if (change) *prev_ptr = nullptr;
  if (prev_ptr == &first_order)  // Nothing to sort/group
    *simple_order = true;
  DBUG_PRINT("exit", ("simple_order: %d", (int)*simple_order));

  trace_each_item.end();
  trace_simpl.add("resulting_clause_is_simple", *simple_order);
  if (trace->is_started() && change) {
    String str;
    Query_block::print_order(
        thd, &str, first_order,
        enum_query_type(QT_TO_SYSTEM_CHARSET | QT_SHOW_SELECT_NUMBER |
                        QT_NO_DEFAULT_DB));
    trace_simpl.add_utf8("resulting_clause", str.ptr(), str.length());
  }

  return first_order;
}

/**
  Optimize conditions by

     a) applying transitivity to build multiple equality predicates
        (MEP): if x=y and y=z the MEP x=y=z is built.
     b) apply constants where possible. If the value of x is known to be
        42, x is replaced with a constant of value 42. By transitivity, this
        also applies to MEPs, so the MEP in a) will become 42=x=y=z.
     c) remove conditions that are always false or always true

  @param thd                Thread handler
  @param[in,out] cond       WHERE or HAVING condition to optimize
  @param[out] cond_equal    The built multiple equalities
  @param join_list          list of join operations with join conditions
                            = NULL: Called for HAVING condition
  @param[out] cond_value    Not changed if cond was empty
                              COND_TRUE if cond is always true
                              COND_FALSE if cond is impossible
                              COND_OK otherwise


  @returns false if success, true if error
*/

bool optimize_cond(THD *thd, Item **cond, COND_EQUAL **cond_equal,
                   mem_root_deque<Table_ref *> *join_list,
                   Item::cond_result *cond_value) {
  DBUG_TRACE;
  Opt_trace_context *const trace = &thd->opt_trace;

  Opt_trace_object trace_wrapper(trace);
  Opt_trace_object trace_cond(trace, "condition_processing");
  trace_cond.add_alnum("condition", join_list ? "WHERE" : "HAVING");
  trace_cond.add("original_condition", *cond);
  Opt_trace_array trace_steps(trace, "steps");

  /*
    Enter this function
    a) For a WHERE condition or a query having outer join.
    b) For a HAVING condition.
  */
  assert(*cond || join_list);

  /*
    Build all multiple equality predicates and eliminate equality
    predicates that can be inferred from these multiple equalities.
    For each reference of a field included into a multiple equality
    that occurs in a function set a pointer to the multiple equality
    predicate. Substitute a constant instead of this field if the
    multiple equality contains a constant.
    This is performed for the WHERE condition and any join conditions, but
    not for the HAVING condition.
  */
  if (join_list) {
    Opt_trace_object step_wrapper(trace);
    step_wrapper.add_alnum("transformation", "equality_propagation");
    {
      Opt_trace_disable_I_S disable_trace_wrapper(
          trace, !(*cond && (*cond)->has_subquery()));
      Opt_trace_array trace_subselect(trace, "subselect_evaluation");
      if (build_equal_items(thd, *cond, cond, nullptr, true, join_list,
                            cond_equal))
        return true;
    }
    step_wrapper.add("resulting_condition", *cond);
  }
  /*
    change field = field to field = const for each found field = const
   */
  if (*cond) {
    Opt_trace_object step_wrapper(trace);
    step_wrapper.add_alnum("transformation", "constant_propagation");
    {
      Opt_trace_disable_I_S disable_trace_wrapper(trace,
                                                  !(*cond)->has_subquery());
      Opt_trace_array trace_subselect(trace, "subselect_evaluation");
      if (propagate_cond_constants(thd, nullptr, *cond, *cond)) return true;
    }
    step_wrapper.add("resulting_condition", *cond);
  }

  /*
    Remove all instances of item == item
    Remove all and-levels where CONST item != CONST item
  */
  DBUG_EXECUTE("where",
               print_where(thd, *cond, "after const change", QT_ORDINARY););
  if (*cond) {
    Opt_trace_object step_wrapper(trace);
    step_wrapper.add_alnum("transformation", "trivial_condition_removal");
    {
      Opt_trace_disable_I_S disable_trace_wrapper(trace,
                                                  !(*cond)->has_subquery());
      Opt_trace_array trace_subselect(trace, "subselect_evaluation");
      if (remove_eq_conds(thd, *cond, cond, cond_value)) return true;
    }
    step_wrapper.add("resulting_condition", *cond);
  }
  if (thd->is_error()) return true;
  return false;
}

/**
  Checks if a condition can be evaluated during constant folding. It can be
  evaluated if it is constant during execution and not expensive to evaluate. If
  it contains a subquery, it should not be evaluated if the option
  OPTION_NO_SUBQUERY_DURING_OPTIMIZATION is active.
*/
static bool can_evaluate_condition(THD *thd, Item *condition) {
  return condition->const_for_execution() && !condition->is_expensive() &&
         evaluate_during_optimization(condition,
                                      thd->lex->current_query_block());
}

/**
  Calls fold_condition. If that made the condition constant for execution,
  simplify and fold again. @see fold_condition() for arguments.
*/
static bool fold_condition_exec(THD *thd, Item *cond, Item **retcond,
                                Item::cond_result *cond_value) {
  if (fold_condition(thd, cond, retcond, cond_value)) return true;
  if (*retcond != nullptr &&
      can_evaluate_condition(thd, *retcond))  // simplify further maybe
    return remove_eq_conds(thd, *retcond, retcond, cond_value);
  return false;
}

/**
  Removes const and eq items. Returns the new item, or nullptr if no condition.

  @param      thd        thread handler
  @param      cond       the condition to handle
  @param[out] retcond    condition after const removal
  @param[out] cond_value resulting value of the condition
              =COND_OK    condition must be evaluated (e.g. field = constant)
              =COND_TRUE  always true                 (e.g. 1 = 1)
              =COND_FALSE always false                (e.g. 1 = 2)

  @returns false if success, true if error
*/
bool remove_eq_conds(THD *thd, Item *cond, Item **retcond,
                     Item::cond_result *cond_value) {
  assert(cond->real_item()->is_bool_func());
  if (cond->type() == Item::COND_ITEM) {
    Item_cond *const item_cond = down_cast<Item_cond *>(cond);
    const bool and_level = item_cond->functype() == Item_func::COND_AND_FUNC;
    List_iterator<Item> li(*item_cond->argument_list());
    bool should_fix_fields = false;
    *cond_value = Item::COND_UNDEF;
    Item *item;
    while ((item = li++)) {
      Item *new_item;
      Item::cond_result tmp_cond_value;
      if (remove_eq_conds(thd, item, &new_item, &tmp_cond_value)) return true;

      if (new_item == nullptr)
        li.remove();
      else if (item != new_item) {
        (void)li.replace(new_item);
        should_fix_fields = true;
      }
      if (*cond_value == Item::COND_UNDEF) *cond_value = tmp_cond_value;
      switch (tmp_cond_value) {
        case Item::COND_OK:  // Not true or false
          if (and_level || *cond_value == Item::COND_FALSE)
            *cond_value = tmp_cond_value;
          break;
        case Item::COND_FALSE:
          if (and_level)  // Always false
          {
            *cond_value = tmp_cond_value;
            *retcond = nullptr;
            return false;
          }
          break;
        case Item::COND_TRUE:
          if (!and_level)  // Always true
          {
            *cond_value = tmp_cond_value;
            *retcond = nullptr;
            return false;
          }
          break;
        case Item::COND_UNDEF:  // Impossible
          assert(false);        /* purecov: deadcode */
      }
    }
    if (should_fix_fields) item_cond->update_used_tables();

    if (item_cond->argument_list()->elements == 0 ||
        *cond_value != Item::COND_OK) {
      *retcond = nullptr;
      return false;
    }
    if (item_cond->argument_list()->elements == 1) {
      /*
        BUG#11765699:
        We're dealing with an AND or OR item that has only one
        argument. However, it is not an option to empty the list
        because:

         - this function is called for either JOIN::conds or
           JOIN::having, but these point to the same condition as
           Query_block::where and Query_block::having do.

         - The return value of remove_eq_conds() is assigned to
           JOIN::conds and JOIN::having, so emptying the list and
           returning the only remaining item "replaces" the AND or OR
           with item for the variables in JOIN. However, the return
           value is not assigned to the Query_block counterparts. Thus,
           if argument_list is emptied, Query_block forgets the item in
           argument_list()->head().

        item is therefore returned, but argument_list is not emptied.
      */
      item = item_cond->argument_list()->head();
      /*
        Consider reenabling the line below when the optimizer has been
        split into properly separated phases.

        item_cond->argument_list()->empty();
      */
      *retcond = item;
      return false;
    }
  } else if (can_evaluate_condition(thd, cond)) {
    bool value;
    if (eval_const_cond(thd, cond, &value)) return true;
    *cond_value = value ? Item::COND_TRUE : Item::COND_FALSE;
    *retcond = nullptr;
    return false;
  } else {  // Boolean compare function
    *cond_value = cond->eq_cmp_result();
    if (*cond_value == Item::COND_OK) {
      return fold_condition_exec(thd, cond, retcond, cond_value);
    }
    Item *left_item = down_cast<Item_func *>(cond)->arguments()[0];
    Item *right_item = down_cast<Item_func *>(cond)->arguments()[1];
    if (left_item->eq(right_item, true) && !cond->is_non_deterministic()) {
      /*
       Two identical items are being compared:
       1) If the items are not nullable, return result from eq_cmp_result(),
          that is, we can short circuit because result is statically always
          known to be true or false, depending on which operator we are
          dealing with. If the operator allows equality, *cond_value is
          Item::COND_TRUE (a non-null value is always equal to itself), else
          Item::COND_FALSE (a non-null value is never unequal to itself).
       2) If the items are nullable and the result from eq_cmp_result() is
          false, result is always false, that is, the operator doesn't
          allow for equality, the result is always false: Any non-null
          value cannot obviously be unequal to itself, and any NULL value
          would yield an undefined result (e.g. NULL < NULL
          is undefined), and hence Item::COND_FALSE in this context is the
          effective result.
          (Call order ensures test is not applied to conditions with explicit
          truth value test)
       3) If the <=> operator is used, result is always true because
          NULL = NULL is true for this operator
      */
      if (!left_item->is_nullable() || *cond_value == Item::COND_FALSE ||
          down_cast<Item_func *>(cond)->functype() == Item_func::EQUAL_FUNC) {
        *retcond = nullptr;
        return false;
      }
    }
  }
  return fold_condition_exec(thd, cond, retcond, cond_value);
}

/**
  Check if GROUP BY/DISTINCT can be optimized away because the set is
  already known to be distinct.

  Used in removing the GROUP BY/DISTINCT of the following types of
  statements:
  @code
    SELECT [DISTINCT] <unique_key_cols>... FROM <single_table_ref>
      [GROUP BY <unique_key_cols>,...]
  @endcode

    If (a,b,c is distinct)
    then <any combination of a,b,c>,{whatever} is also distinct

    This function checks if all the key parts of any of the unique keys
    of the table are referenced by a list : either the select list
    through find_field_in_item_list or GROUP BY list through
    find_field_in_order_list.
    If the above holds and the key parts cannot contain NULLs then we
    can safely remove the GROUP BY/DISTINCT,
    as no result set can be more distinct than an unique key.

  @param tab                  The join table to operate on.
  @param find_func            function to iterate over the list and search
                              for a field
  @param data                 data that's passed through to to find_func

  @retval
    1                    found
  @retval
    0                    not found.

  @note
    The function assumes that make_outerjoin_info() has been called in
    order for the check for outer tables to work.
*/

static bool list_contains_unique_index(JOIN_TAB *tab,
                                       bool (*find_func)(Field *, void *),
                                       void *data) {
  TABLE *table = tab->table();

  if (tab->is_inner_table_of_outer_join()) return false;
  for (uint keynr = 0; keynr < table->s->keys; keynr++) {
    if (keynr == table->s->primary_key ||
        (table->key_info[keynr].flags & HA_NOSAME)) {
      KEY *keyinfo = table->key_info + keynr;
      KEY_PART_INFO *key_part, *key_part_end;

      for (key_part = keyinfo->key_part,
          key_part_end = key_part + keyinfo->user_defined_key_parts;
           key_part < key_part_end; key_part++) {
        if (key_part->field->is_nullable() || !find_func(key_part->field, data))
          break;
      }
      if (key_part == key_part_end) return true;
    }
  }
  return false;
}

/**
  Helper function for list_contains_unique_index.
  Find a field reference in a list of ORDER structures.
  Finds a direct reference of the Field in the list.

  @param field                The field to search for.
  @param data                 ORDER *.The list to search in

  @retval
    1                    found
  @retval
    0                    not found.
*/

static bool find_field_in_order_list(Field *field, void *data) {
  ORDER *group = (ORDER *)data;
  bool part_found = false;
  for (ORDER *tmp_group = group; tmp_group; tmp_group = tmp_group->next) {
    const Item *item = (*tmp_group->item)->real_item();
    if (item->type() == Item::FIELD_ITEM &&
        down_cast<const Item_field *>(item)->field->eq(field)) {
      part_found = true;
      break;
    }
  }
  return part_found;
}

/**
  Helper function for list_contains_unique_index.
  Find a field reference in a dynamic list of Items.
  Finds a direct reference of the Field in the list.

  @param[in] field             The field to search for.
  @param[in] data              List<Item> *.The list to search in

  @retval
    1                    found
  @retval
    0                    not found.
*/

static bool find_field_in_item_list(Field *field, void *data) {
  mem_root_deque<Item *> *fields =
      reinterpret_cast<mem_root_deque<Item *> *>(data);
  bool part_found = false;

  for (const Item *item : VisibleFields(*fields)) {
    if (item->type() == Item::FIELD_ITEM &&
        down_cast<const Item_field *>(item)->field->eq(field)) {
      part_found = true;
      break;
    }
  }
  return part_found;
}

ORDER *create_order_from_distinct(THD *thd, Ref_item_array ref_item_array,
                                  ORDER *order_list,
                                  mem_root_deque<Item *> *fields,
                                  bool skip_aggregates,
                                  bool convert_bit_fields_to_long,
                                  bool *all_order_by_fields_used) {
  ORDER *group = nullptr, **prev = &group;

  *all_order_by_fields_used = true;

  for (ORDER *order = order_list; order; order = order->next) {
    if (order->in_field_list) {
      ORDER *ord = (ORDER *)thd->memdup((char *)order, sizeof(ORDER));
      if (!ord) return nullptr;
      *prev = ord;
      prev = &ord->next;
      (*ord->item)->marker = Item::MARKER_DISTINCT_GROUP;
    } else
      *all_order_by_fields_used = false;
  }

  Mem_root_array<std::pair<Item *, ORDER *>> bit_fields_to_add(thd->mem_root);

  for (Item *&item : VisibleFields(*fields)) {
    if (!item->const_item() && (!skip_aggregates || !item->has_aggregation()) &&
        item->marker != Item::MARKER_DISTINCT_GROUP) {
      /*
        Don't put duplicate columns from the SELECT list into the
        GROUP BY list.
      */
      ORDER *ord_iter;
      for (ord_iter = group; ord_iter; ord_iter = ord_iter->next)
        if ((*ord_iter->item)->eq(item, true)) goto next_item;

      ORDER *ord = (ORDER *)thd->mem_calloc(sizeof(ORDER));
      if (!ord) return nullptr;

      if (item->type() == Item::FIELD_ITEM &&
          item->data_type() == MYSQL_TYPE_BIT && convert_bit_fields_to_long) {
        /*
          Because HEAP tables can't index BIT fields we need to use an
          additional hidden field for grouping because later it will be
          converted to a LONG field. Original field will remain of the
          BIT type and will be returned to a client.
          @note setup_ref_array() needs to account for the extra space.
          @note We need to defer the actual adding to after the loop,
            or we will invalidate the iterator to “fields”.
        */
        Item_field *new_item = new Item_field(thd, (Item_field *)item);
        ord->item = &item;  // Temporary; for the duplicate check above.
        bit_fields_to_add.push_back(std::make_pair(new_item, ord));
      } else if (ref_item_array.is_null()) {
        // No slices are in use, so just use the field from the list.
        ord->item = &item;
      } else {
        /*
          We have here only visible fields, so we can use simple indexing
          of ref_item_array (order in the array and in the list are same)
        */
        ord->item = &ref_item_array[0];
      }
      ord->direction = ORDER_ASC;
      *prev = ord;
      prev = &ord->next;
    }
  next_item:
    if (!ref_item_array.is_null()) {
      ref_item_array.pop_front();
    }
  }
  for (const auto &item_and_order : bit_fields_to_add) {
    item_and_order.second->item =
        thd->lex->current_query_block()->add_hidden_item(item_and_order.first);
    thd->lex->current_query_block()->hidden_items_from_optimization++;
  }
  *prev = nullptr;
  return group;
}

/**
  Return table number if there is only one table in sort order
  and group and order is compatible, else return 0.
*/

static TABLE *get_sort_by_table(ORDER *a, ORDER *b, Table_ref *tables) {
  DBUG_TRACE;
  table_map map = (table_map)0;

  if (!a)
    a = b;  // Only one need to be given
  else if (!b)
    b = a;

  for (; a && b; a = a->next, b = b->next) {
    if (!(*a->item)->eq(*b->item, true)) return nullptr;
    map |= a->item[0]->used_tables();
  }
  map &= ~INNER_TABLE_BIT;
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))) return nullptr;

  for (; !(map & tables->map()); tables = tables->next_leaf)
    ;
  if (map != tables->map()) return nullptr;  // More than one table
  DBUG_PRINT("exit", ("sort by table: %d", tables->tableno()));
  return tables->table;
}

/**
  Update some values in keyuse for faster choose_table_order() loop.

  @todo Check if this is the real meaning of ref_table_rows.
*/

void JOIN::optimize_keyuse() {
  for (size_t ix = 0; ix < keyuse_array.size(); ++ix) {
    Key_use *keyuse = &keyuse_array.at(ix);
    table_map map;
    /*
      If we find a ref, assume this table matches a proportional
      part of this table.
      For example 100 records matching a table with 5000 records
      gives 5000/100 = 50 records per key
      Constant tables are ignored.
      To avoid bad matches, we don't make ref_table_rows less than 100.
    */
    keyuse->ref_table_rows = ~(ha_rows)0;  // If no ref
    if (keyuse->used_tables &
        (map = keyuse->used_tables & ~(const_table_map | PSEUDO_TABLE_BITS))) {
      uint tableno;
      for (tableno = 0; !(map & 1); map >>= 1, tableno++) {
      }
      if (map == 1)  // Only one table
      {
        TABLE *tmp_table = join_tab[tableno].table();

        keyuse->ref_table_rows =
            max<ha_rows>(tmp_table->file->stats.records, 100);
      }
    }
    /*
      Outer reference (external field) is constant for single executing
      of subquery
    */
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT) keyuse->ref_table_rows = 1;
  }
}

/**
  Function sets FT hints, initializes FT handlers
  and checks if FT index can be used as covered.
*/

bool JOIN::optimize_fts_query() {
  ASSERT_BEST_REF_IN_JOIN_ORDER(this);

  assert(query_block->has_ft_funcs());

  // Only used by the old optimizer.
  assert(!thd->lex->using_hypergraph_optimizer());

  for (uint i = const_tables; i < tables; i++) {
    JOIN_TAB *tab = best_ref[i];
    if (tab->type() != JT_FT) continue;

    Item_func_match *ifm;
    Item_func_match *ft_func =
        down_cast<Item_func_match *>(tab->position()->key->val);
    List_iterator<Item_func_match> li(*(query_block->ftfunc_list));

    while ((ifm = li++)) {
      if (!(ifm->used_tables() & tab->table_ref->map()) || ifm->master)
        continue;

      if (ifm != ft_func) {
        if (ifm->can_skip_ranking())
          ifm->set_hints(this, FT_NO_RANKING, HA_POS_ERROR, false);
      }
    }

    /*
      Check if internal sorting is needed. FT_SORTED flag is set
      if no ORDER BY clause or ORDER BY MATCH function is the same
      as the function that is used for FT index and FT table is
      the first non-constant table in the JOIN.
    */
    if (i == const_tables && !(ft_func->get_hints()->get_flags() & FT_BOOL) &&
        (order.empty() || ft_func == test_if_ft_index_order(order.order)))
      ft_func->set_hints(this, FT_SORTED, m_select_limit, false);

    /*
      Check if ranking is not needed. FT_NO_RANKING flag is set if
      MATCH function is used only in WHERE condition and  MATCH
      function is not part of an expression.
    */
    if (ft_func->can_skip_ranking())
      ft_func->set_hints(this, FT_NO_RANKING,
                         order.empty() ? m_select_limit : HA_POS_ERROR, false);
  }

  return init_ftfuncs(thd, query_block);
}

/**
  Check if FTS index only access is possible.

  @param tab  pointer to JOIN_TAB structure.

  @return  true if index only access is possible,
           false otherwise.
*/

bool JOIN::fts_index_access(JOIN_TAB *tab) {
  assert(tab->type() == JT_FT);
  TABLE *table = tab->table();

  // Give up if index-only access has already been disabled on this table.
  if (table->no_keyread) {
    return false;
  }

  if ((table->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT) == 0)
    return false;  // Optimizations requires extended FTS support by table
                   // engine

  /*
    This optimization does not work with filesort nor GROUP BY
  */
  if (grouped ||
      (!order.empty() && m_ordered_index_usage != ORDERED_INDEX_ORDER_BY))
    return false;

  /*
    Check whether the FTS result is covering.  If only document id
    and rank is needed, there is no need to access table rows.
  */
  for (uint i = bitmap_get_first_set(table->read_set); i < table->s->fields;
       i = bitmap_get_next_set(table->read_set, i)) {
    if (table->field[i] != table->fts_doc_id_field ||
        !tab->ft_func()->docid_in_result())
      return false;
  }

  return true;
}

bool JOIN::contains_non_aggregated_fts() const {
  return query_block->has_ft_funcs() &&
         std::any_of(fields->begin(), fields->end(), [](Item *item) {
           return WalkItem(item, enum_walk::PREFIX | enum_walk::POSTFIX,
                           NonAggregatedFullTextSearchVisitor(
                               [](Item_func_match *) { return true; }));
         });
}

/**
   For {semijoin,subquery} materialization: calculates various cost
   information, based on a plan in join->best_positions covering the
   to-be-materialized query block and only this.

   @param join     JOIN where plan can be found
   @param sj_nest  sj materialization nest (NULL if subquery materialization)
   @param n_tables number of to-be-materialized tables
   @param[out] sjm where computed costs will be stored

   @note that this function modifies join->map2table, which has to be filled
   correctly later.
*/
static void calculate_materialization_costs(JOIN *join, Table_ref *sj_nest,
                                            uint n_tables,
                                            Semijoin_mat_optimize *sjm) {
  double mat_cost;           // Estimated cost of materialization
  double mat_rowcount;       // Estimated row count before duplicate removal
  double distinct_rowcount;  // Estimated rowcount after duplicate removal
  mem_root_deque<Item *> *inner_expr_list;

  if (sj_nest) {
    /*
      get_partial_join_cost() assumes a regular join, which is correct when
      we optimize a sj-materialization nest (always executed as regular
      join).
    */
    get_partial_join_cost(join, n_tables, &mat_cost, &mat_rowcount);
    n_tables += join->const_tables;
    inner_expr_list = &sj_nest->nested_join->sj_inner_exprs;
  } else {
    mat_cost = join->best_read;
    mat_rowcount = static_cast<double>(join->best_rowcount);
    inner_expr_list = &join->query_block->fields;
  }

  /*
    Adjust output cardinality estimates. If the subquery has form

    ... oe IN (SELECT t1.colX, t2.colY, func(X,Y,Z) )

    then the number of distinct output record combinations has an
    upper bound of product of number of records matching the tables
    that are used by the SELECT clause.
    TODO:
    We can get a more precise estimate if we
     - use rec_per_key cardinality estimates. For simple cases like
     "oe IN (SELECT t.key ...)" it is trivial.
     - Functional dependencies between the tables in the semi-join
     nest (the payoff is probably less here?)
  */
  {
    for (uint i = 0; i < n_tables; i++) {
      JOIN_TAB *const tab = join->best_positions[i].table;
      join->map2table[tab->table_ref->tableno()] = tab;
    }
    table_map map = 0;
    for (Item *item : VisibleFields(*inner_expr_list)) {
      map |= item->used_tables();
    }
    map &= ~PSEUDO_TABLE_BITS;
    Table_map_iterator tm_it(map);
    int tableno;
    double rows = 1.0;
    while ((tableno = tm_it.next_bit()) != Table_map_iterator::BITMAP_END)
      rows *= join->map2table[tableno]->table()->quick_condition_rows;
    distinct_rowcount = min(mat_rowcount, rows);
  }
  /*
    Calculate temporary table parameters and usage costs
  */
  const uint rowlen = get_tmp_table_rec_length(*inner_expr_list);

  const Cost_model_server *cost_model = join->cost_model();

  Cost_model_server::enum_tmptable_type tmp_table_type;
  if (rowlen * distinct_rowcount < join->thd->variables.max_heap_table_size)
    tmp_table_type = Cost_model_server::MEMORY_TMPTABLE;
  else
    tmp_table_type = Cost_model_server::DISK_TMPTABLE;

  /*
    Let materialization cost include the cost to create the temporary
    table and write the rows into it:
  */
  mat_cost += cost_model->tmptable_create_cost(tmp_table_type);
  mat_cost +=
      cost_model->tmptable_readwrite_cost(tmp_table_type, mat_rowcount, 0.0);

  sjm->materialization_cost.reset();
  sjm->materialization_cost.add_io(mat_cost);

  sjm->expected_rowcount = distinct_rowcount;

  /*
    Set the cost to do a full scan of the temptable (will need this to
    consider doing sjm-scan):
  */
  sjm->scan_cost.reset();
  if (distinct_rowcount > 0.0) {
    const double scan_cost = cost_model->tmptable_readwrite_cost(
        tmp_table_type, 0.0, distinct_rowcount);
    sjm->scan_cost.add_io(scan_cost);
  }

  // The cost to lookup a row in temp. table
  const double row_cost =
      cost_model->tmptable_readwrite_cost(tmp_table_type, 0.0, 1.0);
  sjm->lookup_cost.reset();
  sjm->lookup_cost.add_io(row_cost);
}

/**
   Decides between EXISTS and materialization; performs last steps to set up
   the chosen strategy.
   @returns 'false' if no error

   @note If UNION this is called on each contained JOIN.

 */
bool JOIN::decide_subquery_strategy() {
  assert(query_expression()->item);

  switch (query_expression()->item->substype()) {
    case Item_subselect::IN_SUBS:
    case Item_subselect::ALL_SUBS:
    case Item_subselect::ANY_SUBS:
      // All of those are children of Item_in_subselect and may use EXISTS
      break;
    default:
      return false;
  }

  Item_in_subselect *const in_pred =
      static_cast<Item_in_subselect *>(query_expression()->item);

  Subquery_strategy chosen_method = in_pred->strategy;
  // Materialization does not allow UNION so this can't happen:
  assert(chosen_method != Subquery_strategy::SUBQ_MATERIALIZATION);

  if ((chosen_method == Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT) &&
      compare_costs_of_subquery_strategies(&chosen_method))
    return true;

  switch (chosen_method) {
    case Subquery_strategy::SUBQ_EXISTS:
      if (query_block->m_windows.elements > 0)  // grep for WL#10431
      {
        my_error(ER_NOT_SUPPORTED_YET, MYF(0),
                 "the combination of this ALL/ANY/SOME/IN subquery with this"
                 " comparison operator and with contained window functions");
        return true;
      }
      return in_pred->finalize_exists_transform(thd, query_block);
    case Subquery_strategy::SUBQ_MATERIALIZATION:
      return in_pred->finalize_materialization_transform(thd, this);
    default:
      assert(false);
      return true;
  }
}

/**
   Tells what is the cheapest between IN->EXISTS and subquery materialization,
   in terms of cost, for the subquery's JOIN.
   Input:
   - join->{best_positions,best_read,best_rowcount} must contain the
   execution plan of EXISTS (where 'join' is the subquery's JOIN)
   - join2->{best_positions,best_read,best_rowcount} must be correctly set
   (where 'join2' is the parent join, the grandparent join, etc).
   Output:
   join->{best_positions,best_read,best_rowcount} contain the cheapest
   execution plan (where 'join' is the subquery's JOIN).

   This plan choice has to happen before calling functions which set up
   execution structures, like JOIN::get_best_combination().

   @param[out] method  chosen method (EXISTS or materialization) will be put
                       here.
   @returns false if success
*/
bool JOIN::compare_costs_of_subquery_strategies(Subquery_strategy *method) {
  *method = Subquery_strategy::SUBQ_EXISTS;

  Subquery_strategy allowed_strategies = query_block->subquery_strategy(thd);

  /*
    A non-deterministic subquery should not use materialization, unless forced.
    For a detailed explanation, see Query_block::decorrelate_where_cond().
    Here, the same logic is applied also for subqueries that are not converted
    to semi-join.
  */
  if (allowed_strategies == Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT &&
      (query_expression()->uncacheable & UNCACHEABLE_RAND))
    allowed_strategies = Subquery_strategy::SUBQ_EXISTS;

  if (allowed_strategies == Subquery_strategy::SUBQ_EXISTS) return false;

  assert(allowed_strategies ==
             Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT ||
         allowed_strategies == Subquery_strategy::SUBQ_MATERIALIZATION);

  const JOIN *parent_join = query_expression()->outer_query_block()->join;
  if (!parent_join || !parent_join->child_subquery_can_materialize)
    return false;

  Item_in_subselect *const in_pred =
      static_cast<Item_in_subselect *>(query_expression()->item);

  /*
    Testing subquery_allows_etc() at each optimization is necessary as each
    execution of a prepared statement may use a different type of parameter.
  */
  if (!in_pred->subquery_allows_materialization(
          thd, query_block, query_block->outer_query_block()))
    return false;

  Opt_trace_context *const trace = &thd->opt_trace;
  Opt_trace_object trace_wrapper(trace);
  Opt_trace_object trace_subqmat(
      trace, "execution_plan_for_potential_materialization");
  const double saved_best_read = best_read;
  const ha_rows saved_best_rowcount = best_rowcount;
  POSITION *const saved_best_pos = best_positions;

  if (in_pred->in2exists_added_to_where()) {
    Opt_trace_array trace_subqmat_steps(trace, "steps");

    // Up to one extra slot per semi-join nest is needed (if materialized)
    const uint sj_nests = query_block->sj_nests.size();

    if (!(best_positions = new (thd->mem_root) POSITION[tables + sj_nests]))
      return true;

    // Compute plans which do not use outer references

    assert(allow_outer_refs);
    allow_outer_refs = false;

    if (optimize_semijoin_nests_for_materialization(this)) return true;

    if (Optimize_table_order(thd, this, nullptr).choose_table_order())
      return true;
  } else {
    /*
      If IN->EXISTS didn't add any condition to WHERE (only to HAVING, which
      can happen if subquery has aggregates) then the plan for materialization
      will be the same as for EXISTS - don't compute it again.
    */
    trace_subqmat.add("surely_same_plan_as_EXISTS", true)
        .add_alnum("cause", "EXISTS_did_not_change_WHERE");
  }

  Semijoin_mat_optimize sjm;
  calculate_materialization_costs(this, nullptr, primary_tables, &sjm);

  /*
    The number of evaluations of the subquery influences costs, we need to
    compute it.
  */
  Opt_trace_object trace_subq_mat_decision(trace, "subq_mat_decision");
  const double subq_executions = calculate_subquery_executions(in_pred, trace);
  const double cost_exists = subq_executions * saved_best_read;
  const double cost_mat_table = sjm.materialization_cost.total_cost();
  const double cost_mat =
      cost_mat_table + subq_executions * sjm.lookup_cost.total_cost();
  const bool mat_chosen =
      (allowed_strategies == Subquery_strategy::CANDIDATE_FOR_IN2EXISTS_OR_MAT)
          ? (cost_mat < cost_exists)
          : true;
  trace_subq_mat_decision
      .add("cost_to_create_and_fill_materialized_table", cost_mat_table)
      .add("cost_of_one_EXISTS", saved_best_read)
      .add("number_of_subquery_evaluations", subq_executions)
      .add("cost_of_materialization", cost_mat)
      .add("cost_of_EXISTS", cost_exists)
      .add("chosen", mat_chosen);
  if (mat_chosen) {
    *method = Subquery_strategy::SUBQ_MATERIALIZATION;
  } else {
    best_read = saved_best_read;
    best_rowcount = saved_best_rowcount;
    best_positions = saved_best_pos;
    /*
      Don't restore JOIN::positions or best_ref, they're not used
      afterwards. best_positions is (like: by get_sj_strategy()).
    */
  }
  return false;
}

double calculate_subquery_executions(const Item_subselect *subquery,
                                     Opt_trace_context *trace) {
  Opt_trace_array trace_parents(trace, "parent_fanouts");
  double subquery_executions = 1.0;
  for (;;) {
    const Query_block *const parent_query_block =
        subquery->unit->outer_query_block();
    const JOIN *const parent_join = parent_query_block->join;
    if (parent_join == nullptr) {
      /*
        May be single-table UPDATE/DELETE, has no join.
        @todo  we should find how many rows it plans to UPDATE/DELETE, taking
        inspiration in Explain_table::explain_rows_and_filtered().
        This is not a priority as it applies only to
        UPDATE - child(non-mat-subq) - grandchild(may-be-mat-subq).
        And it will autosolve the day UPDATE gets a JOIN.
      */
      break;
    }

    Opt_trace_object trace_parent(trace);
    trace_parent.add_select_number(parent_query_block->select_number);
    double parent_fanout;
    if (  // safety, not sure needed
        parent_join->plan_is_const() ||
        // if subq is in condition on constant table:
        !parent_join->child_subquery_can_materialize) {
      parent_fanout = 1.0;
      trace_parent.add("subq_attached_to_const_table", true);
    } else {
      if (subquery->in_cond_of_tab != NO_PLAN_IDX) {
        /*
          Subquery is attached to a certain 'pos', pos[-1].prefix_rowcount
          is the number of times we'll start a loop accessing 'pos'; each such
          loop will read pos->rows_fetched rows of 'pos', so subquery will
          be evaluated pos[-1].prefix_rowcount * pos->rows_fetched times.
          Exceptions:
          - if 'pos' is first, use 1.0 instead of pos[-1].prefix_rowcount
          - if 'pos' is first of a sj-materialization nest, same.

          If in a sj-materialization nest, pos->rows_fetched and
          pos[-1].prefix_rowcount are of the "nest materialization" plan
          (copied back in fix_semijoin_strategies()), which is
          appropriate as it corresponds to evaluations of our subquery.

          pos->prefix_rowcount is not suitable because if we have:
          select ... from ot1 where ot1.col in
            (select it1.col1 from it1 where it1.col2 not in (subq));
          and subq does subq-mat, and plan is ot1 - it1+firstmatch(ot1),
          then:
          - t1.prefix_rowcount==1 (due to firstmatch)
          - subq is attached to it1, and is evaluated for each row read from
            t1, potentially way more than 1.
         */
        const uint idx = subquery->in_cond_of_tab;
        assert((int)idx >= 0 && idx < parent_join->tables);
        trace_parent.add("subq_attached_to_table", true);
        QEP_TAB *const parent_tab = &parent_join->qep_tab[idx];
        trace_parent.add_utf8_table(parent_tab->table_ref);
        parent_fanout = parent_tab->position()->rows_fetched;
        if ((idx > parent_join->const_tables) &&
            !sj_is_materialize_strategy(parent_tab->position()->sj_strategy))
          parent_fanout *= parent_tab[-1].position()->prefix_rowcount;
      } else {
        /*
          Subquery is SELECT list, GROUP BY, ORDER BY, HAVING: it is evaluated
          at the end of the parent join's execution.
          It can be evaluated once per row-before-grouping:
          SELECT SUM(t1.col IN (subq)) FROM t1 GROUP BY expr;
          or once per row-after-grouping:
          SELECT SUM(t1.col) AS s FROM t1 GROUP BY expr HAVING s IN (subq),
          SELECT SUM(t1.col) IN (subq) FROM t1 GROUP BY expr
          It's hard to tell. We simply assume 'once per
          row-before-grouping'.

          Another approximation:
          SELECT ... HAVING x IN (subq) LIMIT 1
          best_rowcount=1 due to LIMIT, though HAVING (and thus the subquery)
          may be evaluated many times before HAVING becomes true and the limit
          is reached.
        */
        trace_parent.add("subq_attached_to_join_result", true);
        parent_fanout = static_cast<double>(parent_join->best_rowcount);
      }
    }
    subquery_executions *= parent_fanout;
    trace_parent.add("fanout", parent_fanout);
    const bool cacheable = parent_query_block->is_cacheable();
    trace_parent.add("cacheable", cacheable);
    if (cacheable) {
      // Parent executed only once
      break;
    }
    /*
      Parent query is executed once per outer row => go up to find number of
      outer rows. Example:
      SELECT ... IN(subq-with-in2exists WHERE ... IN (subq-with-mat))
    */
    subquery = parent_join->query_expression()->item;
    if (subquery == nullptr) {
      // derived table, materialized only once
      break;
    }
  }  // for(;;)
  return subquery_executions;
}

/**
  Optimize rollup specification.

  Allocate objects needed for rollup processing.

  @returns false if success, true if error.
*/

bool JOIN::optimize_rollup() {
  tmp_table_param.allow_group_via_temp_table = false;
  rollup_state = RollupState::INITED;
  tmp_table_param.group_parts = send_group_parts;
  return false;
}

/**
  Refine the best_rowcount estimation based on what happens after tables
  have been joined: LIMIT and type of result sink.
 */
void JOIN::refine_best_rowcount() {
  // If plan is const, 0 or 1 rows should be returned
  assert(!plan_is_const() || best_rowcount <= 1);

  if (plan_is_const()) return;

  /*
    If a derived table, or a member of a UNION which itself forms a derived
    table:
    setting estimate to 0 or 1 row would mark the derived table as const.
    The row count is bumped to the nearest higher value, so that the
    query block will not be evaluated during optimization.
  */
  if (best_rowcount <= 1 &&
      query_block->master_query_expression()->first_query_block()->linkage ==
          DERIVED_TABLE_TYPE)
    best_rowcount = PLACEHOLDER_TABLE_ROW_ESTIMATE;

  /*
    There will be no more rows than defined in the LIMIT clause. Use it
    as an estimate. If LIMIT 1 is specified, the query block will be
    considered "const", with actual row count 0 or 1.
  */
  best_rowcount = std::min(best_rowcount, query_expression()->select_limit_cnt);
}

mem_root_deque<Item *> *JOIN::get_current_fields() {
  assert((int)current_ref_item_slice >= 0);
  if (current_ref_item_slice == REF_SLICE_SAVED_BASE) return fields;
  return &tmp_fields[current_ref_item_slice];
}

const Cost_model_server *JOIN::cost_model() const {
  assert(thd != nullptr);
  return thd->cost_model();
}

/**
  @} (end of group Query_Optimizer)
*/

/**
  This function is used to get the key length of Item object on
  which one tmp field will be created during create_tmp_table.
  This function references KEY_PART_INFO::init_from_field().

  @param item  A inner item of outer join

  @return  The length of a item to be as a key of a temp table
*/

static uint32 get_key_length_tmp_table(Item *item) {
  uint32 len = 0;

  item = item->real_item();
  if (item->type() == Item::FIELD_ITEM)
    len = ((Item_field *)item)->field->key_length();
  else
    len = item->max_length;

  if (item->is_nullable()) len += HA_KEY_NULL_LENGTH;

  // references KEY_PART_INFO::init_from_field()
  enum_field_types type = item->data_type();
  if (type == MYSQL_TYPE_BLOB || type == MYSQL_TYPE_VARCHAR ||
      type == MYSQL_TYPE_GEOMETRY)
    len += HA_KEY_BLOB_LENGTH;

  return len;
}

bool evaluate_during_optimization(const Item *item, const Query_block *select) {
  /*
    Should only be called on items that are const_for_execution(), as those
    items are the only ones that are allowed to be evaluated during optimization
    in the first place.

    Additionally, allow items that only access tables in JOIN::const_table_map.
    This should not be necessary, but the const_for_execution() property is not
    always updated correctly by update_used_tables() for certain subqueries.
  */
  assert(item->const_for_execution() ||
         (item->used_tables() & ~select->join->const_table_map) == 0);

  // If the Item does not access any tables, it can always be evaluated.
  if (item->const_item()) return true;

  // Do not evaluate stored procedure in EXPLAIN
  if (current_thd->lex->is_explain() &&
      WalkItem(item, enum_walk::PREFIX, [](const Item *curitem) {
        return curitem->has_stored_program();
      }))
    return false;

  return !item->has_subquery() || (select->active_options() &
                                   OPTION_NO_SUBQUERY_DURING_OPTIMIZATION) == 0;
}

/// Does this path scan any base tables in a secondary engine?
static bool ReferencesSecondaryEngineBaseTables(AccessPath *path) {
  bool found = false;
  WalkAccessPaths(path, /*join=*/nullptr, WalkAccessPathPolicy::ENTIRE_TREE,
                  [&found](const AccessPath *subpath, const JOIN *) {
                    TABLE *table = GetBasicTable(subpath);
                    if (table != nullptr && table->s->is_secondary_engine()) {
                      found = true;
                    }
                    return found;
                  });
  return found;
}

bool IteratorsAreNeeded(const THD *thd, AccessPath *root_path) {
  const handlerton *secondary_engine = SecondaryEngineHandlerton(thd);

  // Queries running in the primary engine always need iterators.
  if (secondary_engine == nullptr) {
    return true;
  }

  // If the entire query is optimized away, we create iterators regardless of
  // whether an external executor is used, since the secondary engine may decide
  // not to offload the query to the external executor in this case.
  if (!ReferencesSecondaryEngineBaseTables(root_path)) {
    return true;
  }

  // Otherwise, create iterators if the secondary engine does not use an
  // external executor.
  return !IsBitSet(static_cast<int>(SecondaryEngineFlag::USE_EXTERNAL_EXECUTOR),
                   secondary_engine->secondary_engine_flags);
}

/// Constant used to signal that there is no limit in EstimateRowAccesses().
static constexpr double kNoLimit = std::numeric_limits<double>::infinity();

/**
  Estimates how many rows that have to be read from the outer table of a join in
  order to reach the given limit.

  @param join_path  The AccessPath representing the join.
  @param outer      The AccessPath representing the outer table in the join.
  @param limit      The maximum number of rows to read from the join result.

  @return The number of rows to read from the outer table before reaching the
  limit, or kNoLimit if the entire table is expected to be read.
 */
static double GetRowsNeededFromOuterTable(const AccessPath *join_path,
                                          const AccessPath *outer,
                                          double limit) {
  const double input_rows = outer->num_output_rows();
  const double output_rows = join_path->num_output_rows();

  if (input_rows > 0 && output_rows > 0) {
    const double fanout = output_rows / input_rows;
    return ceil(limit / fanout);
  }

  return kNoLimit;
}

/**
  Estimates the number of row accesses that will be performed by a nested loop
  join.

  Nested loop join reads the outer table once, and the inner table once per row
  in the outer table. If there is a limit on the query, it might not need to
  read all rows in the outer table.

  @param join_path  The AccessPath representing the nested loop join.
  @param num_evaluations  The number of times the join will be executed.
  @param limit  The maximum number of rows to read from the join result.
  @return An estimate of the number of row accesses.
 */
static double EstimateRowAccessesInNestedLoopJoin(const AccessPath *join_path,
                                                  const AccessPath *outer,
                                                  const AccessPath *inner,
                                                  double num_evaluations,
                                                  double limit) {
  const double limit_on_outer =
      GetRowsNeededFromOuterTable(join_path, outer, limit);
  return EstimateRowAccesses(outer, num_evaluations, limit_on_outer) +
         EstimateRowAccesses(
             inner,
             num_evaluations * min(limit_on_outer, outer->num_output_rows()),
             kNoLimit);
}

/**
  Estimates the number of row accesses performed by the subqueries contained in
  an item. The returned estimate is pessimistic, as it assumes the contained
  subqueries are evaluated each time the item is evaluated. If the item for
  example is an Item_cond_or, say, x=y OR (SELECT ...), the subquery is not
  evaluated if x=y is true, but the estimate does not take the selectivity of
  x=y into account.

  @param item The item to check.
  @param num_evaluations The number of times the item is evaluated.
  @return An estimate of the number of row accesses.
 */
static double EstimateRowAccessesInItem(Item *item, double num_evaluations) {
  double rows = 0.0;
  WalkItem(item, enum_walk::PREFIX, [num_evaluations, &rows](Item *subitem) {
    if (subitem->type() == Item::SUBSELECT_ITEM) {
      Item_subselect *subselect = down_cast<Item_subselect *>(subitem);
      Query_block *query_block = subselect->unit->first_query_block();
      AccessPath *path;
      if (subselect->unit->root_access_path() != nullptr) {
        path = subselect->unit->root_access_path();
      } else {
        path = subselect->unit->item->root_access_path();
      }
      // In some cases, for old optimizer, when subtitem is a
      // Item_singlerow_subselect, its Query_expression::root_access_path has
      // not been set, and Item_singlerow_subselect::root_access_path() always
      // returns nullptr, so we need to check:
      if (path != nullptr) {
        rows += EstimateRowAccesses(
            path, query_block->is_cacheable() ? 1.0 : num_evaluations,
            kNoLimit);
      }
    }
    return false;
  });
  return rows;
}

double EstimateRowAccesses(const AccessPath *path, double num_evaluations,
                           double limit) {
  assert(limit >= 0.0);

  double rows = 0.0;
  WalkAccessPaths(
      path, /*join=*/nullptr, WalkAccessPathPolicy::ENTIRE_TREE,
      [num_evaluations, limit, &rows](const AccessPath *subpath, const JOIN *) {
        // Count rows accessed in base tables.
        if (const TABLE *table = GetBasicTable(subpath);
            table != nullptr && table->s != nullptr &&
            table->s->tmp_table != INTERNAL_TMP_TABLE &&
            table->pos_in_table_list != nullptr &&
            table->pos_in_table_list->is_base_table()) {
          double num_output_rows = subpath->num_output_rows();

          // Workaround for the old optimizer only: test_if_skip_sort_order()
          // sets the cardinality of index scans to the same as the query
          // block's limit, if there is one, so the estimate in the access path
          // may be too low. Get the cardinality from the handler's statistics
          // instead.
          if (subpath->type == AccessPath::INDEX_SCAN &&
              !current_thd->lex->using_hypergraph_optimizer()) {
            num_output_rows = table->file->stats.records;
          }

          // Workaround for HeatWave. All access paths in HeatWave currently
          // have num_output_rows set to zero. Get the handler's estimate
          // instead.
          if (num_output_rows == 0 && table->s->is_secondary_engine()) {
            assert(subpath->type == AccessPath::TABLE_SCAN);
            num_output_rows = table->file->stats.records;
          }

          assert(num_output_rows >= 0);

          rows += num_evaluations * min(limit, num_output_rows);
          return true;  // Done with this subtree.
        }

        switch (subpath->type) {
          case AccessPath::LIMIT_OFFSET: {
            const auto &param = subpath->limit_offset();
            rows += EstimateRowAccesses(
                param.child, num_evaluations,
                min(limit, static_cast<double>(param.limit)));
            return true;
          }
          case AccessPath::AGGREGATE: {
            // Assume that aggregation needs to read the entire input,
            // regardless of limit. This might be too pessimistic for explicitly
            // grouped queries, but let's be conservative for now.
            rows += EstimateRowAccesses(subpath->aggregate().child,
                                        num_evaluations, kNoLimit);
            return true;
          }
          case AccessPath::TEMPTABLE_AGGREGATE: {
            // Temptable aggregation needs to read the entire input.
            rows += EstimateRowAccesses(
                subpath->temptable_aggregate().subquery_path, num_evaluations,
                kNoLimit);
            return true;
          }
          case AccessPath::MATERIALIZE: {
            // Materialize once per query or once per evaluation.
            const double num_materializations =
                subpath->materialize().param->rematerialize ? num_evaluations
                                                            : 1.0;
            for (const MaterializePathParameters::QueryBlock &query_block :
                 subpath->materialize().param->query_blocks) {
              rows += EstimateRowAccesses(query_block.subquery_path,
                                          num_materializations, kNoLimit);
            }
            return true;
          }
          case AccessPath::APPEND: {
            // UNION ALL can stop reading from children once the limit is
            // reached.
            double limit_on_next_child = limit;
            for (AppendPathParameters child : *subpath->append().children) {
              if (limit_on_next_child <= 0) break;
              rows += EstimateRowAccesses(child.path, num_evaluations,
                                          limit_on_next_child);
              limit_on_next_child -= child.path->num_output_rows();
            }
            return true;
          }
          case AccessPath::NESTED_LOOP_JOIN: {
            rows += EstimateRowAccessesInNestedLoopJoin(
                subpath, subpath->nested_loop_join().outer,
                subpath->nested_loop_join().inner, num_evaluations, limit);
            return true;
          }
          case AccessPath::NESTED_LOOP_SEMIJOIN_WITH_DUPLICATE_REMOVAL: {
            rows += EstimateRowAccessesInNestedLoopJoin(
                subpath,
                subpath->nested_loop_semijoin_with_duplicate_removal().outer,
                subpath->nested_loop_semijoin_with_duplicate_removal().inner,
                num_evaluations, limit);
            return true;
          }
          case AccessPath::BKA_JOIN: {
            // BKA join reads each side once.
            const auto &param = subpath->bka_join();
            rows += EstimateRowAccesses(param.outer, num_evaluations, kNoLimit);
            rows += EstimateRowAccesses(param.inner, num_evaluations, kNoLimit);
            return true;
          }
          case AccessPath::HASH_JOIN: {
            // Hash join reads each side once. If there is a LIMIT clause, it
            // might not need to read all rows from the outer table.
            const auto &param = subpath->hash_join();
            rows += EstimateRowAccesses(
                param.outer, num_evaluations,
                GetRowsNeededFromOuterTable(subpath, param.outer, limit));
            rows += EstimateRowAccesses(param.inner, num_evaluations, kNoLimit);
            // Subqueries in the non-equijoin conditions may access rows.
            for (Item *item : param.join_predicate->expr->join_conditions) {
              rows += EstimateRowAccessesInItem(
                  item, num_evaluations * subpath->num_output_rows());
            }
            return true;
          }
          case AccessPath::FILTER: {
            // Filters may access rows in subqueries. Count them.
            const auto &param = subpath->filter();
            const double input_rows = param.child->num_output_rows();
            const double output_rows = subpath->num_output_rows();
            const double rows_needed_from_child =
                (input_rows > 0 && output_rows > 0)
                    ? limit / (output_rows / input_rows)
                    : kNoLimit;
            rows += EstimateRowAccessesInItem(
                param.condition,
                num_evaluations * min(param.child->num_output_rows(),
                                      rows_needed_from_child));
            rows += EstimateRowAccesses(param.child, num_evaluations,
                                        rows_needed_from_child);
            return true;
          }
          case AccessPath::SORT: {
            // SORT needs to read the entire input, regardless of LIMIT.
            rows += EstimateRowAccesses(subpath->sort().child, num_evaluations,
                                        kNoLimit);
            return true;
          }
          default:
            return false;  // Keep traversing.
        }
      });

  return rows;
}

bool IsHashEquijoinCondition(const Item_eq_base *item, table_map left_side,
                             table_map right_side) {
  // We are not able to create hash join conditions from row values consisting
  // of multiple columns, so let them be added as extra conditions instead.
  if (item->get_comparator()->get_child_comparator_count() > 1) {
    return false;
  }

  table_map left_arg_tables = item->get_arg(0)->used_tables();
  table_map right_arg_tables = item->get_arg(1)->used_tables();

  // The equality is commutative. If the left side of the equality doesn't
  // reference any table on the left side of the join, swap left and right to
  // see if it's satisfied the other way around.
  if (!Overlaps(left_arg_tables, left_side)) {
    std::swap(left_arg_tables, right_arg_tables);
  }

  // One side of the equality should reference tables on one side of the join,
  // and the other side of the equality should reference the other side of the
  // join.
  return Overlaps(left_arg_tables, left_side) &&
         !Overlaps(left_arg_tables, right_side) &&
         Overlaps(right_arg_tables, right_side) &&
         !Overlaps(right_arg_tables, left_side);
}